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

/* ============================================================
   Emergency Liquidity Assistance (NBE/ELA/001/2024)
   NBE lender-of-last-resort. Connects to Recovery Layer 3.
   Eligibility gate · collateral pool & haircuts · application pack ·
   tenor/rate/margin. Internal workflow — no funds move here.
   ============================================================ */

// the seven minimum eligibility criteria (Art. 8)
const ELA_ELIG = [
  { c: "Solvent & viable on a forward-looking basis", state: "RECONCILED", note: "CAR 13.0% vs 11% min · projected above minima" },
  { c: "Experiencing temporary liquidity challenges", state: "RECONCILED", note: "Stressed LCR 142% trending to floor under deposit-run scenario" },
  { c: "Exhausted interbank & NBE standing facilities", state: "REVIEW_PENDING", note: "Interbank tapped; standing facility evidence pending" },
  { c: "Liquidity Contingency Plan activated & failed", state: "REVIEW_PENDING", note: "LCP invoked Jun 28; residual gap remains" },
  { c: "Eligible collateral adequate to secure exposure", state: "RECONCILED", note: "Br 18,200M post-haircut vs Br 12,000M request" },
  { c: "Fit-and-proper shareholders, directors, management", state: "RECONCILED", note: "Confirmed per NBE fit-and-proper directive" },
  { c: "Shareholder / parent liquidity attempts evidenced", state: "EVIDENCE_NEEDED", evLabel: "Evidence needed", note: "Evidence of shareholder support request not attached" },
];

// eligible collateral pool (Art. 6) with NBE haircuts (Art. 11)
const ELA_COLLATERAL = [
  { no: "1", asset: "Government T-bills & FDRE bonds", market: 9650, haircut: 5, eligible: 9168 },
  { no: "2", asset: "NBE debt instruments", market: 4200, haircut: 2, eligible: 4116 },
  { no: "3", asset: "Federal-government-guaranteed bonds", market: 3800, haircut: 10, eligible: 3420 },
  { no: "4", asset: "Eligible corporate bonds", market: 2100, haircut: 25, eligible: 1575 },
];

// application pack (Art. 9) — board-signed request checklist
const ELA_PACK = [
  { item: "Written request signed by Board Chair", done: true },
  { item: "Signed board minutes approving ELA need", done: true },
  { item: "List of maturing debt obligations & deposits", done: true },
  { item: "Causes & persistence of liquidity challenge", done: true },
  { item: "Board-approved Liquidity Contingency Plan + activation", done: false },
  { item: "Weekly liquidity-gap analysis + exit strategy", done: true },
  { item: "Daily ELA utilisation plan", done: false },
  { item: "Evidence of shareholder/parent liquidity attempts", done: false },
];

