// Documentation / Wiki screen — keyword search + article + TOC

function Documentation({ user, perms }) {
  const [articleId, setArticleId] = useState("gs-overview");
  const [query, setQuery] = useState("");
  const [category, setCategory] = useState(null); // null = all

  // Search
  const q = query.trim().toLowerCase();
  const searchResults = q ? DOC_INDEX.filter(a => a.searchText.includes(q)).slice(0, 20) : null;

  const article = DOC_ARTICLES.find(a => a.id === articleId) || DOC_ARTICLES[0];

  return (
    <div>
      <PageHeader
        title="Documentation"
        sub="User guide, workflows, FAQ and release notes · last updated 2025-05-13"
        right={
          <>
            <button className="btn"><Icon name="print" size={14} /> Print article</button>
            <button className="btn"><Icon name="download" size={14} /> Export to PDF</button>
          </>
        }
      />

      {/* Hero search */}
      <div className="card" style={{ padding: "18px 22px", marginBottom: 18, background: "linear-gradient(135deg, #f3f8fa, #e7f3f6)", border: "1px solid #c8e3ea" }}>
        <div className="row gap-12" style={{ alignItems: "center" }}>
          <Icon name="book" size={24} stroke="var(--teal)" />
          <div style={{ flex: 1 }}>
            <div className="serif" style={{ fontSize: 18, fontWeight: 500, marginBottom: 2 }}>TCMS Knowledge Base</div>
            <div className="tiny muted">{DOC_ARTICLES.length} articles · {DOC_CATEGORIES.length} categories · keyword indexed</div>
          </div>
          <div className="search" style={{ flex: "0 0 360px" }}>
            <Icon name="search" size={14} />
            <input
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder="Search articles, tags, content…"
              style={{ width: 360, height: 36, fontSize: 13 }}
              autoFocus
            />
          </div>
        </div>
      </div>

      {q ? (
        <SearchResults results={searchResults} query={q} onOpen={id => { setArticleId(id); setQuery(""); }} />
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "230px 1fr 220px", gap: 18 }}>
          {/* LEFT — category tree */}
          <DocsSidebar articleId={articleId} onSelect={setArticleId} />

          {/* CENTER — article */}
          <ArticleView article={article} onNavigate={setArticleId} />

          {/* RIGHT — TOC + related */}
          <ArticleAside article={article} onNavigate={setArticleId} />
        </div>
      )}
    </div>
  );
}

function DocsSidebar({ articleId, onSelect }) {
  return (
    <div className="card" style={{ padding: 8, height: "fit-content", position: "sticky", top: 8 }}>
      {DOC_CATEGORIES.map(cat => {
        const items = DOC_ARTICLES.filter(a => a.category === cat.id);
        return (
          <div key={cat.id} style={{ marginBottom: 4 }}>
            <div className="nav-label" style={{ color: "var(--ink-mute)", padding: "10px 10px 4px" }}>
              <span className="row gap-6">
                <Icon name={cat.icon === "chat" ? "chat" : cat.icon === "grid" ? "grid" : cat.icon === "history" ? "history" : cat.icon === "shield" ? "shield" : cat.icon === "arrowRight" ? "arrowRight" : cat.icon === "bolt" ? "bolt" : "book"} size={11} />
                {cat.label}
              </span>
            </div>
            {items.map(a => (
              <button
                key={a.id}
                onClick={() => onSelect(a.id)}
                className="nav-item"
                style={{
                  color: articleId === a.id ? "var(--ink)" : "var(--ink-mute)",
                  background: articleId === a.id ? "var(--paper)" : "transparent",
                  fontSize: 12, padding: "5px 10px", lineHeight: 1.3,
                }}
              >
                <span style={{ flex: 1, textAlign: "left" }}>{a.title}</span>
                {cat.id === "releases" && a.version && (
                  <span className="mono tiny" style={{ color: a.version === "1.1.0" ? "var(--teal)" : "var(--ink-mute)", fontSize: 9 }}>
                    {a.version === "1.1.0" ? "NEW" : "v" + a.version}
                  </span>
                )}
              </button>
            ))}
          </div>
        );
      })}
    </div>
  );
}

