/* educator-features.jsx — Platform Feature settings: select · save · export */

const FEATURE_GROUPS = [
  { id:"learner", title:"Learner", icon:"graduation", color:"#1281c4",
    items:[
      { id:"ple",        label:"Personal learning environment", desc:"One home for courses, slides & books", tier:1 },
      { id:"voucher",    label:"Access via voucher link",       desc:"Invite code or link — zero friction", tier:1 },
      { id:"social-reg", label:"Register via socials (SSO)",    desc:"Sign up with socials or email", tier:1 },
      { id:"gami",       label:"Gamification",                  desc:"XP, badges, streaks & leaderboards", tier:1 },
      { id:"passport",   label:"Skills Passport",               desc:"Verified e-CF competency record", tier:2 },
      { id:"l-mail",     label:"Communication & mailing",       desc:"Multilingual (EN/NL/DE/ES/AR)", tier:2 },
    ]},
  { id:"trainer", title:"Trainer", icon:"person", color:"#3bc1ce",
    items:[
      { id:"t-dash",     label:"Trainer dashboard",     desc:"Evaluation score, NPS & learner load", tier:1 },
      { id:"live",       label:"Live Session mode",     desc:"Present slides with real-time Q&A", tier:2 },
      { id:"t-cohorts",  label:"My Cohorts",            desc:"Roster & engagement RAG tracking", tier:1 },
      { id:"t-mats",     label:"My Materials",          desc:"Courseware, slideware, memo cards, books", tier:1 },
      { id:"evals",      label:"Evaluations",           desc:"360° feedback across 9 dimensions", tier:2 },
      { id:"cand-fb",    label:"Candidate feedback",    desc:"Collected & shared back to learners", tier:2 },
      { id:"one-env",    label:"One environment for all", desc:"Every cohort & tool in one place", tier:1 },
      { id:"qa-inbox",   label:"Learner Q&A inbox",     desc:"Answer questions in one place", tier:2 },
    ]},
  { id:"educator", title:"Educator", icon:"grid", color:"#1d3d7c",
    items:[
      { id:"admin-dash", label:"Central admin dashboard", desc:"All activity at a glance", tier:1 },
      { id:"kanban",     label:"Cohort Kanban",           desc:"Planned → Conducting → Completed", tier:1 },
      { id:"manage",     label:"Learner & trainer management", desc:"From one console", tier:1 },
      { id:"catalogue",  label:"Products catalogue",      desc:"Courses, materials & assets", tier:1 },
      { id:"lb-oversee", label:"Leaderboard oversight",   desc:"Across cohorts & globally", tier:2 },
      { id:"int-set",    label:"Integrations & settings", desc:"Connect your stack", tier:2 },
      { id:"custom-env", label:"Custom environment",      desc:"Own branding, colours & style", tier:3 },
      { id:"var-rewards",label:"Variable rewards",        desc:"Surprise gamification incentives", tier:3 },
    ]},
  { id:"content", title:"Content Creation", icon:"slides", color:"#f99d25",
    items:[
      { id:"studio",     label:"Presentation Studio",   desc:"Build & manage slide decks", tier:1 },
      { id:"html-slides",label:"Rebuild slides to HTML", desc:"Crisp at any size", tier:2 },
      { id:"per-slide",  label:"Per-slide styling",     desc:"Theming with live preview", tier:2 },
      { id:"auto-gami",  label:"AI auto-gamification",  desc:"Quizzes, flashcards, XP", tier:2 },
      { id:"audiobooks", label:"Audiobooks",            desc:"Turn books into listening books", tier:3 },
      { id:"labs",       label:"Labs",                  desc:"Hands-on practice environments", tier:3 },
      { id:"prac-exam",  label:"Practice exam generation", desc:"", tier:2 },
      { id:"real-exam",  label:"Real exam creation",    desc:"Proctoring & (social) badging", tier:3 },
      { id:"upload-pptx",label:"Upload PPTX",           desc:"Import existing decks", tier:1 },
      { id:"ai-content", label:"AI content generation", desc:"Draft courses & assets", tier:3 },
    ]},
  { id:"resource", title:"Resource Management", icon:"book", color:"#0891b2",
    items:[
      { id:"content-lib",label:"Content library",       desc:"Internal & external courseware", tier:1 },
      { id:"trainer-lib",label:"Trainers library",      desc:"Internal & external booking", tier:2 },
      { id:"elearn-lib", label:"eLearnings library",    desc:"Internal & external", tier:2 },
      { id:"reselling",  label:"Seat reselling",        desc:"Sell, buy & exchange seats", tier:3 },
      { id:"games-lib",  label:"Games library",         desc:"Reusable gamified activities", tier:2 },
      { id:"mcp-import", label:"Import content via MCP", desc:"Connect external sources", tier:3 },
      { id:"scorm-lti",  label:"Connect eLearnings",    desc:"SCORM & LTI connectors", tier:2 },
      { id:"bulk-import",label:"Content bulk import",   desc:"", tier:2 },
      { id:"booking-exp",label:"Export to booking platforms", desc:"Edudex, Bloomville, Archipel, Springest", tier:3 },
    ]},
  { id:"cohort", title:"Cohort Management", icon:"users", color:"#0f6ca6",
    items:[
      { id:"plan-sched", label:"Plan & schedule cohorts", desc:"On-site, virtual or blended", tier:1 },
      { id:"assign",     label:"Assign trainers & seats", desc:"Per session", tier:1 },
      { id:"roster",     label:"Participant roster",      desc:"With engagement status", tier:1 },
      { id:"sess-prep",  label:"Session Prep",            desc:"Materials & gamification ready to go", tier:2 },
      { id:"voucher-alloc", label:"Voucher & seat allocation", desc:"Per client", tier:2 },
      { id:"lifecycle",  label:"Lifecycle tracking",      desc:"Kick-off to certification", tier:2 },
      { id:"run-elearn", label:"Run eLearnings",          desc:"Deliver online modules to cohorts", tier:2 },
    ]},
  { id:"reports", title:"Evaluation & Reports", icon:"bars", color:"#7c3aed",
    items:[
      { id:"course-kpi", label:"Course KPI dashboards",  desc:"Completion, pass rate, NPS", tier:1 },
      { id:"trainer-kpi",label:"Trainer KPIs",           desc:"Scores & benchmarking", tier:2 },
      { id:"eval-surveys",label:"Evaluation surveys",    desc:"Auto-sent after each cohort", tier:2 },
      { id:"engage-an",  label:"Engagement analytics",   desc:"XP, streaks & activity", tier:2 },
      { id:"nps",        label:"Satisfaction & NPS scoring", desc:"Per dimension", tier:2 },
      { id:"export-rep", label:"Exportable reports",     desc:"For clients & management", tier:2 },
      { id:"eval-links", label:"Evaluation-tool links",  desc:"CourseSurvey & others", tier:3 },
      { id:"passport-gen",label:"Skills Passport generation", desc:"", tier:3 },
      { id:"recommend",  label:"Course recommendation",  desc:"Next-step suggestions", tier:3 },
    ]},
  { id:"security", title:"Accreditation & Security", icon:"shield", color:"#c0392b",
    items:[
      { id:"qms",        label:"Quality management",     desc:"Extracts & processes", tier:2 },
      { id:"iso9001",    label:"ISO 9001",               desc:"Documentation & tasks", tier:2 },
      { id:"iso27001",   label:"ISO 27001",              desc:"Documentation, tasks & platform input", tier:3 },
      { id:"gdpr",       label:"GDPR settings",          desc:"Data controls", tier:1 },
      { id:"ttt",        label:"Train-the-Trainer module", desc:"Certify your own trainers", tier:3 },
    ]},
  { id:"crm", title:"CRM", icon:"globe", color:"#2e7d32",
    items:[
      { id:"accounts",   label:"Accounts & contacts",    desc:"Client organisations in one place", tier:1 },
      { id:"t-accounts", label:"Trainer accounts",       desc:"& assignment history", tier:2 },
      { id:"seat-med",   label:"Seat mediation tracking", desc:"Per deal", tier:3 },
      { id:"pipeline",   label:"Pipeline overview",      desc:"From lead to enrolment", tier:2 },
      { id:"contacts",   label:"Contact records",        desc:"Linked to cohorts & orders", tier:1 },
      { id:"crm-int",    label:"Integrations",           desc:"Sync your existing tools", tier:2 },
      { id:"support",    label:"Support system",         desc:"Tickets & help features", tier:2 },
    ]},
  { id:"marketing", title:"Marketing & Payment", icon:"mail", color:"#d4761b",
    items:[
      { id:"campaigns",  label:"Mailing campaigns",      desc:"Reach learners & prospects", tier:2 },
      { id:"events-reg", label:"Events & registration",  desc:"Host & sign-up flows", tier:2 },
      { id:"voucher-codes", label:"Voucher links & codes", desc:"Instant access", tier:1 },
      { id:"advice-med", label:"Seat & advice mediation", desc:"Commission-based revenue", tier:3 },
      { id:"billing",    label:"Platform fees & billing", desc:"Per user", tier:2 },
      { id:"payment",    label:"Payment integration",    desc:"Checkout built in", tier:2 },
      { id:"social-post",label:"Social post features",   desc:"Publish from templates", tier:3 },
      { id:"mca",        label:"Marketing Content Agent", desc:"Auto-generate from course & portfolio", tier:3 },
    ]},
];

