/* educator-ui.jsx — shared UI primitives */
const { useState, useEffect } = React;

/* ── Active brand theme (Style Tailor) ── */
function useTheme() {
  const [theme, setTheme] = useState(() => (window.VHTheme && window.VHTheme.current()) || null);
  useEffect(() => {
    const h = e => setTheme((e && e.detail) || (window.VHTheme && window.VHTheme.current()) || null);
    window.addEventListener("vh-theme-change", h);
    return () => window.removeEventListener("vh-theme-change", h);
  }, []);
  const branded = !!(theme && theme.primary && theme.domain && theme.domain !== "vanharen.net");
  return { theme, branded };
}

/* ── Icons ── */
const PATHS = {
  grid:["M4 4h7v7H4zM13 4h7v7h-7zM13 13h7v7h-7zM4 13h7v7H4z"],
  users:["M16 19v-1a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v1","M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z","M22 19v-1a4 4 0 0 0-3-3.9","M16 3.1A4 4 0 0 1 16 11"],
  person:["M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z","M4 21v-1a8 8 0 0 1 16 0v1"],
  book:["M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z","M19 19H6a2 2 0 0 0-2 2"],
  trophy:["M7 4h10v4a5 5 0 0 1-10 0z","M7 6H4v2a3 3 0 0 0 3 3","M17 6h3v2a3 3 0 0 1-3 3","M10 14h4l-.5 4h-3z","M8 21h8"],
  bars:["M4 20V10M10 20V4M16 20v-7M22 20H2"],
  bolt:[["M13 2L4 14h6l-1 8 9-12h-6z",{fill:"currentColor",stroke:"none"}]],
  flame:["M12 3c1 3-2 4-2 7a2 2 0 0 0 4 0c2 2 3 3 3 6a5 5 0 0 1-10 0c0-4 4-5 5-13z"],
  search:["M11 11m-7 0a7 7 0 1 0 14 0a7 7 0 1 0-14 0","M21 21l-4.3-4.3"],
  bell:["M6 9a6 6 0 1 1 12 0c0 5 2 6 2 6H4s2-1 2-6","M10 20a2 2 0 0 0 4 0"],
  graduation:["M3 9l9-5 9 5-9 5z","M7 11v5c0 1 2.2 2.5 5 2.5s5-1.5 5-2.5v-5","M21 9v5"],
  layers:["M12 3l9 5-9 5-9-5z","M3 12l9 5 9-5"],
  globe:["M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0-18 0","M3 12h18","M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18z"],
  shield:["M12 3l8 3v6c0 5-3.5 7.5-8 9-4.5-1.5-8-4-8-9V6z"],
  slides:["M2 3h20v14H2z","M8 21h8M12 17v4"],
  quiz:["M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0-18 0","M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3","M12 17h.01"],
  cert:["M12 14a5 5 0 1 0 0-10 5 5 0 0 0 0 10z","M9 13l-2 7 5-3 5 3-2-7"],
  file:["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6"],
  checkCircle:["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M8 12l3 3 5-6"],
  medal:["M8 3l4 7 4-7","M12 21a5 5 0 1 0 0-10 5 5 0 0 0 0 10z"],
  wand:["M15 4V2M15 10V8M19 6h2M9 6h2","M17 6l-12 12","M14 9l1 1"],
  check:["M5 13l4 4L19 7"],
  plus:["M12 5v14","M5 12h14"],
  download:["M12 4v11","M8 11l4 4 4-4","M5 20h14"],
  arrowR:["M5 12h14","M13 6l6 6-6 6"],
  chevL:["M15 6l-6 6 6 6"],
  chevD:["M6 9l6 6 6-6"],
  calendar:["M3 5h18a2 2 0 0 1 2 2v13a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z","M16 2v4","M8 2v4","M3 10h18"],
  pin:["M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z","M12 10m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0"],
  lock:["M6 11h12v9H6z","M9 11V8a3 3 0 0 1 6 0v3"],
  gear:["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.6 1.6 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.6 1.6 0 0 0-2.7 1.1V21a2 2 0 1 1-4 0v-.1A1.6 1.6 0 0 0 6.6 19l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1A1.6 1.6 0 0 0 4 13.6H4a2 2 0 1 1 0-4h.1A1.6 1.6 0 0 0 5 6.6L4.9 6.5a2 2 0 1 1 2.8-2.8l.1.1A1.6 1.6 0 0 0 10 4.6V4a2 2 0 1 1 4 0v.1a1.6 1.6 0 0 0 2.7 1.1l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.6 1.6 0 0 0-.3 1.8"],
  star:[["M12 3l2.9 5.9 6.5.9-4.7 4.6 1.1 6.5L12 18l-5.8 3 1.1-6.5L2.6 9.8l6.5-.9z",{fill:"currentColor",stroke:"none"}]],
  toggle:["M1 12a5 5 0 0 0 5 5h12a5 5 0 0 0 0-10H6a5 5 0 0 0-5 5z","M16 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0"],
  palette:["M12 3a9 9 0 1 0 0 18c1.7 0 2-1.3 1.2-2.2-.8-.9-.5-2.2.8-2.2H17a4 4 0 0 0 4-4c0-4.4-4-7.4-9-7.4z","M7.5 11.5h.01","M10.5 7.5h.01","M14.5 7.5h.01"],
  pipeline:["M22 3H2l8 9.46V19l4 2v-8.54z"],
  list:["M8 6h13M8 12h13M8 18h13","M3 6h.01M3 12h.01M3 18h.01"],
  clock:["M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0-18 0","M12 7v5l3 2"],
  share:["M4 12v7a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-7","M12 3v13","M8 7l4-4 4 4"],
  link:["M9 15l6-6","M11 6l1-1a4 4 0 0 1 6 6l-1 1","M13 18l-1 1a4 4 0 0 1-6-6l1-1"],
  refresh:["M3 12a9 9 0 0 1 15-6.7L21 8","M21 3v5h-5","M21 12a9 9 0 0 1-15 6.7L3 16","M3 21v-5h5"],
  mail:["M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z","M22 6l-10 7L2 6"],
  x:["M6 6l12 12M18 6L6 18"],
  edit:["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z"],
  video:["M3 6a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z","M16 10l5-3v10l-5-3z"],
  monitor:["M3 4h18a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z","M8 21h8","M12 17v4"],
  copy:["M9 9h11a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V10a1 1 0 0 1 1-1z","M5 15H4a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1h11a1 1 0 0 1 1 1v1"],
  eye:["M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z","M12 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0"],
  external:["M14 4h6v6","M20 4l-9 9","M18 13v6a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h6"],
  play:[["M7 5l12 7-12 7z",{fill:"currentColor",stroke:"none"}]],
  ticket:["M3 8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v2a2 2 0 0 0 0 4v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2a2 2 0 0 0 0-4z","M13 6v12"],
};

