// route-agent.jsx — Agent Brain. The headline AI capability:
// one agent with access to Shopify data + all Ecommos apps + workflows.
// UX inspiration: Cursor Composer / ChatGPT with tools / Linear AI.

const AGENT_SAMPLE_QUERIES = [
  { icon: 'sparkle', t: 'VIP customers who haven\'t ordered in 30 days', sample: true },
  { icon: 'cart', t: 'Top 5 SKUs by revenue last month' },
  { icon: 'store', t: 'Pause all storefront widgets if inventory < 10' },
  { icon: 'wand', t: 'Refund order #1042 and notify customer' },
];

const CONNECTED_SOURCES = [
  { kind: 'shopify', name: 'Products & inventory', count: '4,212 SKUs', tone: 'success' },
  { kind: 'shopify', name: 'Orders', count: '38k orders', tone: 'success' },
  { kind: 'shopify', name: 'Customers', count: '12.4k customers', tone: 'success' },
  { kind: 'shopify', name: 'Analytics', count: 'last 24 months', tone: 'success' },
  { kind: 'app', name: 'Coupon Manager', count: 'v3 · 24 codes', tone: 'magic' },
  { kind: 'app', name: 'Loyalty Hearts', count: 'v7 · 1.2k members', tone: 'magic' },
  { kind: 'app', name: 'Bundle Deals', count: 'v2 · 6 bundles', tone: 'magic' },
  { kind: 'app', name: 'Spin to Win', count: 'v4 · paused', tone: 'magic' },
];

