/* educator-screens3.jsx — Trainers, Products, Integration, Settings */

/* ── TRAINERS ── */
const TRAINERS_DATA = [
  { id:1, name:"Prof. Jan Bakker",       initials:"JB", title:"Senior PM Trainer",          location:"Amsterdam, NL", langs:["Dutch","English"], courses:["IPMA","PRINCE2","TOGAF"], cohorts:28, learners:486, evals:312, score:4.8 },
  { id:2, name:"Mariëlle van der Berg",  initials:"MV", title:"ITIL & Service Mgmt Trainer", location:"Utrecht, NL",   langs:["Dutch","English"], courses:["ITIL","SIAM"],            cohorts:34, learners:612, evals:398, score:4.7 },
  { id:3, name:"David Okonkwo",          initials:"DO", title:"BiSL & Business IT Trainer",  location:"Rotterdam, NL", langs:["English"],          courses:["BiSL","TOGAF"],           cohorts:19, learners:314, evals:201, score:4.6 },
  { id:4, name:"Sophie Vermeer",         initials:"SV", title:"Agile & Scrum Trainer",       location:"Eindhoven, NL", langs:["Dutch","English"],  courses:["IPMA","PRINCE2"],         cohorts:22, learners:388, evals:260, score:4.5 },
];

const COURSE_COLORS_MAP = {
  IPMA:{"#deedf9":"#1281c4"}, PRINCE2:{"#f0e6ff":"#7c3aed"}, TOGAF:{"#e8f5e9":"#2e7d32"},
  ITIL:{"#e8eaf6":"#3949ab"}, BiSL:{"#d0f4f7":"#00838f"}, SIAM:{"#fce4ec":"#c62828"},
};

function CourseTag({ name }) {
  const pairs = { IPMA:["#deedf9","#1281c4"], PRINCE2:["#f0e6ff","#7c3aed"], TOGAF:["#e8f5e9","#2e7d32"], ITIL:["#e8eaf6","#3949ab"], BiSL:["#d0f4f7","#00838f"], SIAM:["#fce4ec","#c62828"] };
  const [bg,color] = pairs[name]||["var(--chip)","var(--ink-2)"];
  return <span style={{ display:"inline-flex", fontSize:11.5, fontWeight:700, padding:"3px 9px", borderRadius:999, background:bg, color, whiteSpace:"nowrap" }}>{name}</span>;
}

