/* global React, Icon, Button, IconBtn, Chip, Badge, Pill, Avatar, Field, Input, Select, Toggle, Tabs, Segmented,
   KPICard, Sparkline, LineChart, BarChart, AreaChart, Donut, StatBlock,
   Table, FeedItem, StatusPill, MOCK, Banner, Popover, PopoverItem, Modal, Drawer, EmptyState, Breadcrumb */

const { useState } = React;

/* ============================================================
   Reusable page bits
   ============================================================ */

function PageHead({ eyebrow, title, gradWord, lead, actions, breadcrumb }) {
  return (
    <div className="page-head" data-screen-label="page-head">
      <div className="titles">
        {breadcrumb}
        {eyebrow && <span className="eyebrow">{eyebrow}</span>}
        <h1 className="h-1" style={{ fontSize: "clamp(34px, 3.4vw, 52px)" }}>
          {gradWord ? (
            <>
              <span>{title} </span>
              <span className="grad-text">{gradWord}</span>
            </>
          ) : title}
        </h1>
        {lead && <p className="lead" style={{ maxWidth: 640 }}>{lead}</p>}
      </div>
      {actions && <div className="actions">{actions}</div>}
    </div>
  );
}

/* ============================================================
   ANALYTICS — Catalyst overview
   ============================================================ */