const ALL_FEATURES = FEATURE_GROUPS.flatMap(g => g.items.map(it => ({ ...it, group:g.id, groupTitle:g.title })));
const FEATURE_TOTAL = ALL_FEATURES.length;
const FEATURE_STORE_KEY = "vhl_features";

const PLAN_PRESETS = [
  { id:"all",     label:"All features", maxTier:99 },
  { id:"enterprise", label:"Enterprise", maxTier:3 },
  { id:"professional", label:"Professional", maxTier:2 },
  { id:"core",    label:"Core", maxTier:1 },
  { id:"none",    label:"None", maxTier:0 },
];

function presetState(maxTier) {
  const s = {};
  ALL_FEATURES.forEach(f => { s[f.id] = f.tier <= maxTier; });
  return s;
}

function FeatureToggle({ on, onClick, color }) {
  return (
    <button onClick={onClick} aria-pressed={on}
      style={{ width:42, height:23, borderRadius:999, background:on?(color||"var(--vh-blue-500)"):"var(--line)", border:"none", cursor:"pointer", position:"relative", transition:"background .2s", flexShrink:0 }}>
      <span style={{ position:"absolute", top:3, left:on?22:3, width:17, height:17, borderRadius:"50%", background:"#fff", boxShadow:"0 1px 3px rgba(0,0,0,.2)", transition:"left .2s", display:"block" }}/>
    </button>
  );
}

