// Recursive MLS — Admin screen: Knowledgebase manager.
// MLS staff add videos / PDFs / articles, organize them in nested folders
// (e.g. Product lines › Listings › Add / Edit), and author long-form articles in a
// CMS editor. LMS-ready & SCORM-compliant: quizzes, video watch-verification, and
// SCORM 1.2 / 2004 + xAPI import/export.
const { useState: _uK } = React;

// Nested folder taxonomy (folders contain folders or content)
const KB_TREE = [
  { id: "onboarding", label: "Onboarding", icon: "rocket", children: [
    { id: "getting-started", label: "Getting started", icon: "play" },
    { id: "account-setup", label: "Account setup", icon: "user-cog" },
  ] },
  { id: "product", label: "Product lines", icon: "box", children: [
    { id: "listings", label: "Listings", icon: "home", children: [
      { id: "addedit", label: "Add / Edit", icon: "list-plus" },
      { id: "mylistings", label: "My listings", icon: "folder" },
    ] },
    { id: "cma", label: "CMA & Pricing", icon: "calculator" },
    { id: "showings", label: "Showings", icon: "calendar-clock" },
    { id: "marketing", label: "Marketing kit", icon: "megaphone" },
    { id: "search", label: "Find homes & maps", icon: "search" },
  ] },
  { id: "compliance", label: "Compliance", icon: "scale", children: [
    { id: "rules", label: "Rules & regulations", icon: "gavel" },
    { id: "fairhousing", label: "Fair Housing", icon: "shield-check" },
  ] },
  { id: "platform", label: "Platform", icon: "database", children: [
    { id: "data", label: "Data & integrations", icon: "plug" },
  ] },
];

