/* educator-screens2.jsx — Session Prep, Gamification, Leaderboard, Reports, App */

/* ── SESSION PREP ── */
const SLIDE_URLS = {
  ipma: 'slides/IPMA-D Slides.html',
  bisl: 'slides/BiSL Slides.html',
  itil: 'slides/ITIL4 Slides.html',
};

function SessionPrep() {
  const preps=[
    { id:"ipma", name:"IPMA-D® Certification", icon:"graduation", modules:5, slides:147, quizzes:5, color:"var(--vh-blue-500)", ready:true },
    { id:"bisl", name:"BiSL® Foundation",      icon:"layers",     modules:4, slides:112, quizzes:3, color:"var(--vh-teal)",     ready:true },
    { id:"itil", name:"ITIL® 4 Foundation",    icon:"globe",      modules:6, slides:184, quizzes:6, color:"var(--vh-blue-400)", ready:false },
  ];
  const tools=[
    { icon:"slides", label:"Slide Deck",  bg:"var(--vh-blue-50)",   ic:"var(--vh-blue-500)" },
    { icon:"quiz",   label:"Quiz Bank",   bg:"var(--accent-soft)",   ic:"var(--accent)" },
    { icon:"cert",   label:"Assessment",  bg:"#e8f5e9",              ic:"#2e7d32" },
    { icon:"file",   label:"Materials",   bg:"#f3e8ff",              ic:"#7c3aed" },
  ];
  return (
    <div>
      <div className="between" style={{ marginBottom:24 }}>
        <div className="page-head" style={{ marginBottom:0 }}><h1>Session Prep</h1><p>Slides, quizzes, assessments and materials for your sessions.</p></div>
        <button className="btn btn-acc" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}><Icon name="download" size={15}/>Export Pack</button>
      </div>
      <div style={{ display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:18 }}>
        {preps.map(c=>(
          <div key={c.id} className="card" style={{ padding:22 }}>
            <div style={{ width:46, height:46, borderRadius:13, background:"var(--surface-3)", display:"grid", placeItems:"center", marginBottom:14 }}>
              <Icon name={c.icon} size={22} style={{ color:c.color }}/>
            </div>
            <div style={{ fontFamily:"var(--display)", fontWeight:800, fontSize:16.5, marginBottom:4 }}>{c.name}</div>
            <div className="dim" style={{ fontSize:12.5, marginBottom:12 }}>{c.modules} modules · {c.slides} slides</div>
            <div style={{ display:"flex", gap:6, marginBottom:16, flexWrap:"wrap" }}>
              <span className={"tag"+(c.ready?" green":"")}>{c.ready?"✓ Ready":"In Prep"}</span>
              <span className="tag blue">{c.quizzes} quizzes</span>
            </div>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:8, marginBottom:18 }}>
              {tools.map(t=>(
                <button key={t.label} className="prep-tool"
                  onClick={()=>{ if(t.label==='Slide Deck' && SLIDE_URLS[c.id]) window.open(SLIDE_URLS[c.id],'_blank'); }}>
                  <div style={{ width:26, height:26, borderRadius:7, background:t.bg, display:"grid", placeItems:"center", flex:"none" }}><Icon name={t.icon} size={13} style={{ color:t.ic }}/></div>
                  {t.label}
                </button>
              ))}
            </div>
            <div className="divider" style={{ marginBottom:14 }}/>
            <div className="eyebrow" style={{ marginBottom:10 }}>Modules</div>
            {Array.from({length:c.modules}).map((_,i)=>(
              <div key={i} style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"7px 0", borderBottom:i<c.modules-1?"1px solid var(--line-2)":"none" }}>
                <span style={{ fontSize:13, color:"var(--ink-2)" }}>Module {i+1}</span>
                <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                  <span className="dim" style={{ fontSize:11.5 }}>{Math.floor(c.slides/c.modules)} slides</span>
                  <Icon name="check" size={13} style={{ color:"#2e7d32" }}/>
                </div>
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── GAMIFICATION ── */
function Gamification() {
  const [xpMult, setXpMult] = useState("1.0");
  const [configCourse, setConfigCourse] = useState(null);
  const [cfg, setCfg] = useState({ xpLesson:50, xpQuiz:150, badges:5 });

  return (
    <div>
      {/* Configure Modal */}
      {configCourse && (
        <div style={{ position:'fixed', inset:0, background:'rgba(13,26,52,.55)', backdropFilter:'blur(4px)', zIndex:60, display:'grid', placeItems:'center', padding:24 }}
          onClick={e=>{ if(e.target===e.currentTarget) setConfigCourse(null); }}>
          <div className="card" style={{ width:'100%', maxWidth:520, padding:28, boxShadow:'var(--shadow-lg)', animation:'vhPop .22s cubic-bezier(.2,.7,.3,1)' }}>
            <div className="between" style={{ marginBottom:20 }}>
              <div>
                <div className="eyebrow">Gamification Config</div>
                <h2 style={{ fontSize:20, marginTop:4 }}>{configCourse.name}</h2>
              </div>
              <button className="icon-btn" onClick={()=>setConfigCourse(null)} style={{ fontSize:18, fontWeight:700, color:'var(--ink-3)' }}>✕</button>
            </div>

            {/* XP sliders */}
            <div style={{ display:'flex', flexDirection:'column', gap:20, marginBottom:24 }}>
              {[['XP per lesson','xpLesson',0,200,10],['XP per quiz','xpQuiz',0,500,25]].map(([label,key,min,max,step])=>(
                <div key={key}>
                  <div className="between" style={{ marginBottom:8 }}>
                    <span style={{ fontSize:13.5, fontWeight:600 }}>{label}</span>
                    <span className="kpi" style={{ fontSize:18, color:'var(--accent)' }}>{cfg[key]} XP</span>
                  </div>
                  <input type="range" min={min} max={max} step={step} value={cfg[key]}
                    onChange={e=>setCfg(c=>({...c,[key]:+e.target.value}))}
                    style={{ width:'100%', accentColor:'var(--accent)' }}/>
                  <div style={{ display:'flex', justifyContent:'space-between', fontSize:11.5, color:'var(--ink-3)', marginTop:4 }}><span>{min}</span><span>{max}</span></div>
                </div>
              ))}
              <div>
                <div className="between" style={{ marginBottom:8 }}>
                  <span style={{ fontSize:13.5, fontWeight:600 }}>Number of badges</span>
                  <span className="kpi" style={{ fontSize:18, color:'var(--vh-blue-500)' }}>{cfg.badges}</span>
                </div>
                <input type="range" min={1} max={10} step={1} value={cfg.badges}
                  onChange={e=>setCfg(c=>({...c,badges:+e.target.value}))}
                  style={{ width:'100%', accentColor:'var(--vh-blue-500)' }}/>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:11.5, color:'var(--ink-3)', marginTop:4 }}><span>1</span><span>10</span></div>
              </div>
            </div>

            {/* Badge preview */}
            <div style={{ padding:'14px 16px', borderRadius:12, background:'var(--surface-2)', border:'1px solid var(--line)', marginBottom:22 }}>
              <div className="eyebrow" style={{ marginBottom:10 }}>Badge milestones</div>
              <div style={{ display:'flex', gap:10, flexWrap:'wrap' }}>
                {['First Login','Quiz Master','Speed Learner','Top Scorer','Completer'].slice(0,cfg.badges).map(b=>(
                  <span key={b} style={{ display:'inline-flex', alignItems:'center', gap:5, padding:'4px 11px', borderRadius:999, background:'var(--accent-soft)', color:'var(--accent-ink)', fontSize:12, fontWeight:600 }}>🏅 {b}</span>
                ))}
              </div>
            </div>

            <div style={{ display:'flex', gap:10, justifyContent:'flex-end' }}>
              <button className="btn btn-ghost" onClick={()=>setConfigCourse(null)}>Cancel</button>
              <button className="btn btn-acc" onClick={()=>setConfigCourse(null)}><Icon name="check" size={14}/>Save changes</button>
            </div>
          </div>
        </div>
      )}
      <div className="between" style={{ marginBottom:24 }}>
        <div className="page-head" style={{ marginBottom:0 }}><h1>Gamification</h1><p>{GAMIFY_DATA.filter(g=>g.on).length} courses gamified · manage XP, badges, quizzes and leaderboards</p></div>
        <div style={{ display:"flex", gap:10, alignItems:"center" }}>
          <span style={{ fontSize:13.5, fontWeight:600, color:"var(--ink-2)" }}>Global XP: <strong>{xpMult}x</strong></span>
          <button className="btn btn-acc" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}><Icon name="bolt" size={14}/>Enable all</button>
        </div>
      </div>

      <div className="eyebrow" style={{ marginBottom:14 }}>Gamified Courses</div>
      <div style={{ display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:16, marginBottom:28 }}>
        {GAMIFY_DATA.filter(g=>g.on).map(g=>(
          <div key={g.id} className="card" style={{ overflow:"hidden" }}>
            <div style={{ padding:"18px 20px 16px", background:`linear-gradient(135deg,${g.color},var(--vh-navy))`, position:"relative" }}>
              <div style={{ position:"absolute", inset:0, backgroundImage:"radial-gradient(rgba(255,255,255,.15) 1px,transparent 1.1px)", backgroundSize:"16px 16px" }}/>
              <div style={{ position:"relative" }}>
                <div style={{ display:"flex", alignItems:"center", gap:10, marginBottom:4 }}>
                  <Icon name={g.icon} size={18} style={{ color:"rgba(255,255,255,.9)" }}/>
                  <div style={{ fontFamily:"var(--display)", fontWeight:800, fontSize:15, color:"#fff", lineHeight:1.15 }}>{g.name}</div>
                </div>
                <div style={{ fontSize:12.5, color:"rgba(255,255,255,.75)" }}>{g.learners} learners · {g.completion}% complete</div>
              </div>
            </div>
            <div style={{ padding:"16px 20px" }}>
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12, marginBottom:16 }}>
                {[["Quiz Qs", g.quizzes],["Badges", g.badges],["XP/lesson", g.xpLesson],["XP/quiz", g.xpQuiz]].map(([k,v])=>(
                  <div key={k} style={{ textAlign:"center" }}>
                    <div style={{ fontFamily:"var(--display)", fontWeight:800, fontSize:22 }}>{v}</div>
                    <div className="dim" style={{ fontSize:11.5 }}>{k}</div>
                  </div>
                ))}
              </div>
              <button className="btn btn-ghost" style={{ width:"100%", fontSize:13 }} onClick={()=>setConfigCourse(g)}>Configure <Icon name="arrowR" size={13}/></button>
            </div>
          </div>
        ))}
      </div>

      <div className="eyebrow" style={{ marginBottom:14 }}>Not Yet Gamified</div>
      {GAMIFY_DATA.filter(g=>!g.on).map(g=>(
        <div key={g.id} className="card" style={{ padding:"16px 20px", display:"flex", alignItems:"center", gap:14, marginBottom:10 }}>
          <div style={{ width:38, height:38, borderRadius:10, background:"var(--surface-3)", display:"grid", placeItems:"center" }}>
            <Icon name={g.icon} size={18} style={{ color:"var(--ink-3)" }}/>
          </div>
          <div style={{ flex:1 }}>
            <div style={{ fontWeight:700 }}>{g.name}</div>
            <div className="dim" style={{ fontSize:12.5 }}>Not yet gamified · {g.learners} learners enrolled</div>
          </div>
          <span style={{ display:"inline-flex", alignItems:"center", gap:6, padding:"5px 12px", borderRadius:8, border:"1.5px solid var(--line)", fontSize:12.5, fontWeight:600, color:"var(--ink-3)" }}>Off</span>
          <button className="btn btn-pri btn-sm" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}>Enable gamification</button>
        </div>
      ))}
    </div>
  );
}