function ArticleView({ article, onNavigate }) {
  if (!article) return null;
  const cat = DOC_CATEGORIES.find(c => c.id === article.category);
  return (
    <div className="card" style={{ padding: "28px 36px" }}>
      <div className="row gap-6 tiny muted" style={{ marginBottom: 10 }}>
        <span>{cat?.label}</span>
        <span>·</span>
        <span className="mono">Updated {article.updated}</span>
        {article.author && <><span>·</span><span>{article.author}</span></>}
        {article.version && <><span>·</span><Pill className="plain" style={{ fontSize: 10 }}>v{article.version}</Pill></>}
      </div>
      <h1 className="serif" style={{ fontSize: 28, fontWeight: 500, letterSpacing: "-0.01em", margin: "0 0 8px" }}>{article.title}</h1>
      <div className="muted" style={{ fontSize: 14, marginBottom: 16 }}>{article.excerpt}</div>

      <div className="row gap-4" style={{ marginBottom: 24, flexWrap: "wrap" }}>
        {article.tags?.map(t => (
          <span key={t} className="pill plain" style={{ fontSize: 10 }}>#{t}</span>
        ))}
      </div>

      <div className="divider" />

      <div style={{ fontSize: 14, lineHeight: 1.65, color: "var(--ink)" }}>
        {article.blocks.map((b, i) => <Block key={i} block={b} idx={i} />)}
      </div>

      {/* Footer nav */}
      <div className="divider" />
      <div className="row" style={{ justifyContent: "space-between", marginTop: 12 }}>
        <button className="btn ghost"><Icon name="check" size={12} /> Helpful</button>
        <div className="row gap-12 tiny muted">
          <span>Article ID: <span className="mono">{article.id}</span></span>
          <a style={{ color: "var(--teal)" }}>Edit on internal wiki ↗</a>
        </div>
      </div>
    </div>
  );
}