function Trainers() {
  const [q,setQ]=useState("");
  const list = TRAINERS_DATA.filter(t=>!q||t.name.toLowerCase().includes(q.toLowerCase()));
  return (
    <div>
      <div className="between" style={{ marginBottom:24 }}>
        <div className="page-head" style={{ marginBottom:0 }}><h1>Trainers</h1><p>{TRAINERS_DATA.length} certified trainers · 116 cohorts delivered</p></div>
        <button className="btn btn-acc" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}><Icon name="plus" size={14}/>Add Trainer</button>
      </div>
      <div className="stat-grid" style={{ marginBottom:22 }}>
        {[
          { label:"Avg Eval Score",    val:"4.6/5.0", icon:"star",       ic:"#00838f",  bg:"var(--vh-blue-50)" },
          { label:"Total Learners",    val:"1,968",   icon:"users",      ic:"#1281c4",  bg:"#deedf9" },
          { label:"Total Cohorts",     val:"116",     icon:"layers",     ic:"#7c3aed",  bg:"#f0e6ff" },
          { label:"Avg NPS",           val:"59",      icon:"bolt",       ic:"#b45309",  bg:"var(--accent-soft)" },
        ].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:30, color:s.ic }}>{s.val}</div>
          </div>
        ))}
      </div>
      <div style={{ display:"flex", gap:12, marginBottom:18, alignItems:"center" }}>
        <label className="search" style={{ maxWidth:300 }}>
          <Icon name="search" size={15}/><input placeholder="Search trainers…" value={q} onChange={e=>setQ(e.target.value)}/>
        </label>
        <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</option><option>ITIL</option><option>PRINCE2</option>
        </select>
      </div>
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:16 }}>
        {list.map(t=>(
          <div key={t.id} className="card" style={{ padding:22 }}>
            <div style={{ display:"flex", gap:14, marginBottom:16 }}>
              <Av initials={t.initials} size={52}/>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontWeight:800, fontSize:16, fontFamily:"var(--display)" }}>{t.name}</div>
                <div className="dim" style={{ fontSize:13, marginTop:3 }}>{t.title}</div>
                <div style={{ display:"flex", gap:8, marginTop:8, flexWrap:"wrap" }}>
                  <span style={{ display:"inline-flex", alignItems:"center", gap:5, fontSize:12, color:"var(--ink-2)" }}><Icon name="globe" size={12}/>{t.location}</span>
                  {t.langs.map(l=><span key={l} className="tag" style={{ fontSize:11.5, padding:"2px 8px" }}>{l}</span>)}
                </div>
              </div>
              <Ring value={(t.score/5)*100} size={64} stroke={6} color="var(--vh-teal)">
                <div style={{ textAlign:"center" }}>
                  <div style={{ fontFamily:"var(--display)", fontWeight:800, fontSize:16, color:"var(--vh-teal)" }}>{t.score}</div>
                  <div style={{ fontSize:9, color:"var(--ink-3)", fontWeight:600 }}>eval</div>
                </div>
              </Ring>
            </div>
            <div style={{ display:"flex", gap:6, flexWrap:"wrap", marginBottom:14 }}>
              {t.courses.map(c=><CourseTag key={c} name={c}/>)}
            </div>
            <div style={{ paddingTop:14, borderTop:"1px solid var(--line)", display:"flex", gap:16, fontSize:12.5, color:"var(--ink-2)" }}>
              <span><strong style={{ color:"var(--ink)", fontFamily:"var(--display)", fontSize:14 }}>{t.cohorts}</strong> cohorts</span>
              <span><strong style={{ color:"var(--ink)", fontFamily:"var(--display)", fontSize:14 }}>{t.learners.toLocaleString()}</strong> learners</span>
              <span><strong style={{ color:"var(--ink)", fontFamily:"var(--display)", fontSize:14 }}>{t.evals}</strong> evaluations</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── PRODUCTS ── */
const PRODUCTS_DATA = [
  { name:"IPMA-D® Certification",  icon:"graduation", color:"var(--vh-blue-500)", content:"Published", courseware:"Published", memo:"Published", selfAssess:"Published", book:"Published", gamified:true,  learners:234 },
  { name:"BiSL® Foundation",       icon:"layers",     color:"var(--vh-teal)",     content:"Published", courseware:"Published", memo:"Published", selfAssess:"Draft",     book:"Published", gamified:true,  learners:189 },
  { name:"ITIL® 4 Foundation",     icon:"globe",      color:"var(--vh-blue-400)", content:"Published", courseware:"Published", memo:"Published", selfAssess:"Published", book:"Published", gamified:true,  learners:312 },
  { name:"PRINCE2® Foundation",    icon:"shield",     color:"#7c3aed",            content:"Published", courseware:"Draft",     memo:"Published", selfAssess:"—",         book:"Published", gamified:false, learners:156 },
  { name:"TOGAF® Foundation",      icon:"cert",       color:"#2e7d32",            content:"Published", courseware:"Published", memo:"—",         selfAssess:"Published", book:"Draft",     gamified:false, learners:98  },
  { name:"SIAM™ Foundation",       icon:"globe",      color:"#c62828",            content:"Draft",     courseware:"—",         memo:"—",         selfAssess:"—",         book:"Draft",     gamified:false, learners:0   },
];

function StatusChip({ v }) {
  if(!v||v==="—") return <span style={{ color:"var(--ink-3)", fontSize:13 }}>—</span>;
  const published = v==="Published";
  return <span style={{ display:"inline-flex", alignItems:"center", gap:4, fontSize:12, fontWeight:600, padding:"3px 10px", borderRadius:999, background:published?"#e8f5e9":"#fff3e0", color:published?"#2e7d32":"#b45309" }}>{v}</span>;
}

function Products() {
  const [selected, setSelected] = useState(null);
  const [form, setForm] = useState({});
  const set = (k,v) => setForm(f=>({...f,[k]:v}));

  if (selected) {
    const SECTIONS = [
      { key:'overview',     label:'About This Course (Overview)',       hint:'Brief summary of the training\'s purpose and unique value. Advised duration.',       rows:4, words:'30–50 words',  req:true  },
      { key:'audience',     label:'Target Audience',                    hint:'Description of who should attend. Specify roles they might search for.',              rows:3, words:'20–30 words',  req:true  },
      { key:'objectives',   label:'Training Objectives',                hint:'Key learning outcomes and skills participants will gain.',                            rows:4, words:'50–70 words',  req:true  },
      { key:'content',      label:'Course Content',                     hint:'Detailed breakdown of topics covered, subtopics and key concepts. Use bullet points.', rows:6, words:'100–150 words', req:true  },
      { key:'prerequisites',label:'Prerequisites',                      hint:'Required prior knowledge or certifications. Mention specific certs or experience.',    rows:2, words:'20–30 words',  req:true  },
      { key:'followUp',     label:'Recommended Follow-Up Trainings',    hint:'Suggestions for further learning and advancement.',                                  rows:3, words:'40–60 words',  req:false },
      { key:'related',      label:'Related Products',                   hint:'Information about related materials, exams or companion products.',                   rows:2, words:'30–40 words',  req:false },
    ];
    const reqKeys = ['title','overview','audience','objectives','content','prerequisites','metaDesc','keywords'];
    const filled = reqKeys.filter(k=>(form[k]||'').length>10).length;
    const score = Math.round((filled/reqKeys.length)*100);
    const scoreColor = score>=70?'#2e7d32':score>=40?'#b45309':'#c62828';
    const scoreLabel = score>=70?'Great':'Fair (fill all fields)';

    const Field = ({fkey, label, type='text', hint, max, rows=1}) => {
      const val = form[fkey]||'';
      const wc = val.trim().split(/\s+/).filter(Boolean).length;
      const style = { width:'100%', padding:'10px 13px', border:'1.5px solid var(--line)', borderRadius:10, fontSize:13.5, color:'var(--ink)', background:'var(--surface)', fontFamily:'var(--body)', outline:'none', resize:'vertical' };
      const focus = e=>e.target.style.borderColor='var(--vh-blue-200)';
      const blur  = e=>e.target.style.borderColor='var(--line)';
      return (
        <div style={{ marginBottom:18 }}>
          <div style={{ display:'flex', justifyContent:'space-between', marginBottom:6, alignItems:'baseline' }}>
            <label style={{ fontSize:12.5, fontWeight:700, color:'var(--ink-2)', textTransform:'uppercase', letterSpacing:'.06em' }}>{label}</label>
            <span style={{ fontSize:11.5, color:'var(--ink-3)' }}>{hint && <span style={{ fontStyle:'italic', marginRight:8 }}>{hint}</span>}{max?`${val.length}/${max}`:wc>0?`${wc} words`:''}</span>
          </div>
          {type==='textarea'
            ? <textarea rows={rows} value={val} onChange={e=>set(fkey,e.target.value)} placeholder="Start typing…" style={style} onFocus={focus} onBlur={blur}/>
            : <input type="text" value={val} onChange={e=>set(fkey,e.target.value)} style={style} onFocus={focus} onBlur={blur}/>}
        </div>
      );
    };

    return (
      <div>
        <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:24 }}>
          <button className="btn btn-ghost btn-sm" onClick={()=>setSelected(null)}><Icon name="chevL" size={14}/>Products</button>
          <span style={{ color:'var(--ink-3)' }}>/</span>
          <span style={{ fontWeight:700 }}>{selected.name}</span>
          <span className="tag" style={{ marginLeft:4 }}>SEO Description</span>
        </div>

        <div style={{ display:'grid', gridTemplateColumns:'1fr 340px', gap:20 }}>
          {/* Left — content form */}
          <div style={{ display:'flex', flexDirection:'column', gap:16 }}>

            {/* Basics */}
            <div className="card" style={{ padding:24 }}>
              <div className="eyebrow" style={{ marginBottom:16 }}>Course Basics</div>
              <Field fkey="title" label="SEO Title" hint="5–10 words" max={60}/>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
                <Field fkey="slug" label="URL Slug" hint='e.g. ipma-d-certification'/>
                <Field fkey="productId" label="Product ID (optional)"/>
              </div>
              <Field fkey="keywords" label="Keywords" hint="Comma-separated primary search terms"/>
            </div>

            {/* Description sections from template */}
            <div className="card" style={{ padding:24 }}>
              <div className="between" style={{ marginBottom:20 }}>
                <div className="eyebrow">Course Description Sections</div>
                <span title="Binnenkort" style={{ fontSize:12.5, color:'var(--ink-3)', fontWeight:600, cursor:"not-allowed", opacity:.6 }}>View template guide</span>
              </div>
              {SECTIONS.map(s=>(
                <div key={s.key}>
                  <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:6 }}>
                    <span style={{ fontSize:13, fontWeight:700, color:'var(--ink)' }}>{s.label}</span>
                    <span style={{ fontSize:11, padding:'2px 8px', borderRadius:999, background:s.req?'var(--vh-blue-50)':'var(--chip)', color:s.req?'var(--vh-blue-600)':'var(--ink-3)', fontWeight:600 }}>{s.req?'Required':'Optional'}</span>
                    <span style={{ fontSize:11.5, color:'var(--ink-3)', marginLeft:'auto', fontStyle:'italic' }}>{s.words}</span>
                  </div>
                  <div style={{ fontSize:12, color:'var(--ink-3)', marginBottom:8 }}>💡 SEO tip: {s.hint}</div>
                  <textarea rows={s.rows} value={form[s.key]||''} onChange={e=>set(s.key,e.target.value)}
                    placeholder="Start typing…"
                    style={{ width:'100%', padding:'10px 13px', border:'1.5px solid var(--line)', borderRadius:10, fontSize:13.5, color:'var(--ink)', background:'var(--surface)', fontFamily:'var(--body)', resize:'vertical', outline:'none', marginBottom:18 }}
                    onFocus={e=>e.target.style.borderColor='var(--vh-blue-200)'}
                    onBlur={e=>e.target.style.borderColor='var(--line)'}/>
                </div>
              ))}
            </div>

            {/* Meta + Google preview */}
            <div className="card" style={{ padding:24 }}>
              <div className="eyebrow" style={{ marginBottom:16 }}>Meta & Search Preview</div>
              <Field fkey="metaDesc" label="Meta Description" type="textarea" hint="150–160 chars" max={160} rows={3}/>
              <div style={{ padding:'16px 20px', borderRadius:12, background:'var(--surface-2)', border:'1px solid var(--line)' }}>
                <div style={{ fontSize:12, color:'var(--ink-3)', marginBottom:4 }}>https://vanharen.net/training/{form.slug||'url-slug'}</div>
                <div style={{ fontSize:18, color:'#1a0dab', fontWeight:600, marginBottom:4 }}>{form.title||selected.name+' — Van Haren Training'}</div>
                <div style={{ fontSize:13.5, color:'var(--ink-2)', lineHeight:1.5 }}>{form.metaDesc||'Professional certification training. Expert-led, online and on-site. Register now.'}</div>
              </div>
            </div>
          </div>

          {/* Right panel */}
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            {/* SEO Score */}
            <div className="card" style={{ padding:20, position:'sticky', top:0 }}>
              <div className="eyebrow" style={{ marginBottom:14 }}>SEO Score</div>
              <div style={{ display:'flex', alignItems:'center', gap:14, marginBottom:16 }}>
                <Ring value={score} size={68} stroke={7} color={scoreColor}>
                  <span style={{ fontFamily:'var(--display)', fontWeight:800, fontSize:17, color:scoreColor }}>{score}</span>
                </Ring>
                <div>
                  <div style={{ fontWeight:700, fontSize:15, color:scoreColor }}>{scoreLabel}</div>
                  <div className="dim" style={{ fontSize:12 }}>{filled}/{reqKeys.length} fields complete</div>
                </div>
              </div>
              {reqKeys.map(k=>{
                const labels={title:'SEO Title',overview:'Overview',audience:'Target Audience',objectives:'Objectives',content:'Course Content',prerequisites:'Prerequisites',metaDesc:'Meta Description',keywords:'Keywords'};
                const ok=(form[k]||'').length>10;
                return (
                  <div key={k} style={{ display:'flex', alignItems:'center', gap:10, padding:'6px 0', borderBottom:'1px solid var(--line-2)' }}>
                    <Icon name={ok?'check':'lock'} size={13} style={{ color:ok?'#2e7d32':'var(--ink-3)' }}/>
                    <span style={{ fontSize:12.5, flex:1 }}>{labels[k]}</span>
                    <span style={{ fontSize:12, color:ok?'#2e7d32':'var(--ink-3)', fontWeight:600 }}>{ok?'✓':'Missing'}</span>
                  </div>
                );
              })}
            </div>

            {/* Publish */}
            <div className="card" style={{ padding:20 }}>
              <div className="eyebrow" style={{ marginBottom:12 }}>Publishing</div>
              <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
                <button className="btn btn-ghost" disabled title="Binnenkort" style={{ justifyContent:'flex-start', opacity:.5, cursor:"not-allowed" }}><Icon name="file" size={14}/>Save as Draft</button>
                <button className="btn btn-pri" disabled title="Binnenkort" style={{ justifyContent:'flex-start', opacity:.5, cursor:"not-allowed" }}><Icon name="share" size={14}/>Publish Page</button>
                <button className="btn btn-acc" disabled title="Binnenkort" style={{ justifyContent:'flex-start', opacity:.5, cursor:"not-allowed" }}><Icon name="globe" size={14}/>Post to Website</button>
              </div>
              <div style={{ marginTop:14, paddingTop:14, borderTop:'1px solid var(--line)', fontSize:12.5, color:'var(--ink-3)' }}>Last edited: today, 11:32</div>
            </div>

            {/* Content status */}
            <div className="card" style={{ padding:20 }}>
              <div className="eyebrow" style={{ marginBottom:12 }}>Content Status</div>
              {[['Course Content',selected.content],['Courseware',selected.courseware],['Book',selected.book],['Gamified',selected.gamified?'On':'Off']].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><StatusChip v={v}/>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="between" style={{ marginBottom:24 }}>
        <div className="page-head" style={{ marginBottom:0 }}><h1>Products</h1><p>Manage content availability for all {PRODUCTS_DATA.length} products</p></div>
        <button className="btn btn-acc" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}><Icon name="plus" size={14}/>New Course</button>
      </div>
      <div className="card" style={{ overflowX:"auto" }}>
        <table className="tbl" style={{ minWidth:900 }}>
          <thead>
            <tr>
              <th>Course</th>
              <th>Course Content</th>
              <th>Courseware</th>
              <th>Memo Trainer</th>
              <th>Self Assess.</th>
              <th>Book</th>
              <th>Gamified</th>
              <th>Learners</th>
              <th>SEO Description</th>
            </tr>
          </thead>
          <tbody>
            {PRODUCTS_DATA.map(p=>(
              <tr key={p.name} style={{ cursor:'pointer' }} onClick={()=>{ setSelected(p); setForm({ title:p.name+' — Van Haren Training', slug:p.name.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/-$/,''), productId:'', keywords:p.name.split('®')[0].trim()+', certification, training, Van Haren', overview:'', audience:'', objectives:'', content:'', prerequisites:'', followUp:'', related:'', metaDesc:'' }); }}>
                <td>
                  <div style={{ display:"flex", alignItems:"center", gap:11 }}>
                    <div style={{ width:38, height:38, borderRadius:10, background:p.color+"22", display:"grid", placeItems:"center" }}>
                      <Icon name={p.icon} size={18} style={{ color:p.color }}/>
                    </div>
                    <div>
                      <div style={{ fontWeight:700 }}>{p.name}</div>
                    </div>
                  </div>
                </td>
                <td><StatusChip v={p.content}/></td>
                <td><StatusChip v={p.courseware}/></td>
                <td><StatusChip v={p.memo}/></td>
                <td><StatusChip v={p.selfAssess}/></td>
                <td><StatusChip v={p.book}/></td>
                <td>
                  {p.gamified
                    ? <span style={{ display:"inline-flex", alignItems:"center", gap:5, fontSize:12.5, fontWeight:700, color:"var(--vh-blue-500)" }}><Icon name="check" size={13} style={{ color:"var(--vh-blue-500)"}}/> On</span>
                    : <span style={{ color:"var(--ink-3)", fontSize:12.5 }}>Off</span>}
                </td>
                <td><span className="kpi" style={{ fontSize:15 }}>{p.learners||"—"}</span></td>
                <td>
                  <button className="btn btn-outline btn-sm" style={{ gap:6 }}
                    onClick={e=>{ e.stopPropagation(); setSelected(p); setForm({ title:p.name+' — Van Haren Training', slug:p.name.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/-$/,''), productId:'', keywords:p.name.split('®')[0].trim()+', certification, training, Van Haren', overview:'', audience:'', objectives:'', content:'', prerequisites:'', followUp:'', related:'', metaDesc:'' }); }}>
                    <Icon name="file" size={12}/> SEO Description
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ── INTEGRATION ── */
const INTEGRATIONS = [
  { id:1, name:"Microsoft Teams",   icon:"slides", status:"Connected",    sync:"2 min ago",    color:"#5059c9", desc:"Live sessions, chat & meeting scheduling" },
  { id:2, name:"Zoom",              icon:"slides", status:"Connected",    sync:"15 min ago",   color:"#2d8cff", desc:"Video sessions and webinar delivery" },
  { id:3, name:"Outlook Calendar",  icon:"clock",  status:"Connected",    sync:"Continuous",   color:"#0078d4", desc:"Session scheduling and reminders" },
  { id:4, name:"LRS / xAPI",        icon:"layers", status:"Connected",    sync:"Real-time",    color:"#2e7d32", desc:"Learning record store for completion tracking" },
  { id:5, name:"Salesforce CRM",    icon:"globe",  status:"Disconnected", sync:"—",            color:"#00a1e0", desc:"Learner enrollment and CRM sync" },
  { id:6, name:"Moodle LMS",        icon:"book",   status:"Disconnected", sync:"—",            color:"#f98012", desc:"External LMS content exchange" },
];

function Integration() {
  const [states, setStates] = useState(() => Object.fromEntries(INTEGRATIONS.map(i=>[i.id, i.status==="Connected"])));
  return (
    <div>
      <div className="between" style={{ marginBottom:24 }}>
        <div className="page-head" style={{ marginBottom:0 }}><h1>Integration</h1><p>Connect external tools, LMS systems and data services.</p></div>
        <button className="btn btn-acc" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}><Icon name="plus" size={14}/>Add Integration</button>
      </div>

      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:16, marginBottom:24 }}>
        {INTEGRATIONS.map(intg=>(
          <div key={intg.id} className="card" style={{ padding:20 }}>
            <div style={{ display:"flex", alignItems:"flex-start", gap:14 }}>
              <div style={{ width:44, height:44, borderRadius:12, background:intg.color+"18", display:"grid", placeItems:"center", flex:"none" }}>
                <Icon name={intg.icon} size={20} style={{ color:intg.color }}/>
              </div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontWeight:700, fontSize:15 }}>{intg.name}</div>
                <div className="dim" style={{ fontSize:12.5, marginTop:3 }}>{intg.desc}</div>
                {states[intg.id]&&<div style={{ fontSize:11.5, color:"#2e7d32", marginTop:6, display:"flex", alignItems:"center", gap:5 }}><span style={{ width:6, height:6, borderRadius:"50%", background:"#2e7d32", display:"inline-block" }}/>Last sync: {intg.sync}</div>}
              </div>
              {/* Toggle */}
              <button onClick={()=>setStates(s=>({...s,[intg.id]:!s[intg.id]}))}
                style={{ width:44, height:24, borderRadius:999, background:states[intg.id]?"var(--vh-blue-500)":"var(--line)", border:"none", cursor:"pointer", position:"relative", transition:"background .2s", flexShrink:0 }}>
                <span style={{ position:"absolute", top:3, left:states[intg.id]?20:3, width:18, height:18, borderRadius:"50%", background:"#fff", boxShadow:"0 1px 3px rgba(0,0,0,.2)", transition:"left .2s", display:"block" }}/>
              </button>
            </div>
            <div style={{ marginTop:14, paddingTop:14, borderTop:"1px solid var(--line)", display:"flex", justifyContent:"space-between", alignItems:"center" }}>
              <span className={"tag "+(states[intg.id]?"green":"")}>
                {states[intg.id]?"● Connected":"○ Disconnected"}
              </span>
              <button className="btn btn-outline btn-sm" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}>{states[intg.id]?"Configure":"Connect"} <Icon name="arrowR" size={12}/></button>
            </div>
          </div>
        ))}
      </div>

      {/* API token */}
      <div className="card" style={{ padding:22 }}>
        <div className="between" style={{ marginBottom:16 }}>
          <div><div className="eyebrow">API Access</div><div style={{ fontWeight:700, fontSize:15, marginTop:4 }}>Developer Token</div></div>
          <button className="btn btn-ghost btn-sm" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}><Icon name="refresh" size={13}/>Rotate token</button>
        </div>
        <div style={{ display:"flex", alignItems:"center", gap:12, padding:"12px 16px", borderRadius:10, background:"var(--surface-2)", border:"1px solid var(--line)", fontFamily:"ui-monospace,monospace", fontSize:13, color:"var(--ink-2)" }}>
          <Icon name="lock" size={15} style={{ color:"var(--ink-3)" }}/>
          <span style={{ flex:1 }}>vh_edu_••••••••••••••••••••••••••••••••</span>
          <button className="btn btn-ghost btn-sm" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}>Copy</button>
        </div>
      </div>
    </div>
  );
}

