/* global React, Icon, StatusChip, Avatar, PageHeader, Banner, PEOPLE, etb */
const { useState: useStateM } = React;

const genHelp = (title, purpose, guardrail) => ({
  title, purpose, first: "Scan the readiness chips and any blocker banner before trusting a figure.",
  terms: [["Internal workpaper", "Analysis workspace, not an official calculation."], ["Blocker", "A gap holding a number back."]],
  next: ["Open a row to inspect source and evidence.", "Clear blockers via Exceptions."],
  connections: ["Sources come from the Data Harmonizer.", "Figures feed the export gate."],
  guardrail,
});

/* ---------- Capital Adequacy — single spreadsheet (NBE template) ---------- */
function Capital({ go, info }) {
  return (
    <div className="main-inner">
      <PageHeader eyebrow="Prudential Risk" title="Capital Adequacy" onInfo={() => info(genHelp("Capital Adequacy", "The NBE Capital Adequacy workbook, rendered live. CET1, AT1 and Tier 2 bridge to total regulatory capital and the CAR — every cell bound to source and rule evidence. Click Stress test to add severity columns.", "Internal capital workpaper. CAR is not an official NBE figure until evidence and approvals pass; workbook export stays blocked."))} />
      <CapitalTemplate go={go} />
    </div>
  );
}