function AdminKnowledge() {
  const KB = window.RC_KB;
  const [view, setView] = _uK("library");           // library | editor
  const [sel, setSel] = _uK("addedit");             // selected folder id
  const [expanded, setExpanded] = _uK({ product: true, listings: true, compliance: true });
  const [adding, setAdding] = _uK(false);
  const [newType, setNewType] = _uK("video");
  const [folderModal, setFolderModal] = _uK(false);
  const [scormModal, setScormModal] = _uK(false);
  const [passkey, setPasskey] = _uK(false);
  const [quiz, setQuiz] = _uK(false);

  // map a folder id to its article section bucket (reuse kb.js sections)
  const sectionFor = { "getting-started": "getting-started", addedit: "listings", mylistings: "listings", cma: "cma", showings: "showings", marketing: "marketing", search: "search", rules: "rules", fairhousing: "fairhousing", data: "data" };
  const list = KB.articles.filter((a) => a.section === (sectionFor[sel] || sel));

  // breadcrumb path
  function findPath(nodes, id, trail) {
    for (const n of nodes) {
      const t = [...trail, n];
      if (n.id === id) return t;
      if (n.children) { const r = findPath(n.children, id, t); if (r) return r; }
    }
    return null;
  }
  const path = findPath(KB_TREE, sel, []) || [];

  const typeBadge = (t) => {
    const m = KB.typeMeta[t]; const tones = { video: ["#faece3", "#c0612f"], pdf: ["#eef4f1", "#006747"], article: ["#eef1f6", "#16243A"] };
    const [bg, fg] = tones[t]; return <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 10.5, fontWeight: 600, color: fg, background: bg, borderRadius: 4, padding: "3px 7px" }}><Icon name={m.icon} size={12} color={fg} /> {m.label}</span>;
  };

  // ---- recursive folder tree row ----
  const Tree = ({ nodes, depth }) => nodes.map((n) => {
    const hasKids = n.children && n.children.length;
    const isOpen = expanded[n.id];
    const active = sel === n.id;
    return (
      <div key={n.id}>
        <div className="rc-nav-item" onClick={() => { setSel(n.id); if (hasKids) setExpanded({ ...expanded, [n.id]: !isOpen }); }}
          style={{ display: "flex", alignItems: "center", gap: 7, padding: "7px 8px", paddingLeft: 8 + depth * 15, borderRadius: 7, cursor: "pointer", fontSize: 13, background: active ? "#eef4f1" : "transparent", color: active ? "#006747" : "#4a504a", fontWeight: active ? 600 : 400 }}>
          {hasKids ? <Icon name={isOpen ? "chevron-down" : "chevron-right"} size={13} color="#a8aca6" /> : <span style={{ width: 13, flex: "none" }} />}
          <Icon name={hasKids ? (isOpen ? "folder-open" : "folder") : n.icon} size={15} color={active ? "#006747" : "#8a8e88"} />
          <span style={{ flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{n.label}</span>
        </div>
        {hasKids && isOpen && <Tree nodes={n.children} depth={depth + 1} />}
      </div>
    );
  });

  if (view === "editor") return <ArticleEditor onBack={() => setView("library")} folderPath={path} onQuiz={() => setQuiz(true)} onPasskey={() => setPasskey(true)} />;

  return (
    <div style={{ height: "100%", overflowY: "auto", background: "#f4f3ef" }}>
      <div style={{ maxWidth: 1240, margin: "0 auto", padding: "26px 28px 64px" }}>

        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 18, flexWrap: "wrap", marginBottom: 20 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "1.5px", textTransform: "uppercase", color: "#8a8e88", marginBottom: 6 }}>Administrator · Knowledgebase</div>
            <h1 style={{ margin: 0, fontSize: 25, fontWeight: 600, letterSpacing: "-0.6px" }}>Content manager</h1>
            <p style={{ margin: "5px 0 0", fontSize: 14, color: "#8a8e88" }}>Author, organize in folders, and ship SCORM-compliant training.</p>
          </div>
          <div style={{ display: "flex", gap: 9 }}>
            <button onClick={() => setScormModal(true)} style={btnGhostS}><Icon name="package" size={15} color="#006747" /> Import SCORM</button>
            <button onClick={() => setAdding(true)} style={btnPrimaryS}><Icon name="plus" size={16} color="#fff" /> Add content</button>
          </div>
        </div>

        {/* KPIs */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14, marginBottom: 22 }}>
          {[["Published items", KB.articles.length, "library"], ["Quizzes", "7", "list-checks"], ["SCORM packages", "12", "package"], ["Completions (30d)", "2,840", "graduation-cap"]].map(([k, v, ic]) => (
            <div key={k} style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "15px 16px", display: "flex", alignItems: "center", gap: 12 }}>
              <span style={{ width: 38, height: 38, borderRadius: 8, background: "#eef4f1", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={ic} size={18} color="#006747" /></span>
              <div><div style={{ fontFamily: "'Space Mono',monospace", fontSize: 21, fontWeight: 700, color: "#1d241f" }}>{v}</div><div style={{ fontSize: 11, color: "#a8aca6", textTransform: "uppercase", letterSpacing: ".5px" }}>{k}</div></div>
            </div>
          ))}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "256px 1fr", gap: 22, alignItems: "start" }}>
          {/* folder tree */}
          <div style={{ position: "sticky", top: 0, background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "12px 10px" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 6px 10px" }}>
              <span style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#a8aca6" }}>Folders</span>
              <button onClick={() => setFolderModal(true)} title="New folder or section" style={{ border: 0, background: "none", cursor: "pointer", display: "flex", alignItems: "center", gap: 3, color: "#006747", fontSize: 11.5, fontWeight: 600, fontFamily: "inherit" }}><Icon name="folder-plus" size={14} color="#006747" /> New</button>
            </div>
            <Tree nodes={KB_TREE} depth={0} />
          </div>

          {/* content area */}
          <div>
            {/* breadcrumb */}
            <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 14, flexWrap: "wrap" }}>
              <span style={{ fontSize: 12.5, color: "#a8aca6" }}>Knowledgebase</span>
              {path.map((p, i) => (
                <React.Fragment key={p.id}>
                  <Icon name="chevron-right" size={13} color="#c4c2b8" />
                  <span onClick={() => setSel(p.id)} style={{ fontSize: 12.5, fontWeight: i === path.length - 1 ? 600 : 400, color: i === path.length - 1 ? "#1d241f" : "#8a8e88", cursor: "pointer" }}>{p.label}</span>
                </React.Fragment>
              ))}
            </div>

            <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", overflow: "hidden" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 16px", borderBottom: "1px solid #f0efe9" }}>
                <Icon name="folder-open" size={16} color="#006747" />
                <span style={{ fontSize: 14, fontWeight: 600 }}>{(path[path.length - 1] || {}).label}</span>
                <span style={{ fontSize: 12, color: "#a8aca6" }}>· {list.length} items</span>
                <div style={{ flex: 1 }} />
                <button onClick={() => setFolderModal(true)} style={{ ...miniBtn }}><Icon name="folder-plus" size={13} color="#6b706a" /> Subfolder</button>
                <button onClick={() => { setNewType("article"); setView("editor"); }} style={{ ...miniBtn }}><Icon name="pen-line" size={13} color="#6b706a" /> New article</button>
              </div>
              {list.length === 0 && <div style={{ padding: 32, textAlign: "center", color: "#a8aca6", fontSize: 13 }}>This folder is empty. Add content or a subfolder.</div>}
              {list.map((a, i) => (
                <div key={a.id} onClick={() => a.type === "article" && setView("editor")} className="rc-row" style={{ display: "grid", gridTemplateColumns: "1fr 120px 90px 130px 80px", gap: 12, padding: "13px 16px", borderBottom: i < list.length - 1 ? "1px solid #f4f3ee" : "none", alignItems: "center", cursor: "pointer" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
                    <Icon name={KB.typeMeta[a.type].icon} size={16} color="#8a8e88" />
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.title}</div>
                      <div style={{ fontSize: 11, color: "#a8aca6", marginTop: 2 }}>Updated {a.updated}</div>
                    </div>
                  </div>
                  <div>{typeBadge(a.type)}</div>
                  <div style={{ fontFamily: "'Space Mono',monospace", fontSize: 12, color: "#8a8e88", textAlign: "right" }}>{a.views.toLocaleString()}</div>
                  <div style={{ display: "flex", gap: 5 }}>
                    {a.lms && a.lms.required && <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".4px", color: "#006747", background: "#e8f4ee", borderRadius: 3, padding: "2px 5px" }}>REQ</span>}
                    {a.lms && a.lms.ce && <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".4px", color: "#16243A", background: "#eef1f6", borderRadius: 3, padding: "2px 5px" }}>CE</span>}
                    <span title="SCORM compliant" style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".4px", color: "#6b706a", background: "#f0efe9", borderRadius: 3, padding: "2px 5px" }}>SCORM</span>
                  </div>
                  <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", color: "#a8aca6" }}>
                    <Icon name="pencil" size={15} color="#a8aca6" /><Icon name="download" size={15} color="#a8aca6" />
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {adding && <AddContent type={newType} setType={setNewType} onClose={() => setAdding(false)} onArticle={() => { setAdding(false); setView("editor"); }} onQuiz={() => { setAdding(false); setQuiz(true); }} onPasskey={() => setPasskey(true)} />}
      {folderModal && <FolderModal onClose={() => setFolderModal(false)} />}
      {scormModal && <ScormImport onClose={() => setScormModal(false)} />}
      {quiz && <QuizBuilder onClose={() => setQuiz(false)} />}
      {passkey && <PasskeyPreview onClose={() => setPasskey(false)} />}
    </div>
  );
}