/* ── SETTINGS ── */
function Settings() {
  const [notifs, setNotifs] = useState({ email:true, inapp:true, weekly:false, cert:true });
  const [prefs, setPrefs] = useState({ lang:"English", timezone:"Europe/Amsterdam", theme:"light" });

  return (
    <div>
      <div className="page-head"><h1>Settings</h1><p>Manage your profile, notifications and preferences.</p></div>
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:18 }}>
        {/* Profile */}
        <div className="card" style={{ padding:24 }}>
          <div className="eyebrow" style={{ marginBottom:16 }}>Profile</div>
          <div style={{ display:"flex", alignItems:"center", gap:16, marginBottom:20 }}>
            <Av initials="EA" size={64}/>
            <div>
              <div style={{ fontFamily:"var(--display)", fontWeight:800, fontSize:18 }}>Eva Andersson</div>
              <div className="dim" style={{ fontSize:13 }}>Senior Educator</div>
              <button className="btn btn-ghost btn-sm" disabled title="Binnenkort" style={{ marginTop:8, fontSize:12, opacity:.5, cursor:"not-allowed" }}>Change photo</button>
            </div>
          </div>
          {[["Full name","Eva Andersson"],["Email","educator@vanharen.net"],["Job title","Senior Educator"],["Department","Learning & Development"]].map(([label,val])=>(
            <div key={label} style={{ marginBottom:14 }}>
              <div style={{ fontSize:12, fontWeight:600, color:"var(--ink-3)", marginBottom:5, textTransform:"uppercase", letterSpacing:".06em" }}>{label}</div>
              <input defaultValue={val} style={{ width:"100%", padding:"10px 13px", border:"1.5px solid var(--line)", borderRadius:10, fontSize:13.5, color:"var(--ink)", background:"var(--surface)", fontFamily:"var(--body)", outline:"none", transition:"border-color .15s" }}
                onFocus={e=>e.target.style.borderColor="var(--vh-blue-200)"}
                onBlur={e=>e.target.style.borderColor="var(--line)"}/>
            </div>
          ))}
          <button className="btn btn-pri" disabled title="Binnenkort" style={{ marginTop:4, opacity:.5, cursor:"not-allowed" }}>Save changes</button>
        </div>

        <div style={{ display:"flex", flexDirection:"column", gap:18 }}>
          {/* Notifications */}
          <div className="card" style={{ padding:22 }}>
            <div className="eyebrow" style={{ marginBottom:16 }}>Notifications</div>
            {[
              ["email",   "Email notifications",     "Receive session reminders and learner alerts"],
              ["inapp",   "In-app notifications",    "Get real-time alerts inside the platform"],
              ["weekly",  "Weekly digest",           "Summary of learner progress every Monday"],
              ["cert",    "Certificate alerts",      "When a learner reaches certification readiness"],
            ].map(([key,label,desc])=>(
              <div key={key} style={{ display:"flex", alignItems:"center", gap:14, padding:"11px 0", borderBottom:"1px solid var(--line-2)" }}>
                <div style={{ flex:1 }}>
                  <div style={{ fontWeight:600, fontSize:14 }}>{label}</div>
                  <div className="dim" style={{ fontSize:12 }}>{desc}</div>
                </div>
                <button onClick={()=>setNotifs(n=>({...n,[key]:!n[key]}))}
                  style={{ width:44, height:24, borderRadius:999, background:notifs[key]?"var(--vh-blue-500)":"var(--line)", border:"none", cursor:"pointer", position:"relative", transition:"background .2s", flexShrink:0 }}>
                  <span style={{ position:"absolute", top:3, left:notifs[key]?20:3, width:18, height:18, borderRadius:"50%", background:"#fff", boxShadow:"0 1px 3px rgba(0,0,0,.2)", transition:"left .2s", display:"block" }}/>
                </button>
              </div>
            ))}
          </div>

          {/* Preferences */}
          <div className="card" style={{ padding:22 }}>
            <div className="eyebrow" style={{ marginBottom:16 }}>Preferences</div>
            {[["Language","lang",["English","Dutch","German","French"]],["Timezone","timezone",["Europe/Amsterdam","Europe/London","America/New_York"]],["Theme","theme",["light","dark","system"]]].map(([label,key,opts])=>(
              <div key={key} style={{ marginBottom:14 }}>
                <div style={{ fontSize:12, fontWeight:600, color:"var(--ink-3)", marginBottom:5, textTransform:"uppercase", letterSpacing:".06em" }}>{label}</div>
                <select value={prefs[key]} onChange={e=>setPrefs(p=>({...p,[key]:e.target.value}))}
                  style={{ width:"100%", padding:"10px 13px", border:"1.5px solid var(--line)", borderRadius:10, fontSize:13.5, color:"var(--ink)", background:"var(--surface)", fontFamily:"var(--body)", cursor:"pointer", outline:"none" }}>
                  {opts.map(o=><option key={o} value={o}>{o}</option>)}
                </select>
              </div>
            ))}
          </div>

          {/* Security */}
          <div className="card" style={{ padding:22 }}>
            <div className="eyebrow" style={{ marginBottom:16 }}>Security</div>
            <button className="btn btn-outline" disabled title="Binnenkort" style={{ width:"100%", marginBottom:10, justifyContent:"flex-start", opacity:.5, cursor:"not-allowed" }}><Icon name="lock" size={15}/>Change password</button>
            <button className="btn btn-outline" disabled title="Binnenkort" style={{ width:"100%", justifyContent:"flex-start", opacity:.5, cursor:"not-allowed" }}><Icon name="shield" size={15}/>Enable two-factor authentication</button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── App (final render) ── */