/* ── LEADERBOARD ── */
function Leaderboard() {
  const [period,setPeriod]=useState("Week");
  return (
    <div>
      <div className="between" style={{ marginBottom:24 }}>
        <div className="page-head" style={{ marginBottom:0 }}><h1>Leaderboard</h1><p>Live XP rankings across your cohorts.</p></div>
        <button className="btn btn-acc" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}><Icon name="trophy" size={15}/>Configure Prizes</button>
      </div>
      <div style={{ display:"grid", gridTemplateColumns:"1fr 300px", gap:18 }}>
        <div>
          <div className="segtabs" style={{ marginBottom:18 }}>
            {["Week","Month","Year"].map(p=><button key={p} className={"segtab"+(period===p?" on":"")} onClick={()=>setPeriod(p)}>{p}</button>)}
          </div>
          {LB_DATA.map((l,i)=>(
            <div key={l.rank} className="lb-row">
              <RankBadge rank={l.rank}/>
              <Av initials={l.initials} size={38}/>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontWeight:700, fontSize:14 }}>{l.name}</div>
                <div className="dim" style={{ fontSize:12.5 }}>{l.org}</div>
              </div>
              <div style={{ display:"flex", gap:5, flexWrap:"wrap" }}>{l.courses.map(c=><CourseChip key={c} name={c}/>)}</div>
              <span className="kpi" style={{ fontSize:18, color:i===0?"var(--accent)":"var(--ink)", minWidth:64, textAlign:"right" }}>
                {l.xp.toLocaleString()}<span style={{ fontSize:11, color:"var(--ink-3)", fontWeight:600 }}> XP</span>
              </span>
            </div>
          ))}
        </div>

        {/* Prize panel */}
        <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
          {[
            { period:'Week',  prize:'Free Ebook',        desc:'"Project Management by ICB4"', value:'€45',    grad:'linear-gradient(145deg,#b45309,var(--accent))',                     icon:'book' },
            { period:'Month', prize:'Free eLearning',    desc:'Course of your choice',         value:'€199',   grad:'linear-gradient(145deg,var(--vh-blue-600),var(--vh-navy))',         icon:'graduation' },
            { period:'Year',  prize:'Learner of the Year',desc:'Trophy + award ceremony',      value:'Annual', grad:'linear-gradient(145deg,#5c4300,#b8960c)',                           icon:'trophy' },
          ].map(p=>(
            <div key={p.period} className="card" style={{ background:p.grad, border:'none', padding:18, position:'relative', overflow:'hidden' }}>
              <div style={{ position:'absolute', inset:0, backgroundImage:'radial-gradient(rgba(255,255,255,.12) 1px,transparent 1.1px)', backgroundSize:'16px 16px' }}/>
              <div style={{ position:'relative' }}>
                <div className="eyebrow" style={{ color:'rgba(255,255,255,.65)', marginBottom:5 }}>Prize of the {p.period}</div>
                <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:8 }}>
                  <div>
                    <div style={{ fontFamily:'var(--display)', fontWeight:800, fontSize:19, color:'#fff', lineHeight:1.1 }}>{p.prize}</div>
                    <div style={{ fontSize:12, color:'rgba(255,255,255,.8)', marginTop:4 }}>{p.desc}</div>
                  </div>
                  <span style={{ display:'inline-flex', alignItems:'center', gap:5, background:'rgba(255,255,255,.18)', color:'#fff', borderRadius:999, padding:'4px 11px', fontSize:12, fontWeight:700, whiteSpace:'nowrap', flex:'none' }}>
                    <Icon name="medal" size={12}/>{p.value}
                  </span>
                </div>
              </div>
            </div>
          ))}
          <div className="card" style={{ padding:18 }}>
            <div className="eyebrow" style={{ marginBottom:12 }}>Current Leader</div>
            <div style={{ display:'flex', alignItems:'center', gap:11, marginBottom:16 }}>
              <Av initials="MV" size={40} bg="linear-gradient(135deg,var(--accent),#b45309)"/>
              <div style={{ flex:1 }}>
                <div style={{ fontWeight:700, fontSize:15 }}>Mara de Vries</div>
                <div className="dim" style={{ fontSize:12.5 }}>Shell · IPMA-D®</div>
              </div>
              <span className="kpi" style={{ fontSize:22, color:'var(--accent)' }}>2,840</span>
            </div>
            <button className="btn btn-acc" style={{ width:'100%', opacity:.5, cursor:"not-allowed" }} disabled title="Binnenkort">🏅 Announce Winner</button>
            <div style={{ marginTop:14, paddingTop:14, borderTop:'1px solid var(--line)' }}>
              <div className="eyebrow" style={{ marginBottom:10 }}>Platform Totals</div>
              {[['Total XP earned','18.4k'],['Badges awarded','42'],['Certif. ready','4 learners']].map(([k,v])=>(
                <div key={k} style={{ display:'flex', justifyContent:'space-between', padding:'7px 0', borderBottom:'1px solid var(--line-2)', fontSize:13 }}>
                  <span className="dim">{k}</span><span style={{ fontWeight:700 }}>{v}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── COURSE KPIs ── */
function Reports() {
  const K = KPI_DATA;
  const maxM = Math.max(...K.monthly);
  const months = ["Jan","Feb","Mar","Apr","May","Jun"];

  return (
    <div>
      <div className="between" style={{ marginBottom:24 }}>
        <div className="page-head" style={{ marginBottom:0 }}><h1>Course KPIs</h1><p>Quality metrics from {K.responses * COHORTS.length} participant evaluations</p></div>
        <div style={{ display:"flex", gap:10 }}>
          <select style={{ padding:"9px 13px", border:"1px solid var(--line)", borderRadius:10, fontSize:13, fontFamily:"var(--body)", color:"var(--ink)", background:"var(--surface)", cursor:"pointer" }}>
            <option>All products</option><option>IPMA-D®</option><option>BiSL®</option>
          </select>
          <button className="btn btn-acc" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}><Icon name="download" size={14}/>Export</button>
        </div>
      </div>

      {/* Top KPIs */}
      <div className="stat-grid" style={{ marginBottom:18 }}>
        {[
          { label:"Overall Score",  val:`${K.score}/5`, sub:"across all dimensions", ic:"#00838f",            bg:"var(--vh-blue-50)",  icon:"star" },
          { label:"NPS",            val:K.nps,           sub:"net promoter score",    ic:"#7c3aed",            bg:"#f3e8ff",            icon:"users" },
          { label:"Satisfaction",   val:`${K.satisfaction}%`, sub:"4 or 5 stars",    ic:"#b45309",            bg:"var(--accent-soft)", icon:"bolt" },
          { label:"Responses",      val:K.responses*5,   sub:"evaluation forms",     ic:"#2e7d32",            bg:"#e8f5e9",            icon:"person" },
        ].map(s=>(
          <div key={s.label} className="card stat-card">
            <div className="between" style={{ marginBottom:12 }}>
              <div className="eyebrow">{s.label}</div>
              <div className="stat-ico" style={{ background:s.bg }}><Icon name={s.icon} size={17} style={{ color:s.ic }}/></div>
            </div>
            <div className="kpi" style={{ fontSize:34, color:s.ic }}>{s.val}</div>
            <div className="dim" style={{ fontSize:12.5, marginTop:6 }}>{s.sub}</div>
          </div>
        ))}
      </div>

      <div style={{ display:"grid", gridTemplateColumns:"1.4fr 1fr", gap:18, marginBottom:18 }}>
        {/* Quality dimensions */}
        <div className="card" style={{ padding:22 }}>
          <div className="eyebrow" style={{ marginBottom:18 }}>Quality Dimensions — Platform Average</div>
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:14 }}>
            {K.dimensions.map(d=>(
              <div key={d.label} style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 14px", borderRadius:12, background:"var(--surface-2)", border:"1px solid var(--line)" }}>
                <div style={{ width:34, height:34, borderRadius:9, background:d.color+"22", display:"grid", placeItems:"center", flex:"none" }}>
                  <Icon name="star" size={16} style={{ color:d.color }}/>
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:12.5, fontWeight:600, marginBottom:5, lineHeight:1.2 }}>{d.label}</div>
                  <div style={{ height:5, borderRadius:999, background:"var(--surface-3)", overflow:"hidden" }}>
                    <div style={{ height:"100%", width:`${(d.score/5)*100}%`, borderRadius:999, background:d.color }}/>
                  </div>
                </div>
                <span style={{ fontFamily:"var(--display)", fontWeight:800, fontSize:18, color:d.color }}>{d.score}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Monthly trend + rating distribution */}
        <div style={{ display:"flex", flexDirection:"column", gap:18 }}>
          <div className="card" style={{ padding:22, flex:1 }}>
            <div className="eyebrow" style={{ marginBottom:14 }}>Monthly Trend — Overall</div>
            <div style={{ position:"relative", height:80 }}>
              <svg width="100%" height="80" viewBox="0 0 260 80" preserveAspectRatio="none">
                <defs>
                  <linearGradient id="trendFill" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="var(--vh-teal)" stopOpacity=".18"/>
                    <stop offset="100%" stopColor="var(--vh-teal)" stopOpacity="0"/>
                  </linearGradient>
                </defs>
                {(() => {
                  const pts = K.monthly.map((v,i)=>({x:i*(260/5),y:80-(((v-3.5)/(maxM-3.4))*70)}));
                  const area = `M${pts.map(p=>`${p.x},${p.y}`).join(" L")} L${pts[pts.length-1].x},80 L0,80 Z`;
                  const line = `M${pts.map(p=>`${p.x},${p.y}`).join(" L")}`;
                  return <>
                    <path d={area} fill="url(#trendFill)"/>
                    <path d={line} fill="none" stroke="var(--vh-teal)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
                    {pts.map((p,i)=><circle key={i} cx={p.x} cy={p.y} r="4" fill="var(--vh-teal)" stroke="var(--surface)" strokeWidth="2"/>)}
                  </>;
                })()}
              </svg>
            </div>
            <div style={{ display:"flex", justifyContent:"space-between", marginTop:8 }}>
              {months.map((m,i)=><span key={m} style={{ fontSize:10.5, color:"var(--ink-3)", fontWeight:600 }}>{m}</span>)}
            </div>
          </div>

          <div className="card" style={{ padding:22 }}>
            <div className="eyebrow" style={{ marginBottom:14 }}>Rating Distribution</div>
            {K.ratings.map((pct,i)=>(
              <div key={i} style={{ display:"flex", alignItems:"center", gap:10, marginBottom:8 }}>
                <span style={{ fontSize:12.5, fontWeight:600, minWidth:40, color:"var(--ink-2)" }}>{5-i} stars</span>
                <div style={{ flex:1, height:8, borderRadius:999, background:"var(--surface-3)", overflow:"hidden" }}>
                  <div style={{ height:"100%", width:pct+"%", borderRadius:999, background:"var(--vh-teal)", transition:"width .5s ease" }}/>
                </div>
                <span style={{ fontSize:12.5, fontWeight:700, minWidth:30, textAlign:"right" }}>{pct}%</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SessionPrep, Gamification, Leaderboard, Reports });