function Icon({ name, size=22, stroke=2, style, className }) {
  const paths = PATHS[name] || PATHS.grid;
  return React.createElement("svg",{width:size,height:size,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:stroke,strokeLinecap:"round",strokeLinejoin:"round",style,className,"aria-hidden":true},
    paths.map((p,i)=>Array.isArray(p)?React.createElement("path",{key:i,d:p[0],...p[1]}):React.createElement("path",{key:i,d:p})));
}

function HexMark({ size=34 }) {
  const { theme, branded } = useTheme();
  if (branded) {
    const mono = theme.mark || (window.VHTheme && window.VHTheme.monogram(theme.name)) || "•";
    return (
      <div style={{ width:size, height:size, borderRadius:Math.round(size*0.28), flex:'none',
        background:'linear-gradient(135deg, var(--vh-blue-400), var(--vh-navy))',
        display:'grid', placeItems:'center', color:'#fff', fontFamily:'var(--display)',
        fontWeight:800, fontSize:(mono.length>=3?size*0.34:size*0.44), letterSpacing:'-.02em',
        boxShadow:'var(--shadow-sm)' }} title={theme.name}>{mono}</div>
    );
  }
  return (
    <div style={{ width:size, height:size, position:'relative', flex:'none' }}>
      <div style={{ position:'absolute', inset:0, background:'var(--vh-blue-500)', clipPath:'polygon(50% 0,93% 25%,93% 75%,50% 100%,7% 75%,7% 25%)' }}/>
      <svg viewBox="0 0 24 24" width={size} height={size} style={{ position:'absolute', inset:0 }}
        fill="none" stroke="#fff" strokeWidth={3} strokeLinecap="round" strokeLinejoin="round">
        <g transform="translate(12,11) scale(0.68) translate(-12,-11)">
          <path d="M3 9l9-5 9 5-9 5z"/>
          <path d="M7 11v5c0 1 2.2 2.5 5 2.5s5-1.5 5-2.5v-5"/>
          <path d="M21 9v5"/>
        </g>
      </svg>
    </div>
  );
}

function Av({ initials, size=36, bg }) {
  return <div style={{ width:size, height:size, borderRadius:Math.round(size*.28), background:bg||"linear-gradient(135deg,var(--vh-blue-400),var(--vh-navy))", display:"grid", placeItems:"center", color:"#fff", fontFamily:"var(--display)", fontWeight:700, fontSize:size*.38, flexShrink:0 }}>{initials}</div>;
}