function ELA({ go, info }) {
  const [drawer, setDrawer] = useStateELA(null);
  const [life, setLife] = useStateELA(null);
  const [actionNode, openAction] = useActionDrawer();
  const [toastNode, showToast] = useToast();
  const reqAmount = 12000;
  const totalEligible = ELA_COLLATERAL.reduce((a, c) => a + c.eligible, 0);
  const coverage = (totalEligible / reqAmount * 100).toFixed(0);
  const eligPass = ELA_ELIG.filter(e => e.state === "RECONCILED").length;
  const packDone = ELA_PACK.filter(p => p.done).length;
  const slfRate = 16, elaRate = slfRate + 2;  // standing facility + 2pp (Art. 13.3)
  const elaBlocked = eligPass < ELA_ELIG.length || packDone < ELA_PACK.length;

  return (
    <div className="main-inner">
      <PageHeader eyebrow="Governance · Crisis management" title="Emergency Liquidity Assistance"
        onInfo={() => info({ title: "Emergency Liquidity Assistance (ELA)", purpose: "NBE's lender-of-last-resort facility (NBE/ELA/001/2024) for a solvent bank facing temporary liquidity strain. This surface assembles the eligibility gate, the collateral pool with NBE haircuts, and the board-signed application pack — the Layer-3 escalation from Recovery Planning.", first: "ELA is only for a solvent, viable bank that has exhausted the interbank market and activated its LCP. Read the eligibility gate first; a single failed criterion blocks the application.", terms: [["Solvent & viable", "Meets the minimum CAR on a forward-looking basis."], ["Eligible collateral", "Govt/NBE debt, guaranteed & corporate bonds — post-haircut."], ["Haircut", "% reduction NBE applies to collateral value."], ["Margin call", "Request for more collateral if its value falls."]], next: ["Complete the eligibility criteria and application pack.", "Confirm collateral covers the request plus haircut and interest.", "Submit the board-signed bilateral request to NBE."], connections: ["Triggered by Recovery Planning Layer 3 (Board + NBE).", "Solvency reads from Capital Adequacy; the gap from Stress Lab.", "Collateral ties to the HQLA / securities source."], guardrail: "Internal workflow only — no funds move and NBE approval is at NBE's sole discretion. ELA is a temporary advance (max 6 months), fully collateralised, at the standing-facility rate + 2pp." })}
        right={<span className="center gap8"><StatusChip s="REVIEW_PENDING" lg /><button className="btn btn-ghost btn-sm" onClick={() => go("recovery")}><Icon name="arrowR" size={14} style={{ transform: "rotate(180deg)" }} /> Back to Recovery L3</button></span>} />

      <div style={{ marginBottom: 18 }}><Banner kind="indigo" icon="refresh"><b>Lender-of-last-resort workflow.</b> ELA is the Layer-3 escalation: a temporary, fully-collateralised Birr advance to a <b>solvent</b> bank that has exhausted all other options. Provision is at NBE's sole discretion — this surface prepares the bilateral request; no funds move here.</Banner></div>

      <div className="grid g4 mb20">
        <Mini label="Requested amount" v={etb(reqAmount)} foot="ETB M · per liquidity gap" />
        <Mini label="Eligible collateral" v={etb(totalEligible)} foot="After NBE haircuts" tone="green" />
        <Mini label="Collateral coverage" v={coverage + "%"} foot="Must exceed 100% + interest" tone={coverage >= 100 ? "green" : "red"} />
        <Mini label="ELA rate" v={elaRate + "%"} foot="Standing facility +2pp · max 6mo" />
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1.1fr 1fr", gap: 18, alignItems: "start" }}>
        {/* eligibility gate */}
        <div className="card card-pad">
          <div className="panel-h"><h3 style={{ fontSize: 15 }}>Eligibility gate</h3><span className={"chip " + (eligPass === ELA_ELIG.length ? "chip-green" : "chip-amber")} style={{ marginLeft: "auto" }}>{eligPass}/{ELA_ELIG.length} met</span></div>
          {ELA_ELIG.map((e, i) => (
            <div key={i} className="cl" style={{ cursor: "pointer" }} onClick={() => setDrawer({ elig: e })}>
              <span className="cl-ic" style={{ background: e.state === "RECONCILED" ? "var(--green-soft)" : e.state === "EVIDENCE_NEEDED" ? "var(--red-soft)" : "var(--amber-soft)", color: e.state === "RECONCILED" ? "var(--green-ink)" : e.state === "EVIDENCE_NEEDED" ? "var(--red)" : "var(--amber)" }}><Icon name={e.state === "RECONCILED" ? "check" : "clock"} size={15} /></span>
              <div className="grow"><div style={{ fontWeight: 600, fontSize: 13 }}>{e.c}</div><div className="muted" style={{ fontSize: 11.5 }}>{e.note}</div></div>
              {e.evLabel ? <span className="chip chip-red"><span className="dot" />{e.evLabel}</span> : <StatusChip s={e.state} />}
            </div>
          ))}
          <div className="mt12"><Banner kind="amber" icon="lock"><b>Solvency is the gate.</b> ELA is for illiquidity, never insolvency — a non-viable bank is ineligible. One unmet criterion blocks the request.</Banner></div>
        </div>

        {/* collateral + application pack */}
        <div className="col" style={{ gap: 18 }}>
          <div className="card">
            <div className="panel-h" style={{ padding: "16px 18px 0" }}><h3 style={{ fontSize: 15 }}>Eligible collateral pool</h3></div>
            <table className="tbl" style={{ marginTop: 8 }}>
              <thead><tr><th>Asset</th><th className="num">Market</th><th className="num">Haircut</th><th className="num">Eligible</th></tr></thead>
              <tbody>
                {ELA_COLLATERAL.map(c => (
                  <tr key={c.no} className="click" onClick={() => setDrawer({ coll: c })}>
                    <td style={{ fontWeight: 600 }}>{c.asset}</td>
                    <td className="num tnum">{etb(c.market)}</td>
                    <td className="num tnum" style={{ color: "var(--red)" }}>−{c.haircut}%</td>
                    <td className="num tnum" style={{ fontWeight: 700, color: "var(--green-ink)" }}>{etb(c.eligible)}</td>
                  </tr>
                ))}
                <tr style={{ background: "var(--surface-2)", fontWeight: 700 }}><td>Total eligible (post-haircut)</td><td className="num tnum">{etb(ELA_COLLATERAL.reduce((a, c) => a + c.market, 0))}</td><td></td><td className="num tnum">{etb(totalEligible)}</td></tr>
              </tbody>
            </table>
          </div>

          <div className="card card-pad">
            <div className="panel-h"><h3 style={{ fontSize: 15 }}>Application pack</h3><span className={"chip " + (packDone === ELA_PACK.length ? "chip-green" : "chip-amber")} style={{ marginLeft: "auto" }}>{packDone}/{ELA_PACK.length}</span></div>
            {ELA_PACK.map((p, i) => (
              <div key={i} className="center gap10" style={{ padding: "7px 0", borderBottom: i < ELA_PACK.length - 1 ? "1px solid var(--border)" : "none" }}>
                <span style={{ width: 20, height: 20, borderRadius: 5, background: p.done ? "var(--green)" : "var(--surface-2)", color: p.done ? "#fff" : "var(--ink-4)", display: "grid", placeItems: "center", border: p.done ? "none" : "1.5px solid var(--border-dark)", flex: "0 0 auto" }}>{p.done ? <Icon name="check" size={12} /> : ""}</span>
                <span style={{ fontSize: 12.5, color: p.done ? "var(--ink)" : "var(--ink-3)" }}>{p.item}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="mt20 between" style={{ alignItems: "center" }}>
        <div className="muted" style={{ fontSize: 12.5 }}>Tenor max 6 months (renewable once) · rate {elaRate}% · margin call if collateral value falls · default penalty +5pp / 30 days.</div>
        <button className="btn btn-dark" onClick={() => openAction(elaBlocked ? {
          title: "ELA request blocked",
          sub: "Complete eligibility gate and application pack",
          chip: <StatusChip s="EXPORT_BLOCKED" />,
          kind: "red",
          icon: "lock",
          banner: <span><b>The bilateral request cannot be prepared yet.</b> ELA requires every eligibility criterion and pack item to be complete.</span>,
          rows: [["Eligibility gate", eligPass + " / " + ELA_ELIG.length + " met"], ["Application pack", packDone + " / " + ELA_PACK.length + " complete"], ["Requested amount", etb(reqAmount) + " M"], ["Collateral coverage", coverage + "%"]],
          items: ELA_ELIG.filter(e => e.state !== "RECONCILED").map(e => ({ title: e.c, body: e.note, icon: "alert" })).concat(ELA_PACK.filter(p => !p.done).map(p => ({ title: p.item, body: "Application pack item pending", icon: "fileText" }))),
          guardrail: "No funds move here. ELA approval is at NBE's sole discretion.",
        } : {
          title: "Submit bilateral request",
          sub: "Internal request pack",
          chip: <StatusChip s="REVIEW_PENDING" />,
          banner: <span><b>ELA request pack staged for internal review.</b> This prepares the checklist and collateral summary only.</span>,
          rows: [["Requested amount", etb(reqAmount) + " M"], ["Eligible collateral", etb(totalEligible) + " M"], ["Rate", elaRate + "%"], ["Tenor", "Max 6 months"]],
          guardrail: "This workspace does not send a request to NBE and does not move funds.",
        })}><Icon name="lock" size={15} /> {elaBlocked ? "Blocked — complete gate & pack" : "Submit bilateral request to NBE"}</button>
      </div>

      {/* active facility lifecycle (illustrative — no funds move) */}
      <div className="card card-pad mt20">
        <div className="panel-h"><h3 style={{ fontSize: 15 }}>Active facility lifecycle</h3><span className="chip chip-amber" style={{ marginLeft: "auto" }}>Illustrative · no funds move</span></div>
        <div className="grid g3" style={{ gap: 14 }}>
          <div className="card card-pad" style={{ padding: "14px 16px", cursor: "pointer" }} onClick={() => setLife("margin")}>
            <div className="center gap8" style={{ color: "var(--amber)" }}><Icon name="alert" size={16} /><b style={{ fontSize: 13.5 }}>Margin call</b></div>
            <div className="muted" style={{ fontSize: 12, marginTop: 6, lineHeight: 1.45 }}>If collateral value falls below the agreed amount, NBE calls for additional eligible collateral (Art. 12).</div>
            <span className="jump mt8">Open <Icon name="arrowR" size={13} /></span>
          </div>
          <div className="card card-pad" style={{ padding: "14px 16px", cursor: "pointer" }} onClick={() => setLife("rollover")}>
            <div className="center gap8" style={{ color: "var(--indigo)" }}><Icon name="refresh" size={16} /><b style={{ fontSize: 13.5 }}>Rollover</b></div>
            <div className="muted" style={{ fontSize: 12, marginTop: 6, lineHeight: 1.45 }}>One renewal up to 6 months under pre-conditions, applied ≥ 10 working days before maturity (Art. 14).</div>
            <span className="jump mt8">Open <Icon name="arrowR" size={13} /></span>
          </div>
          <div className="card card-pad" style={{ padding: "14px 16px", cursor: "pointer" }} onClick={() => setLife("monitor")}>
            <div className="center gap8" style={{ color: "var(--slate)" }}><Icon name="eye" size={16} /><b style={{ fontSize: 13.5 }}>Enhanced monitoring</b></div>
            <div className="muted" style={{ fontSize: 12, marginTop: 6, lineHeight: 1.45 }}>Frequent reporting against the Liquidity Restoration Plan until the ELA is fully repaid (Art. 15).</div>
            <span className="jump mt8">Open <Icon name="arrowR" size={13} /></span>
          </div>
        </div>
      </div>

      {drawer && <Drawer open={!!drawer} onClose={() => setDrawer(null)}>
        {drawer.elig ? <React.Fragment>
          <DrawerHead title="Eligibility criterion" sub="NBE/ELA Art. 8" chip={<StatusChip s={drawer.elig.state} />} onClose={() => setDrawer(null)} />
          <div className="drawer-body">
            <Banner kind={drawer.elig.state === "RECONCILED" ? "green" : drawer.elig.state === "EVIDENCE_NEEDED" ? "red" : "amber"} icon={drawer.elig.state === "RECONCILED" ? "checkCirc" : "alert"}>{drawer.elig.c}</Banner>
            <div className="mt16"><Meta rows={[["Status", <StatusChip s={drawer.elig.state} />], ["Basis", drawer.elig.note], ["Source", "Capital Adequacy · Stress Lab · LCP"], ["Owner", <span className="center gap8"><Avatar name="Hana Girma" size={20} /> Hana Girma</span>]]} /></div>
          </div>
          <div className="drawer-foot"><button className="btn btn-ghost" onClick={() => go("capital")}><Icon name="arrowR" size={14} /> Solvency evidence</button><button className="btn btn-dark" style={{ marginLeft: "auto" }} onClick={() => setDrawer(null)}>Done</button></div>
        </React.Fragment> : <React.Fragment>
          <DrawerHead title={drawer.coll.asset} sub="Eligible collateral · NBE/ELA Art. 6" chip={<StatusChip s="RECONCILED" />} onClose={() => setDrawer(null)} />
          <div className="drawer-body">
            <Meta rows={[["Market value", etb(drawer.coll.market) + " M"], ["NBE haircut", drawer.coll.haircut + "%"], ["Eligible value", etb(drawer.coll.eligible) + " M"], ["Conditions", "Unencumbered · owned by bank · maturity beyond ELA"], ["Margin call", "Triggered if value falls below agreed amount"]]} />
            <div className="mt16"><Banner kind="indigo" icon="info">Collateral must be the bank's property, unencumbered, and mature later than the ELA. Public-debt and NBE instruments are eligible even if related-party.</Banner></div>
          </div>
          <div className="drawer-foot"><button className="btn btn-dark" style={{ marginLeft: "auto" }} onClick={() => setDrawer(null)}>Done</button></div>
        </React.Fragment>}
      </Drawer>}

      {life && <Drawer open={!!life} onClose={() => setLife(null)}>
        {life === "margin" && <React.Fragment>
          <DrawerHead title="Margin call" sub="NBE/ELA Art. 12 · illustrative" chip={<span className="chip chip-amber"><span className="dot" />Collateral shortfall</span>} onClose={() => setLife(null)} />
          <div className="drawer-body">
            <Banner kind="amber" icon="alert"><b>Collateral value has fallen below the agreed amount.</b> NBE calls for additional eligible collateral to restore full coverage plus haircut and interest.</Banner>
            <div className="mt16"><Meta rows={[["Agreed coverage", "Br 18,279 M"], ["Current value (after move)", "Br 16,540 M"], ["Shortfall", <span style={{ color: "var(--red)", fontWeight: 700 }}>Br 1,739 M</span>], ["Eligible collateral to post", "Govt / NBE / guaranteed bonds"], ["Response window", "Per bilateral agreement"]]} /></div>
            <div className="mt16"><Banner kind="indigo" icon="info">Illustrative workflow — no collateral is actually moved here. Posting is recorded as management intent against the bilateral agreement.</Banner></div>
          </div>
          <div className="drawer-foot"><button className="btn btn-ghost" onClick={() => setLife(null)}>Defer</button><button className="btn btn-primary" style={{ marginLeft: "auto" }} onClick={() => setLife(null)}>Post additional collateral</button></div>
        </React.Fragment>}
        {life === "rollover" && <React.Fragment>
          <DrawerHead title="Rollover request" sub="NBE/ELA Art. 14 · illustrative" chip={<StatusChip s="REVIEW_PENDING" />} onClose={() => setLife(null)} />
          <div className="drawer-body">
            <Banner kind="indigo" icon="refresh">A single renewal of up to 6 months may be allowed under exceptional circumstances. Pre-conditions must all be met.</Banner>
            <div className="section-label mt16 mb8">Rollover pre-conditions (Art. 14)</div>
            {[["Signed application from Board Chair", true], ["Signed Board minutes authorising rollover", true], ["Filed ≥ 10 working days before maturity", true], ["Solvent & viable on forward-looking basis", true], ["Adequate eligible collateral", true], ["Improvement shown since first ELA", false]].map((c, i) => (
              <div key={i} className="center gap10" style={{ padding: "8px 0", borderBottom: "1px solid var(--border)" }}><span style={{ width: 20, height: 20, borderRadius: 5, background: c[1] ? "var(--green)" : "var(--amber-soft)", color: c[1] ? "#fff" : "var(--amber)", display: "grid", placeItems: "center", flex: "0 0 auto" }}><Icon name={c[1] ? "check" : "clock"} size={12} /></span><span style={{ fontSize: 13 }}>{c[0]}</span></div>
            ))}
            <div className="mt12"><Banner kind="amber" icon="alert">One pre-condition is pending — the bank must evidence improvement in its liquidity position since the first ELA.</Banner></div>
          </div>
          <div className="drawer-foot"><span className="muted center gap6" style={{ fontSize: 12 }}><Icon name="clock" size={14} /> Max 6-month renewal</span><button className="btn btn-dark" style={{ marginLeft: "auto" }} onClick={() => showToast("Rollover blocked: improvement evidence is pending")}>Submit rollover (1 pending)</button></div>
        </React.Fragment>}
        {life === "monitor" && <React.Fragment>
          <DrawerHead title="Enhanced monitoring" sub="NBE/ELA Art. 15 · illustrative" chip={<span className="chip chip-slate"><span className="dot" />Active oversight</span>} onClose={() => setLife(null)} />
          <div className="drawer-body">
            <Banner kind="indigo" icon="eye">While ELA is outstanding the bank is under enhanced supervisory oversight — more frequent reporting against its Liquidity Restoration Plan.</Banner>
            <div className="mt16"><Meta rows={[["Reporting frequency", "Weekly liquidity-gap analysis"], ["Restoration plan", "On track · 2 of 5 milestones met"], ["Next NBE review", "In 7 days"], ["Repayment", "Principal + interest at maturity (Art. 16)"]]} /></div>
          </div>
          <div className="drawer-foot"><button className="btn btn-dark" style={{ marginLeft: "auto" }} onClick={() => setLife(null)}>Done</button></div>
        </React.Fragment>}
      </Drawer>}
      {actionNode}
      {toastNode}
    </div>
  );
}

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.ELA = ELA;
