/* global React, Icon, StatusChip, Avatar, PageHeader, Drawer, DrawerHead, Banner, Meta, PACKAGES, EXCEPTIONS, PEOPLE, useActionDrawer, useToast */
const { useState: useStateE, useEffect: useEffectE } = React;

const GATE_LABELS = {
  source: "Source snapshots", validation: "Schema validation", mapping: "Cell mapping",
  evidence: "Rule evidence", lineage: "Published lineage", approval: "Maker-checker approval",
};

const EXPORT_HELP = {
  title: "Reg Reporting · Export gate",
  purpose: "Where NBE return packages are assembled from workpaper cells and held behind a six-gate checklist. Official export stays blocked until every gate passes.",
  first: "Read the gate row on each package. A single failed gate blocks official export — but you can still prepare an internal pack.",
  terms: [
    ["Package", "An NBE return (LRM, CAR, NOP…) assembled from mapped workpaper cells."],
    ["Gate", "One of six checks: source, validation, mapping, evidence, lineage, approval."],
    ["Cell map", "The traceable link from each return cell back to its source and rule."],
  ],
  next: ["Open a package to see its gate checklist and cell map.", "Prepare an internal pack for review.", "Clear failing gates by completing the upstream evidence."],
  connections: ["Gates pull status from Harmonizer, workpapers, and Rule Evidence.", "Blockers open as Exceptions.", "Approved packages remain internal — official submission is not available."],
  guardrail: "There is no export writer and no regulator submission. Even a fully-green package is an internal pack only; official NBE export is a future capability.",
};