function Bar({ pct=0, cls="" }) {
  return <div className="bar" style={{ flex:1 }}><i className={cls} style={{ width:pct+"%" }}/></div>;
}

function Ring({ value=0, size=56, stroke=6, color="var(--vh-blue-500)", children }) {
  const r=(size-stroke)/2, c=2*Math.PI*r, off=c*(1-value/100);
  return (
    <div style={{ position:"relative", width:size, height:size, display:"grid", placeItems:"center" }}>
      <svg width={size} height={size} style={{ transform:"rotate(-90deg)" }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--surface-3)" strokeWidth={stroke}/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
          strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round"
          style={{ transition:"stroke-dashoffset .8s cubic-bezier(.2,.7,.3,1)" }}/>
      </svg>
      <div style={{ position:"absolute", inset:0, display:"grid", placeItems:"center", textAlign:"center" }}>{children}</div>
    </div>
  );
}

function CourseChip({ name }) {
  const c = COURSE_CHIP_COLORS[name] || { bg:"var(--chip)", color:"var(--ink-2)" };
  return <span style={{ display:"inline-flex", alignItems:"center", fontSize:11.5, fontWeight:700, padding:"3px 9px", borderRadius:999, background:c.bg, color:c.color, whiteSpace:"nowrap" }}>{name}</span>;
}

function RankBadge({ rank }) {
  const cfg = rank===1?["#f99d25","#fff"]:rank<=3?["var(--vh-navy)","#fff"]:["var(--surface-3)","var(--ink-3)"];
  return <div style={{ width:32, height:32, borderRadius:8, background:cfg[0], color:cfg[1], display:"grid", placeItems:"center", fontFamily:"var(--display)", fontWeight:800, fontSize:14, flexShrink:0 }}>#{rank}</div>;
}

/* ── NAV ── */
const NAV_GROUPS = [
  { section:null, items:[
    { id:"dashboard",   label:"Dashboard",   icon:"grid"       },
  ]},
  { section:"LMS", items:[
    { id:"cohorts",     label:"My Cohorts",  icon:"users"      },
    { id:"products",   label:"Products",    icon:"layers"     },
    { id:"prep",       label:"Session Prep",icon:"book",
      children:[{ id:"gamification", label:"Gamification", icon:"bolt" }] },
    { id:"learners",   label:"Learners",    icon:"person"     },
    { id:"leaderboard",label:"Leaderboard", icon:"trophy"     },
  ]},
  { section:"CRM", items:[
    { id:"trainers",   label:"Accounts",    icon:"graduation" },
    { id:"contacts",   label:"Contacts",    icon:"users"      },
  ]},
  { section:"Reporting", items:[
    { id:"reports",      label:"Course KPIs", icon:"bars" },
    { id:"trainer-kpis", label:"Trainer KPIs",icon:"bars" },
  ]},
  { section:"Marketing", items:[
    { id:"mailing",    label:"Mailing",     icon:"mail"       },
    { id:"events",     label:"Events",      icon:"calendar"   },
  ]},
  { section:null, items:[
    { id:"integration",label:"Integrations",icon:"link"       },
    { id:"styling",    label:"Style Tailor",icon:"palette"    },
    { id:"features",   label:"Features",    icon:"toggle"     },
    { id:"settings",   label:"Settings",    icon:"gear"       },
  ]},
];

const NAV = NAV_GROUPS.flatMap(g => g.items.flatMap(n => [n, ...(n.children||[])]));

function NavItem({ n, route, go, expanded, onToggle, depth }) {
  const active = route === n.id;
  const hasCh = !!(n.children && n.children.length);
  const childActive = hasCh && n.children.some(c => c.id === route);
  const isExp = expanded[n.id] || childActive;
  return (
    <div>
      <button className={"nav-item"+(active?" active":"")} onClick={()=>{ if(hasCh && !isExp) onToggle(n.id); go(n.id); }}
        style={{ width:"100%", paddingLeft: depth > 0 ? 30 : undefined }}>
        <span className="nav-ico"><Icon name={n.icon} size={depth>0?16:21}/></span>
        <span className="lbl" style={{ fontSize:depth>0?13:undefined }}>{n.label}</span>
        {hasCh && <span onClick={e=>{ e.stopPropagation(); onToggle(n.id); }} style={{ marginLeft:"auto", flexShrink:0, display:"inline-flex", padding:3, cursor:"pointer" }}><Icon name="chevD" size={11} style={{ flexShrink:0, opacity:.4, transition:"transform .18s", transform:isExp?"rotate(180deg)":"none" }}/></span>}
      </button>
      {hasCh && isExp && n.children.map(c=>(
        <NavItem key={c.id} n={c} route={route} go={go} expanded={expanded} onToggle={onToggle} depth={depth+1}/>
      ))}
    </div>
  );
}

