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

const { useState: useState2 } = React;

/* ============================================================
   DETAIL — Single audit
   ============================================================ */

function DetailScreen({ go }) {
  const [tab, setTab] = useState2("overview");
  const r = MOCK.audits[0];
  return (
    <div className="page-body" data-screen-label="detail">
      <PageHead
        breadcrumb={<Breadcrumb items={[
          { label: "Catalyst" },
          { label: "Audits", onClick: () => go("table") },
          { label: r.id },
        ]}/>}
        eyebrow={`${r.id} · ${r.client.toUpperCase()} · ${r.office}`}
        title="Loop 14 —"
        gradWord="diagnose phase."
        lead="Northbeam media-mix audit. Run by Milton.AI; reviewed weekly with Inés Vidal. Currently in week 2 of 4."
        actions={
          <>
            <Button variant="ghost" icon={<Icon.Refresh size={14}/>}>Re-run</Button>
            <Button variant="secondary" icon={<Icon.Download size={14}/>}>Export</Button>
            <Button variant="primary" icon={<Icon.Send size={14}/>}>Share with client</Button>
          </>
        }
      />

      <div className="row gap-16 wrap" style={{ alignItems: "center" }}>
        <StatusPill status={r.status}/>
        <Pill dot>{r.phase}</Pill>
        <span className="mono" style={{ color: "var(--ink-3)" }}>Day {r.days} of 21</span>
        <span style={{ width: 1, height: 14, background: "var(--line)" }}/>
        <div className="row gap-8" style={{ alignItems: "center" }}>
          <Avatar name={r.lead} size={22}/><span style={{ fontSize: 13 }}>{r.lead} <span className="muted">· lead</span></span>
        </div>
      </div>

      <Tabs value={tab} onChange={setTab} items={[
        { value: "overview", label: "Overview" },
        { value: "diagnose", label: "Diagnose", count: 4 },
        { value: "simulate", label: "Simulate", count: 2 },
        { value: "prescribe", label: "Prescribe", count: 0 },
        { value: "comments", label: "Comments", count: 12 },
        { value: "files", label: "Files", count: 28 },
      ]}/>

      <Banner tone="grad" title="Diagnose phase complete — 4 high-confidence issues found"
        body="Milton.AI surfaced 4 issues worth simulating. Open the Simulate tab to set assumptions before the Friday review."
        action={<Button variant="ink" size="sm" iconRight={<Icon.ArrowRight size={12}/>}>Open simulator</Button>}/>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 2fr) minmax(0, 1fr)", gap: "var(--d-card-gap)" }}>
        {/* Left column */}
        <div className="col gap-24">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "var(--d-card-gap)" }}>
            <KPICard label="Spend audited" value="$280k" delta={null} deltaLabel="32% of total media"/>
            <KPICard label="Issues found" value="4" delta={null} deltaLabel="2 high · 2 medium"/>
            <KPICard label="Forecast lift" value="+11%" gradient delta={null} deltaLabel="Conservative simulation"/>
          </div>

          <div className="card" style={{ padding: 0 }}>
            <div className="row between" style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)" }}>
              <span className="eyebrow">Findings</span>
              <span className="mono" style={{ color: "var(--ink-3)" }}>04 active</span>
            </div>
            {[
              { code: "F-01", t: "Brand spend over-indexed on prospecting", body: "Q1 prospecting budget grew 38% with no measurable lift in unaided awareness. Recommend cap and reallocate to retention.", tone: "warn", conf: 92 },
              { code: "F-02", t: "Search overlap with paid social", body: "Branded search and Meta retargeting compete on the same intent window — saturation above frequency 7.", tone: "warn", conf: 84 },
              { code: "F-03", t: "Creative fatigue on hero asset", body: "CTR decay on the lead asset since week 6. Two refreshed cuts ready in HIVE for A/B.", tone: "info", conf: 78 },
              { code: "F-04", t: "Geo concentration: FL underweight", body: "Florida shows 1.4× propensity but receives 0.7× spend. Worth simulating.", tone: "info", conf: 71 },
            ].map((f) => (
              <div key={f.code} style={{ borderTop: "1px solid var(--line)", padding: "18px 24px" }}>
                <div className="row between gap-12" style={{ alignItems: "flex-start" }}>
                  <div className="col gap-8" style={{ flex: 1 }}>
                    <div className="row gap-8" style={{ alignItems: "center" }}>
                      <span className="mono" style={{ color: "var(--ink-3)" }}>{f.code}</span>
                      <Pill tone={f.tone} dot>{f.tone === "warn" ? "High" : "Medium"}</Pill>
                    </div>
                    <h4 className="h-4">{f.t}</h4>
                    <p style={{ fontSize: 14, color: "var(--ink-2)", margin: 0, lineHeight: 1.55 }}>{f.body}</p>
                  </div>
                  <div className="col" style={{ alignItems: "flex-end", gap: 4, minWidth: 70 }}>
                    <span className="mono" style={{ color: "var(--ink-3)" }}>Conf.</span>
                    <span style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }}>{f.conf}<span style={{ fontSize: 12, color: "var(--ink-3)" }}>%</span></span>
                  </div>
                </div>
              </div>
            ))}
          </div>

          <div className="card" style={{ padding: 0 }}>
            <div className="row between" style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)" }}>
              <span className="eyebrow">Spend × intent · 30d</span>
              <Segmented value="paid" onChange={() => {}} items={[{ value: "paid", label: "Paid" }, { value: "earned", label: "Earned" }, { value: "owned", label: "Owned" }]}/>
            </div>
            <div style={{ padding: 16 }}>
              <AreaChart data={MOCK.s30} labels={MOCK.s30.map((_, i) => `${i + 1}`)} h={200}/>
            </div>
          </div>
        </div>

        {/* Right column */}
        <div className="col gap-24">
          <div className="card">
            <span className="eyebrow">Engagement</span>
            <div className="col gap-12" style={{ marginTop: 16 }}>
              {[
                ["Client", "Northbeam Inc."],
                ["Office", "MIA · Strategy"],
                ["Started", "Apr 28, 2026"],
                ["Audit fee", "$48,000"],
                ["Spend audited", "$280,000"],
                ["Phase", "Diagnose · w/2 of 4"],
                ["Network", "Magnet Global"],
              ].map(([k, v]) => (
                <div key={k} className="row between" style={{ fontSize: 13, padding: "8px 0", borderBottom: "1px dashed var(--line)" }}>
                  <span className="mono" style={{ color: "var(--ink-3)" }}>{k}</span>
                  <span style={{ fontWeight: 500 }}>{v}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="card">
            <div className="row between">
              <span className="eyebrow">Team</span>
              <Button variant="ghost" size="xs" icon={<Icon.Plus size={12}/>}>Add</Button>
            </div>
            <div className="col gap-10" style={{ marginTop: 14 }}>
              {MOCK.members.map((m) => (
                <div key={m.email} className="row gap-10" style={{ alignItems: "center" }}>
                  <Avatar name={m.name} size={28}/>
                  <div className="col" style={{ flex: 1, minWidth: 0 }}>
                    <span style={{ fontSize: 13, fontWeight: 500 }}>{m.name}</span>
                    <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{m.role} · {m.office}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="card" style={{ padding: 0 }}>
            <div style={{ padding: "20px 24px 12px" }}>
              <span className="eyebrow">Activity</span>
            </div>
            {MOCK.inbox.slice(2, 6).map((it) => <FeedItem key={it.id} item={it}/>)}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   SETTINGS
   ============================================================ */

function SettingsScreen() {
  const [active, setActive] = useState2("account");
  const sections = [
    { id: "account", label: "Account", icon: <Icon.User size={14}/> },
    { id: "team", label: "Team", icon: <Icon.Users size={14}/> },
    { id: "billing", label: "Billing", icon: <Icon.Tag size={14}/> },
    { id: "integrations", label: "Integrations", icon: <Icon.Layers size={14}/> },
    { id: "agents", label: "Agents", icon: <Icon.Spark size={14}/> },
    { id: "appearance", label: "Appearance", icon: <Icon.Sun size={14}/> },
    { id: "advanced", label: "Advanced", icon: <Icon.Code size={14}/> },
  ];
  return (
    <div className="page-body" data-screen-label="settings">
      <PageHead
        breadcrumb={<Breadcrumb items={[{ label: "Workspace" }, { label: "Settings" }]}/>}
        eyebrow="Workspace · Catalyst v4.1"
        title="Settings."
        lead="Account, team, billing, agents. Edits autosave; you'll see a note in the bottom-right when they land."
      />

      <div style={{ display: "grid", gridTemplateColumns: "220px 1fr", gap: 48, alignItems: "flex-start" }}>
        <nav className="col gap-2" style={{ position: "sticky", top: "calc(var(--shell-topbar-h) + 24px)" }}>
          {sections.map((s) => (
            <button key={s.id} onClick={() => setActive(s.id)} style={{
              display: "flex", alignItems: "center", gap: 10, padding: "8px 12px",
              border: 0, background: active === s.id ? "var(--bg-2)" : "transparent",
              color: active === s.id ? "var(--ink)" : "var(--ink-2)",
              fontFamily: "var(--sans)", fontSize: 13, fontWeight: active === s.id ? 500 : 400,
              borderRadius: 4, cursor: "pointer", textAlign: "left",
              borderLeft: active === s.id ? "2px solid var(--grad-4)" : "2px solid transparent",
            }}>
              <span style={{ color: "var(--ink-3)", display: "inline-flex" }}>{s.icon}</span>
              <span>{s.label}</span>
            </button>
          ))}
        </nav>

        <div className="col gap-32" style={{ minWidth: 0, maxWidth: 720 }}>
          {/* Profile */}
          <section>
            <div className="col gap-4" style={{ marginBottom: 18 }}>
              <span className="eyebrow">Profile</span>
              <h2 className="h-2" style={{ fontSize: 28 }}>Your identity inside Catalyst</h2>
            </div>
            <div className="card">
              <div className="row gap-16" style={{ alignItems: "center" }}>
                <Avatar name="Inés Vidal" size={64}/>
                <div className="col gap-4" style={{ flex: 1 }}>
                  <span style={{ fontSize: 16, fontWeight: 600 }}>Inés Vidal</span>
                  <span className="mono" style={{ color: "var(--ink-3)" }}>MIA · Strategy lead · joined 2017</span>
                </div>
                <Button variant="secondary" size="sm">Replace photo</Button>
              </div>
              <div className="divider" style={{ margin: "20px 0" }}/>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <Field label="Full name"><Input value="Inés Vidal" onChange={() => {}}/></Field>
                <Field label="Office"><Select value="MIA" onChange={() => {}} options={["MIA", "NYC", "SCL"]} placeholder=""/></Field>
                <Field label="Email"><Input value="ines@bnmrglvz.com" onChange={() => {}} icon={<Icon.Mail size={14}/>}/></Field>
                <Field label="Phone"><Input value="+1 (786) 770-0010" onChange={() => {}}/></Field>
              </div>
            </div>
          </section>

          {/* Preferences */}
          <section>
            <div className="col gap-4" style={{ marginBottom: 18 }}>
              <span className="eyebrow">Preferences</span>
              <h2 className="h-2" style={{ fontSize: 28 }}>How Catalyst behaves for you</h2>
            </div>
            <div className="card col gap-20">
              <Toggle checked={true} onChange={() => {}}
                label="Editorial reveals"
                description="22px translateY + opacity, 1s cubic-bezier on scroll. Disable for full reduced-motion."/>
              <hr className="divider"/>
              <Toggle checked={true} onChange={() => {}}
                label="Daily Catalyst digest"
                description="One email at 08:00 MIA · what shipped, what stalled, what to simulate."/>
              <hr className="divider"/>
              <Toggle checked={false} onChange={() => {}}
                label="Beta features"
                description="Opt into Milton-IDX v2 and the new Lens diagnostic. May be unstable."/>
            </div>
          </section>

          {/* Agents */}
          <section>
            <div className="col gap-4" style={{ marginBottom: 18 }}>
              <span className="eyebrow">Agents · 14 total</span>
              <h2 className="h-2" style={{ fontSize: 28 }}>Who runs in your name</h2>
            </div>
            <div className="card" style={{ padding: 0 }}>
              {[
                { name: "Milton-IDX", desc: "Knowledge agent · indexes every audit" },
                { name: "Lens-D02", desc: "Brand diagnostic · 2.1k calls / month" },
                { name: "HIVE-C04", desc: "Orchestration · runs C-tier audits end-to-end" },
                { name: "Catalyst-S", desc: "Simulator · runs media-mix decisions" },
              ].map((a, i) => (
                <div key={a.name} className="row between gap-12" style={{ padding: "16px 24px", borderTop: i ? "1px solid var(--line)" : "none" }}>
                  <div className="row gap-12">
                    <span style={{ width: 36, height: 36, background: "var(--ph-magenta)", borderRadius: 4 }}/>
                    <div className="col">
                      <span style={{ fontSize: 14, fontWeight: 500 }}>{a.name}</span>
                      <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{a.desc}</span>
                    </div>
                  </div>
                  <Toggle checked={true} onChange={() => {}}/>
                </div>
              ))}
            </div>
          </section>

          <section>
            <div className="row between" style={{ padding: "16px 0", borderTop: "1px solid var(--neg)", marginTop: 16 }}>
              <div className="col gap-4">
                <h3 className="h-4" style={{ color: "var(--neg)" }}>Delete workspace</h3>
                <span style={{ fontSize: 13, color: "var(--ink-2)" }}>Removes every audit, finding, and prompt. Irreversible.</span>
              </div>
              <Button variant="danger" size="sm">Delete workspace</Button>
            </div>
          </section>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   EMPTY — Onboarding
   ============================================================ */

function EmptyScreen({ go }) {
  return (
    <div className="page-body" data-screen-label="empty">
      <PageHead
        breadcrumb={<Breadcrumb items={[{ label: "Workspace" }, { label: "Projects" }]}/>}
        eyebrow="Empty workspace"
        title="Diagnose"
        gradWord="before you prescribe."
        lead="Catalyst is empty. Start with a paid Audit (2–3 weeks, no templates) or import from another workspace."
      />

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "var(--d-card-gap)" }}>
        {[
          { ph: "var(--ph-pink)", code: "01", t: "Run a paid Audit", body: "Two to three weeks. We diagnose, you decide what's worth simulating.", cta: "Start audit", route: "workflow", primary: true },
          { ph: "var(--ph-teal)", code: "02", t: "Import an engagement", body: "Drop a brief, a deck, or a spreadsheet. Milton.AI normalizes and tags.", cta: "Import", route: null },
          { ph: "var(--ph-magenta)", code: "03", t: "Connect a data source", body: "Hook up GA4, Meta, Snowflake, or Looker. Read-only by default.", cta: "Connect", route: null },
        ].map((c) => (
          <div key={c.code} className="card" style={{ padding: 0, overflow: "hidden", display: "flex", flexDirection: "column" }}>
            <div style={{ height: 140, background: c.ph, position: "relative" }}>
              <div style={{ position: "absolute", inset: 0, background: "var(--ph-overlay)" }}/>
              <span className="mono" style={{ position: "absolute", top: 14, left: 16, color: "white", fontSize: 11, letterSpacing: "0.12em" }}>STEP {c.code}</span>
            </div>
            <div className="col gap-12" style={{ padding: 24, flex: 1 }}>
              <h3 className="h-3" style={{ fontSize: 22 }}>{c.t}</h3>
              <p style={{ fontSize: 14, color: "var(--ink-2)", margin: 0, lineHeight: 1.55, flex: 1 }}>{c.body}</p>
              <Button
                variant={c.primary ? "primary" : "secondary"}
                iconRight={<Icon.ArrowRight size={12}/>}
                onClick={() => c.route && go(c.route)}
                style={{ alignSelf: "flex-start" }}
              >{c.cta}</Button>
            </div>
          </div>
        ))}
      </div>

      <div className="card tint" style={{ padding: 32 }}>
        <div className="row between" style={{ marginBottom: 16 }}>
          <span className="eyebrow">From the field</span>
          <span className="mono" style={{ color: "var(--ink-3)" }}>Recent notes from MIA · NYC · SCL</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 32 }}>
          {[
            { t: "We don't sell AI. We sell better decisions.", who: "Inés Vidal · MIA" },
            { t: "Diagnose before you prescribe. Simulate before you spend.", who: "Marco Ferraro · NYC" },
            { t: "AI is the multiplier. Not the product.", who: "Daniela Reyes · SCL" },
          ].map((q, i) => (
            <div key={i} className="col gap-12">
              <h4 className="h-3" style={{ fontSize: 22, lineHeight: 1.15 }}>{q.t}</h4>
              <span className="mono" style={{ color: "var(--ink-3)" }}>{q.who}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   INBOX
   ============================================================ */

function InboxScreen() {
  const [active, setActive] = useState2(MOCK.inbox[0].id);
  const [filter, setFilter] = useState2("all");
  const items = MOCK.inbox.filter(i => filter === "all" || (filter === "unread" && i.unread) || i.tag === filter);
  const sel = MOCK.inbox.find(i => i.id === active) || MOCK.inbox[0];

  return (
    <div data-screen-label="inbox" style={{ display: "grid", gridTemplateColumns: "minmax(0, 380px) 1fr", height: "calc(100vh - var(--shell-topbar-h))", minHeight: 0 }}>
      <div style={{ borderRight: "1px solid var(--line)", display: "flex", flexDirection: "column", minHeight: 0 }}>
        <div className="col gap-12" style={{ padding: "24px 24px 12px" }}>
          <div className="row between" style={{ alignItems: "center" }}>
            <h2 className="h-3" style={{ fontSize: 22 }}>Inbox</h2>
            <Badge tone="grad">12 NEW</Badge>
          </div>
          <Input icon={<Icon.Search size={14}/>} placeholder="Search inbox…" onChange={() => {}}/>
          <Tabs value={filter} onChange={setFilter} items={[
            { value: "all", label: "All", count: MOCK.inbox.length },
            { value: "unread", label: "Unread", count: MOCK.inbox.filter(i => i.unread).length },
            { value: "agent", label: "Agents", count: 2 },
            { value: "team", label: "Team", count: 3 },
          ]}/>
        </div>
        <div className="scroll" style={{ flex: 1, overflowY: "auto", borderTop: "1px solid var(--line)" }}>
          {items.map((it) => (
            <FeedItem key={it.id} item={it} active={it.id === active} onClick={() => setActive(it.id)}/>
          ))}
        </div>
      </div>

      <div className="scroll" style={{ overflowY: "auto", padding: "32px 48px", minWidth: 0 }}>
        <div className="row between" style={{ marginBottom: 24 }}>
          <Breadcrumb items={[{ label: "Inbox" }, { label: sel.tag.toUpperCase() }, { label: `#${sel.id}` }]}/>
          <div className="row gap-6">
            <IconBtn icon={<Icon.Star size={14}/>} size={32}/>
            <IconBtn icon={<Icon.Trash size={14}/>} size={32}/>
            <IconBtn icon={<Icon.MoreV size={14}/>} size={32}/>
          </div>
        </div>
        <div className="row gap-12" style={{ marginBottom: 16, alignItems: "center" }}>
          {sel.icon ? (
            <span style={{
              width: 40, height: 40, flexShrink: 0,
              background: sel.tone === "grad" ? "var(--brand-grad)" : sel.tone === "warn" ? "var(--warn-bg)" : sel.tone === "pos" ? "var(--pos-bg)" : "var(--bg-2)",
              color: sel.tone === "grad" ? "white" : sel.tone === "warn" ? "var(--warn)" : sel.tone === "pos" ? "var(--pos)" : "var(--ink)",
              borderRadius: 4, display: "inline-flex", alignItems: "center", justifyContent: "center",
            }}>{sel.icon}</span>
          ) : (
            <Avatar name={sel.from} size={40}/>
          )}
          <div className="col">
            <span style={{ fontSize: 14, fontWeight: 600 }}>{sel.from}</span>
            <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{sel.tag.toUpperCase()} · {sel.time} ago</span>
          </div>
        </div>
        <h1 className="h-2" style={{ fontSize: 32 }}>{sel.title}</h1>
        <p className="lead" style={{ marginTop: 16, maxWidth: 640 }}>{sel.body}</p>

        <div className="card" style={{ marginTop: 24, padding: 24 }}>
          <span className="eyebrow">Detail</span>
          <p style={{ marginTop: 14, fontSize: 14, color: "var(--ink-2)", lineHeight: 1.65 }}>
            Diagnose phase concluded at 08:42 MIA. Four findings logged, with confidence above 70 on all of them. Two findings (F-01, F-02) cleared the high-confidence threshold (≥85) and will move into the Simulate phase by default unless flagged otherwise. Recommended next step is to lock simulation assumptions before the Friday client review.
          </p>
        </div>

        <div className="row gap-8" style={{ marginTop: 24 }}>
          <Button variant="primary" icon={<Icon.Send size={14}/>}>Reply</Button>
          <Button variant="secondary">Mark unread</Button>
          <Button variant="ghost">Forward</Button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DetailScreen, SettingsScreen, EmptyScreen, InboxScreen });