function RouteAgent({ navigate, state, setState }) {
  const a = state.agent;
  const set = (patch) => setState((s) => ({ ...s, agent: { ...s.agent, ...(typeof patch === 'function' ? patch(s.agent) : patch) } }));

  if (!a.setupDone) return <AgentSetup set={set} navigate={navigate} />;

  return (
    <div style={{ display: 'flex', height: '100%', background: 'var(--p-color-bg)' }}>
      {/* LEFT — conversation list */}
      <div style={{
        width: 232, background: 'var(--p-color-bg-surface)',
        borderRight: '1px solid var(--p-color-border)',
        display: 'flex', flexDirection: 'column',
        flexShrink: 0,
      }}>
        <div style={{ padding: '12px 12px 8px' }}>
          <Btn variant="magic" icon={I.plus} style={{ width: '100%' }} onClick={() => set({ activeChat: 'new', chat: [] })}>
            New chat
          </Btn>
        </div>
        <Tabs
          tabs={[{ id: 'chats', label: 'Chats', count: 4 }, { id: 'flows', label: 'Workflows', count: 3 }]}
          value={a.leftTab}
          onChange={(t) => set({ leftTab: t })}
        />
        {a.leftTab === 'chats' && (
          <div className="p-scroll" style={{ flex: 1, overflow: 'auto', padding: '10px 8px' }}>
            {[
              { id: 'now', label: 'VIP win-back coupon', ts: 'Just now', active: true },
              { id: 'c1', label: 'Top SKUs last month', ts: '2h ago' },
              { id: 'c2', label: 'Inventory low — pause widget', ts: 'Yesterday' },
              { id: 'c3', label: 'Refund order #1042', ts: '3 days ago' },
            ].map((c) => (
              <div key={c.id} style={{
                padding: '8px 10px', borderRadius: 8, cursor: 'pointer',
                background: c.active ? 'var(--p-color-bg-fill-tertiary)' : 'transparent',
                marginBottom: 2,
              }}>
                <div style={{ fontSize: 12.5, fontWeight: c.active ? 600 : 500, color: 'var(--p-color-text)' }}>{c.label}</div>
                <div style={{ fontSize: 10.5, color: 'var(--p-color-text-secondary)' }}>{c.ts}</div>
              </div>
            ))}
          </div>
        )}
        {a.leftTab === 'flows' && (
          <div className="p-scroll" style={{ flex: 1, overflow: 'auto', padding: '10px 8px' }}>
            {a.workflows.map((f) => (
              <div key={f.id} style={{
                padding: '8px 10px', borderRadius: 8, marginBottom: 4,
                background: 'var(--p-color-bg-surface-secondary)',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Badge tone={f.on ? 'success' : 'critical'} dot>{f.on ? 'on' : 'off'}</Badge>
                  <div style={{ fontSize: 12, fontWeight: 600, flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.name}</div>
                </div>
                <div style={{ fontSize: 10.5, color: 'var(--p-color-text-secondary)', marginTop: 2 }}>{f.trigger}</div>
              </div>
            ))}
          </div>
        )}
        <div style={{ padding: 10, borderTop: '1px solid var(--p-color-border-secondary)' }}>
          <Btn variant="plain" size="sm" icon={I.settings} style={{ width: '100%', justifyContent: 'flex-start' }}
            onClick={() => set({ showSetup: true })}>Brain settings</Btn>
        </div>
      </div>

      {/* CENTER — chat */}
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <AgentChat set={set} chat={a.chat} pendingPlan={a.pendingPlan} a={a} />
      </div>

      {/* RIGHT — connected context */}
      <div style={{
        width: 280, borderLeft: '1px solid var(--p-color-border)',
        background: 'var(--p-color-bg-surface)', flexShrink: 0,
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ padding: '14px 14px 8px', borderBottom: '1px solid var(--p-color-border-secondary)' }}>
          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 4 }}>Sarah's Brain</div>
          <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>
            Connected to your shop · permission level <b>Approval required</b>
          </div>
        </div>
        <div className="p-scroll" style={{ flex: 1, overflow: 'auto', padding: '10px 12px' }}>
          <div style={{ fontSize: 10, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06, fontWeight: 600, margin: '4px 2px 6px' }}>Shopify data</div>
          {CONNECTED_SOURCES.filter((s) => s.kind === 'shopify').map((s) => (
            <SourceRow key={s.name} {...s} />
          ))}
          <div style={{ fontSize: 10, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.06, fontWeight: 600, margin: '14px 2px 6px' }}>Ecommos apps</div>
          {CONNECTED_SOURCES.filter((s) => s.kind === 'app').map((s) => (
            <SourceRow key={s.name} {...s} />
          ))}
        </div>
        <div style={{ padding: 10, borderTop: '1px solid var(--p-color-border-secondary)' }}>
          <Btn variant="plain" size="sm" icon={I.plus} style={{ width: '100%', justifyContent: 'flex-start' }}>Add source</Btn>
        </div>
      </div>

      {a.showSetup && <AgentSetupDialog set={set} a={a} />}
    </div>
  );
}

function SourceRow({ kind, name, count, tone }) {
  return (
    <div style={{
      padding: '7px 8px', borderRadius: 7, marginBottom: 2,
      display: 'flex', alignItems: 'center', gap: 8,
      fontSize: 12,
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 6,
        background: kind === 'shopify' ? 'rgba(94,142,62,0.12)' : 'var(--p-color-bg-fill-magic)',
        color: kind === 'shopify' ? '#3a6420' : 'var(--p-color-text-magic)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>
        {kind === 'shopify' ? <I.store size={11} /> : <I.wand size={11} />}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 500, fontSize: 12, color: 'var(--p-color-text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{name}</div>
        <div style={{ fontSize: 10.5, color: 'var(--p-color-text-secondary)' }}>{count}</div>
      </div>
      <Badge tone={tone} dot></Badge>
    </div>
  );
}

// ─── Setup (first-run) ───────────────────────────────────────
function AgentSetup({ set, navigate }) {
  const [step, setStep] = React.useState(1);
  const [name, setName] = React.useState("Sarah's Brain");
  const [perm, setPerm] = React.useState('approval');
  const [tone, setTone] = React.useState('professional');
  return (
    <div style={{ height: '100%', overflow: 'auto', background: 'var(--p-color-bg)' }} className="p-scroll">
      <Page>
        <PageHeader
          eyebrow="Agent Brain"
          title="Set up your Brain"
          secondary={<Btn variant="plain">Skip · use defaults</Btn>}
        />
        <Banner tone="magic" icon={I.sparkle}>
          <b>One agent that knows your whole shop.</b> Brain can answer questions across Shopify data and any app you've built in Ecommos. It can also take action — with the approval level you choose.
        </Banner>

        <div style={{ display: 'flex', gap: 16, marginTop: 20 }}>
          {/* Stepper */}
          <div style={{ width: 200, flexShrink: 0 }}>
            {[
              ['Personality', '1', 'Name + tone'],
              ['Data sources', '2', 'What can it see'],
              ['Permissions', '3', 'What can it do'],
              ['Workflows', '4', 'Optional automations'],
            ].map(([t, n, sub]) => {
              const cur = parseInt(n) === step;
              const done = parseInt(n) < step;
              return (
                <div key={n} onClick={() => setStep(parseInt(n))} style={{
                  padding: '10px 12px', display: 'flex', gap: 10, alignItems: 'flex-start',
                  borderRadius: 8, marginBottom: 2, cursor: 'pointer',
                  background: cur ? 'var(--p-color-bg-fill-magic)' : 'transparent',
                }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: '50%',
                    background: done ? 'var(--p-color-bg-fill-success-active)' : cur ? 'var(--p-color-bg-fill-magic-active)' : 'var(--p-color-bg-fill-tertiary)',
                    color: done || cur ? 'white' : 'var(--p-color-text-secondary)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 11, fontWeight: 700, flexShrink: 0,
                  }}>{done ? <I.check size={11} /> : n}</div>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: cur ? 600 : 500, color: cur ? 'var(--p-color-text-magic)' : 'var(--p-color-text)' }}>{t}</div>
                    <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)', marginTop: 1 }}>{sub}</div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Content */}
          <div style={{ flex: 1 }}>
            {step === 1 && (
              <Card padding>
                <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>Personality</div>
                <div style={{ fontSize: 12.5, color: 'var(--p-color-text-secondary)', marginBottom: 16 }}>How should your Brain introduce itself?</div>
                <div style={{ fontSize: 12, fontWeight: 500, marginBottom: 4 }}>Name</div>
                <Input value={name} onChange={setName} />
                <div style={{ fontSize: 12, fontWeight: 500, margin: '14px 0 6px' }}>Tone</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {['professional', 'friendly', 'concise', 'verbose', 'witty'].map((t) => (
                    <Chip key={t} active={tone === t} onClick={() => setTone(t)}>{t}</Chip>
                  ))}
                </div>
                <div style={{ fontSize: 12, fontWeight: 500, margin: '14px 0 6px' }}>Avatar</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  {['var(--p-color-bg-fill-magic-active)', '#5e8e3e', '#d97757', '#5e8eb8'].map((c, i) => (
                    <div key={i} style={{
                      width: 40, height: 40, borderRadius: 10,
                      background: i === 0 ? `linear-gradient(135deg, ${c}, #a18bff)` : c,
                      cursor: 'pointer',
                      border: i === 0 ? '2px solid var(--p-color-border-magic)' : '2px solid transparent',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white',
                    }}><I.sparkle size={18} /></div>
                  ))}
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 18 }}>
                  <Btn variant="magic" iconRight={I.chevronRight} onClick={() => setStep(2)}>Continue</Btn>
                </div>
              </Card>
            )}
            {step === 2 && (
              <Card padding>
                <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>Data sources</div>
                <div style={{ fontSize: 12.5, color: 'var(--p-color-text-secondary)', marginBottom: 16 }}>
                  Choose what your Brain can read. You can change this later.
                </div>
                <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.04, fontWeight: 600, marginBottom: 8 }}>Shopify data</div>
                {[
                  ['Products & inventory', '4,212 SKUs', true],
                  ['Orders & fulfillments', '38k orders', true],
                  ['Customers', '12.4k customers', true],
                  ['Discounts & gift cards', 'all active', true],
                  ['Analytics', 'last 24 months', true],
                  ['Themes & content', 'home + 8 pages', false],
                ].map(([n, c, on]) => (
                  <SourceCheckRow key={n} name={n} count={c} on={on} />
                ))}
                <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)', textTransform: 'uppercase', letterSpacing: 0.04, fontWeight: 600, margin: '16px 0 8px' }}>Ecommos apps · 4 of 7</div>
                {[
                  ['Coupon Manager', 'v3 · live', true],
                  ['Loyalty Hearts', 'v7 · live', true],
                  ['Bundle Deals', 'v2 · live', true],
                  ['Spin to Win', 'v4 · paused', true],
                ].map(([n, c, on]) => (
                  <SourceCheckRow key={n} name={n} count={c} on={on} kind="app" />
                ))}
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 18 }}>
                  <Btn onClick={() => setStep(1)}>Back</Btn>
                  <Btn variant="magic" iconRight={I.chevronRight} onClick={() => setStep(3)}>Continue</Btn>
                </div>
              </Card>
            )}
            {step === 3 && (
              <Card padding>
                <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>Permissions</div>
                <div style={{ fontSize: 12.5, color: 'var(--p-color-text-secondary)', marginBottom: 16 }}>How much autonomy do you grant your Brain?</div>
                {[
                  { id: 'read', label: 'Read-only', desc: 'Brain can query and report. Cannot change anything.', risk: 'Safest' },
                  { id: 'approval', label: 'Approval required', desc: 'Brain proposes actions; you approve each one before it runs. ★ Recommended', risk: 'Balanced' },
                  { id: 'auto', label: 'Autonomous', desc: 'Brain executes actions on its own. You see them in the activity log.', risk: 'Power user' },
                ].map((p) => (
                  <Card key={p.id} onClick={() => setPerm(p.id)} style={{
                    padding: 12, marginBottom: 8, cursor: 'pointer',
                    borderColor: perm === p.id ? 'var(--p-color-border-magic)' : 'var(--p-color-border)',
                    boxShadow: perm === p.id ? '0 0 0 1px var(--p-color-border-magic)' : 'var(--p-shadow-100)',
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                      <div style={{
                        width: 14, height: 14, borderRadius: '50%',
                        border: '1.5px solid ' + (perm === p.id ? 'var(--p-color-border-magic)' : 'var(--p-color-border-hover)'),
                        background: perm === p.id ? 'var(--p-color-bg-fill-magic-active)' : 'white',
                        position: 'relative',
                      }}>
                        {perm === p.id && <div style={{ position: 'absolute', inset: 3, background: 'white', borderRadius: '50%' }} />}
                      </div>
                      <div style={{ fontSize: 13, fontWeight: 600 }}>{p.label}</div>
                      <div style={{ flex: 1 }} />
                      <Badge tone={p.id === 'read' ? 'success' : p.id === 'approval' ? 'magic' : 'warning'}>{p.risk}</Badge>
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--p-color-text-secondary)', marginLeft: 22 }}>{p.desc}</div>
                  </Card>
                ))}
                <Banner tone="warning" style={{ marginTop: 12, fontSize: 12 }}>
                  Destructive actions (refunds, deletes, bulk edits) always require approval, regardless of mode.
                </Banner>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 18 }}>
                  <Btn onClick={() => setStep(2)}>Back</Btn>
                  <Btn variant="magic" iconRight={I.chevronRight} onClick={() => setStep(4)}>Continue</Btn>
                </div>
              </Card>
            )}
            {step === 4 && (
              <Card padding>
                <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>Suggested workflows</div>
                <div style={{ fontSize: 12.5, color: 'var(--p-color-text-secondary)', marginBottom: 16 }}>Turn these on now or skip — you can add more later.</div>
                {[
                  ['VIP win-back', 'Weekly · email VIPs who haven\'t ordered in 30+ days', true],
                  ['Low inventory pause', 'When SKU stock < 10 → pause Spin to Win widget', true],
                  ['Welcome new customer', 'On first order → give them a 10% next-order code', false],
                  ['Daily ops summary', 'Every morning at 8am → Slack with KPIs', false],
                ].map(([n, t, on]) => (
                  <div key={n} style={{
                    padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 10,
                    border: '1px solid var(--p-color-border)', borderRadius: 8, marginBottom: 6,
                  }}>
                    <I.layers size={14} style={{ color: 'var(--p-color-text-magic)' }} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 600 }}>{n}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>{t}</div>
                    </div>
                    <Toggle on={on} />
                  </div>
                ))}
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 18 }}>
                  <Btn onClick={() => setStep(3)}>Back</Btn>
                  <Btn variant="magic" icon={I.sparkle} onClick={() => set({ setupDone: true })}>Finish setup</Btn>
                </div>
              </Card>
            )}
          </div>
        </div>
      </Page>
    </div>
  );
}