function ExportGate({ go, info }) {
  const [pkg, setPkg] = useStateE(null);
  return (
    <div className="main-inner">
      <PageHeader eyebrow="Governance · Reg Reporting" title="Export readiness" onInfo={() => info(EXPORT_HELP)}
        right={<button className="btn btn-ghost btn-sm" onClick={() => go("templatehub")}><Icon name="clipboard" size={15} /> Template Hub</button>} />

      <div style={{ marginBottom: 20 }}>
        <Banner kind="red" icon="lock"><b>Official NBE export is not available.</b> Source, rule evidence, lineage, validation, and approvals must all pass first — and even then, packages are prepared as internal review packs. There is no regulator-submission writer in this build.</Banner>
      </div>

      <div className="card">
        <table className="tbl">
          <thead><tr><th>NBE package</th><th>Cells</th><th>Gate status</th><th>Owner</th><th>Readiness</th><th></th></tr></thead>
          <tbody>
            {PACKAGES.map(p => {
              const passed = Object.values(p.gates).filter(g => g === "pass").length;
              const o = PEOPLE[p.owner];
              return (
                <tr key={p.id} className="click" onClick={() => setPkg(p)}>
                  <td><div style={{ fontWeight: 700 }}>{p.name}</div><div className="mono muted" style={{ fontSize: 11.5 }}>{p.code}</div></td>
                  <td className="tnum">{p.cells}</td>
                  <td>
                    <div className="center gap6">
                      {Object.entries(p.gates).map(([g, st]) => (
                        <span key={g} title={GATE_LABELS[g] + " — " + st} style={{ width: 18, height: 18, borderRadius: 5, display: "grid", placeItems: "center",
                          background: st === "pass" ? "var(--green-soft)" : st === "fail" ? "var(--red-soft)" : "var(--amber-soft)",
                          color: st === "pass" ? "var(--green-ink)" : st === "fail" ? "var(--red)" : "var(--amber)" }}>
                          <Icon name={st === "pass" ? "check" : st === "fail" ? "x" : "clock"} size={11} />
                        </span>
                      ))}
                      <span className="muted" style={{ fontSize: 11.5, marginLeft: 2 }}>{passed}/6</span>
                    </div>
                  </td>
                  <td><span className="center gap6" style={{ fontSize: 12.5 }}><Avatar name={o.name} size={20} /> {o.name.split(" ")[0]}</span></td>
                  <td><StatusChip s={p.state} /></td>
                  <td className="num"><span className="jump">Open <Icon name="arrowR" size={13} /></span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <PackageDrawer pkg={pkg} onClose={() => setPkg(null)} go={go} />
    </div>
  );
}

function PackageDrawer({ pkg, onClose, go }) {
  const [actionNode, openAction] = useActionDrawer();
  if (!pkg) return null;
  const allPass = Object.values(pkg.gates).every(g => g === "pass");
  return (
    <React.Fragment>
      <Drawer open={!!pkg} onClose={onClose} wide>
        <DrawerHead title={pkg.name} sub={pkg.code + " · " + pkg.cells + " cells"} chip={<StatusChip s={pkg.state} />} onClose={onClose} />
        <div className="drawer-body">
          {allPass
            ? <Banner kind="green" icon="checkCirc"><b>All six gates pass.</b> This package is ready as an <b>internal review pack</b>. Official NBE submission is a future capability and remains unavailable.</Banner>
            : <Banner kind="red" icon="lock"><b>Official export blocked.</b> {Object.values(pkg.gates).filter(g => g !== "pass").length} of 6 gates are not yet satisfied.</Banner>}

          <div className="section-label mt20 mb12">Export gate checklist</div>
          {Object.entries(pkg.gates).map(([g, st]) => (
            <div key={g} className="gate">
              <span className={"g-ic " + (st === "pass" ? "pass" : st === "fail" ? "fail" : "wait")}><Icon name={st === "pass" ? "check" : st === "fail" ? "x" : "clock"} size={14} /></span>
              <div className="grow"><div className="g-t">{GATE_LABELS[g]}</div><div className="g-d">{st === "pass" ? "Complete" : st === "fail" ? "Failing — upstream evidence incomplete" : "Waiting on a prior gate"}</div></div>
              {st !== "pass" && <button className="btn btn-ghost btn-sm" onClick={() => go(g === "evidence" ? "evidence" : g === "approval" ? "workpaper" : "harmonizer")}>Resolve</button>}
            </div>
          ))}

          <div className="section-label mt24 mb8">Cell map sample</div>
          <table className="tbl"><thead><tr><th>Return cell</th><th>Source</th><th>Rule</th></tr></thead>
            <tbody>
              {[["1.1 HQLA Level 1", "Deposits ledger", "NBE LRM §4.1"], ["2.3 SME outflows", "Deposits ledger", "— no reference"], ["3.1 Loan inflows", "Loans ledger", "NBE LRM §6.1"]].map((r, i) => (
                <tr key={i}><td className="mono" style={{ fontSize: 12 }}>{r[0]}</td><td>{r[1]}</td><td style={{ color: r[2].includes("no reference") ? "var(--amber)" : "var(--ink-2)" }} className="mono" >{r[2]}</td></tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="drawer-foot">
          <button className="btn btn-ghost" onClick={() => openAction({
            title: "Workbook hash",
            sub: pkg.code,
            chip: <StatusChip s="INTERNAL_WP" />,
            banner: <span><b>Workbook fingerprint staged.</b> The hash identifies this internal package draft and its cell-map fixture.</span>,
            rows: [["Package", pkg.name], ["Cells", pkg.cells], ["Hash basis", "Template + cell map + fixture snapshot"], ["Artifact", "Internal review pack only"]],
            guardrail: "No export workbook is written in this Sprint 1 build.",
          })}><Icon name="hash" size={15} /> Workbook hash</button>
          <button className="btn btn-dark" style={{ marginLeft: "auto" }} onClick={() => openAction(allPass ? {
            title: "Prepare internal pack",
            sub: pkg.code,
            chip: <StatusChip s="APPROVED_INTERNAL" />,
            kind: "green",
            icon: "checkCirc",
            banner: <span><b>Internal review pack prepared.</b> It can be reviewed by the bank team, but it is not an official submission.</span>,
            rows: [["Package", pkg.name], ["Gate status", "6 / 6 passed"], ["Output", "Internal pack only"]],
            guardrail: "There is still no export writer and no regulator submission in this build.",
          } : {
            title: "Official export blocked",
            sub: pkg.code,
            chip: <StatusChip s="EXPORT_BLOCKED" />,
            kind: "red",
            icon: "lock",
            banner: <span><b>{Object.values(pkg.gates).filter(g => g !== "pass").length} gate(s) are still open.</b> Resolve the failed checklist items before preparing even an internal pack.</span>,
            rows: [["Source snapshots", pkg.gates.source], ["Validation", pkg.gates.validation], ["Mapping", pkg.gates.mapping], ["Rule evidence", pkg.gates.evidence], ["Lineage", pkg.gates.lineage], ["Approval", pkg.gates.approval]],
          })}>{allPass ? "Prepare internal pack" : "Blocked"}</button>
        </div>
      </Drawer>
      {actionNode}
    </React.Fragment>
  );
}

window.ExportGate = ExportGate;

/* ============================================================
   EXCEPTIONS
   ============================================================ */
const EXC_HELP = {
  title: "Exceptions",
  purpose: "The single queue for everything holding numbers back: failed validation, reconciliation breaks, missing rule evidence, low-confidence mappings, and missing sources.",
  first: "Sort by severity. Each exception names an owner, a reason, and the next action — resolve or waive, both recorded.",
  terms: [["Category", "What kind of gap this is."], ["Waive", "Accept with documented justification (audited)."], ["Resolve", "Fix the underlying source/evidence/mapping."]],
  next: ["Open an exception to see the source record and next action.", "Resolve or waive with a note.", "Jump to the originating workpaper or source."],
  connections: ["Exceptions originate in Harmonizer and workpapers.", "Clearing them advances the export gates."],
  guardrail: "Waiving an exception never makes a number official — it documents a decision. Export gates still apply.",
};

function Exceptions({ go, info }) {
  const [sel, setSel] = useStateE(null);
  const [filter, setFilter] = useStateE("All");
  const [actionNode, openAction] = useActionDrawer();
  const cats = ["All", "Schema validation", "Reconciliation break", "Rule evidence", "Bank policy", "Mapping confidence", "Source missing"];
  const list = filter === "All" ? EXCEPTIONS : EXCEPTIONS.filter(e => e.cat === filter);
  return (
    <div className="main-inner">
      <PageHeader eyebrow="Platform" title="Exceptions" onInfo={() => info(EXC_HELP)}
        right={<button className="btn btn-ghost btn-sm" onClick={() => openAction({
          title: "Export exception queue",
          sub: "Internal CSV preview",
          chip: <StatusChip s="INTERNAL_WP" />,
          banner: <span><b>Exception queue prepared for review.</b> This is an internal queue view, not a file writer.</span>,
          rows: [["Rows", list.length], ["Filter", filter], ["Critical", list.filter(e => e.sev === "red").length], ["Output", "Internal queue preview only"]],
          guardrail: "No export file is written from this screen.",
        })}><Icon name="download" size={15} /> Export queue</button>} />

      <div className="center gap8 wrap mb16">
        {cats.map(c => <button key={c} className={"chip chip-lg " + (filter === c ? "chip-ink" : "chip-neutral")} style={{ cursor: "pointer" }} onClick={() => setFilter(c)}>{c}{c !== "All" && <span style={{ opacity: .6 }}>· {EXCEPTIONS.filter(e => e.cat === c).length}</span>}</button>)}
      </div>

      <div className="card">
        <table className="tbl">
          <thead><tr><th>ID</th><th>Category</th><th>Record</th><th>Module</th><th>Owner</th><th>Severity</th><th></th></tr></thead>
          <tbody>
            {list.map(e => {
              const o = PEOPLE[e.owner];
              return (
                <tr key={e.id} className="click" onClick={() => setSel(e)}>
                  <td className="mono" style={{ fontSize: 12.5 }}>{e.id}</td>
                  <td>{e.cat}</td>
                  <td style={{ maxWidth: 320 }}>{e.rec}</td>
                  <td className="muted">{e.module}</td>
                  <td><span className="center gap6" style={{ fontSize: 12.5 }}><Avatar name={o.name} size={20} /> {o.name.split(" ")[0]}</span></td>
                  <td><span className={"chip chip-" + e.sev}><span className="dot" />{e.sev === "red" ? "Critical" : "To resolve"}</span></td>
                  <td className="num"><span className="jump">Open <Icon name="arrowR" size={13} /></span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <ExcDrawer exc={sel} onClose={() => setSel(null)} go={go} />
      {actionNode}
    </div>
  );
}

function ExcDrawer({ exc, onClose, go }) {
  const [toastNode, showToast] = useToast();
  if (!exc) return null;
  const o = PEOPLE[exc.owner];
  return (
    <Drawer open={!!exc} onClose={onClose}>
      <DrawerHead title={exc.id + " · " + exc.cat} sub={exc.module} chip={<span className={"chip chip-" + exc.sev}><span className="dot" />{exc.sev === "red" ? "Critical" : "To resolve"}</span>} onClose={onClose} />
      <div className="drawer-body">
        <Banner kind={exc.sev === "red" ? "red" : "amber"} icon="alertCirc">{exc.rec}</Banner>
        <div className="mt16"><Meta rows={[
          ["Category", exc.cat],
          ["Module", exc.module],
          ["Owner", <span className="center gap8"><Avatar name={o.name} size={20} /> {o.name} · {o.role}</span>],
          ["Severity", exc.sev === "red" ? "Critical — blocking" : "To resolve"],
          ["Next action", exc.action],
          ["Downstream impact", "Blocks export gate for the owning return"],
        ]} /></div>
        <div className="section-label mt20 mb8">Source record</div>
        <div className="evi-row"><span className="ic-wrap"><Icon name="database" size={15} /></span><div className="grow"><div className="t">Originating snapshot</div><div className="d mono">Open in Data Harmonizer</div></div><button className="btn btn-quiet btn-sm" onClick={() => go("harmonizer")}><Icon name="arrowR" size={13} /></button></div>
      </div>
      <div className="drawer-foot">
        <button className="btn btn-ghost" onClick={() => showToast("Waiver note captured for checker review")}>Waive with note</button>
        <button className="btn btn-primary" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="check" size={15} /> Resolve</button>
      </div>
      {toastNode}
    </Drawer>
  );
}

window.Exceptions = Exceptions;