/* ---------- (legacy analytical Capital — unused) ---------- */
function CapitalLegacy({ go, info }) {
  const [tview, setTview] = useStateM("NBE template");
  const rows = [
    { sec: "Common Equity Tier 1 (CET1)" },
    { l: "Paid-up capital", v: 32000, e: "RECONCILED" },
    { l: "Retained earnings", v: 9400, e: "RECONCILED" },
    { l: "Legal reserve", v: 6800, e: "RECONCILED" },
    { l: "less: Intangible assets", v: -1200, e: "REVIEW_PENDING" },
    { sub: "Total CET1", v: 47000 },
    { sec: "Additional Tier 1 (AT1)" },
    { l: "Perpetual instruments", v: 0, e: "MAPPED" },
    { sec: "Tier 2 capital" },
    { l: "Subordinated debt (eligible)", v: 5200, e: "REVIEW_PENDING" },
    { l: "General provisions (capped)", v: 2800, e: "EVIDENCE_NEEDED" },
    { sub: "Total Tier 2", v: 8000 },
    { tot: "Total regulatory capital", v: 55000 },
  ];
  return (
    <div className="main-inner">
      <PageHeader eyebrow="Prudential Risk" title="Capital Adequacy" onInfo={() => info(genHelp("Capital Adequacy", "Bridges CET1, AT1 and Tier 2 into total regulatory capital and the CAR. The NBE template view renders the official Capital Adequacy workbook row-for-row, with every cell bound to source and rule evidence.", "Internal capital workpaper. CAR is not an official NBE figure until evidence and approvals pass, and the workbook export stays blocked."))}
        right={<div className="seg-ctl">{["Analytical workpaper", "NBE template"].map(t => <button key={t} className={tview === t ? "on" : ""} onClick={() => setTview(t)}>{t}</button>)}</div>} />

      {tview === "NBE template" ? <CapitalTemplate go={go} /> : <React.Fragment>
      <div className="grid g4 mb20">
        <Mini label="Total capital" v={etb(55000)} foot="Br '000" tone="green" />
        <Mini label="Total RWA" v={etb(335000)} foot="Credit + market + op" />
        <Mini label="CAR (total)" v="16.4%" foot="NBE minimum 11%" tone="green" chip="REVIEW_PENDING" />
        <Mini label="CET1 ratio" v="14.0%" foot="Internal workpaper" tone="green" />
      </div>
      <div className="wp">
        <div className="wp-scroll"><table>
          <thead><tr><th style={{ minWidth: 340 }}>Component</th><th className="num">Amount (Br '000)</th><th>Evidence</th><th></th></tr></thead>
          <tbody>
            {rows.map((r, i) => {
              if (r.sec) return <tr key={i} className="section"><td colSpan="4">{r.sec}</td></tr>;
              if (r.sub) return <tr key={i} className="subtotal"><td>{r.sub}</td><td className="num tnum">{etb(r.v)}</td><td></td><td></td></tr>;
              if (r.tot) return <tr key={i} className="total"><td>{r.tot}</td><td className="num tnum">{etb(r.v)}</td><td></td><td></td></tr>;
              return <tr key={i} className="click"><td style={{ fontWeight: 500 }}>{r.l}</td><td className="num tnum" style={{ color: r.v < 0 ? "var(--red)" : "var(--ink)" }}>{etb(r.v)}</td><td><StatusChip s={r.e} /></td><td className="num">{r.e === "EVIDENCE_NEEDED" ? <button className="btn btn-ghost btn-sm" onClick={() => go("evidence")}>Attach rule</button> : <span className="jump">Trace <Icon name="arrowR" size={13} /></span>}</td></tr>;
            })}
          </tbody>
        </table></div>
      </div>
      <div className="mt16"><Banner kind="amber" icon="alert"><b>Deduction review pending.</b> Tier-2 general-provision cap needs an NBE reference, and the intangibles deduction awaits checker sign-off before this CAR can advance.</Banner></div>
      </React.Fragment>}
    </div>
  );
}

/* ---------- Credit Risk ---------- */
function Credit({ go, info }) {
  const rows = [
    { sec: "On-balance sheet exposures" },
    { l: "Sovereign (NBE / Govt)", ead: 28070, rw: "0%", rwa: 0, e: "RECONCILED" },
    { l: "Banks & financial inst.", ead: 14200, rw: "20%", rwa: 2840, e: "RECONCILED" },
    { l: "Corporate loans", ead: 96104, rw: "100%", rwa: 96104, e: "MAPPED" },
    { l: "Retail & SME", ead: 41300, rw: "75%", rwa: 30975, e: "MAPPED" },
    { l: "Past due (>90d)", ead: 6200, rw: "150%", rwa: 9300, e: "VALIDATION_FAILED" },
    { sec: "Off-balance sheet (after CCF)" },
    { l: "Guarantees & standby LCs", ead: 3920, rw: "CCF 50%", rwa: 1960, e: "EVIDENCE_NEEDED" },
    { l: "Trade-related contingents", ead: 5400, rw: "CCF 20%", rwa: 1080, e: "EVIDENCE_NEEDED" },
    { tot: "Total credit RWA", rwa: 142259 },
  ];
  return (
    <div className="main-inner">
      <PageHeader eyebrow="Prudential Risk" title="Credit Risk · RWA" onInfo={() => info(genHelp("Credit Risk", "Builds risk-weighted assets from on- and off-balance exposures with CRM, risk weights and CCF — each cell traceable to the loan and trade-finance sources.", "Internal RWA workpaper. CCF and CRM evidence are incomplete, so this RWA is not official."))}
        right={<button className="btn btn-ghost btn-sm" onClick={() => go("exceptions")}><Icon name="alertCirc" size={15} /> 6 blockers</button>} />
      <div style={{ marginBottom: 16 }}><Banner kind="amber" icon="alert"><b>CRM &amp; CCF evidence incomplete.</b> Off-balance conversion factors lack NBE references, and 312 loan rows failed validation. RWA shown is provisional.</Banner></div>
      <div className="wp"><div className="wp-scroll"><table>
        <thead><tr><th style={{ minWidth: 280 }}>Exposure class</th><th className="num">EAD (Br '000)</th><th className="num">Risk weight / CCF</th><th className="num">RWA</th><th>Evidence</th><th></th></tr></thead>
        <tbody>
          {rows.map((r, i) => {
            if (r.sec) return <tr key={i} className="section"><td colSpan="6">{r.sec}</td></tr>;
            if (r.tot) return <tr key={i} className="total"><td>{r.tot}</td><td></td><td></td><td className="num tnum">{etb(r.rwa)}</td><td></td><td></td></tr>;
            return <tr key={i} className="click"><td style={{ fontWeight: 500 }}>{r.l}</td><td className="num tnum">{etb(r.ead)}</td><td className="num">{r.rw}</td><td className="num tnum" style={{ fontWeight: 600 }}>{etb(r.rwa)}</td><td><StatusChip s={r.e} /></td><td className="num">{(r.e === "EVIDENCE_NEEDED" || r.e === "VALIDATION_FAILED") ? <button className="btn btn-ghost btn-sm" style={{ color: "var(--red)", borderColor: "var(--red-line)" }} onClick={() => go("exceptions")}>Resolve</button> : <span className="jump">Trace <Icon name="arrowR" size={13} /></span>}</td></tr>;
          })}
        </tbody>
      </table></div></div>
    </div>
  );
}

/* ---------- Market / FX · NOP ---------- */
function Market({ go, info }) {
  const rows = [["USD", 142.0, 18400, 12200, 6200], ["EUR", 154.3, 7100, 5400, 1700], ["GBP", 178.1, 2300, 2050, 250], ["CNY", 19.6, 4800, 4300, 500], ["Other", "—", 1900, 1500, 400]];
  const netLong = 9050, capital = 112000, nop = ((netLong / capital) * 100).toFixed(1);
  return (
    <div className="main-inner">
      <PageHeader eyebrow="Prudential Risk" title="Market / FX · Open Position" onInfo={() => info(genHelp("Market / FX · NOP", "The net open position workpaper — currency-by-currency long/short, reconciled to the Tier-1 FX blotter, measured against the NBE single-currency and aggregate limits.", "Internal NOP workpaper. Reconciled to source, but official NBE NOP export remains gated."))}
        right={<span className="center gap8"><StatusChip s="RECONCILED" lg /><button className="btn btn-ghost btn-sm" onClick={() => go("stress")}><Icon name="flask" size={15} /> Stress</button></span>} />
      <div className="grid g4 mb20">
        <Mini label="Net open position" v={etb(netLong)} foot="Aggregate long · Br '000" tone="green" />
        <Mini label="NOP / capital" v={nop + "%"} foot="NBE limit 15%" tone="green" />
        <Mini label="Largest single ccy" v="USD" foot="Br 6,200 long" />
        <Mini label="Limit headroom" v="6.9%" foot="Within limit" tone="green" />
      </div>
      <div className="wp"><div className="wp-scroll"><table>
        <thead><tr><th>Currency</th><th className="num">Rate (ETB)</th><th className="num">Assets</th><th className="num">Liabilities</th><th className="num">Net position</th><th>State</th></tr></thead>
        <tbody>
          {rows.map((r, i) => <tr key={i} className="click"><td style={{ fontWeight: 600 }}>{r[0]}</td><td className="num tnum">{r[1]}</td><td className="num tnum">{etb(r[2])}</td><td className="num tnum">{etb(r[3])}</td><td className="num tnum" style={{ fontWeight: 700, color: "var(--green-ink)" }}>+{etb(r[4])}</td><td><StatusChip s="RECONCILED" /></td></tr>)}
          <tr className="total"><td>Aggregate</td><td></td><td className="num tnum">{etb(34500)}</td><td className="num tnum">{etb(25450)}</td><td className="num tnum">+{etb(netLong)}</td><td></td></tr>
        </tbody>
      </table></div></div>
      <div className="mt16"><Banner kind="green" icon="checkCirc"><b>Reconciled to the Tier-1 FX blotter (Murex).</b> Within NBE single-currency (10%) and aggregate (15%) limits. Note: under the FX-depreciation stress scenario this position breaches — see Stress Lab.</Banner></div>
    </div>
  );
}

/* ---------- Operational Risk (config-required) ---------- */
function OpRisk({ go, info }) {
  return (
    <div className="main-inner">
      <PageHeader eyebrow="Prudential Risk" title="Operational Risk" onInfo={() => info(genHelp("Operational Risk", "Basic Indicator Approach capital from gross income, with loss-event context. Requires a contracted data source before any figure is computed.", "No official impact is computed because the source contract is missing. Synthetic seed data is internal-only."))} />
      <div style={{ maxWidth: 720, margin: "30px auto 0", textAlign: "center" }}>
        <div style={{ width: 64, height: 64, borderRadius: 16, background: "var(--surface-2)", border: "1px solid var(--border)", display: "grid", placeItems: "center", margin: "0 auto 18px", color: "var(--ink-3)" }}><Icon name="briefcase" size={30} /></div>
        <h2 style={{ fontSize: 22, fontWeight: 800, margin: "0 0 8px" }}>Configuration required</h2>
        <p className="muted" style={{ fontSize: 14.5, lineHeight: 1.55, margin: "0 0 22px" }}>The Basic Indicator Approach needs a gross-income schedule and a loss-event register. Neither is contracted for this entity, so <b>no official impact is computed</b>.</p>
        <div style={{ textAlign: "left" }}>
          {[["Gross income schedule (3-yr)", "SOURCE_MISSING", "Not contracted"], ["Operational loss-event register", "SYNTHETIC", "Synthetic seed only"], ["BIA alpha factor reference", "EVIDENCE_NEEDED", "NBE reference not attached"]].map((r, i) => (
            <div key={i} className="cl"><span className="cl-ic" style={{ background: "var(--surface-2)", color: "var(--ink-2)" }}><Icon name={i === 1 ? "flask" : "database"} size={15} /></span>
              <div className="grow"><div style={{ fontWeight: 600, fontSize: 13.5 }}>{r[0]}</div><div className="muted" style={{ fontSize: 12 }}>{r[2]}</div></div><StatusChip s={r[1]} /></div>
          ))}
        </div>
        <div className="center gap10" style={{ justifyContent: "center", marginTop: 22 }}>
          <button className="btn btn-ghost" onClick={() => go("harmonizer")}><Icon name="database" size={15} /> Configure data contract</button>
          <button className="btn btn-primary" onClick={() => go("control")}>Back to Control Room</button>
        </div>
      </div>
    </div>
  );
}

/* ---------- shared Mini stat ---------- */
function Mini({ label, v, foot, tone, chip }) {
  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="between"><div className="section-label">{label}</div>{chip && <StatusChip s={chip} />}</div><div className="big-num tnum" style={{ marginTop: 6, color: c }}>{v}</div><div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>{foot}</div></div>;
}

Object.assign(window, { Capital, Credit, Market, OpRisk });
