// Data Export Guides — renders the customer-facing onboarding guides the
// user supplied as .docx files (converted at build time to JS data at
// src/onboarding-guides.js → window.PerduraOnboardingGuides). Wording is
// preserved verbatim per product copy decision.
//
// Two surfaces:
//   1) Sidebar → Help → Data Export Guides  (full guide reader)
//   2) Contextual links from Settings → Sources + the Onboarding Wizard
//      jump straight to a system section via the GuidesPage(initialGuide,
//      initialSystem) entry point.

const { useState: useStateG, useEffect: useEffectG, useMemo: useMemoG } = React;

function Block({ block }) {
  if (block.kind === "h") {
    const lvl = block.level || 2;
    if (lvl <= 1) return <h2 style={{ fontSize: 22, fontWeight: 700, marginTop: 24, marginBottom: 8 }}>{block.text}</h2>;
    if (lvl === 2) return <h3 style={{ fontSize: 17, fontWeight: 700, marginTop: 22, marginBottom: 6, color: "var(--text)" }}>{block.text}</h3>;
    return <h4 style={{ fontSize: 13.5, fontWeight: 600, marginTop: 14, marginBottom: 4, color: "var(--text-2)", textTransform: "uppercase", letterSpacing: 0.4 }}>{block.text}</h4>;
  }
  if (block.kind === "li") {
    return <li style={{ fontSize: 13.5, lineHeight: 1.6, color: "var(--text-2)", marginBottom: 4 }}>{block.text}</li>;
  }
  if (block.kind === "table") {
    return (
      <div style={{ margin: "12px 0", overflow: "auto", border: "1px solid var(--border)", borderRadius: 6 }}>
        <table className="pc-table" style={{ width: "100%", fontSize: 12.5 }}>
          <tbody>
            {block.rows.map((r, i) => (
              <tr key={i}>{r.map((c, j) => <td key={j} style={{ padding: "6px 10px", borderBottom: "1px solid var(--border)", verticalAlign: "top" }}>{c}</td>)}</tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
  return <p style={{ fontSize: 13.5, lineHeight: 1.65, color: "var(--text-2)", margin: "6px 0" }}>{block.text}</p>;
}

function BlockList({ blocks }) {
  // Group consecutive li blocks into a single <ul> so list bullets render properly.
  const out = [];
  let current = null;
  blocks.forEach((b, i) => {
    if (b.kind === "li") {
      if (!current) { current = { kind: "ul", items: [] }; out.push(current); }
      current.items.push(b);
    } else {
      current = null;
      out.push(b);
    }
  });
  return (
    <>
      {out.map((b, i) => {
        if (b.kind === "ul") {
          return <ul key={i} style={{ paddingLeft: 22, marginTop: 4, marginBottom: 10 }}>
            {b.items.map((li, j) => <Block key={j} block={li} />)}
          </ul>;
        }
        return <Block key={i} block={b} />;
      })}
    </>
  );
}

// Resolve a user-provided system hint (free text or canonical key) to a
// (guideKey, systemKey) tuple. Used by the contextual deep-link from
// Settings → Sources and the Onboarding wizard. Case-insensitive, matches
// either guide.key, system.key, or any system.name.
function resolveDeepLink(guides, hint) {
  if (!hint) return null;
  const h = String(hint).toLowerCase().replace(/[^a-z0-9]+/g, "");
  for (const g of guides) {
    for (const s of g.systems) {
      const sk = (s.key || "").replace(/[^a-z0-9]+/g, "");
      const sn = (s.name || "").toLowerCase().replace(/[^a-z0-9]+/g, "");
      if (sk === h || sn === h || sn.includes(h) || h.includes(sk)) {
        return { guideKey: g.key, systemKey: s.key };
      }
    }
  }
  return null;
}

function GuidesPage({ initialGuide, initialSystem }) {
  const guides = (typeof window !== "undefined" ? window.PerduraOnboardingGuides : null) || [];
  const [activeGuide, setActiveGuide] = useStateG(initialGuide || (guides[0]?.key || ""));
  const [activeSystem, setActiveSystem] = useStateG(initialSystem || "");

  useEffectG(() => {
    // Allow other pages to deep-link us via a transient window flag.
    const hint = window.__perduraGuideHint;
    if (hint) {
      delete window.__perduraGuideHint;
      const resolved = resolveDeepLink(guides, hint);
      if (resolved) {
        setActiveGuide(resolved.guideKey);
        setActiveSystem(resolved.systemKey);
      }
    }
  }, []);

  const guide = useMemoG(() => guides.find(g => g.key === activeGuide) || guides[0], [activeGuide, guides]);
  if (!guide) {
    return (
      <div className="pc-page">
        <div style={{ padding: 32, textAlign: "center", color: "var(--text-3)" }}>
          Loading export guides…
        </div>
      </div>
    );
  }

  const systems = guide.systems || [];
  const sys = systems.find(s => s.key === activeSystem) || null;

  return (
    <div className="pc-page" style={{ maxWidth: 1100, margin: "0 auto" }}>
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.6 }}>Help · Data Export Guide</div>
        <h1 style={{ fontSize: 26, fontWeight: 700, margin: "4px 0 6px 0" }}>{guide.title}</h1>
        {guide.header && guide.header[2] && (
          <div style={{ fontSize: 14, color: "var(--text-3)" }}>{guide.header[2]}</div>
        )}
      </div>

      {/* Guide picker tabs */}
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 16, borderBottom: "1px solid var(--border)", paddingBottom: 4 }}>
        {guides.map(g => (
          <button key={g.key}
            onClick={() => { setActiveGuide(g.key); setActiveSystem(""); }}
            style={{
              padding: "8px 14px", border: "none", background: "none", cursor: "pointer",
              fontSize: 13, fontWeight: 500,
              color: activeGuide === g.key ? "var(--accent)" : "var(--text-3)",
              borderBottom: activeGuide === g.key ? "2px solid var(--accent)" : "2px solid transparent",
              marginBottom: -5,
            }}>
            {g.letter} · {g.title}
          </button>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: systems.length ? "220px 1fr" : "1fr", gap: 24 }}>
        {systems.length > 0 && (
          <aside style={{
            borderRight: "1px solid var(--border)", paddingRight: 16,
            position: "sticky", top: 16, alignSelf: "flex-start", maxHeight: "calc(100vh - 100px)", overflow: "auto",
          }}>
            <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 6 }}>
              Find your system
            </div>
            <button onClick={() => setActiveSystem("")}
              style={{
                width: "100%", textAlign: "left", padding: "6px 8px", marginBottom: 2,
                border: "none", background: activeSystem === "" ? "var(--hover)" : "none",
                cursor: "pointer", borderRadius: 4, fontSize: 12.5,
                color: activeSystem === "" ? "var(--text)" : "var(--text-3)",
                fontWeight: activeSystem === "" ? 600 : 400,
              }}>
              Overview
            </button>
            {systems.map(s => (
              <button key={s.key} onClick={() => setActiveSystem(s.key)}
                style={{
                  width: "100%", textAlign: "left", padding: "6px 8px", marginBottom: 2,
                  border: "none", background: activeSystem === s.key ? "var(--hover)" : "none",
                  cursor: "pointer", borderRadius: 4, fontSize: 12.5,
                  color: activeSystem === s.key ? "var(--text)" : "var(--text-2)",
                  fontWeight: activeSystem === s.key ? 600 : 400,
                }}>
                {s.name}
              </button>
            ))}
          </aside>
        )}

        <article>
          {activeSystem === "" ? <BlockList blocks={guide.intro || []} /> : <BlockList blocks={sys ? sys.blocks : []} />}
          <div style={{ marginTop: 32, padding: 14, background: "var(--bg-elev-2)", border: "1px solid var(--border)", borderRadius: 8, fontSize: 12.5, color: "var(--text-3)" }}>
            Once you have your exports, drop them into <b>Settings → Configuration → Excel / CSV import</b>.
            We'll detect the schema, run the reconciliation gates, and report any unmatched accounts.
          </div>
        </article>
      </div>
    </div>
  );
}

window.GuidesPage = GuidesPage;
window.resolveGuideDeepLink = (hint) => {
  const guides = window.PerduraOnboardingGuides || [];
  return resolveDeepLink(guides, hint);
};
