// CTO / Admin view, fleet posture, worries, governance, cost, blocked deploys.
const { Pill, OwnerChip, Sparkbars, Ring, Kpi } = window;
const { WorryItem, AppTile, Pipeline, CostBar, BlockedDeploys, FleetTable } = window;
const { Icons, DATA } = window;

function CtoView({ onOpenApp, onOpenWorry, onOpenPipeline }) {
  const apps = DATA.APPS;
  const fleetAudit = Math.round(apps.reduce((s, a) => s + a.audit, 0) / apps.length);
  const totalCost = apps.reduce((s, a) => s + a.cost, 0);
  const stalestDeps = apps.reduce((m, a) => Math.max(m, a.depsAge), 0);
  const totalApps = apps.length;
  const detRatio = (() => {
    let det = 0, total = 0;
    apps.forEach(a => a.connections.forEach(c => { total++; if (c.det) det++; }));
    return Math.round((det/total)*100);
  })();

  return (
    <div className="fade-in">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 28 }}>
        <div>
          <div className="eyebrow">Monday, Apr 27 · Meridia · BYOC: AWS us-east-1</div>
          <h1 className="page-title" style={{ marginTop: 8 }}>
            Show me <em>everything</em> I should be worried about.
          </h1>
          <p className="page-sub">Fleet-wide posture across 24 AI-generated apps, 7 operator teams, and the cloud you own. Every red item resolves to a named person within one click.</p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn"><Icons.Upload/> Export evidence pack</button>
          <button className="btn primary"><Icons.Shield/> Run governance scan</button>
        </div>
      </div>

      {/* KPIs */}
      <div className="grid g-4" style={{ marginBottom: 20 }}>
        <div className="card kpi" style={{ display: "flex", gap: 18, alignItems: "center" }}>
          <Ring value={fleetAudit} label="Audit"/>
          <div style={{ minWidth: 0 }}>
            <div className="label">Fleet audit</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 22, color: "var(--ink)", letterSpacing: "-0.02em", marginTop: 2 }}>
              SOC2 · ISO 27001
            </div>
            <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4 }}>Evidence rebuilt 38 min ago · signed</div>
          </div>
        </div>
        <Kpi label="AI-generated apps" value={totalApps} delta="+3 this quarter" deltaDir="neutral"
             spark={DATA.SPARK(11)}/>
        <Kpi label="Monthly cloud + LLM spend" value={"$" + (totalCost/1000).toFixed(1)} unit="k"
             delta="+12.4% vs last month" deltaDir="neg" spark={DATA.SPARK(47)}/>
        <Kpi label="Deterministic call ratio" value={detRatio} unit="%"
             delta="stable vs last week" deltaDir="pos" spark={DATA.SPARK(23)}/>
      </div>

      {/* Worry queue + pipeline */}
      <div className="grid g-12" style={{ marginBottom: 20 }}>
        <div className="col-8">
          <div className="card flush">
            <div className="card-head" style={{ padding: "18px 20px 0", marginBottom: 8 }}>
              <div>
                <h3>Worry queue</h3>
                <div className="subtitle">Ranked by blast radius. 1 red · 3 amber · 1 info.</div>
              </div>
              <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <span className="tag">LAST RESCAN 38 MIN AGO</span>
                <button className="btn sm ghost"><Icons.Spark/> Re-rank</button>
              </div>
            </div>
            <div>
              {DATA.WORRIES.map(w => <WorryItem key={w.id} item={w} onOpen={onOpenWorry}/>)}
            </div>
          </div>
        </div>

        <div className="col-4" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card">
            <div className="card-head" style={{ marginBottom: 6 }}>
              <div>
                <h3>Pending approvals</h3>
                <div className="subtitle">Operator → CTO</div>
              </div>
              <span className="pill dark">4</span>
            </div>
            <div>
              {[
                { op: "ml", what: "Add new outbound domain", target: "api.stripe.com", when: "12m" },
                { op: "tt", what: "Increase LLM budget", target: "Campaign Studio · +$1,500", when: "1h" },
                { op: "nc", what: "Deploy to production", target: "Supplier Portal · v088", when: "3h" },
                { op: "dk", what: "Rotate shared API key", target: "OPENAI_API_KEY · prod", when: "yesterday" },
              ].map((r, i) => (
                <div key={i} className="row" style={{ padding: "12px 0" }}>
                  <div style={{ display: "flex", alignItems: "flex-start", gap: 10, minWidth: 0 }}>
                    <OwnerChip id={r.op} size={22}/>
                    <div style={{ minWidth: 0 }}>
                      <div className="primary">{r.what}</div>
                      <div className="secondary" style={{ fontFamily: "var(--mono)", fontSize: 11.5 }}>{r.target}</div>
                    </div>
                  </div>
                  <div style={{ display: "flex", gap: 4, alignItems: "center" }}>
                    <span className="secondary">{r.when}</span>
                    <button className="btn sm primary" style={{ padding: "3px 8px" }}><Icons.Check s={12}/></button>
                    <button className="btn sm ghost" style={{ padding: "3px 8px" }}><Icons.X s={12}/></button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <div>
                <h3>Epistemic debt</h3>
                <div className="subtitle">Gap between shipped and understood</div>
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
              <Ring value={82} label="Closed" color="var(--orange)"/>
              <div style={{ fontSize: 12.5, color: "var(--muted)", lineHeight: 1.5 }}>
                <div><strong style={{ color: "var(--ink)" }}>82%</strong> of outbound calls are deterministic</div>
                <div><strong style={{ color: "var(--ink)" }}>24 / 24</strong> apps mapped to an owner</div>
                <div><strong style={{ color: "var(--ink)" }}>91%</strong> schemas have a change-review rule</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Pipeline */}
      <div className="card" style={{ marginBottom: 20 }}>
        <div className="card-head">
          <div>
            <h3>Staging → production pipeline</h3>
            <div className="subtitle">Visual gate state. Deploy-to-staging-first default is on for every app.</div>
          </div>
          <button className="btn sm" onClick={onOpenPipeline}>
            Open blocked-deploy ledger <Icons.Arrow s={12}/>
          </button>
        </div>
        <Pipeline/>
        <hr className="dashdiv" style={{ margin: "18px 0 14px" }}/>
        <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 8 }}>Recently blocked, Stoda prevented 2 bad deploys this week</div>
        <div style={{ border: "1px solid var(--tan-2)", borderRadius: 10, overflow: "hidden" }}>
          <BlockedDeploys compact={true} onSelectApp={(n) => {
            const a = DATA.APPS.find(x => x.name === n);
            if (a) onOpenApp(a);
          }}/>
        </div>
      </div>

      {/* Fleet */}
      <div className="card flush" style={{ marginBottom: 20 }}>
        <div className="card-head" style={{ padding: "18px 20px 14px", marginBottom: 0 }}>
          <div>
            <h3>Fleet</h3>
            <div className="subtitle">Every AI-generated app, its owner, and its health.</div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn sm"><Icons.Search s={12}/> Filter</button>
            <button className="btn sm"><Icons.Branch s={12}/> Group: team</button>
          </div>
        </div>
        <FleetTable onOpen={onOpenApp}/>
      </div>

      {/* Uniquely-Stoda row */}
      <div className="grid g-3" style={{ marginBottom: 20 }}>
        <div className="card" style={{ background: "var(--cream-2)" }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Only Stoda sees this</div>
          <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 400, letterSpacing: "-0.02em" }}>
            Schema migration guard
          </h3>
          <p style={{ color: "var(--muted)", fontSize: 13, marginTop: 6 }}>
            Engineer PR <span className="sig">#8421</span> drops column <span className="sig">legacy_stage</span>.
            This will break <strong style={{ color: "var(--ink)" }}>3 AI-generated apps</strong>.
          </p>
          <div style={{ display: "flex", gap: 6, marginTop: 10, flexWrap: "wrap" }}>
            <Pill kind="warn">Quote Copilot</Pill>
            <Pill kind="warn">Onboarding Wizard</Pill>
            <Pill kind="warn">Churn Early Warning</Pill>
          </div>
          <button className="btn sm primary" style={{ marginTop: 14 }}>Draft owner-notification <Icons.Arrow s={12}/></button>
        </div>

        <div className="card" style={{ background: "var(--cream-2)" }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Only Stoda sees this</div>
          <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 400, letterSpacing: "-0.02em" }}>
            Generator arbitrage
          </h3>
          <p style={{ color: "var(--muted)", fontSize: 13, marginTop: 6 }}>
            Campaign Studio generated with <span className="sig">v0</span> · $6,420/mo.
            Equivalent on <span className="sig">Claude Code</span> est. <strong style={{ color: "var(--ink)" }}>$4,280/mo</strong> at 94% behavior-preservation.
          </p>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 14 }}>
            <div className="ring-wrap" style={{ width: 64, height: 64 }}>
              <svg width="64" height="64" viewBox="0 0 64 64">
                <circle cx="32" cy="32" r="26" fill="none" stroke="var(--tan-2)" strokeWidth="6"/>
                <circle cx="32" cy="32" r="26" fill="none" stroke="var(--orange)" strokeWidth="6"
                  strokeDasharray={2*Math.PI*26} strokeDashoffset={2*Math.PI*26*0.06}
                  strokeLinecap="round"
                  style={{ transform: "rotate(-90deg)", transformOrigin: "32px 32px" }}/>
              </svg>
              <div className="label" style={{ fontSize: 16 }}>94%</div>
            </div>
            <div style={{ fontSize: 12.5, color: "var(--muted)" }}>
              Stoda replayed 128 operator-authored tests on the generated equivalent, <strong style={{ color: "var(--ink)" }}>120 matched</strong>.
            </div>
          </div>
          <button className="btn sm primary" style={{ marginTop: 14 }}>View comparison <Icons.Arrow s={12}/></button>
        </div>

        <div className="card" style={{ background: "var(--cream-2)" }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Only Stoda sees this</div>
          <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 400, letterSpacing: "-0.02em" }}>
            Shared-key detection
          </h3>
          <p style={{ color: "var(--muted)", fontSize: 13, marginTop: 6 }}>
            <span className="sig">OPENAI_API_KEY · meridia-prod</span> used by <strong style={{ color: "var(--ink)" }}>4 apps</strong>. Cost is <em>unattributable</em> until split.
          </p>
          <div style={{ marginTop: 14, padding: 12, background: "var(--paper)", borderRadius: 8, border: "1px solid var(--tan-2)" }}>
            <div style={{ fontSize: 11.5, color: "var(--muted)" }}>Unassigned this month</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 28, color: "var(--ink)", letterSpacing: "-0.02em" }}>$3,210</div>
          </div>
          <button className="btn sm primary" style={{ marginTop: 14 }}>Split into per-app keys <Icons.Arrow s={12}/></button>
        </div>
      </div>
    </div>
  );
}

window.CtoView = CtoView;
