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

/* ============================================================
   Recovery Planning — NBE recovery doctrine
   "Before things get dire, what are you doing?"
   Recovery indicators with a 3-zone threshold ladder, a menu of
   NBE-recognised recovery options with quantified capacity, and the
   escalation chain across management layers. Internal workflow only.
   ============================================================ */

// Recovery indicators — each with green/amber/red thresholds and a live value
const REC_INDICATORS = [
  { key: "car", name: "Capital Adequacy Ratio", unit: "%", live: 13.0, recovery: 11.0, escalate: 9.0, dir: "down", live2: 11.2, note: "stressed" },
  { key: "lcr", name: "Liquidity Coverage Ratio", unit: "%", live: 265, recovery: 110, escalate: 100, dir: "down", live2: 142, note: "stressed" },
  { key: "nop", name: "Net Open Position / Tier-1", unit: "%", live: 7.3, recovery: 15, escalate: 18, dir: "up", live2: 16.7, note: "stressed" },
  { key: "dep", name: "Deposit concentration (top-20)", unit: "%", live: 28, recovery: 35, escalate: 45, dir: "up", live2: 41, note: "stressed" },
];
// zone for a value given thresholds + direction
function zoneOf(ind, v) {
  if (ind.dir === "down") return v <= ind.escalate ? "red" : v <= ind.recovery ? "amber" : "green";
  return v >= ind.escalate ? "red" : v >= ind.recovery ? "amber" : "green";
}
const ZTXT = { green: ["Normal", "var(--green-ink)", "var(--green-soft)"], amber: ["Recovery zone", "var(--amber)", "var(--amber-soft)"], red: ["Escalation", "var(--red)", "var(--red-soft)"] };

// NBE-recognised recovery options — menu with quantified capacity & lead time
const REC_OPTIONS = [
  { no: "1", name: "Activate committed liquidity lines / ordinary standing facilities", lever: "Liquidity", category: "Liability management", capacity: "+Br 6,400 M HQLA", metric: "LCR +58pp", lead: "Same day", owner: "dawit", layer: 1, state: "RECONCILED" },
  { no: "2", name: "Sell / repo Level-1 HQLA (T-bills, FDRE bonds)", lever: "Liquidity", capacity: "+Br 9,650 M cash", metric: "LCR +88pp", lead: "1–2 days", owner: "dawit", layer: 1, state: "RECONCILED" },
  { no: "3", name: "Close speculative FX longs", lever: "Market", capacity: "−Br 540 M NOP", metric: "NOP −2.1pp", lead: "Same day", owner: "abel", layer: 1, state: "REVIEW_PENDING" },
  { no: "4", name: "Issue FX-matched term deposits", lever: "Market", capacity: "−Br 230 M NOP", metric: "NOP −0.9pp", lead: "1 week", owner: "abel", layer: 2, state: "REVIEW_PENDING" },
  { no: "5", name: "Suspend dividend / retain earnings", lever: "Capital", capacity: "+Br 1,800 M CET1", metric: "CAR +1.9pp", lead: "Board cycle", owner: "hana", layer: 2, state: "NEEDS_BANK_POLICY" },
  { no: "6", name: "Raise Tier-2 subordinated debt", lever: "Capital", capacity: "+Br 3,000 M T2", metric: "CAR +3.1pp", lead: "1–3 months", owner: "meron", layer: 3, state: "EVIDENCE_NEEDED" },
  { no: "7", name: "Rights issue / new equity", lever: "Capital", capacity: "+Br 5,000 M CET1", metric: "CAR +5.2pp", lead: "3–6 months", owner: "hana", layer: 3, state: "OFFICIAL_FUTURE" },
  { no: "8", name: "Deleverage — slow new lending growth", lever: "Capital", capacity: "−Br 8,000 M RWA", metric: "CAR +0.9pp", lead: "1 quarter", owner: "meron", layer: 2, state: "REVIEW_PENDING" },
];

