/* global React, Icon, StatusChip, Avatar, PageHeader, MODULES, QUEUE, TIMELINE, PEOPLE, BANK, PACKAGES, useActionDrawer */
const { useState: useStateCR, useEffect: useEffectCR } = React;
function readApprovals() { try { return JSON.parse(localStorage.getItem("tos_stress_approvals") || "[]"); } catch (e) { return []; } }

const CONTROL_HELP = {
  title: "Control Room",
  purpose: "The command center for the current prudential cycle. It answers: what is ready, what is blocked, who owns the next action, and what needs a decision today.",
  first: "Start with the red export-readiness banner, then scan module tiles for any red or amber state. Each tile leads to evidence — never to a dead end.",
  terms: [
    ["Readiness state", "Where a module sits between source intake and approved internal workpaper."],
    ["Blocker", "A specific gap (source, validation, evidence, policy) holding a number back."],
    ["Owner", "The person responsible for the next action on that module."],
  ],
  next: [
    "Open a module tile to drill into its workpaper, source, and evidence.",
    "Pick a task from Today's decisions to act as maker or checker.",
    "Click the export status to see the gate checklist.",
  ],
  connections: [
    "Tiles route to Data Harmonizer and each risk workpaper.",
    "Blocker counts open Exceptions filtered to that module.",
    "Export status opens Reg Reporting's export gate.",
  ],
  guardrail: "Nothing here is an official NBE calculation or submission. Tiles show internal-workpaper readiness only; official export stays blocked until every gate passes.",
};