// ============ CMS ARTICLE EDITOR ============
function ArticleEditor({ onBack, folderPath }) {
  const [quiz, setQuiz] = _uK(false);
  const [passkey, setPasskey] = _uK(false);
  const onQuiz = () => setQuiz(true);
  const onPasskey = () => setPasskey(true);
  const tools = [
    [["undo-2"], ["redo-2"]],
    [["heading-1"], ["heading-2"], ["heading-3"], ["pilcrow"]],
    [["bold"], ["italic"], ["underline"], ["strikethrough"]],
    [["list"], ["list-ordered"], ["list-checks"], ["quote"]],
    [["link"], ["image"], ["video"], ["table"], ["code"]],
    [["align-left"], ["align-center"], ["align-justify"]],
  ];
  return (
    <div style={{ height: "100%", display: "grid", gridTemplateRows: "auto 1fr", background: "#f4f3ef", overflow: "hidden" }}>
      {/* editor toolbar */}
      <div style={{ background: "#fff", borderBottom: "1px solid #ececec", padding: "12px 22px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <button onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", fontSize: 13, fontWeight: 600, color: "#006747", background: "none", border: 0, cursor: "pointer" }}><Icon name="arrow-left" size={16} color="#006747" /> Content manager</button>
          <div style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 12, color: "#a8aca6" }}>
            {folderPath.map((p) => <React.Fragment key={p.id}><Icon name="chevron-right" size={12} color="#c4c2b8" /><span>{p.label}</span></React.Fragment>)}
          </div>
          <div style={{ flex: 1 }} />
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11.5, color: "#1f8a5b" }}><span style={{ width: 7, height: 7, borderRadius: "50%", background: "#1f8a5b" }} /> Draft saved</span>
          <button style={btnGhostS}><Icon name="eye" size={15} color="#006747" /> Preview</button>
          <button style={btnPrimaryS}><Icon name="check" size={15} color="#fff" /> Publish</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 300px", overflow: "hidden" }}>
        {/* canvas */}
        <div style={{ overflowY: "auto", display: "flex", justifyContent: "center", padding: "0 0 60px" }}>
          <div style={{ width: 760, maxWidth: "100%" }}>
            {/* formatting toolbar */}
            <div style={{ position: "sticky", top: 0, zIndex: 5, background: "#fbfaf7", borderBottom: "1px solid #ececec", display: "flex", flexWrap: "wrap", gap: 4, padding: "10px 16px", margin: "0 -0px" }}>
              <select style={{ border: "1px solid #e2e0d8", borderRadius: 6, padding: "5px 8px", fontFamily: "inherit", fontSize: 12.5, color: "#4a504a", background: "#fff", marginRight: 4 }}>
                <option>Paragraph</option><option>Heading 1</option><option>Heading 2</option><option>Heading 3</option><option>Quote</option>
              </select>
              {tools.map((grp, gi) => (
                <div key={gi} style={{ display: "flex", gap: 2, paddingRight: 6, marginRight: 2, borderRight: gi < tools.length - 1 ? "1px solid #e7e5df" : "none" }}>
                  {grp.map(([ic]) => <button key={ic} style={tbtn}><Icon name={ic} size={15} color="#4a504a" /></button>)}
                </div>
              ))}
            </div>
            {/* document */}
            <div style={{ background: "#fff", minHeight: 600, boxShadow: "0 1px 3px rgba(0,0,0,.06)", margin: "20px 0", padding: "40px 56px" }}>
              <input defaultValue="How to publish a clean listing" style={{ width: "100%", border: 0, outline: 0, fontFamily: "inherit", fontSize: 30, fontWeight: 600, letterSpacing: "-0.8px", color: "#1d241f", marginBottom: 6 }} />
              <input defaultValue="A step-by-step guide to clearing compliance before you go live." style={{ width: "100%", border: 0, outline: 0, fontFamily: "inherit", fontSize: 15, color: "#8a8e88", marginBottom: 24 }} />
              <h2 style={{ fontSize: 20, fontWeight: 600, color: "#1d241f", margin: "0 0 10px" }}>Before you start</h2>
              <p style={{ fontSize: 15, lineHeight: 1.7, color: "#4a504a", margin: "0 0 16px" }}>Every listing runs through the live compliance engine as you type. This guide walks through the four checks that block publishing, and how to clear each one.</p>
              <div style={{ borderLeft: "3px solid #006747", background: "#f6f5f1", padding: "12px 16px", borderRadius: "0 6px 6px 0", margin: "0 0 18px" }}>
                <div style={{ fontSize: 13.5, color: "#4a504a", lineHeight: 1.6 }}><strong style={{ fontWeight: 600 }}>Tip:</strong> Verify square footage against county records first — it's the most common blocker.</div>
              </div>
              <h2 style={{ fontSize: 20, fontWeight: 600, color: "#1d241f", margin: "0 0 10px" }}>The four checks</h2>
              <ol style={{ fontSize: 15, lineHeight: 1.8, color: "#4a504a", paddingLeft: 22, margin: "0 0 18px" }}>
                <li>Fair Housing language scan</li><li>No access codes in public remarks</li><li>Square-footage verification</li><li>Required media &amp; brokerage data</li>
              </ol>
              <div style={{ height: 200, borderRadius: 6, background: "center/cover url(https://images.unsplash.com/photo-1564013799919-ab600027ffc6?auto=format&fit=crop&w=900&q=70)", position: "relative", display: "flex", alignItems: "flex-end", margin: "0 0 8px" }}>
                <span style={{ fontSize: 11, color: "#fff", background: "rgba(0,0,0,.55)", borderRadius: 4, padding: "3px 8px", margin: 10 }}>Figure 1 — the compliance panel</span>
              </div>
              <p style={{ fontSize: 12.5, color: "#bcbfba", margin: 0, textAlign: "center" }}>Drag to reorder blocks · / for commands · type to continue…</p>
            </div>
          </div>
        </div>

        {/* settings rail */}
        <div style={{ borderLeft: "1px solid #ececec", background: "#fff", overflowY: "auto" }}>
          <ESect title="Placement">
            <label style={elbl}>Folder</label>
            <select style={einp}><option>Product lines › Listings › Add / Edit</option><option>Product lines › CMA &amp; Pricing</option><option>Compliance › Rules &amp; regulations</option></select>
            <label style={{ ...elbl, marginTop: 12 }}>Tags</label>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>{["listings", "compliance", "publish"].map((t) => <span key={t} style={{ fontSize: 11.5, color: "#4a504a", background: "#f0efe9", borderRadius: 4, padding: "3px 8px" }}>{t}</span>)}</div>
          </ESect>

          <ESect title="Learning (LMS)">
            <Toggle label="Required for new agents" on />
            <Toggle label="CE-eligible" on />
            <label style={{ ...elbl, marginTop: 12 }}>Course / module</label>
            <input defaultValue="Listing mastery" style={einp} />
            <input defaultValue="Creating listings" style={{ ...einp, marginTop: 6 }} />
            <button onClick={onQuiz} style={{ ...railBtn, marginTop: 12 }}><Icon name="list-checks" size={15} color="#006747" /> Attach a quiz</button>
            <button onClick={onPasskey} style={{ ...railBtn, marginTop: 8 }}><Icon name="scan-face" size={15} color="#006747" /> Watch-verification</button>
          </ESect>

          <ESect title="SCORM / xAPI" last>
            <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: "#1f8a5b", marginBottom: 10 }}><Icon name="badge-check" size={15} color="#1f8a5b" /> SCORM 2004 compliant</div>
            <label style={elbl}>Export format</label>
            <select style={einp}><option>SCORM 2004 (4th ed.)</option><option>SCORM 1.2</option><option>xAPI (Tin Can)</option><option>cmi5</option></select>
            <button style={{ ...railBtn, marginTop: 10 }}><Icon name="download" size={15} color="#006747" /> Export package</button>
            <div style={{ fontSize: 11, color: "#a8aca6", marginTop: 8, lineHeight: 1.45 }}>Tracks completion, score, and time on task via the LMS runtime.</div>
          </ESect>
        </div>
      </div>
      {quiz && <QuizBuilder onClose={() => setQuiz(false)} />}
      {passkey && <PasskeyPreview onClose={() => setPasskey(false)} />}
    </div>
  );
}

