/* global React, Icon, StatusChip, Avatar, PageHeader, Banner, Drawer, DrawerHead, Meta, PEOPLE */
const { useState: useStateTH } = React;

/* ============================================================
   Template Hub — registry of NBE return templates & country packs
   The shelf of report definitions that the Export Gate assembles.
   ============================================================ */
const TEMPLATES = [
  { id: "t1", code: "NBE/CAR", name: "Capital Adequacy Return", pack: "NBE v3.1", version: "v3.1", cells: 286, cycle: "Quarterly", route: "capital", state: "REVIEW_PENDING", owner: "meron", updated: "Apr 2025", mapped: 286, evid: 248, source: "SBB/95/2025 PDF", anchor: "Annex capital template · floors 7/9/11%" },
  { id: "t2", code: "NBE/LRM", name: "Liquidity Return (LCR)", pack: "NBE v3.1", version: "v3.1", cells: 412, cycle: "Monthly", route: "lcr", state: "EXPORT_BLOCKED", owner: "sara", updated: "Apr 2025", mapped: 412, evid: 380, source: "User Annex III screenshot", anchor: "HQLA 28,884 · LCR 264.91%" },
  { id: "t3", code: "NBE/NSFR", name: "Net Stable Funding Return", pack: "NBE v3.1", version: "v3.1", cells: 96, cycle: "Quarterly", route: "lcr", state: "MAPPED", owner: "sara", updated: "Apr 2025", mapped: 96, evid: 70, source: "NBE liquidity pack", anchor: "ASF / RSF floor 100%" },
  { id: "t4", code: "NBE/CR", name: "Credit Risk RWA Return", pack: "NBE v3.1", version: "v3.1", cells: 320, cycle: "Quarterly", route: "credit", state: "EVIDENCE_NEEDED", owner: "yonas", updated: "Apr 2025", mapped: 300, evid: 210, source: "Credit risk2.xlsx", anchor: "On/Off balance CRM + CCF ladder" },
  { id: "t5", code: "NBE/NOP", name: "Net Open Position Return", pack: "NBE v3.1", version: "v3.1", cells: 64, cycle: "Weekly", route: "market", state: "APPROVED_INTERNAL", owner: "abel", updated: "Apr 2025", mapped: 64, evid: 64, source: "Credit risk2.xlsx · Mkt", anchor: "NOP ±18% Tier 1" },
  { id: "t6", code: "NBE/OR", name: "Operational Risk Return (SMA)", pack: "NBE v3.1", version: "v3.1", cells: 92, cycle: "Annual", route: "oprisk", state: "REVIEW_PENDING", owner: "robel", updated: "Apr 2025", mapped: 92, evid: 78, source: "Credit risk2.xlsx · OPerational", anchor: "BI/BIC/ILM + BIC × 9.1 fallback" },
  { id: "t7", code: "NBE/LE", name: "Large Exposures Return", pack: "NBE v3.1", version: "v3.1", cells: 158, cycle: "Quarterly", route: "credit", state: "EXPORT_BLOCKED", owner: "yonas", updated: "Apr 2025", mapped: 120, evid: 60, source: "SBB/95/2025 PDF", anchor: "Large exposure return · future parity" },
  { id: "t8", code: "NBE/IRRBB", name: "Interest-Rate Risk Return", pack: "NBE v3.1", version: "v3.1", cells: 110, cycle: "Quarterly", route: "irrbb", state: "NEEDS_BANK_POLICY", owner: "dawit", updated: "Apr 2025", mapped: 90, evid: 40, source: "Bank policy required", anchor: "IRRBB assumptions shell" },
];

const PACKS = [
  { id: "p1", name: "Ethiopia · NBE Prudential Pack", version: "v3.1", state: "RECONCILED", templates: 8, active: true, note: "Active · SBB95/2025 + LRM + ELA", source: "SBB/95/2025 · SBB/93/2025 · ELA/001/2024" },
  { id: "p2", name: "Kenya · CBK Pack", version: "—", state: "OFFICIAL_FUTURE", templates: 0, active: false, note: "Roadmap — not yet available", source: "Not loaded" },
];