function SourceCheckRow({ name, count, on, kind }) {
  const [v, setV] = React.useState(on);
  return (
    <div style={{
      padding: '8px 10px', display: 'flex', alignItems: 'center', gap: 10,
      border: '1px solid var(--p-color-border-secondary)', borderRadius: 8, marginBottom: 4,
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 6,
        background: kind === 'app' ? 'var(--p-color-bg-fill-magic)' : 'rgba(94,142,62,0.12)',
        color: kind === 'app' ? 'var(--p-color-text-magic)' : '#3a6420',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{kind === 'app' ? <I.wand size={11} /> : <I.store size={11} />}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 500 }}>{name}</div>
        <div style={{ fontSize: 11, color: 'var(--p-color-text-secondary)' }}>{count}</div>
      </div>
      <Toggle on={v} onChange={setV} />
    </div>
  );
}

function Toggle({ on, onChange }) {
  return (
    <button
      onClick={() => onChange && onChange(!on)}
      style={{
        appearance: 'none', border: 'none', cursor: 'pointer',
        width: 32, height: 18, borderRadius: 999,
        background: on ? 'var(--p-color-bg-fill-success-active)' : 'var(--p-color-bg-fill-tertiary)',
        position: 'relative', padding: 0,
        transition: 'background .15s',
      }}
    >
      <div style={{
        position: 'absolute', top: 2, left: on ? 16 : 2,
        width: 14, height: 14, borderRadius: '50%',
        background: 'white', boxShadow: '0 1px 2px rgba(0,0,0,0.15)',
        transition: 'left .15s',
      }} />
    </button>
  );
}