// ============ ADD CONTENT SLIDE-OVER ============
function AddContent({ type, setType, onClose, onArticle, onQuiz, onPasskey }) {
  return (
    <div onClick={onClose} style={overlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 460, height: "100%", background: "#fff", boxShadow: "-8px 0 40px rgba(0,0,0,.2)", display: "flex", flexDirection: "column" }}>
        <div style={modalHead}><Icon name="plus-circle" size={18} color="#006747" /><span style={{ fontSize: 15, fontWeight: 600, flex: 1 }}>Add content</span><button onClick={onClose} style={xBtn}><Icon name="x" size={20} color="#8a8e88" /></button></div>
        <div style={{ overflowY: "auto", padding: 20, flex: 1 }}>
          <label style={elbl}>Content type</label>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 8, marginBottom: 18 }}>
            {[["video", "Video", "play-circle"], ["pdf", "PDF", "file-text"], ["article", "Article", "book-open"], ["quiz", "Quiz", "list-checks"]].map(([v, label, ic]) => (
              <button key={v} onClick={() => setType(v)} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 7, padding: "13px 6px", border: "1px solid", borderColor: type === v ? "#006747" : "#e2e0d8", background: type === v ? "#eef4f1" : "#fff", borderRadius: 8, cursor: "pointer", fontFamily: "inherit", fontSize: 11.5, fontWeight: 600, color: type === v ? "#006747" : "#6b706a" }}>
                <Icon name={ic} size={19} color={type === v ? "#006747" : "#8a8e88"} /> {label}
              </button>
            ))}
          </div>

          {type === "article" ? (
            <div style={{ background: "#eef4f1", border: "1px solid #d6e7de", borderRadius: 9, padding: 16, textAlign: "center" }}>
              <Icon name="pen-line" size={26} color="#006747" />
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", marginTop: 8 }}>Long-form article</div>
              <div style={{ fontSize: 12, color: "#4a6157", margin: "5px 0 12px", lineHeight: 1.5 }}>Write rich content with the full CMS editor — headings, images, callouts, tables &amp; embeds.</div>
              <button onClick={onArticle} style={{ ...btnPrimaryS, width: "100%", justifyContent: "center" }}><Icon name="arrow-right" size={15} color="#fff" /> Open editor</button>
            </div>
          ) : type === "quiz" ? (
            <div style={{ background: "#eef4f1", border: "1px solid #d6e7de", borderRadius: 9, padding: 16, textAlign: "center" }}>
              <Icon name="list-checks" size={26} color="#006747" />
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", marginTop: 8 }}>Knowledge check</div>
              <div style={{ fontSize: 12, color: "#4a6157", margin: "5px 0 12px", lineHeight: 1.5 }}>Build a graded quiz with a passing score — results report to the LMS via SCORM.</div>
              <button onClick={onQuiz} style={{ ...btnPrimaryS, width: "100%", justifyContent: "center" }}><Icon name="arrow-right" size={15} color="#fff" /> Build quiz</button>
            </div>
          ) : (
            <React.Fragment>
              <label style={elbl}>{type === "video" ? "Video file or URL" : "PDF file"}</label>
              <div style={{ border: "1.5px dashed #d9d7cd", borderRadius: 8, padding: "22px 16px", display: "flex", flexDirection: "column", alignItems: "center", gap: 8, color: "#8a8e88", fontSize: 12.5, textAlign: "center", marginBottom: 16 }}>
                <Icon name={type === "video" ? "upload-cloud" : "file-up"} size={26} color="#c4c2b8" />
                Drop a file here, or click to upload
                {type === "video" && <span style={{ fontSize: 11, color: "#bcbfba" }}>MP4 up to 2 GB · or paste a hosted URL</span>}
              </div>
              <label style={elbl}>Title</label>
              <input placeholder="e.g. How to publish a clean listing" style={einp} />
              <label style={{ ...elbl, marginTop: 14 }}>Folder</label>
              <select style={einp}><option>Product lines › Listings › Add / Edit</option><option>Product lines › CMA &amp; Pricing</option><option>Compliance › Rules &amp; regulations</option></select>
              {type === "video" && (
                <div style={{ marginTop: 16, background: "#f6f5f1", borderRadius: 8, padding: 14 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: "#1d241f", marginBottom: 10 }}>Video LMS settings</div>
                  <Toggle label="Disable skip-ahead" on />
                  <Toggle label="Require watch-verification" on />
                  <button onClick={onPasskey} style={{ ...railBtn, marginTop: 10 }}><Icon name="scan-face" size={14} color="#006747" /> Preview re-auth prompt</button>
                </div>
              )}
            </React.Fragment>
          )}
        </div>
        <div style={modalFoot}><button onClick={onClose} style={btnGhostS}>Cancel</button><button onClick={onClose} style={btnPrimaryS}><Icon name="check" size={15} color="#fff" /> Save</button></div>
      </div>
    </div>
  );
}