function TemplateHub({ go, info }) {
  const [tab, setTab] = useStateTH("Templates");
  const [sel, setSel] = useStateTH(null);
  const ready = TEMPLATES.filter(t => t.state === "APPROVED_INTERNAL").length;
  const blocked = TEMPLATES.filter(t => t.state === "EXPORT_BLOCKED").length;

  return (
    <div className="main-inner">
      <PageHeader eyebrow="Governance · Reg Reporting" title="Template Hub"
        onInfo={() => info({ title: "Template Hub", purpose: "The registry of NBE return templates and country packs — the shelf of report definitions the Export Gate assembles from. Each template declares its cells, cycle, owner, mapping and evidence coverage, and which workpaper feeds it.", first: "Read each template's mapping and evidence coverage; a template can't reach an internal pack until both are complete and approvals pass.", terms: [["Template", "An NBE return definition (cells, cycle, version)."], ["Country pack", "A versioned bundle of templates + factor libraries."], ["Cell map", "The link from each return cell to its workpaper source."]], next: ["Open a template to see its cell map, coverage and owner.", "Jump to the feeding workpaper.", "Send a ready template to the Export Gate."], connections: ["Templates feed the Export Gate's six-gate checklist.", "Cells map to workpaper rows; factors carry rule evidence.", "Packs are activated in Onboarding."], guardrail: "Templates are output definitions, not the system of record. Official export stays blocked until source, mapping, evidence, lineage and approvals pass. Only the Ethiopia/NBE pack is active." })}
        right={<button className="btn btn-dark btn-sm" onClick={() => go("export")}><Icon name="fileText" size={15} /> Export Gate</button>} />

      <div className="grid g4 mb16">
        <Mini label="Templates" v={TEMPLATES.length} foot="In the active NBE pack" />
        <Mini label="Approved internal" v={ready + " / " + TEMPLATES.length} foot="Ready as internal pack" tone="green" />
        <Mini label="Export-blocked" v={blocked} foot="Evidence / approval gaps" tone="red" />
        <Mini label="Active packs" v="1" foot="Ethiopia · NBE v3.1" />
      </div>

      <div className="seg-ctl mb20">{["Templates", "Country packs"].map(t => <button key={t} className={tab === t ? "on" : ""} onClick={() => setTab(t)}>{t}</button>)}</div>

      {tab === "Templates" && <div className="card">
        <table className="tbl">
          <thead><tr><th>Code</th><th>Return</th><th>Source tag</th><th>Cycle</th><th>Cells</th><th>Mapping</th><th>Evidence</th><th>State</th><th>Owner</th><th></th></tr></thead>
          <tbody>
            {TEMPLATES.map(t => { const p = PEOPLE[t.owner]; const mapPct = Math.round(t.mapped / t.cells * 100); const evPct = Math.round(t.evid / t.cells * 100); return (
              <tr key={t.id} className="click" onClick={() => setSel(t)}>
                <td className="mono" style={{ fontSize: 12 }}>{t.code}</td>
                <td style={{ fontWeight: 600 }}>{t.name}</td>
                <td><SourceTag source={t.source} anchor={t.anchor} /></td>
                <td className="muted">{t.cycle}</td>
                <td className="tnum">{t.cells}</td>
                <td><Cov2 pct={mapPct} /></td>
                <td><Cov2 pct={evPct} /></td>
                <td><StatusChip s={t.state} /></td>
                <td><span className="center gap6" style={{ fontSize: 12.5 }}><Avatar name={p.name} size={20} /> {p.name.split(" ")[0]}</span></td>
                <td className="num"><span className="jump">Open <Icon name="arrowR" size={13} /></span></td>
              </tr>
            ); })}
          </tbody>
        </table>
      </div>}

      {tab === "Country packs" && <div className="col" style={{ gap: 14 }}>
        {PACKS.map(p => (
          <div key={p.id} className={"card card-pad" + (p.active ? "" : " dim")}>
            <div className="between"><div className="center gap12"><span style={{ width: 38, height: 38, borderRadius: 10, background: "var(--surface-2)", border: "1px solid var(--border)", display: "grid", placeItems: "center" }}><Icon name="globe" size={20} /></span><div><div style={{ fontWeight: 700, fontSize: 15 }}>{p.name}</div><div className="muted" style={{ fontSize: 12.5 }}>{p.note}</div><div className="mono muted" style={{ fontSize: 11.5, marginTop: 3 }}>{p.source}</div></div></div>
              <div className="center gap10">{p.active ? <span className="chip chip-green"><span className="dot" />Active</span> : <StatusChip s="OFFICIAL_FUTURE" />}<span className="chip chip-neutral">{p.version}</span><span className="chip chip-neutral">{p.templates} templates</span></div></div>
          </div>
        ))}
        <Banner kind="indigo" icon="info">A country pack bundles the regulator's templates, factor libraries and source requirements. Only the <b>Ethiopia · NBE</b> pack is active; others are roadmap. Packs are activated during Onboarding.</Banner>
      </div>}

      {sel && <Drawer open={!!sel} onClose={() => setSel(null)} wide>
        <DrawerHead title={sel.name} sub={sel.code + " · " + sel.pack + " · " + sel.cells + " cells"} chip={<StatusChip s={sel.state} />} onClose={() => setSel(null)} />
        <div className="drawer-body">
          {sel.state === "EXPORT_BLOCKED" && <Banner kind="red" icon="lock"><b>Official export blocked.</b> Mapping and/or evidence coverage is incomplete for this return.</Banner>}
          <div className="mt16"><Meta rows={[
            ["Return code", <span className="mono">{sel.code}</span>], ["Country pack", sel.pack + " · " + sel.version], ["Reporting cycle", sel.cycle],
            ["Cells", sel.cells], ["Cell mapping", sel.mapped + " / " + sel.cells + " (" + Math.round(sel.mapped / sel.cells * 100) + "%)"],
            ["Rule evidence", sel.evid + " / " + sel.cells + " (" + Math.round(sel.evid / sel.cells * 100) + "%)"],
            ["Source tag", sel.source],
            ["Directive anchor", sel.anchor],
            ["Feeding workpaper", sel.code.replace("NBE/", "") + " sheet"], ["Owner", <span className="center gap8"><Avatar name={PEOPLE[sel.owner].name} size={20} /> {PEOPLE[sel.owner].name}</span>], ["Last updated", sel.updated],
          ]} /></div>
          <div className="section-label mt20 mb8">Cell map sample</div>
          <table className="tbl"><thead><tr><th>Return cell</th><th>Source / workpaper row</th><th>Rule</th></tr></thead>
            <tbody>
              {[["1.1 Total capital", sel.code.replace("NBE/", "") + " · row 11", "NBE CAR §6"], ["2.3 Weighted item", "Workpaper · mapped cell", "NBE ref"], ["3.1 Ratio", "Computed", "—"]].map((r, i) => (
                <tr key={i}><td className="mono" style={{ fontSize: 12 }}>{r[0]}</td><td>{r[1]}</td><td className="mono muted">{r[2]}</td></tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="drawer-foot">
          <button className="btn btn-ghost" onClick={() => go(sel.route)}><Icon name="arrowR" size={14} /> Open feeding workpaper</button>
          <button className="btn btn-dark" style={{ marginLeft: "auto" }} onClick={() => go("export")}>Export Gate <Icon name="arrowR" size={14} /></button>
        </div>
      </Drawer>}
    </div>
  );
}

function Cov2({ pct }) {
  const c = pct >= 100 ? "var(--green)" : pct >= 80 ? "var(--amber)" : "var(--red)";
  return <span className="center gap8" style={{ fontSize: 12 }}><span className="bar" style={{ width: 46 }}><span style={{ width: pct + "%", background: c }} /></span><b className="tnum">{pct}%</b></span>;
}
function SourceTag({ source, anchor }) {
  return <span className="col" style={{ gap: 2, alignItems: "flex-start", maxWidth: 190 }}><span className="mono" style={{ fontSize: 11.5, color: "var(--ink-2)" }}>{source}</span><span className="muted" style={{ fontSize: 11 }}>{anchor}</span></span>;
}
function Mini({ label, v, foot, tone }) {
  const c = { green: "var(--green-ink)", red: "var(--red)", indigo: "var(--indigo)" }[tone] || "var(--ink)";
  return <div className="card card-pad" style={{ padding: "15px 18px" }}><div className="section-label">{label}</div><div className="big-num tnum" style={{ marginTop: 6, color: c, fontSize: 26 }}>{v}</div><div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>{foot}</div></div>;
}

window.TemplateHub = TemplateHub;