// escalation layers — who acts, when it passes up
const REC_LAYERS = [
  { layer: 1, name: "Treasury / ALCO desk", who: ["dawit", "abel"], trigger: "Indicator enters Recovery zone", mandate: "Execute Layer-1 liquidity & market options within delegated limits", sla: "Same day" },
  { layer: 2, name: "ALCO + Risk Committee", who: ["hana", "meron"], trigger: "Layer-1 insufficient OR indicator deteriorating", mandate: "Capital conservation, deleveraging, deposit actions", sla: "48 hours" },
  { layer: 3, name: "Board + NBE notification", who: ["hana"], trigger: "Indicator breaches Escalation threshold", mandate: "Capital raise, recovery-plan activation, regulator engagement", sla: "5 working days max" },
];

const REC_PLAN_SECTIONS = [
  { no: "1", title: "Executive Summary", items: "Background, Recovery Plan, scope, material changes" },
  { no: "2", title: "Strategic and Governance Analysis", items: "Business model, critical functions, governance, oversight, risk management" },
  { no: "3", title: "Core of Recovery Plan", items: "Triggers, indicators, scenarios, options, contingency, communication" },
  { no: "4", title: "Implementation Strategies", items: "Actions, owners, timing, impediments, resource needs" },
];

const REC_INDICATOR_CATALOG = [
  { cat: "Capital", examples: "CAR, CET1 ratio, Tier 1 ratio, total capital ratio, leverage ratio" },
  { cat: "Liquidity", examples: "Liquidity ratio, reserve ratio, LCR, NSFR, loan-to-deposit, cost of funds, wholesale concentration" },
  { cat: "Profitability", examples: "ROA, ROE, net interest margin, cost-to-income, operational-risk loss" },
  { cat: "Asset quality", examples: "NPL ratio, impaired loans, loan-loss coverage, provision coverage, sector concentration" },
  { cat: "Operational risk", examples: "Critical-system downtime, cyber incidents, staff turnover, compliance breaches" },
  { cat: "Market / macro", examples: "Price-to-book, share volatility, credit rating, GDP/employment/sector indicators" },
];

const REC_OPTION_ASSESSMENT = [
  "Expected financial impact: capital, liquidity and other effects",
  "Operational benefits, side effects and systemic consequences",
  "Implementation time, resources and execution owner",
  "Potential impediments and remediation actions",
  "Implementation costs and option-specific communications",
  "Business continuity support needed to execute the option",
];