const TITLES = {
  dashboard:"Dashboard", cohorts:"My Cohorts", learners:"Learners",
  trainers:"Trainers", products:"Products",
  prep:"Session Prep", gamification:"Gamification",
  leaderboard:"Leaderboard", reports:"Course KPIs",
  integration:"Integration", settings:"Settings", features:"Features", styling:"Style Tailor",
  events:"Events", studio:"Presentation Studio",
};

function App() {
  const [lang, setLang] = useState(() => localStorage.getItem('vhl_lang') || 'en');
  const [route,setRoute]=useState("dashboard");
  const [toastMsg, setToastMsg] = useState(null);
  const toast = (msg, icon) => { setToastMsg({ msg, icon, key: Date.now() }); };
  useEffect(() => { window.eduToast = toast; }, []);
  useEffect(() => {
    if (!toastMsg) return;
    const id = setTimeout(() => setToastMsg(null), 2800);
    return () => clearTimeout(id);
  }, [toastMsg]);
  useEffect(() => {
    localStorage.setItem('vhl_lang', lang);
    const isRTL = (LANG_LIST.find(l => l.code === lang) || {}).rtl;
    document.documentElement.dir = isRTL ? 'rtl' : 'ltr';
    document.documentElement.lang = lang;
  }, [lang]);
  const go=r=>{setRoute(r);document.querySelector(".canvas")?.scrollTo(0,0);};
  return (
    <LangContext.Provider value={{ lang, setLang }}>
      <div className="app">
        <Sidebar route={route} go={go}/>
        <div className="main">
          <Topbar/>
          <div className="canvas scroll">
            {route==="events"      && <Events/>}
            {(route==="studio"||route==="products") && <window.ProductsScreen toast={toast}/>}
            {route==="dashboard"    && <Dashboard go={go}/>}
            {route==="cohorts"      && <Cohorts/>}
            {route==="learners"     && <Learners/>}
            {route==="trainers"     && <Trainers/>}
            {route==="prep"         && <SessionPrep/>}
            {route==="gamification" && <Gamification/>}
            {route==="leaderboard"  && <Leaderboard/>}
            {route==="reports"      && <Reports/>}
            {route==="contacts"     && window.Contacts && <window.Contacts/>}
            {route==="trainer-kpis" && window.TrainerKPIs && <window.TrainerKPIs/>}
            {route==="mailing"      && window.Mailing && <window.Mailing/>}
            {route==="integration"  && <Integration/>}
            {route==="styling"      && window.StyleTailor && <window.StyleTailor/>}
            {route==="features"     && window.FeatureSettings && <window.FeatureSettings/>}
            {route==="settings"     && <Settings/>}
          </div>
        </div>
        {toastMsg && (
          <div key={toastMsg.key} style={{ position:"fixed", bottom:28, left:"50%", transform:"translateX(-50%)", zIndex:400, display:"flex", alignItems:"center", gap:10, background:"var(--vh-navy)", color:"#fff", padding:"13px 22px", borderRadius:12, boxShadow:"0 12px 40px rgba(13,26,52,.35)", fontSize:14, fontWeight:600, animation:"vhPop .3s both" }}>
            <Icon name={toastMsg.icon || "check"} size={17} style={{ color:"var(--vh-orange)" }}/>{toastMsg.msg}
          </div>
        )}
      </div>
    </LangContext.Provider>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