function ControlRoom({ go, info }) {
  const blocked = PACKAGES.filter(p => p.state === "EXPORT_BLOCKED").length;
  const totalGates = PACKAGES.reduce((a, p) => a + Object.values(p.gates).filter(g => g !== "pass").length, 0);
  const [approvals, setApprovals] = useStateCR(readApprovals);
  const [actionNode, openAction] = useActionDrawer();
  useEffectCR(() => {
    const h = () => setApprovals(readApprovals());
    window.addEventListener("tos-approvals", h); window.addEventListener("storage", h);
    return () => { window.removeEventListener("tos-approvals", h); window.removeEventListener("storage", h); };
  }, []);

  return (
    <div className="main-inner">
      <PageHeader
        eyebrow={"Prudential cycle · " + BANK.cycleShort}
        title="Control Room"
        onInfo={() => info(CONTROL_HELP)}
        right={<React.Fragment>
          <button className="btn btn-ghost btn-sm" onClick={() => openAction({
            title: BANK.cycleShort + " period-end",
            sub: "Cycle control checkpoint",
            chip: <StatusChip s="REVIEW_PENDING" />,
            banner: <span><b>Period-end checklist opened.</b> This records the internal close workflow and highlights blockers before the cycle can move to export readiness.</span>,
            rows: [["Cycle", BANK.cycle], ["Open blockers", "37"], ["Gate status", totalGates + " evidence gates open"], ["Next action", "Clear validation, evidence, lineage and approval gates"]],
            items: [
              { title: "Freeze source snapshots", body: "Only approved, hashed internal review snapshots are used in this environment.", icon: "database" },
              { title: "Complete maker-checker queue", body: approvals.length + QUEUE.length + " open decision items remain.", icon: "users" },
              { title: "Review export gates", body: "Official export remains blocked until all six gates pass.", icon: "lock" },
            ],
          })}><Icon name="calendar" size={15} /> {BANK.cycleShort} · Period-end</button>
          <button className="btn btn-dark btn-sm" onClick={() => go("export")}><Icon name="fileText" size={15} /> Export readiness</button>
        </React.Fragment>}
      />

      {/* export blocker banner */}
      <div className="banner banner-red" style={{ marginBottom: 22, alignItems: "center", padding: "15px 18px" }}>
        <Icon name="lock" size={20} className="ic" />
        <div className="grow">
          <div style={{ fontWeight: 800, fontSize: 14.5 }}>Official export blocked — {totalGates} evidence gates open across {PACKAGES.length} NBE packages</div>
          <div style={{ marginTop: 2, opacity: .85 }}>Source, rule evidence, lineage, and approvals must all pass. {blocked} packages are blocked; 1 is approved as an internal workpaper.</div>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={() => go("export")} style={{ flex: "0 0 auto" }}>Review gates <Icon name="arrowR" size={14} /></button>
      </div>

      {/* top metrics strip */}
      <div className="grid g4" style={{ marginBottom: 22 }}>
        <Stat label="Cycle progress" value="63%" foot="Across 8 active modules" tone="amber" bar={63} />
        <Stat label="Open blockers" value="37" foot="9 critical · 28 to resolve" tone="red" />
        <Stat label="Awaiting your review" value="4" foot="As checker · due today" tone="amber" />
        <Stat label="Approved internal" value="1 / 5" foot="NOP return · internal only" tone="green" />
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1.62fr 1fr", gap: 18, alignItems: "start" }}>
        {/* module readiness grid */}
        <div>
          <div className="panel-h"><h3>Module readiness</h3><span className="sub">Every tile leads to a workpaper or evidence surface</span></div>
          <div className="grid g2">
            {MODULES.map(m => {
              const p = PEOPLE[m.owner];
              const barCls = m.pct >= 80 ? "" : m.pct >= 50 ? "amber" : "red";
              return (
                <div key={m.id} className="tile" onClick={() => go(m.route)}>
                  <div className="th" style={{ marginBottom: 10 }}>
                    <span style={{ width: 30, height: 30, borderRadius: 8, background: "var(--surface-2)", border: "1px solid var(--border)", display: "grid", placeItems: "center", color: "var(--ink-2)" }}>
                      <Icon name={m.icon} size={17} />
                    </span>
                    <span className="tname">{m.name}</span>
                    <span style={{ marginLeft: "auto" }}><Icon name="arrowUR" size={15} className="muted" /></span>
                  </div>
                  <div style={{ marginBottom: 10 }}><StatusChip s={m.state} /></div>
                  <div className="muted" style={{ fontSize: 12, minHeight: 32, lineHeight: 1.4 }}>{m.note}</div>
                  <div className={"bar " + barCls} style={{ margin: "12px 0 10px" }}><span style={{ width: m.pct + "%" }} /></div>
                  <div className="between">
                    <span className="center gap6" style={{ fontSize: 12 }}>
                      <Avatar name={p.name} size={20} /><span className="muted">{p.name.split(" ")[0]}</span>
                    </span>
                    {m.blockers > 0
                      ? <span className="center gap6 link" onClick={(e) => { e.stopPropagation(); go("exceptions"); }} style={{ fontSize: 12, borderBottom: "none", color: "var(--red)" }}>
                          <Icon name="alertCirc" size={14} /> <span>{m.blockers} blocker{m.blockers > 1 ? "s" : ""}</span></span>
                      : <span className="center gap6" style={{ fontSize: 12, color: "var(--green-ink)", fontWeight: 600 }}><Icon name="check" size={14} /> <span>clear</span></span>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* right rail */}
        <div className="col" style={{ gap: 18 }}>
          {/* owner queue */}
          <div className="card card-pad">
            <div className="panel-h"><h3>Today's decisions</h3><span className="chip chip-amber" style={{ marginLeft: "auto" }}>{QUEUE.length + approvals.length} open</span></div>
            <div>
              {approvals.map(a => (
                <div key={a.id} className="q-row" onClick={() => go("capital")}>
                  <Avatar name="Hana Girma" size={28} />
                  <div className="grow" style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>Approve stress assumptions · {a.name}</div>
                    <div className="muted" style={{ fontSize: 11.5 }}>{a.module} · checker {a.checker}</div>
                  </div>
                  <span className="chip chip-indigo" style={{ flex: "0 0 auto" }}>Stress · new</span>
                </div>
              ))}
              {QUEUE.map(q => {
                const p = PEOPLE[q.who];
                return (
                  <div key={q.id} className="q-row" onClick={() => go(q.route)}>
                    <Avatar name={p.name} size={28} />
                    <div className="grow" style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{q.title}</div>
                      <div className="muted" style={{ fontSize: 11.5 }}>{q.module} · {p.name}</div>
                    </div>
                    <span className={"chip chip-" + q.sev} style={{ flex: "0 0 auto" }}>{q.sla}</span>
                  </div>
                );
              })}
            </div>
          </div>

          {/* run timeline */}
          <div className="card card-pad">
            <div className="panel-h"><h3>Run timeline</h3><span className="sub">{BANK.cycleShort}</span></div>
            <div className="col" style={{ gap: 0 }}>
              {TIMELINE.map((t, i) => {
                const map = { done: ["check", "var(--green)", "#fff"], fail: ["alert", "var(--red)", "#fff"], active: ["clock", "var(--ink)", "var(--lime)"], todo: ["", "var(--surface-2)", "var(--ink-4)"], blocked: ["lock", "var(--red-soft)", "var(--red)"] };
                const [ic, bg, fg] = map[t.state];
                return (
                  <div key={i} className="center gap12" style={{ padding: "7px 0" }}>
                    <div style={{ position: "relative", display: "grid", placeItems: "center" }}>
                      <span style={{ width: 24, height: 24, borderRadius: 50, background: bg, color: fg, border: t.state === "todo" ? "1.5px solid var(--border-dark)" : "none", display: "grid", placeItems: "center" }}>
                        {ic ? <Icon name={ic} size={13} /> : <span style={{ width: 6, height: 6, borderRadius: 50, background: "var(--ink-4)" }} />}
                      </span>
                      {i < TIMELINE.length - 1 && <span style={{ position: "absolute", top: 24, width: 2, height: 16, background: "var(--border)" }} />}
                    </div>
                    <span style={{ fontSize: 13, fontWeight: t.state === "active" ? 700 : 500, color: t.state === "todo" ? "var(--ink-3)" : "var(--ink)" }}>{t.step}</span>
                    {t.state === "fail" && <span className="chip chip-red" style={{ marginLeft: "auto" }}>3 failed</span>}
                    {t.state === "active" && <span className="chip chip-amber" style={{ marginLeft: "auto" }}>in progress</span>}
                    {t.state === "blocked" && <span className="chip chip-red" style={{ marginLeft: "auto" }}>blocked</span>}
                  </div>
                );
              })}
            </div>
            <button className="btn btn-ghost btn-sm" style={{ width: "100%", marginTop: 12 }} onClick={() => go("harmonizer")}>Open run workflow <Icon name="arrowR" size={14} /></button>
          </div>
        </div>
      </div>
      {actionNode}
    </div>
  );
}

function Stat({ label, value, foot, tone, bar }) {
  const toneColor = { red: "var(--red)", amber: "var(--amber)", green: "var(--green-ink)" }[tone] || "var(--ink)";
  return (
    <div className="card card-pad" style={{ padding: "16px 18px" }}>
      <div className="section-label">{label}</div>
      <div className="big-num" style={{ marginTop: 6, color: toneColor }}>{value}</div>
      {bar != null && <div className={"bar " + (tone === "red" ? "red" : tone === "amber" ? "amber" : "")} style={{ margin: "8px 0" }}><span style={{ width: bar + "%" }} /></div>}
      <div className="muted" style={{ fontSize: 11.5, marginTop: bar != null ? 0 : 6 }}>{foot}</div>
    </div>
  );
}

window.ControlRoom = ControlRoom;