function FeatureSettings() {
  const [state, setState] = useState(() => {
    try {
      const raw = JSON.parse(localStorage.getItem(FEATURE_STORE_KEY) || "null");
      if (raw && typeof raw === "object") {
        const s = {};
        ALL_FEATURES.forEach(f => { s[f.id] = f.id in raw ? !!raw[f.id] : true; });
        return s;
      }
    } catch (e) {}
    return presetState(99);
  });
  const [dirty, setDirty] = useState(false);
  const [query, setQuery] = useState("");
  const [exportOpen, setExportOpen] = useState(false);

  const enabledCount = ALL_FEATURES.reduce((n, f) => n + (state[f.id] ? 1 : 0), 0);
  const pct = Math.round((enabledCount / FEATURE_TOTAL) * 100);

  function toast(msg, icon) { if (window.eduToast) window.eduToast(msg, icon); }
  function setFeature(id, val) { setState(s => ({ ...s, [id]: val })); setDirty(true); }
  function toggleGroup(g, val) {
    setState(s => { const n = { ...s }; g.items.forEach(it => { n[it.id] = val; }); return n; });
    setDirty(true);
  }
  function applyPreset(p) { setState(presetState(p.maxTier)); setDirty(true); toast(`${p.label} preset applied`, "bolt"); }
  function save() {
    localStorage.setItem(FEATURE_STORE_KEY, JSON.stringify(state));
    setDirty(false);
    toast("Feature configuration saved", "check");
  }

  function download(name, content, type) {
    const blob = new Blob([content], { type });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = name; document.body.appendChild(a); a.click();
    document.body.removeChild(a); URL.revokeObjectURL(url);
  }
  function exportJSON() {
    const payload = {
      product: "LearnALot LMS & Gamification",
      generated: new Date().toISOString(),
      enabled: enabledCount, total: FEATURE_TOTAL,
      groups: FEATURE_GROUPS.map(g => ({
        category: g.title,
        features: g.items.map(it => ({ id:it.id, name:it.label, enabled:!!state[it.id], tier:it.tier })),
      })),
    };
    download("learnalot-features.json", JSON.stringify(payload, null, 2), "application/json");
    setExportOpen(false); toast("Exported JSON", "file");
  }
  function exportCSV() {
    const rows = [["Category","Feature","Description","Tier","Enabled"]];
    ALL_FEATURES.forEach(f => rows.push([f.groupTitle, f.label, f.desc || "", "T"+f.tier, state[f.id] ? "Yes" : "No"]));
    const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g,'""')}"`).join(",")).join("\n");
    download("learnalot-features.csv", csv, "text/csv");
    setExportOpen(false); toast("Exported CSV", "file");
  }
  function printSheet() {
    setExportOpen(false);
    setTimeout(() => window.print(), 60);
  }

  const sheet = ReactDOM.createPortal(
    <div id="feature-export-sheet">
      <style>{`
        #feature-export-sheet{font-family:'Hanken Grotesk',system-ui,sans-serif;color:#231f20;background:#fff;width:100%}
        #feature-export-sheet .fx-head{background:#1d3d7c;color:#fff;border-radius:12px;padding:16px 20px;display:flex;align-items:center;justify-content:space-between;gap:18px}
        #feature-export-sheet .fx-brand{display:flex;align-items:center;gap:13px}
        #feature-export-sheet .fx-brand img{height:26px;width:auto;display:block}
        #feature-export-sheet .fx-divider{width:1px;height:30px;background:rgba(255,255,255,.3)}
        #feature-export-sheet .fx-eyebrow{font-family:'Saira',sans-serif;text-transform:uppercase;letter-spacing:.2em;font-size:8.5px;font-weight:600;color:#94bfe6}
        #feature-export-sheet .fx-title{font-family:'Saira',sans-serif;font-weight:800;font-size:21px;line-height:1;margin-top:3px}
        #feature-export-sheet .fx-title b{color:#f99d25}
        #feature-export-sheet .fx-meta{text-align:right;font-size:10.5px;line-height:1.5;color:rgba(255,255,255,.85)}
        #feature-export-sheet .fx-count{font-family:'Saira',sans-serif;font-weight:800;font-size:26px;color:#fff;line-height:1}
        #feature-export-sheet .fx-cols{column-count:3;column-gap:14px;margin-top:14px}
        #feature-export-sheet .fx-cat{break-inside:avoid;-webkit-column-break-inside:avoid;page-break-inside:avoid;margin-bottom:11px;border:1px solid #e6ecf4;border-radius:8px;overflow:hidden}
        #feature-export-sheet .fx-cat-h{display:flex;align-items:center;gap:7px;padding:6px 9px;border-bottom:1px solid #e6ecf4}
        #feature-export-sheet .fx-dot{width:9px;height:9px;border-radius:3px;flex:none;transform:rotate(45deg)}
        #feature-export-sheet .fx-cat-t{font-family:'Saira',sans-serif;font-weight:700;font-size:10.5px;color:#1d3d7c;flex:1;line-height:1}
        #feature-export-sheet .fx-cat-n{font-size:8.5px;font-weight:700;color:#7d8aa0}
        #feature-export-sheet ul.fx-list{list-style:none;margin:0;padding:5px 9px 7px}
        #feature-export-sheet ul.fx-list li{display:flex;align-items:flex-start;gap:6px;font-size:8.6px;line-height:1.3;padding:1.6px 0;color:#3a4252}
        #feature-export-sheet ul.fx-list li.off{color:#aeb6c4}
        #feature-export-sheet ul.fx-list li.off .fx-name{text-decoration:line-through}
        #feature-export-sheet .fx-box{width:9px;height:9px;border-radius:2px;flex:none;margin-top:1.5px;border:1.2px solid #c3ccda;display:grid;place-items:center}
        #feature-export-sheet .fx-box svg{width:7px;height:7px;display:block}
        #feature-export-sheet .fx-foot{margin-top:6px;display:flex;align-items:center;justify-content:space-between;font-size:8.5px;color:#7d8aa0}
      `}</style>
      <div className="fx-head">
        <div className="fx-brand">
          <img src="assets/vanharen-logo.png" alt="Van Haren" style={{ filter:"brightness(0) invert(1)" }}/>
          <div className="fx-divider"></div>
          <div>
            <div className="fx-eyebrow">Platform Feature Configuration</div>
            <div className="fx-title">Learn<b>A</b>Lot</div>
          </div>
        </div>
        <div className="fx-meta">
          <div className="fx-count">{enabledCount}<span style={{ fontSize:13, fontWeight:600, color:"rgba(255,255,255,.7)" }}> / {FEATURE_TOTAL}</span></div>
          <div>features enabled</div>
          <div style={{ marginTop:3 }}>{new Date().toLocaleDateString("en-GB", { day:"numeric", month:"long", year:"numeric" })}</div>
        </div>
      </div>
      <div className="fx-cols">
        {FEATURE_GROUPS.map(g => {
          const on = g.items.reduce((n,it)=>n+(state[it.id]?1:0),0);
          return (
            <div key={g.id} className="fx-cat">
              <div className="fx-cat-h">
                <span className="fx-dot" style={{ background:g.color }}></span>
                <span className="fx-cat-t">{g.title}</span>
                <span className="fx-cat-n">{on}/{g.items.length}</span>
              </div>
              <ul className="fx-list">
                {g.items.map(it => {
                  const isOn = !!state[it.id];
                  return (
                    <li key={it.id} className={isOn?"":"off"}>
                      <span className="fx-box" style={isOn?{ background:g.color, borderColor:g.color }:undefined}>
                        {isOn && <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 13l4 4L19 7"/></svg>}
                      </span>
                      <span className="fx-name">{it.label}</span>
                    </li>
                  );
                })}
              </ul>
            </div>
          );
        })}
      </div>
      <div className="fx-foot">
        <span>Van Haren Learning — LearnALot LMS &amp; Gamification</span>
        <span>Filled = enabled · Empty = not included in this environment</span>
      </div>
    </div>,
    document.body
  );

  const q = query.trim().toLowerCase();
  const groups = FEATURE_GROUPS.map(g => ({
    ...g,
    items: q ? g.items.filter(it => (it.label + " " + (it.desc||"")).toLowerCase().includes(q)) : g.items,
  })).filter(g => g.items.length);

  return (
    <div>
      {/* Header */}
      <div className="between" style={{ marginBottom:18, alignItems:"flex-start", gap:16, flexWrap:"wrap" }}>
        <div className="page-head" style={{ marginBottom:0 }}>
          <h1>Features</h1>
          <p>Select which platform capabilities are enabled for this environment, then save or export the configuration.</p>
        </div>
        <div style={{ display:"flex", alignItems:"center", gap:10, position:"relative" }}>
          <div style={{ position:"relative" }}>
            <button className="btn btn-outline" onClick={()=>setExportOpen(o=>!o)}><Icon name="file" size={14}/>Export<Icon name="chevD" size={11} style={{ opacity:.5 }}/></button>
            {exportOpen && (
              <div className="card" style={{ position:"absolute", right:0, top:"calc(100% + 6px)", zIndex:20, padding:6, minWidth:190, boxShadow:"var(--shadow-lg)" }}>
                {[["Save as PDF (one sheet)","download",printSheet],["Export as JSON","file",exportJSON],["Export as CSV","bars",exportCSV]].map(([label,ic,fn])=>(
                  <button key={label} onClick={fn} className="prep-tool" style={{ width:"100%", background:"none", border:"none", justifyContent:"flex-start", marginBottom:2 }}>
                    <Icon name={ic} size={15} style={{ color:"var(--ink-3)" }}/>{label}
                  </button>
                ))}
              </div>
            )}
          </div>
          <button className="btn btn-pri" onClick={save} disabled={!dirty} style={{ opacity:dirty?1:.55, cursor:dirty?"pointer":"default" }}>
            <Icon name="check" size={14}/>{dirty ? "Save changes" : "Saved"}
          </button>
        </div>
      </div>

      {/* Summary + presets bar */}
      <div className="card" style={{ padding:"18px 22px", marginBottom:20 }}>
        <div className="between" style={{ gap:20, flexWrap:"wrap" }}>
          <div style={{ display:"flex", alignItems:"center", gap:22 }}>
            <div>
              <div style={{ display:"flex", alignItems:"baseline", gap:8 }}>
                <span className="kpi" style={{ fontSize:30, color:"var(--vh-navy)" }}>{enabledCount}</span>
                <span className="dim" style={{ fontSize:15, fontWeight:600 }}>of {FEATURE_TOTAL} features enabled</span>
              </div>
              <div className="bar green" style={{ width:240, marginTop:9 }}><i style={{ width:pct+"%" }}/></div>
            </div>
          </div>
          <div style={{ display:"flex", alignItems:"center", gap:10, flexWrap:"wrap" }}>
            <span className="dim" style={{ fontSize:12, fontWeight:700, textTransform:"uppercase", letterSpacing:".1em" }}>Quick plan</span>
            {PLAN_PRESETS.map(p=>(
              <button key={p.id} className="filter-chip" onClick={()=>applyPreset(p)}>{p.label}</button>
            ))}
          </div>
        </div>
      </div>

      {/* Search */}
      <label className="search" style={{ maxWidth:360, marginBottom:18 }}>
        <Icon name="search" size={17}/><input value={query} onChange={e=>setQuery(e.target.value)} placeholder="Search features…"/>
      </label>

      {/* Category cards */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(2, 1fr)", gap:18, alignItems:"start" }}>
        {groups.map(g=>{
          const on = g.items.reduce((n,it)=>n+(state[it.id]?1:0),0);
          const allOn = on === g.items.length;
          return (
            <div key={g.id} className="card" style={{ padding:0, overflow:"hidden" }}>
              <div style={{ display:"flex", alignItems:"center", gap:13, padding:"15px 18px", borderBottom:"1px solid var(--line)", background:"var(--surface-2)" }}>
                <div style={{ width:38, height:38, borderRadius:11, display:"grid", placeItems:"center", flex:"none", background:g.color+"18" }}>
                  <Icon name={g.icon} size={19} style={{ color:g.color }}/>
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontFamily:"var(--display)", fontWeight:700, fontSize:15.5, color:"var(--vh-navy)" }}>{g.title}</div>
                  <div className="dim" style={{ fontSize:12 }}>{on} of {g.items.length} enabled</div>
                </div>
                <button className="btn btn-sm btn-ghost" style={{ fontSize:12 }} onClick={()=>toggleGroup(g, !allOn)}>{allOn ? "Disable all" : "Enable all"}</button>
              </div>
              <div style={{ padding:"4px 18px 8px" }}>
                {g.items.map(it=>{
                  const isOn = !!state[it.id];
                  return (
                    <div key={it.id} style={{ display:"flex", alignItems:"center", gap:14, padding:"11px 0", borderBottom:"1px solid var(--line-2)" }}>
                      <div style={{ flex:1, minWidth:0 }}>
                        <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                          <span style={{ fontWeight:600, fontSize:13.7, color:isOn?"var(--ink)":"var(--ink-3)" }}>{it.label}</span>
                          <span title={["","Core","Professional","Enterprise"][it.tier]} style={{ fontSize:9.5, fontWeight:800, letterSpacing:".05em", color:g.color, background:g.color+"16", padding:"2px 6px", borderRadius:999 }}>T{it.tier}</span>
                        </div>
                        {it.desc && <div className="dim" style={{ fontSize:11.7, marginTop:2 }}>{it.desc}</div>}
                      </div>
                      <FeatureToggle on={isOn} color={g.color} onClick={()=>setFeature(it.id, !isOn)}/>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
      {!groups.length && <div className="dim" style={{ textAlign:"center", padding:"40px 0" }}>No features match “{query}”.</div>}
      {sheet}
    </div>
  );
}

Object.assign(window, { FeatureSettings });