function Recovery({ go, info }) {
  const [opt, setOpt] = useStateRec(null);
  const [layerOpen, setLayerOpen] = useStateRec(null);
  const [actionNode, openAction] = useActionDrawer();
  const [toastNode, showToast] = useToast();
  // current active stress posture: how many indicators are in recovery/escalation
  const stressedZones = REC_INDICATORS.map(i => zoneOf(i, i.live2));
  const inEscalation = stressedZones.filter(z => z === "red").length;
  const inRecovery = stressedZones.filter(z => z === "amber").length;
  const activeLayer = inEscalation > 0 ? 3 : inRecovery > 0 ? 2 : 1;

  return (
    <div className="main-inner">
      <PageHeader eyebrow="Governance" title="Recovery Planning"
        onInfo={() => info({ title: "Recovery Planning", purpose: "The bank's pre-agreed answer to NBE's question: 'before things get dire, what are you doing?' Recovery indicators carry threshold ladders (Normal → Recovery → Escalation); each zone unlocks a menu of NBE-recognised recovery options with quantified capacity; and deterioration escalates across defined management layers.", first: "Read the indicator ladder — any amber/red indicator activates the matching recovery layer. The options menu shows how much capacity each measure restores and who owns it.", terms: [["Recovery indicator", "A metric with pre-set thresholds that triggers the plan."], ["Recovery option", "A pre-agreed management action with quantified capacity."], ["Escalation layer", "Which management tier owns the response."]], next: ["Review which indicators are in the recovery/escalation zone.", "Select recovery options and see aggregate capacity vs the gap.", "Escalate to the next management layer if Layer-1 is insufficient."], connections: ["Indicators are driven by Stress Lab scenarios.", "Options reference Capital / LCR / NOP workpapers.", "Activation compiles a Board / NBE recovery pack."], guardrail: "Internal workflow only. Recovery options are documented management intent — they do not execute transactions or change official numbers." })}
        right={<span className="center gap8"><span className={"chip chip-lg " + (activeLayer === 3 ? "chip-red" : activeLayer === 2 ? "chip-amber" : "chip-green")}><span className="dot" />Layer {activeLayer} active</span><button className="btn btn-ghost btn-sm" onClick={() => go("stress")}><Icon name="flask" size={15} /> Stress Lab</button></span>} />

      <div style={{ marginBottom: 18 }}><Banner kind="indigo" icon="refresh"><b>Internal recovery playbook.</b> This is the bank's pre-agreed answer to NBE: which measures, how much capacity, who acts, and when it escalates — documented management intent, not transaction execution.</Banner></div>
      <div className="mt12 mb20"><Banner kind="amber" icon="lock"><b>Directive guardrail.</b> Recovery options assume no extraordinary NBE or government financial support. Any public external communication requires NBE consent before release.</Banner></div>

      <div className="panel-h"><h3 style={{ fontSize: 15 }}>NBE recovery plan structure</h3><span className="sub">SBB/93/2025 · required content map</span></div>
      <div className="grid g4 mb24" style={{ gap: 14 }}>
        {REC_PLAN_SECTIONS.map(s => (
          <div key={s.no} className="card card-pad" style={{ padding: "15px 16px" }}>
            <div className="between"><span className="chip chip-neutral">{s.no}</span><StatusChip s="REVIEW_PENDING" /></div>
            <div style={{ fontWeight: 750, fontSize: 13.5, marginTop: 10 }}>{s.title}</div>
            <div className="muted" style={{ fontSize: 11.5, marginTop: 5, lineHeight: 1.45 }}>{s.items}</div>
          </div>
        ))}
      </div>

      <div className="panel-h"><h3 style={{ fontSize: 15 }}>Annex II indicator catalog</h3><span className="sub">quantitative triggers sit above prudential floors; early warnings calibrate before breach</span></div>
      <div className="grid g3 mb24" style={{ gap: 14 }}>
        {REC_INDICATOR_CATALOG.map(c => (
          <div key={c.cat} className="card card-pad" style={{ padding: "14px 16px" }}>
            <div className="section-label">{c.cat}</div>
            <div className="muted" style={{ fontSize: 12, lineHeight: 1.45, marginTop: 7 }}>{c.examples}</div>
          </div>
        ))}
      </div>

      {/* recovery indicator ladder */}
      <div className="panel-h"><h3 style={{ fontSize: 15 }}>Recovery indicators</h3><span className="sub">live · and under the active stress scenario</span></div>
      <div className="grid g2 mb24" style={{ gap: 14 }}>
        {REC_INDICATORS.map(ind => {
          const zLive = zoneOf(ind, ind.live), zStr = zoneOf(ind, ind.live2);
          const lo = Math.min(ind.escalate, ind.recovery, ind.live, ind.live2);
          const hi = Math.max(ind.escalate, ind.recovery, ind.live, ind.live2);
          const pos = v => ((v - lo) / (hi - lo || 1)) * 100;
          return (
            <div key={ind.key} className="card card-pad" style={{ padding: "16px 18px" }}>
              <div className="between" style={{ gap: 8 }}><div style={{ fontWeight: 700, fontSize: 13.5, lineHeight: 1.2 }}>{ind.name}</div><span className={"chip chip-" + zStr} style={{ flex: "0 0 auto" }}><span className="dot" />{ZTXT[zStr][0]}</span></div>
              <div className="center gap16 mt12" style={{ fontSize: 12 }}>
                <span>Live <b className="tnum" style={{ color: ZTXT[zLive][1], fontSize: 16 }}>{ind.live}{ind.unit}</b></span>
                <span className="muted">Stressed <b className="tnum" style={{ color: ZTXT[zStr][1] }}>{ind.live2}{ind.unit}</b></span>
              </div>
              {/* threshold ladder bar */}
              <div style={{ position: "relative", height: 8, borderRadius: 6, background: "linear-gradient(90deg, var(--green-soft), var(--amber-soft), var(--red-soft))", margin: "14px 0 6px" }}>
                <span style={{ position: "absolute", left: Math.max(0, Math.min(100, pos(ind.recovery))) + "%", top: -3, width: 2, height: 14, background: "var(--amber)" }} />
                <span style={{ position: "absolute", left: Math.max(0, Math.min(100, pos(ind.escalate))) + "%", top: -3, width: 2, height: 14, background: "var(--red)" }} />
                <span style={{ position: "absolute", left: "calc(" + Math.max(0, Math.min(100, pos(ind.live2))) + "% - 6px)", top: -4, width: 12, height: 16, borderRadius: 4, background: "var(--ink)", border: "2px solid #fff", boxShadow: "0 1px 3px rgba(0,0,0,.3)" }} title="stressed value" />
              </div>
              <div className="between muted" style={{ fontSize: 10.5 }}><span>Recovery {ind.recovery}{ind.unit}</span><span>Escalate {ind.escalate}{ind.unit}</span></div>
            </div>
          );
        })}
      </div>

      {/* escalation chain */}
      <div className="panel-h"><h3 style={{ fontSize: 15 }}>Escalation chain</h3><span className="sub">if one layer can't resolve it, it passes to the next</span></div>
      <div className="grid g3 mb24" style={{ gap: 14 }}>
        {REC_LAYERS.map(l => {
          const active = l.layer === activeLayer, passed = l.layer < activeLayer;
          return (
            <div key={l.layer} className="card card-pad" style={{ padding: "16px 18px", cursor: "pointer", borderColor: active ? "var(--red-line)" : undefined, background: active ? "var(--red-soft)" : passed ? "var(--surface-2)" : undefined }} onClick={() => setLayerOpen(l)}>
              <div className="between"><span className="chip chip-neutral">Layer {l.layer}</span>{active ? <span className="chip chip-red"><span className="dot" />Active</span> : passed ? <span className="chip chip-slate">Cleared</span> : <span className="chip chip-neutral">Standby</span>}</div>
              <div style={{ fontWeight: 700, fontSize: 14, marginTop: 10 }}>{l.name}</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 4, minHeight: 32 }}>{l.mandate}</div>
              <div className="between mt12" style={{ paddingTop: 10, borderTop: "1px solid var(--border)" }}>
                <span className="center" style={{ marginLeft: 0 }}>{l.who.map((w, i) => <span key={w} style={{ marginLeft: i ? -6 : 0 }}><Avatar name={PEOPLE[w].name} size={22} /></span>)}</span>
                <span className="muted" style={{ fontSize: 11.5 }}>SLA {l.sla}</span>
              </div>
            </div>
          );
        })}
      </div>

      {/* recovery options menu */}
      <div className="panel-h"><h3 style={{ fontSize: 15 }}>Recovery options menu</h3><span className="sub">NBE-recognised measures · quantified capacity</span>
        <div className="right"><button className="btn btn-dark btn-sm" onClick={() => openAction({
          title: "Compile Board / NBE pack",
          sub: "Recovery plan evidence pack",
          chip: <StatusChip s="REVIEW_PENDING" />,
          banner: <span><b>Recovery pack compiled for internal review.</b> It assembles indicators, options, owners, escalation layers and communications guardrails.</span>,
          rows: [["Indicators", REC_INDICATORS.length], ["Recovery options", REC_OPTIONS.length], ["Active layer", "Layer " + activeLayer], ["Directive", "SBB/93/2025 recovery workflow"]],
          items: [
            { title: "Board pack", body: "Internal pack only; no external communication is sent.", icon: "fileText" },
            { title: "NBE consent guardrail", body: "Public external communication remains gated until consent is recorded.", icon: "lock" },
            { title: "No execution", body: "Options remain documented intent; no transaction is executed.", icon: "refresh" },
          ],
        })}><Icon name="fileText" size={14} /> Compile Board / NBE pack</button></div></div>
      <div className="xl-wrap">
        <table className="xl">
          <colgroup><col style={{ width: 38 }} /><col style={{ minWidth: 280 }} /><col style={{ width: 100 }} /><col style={{ width: 150 }} /><col style={{ width: 120 }} /><col style={{ width: 110 }} /><col style={{ width: 110 }} /><col style={{ width: 70 }} /></colgroup>
          <thead><tr><th className="xl-no"></th><th style={{ textAlign: "left" }}>Recovery measure</th><th className="xl-amt">Lever</th><th className="xl-amt">Capacity</th><th className="xl-amt">Ratio effect</th><th className="xl-amt">Lead time</th><th className="xl-amt">Owner</th><th className="xl-amt">Layer</th></tr></thead>
          <tbody>
            {REC_OPTIONS.map(o => { const p = PEOPLE[o.owner]; return (
              <tr key={o.no} className="xl-item xl-cell hit" onClick={() => setOpt(o)}>
                <td className="xl-no">{o.no}</td>
                <td className="xl-label">{o.name}</td>
                <td className="xl-amt"><span className={"chip " + (o.lever === "Liquidity" ? "chip-green" : o.lever === "Market" ? "chip-indigo" : "chip-slate")} style={{ fontSize: 10.5 }}>{o.lever}</span></td>
                <td className="xl-amt tnum" style={{ fontWeight: 600 }}>{o.capacity}</td>
                <td className="xl-amt tnum" style={{ color: "var(--green-ink)", fontWeight: 600 }}>{o.metric}</td>
                <td className="xl-amt muted" style={{ fontSize: 12 }}>{o.lead}</td>
                <td className="xl-amt" style={{ textAlign: "right" }}><span className="center gap6" style={{ justifyContent: "flex-end", fontSize: 12 }}><Avatar name={p.name} size={18} /> {p.name.split(" ")[0]}</span></td>
                <td className="xl-amt tnum">L{o.layer}</td>
              </tr>
            ); })}
          </tbody>
        </table>
      </div>
      <div className="mt16"><Banner kind="amber" icon="info">Each measure is pre-quantified so management knows <b>how much capacity</b> it buys and <b>how fast</b>. NBE expects this menu agreed <i>before</i> a crisis — the plan is the deliverable, executed only if an indicator breaches.</Banner></div>

      {/* option drawer */}
      {opt && <Drawer open={!!opt} onClose={() => setOpt(null)} wide>
        <DrawerHead title={opt.no + " · " + opt.name} sub={opt.lever + " lever · owner " + PEOPLE[opt.owner].name} chip={<StatusChip s={opt.state} />} onClose={() => setOpt(null)} />
        <div className="drawer-body">
          <Banner kind="indigo" icon="refresh">Documented management intent — selecting this does not execute a transaction. It adds the measure to the recovery pack with its quantified capacity.</Banner>
          <div className="mt16"><Meta rows={[
            ["Recovery lever", opt.lever],
            ["Quantified capacity", opt.capacity],
            ["Ratio effect", opt.metric],
            ["Lead time", opt.lead],
            ["Owner", <span className="center gap8"><Avatar name={PEOPLE[opt.owner].name} size={20} /> {PEOPLE[opt.owner].name}</span>],
            ["Escalation layer", "Layer " + opt.layer],
            ["Readiness", <StatusChip s={opt.state} />],
          ]} /></div>
          <div className="section-label mt20 mb8">Who · when · how</div>
          <div className="meta" style={{ gridTemplateColumns: "100px 1fr" }}>
            <dt className="muted">Who</dt><dd>{PEOPLE[opt.owner].name} ({PEOPLE[opt.owner].role}) under Layer-{opt.layer} mandate</dd>
            <dt className="muted">When</dt><dd>On the matching indicator entering its recovery zone</dd>
            <dt className="muted">How</dt><dd>Within delegated limits; logged to the audit trail on execution</dd>
          </div>
          <div className="section-label mt20 mb8">Directive-required option assessment</div>
          {REC_OPTION_ASSESSMENT.map((item, i) => (
            <div key={i} className="evi-row">
              <span className="ic-wrap"><Icon name="check" size={14} /></span>
              <div className="grow"><div className="t" style={{ fontSize: 12.5 }}>{item}</div></div>
            </div>
          ))}
          <div className="mt16"><Banner kind="amber" icon="lock">External public communication for this option stays gated until NBE consent is recorded. This workspace records readiness only; it does not execute the measure.</Banner></div>
        </div>
        <div className="drawer-foot">
          <button className="btn btn-ghost" onClick={() => go(opt.lever === "Liquidity" ? "lcr" : opt.lever === "Market" ? "market" : "capital")}><Icon name="arrowR" size={14} /> See affected workpaper</button>
          <button className="btn btn-primary" style={{ marginLeft: "auto" }} onClick={() => { showToast("Recovery option added to internal pack"); setOpt(null); }}>Add to recovery pack</button>
        </div>
      </Drawer>}

      {/* layer drawer */}
      {layerOpen && <Drawer open={!!layerOpen} onClose={() => setLayerOpen(null)}>
        <DrawerHead title={"Layer " + layerOpen.layer + " · " + layerOpen.name} chip={<span className={"chip " + (layerOpen.layer === activeLayer ? "chip-red" : "chip-neutral")}>{layerOpen.layer === activeLayer ? "Active" : layerOpen.layer < activeLayer ? "Cleared" : "Standby"}</span>} onClose={() => setLayerOpen(null)} />
        <div className="drawer-body">
          <Meta rows={[
            ["Escalates when", layerOpen.trigger],
            ["Mandate", layerOpen.mandate],
            ["SLA", layerOpen.sla],
            ["Members", <span className="center gap6">{layerOpen.who.map(w => <span key={w} className="center gap4" style={{ marginRight: 8 }}><Avatar name={PEOPLE[w].name} size={20} /> {PEOPLE[w].name.split(" ")[0]}</span>)}</span>],
          ]} />
          <div className="section-label mt20 mb8">Options at this layer</div>
          {REC_OPTIONS.filter(o => o.layer === layerOpen.layer).map(o => (
            <div key={o.no} className="evi-row"><span className="ic-wrap"><Icon name="refresh" size={15} /></span><div className="grow"><div className="t" style={{ fontSize: 13 }}>{o.name}</div><div className="d">{o.capacity} · {o.metric}</div></div></div>
          ))}
        </div>
        <div className="drawer-foot"><span className="muted center gap6" style={{ fontSize: 12 }}><Icon name="users" size={14} /> Management layer</span>{layerOpen.layer === 3 ? <button className="btn btn-dark" style={{ marginLeft: "auto" }} onClick={() => go("ela")}>Open Emergency Liquidity <Icon name="arrowR" size={14} /></button> : <button className="btn btn-dark" style={{ marginLeft: "auto" }} onClick={() => setLayerOpen(null)}>Done</button>}</div>
      </Drawer>}
      {actionNode}
      {toastNode}
    </div>
  );
}
window.Recovery = Recovery;