function AgentSetupDialog({ set, a }) {
  return (
    <Dialog title="Brain settings" icon={I.settings} onClose={() => set({ showSetup: false })}>
      <div style={{ fontSize: 13, color: 'var(--p-color-text-secondary)', marginBottom: 14 }}>
        Adjust your Brain's sources, permissions, and tone. For a full re-setup, click "Re-run wizard".
      </div>
      {/* simplified */}
      <div style={{ display: 'grid', gap: 12 }}>
        {[
          { label: 'Name', value: "Sarah's Brain" },
          { label: 'Tone', value: 'Professional' },
          { label: 'Permission level', value: 'Approval required' },
          { label: 'Data sources', value: '5 Shopify scopes · 4 apps' },
          { label: 'Active workflows', value: '3 of 4 on' },
        ].map((r) => (
          <div key={r.label} style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '6px 0', borderBottom: '1px solid var(--p-color-border-secondary)' }}>
            <div style={{ fontSize: 12, color: 'var(--p-color-text-secondary)', flex: 1 }}>{r.label}</div>
            <div style={{ fontSize: 13 }}>{r.value}</div>
            <Btn variant="plain" size="sm" icon={I.edit} />
          </div>
        ))}
      </div>
      <Btn variant="plain" size="sm" style={{ marginTop: 12 }} onClick={() => set({ setupDone: false, showSetup: false })}>Re-run setup wizard</Btn>
    </Dialog>
  );
}