function Block({ block }) {
  switch (block.type) {
    case "p":
      return <p style={{ margin: "0 0 14px" }}>{block.text}</p>;
    case "h2":
      return <h2 id={slug(block.text)} className="serif" style={{ fontSize: 19, fontWeight: 500, margin: "24px 0 10px", scrollMarginTop: 80 }}>{block.text}</h2>;
    case "h3":
      return <h3 id={slug(block.text)} style={{ fontSize: 15, fontWeight: 600, margin: "18px 0 8px", scrollMarginTop: 80 }}>{block.text}</h3>;
    case "ul":
      return (
        <ul style={{ margin: "0 0 14px", paddingLeft: 22 }}>
          {block.items.map((it, i) => <li key={i} style={{ marginBottom: 4 }}>{it}</li>)}
        </ul>
      );
    case "ol":
      return (
        <ol style={{ margin: "0 0 14px", paddingLeft: 22 }}>
          {block.items.map((it, i) => <li key={i} style={{ marginBottom: 4 }}>{it}</li>)}
        </ol>
      );
    case "code":
      return (
        <pre style={{ background: "#0b1e33", color: "#cfe0f2", padding: 14, borderRadius: 6, overflowX: "auto", fontSize: 12, fontFamily: "IBM Plex Mono, monospace", margin: "0 0 14px", lineHeight: 1.5 }}>
          {block.text}
        </pre>
      );
    case "kv":
      return (
        <table style={{ width: "100%", margin: "0 0 14px", borderCollapse: "collapse" }}>
          <tbody>
            {block.rows.map(([k, v], i) => (
              <tr key={i} style={{ borderTop: i === 0 ? "1px solid var(--line)" : "1px solid #eef1f5" }}>
                <td style={{ padding: "8px 12px 8px 0", color: "var(--ink-mute)", verticalAlign: "top", width: "30%", fontWeight: 500 }}>{k}</td>
                <td style={{ padding: "8px 0" }}>{v}</td>
              </tr>
            ))}
            <tr style={{ borderTop: "1px solid var(--line)" }}></tr>
          </tbody>
        </table>
      );
    case "table":
      return (
        <div className="card" style={{ margin: "0 0 14px", overflow: "hidden" }}>
          <table className="table">
            <thead>
              <tr>{block.headers.map((h, i) => <th key={i}>{h}</th>)}</tr>
            </thead>
            <tbody>
              {block.rows.map((row, ri) => (
                <tr key={ri}>{row.map((c, ci) => <td key={ci} className={ci === 0 ? "bold tiny" : "tiny"}>{c}</td>)}</tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    case "callout": {
      const tones = {
        info: { bg: "var(--teal-soft)", bd: "#c8e3ea", color: "var(--teal)", icon: "shield" },
        warn: { bg: "var(--amber-soft)", bd: "#f0d8a8", color: "var(--amber)", icon: "bell" },
        tip:  { bg: "var(--green-soft)", bd: "#bfd9c4", color: "var(--green)", icon: "sparkle" },
      };
      const t = tones[block.tone] || tones.info;
      return (
        <div style={{ background: t.bg, border: `1px solid ${t.bd}`, borderRadius: 6, padding: 14, display: "flex", gap: 10, margin: "0 0 14px" }}>
          <Icon name={t.icon} size={16} stroke={t.color} />
          <div style={{ fontSize: 13, lineHeight: 1.55 }}>
            {block.title && <b style={{ color: t.color }}>{block.title}.</b>}{" "}
            {block.text}
          </div>
        </div>
      );
    }
    case "permMatrix":
      return <PermMatrix />;
    case "divider":
      return <div className="divider" />;
    default:
      return null;
  }
}

function PermMatrix() {
  const features = [
    { k: "viewRates", l: "View rates (own scope)" },
    { k: "edit", l: "Create / update rates" },
    { k: "import", l: "Import rates (template / AI)" },
    { k: "export", l: "Export rate sheet" },
    { k: "calculator", l: "Rate Calculator" },
    { k: "aiqa", l: "AI Q&A (DIFY)" },
    { k: "admin", l: "Admin functions" },
  ];
  const roles = ["rate_calculator", "read", "edit", "fbp", "procurement", "admin"];
  return (
    <div className="card" style={{ overflow: "hidden", margin: "0 0 14px" }}>
      <table className="table">
        <thead>
          <tr>
            <th>Feature</th>
            {roles.map(r => <th key={r} style={{ textAlign: "center" }}>{r}</th>)}
          </tr>
        </thead>
        <tbody>
          {features.map(f => (
            <tr key={f.k}>
              <td className="tiny">{f.l}</td>
              {roles.map(r => (
                <td key={r} style={{ textAlign: "center" }}>
                  {PERMS[r][f.k]
                    ? <span style={{ color: "var(--green)", fontSize: 13 }}>✓</span>
                    : <span style={{ color: "var(--line-strong)", fontSize: 13 }}>—</span>}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function ArticleAside({ article, onNavigate }) {
  const headings = article.blocks.filter(b => b.type === "h2" || b.type === "h3").map(b => ({ text: b.text, level: b.type, id: slug(b.text) }));
  const related = (article.related || []).map(id => DOC_ARTICLES.find(a => a.id === id)).filter(Boolean);

  return (
    <div style={{ position: "sticky", top: 8, height: "fit-content", display: "flex", flexDirection: "column", gap: 12 }}>
      {headings.length > 0 && (
        <div className="card" style={{ padding: 14 }}>
          <div className="tiny mono muted" style={{ textTransform: "uppercase", letterSpacing: 0.08, marginBottom: 10 }}>On this page</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 4, borderLeft: "2px solid var(--line)" }}>
            {headings.map((h, i) => (
              <a key={i} href={`#${h.id}`} style={{ paddingLeft: h.level === "h3" ? 18 : 10, paddingTop: 3, paddingBottom: 3, color: "var(--ink-mute)", textDecoration: "none", fontSize: 12, lineHeight: 1.4 }}
                onMouseEnter={e => e.currentTarget.style.color = "var(--teal)"}
                onMouseLeave={e => e.currentTarget.style.color = "var(--ink-mute)"}>
                {h.text}
              </a>
            ))}
          </div>
        </div>
      )}
      {related.length > 0 && (
        <div className="card" style={{ padding: 14 }}>
          <div className="tiny mono muted" style={{ textTransform: "uppercase", letterSpacing: 0.08, marginBottom: 10 }}>Related</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {related.map(r => (
              <button key={r.id} onClick={() => onNavigate(r.id)}
                className="row gap-6"
                style={{ background: "transparent", border: 0, color: "var(--ink)", fontSize: 12, padding: "6px 0", textAlign: "left", cursor: "pointer", borderTop: "1px solid var(--line)", lineHeight: 1.35 }}>
                <Icon name="arrowRight" size={11} stroke="var(--teal)" />
                <span>{r.title}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {article.category === "releases" && article.releaseDate && (
        <div className="card" style={{ padding: 14, background: "var(--paper)" }}>
          <div className="tiny mono muted" style={{ textTransform: "uppercase", letterSpacing: 0.08, marginBottom: 6 }}>Version</div>
          <div className="serif" style={{ fontSize: 20, fontWeight: 500 }}>v{article.version}</div>
          <div className="tiny muted mono">Released {article.releaseDate}</div>
        </div>
      )}
    </div>
  );
}

function SearchResults({ results, query, onOpen }) {
  if (results.length === 0) {
    return (
      <div className="card" style={{ padding: 60, textAlign: "center" }}>
        <Icon name="search" size={36} stroke="var(--line-strong)" />
        <div className="serif" style={{ fontSize: 18, fontWeight: 500, marginTop: 14 }}>No results for "{query}"</div>
        <div className="muted" style={{ marginTop: 6 }}>Try a shorter keyword, or browse the categories below.</div>
        <div className="row gap-6" style={{ justifyContent: "center", marginTop: 20, flexWrap: "wrap" }}>
          {DOC_CATEGORIES.map(c => (
            <button key={c.id} className="btn">{c.label}</button>
          ))}
        </div>
      </div>
    );
  }
  return (
    <div>
      <div className="muted tiny" style={{ marginBottom: 12 }}>
        Found <b style={{ color: "var(--ink)" }}>{results.length}</b> article{results.length === 1 ? "" : "s"} matching <b style={{ color: "var(--ink)" }}>"{query}"</b>
      </div>
      <div style={{ display: "grid", gap: 10 }}>
        {results.map(r => {
          const cat = DOC_CATEGORIES.find(c => c.id === r.category);
          // Find a snippet around the match
          const idx = r.searchText.indexOf(query);
          let snippet = r.excerpt;
          if (idx >= 0) {
            const start = Math.max(0, idx - 40);
            const end = Math.min(r.searchText.length, idx + query.length + 80);
            snippet = (start > 0 ? "…" : "") + r.searchText.slice(start, end) + (end < r.searchText.length ? "…" : "");
          }
          return (
            <div key={r.id} className="card" style={{ padding: 16, cursor: "pointer", transition: "border-color 0.12s" }}
              onClick={() => onOpen(r.id)}
              onMouseEnter={e => e.currentTarget.style.borderColor = "var(--teal)"}
              onMouseLeave={e => e.currentTarget.style.borderColor = "var(--line)"}>
              <div className="row gap-8" style={{ marginBottom: 4 }}>
                <Pill className="plain" style={{ fontSize: 10 }}>{cat?.label}</Pill>
                <span className="tiny muted mono">Updated {r.updated}</span>
                {r.version && <Pill className="plain" style={{ fontSize: 10 }}>v{r.version}</Pill>}
              </div>
              <div className="bold" style={{ fontSize: 15 }}>
                <Highlight text={r.title} q={query} />
              </div>
              <div className="muted" style={{ fontSize: 12.5, marginTop: 4, lineHeight: 1.5 }}>
                <Highlight text={snippet} q={query} />
              </div>
              <div className="row gap-4" style={{ marginTop: 8, flexWrap: "wrap" }}>
                {r.tags?.slice(0, 6).map(t => (
                  <span key={t} className="pill plain" style={{ fontSize: 9 }}>
                    {t.toLowerCase().includes(query) ? <mark style={{ background: "#fdf6c3", padding: "0 2px" }}>#{t}</mark> : `#${t}`}
                  </span>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function Highlight({ text, q }) {
  if (!q) return <>{text}</>;
  const lc = text.toLowerCase();
  const parts = [];
  let i = 0, p = 0;
  while ((i = lc.indexOf(q, p)) >= 0) {
    if (i > p) parts.push(<React.Fragment key={p}>{text.slice(p, i)}</React.Fragment>);
    parts.push(<mark key={i} style={{ background: "#fdf6c3", padding: "0 1px", borderRadius: 2 }}>{text.slice(i, i + q.length)}</mark>);
    p = i + q.length;
  }
  if (p < text.length) parts.push(<React.Fragment key={p}>{text.slice(p)}</React.Fragment>);
  return <>{parts}</>;
}

function slug(s) {
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
}

Object.assign(window, { Documentation });