function AnalyticsScreen({ go }) {
  const [range, setRange] = useState("30d");
  return (
    <div className="page-body" data-screen-label="analytics">
      <PageHead
        breadcrumb={<Breadcrumb items={[{ label: "Catalyst" }, { label: "Overview" }]}/>}
        eyebrow="Catalyst · 30 days"
        title="Decisions made,"
        gradWord="measured."
        lead="What the firm decided this month, where the gradient pulled, and what to simulate next."
        actions={
          <>
            <Segmented value={range} onChange={setRange} items={[
              { value: "7d", label: "7d" },
              { value: "30d", label: "30d" },
              { value: "qtd", label: "QTD" },
              { value: "ytd", label: "YTD" },
            ]}/>
            <Button variant="secondary" icon={<Icon.Download size={14}/>}>Export</Button>
            <Button variant="primary" icon={<Icon.Bolt size={14}/>}>Run Catalyst</Button>
          </>
        }
      />

      {/* Hero KPI strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, minmax(0, 1fr))", gap: "var(--d-card-gap)" }}>
        <KPICard label="Decisions logged" value="1,284" delta={12.4} spark={MOCK.s30}/>
        <KPICard label="Active audits" value="38" delta={-3.1} spark={MOCK.s30b}/>
        <KPICard label="Agents in rotation" value="14" delta={7.7} spark={MOCK.s30}/>
        <KPICard label="Avg. cycle time" value="11.3d" delta={-8.2} spark={MOCK.s30b}/>
      </div>

      {/* Big chart + side panel */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 2fr) minmax(0, 1fr)", gap: "var(--d-card-gap)" }}>
        <div className="card" style={{ padding: 0, overflow: "hidden", display: "flex", flexDirection: "column" }}>
          <div className="row between" style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)" }}>
            <div className="col gap-4">
              <span className="eyebrow">Catalyst index</span>
              <span className="h-3" style={{ marginTop: 8 }}>Decisions × confidence, last 30 days</span>
            </div>
            <Tabs variant="pills" value="all" onChange={() => {}} items={[
              { value: "all", label: "All" }, { value: "mia", label: "MIA" }, { value: "nyc", label: "NYC" }, { value: "scl", label: "SCL" },
            ]}/>
          </div>
          <div style={{ padding: "8px 16px 0", flex: 1, minHeight: 300, display: "flex" }}>
            <LineChart series={[
              { data: MOCK.s30, color: "var(--brand-grad)" },
              { data: MOCK.s30b, color: "var(--ink-3)", dashed: true },
            ]} labels={["May 1","","","","Wk 2","","","","Wk 3","","","","Wk 4","","Today"]} fill/>
          </div>
          <div className="row gap-16" style={{ padding: "12px 24px 16px", color: "var(--ink-3)", fontSize: 12 }}>
            <span className="row gap-6"><i style={{ width: 14, height: 2, background: "var(--brand-grad)" }}/> Decisions logged</span>
            <span className="row gap-6"><i style={{ width: 14, height: 2, background: "var(--ink-3)", borderTop: "1px dashed" }}/> Decisions ÷ audits</span>
          </div>
        </div>

        <div className="col gap-16">
          <div className="card" style={{ padding: 24 }}>
            <span className="eyebrow">Suite usage</span>
            <div className="row between gap-16" style={{ marginTop: 18, alignItems: "center" }}>
              <Donut value={68} size={104} label="68%" sub="Adoption"/>
              <div className="col gap-8" style={{ flex: 1 }}>
                {[
                  { label: "BrandLens", val: 92, c: "var(--grad-4)" },
                  { label: "Catalyst", val: 78, c: "var(--grad-3)" },
                  { label: "HIVE", val: 54, c: "var(--grad-2)" },
                  { label: "Milton.AI", val: 41, c: "var(--grad-1)" },
                ].map((r) => (
                  <div key={r.label} className="col gap-4">
                    <div className="row between" style={{ fontSize: 12 }}>
                      <span>{r.label}</span><span className="mono" style={{ color: "var(--ink-3)" }}>{r.val}%</span>
                    </div>
                    <div style={{ height: 4, background: "var(--bg-2)", borderRadius: 2 }}>
                      <div style={{ width: `${r.val}%`, height: "100%", background: r.c, borderRadius: 2 }}/>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div className="card" style={{ padding: 0 }}>
            <div className="row between" style={{ padding: "16px 20px 12px" }}>
              <span className="eyebrow">Top agents</span>
              <span className="mono" style={{ color: "var(--ink-3)" }}>14 total</span>
            </div>
            {[
              { name: "Milton-IDX", desc: "Knowledge agent · 3.4k calls", v: 92, t: "var(--ph-pink)" },
              { name: "Lens-D02", desc: "Diagnostic · 2.1k calls", v: 78, t: "var(--ph-teal)" },
              { name: "HIVE-C04", desc: "Orchestration · 1.6k", v: 54, t: "var(--ph-magenta)" },
              { name: "Catalyst-S", desc: "Simulator · 1.2k", v: 41, t: "var(--ph-orange)" },
            ].map((a) => (
              <div key={a.name} className="row gap-12" style={{ padding: "12px 20px", borderTop: "1px solid var(--line)" }}>
                <span style={{ width: 28, height: 28, background: a.t, borderRadius: 4 }}/>
                <div className="col" style={{ flex: 1, minWidth: 0 }}>
                  <span style={{ fontSize: 13, fontWeight: 500 }}>{a.name}</span>
                  <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{a.desc}</span>
                </div>
                <Sparkline data={MOCK.s30.slice(-12)} w={64} h={20} color="var(--ink)" area={false}/>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Editorial stat band */}
      <div className="card tint" style={{ padding: "32px var(--d-card-p)" }}>
        <div className="row between" style={{ marginBottom: 24, alignItems: "flex-end" }}>
          <span className="eyebrow">The firm in numbers</span>
          <span className="mono" style={{ color: "var(--ink-3)" }}>Updated 09:42 · MIA</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 32 }}>
          <StatBlock label="Years operating" value="17"/>
          <StatBlock label="Internal AI agents" value="14"/>
          <StatBlock label="Prompts in rotation" value="450+"/>
          <StatBlock label="MIA · NYC · SCL" value="3" gradient/>
        </div>
      </div>

      {/* Two-column: spend + activity */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: "var(--d-card-gap)" }}>
        <div className="card" style={{ padding: 0, display: "flex", flexDirection: "column" }}>
          <div className="row between" style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)" }}>
            <div className="col gap-4">
              <span className="eyebrow">Engagement spend</span>
              <span className="h-3" style={{ marginTop: 8 }}>Last 12 months</span>
            </div>
            <span className="mono" style={{ color: "var(--ink-3)" }}>USD ·  Magnet network</span>
          </div>
          <div style={{ padding: "16px 24px", flex: 1, minHeight: 220, display: "flex" }}>
            <BarChart data={MOCK.bars12} labels={MOCK.s12m} fill/>
          </div>
        </div>

        <div className="card" style={{ padding: 0 }}>
          <div className="row between" style={{ padding: "20px 24px 12px" }}>
            <div className="col gap-4">
              <span className="eyebrow">Activity</span>
              <span className="h-3" style={{ marginTop: 8 }}>Recent commits</span>
            </div>
            <Button variant="ghost" size="sm" iconRight={<Icon.ArrowRight size={12}/>} onClick={() => go && go("inbox")}>Inbox</Button>
          </div>
          <div>
            {MOCK.inbox.slice(0, 4).map((it) => <FeedItem key={it.id} item={it}/>)}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   TABLE — Audits list
   ============================================================ */

function TableScreen({ go }) {
  const [tab, setTab] = useState("all");
  const [view, setView] = useState("table");
  const rows = MOCK.audits.filter(r => tab === "all" || r.status === tab);

  const cols = [
    { key: "id", label: "ID", sortable: true, width: 110, render: (r) => <span className="mono" style={{ color: "var(--ink-3)" }}>{r.id}</span> },
    { key: "name", label: "Engagement", sortable: true, render: (r) => (
      <div className="col gap-4">
        <span style={{ fontWeight: 500 }}>{r.name}</span>
        <span className="mono" style={{ color: "var(--ink-3)", fontSize: 10 }}>{r.client.toUpperCase()} · {r.office}</span>
      </div>
    )},
    { key: "phase", label: "Phase", sortable: true, render: (r) => <span style={{ fontSize: 13 }}>{r.phase}</span> },
    { key: "status", label: "Status", sortable: true, render: (r) => <StatusPill status={r.status}/> },
    { key: "lead", label: "Lead", render: (r) => (
      <div className="row gap-8"><Avatar name={r.lead} size={22}/><span style={{ fontSize: 13 }}>{r.lead}</span></div>
    )},
    { key: "spend", label: "Spend", sortable: true, align: "right", render: (r) => (
      <span className="num" style={{ fontFamily: "var(--mono)", fontSize: 13 }}>${(r.spend / 1000).toFixed(0)}k</span>
    )},
    { key: "days", label: "Days", sortable: true, align: "right", render: (r) => (
      <span className="num" style={{ fontFamily: "var(--mono)", fontSize: 13, color: "var(--ink-3)" }}>{r.days}</span>
    )},
    { key: "_", label: "", width: 40, render: (r) => (
      <Popover trigger={<IconBtn icon={<Icon.MoreV size={14}/>} size={28}/>}>
        {({ close }) => (<>
          <PopoverItem icon={<Icon.Eye size={14}/>} label="View detail" onClick={() => { close(); go("detail"); }}/>
          <PopoverItem icon={<Icon.Edit size={14}/>} label="Edit"/>
          <PopoverItem icon={<Icon.Copy size={14}/>} label="Duplicate"/>
          <hr className="divider" style={{ margin: "6px 0" }}/>
          <PopoverItem icon={<Icon.Trash size={14}/>} label="Archive" danger/>
        </>)}
      </Popover>
    )},
  ];

  return (
    <div className="page-body" data-screen-label="table">
      <PageHead
        breadcrumb={<Breadcrumb items={[{ label: "Catalyst" }, { label: "Audits" }]}/>}
        eyebrow="Engagements · 38 active"
        title="Every audit,"
        gradWord="every phase."
        lead="Diagnose. Simulate. Prescribe. Ship. Sort by phase, lead, or spend."
        actions={
          <>
            <Button variant="secondary" icon={<Icon.Filter size={14}/>}>Filters · 2</Button>
            <Button variant="primary" icon={<Icon.Plus size={14}/>}>New audit</Button>
          </>
        }
      />

      <div className="row between gap-12" style={{ flexWrap: "wrap" }}>
        <Tabs value={tab} onChange={setTab} items={[
          { value: "all", label: "All", count: MOCK.audits.length },
          { value: "active", label: "Active", count: MOCK.audits.filter(r => r.status === "active").length },
          { value: "review", label: "In review", count: MOCK.audits.filter(r => r.status === "review").length },
          { value: "shipped", label: "Shipped", count: MOCK.audits.filter(r => r.status === "shipped").length },
          { value: "archived", label: "Archived", count: MOCK.audits.filter(r => r.status === "archived").length },
        ]}/>
        <div className="row gap-8">
          <Input icon={<Icon.Search size={14}/>} placeholder="Search audits…" fullWidth={false} style={{ width: 240 }}/>
          <Segmented value={view} onChange={setView} items={[
            { value: "table", icon: <Icon.List size={12}/>, label: "Table" },
            { value: "grid", icon: <Icon.Grid size={12}/>, label: "Grid" },
          ]}/>
        </div>
      </div>

      {/* Active filters as chips */}
      <div className="row gap-6 wrap">
        <Chip onRemove={() => {}}><span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>OFFICE:</span> MIA</Chip>
        <Chip onRemove={() => {}}><span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>SPEND:</span> &gt; $50k</Chip>
        <Button variant="ghost" size="sm">Clear all</Button>
      </div>

      <Table columns={cols} rows={rows} selectable onRowClick={() => go("detail")}/>

      <div className="row between" style={{ color: "var(--ink-3)" }}>
        <span className="mono">Showing 1–{rows.length} of {MOCK.audits.length}</span>
        <div className="row gap-6">
          <IconBtn icon={<Icon.ChevronLeft size={14}/>} size={28}/>
          <span className="mono" style={{ fontSize: 11 }}>1 / 1</span>
          <IconBtn icon={<Icon.ChevronRight size={14}/>} size={28}/>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PageHead, AnalyticsScreen, TableScreen });