// ─── Agent chat ──────────────────────────────────────────────
function AgentChat({ set, chat, pendingPlan, a }) {
  const [draft, setDraft] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [chat, busy, pendingPlan]);

  const send = (text) => {
    if (!text.trim()) return;
    const msgs = [...chat, { role: 'user', content: text, ts: 'just now' }];
    set({ chat: msgs });
    setDraft('');
    setBusy(true);

    // canned multi-stage response
    setTimeout(() => {
      // stage 1: tool call
      set((s) => ({
        chat: [...s.chat, {
          role: 'ai', ts: 'just now',
          content: `Let me query your customers — VIP segment with no orders in 30+ days.`,
          tool: {
            name: 'Shopify.customers.search',
            args: { tag: 'VIP', lastOrderDate: '<30d ago' },
            result: { count: 47, sample: [
              ['Anna T.', 'anna@…', '42d ago', '$840 LTV'],
              ['Minh L.', 'minhl@…', '38d ago', '$1,210 LTV'],
              ['Priya S.', 'priya@…', '31d ago', '$612 LTV'],
            ]},
          },
        }],
      }));
      setTimeout(() => {
        // stage 2: action plan
        set((s) => ({
          chat: [...s.chat, {
            role: 'ai', ts: 'just now',
            content: `Found **47 VIP customers** who haven't ordered in 30+ days. Average LTV is $890. Want me to send them a comeback offer?`,
            suggestions: [
              { label: 'Send 15% off · all 47', primary: true, action: 'plan' },
              { label: 'Show all 47', action: 'list' },
              { label: 'Just send Slack alert', action: 'slack' },
            ],
          }],
        }));
        setBusy(false);
      }, 900);
    }, 1000);
  };

  const onSuggest = (s) => {
    if (s.action === 'plan') {
      // show approval plan
      set({
        pendingPlan: {
          title: 'Re-engage 47 VIP customers',
          steps: [
            { name: 'Create coupon code', detail: 'VIP-COMEBACK-15 · 15% off · valid 14 days', app: 'Coupon Manager', destructive: false },
            { name: 'Apply to 47 customers', detail: 'Restrict redemption to listed customer IDs', app: 'Coupon Manager', destructive: false },
            { name: 'Send email', detail: 'Subject: "We miss you, Anna. Here\'s 15% back." · personalized per recipient', app: 'Shopify Email', destructive: false },
          ],
          impact: ['47 emails will be sent', '1 new discount code created', 'Estimated 6.4 orders recovered (based on 13.6% win-back rate)'],
        },
      });
    } else if (s.action === 'list') {
      set((st) => ({
        chat: [...st.chat, { role: 'ai', ts: 'just now', content: 'Here are all 47 — sorted by LTV.', dataTable: true }],
      }));
    } else {
      set((st) => ({
        chat: [...st.chat, { role: 'ai', ts: 'just now', content: 'OK — sent a Slack note to #marketing with the segment.' }],
      }));
    }
  };

  const empty = chat.length === 0;
  return (
    <>
      {empty ? (
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '40px 32px', maxWidth: 720, margin: '0 auto' }}>
          <div style={{ textAlign: 'center', marginBottom: 28 }}>
            <div style={{
              width: 56, height: 56, borderRadius: 16,
              background: 'linear-gradient(135deg, var(--p-color-bg-fill-magic-active) 0%, #a18bff 100%)',
              color: 'white', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              marginBottom: 14, boxShadow: '0 8px 24px rgba(107,70,193,0.25)',
            }}>
              <I.sparkle size={28} />
            </div>
            <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: -0.5, marginBottom: 6 }}>
              Ask Sarah's Brain anything
            </div>
            <div style={{ fontSize: 14, color: 'var(--p-color-text-secondary)' }}>
              Connected to your shop and {CONNECTED_SOURCES.length} data sources. Try one of these — or just ask.
            </div>
          </div>

          <Card style={{ padding: 14, marginBottom: 20 }}>
            <Input
              multiline rows={3} autoFocus
              value={draft} onChange={setDraft}
              onKeyDown={(e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); send(draft); } }}
              placeholder={'e.g. "How many VIP customers haven\'t ordered in 30 days?"'}
            />
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>
              <Btn variant="plain" size="sm" icon={I.paperclip}>Attach</Btn>
              <Btn variant="plain" size="sm" icon={I.store}>Scope to app</Btn>
              <div style={{ flex: 1 }} />
              <span style={{ fontSize: 11, color: 'var(--p-color-text-secondary)' }}><span className="p-mono">⌘↵</span></span>
              <Btn variant="magic" icon={I.send} onClick={() => send(draft)} disabled={!draft.trim()}>Ask</Btn>
            </div>
          </Card>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
            {AGENT_SAMPLE_QUERIES.map((q) => {
              const Icn = I[q.icon] || I.sparkle;
              return (
                <Card key={q.t} onClick={() => send(q.t)} style={{ padding: 12, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: 8,
                    background: 'var(--p-color-bg-fill-magic)',
                    color: 'var(--p-color-text-magic)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                  }}><Icn size={14} /></div>
                  <div style={{ flex: 1, minWidth: 0, fontSize: 12.5, color: 'var(--p-color-text)', fontWeight: 500 }}>{q.t}</div>
                  <I.chevronRight size={12} />
                </Card>
              );
            })}
          </div>
        </div>
      ) : (
        <>
          <div style={{
            padding: '12px 20px', borderBottom: '1px solid var(--p-color-border-secondary)',
            background: 'var(--p-color-bg-surface)', display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <AIAvatar size={28} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>Sarah's Brain</div>
              <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>VIP win-back coupon</div>
            </div>
            <Badge tone="magic" dot>Approval mode</Badge>
            <Btn variant="plain" size="sm" icon={I.more} />
          </div>
          <div ref={scrollRef} className="p-scroll" style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: '20px 20px 12px' }}>
            <div style={{ maxWidth: 720, margin: '0 auto' }}>
              {chat.map((m, i) => <AgentMessage key={i} m={m} onSuggest={onSuggest} />)}
              {busy && (
                <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 12 }}>
                  <AIAvatar size={24} />
                  <div style={{ padding: '8px 12px', background: 'var(--p-color-bg-fill-magic)', color: 'var(--p-color-text-magic)', borderRadius: 12, display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5 }}>
                    <ThinkingDots /> querying your shop…
                  </div>
                </div>
              )}
              {pendingPlan && <ActionPlanCard plan={pendingPlan} set={set} />}
            </div>
          </div>
          <div style={{ padding: '12px 20px', borderTop: '1px solid var(--p-color-border-secondary)', background: 'var(--p-color-bg-surface)' }}>
            <div style={{ maxWidth: 720, margin: '0 auto' }}>
              <Card style={{ padding: 8 }}>
                <Input
                  multiline rows={2}
                  value={draft} onChange={setDraft}
                  onKeyDown={(e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); send(draft); } }}
                  placeholder="Follow up — ask, refine, or instruct…"
                />
                <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 6 }}>
                  <Btn variant="plain" size="sm" icon={I.paperclip} />
                  <Btn variant="plain" size="sm" icon={I.store} title="Scope to a source" />
                  <div style={{ flex: 1 }} />
                  <Btn variant="magic" size="sm" icon={I.send} onClick={() => send(draft)} disabled={!draft.trim() || busy}>Send</Btn>
                </div>
              </Card>
            </div>
          </div>
        </>
      )}
    </>
  );
}