function Sidebar({ route, go }) {
  const { lang } = useLang();
  const TL = T[lang] || T.en;
  const { theme, branded } = useTheme();
  const [sec, setSec] = useState({});
  const [exp, setExp] = useState({});
  function toggleSec(s) { setSec(c=>({...c,[s]:!c[s]})); }
  function toggleExp(id) { setExp(e=>({...e,[id]:!e[id]})); }
  return (
    <nav className="rail">
      <div style={{ padding:"20px 16px 10px", display:"flex", alignItems:"center", gap:11 }}>
        <HexMark size={34}/>
        <div className="rail-wordmark">
          {branded
            ? <div style={{ fontFamily:"var(--display)", fontWeight:800, fontSize:16, color:"var(--ink)", letterSpacing:"-.01em", lineHeight:1, maxWidth:150, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }} title={theme.name}>{theme.name}</div>
            : <img src="assets/vanharen-logo.png" alt="Van Haren" style={{ height:20, width:"auto", display:"block" }}/>}
          <div className="dim" style={{ fontSize:10.5, fontWeight:700, letterSpacing:".18em", textTransform:"uppercase", marginTop:3 }}>Educator</div>
        </div>
      </div>
      <div style={{ flex:1, overflowY:"auto", paddingBottom:8 }} className="scroll">
        {NAV_GROUPS.map((g,gi)=>(
          <div key={gi}>
            {gi>0 && <div style={{ height:1, background:"var(--rail-border)", margin:"5px 16px" }}/>}
            {g.section && (
              <button onClick={()=>toggleSec(g.section)} style={{ width:"100%", display:"flex", alignItems:"center", justifyContent:"space-between", padding:"6px 16px 2px", background:"none", border:"none", cursor:"pointer" }}>
                <span className="lbl" style={{ fontSize:10, fontWeight:800, textTransform:"uppercase", letterSpacing:".16em", color:"var(--rail-ink-dim)" }}>{g.section}</span>
                <Icon name="chevD" size={10} style={{ color:"var(--rail-ink-dim)", opacity:.5, transition:"transform .18s", transform:sec[g.section]?"rotate(-90deg)":"none" }}/>
              </button>
            )}
            {!sec[g.section] && (
              <div style={{ padding:"1px 13px 0", display:"flex", flexDirection:"column", gap:1 }}>
                {g.items.map(n=>(
                  <NavItem key={n.id} n={n} route={route} go={go} expanded={exp} onToggle={toggleExp} depth={0}/>
                ))}
              </div>
            )}
          </div>
        ))}
      </div>
      <LangPicker/>
      <div style={{ padding:"0 13px 16px" }}>
        <div style={{ height:1, background:"var(--rail-border)", marginBottom:12 }}/>
        <button className="nav-item" onClick={()=>window.location.href="Login.html"}
          onMouseEnter={e=>e.currentTarget.style.color="#c62828"}
          onMouseLeave={e=>e.currentTarget.style.color=""}>
          <span className="nav-ico"><Icon name="chevL" size={21}/></span>
          <span className="lbl" style={{ fontSize:13.5 }}>{TL.logout}</span>
        </button>
      </div>
    </nav>
  );
}

function Topbar() {
  const { lang } = useLang();
  const TL = T[lang] || T.en;
  const eduTL = TL.edu || {};
  return (
    <header className="topbar">
      <label className="search">
        <Icon name="search" size={18}/><input placeholder={eduTL.search || "Search cohorts, learners, sessions…"}/>
      </label>
      <div style={{ flex:1 }}/>
      <span className="streak"><Icon name="flame" size={16}/>{eduTL.streak ? eduTL.streak(ME.streak) : ME.streak + " day streak"}</span>
      <span className="xp-chip"><Icon name="bolt" size={16}/>{ME.xp.toLocaleString()}</span>
      <button className="icon-btn"><Icon name="bell" size={21}/></button>
      <div style={{ display:"flex", alignItems:"center", gap:10 }}>
        <div className="avatar">{ME.initials}</div>
        <div style={{ lineHeight:1.2 }} className="rail-wordmark">
          <div style={{ fontWeight:700, fontSize:13.5 }}>{ME.name}</div>
          <div className="dim" style={{ fontSize:11.5 }}>{ME.role}</div>
        </div>
      </div>
    </header>
  );
}

Object.assign(window, { Icon, HexMark, Av, Bar, Ring, CourseChip, RankBadge, NAV, Sidebar, Topbar });