// ============ FOLDER / SECTION MODAL ============
function FolderModal({ onClose }) {
  return (
    <div onClick={onClose} style={centerOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 440, background: "#fff", borderRadius: 4, boxShadow: "0 18px 60px rgba(0,0,0,.3)", overflow: "hidden" }}>
        <div style={modalHead}><Icon name="folder-plus" size={18} color="#006747" /><span style={{ fontSize: 15, fontWeight: 600, flex: 1 }}>New folder / section</span><button onClick={onClose} style={xBtn}><Icon name="x" size={20} color="#8a8e88" /></button></div>
        <div style={{ padding: 20 }}>
          <label style={elbl}>Name</label>
          <input placeholder="e.g. Open houses" style={einp} autoFocus />
          <label style={{ ...elbl, marginTop: 14 }}>Nest inside</label>
          <select style={einp}><option>— Top level (new section)</option><option>Product lines</option><option>Product lines › Listings</option><option>Compliance</option><option>Platform</option></select>
          <label style={{ ...elbl, marginTop: 14 }}>Icon</label>
          <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>{["folder", "home", "calculator", "megaphone", "scale", "shield-check", "database", "rocket"].map((ic, i) => (
            <span key={ic} style={{ width: 36, height: 36, borderRadius: 8, border: i === 0 ? "1.5px solid #006747" : "1px solid #e2e0d8", background: i === 0 ? "#eef4f1" : "#fff", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Icon name={ic} size={16} color={i === 0 ? "#006747" : "#8a8e88"} /></span>
          ))}</div>
          <div style={{ fontSize: 11.5, color: "#a8aca6", marginTop: 14, lineHeight: 1.45 }}>Folders nest to any depth, so agents can click through Product lines › Listings › Add / Edit to find content.</div>
        </div>
        <div style={modalFoot}><button onClick={onClose} style={btnGhostS}>Cancel</button><button onClick={onClose} style={btnPrimaryS}><Icon name="check" size={15} color="#fff" /> Create</button></div>
      </div>
    </div>
  );
}

// ============ SCORM IMPORT ============
function ScormImport({ onClose }) {
  return (
    <div onClick={onClose} style={centerOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 480, background: "#fff", borderRadius: 4, boxShadow: "0 18px 60px rgba(0,0,0,.3)", overflow: "hidden" }}>
        <div style={modalHead}><Icon name="package" size={18} color="#006747" /><span style={{ fontSize: 15, fontWeight: 600, flex: 1 }}>Import SCORM package</span><button onClick={onClose} style={xBtn}><Icon name="x" size={20} color="#8a8e88" /></button></div>
        <div style={{ padding: 20 }}>
          <div style={{ border: "1.5px dashed #d9d7cd", borderRadius: 10, padding: "30px 16px", display: "flex", flexDirection: "column", alignItems: "center", gap: 9, color: "#8a8e88", fontSize: 13, textAlign: "center" }}>
            <Icon name="upload-cloud" size={30} color="#c4c2b8" />
            Drop a SCORM .zip here, or click to upload
            <span style={{ fontSize: 11, color: "#bcbfba" }}>SCORM 1.2 · SCORM 2004 · xAPI · cmi5 — up to 500 MB</span>
          </div>
          <div style={{ marginTop: 14, background: "#f6f5f1", borderRadius: 8, padding: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <span style={{ width: 34, height: 34, borderRadius: 7, background: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="file-archive" size={16} color="#006747" /></span>
              <div style={{ flex: 1 }}><div style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f" }}>fair-housing-2026.zip</div><div style={{ fontSize: 11, color: "#a8aca6" }}>SCORM 2004 · 18.4 MB · manifest valid</div></div>
              <Icon name="check-circle" size={17} color="#1f8a5b" />
            </div>
          </div>
          <label style={{ ...elbl, marginTop: 14 }}>Import into folder</label>
          <select style={einp}><option>Compliance › Fair Housing</option><option>Product lines › Listings</option></select>
        </div>
        <div style={modalFoot}><button onClick={onClose} style={btnGhostS}>Cancel</button><button onClick={onClose} style={btnPrimaryS}><Icon name="download" size={15} color="#fff" /> Import</button></div>
      </div>
    </div>
  );
}

// ============ QUIZ BUILDER ============
function QuizBuilder({ onClose }) {
  const q = [
    { q: "Before publishing, square footage must be…", a: ["Left blank if unknown", "Verified against public records or certified", "Estimated by the agent"], correct: 1 },
    { q: "Which of these may NOT appear in public remarks?", a: ["Lockbox / access codes", "Number of bedrooms", "School district"], correct: 0 },
  ];
  return (
    <div onClick={onClose} style={centerOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 600, maxHeight: "86%", background: "#fff", borderRadius: 4, boxShadow: "0 18px 60px rgba(0,0,0,.3)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <div style={modalHead}><Icon name="list-checks" size={18} color="#006747" /><span style={{ fontSize: 15, fontWeight: 600, flex: 1 }}>Quiz builder</span><span style={{ fontSize: 11, fontWeight: 600, color: "#6b706a", background: "#f0efe9", borderRadius: 4, padding: "3px 8px" }}>SCORM-scored</span><button onClick={onClose} style={xBtn}><Icon name="x" size={20} color="#8a8e88" /></button></div>
        <div style={{ overflowY: "auto", padding: 20, flex: 1 }}>
          <div style={{ display: "flex", gap: 14, marginBottom: 18 }}>
            <div style={{ flex: 1 }}><label style={elbl}>Quiz title</label><input defaultValue="Publishing a clean listing — check" style={einp} /></div>
            <div style={{ width: 110 }}><label style={elbl}>Pass score</label><input defaultValue="80%" style={einp} /></div>
          </div>
          {q.map((item, qi) => (
            <div key={qi} style={{ border: "1px solid #ececec", borderRadius: 9, padding: 14, marginBottom: 12 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
                <span style={{ fontFamily: "'Space Mono',monospace", fontSize: 12, fontWeight: 700, color: "#006747" }}>Q{qi + 1}</span>
                <input defaultValue={item.q} style={{ flex: 1, border: 0, outline: 0, fontFamily: "inherit", fontSize: 13.5, fontWeight: 600, color: "#1d241f" }} />
                <Icon name="trash-2" size={15} color="#bcbfba" />
              </div>
              {item.a.map((opt, oi) => (
                <div key={oi} style={{ display: "flex", alignItems: "center", gap: 9, padding: "7px 10px", borderRadius: 7, background: oi === item.correct ? "#eef4f1" : "transparent", marginBottom: 4 }}>
                  <span style={{ width: 16, height: 16, borderRadius: "50%", border: oi === item.correct ? "none" : "1.5px solid #cdcdc4", background: oi === item.correct ? "#006747" : "transparent", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>{oi === item.correct && <Icon name="check" size={11} color="#fff" />}</span>
                  <span style={{ fontSize: 13, color: oi === item.correct ? "#1d241f" : "#4a504a" }}>{opt}</span>
                  {oi === item.correct && <span style={{ fontSize: 10, fontWeight: 700, color: "#006747", marginLeft: "auto" }}>CORRECT</span>}
                </div>
              ))}
              <button style={{ ...miniBtn, marginTop: 6 }}><Icon name="plus" size={13} color="#6b706a" /> Add option</button>
            </div>
          ))}
          <button style={{ ...railBtn, width: "auto" }}><Icon name="plus" size={15} color="#006747" /> Add question</button>
        </div>
        <div style={modalFoot}><span style={{ fontSize: 11.5, color: "#a8aca6", marginRight: "auto" }}>Results report to the LMS via SCORM/xAPI</span><button onClick={onClose} style={btnGhostS}>Cancel</button><button onClick={onClose} style={btnPrimaryS}><Icon name="check" size={15} color="#fff" /> Save quiz</button></div>
      </div>
    </div>
  );
}

// ============ PASSKEY / WATCH-VERIFICATION PREVIEW ============
function PasskeyPreview({ onClose }) {
  return (
    <div onClick={onClose} style={centerOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 540, background: "#fff", borderRadius: 4, boxShadow: "0 18px 60px rgba(0,0,0,.3)", overflow: "hidden" }}>
        <div style={modalHead}><Icon name="scan-face" size={18} color="#006747" /><span style={{ fontSize: 15, fontWeight: 600, flex: 1 }}>Watch-verification</span><button onClick={onClose} style={xBtn}><Icon name="x" size={20} color="#8a8e88" /></button></div>
        <div style={{ padding: 20 }}>
          <p style={{ margin: "0 0 16px", fontSize: 13, color: "#4a504a", lineHeight: 1.55 }}>For CE-eligible videos, agents must periodically confirm they're present. Configure how and how often — completion only counts when every checkpoint passes.</p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 18 }}>
            <div><label style={elbl}>Re-auth every</label><select style={einp}><option>5 minutes</option><option>10 minutes</option><option>Random intervals</option></select></div>
            <div><label style={elbl}>Method</label><select style={einp}><option>Passkey / biometric</option><option>PIN</option><option>Attention prompt</option></select></div>
          </div>

          {/* live preview of the agent-facing prompt */}
          <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#a8aca6", marginBottom: 8 }}>Agent sees</div>
          <div style={{ borderRadius: 12, overflow: "hidden", position: "relative", background: "#1c1c1c", height: 230, display: "flex", alignItems: "center", justifyContent: "center" }}>
            <div style={{ position: "absolute", inset: 0, background: "center/cover url(https://images.unsplash.com/photo-1521791136064-7986c2920216?auto=format&fit=crop&w=900&q=60)", opacity: .25 }} />
            <div style={{ position: "relative", width: 300, background: "#fff", borderRadius: 12, padding: "22px 22px 20px", textAlign: "center", boxShadow: "0 12px 40px rgba(0,0,0,.4)" }}>
              <span style={{ width: 48, height: 48, borderRadius: "50%", background: "#eef4f1", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 10 }}><Icon name="fingerprint" size={24} color="#006747" /></span>
              <div style={{ fontSize: 15, fontWeight: 600, color: "#1d241f" }}>Still watching?</div>
              <div style={{ fontSize: 12, color: "#8a8e88", margin: "5px 0 16px", lineHeight: 1.5 }}>Confirm your identity to keep earning CE credit for this video.</div>
              <button style={{ width: "100%", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8, fontFamily: "inherit", fontSize: 13, fontWeight: 600, color: "#fff", background: "#006747", border: 0, borderRadius: 8, padding: "11px", cursor: "pointer" }}><Icon name="fingerprint" size={16} color="#fff" /> Verify with passkey</button>
              <div style={{ fontSize: 10.5, color: "#bcbfba", marginTop: 9 }}>Video paused · resumes after you verify</div>
            </div>
          </div>
        </div>
        <div style={modalFoot}><button onClick={onClose} style={btnGhostS}>Cancel</button><button onClick={onClose} style={btnPrimaryS}><Icon name="check" size={15} color="#fff" /> Save settings</button></div>
      </div>
    </div>
  );
}

// ---- shared atoms ----
function ESect({ title, children, last }) { return <div style={{ padding: "16px 18px", borderBottom: last ? "none" : "1px solid #f0efe9" }}><div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#a8aca6", marginBottom: 12 }}>{title}</div>{children}</div>; }
function Toggle({ label, on }) {
  const [v, setV] = _uK(!!on);
  return (
    <div onClick={() => setV(!v)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 0", cursor: "pointer" }}>
      <div style={{ width: 36, height: 20, borderRadius: 999, flex: "none", background: v ? "#006747" : "#d8d6cd", position: "relative", transition: "background .15s" }}><span style={{ position: "absolute", top: 2, left: v ? 18 : 2, width: 16, height: 16, borderRadius: "50%", background: "#fff", transition: "left .15s" }} /></div>
      <span style={{ fontSize: 13, color: "#4a504a" }}>{label}</span>
    </div>
  );
}
const tbtn = { width: 30, height: 30, border: 0, background: "transparent", borderRadius: 6, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" };
const elbl = { display: "block", fontSize: 10.5, fontWeight: 600, letterSpacing: ".5px", textTransform: "uppercase", color: "#a8aca6", marginBottom: 7 };
const einp = { width: "100%", boxSizing: "border-box", border: "1px solid #e2e0d8", borderRadius: 8, padding: "9px 11px", fontFamily: "inherit", fontSize: 13, color: "#1d241f", outline: 0, appearance: "auto" };
const railBtn = { width: "100%", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#006747", background: "#eef4f1", border: "1px solid #d6e7de", borderRadius: 8, padding: "9px", cursor: "pointer" };
const miniBtn = { display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "inherit", fontSize: 11.5, fontWeight: 600, color: "#6b706a", background: "#f6f5f1", border: "1px solid #e7e5df", borderRadius: 6, padding: "5px 9px", cursor: "pointer" };
const overlay = { position: "absolute", inset: 0, background: "rgba(20,28,22,.5)", display: "flex", justifyContent: "flex-end", zIndex: 40 };
const centerOverlay = { position: "absolute", inset: 0, background: "rgba(20,28,22,.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 40, padding: 30 };
const modalHead = { display: "flex", alignItems: "center", gap: 10, padding: "16px 20px", borderBottom: "1px solid #ececec" };
const modalFoot = { borderTop: "1px solid #ececec", padding: "14px 20px", display: "flex", gap: 10, alignItems: "center", justifyContent: "flex-end" };
const xBtn = { border: 0, background: "none", cursor: "pointer", display: "flex" };
const lbl = elbl;
const inp = einp;
const btnPrimaryS = { display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 13, fontWeight: 600, color: "#fff", background: "#006747", border: 0, borderRadius: 8, padding: "10px 16px", cursor: "pointer" };
const btnGhostS = { display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#006747", background: "#fff", border: "1px solid #d7ddd9", borderRadius: 8, padding: "9px 14px", cursor: "pointer" };

window.AdminKnowledge = AdminKnowledge;