function AgentMessage({ m, onSuggest }) {
  if (m.role === 'user') {
    return (
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 14 }}>
        <div style={{
          maxWidth: 540, background: 'var(--p-color-bg-inverse)', color: 'white',
          padding: '10px 14px', borderRadius: '14px 14px 4px 14px',
          fontSize: 13.5, lineHeight: 1.5,
        }}>{m.content}</div>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
      <AIAvatar size={26} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          background: 'var(--p-color-bg-surface)', border: '1px solid var(--p-color-border-secondary)',
          padding: '10px 14px', borderRadius: '4px 14px 14px 14px',
          fontSize: 13.5, lineHeight: 1.5,
        }} dangerouslySetInnerHTML={{ __html: renderMd(m.content) }} />
        {m.tool && <ToolCallCard tool={m.tool} />}
        {m.dataTable && <BigDataTable />}
        {m.suggestions && (
          <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
            {m.suggestions.map((s) => (
              <Btn key={s.label} variant={s.primary ? 'magic' : 'secondary'} size="sm"
                icon={s.primary ? I.sparkle : null}
                onClick={() => onSuggest(s)}>{s.label}</Btn>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function ToolCallCard({ tool }) {
  return (
    <Card style={{ marginTop: 8, overflow: 'hidden' }}>
      <div style={{
        padding: '6px 10px', background: 'var(--p-color-bg-surface-secondary)',
        borderBottom: '1px solid var(--p-color-border-secondary)',
        display: 'flex', alignItems: 'center', gap: 8,
        fontSize: 11.5,
      }}>
        <I.spinner size={11} style={{ color: 'var(--p-color-text-magic)', animation: 'none' }} />
        <span className="p-mono" style={{ fontWeight: 600 }}>{tool.name}</span>
        <span style={{ color: 'var(--p-color-text-secondary)' }} className="p-mono">
          {JSON.stringify(tool.args).replace(/[{}"]/g, '').replace(/,/g, ', ')}
        </span>
        <div style={{ flex: 1 }} />
        <Badge tone="success" dot style={{ fontSize: 10 }}>{tool.result.count != null ? tool.result.count + ' rows' : 'ok'}</Badge>
      </div>
      {tool.result.sample && (
        <div style={{ padding: 6 }}>
          <div className="p-table__head" style={{ gridTemplateColumns: '1.2fr 1.4fr 1fr 0.9fr', borderRadius: 0, padding: '6px 10px', background: 'transparent', borderBottom: '1px solid var(--p-color-border-secondary)' }}>
            <div>Name</div><div>Email</div><div>Last order</div><div style={{ textAlign: 'right' }}>LTV</div>
          </div>
          {tool.result.sample.map((r, i) => (
            <div key={i} className="p-table__row" style={{ gridTemplateColumns: '1.2fr 1.4fr 1fr 0.9fr', padding: '7px 10px', fontSize: 12 }}>
              <div style={{ fontWeight: 500 }}>{r[0]}</div>
              <div className="p-mono" style={{ color: 'var(--p-color-text-secondary)' }}>{r[1]}</div>
              <div style={{ color: 'var(--p-color-text-secondary)' }}>{r[2]}</div>
              <div style={{ textAlign: 'right' }} className="p-mono">{r[3]}</div>
            </div>
          ))}
          <div style={{ textAlign: 'center', padding: '6px 0', fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>
            + 44 more · <a style={{ color: 'var(--p-color-text-link)', cursor: 'pointer' }}>show all</a>
          </div>
        </div>
      )}
    </Card>
  );
}

function BigDataTable() {
  // Just visual; show 8 more rows
  const rows = [
    ['Anna T.', 'anna@…', '42d ago', '$840'],
    ['Minh L.', 'minhl@…', '38d ago', '$1,210'],
    ['Priya S.', 'priya@…', '31d ago', '$612'],
    ['Marcus R.', 'mrx@…', '45d ago', '$1,820'],
    ['Linh P.', 'linh@…', '37d ago', '$430'],
    ['Yuki H.', 'yuki@…', '33d ago', '$2,100'],
    ['Theo W.', 'theo@…', '49d ago', '$520'],
    ['Hà N.', 'han@…', '36d ago', '$390'],
  ];
  return (
    <Card style={{ marginTop: 8, overflow: 'hidden' }}>
      <div className="p-table__head" style={{ gridTemplateColumns: '1.2fr 1.4fr 1fr 0.9fr', borderRadius: 0, padding: '8px 12px' }}>
        <div>Name</div><div>Email</div><div>Last order</div><div style={{ textAlign: 'right' }}>LTV</div>
      </div>
      {rows.map((r, i) => (
        <div key={i} className="p-table__row" style={{ gridTemplateColumns: '1.2fr 1.4fr 1fr 0.9fr', padding: '8px 12px' }}>
          <div style={{ fontWeight: 500 }}>{r[0]}</div>
          <div className="p-mono" style={{ color: 'var(--p-color-text-secondary)' }}>{r[1]}</div>
          <div style={{ color: 'var(--p-color-text-secondary)' }}>{r[2]}</div>
          <div style={{ textAlign: 'right' }} className="p-mono">{r[3]}</div>
        </div>
      ))}
      <div style={{ padding: '8px 12px', background: 'var(--p-color-bg-surface-secondary)', borderTop: '1px solid var(--p-color-border-secondary)', fontSize: 12, color: 'var(--p-color-text-secondary)', textAlign: 'center' }}>
        Showing 8 of 47 · <a style={{ color: 'var(--p-color-text-link)', cursor: 'pointer' }}>Export CSV</a>
      </div>
    </Card>
  );
}

function ActionPlanCard({ plan, set }) {
  const [executing, setExecuting] = React.useState(false);
  const [progress, setProgress] = React.useState(0);
  const [done, setDone] = React.useState(false);

  const approve = () => {
    setExecuting(true);
    let step = 0;
    const tick = () => {
      step++;
      setProgress(step);
      if (step < plan.steps.length) setTimeout(tick, 700);
      else {
        setTimeout(() => {
          setDone(true);
          set((s) => ({
            pendingPlan: null,
            chat: [...s.chat, {
              role: 'ai', ts: 'just now',
              content: `Done — all 3 steps executed. **47 emails queued · 1 code created**. Want to save this as a recurring workflow?`,
              saveAsFlow: true,
            }],
          }));
        }, 500);
      }
    };
    setTimeout(tick, 600);
  };

  return (
    <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
      <AIAvatar size={26} />
      <Card style={{
        flex: 1, borderColor: 'var(--p-color-border-magic)',
        boxShadow: '0 0 0 1px var(--p-color-border-magic), 0 8px 24px rgba(107,70,193,0.08)',
      }}>
        <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--p-color-border-secondary)', display: 'flex', alignItems: 'center', gap: 8 }}>
          <I.sparkle size={14} style={{ color: 'var(--p-color-text-magic)' }} />
          <div style={{ fontSize: 13, fontWeight: 600 }}>Action plan</div>
          <Badge tone="magic">{plan.steps.length} steps · needs approval</Badge>
          <div style={{ flex: 1 }} />
          <span style={{ fontSize: 12, fontWeight: 600 }}>{plan.title}</span>
        </div>
        <div style={{ padding: '10px 14px' }}>
          {plan.steps.map((s, i) => {
            const stepDone = progress > i;
            const stepCurrent = executing && progress === i;
            return (
              <div key={i} style={{ display: 'flex', gap: 10, padding: '8px 0', borderBottom: i < plan.steps.length - 1 ? '1px solid var(--p-color-border-secondary)' : 'none', alignItems: 'flex-start' }}>
                <div style={{
                  width: 22, height: 22, borderRadius: '50%',
                  background: stepDone ? 'var(--p-color-bg-fill-success-active)' : stepCurrent ? 'var(--p-color-bg-fill-magic-active)' : 'var(--p-color-bg-fill-tertiary)',
                  color: stepDone || stepCurrent ? 'white' : 'var(--p-color-text-secondary)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontWeight: 700, fontSize: 11, flexShrink: 0,
                }}>{stepDone ? <I.check size={11} /> : stepCurrent ? <I.spinner size={11} /> : i + 1}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{s.name}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)' }}>{s.detail}</div>
                </div>
                <Badge>{s.app}</Badge>
              </div>
            );
          })}
          <div style={{ marginTop: 12, padding: 10, background: 'var(--p-color-bg-fill-info)', borderRadius: 8, fontSize: 11.5, color: 'var(--p-color-text-info)' }}>
            <b>Impact preview:</b>
            <ul style={{ margin: '4px 0 0', paddingLeft: 18 }}>
              {plan.impact.map((l, i) => <li key={i}>{l}</li>)}
            </ul>
          </div>
        </div>
        <div style={{ padding: '10px 14px', background: 'var(--p-color-bg-surface-secondary)', borderTop: '1px solid var(--p-color-border-secondary)', display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          {!executing && !done && (
            <>
              <Btn size="sm" onClick={() => set({ pendingPlan: null })}>Cancel</Btn>
              <Btn size="sm">Step by step</Btn>
              <Btn variant="magic" size="sm" icon={I.sparkle} onClick={approve}>Approve &amp; run</Btn>
            </>
          )}
          {executing && !done && (
            <>
              <span style={{ fontSize: 12, color: 'var(--p-color-text-secondary)', display: 'flex', alignItems: 'center', gap: 6 }}>
                <I.spinner /> Executing step {progress + 1} of {plan.steps.length}…
              </span>
            </>
          )}
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { RouteAgent });
