// Loop MVP — People + Agent screens

const Dp = () => window.LOOP_DATA;

// ─────────────────────────────────────────────────────────────
// PeopleScreen — "my people" view with grouping & filters
// ─────────────────────────────────────────────────────────────
function PeopleScreen({ persona, go }) {
  const people = Dp().people;
  const [filter, setFilter] = React.useState('all');
  const [query, setQuery] = React.useState('');
  const filters = [
    { key: 'all', label: 'Everyone' },
    { key: 'needs-attention', label: 'Needs a touch' },
    { key: 'Investors', label: 'Investors' },
    { key: 'Team', label: 'Team' },
    { key: 'Candidates', label: 'Candidates' },
    { key: 'Customers', label: 'Customers' },
  ];
  const filtered = people.filter(p => {
    if (filter !== 'all' && filter !== 'needs-attention' && p.group !== filter) return false;
    if (filter === 'needs-attention' && p.status !== 'needs-attention') return false;
    if (query && !p.name.toLowerCase().includes(query.toLowerCase())) return false;
    return true;
  });
  // group
  const groups = {};
  filtered.forEach(p => { (groups[p.group] = groups[p.group] || []).push(p); });

  return (
    <Screen>
      <Header large title="My people" eyebrow="Relationships under management" />

      <div style={{ padding: '14px 22px 8px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px',
          background: 'var(--canvas-lifted)', borderRadius: 999 }}>
          <Icon name="search" size={18} color="var(--slate)" />
          <input value={query} onChange={(e) => setQuery(e.target.value)}
            placeholder="Search 248 people"
            style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 450 }} />
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '12px 22px 8px' }}>
        {filters.map(f => (
          <button key={f.key} onClick={() => setFilter(f.key)} style={{
            padding: '8px 16px', borderRadius: 999,
            border: filter === f.key ? '1.5px solid var(--ink)' : '1.5px solid rgba(20,20,19,0.15)',
            background: filter === f.key ? 'var(--ink)' : 'transparent',
            color: filter === f.key ? 'var(--canvas)' : 'var(--ink)',
            fontSize: 13, fontWeight: 500, cursor: 'pointer', whiteSpace: 'nowrap',
          }}>{f.label}</button>
        ))}
      </div>

      {Object.entries(groups).map(([groupName, list]) => (
        <Section key={groupName} eyebrow={groupName} title="" style={{ marginTop: 8 }}>
          <Card style={{ padding: '4px 20px' }}>
            {list.map((p, i) => (
              <Row key={p.id} divider={i < list.length - 1}
                leading={<Avatar initials={p.initials} tint={p.tint} size={44} photo={p.photo} />}
                title={p.name}
                subtitle={`${p.role} · last ${p.last}`}
                trailing={<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <Dot tone={p.status === 'needs-attention' ? 'high' : p.status === 'warm' ? 'med' : 'success'} />
                  <Icon name="chevron-right" size={16} color="var(--slate)" />
                </div>}
                onClick={() => go('person', { id: p.id })} />
            ))}
          </Card>
        </Section>
      ))}
      <div style={{ height: 24 }} />
    </Screen>
  );
}

// ─────────────────────────────────────────────────────────────
// PersonScreen — relationship detail
// ─────────────────────────────────────────────────────────────
function PersonScreen({ persona, go, params }) {
  const p = Dp().people.find(x => x.id === params?.id) || Dp().people[0];
  const dossier = (Dp().dossiers && (Dp().dossiers[p.id] || Dp().dossiers._default)) || { pillars: [] };

  const timeline = [
    { when: 'Today 09:30', kind: 'meeting', body: 'Series C check-in · upcoming', detail: 'You + Jess Lee' },
    { when: 'Tue', kind: 'email', body: 'Asked for an updated cap table.', detail: 'Inbound · Gmail' },
    { when: 'May 5', kind: 'meeting', body: 'Board call · captured by Loop', detail: '7 decisions, 12 actions' },
    { when: 'Apr 28', kind: 'note', body: 'Birthday on May 23. Likes single-origin coffee.', detail: 'Your note' },
    { when: 'Apr 14', kind: 'meeting', body: 'First Series C conversation', detail: 'Loop summary' },
  ];

  return (
    <Screen padBottom={130}>
      <Header back={() => go('people')} title="" trailing={
        <button style={{ width: 40, height: 40, borderRadius: '50%', background: 'transparent', border: 'none', cursor: 'pointer' }}>
          <Icon name="more-horizontal" size={22} /></button>} />

      {/* Hero portrait */}
      <div style={{ padding: '8px 22px 24px', textAlign: 'center', position: 'relative' }}>
        <div style={{ position: 'absolute', left: 0, right: 0, top: 50 }}>
          <OrbitalArc width={400} height={120} opacity={0.5} />
        </div>
        <div style={{ position: 'relative', display: 'inline-block' }}>
          <Avatar initials={p.initials} tint={p.tint} size={170} photo={p.photo} />
          <div style={{ position: 'absolute', bottom: 4, right: -4 }}>
            <SatelliteCTA icon="message-circle" size={48} />
          </div>
        </div>
        <h1 style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.025em', margin: '20px 0 4px' }}>{p.name}</h1>
        <div style={{ fontSize: 14, color: 'var(--slate)' }}>{p.role}</div>
        <div style={{ marginTop: 16, display: 'inline-flex', gap: 8 }}>
          <Chip tone={p.status === 'needs-attention' ? 'warning' : p.status === 'warm' ? 'default' : 'success'}>
            {p.status.replace('-', ' ')}
          </Chip>
          <Chip>last {p.last}</Chip>
        </div>
      </div>

      {/* Next move */}
      <Section eyebrow="Next move" title="" style={{ marginTop: 4 }}>
        <Card ink style={{ padding: 22 }}>
          <div style={{ fontSize: 18, fontWeight: 500, letterSpacing: '-0.01em', lineHeight: 1.3 }}>{p.next}</div>
          <div style={{ marginTop: 12, fontSize: 13, color: 'rgba(252,251,250,0.6)' }}>
            Loop will brief you 30 minutes before the meeting.
          </div>
        </Card>
      </Section>

      {/* CIA-level dossier */}
      <Section eyebrow="The dossier" title="What you need to know" style={{ marginTop: 22 }}
        action={<Chip tone="success"><Dot tone="success" size={6} /> Updated 12m</Chip>}>
        <Card style={{ padding: 22, position: 'relative', overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <Icon name="lock" size={14} color="var(--slate)" />
            <span style={{ fontSize: 11, color: 'var(--slate)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700 }}>
              Confidential · your eyes only
            </span>
          </div>
          <p style={{ fontSize: 13, color: 'var(--slate)', lineHeight: 1.45, margin: '8px 0 0' }}>
            Assembled by Loop from CRM, public sources, your inbox, and prior meetings.
          </p>
        </Card>

        {dossier.pillars.map((pillar, i) => (
          <Card key={i} style={{ marginTop: 10, padding: 20 }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
              <span style={{ fontSize: 18, fontWeight: 500, letterSpacing: '-0.02em', color: 'var(--loop-orange-light)', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>
                {String(i + 1).padStart(2, '0')}
              </span>
              <Eyebrow>{pillar.label}</Eyebrow>
            </div>
            <p style={{ marginTop: 10, fontSize: 14, lineHeight: 1.5, color: 'var(--ink)' }}>{pillar.body}</p>
          </Card>
        ))}
      </Section>

      {/* Quick stats */}
      <Section eyebrow="Numbers" title="" style={{ marginTop: 22 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
          {[
            { label: 'Touches · 30d', value: '7' },
            { label: 'Avg response', value: '4h' },
            { label: 'Open threads', value: '2' },
          ].map((s, i) => (
            <Card key={i} style={{ padding: 14, textAlign: 'center' }}>
              <div style={{ fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em' }}>{s.value}</div>
              <div style={{ marginTop: 4, fontSize: 11, color: 'var(--slate)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{s.label}</div>
            </Card>
          ))}
        </div>
      </Section>

      {/* Timeline */}
      <Section eyebrow="Together" title="History" style={{ marginTop: 22 }}>
        <Card style={{ padding: '4px 20px' }}>
          {timeline.map((t, i) => {
            const ICON = { meeting: 'video', email: 'mail', note: 'sticky-note' }[t.kind];
            return (
              <Row key={i} divider={i < timeline.length - 1}
                leading={<div style={{ width: 56 }}>
                  <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--ink)' }}>{t.when}</div>
                  <div style={{ fontSize: 11, color: 'var(--slate)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{t.kind}</div>
                </div>}
                title={t.body} subtitle={t.detail}
                trailing={<Icon name={ICON} size={18} color="var(--slate)" />} />
            );
          })}
        </Card>
      </Section>

      <div style={{ position: 'sticky', bottom: 12, marginTop: 24, marginLeft: 0, marginRight: 0, display: 'flex', gap: 10 }}>
        <Button variant="secondary" style={{ flex: 1 }} icon={<Icon name="mail" size={16} />}>Draft</Button>
        <Button variant="primary" style={{ flex: 1 }} icon={<Icon name="calendar" size={16} color="var(--canvas)" />}>Schedule</Button>
        <Button variant="signal" style={{ flex: 1 }} icon={<Icon name="sparkles" size={16} color="var(--white)" />}>Ask</Button>
      </div>
    </Screen>
  );
}

// ─────────────────────────────────────────────────────────────
// AgentsScreen — agent library / dashboard
// ─────────────────────────────────────────────────────────────
function AgentsScreen({ persona, go }) {
  const agents = Dp().agents[persona];

  return (
    <Screen>
      <Header large title="Agents" eyebrow="Your stack" trailing={
        <button onClick={() => go('agent-builder')}
          style={{ width: 40, height: 40, borderRadius: '50%', background: 'var(--ink)', color: 'var(--canvas)',
            border: 'none', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="plus" size={20} color="var(--canvas)" />
        </button>} />

      <Section style={{ marginTop: 10 }}>
        <Card ink style={{ padding: 22, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', right: -30, top: -30, width: 130, height: 130,
            borderRadius: '50%', border: '1.2px solid rgba(243,115,56,0.3)' }} />
          <Eyebrow style={{ color: 'var(--canvas)' }}>Now running</Eyebrow>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginTop: 12 }}>
            <div style={{ fontSize: 56, fontWeight: 500, letterSpacing: '-0.03em', lineHeight: 1 }}>{agents.length}</div>
            <div style={{ fontSize: 14, color: 'rgba(252,251,250,0.7)' }}>agents · {agents.reduce((s, a) => s + parseInt(a.runs), 0)} runs today</div>
          </div>
          <div style={{ marginTop: 14, fontSize: 14, color: 'rgba(252,251,250,0.65)', maxWidth: 280, lineHeight: 1.4 }}>
            All routed to your inbox, your CRM, and your daily brief. Tap any agent to coordinate.
          </div>
        </Card>
      </Section>

      <Section eyebrow="Your agents" title="" style={{ marginTop: 22 }}>
        {agents.map((a, i) => (
          <Card key={a.id} onClick={() => go('agent-chat', { id: a.id })}
            style={{ marginBottom: 10, padding: 20 }}>
            <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
              <div style={{ width: 48, height: 48, borderRadius: '50%', background: 'var(--canvas-whisper)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name="sparkles" size={22} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                  <div style={{ fontSize: 17, fontWeight: 500, letterSpacing: '-0.01em' }}>{a.name}</div>
                  {a.live && <Chip tone="success"><Dot tone="success" size={6} /> Live</Chip>}
                </div>
                <div style={{ fontSize: 14, color: 'var(--slate)', lineHeight: 1.4 }}>{a.role}</div>
                <div style={{ marginTop: 12, display: 'flex', gap: 14, fontSize: 11,
                  color: 'var(--slate)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
                  <span>{a.skills} skills</span>
                  <span>·</span>
                  <span>{a.runs}</span>
                </div>
              </div>
              <Icon name="chevron-right" size={20} color="var(--slate)" />
            </div>
          </Card>
        ))}
      </Section>

      <Section eyebrow="Pre-built" title="Add a starter" style={{ marginTop: 22 }}>
        <div style={{ display: 'flex', gap: 12, overflowX: 'auto', padding: '0 22px 4px', margin: '0 -22px' }}>
          {[
            { name: 'Investor relations', desc: 'Briefs + cap table awareness.', tint: '#CF4500' },
            { name: 'Customer success', desc: 'Renewal radar + health scores.', tint: '#3860BE' },
            { name: 'Deal review', desc: 'Reads CRM, flags risk.', tint: '#1F7A4D' },
            { name: 'Recruiting', desc: 'Pipeline keeper + panel summaries.', tint: '#9A3A0A' },
          ].map((s, i) => (
            <Card key={i} style={{ minWidth: 220, padding: 18 }}>
              <Avatar initials={s.name[0]} tint={s.tint} size={36} />
              <div style={{ fontSize: 15, fontWeight: 500, marginTop: 10 }}>{s.name}</div>
              <div style={{ fontSize: 12, color: 'var(--slate)', marginTop: 2, lineHeight: 1.4 }}>{s.desc}</div>
              <Button variant="secondary" size="sm" style={{ marginTop: 14 }}>Add</Button>
            </Card>
          ))}
        </div>
      </Section>

      <Section style={{ marginTop: 22, paddingBottom: 24 }}>
        <Card lifted style={{ padding: 22 }} onClick={() => go('agent-builder')}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--loop-orange)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="plus" size={26} color="var(--white)" />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 17, fontWeight: 500 }}>Build your own agent</div>
              <div style={{ fontSize: 13, color: 'var(--slate)', marginTop: 2 }}>No code. Define role, data, triggers, outputs.</div>
            </div>
            <SatelliteCTA icon="arrow-right" size={40} />
          </div>
        </Card>
      </Section>
    </Screen>
  );
}

// ─────────────────────────────────────────────────────────────
// AgentChatScreen — converse with one agent
// ─────────────────────────────────────────────────────────────
function AgentChatScreen({ persona, go, params }) {
  const agent = Dp().agents[persona].find(a => a.id === params?.id) || Dp().agents[persona][0];
  const seed = persona === 'principal' ? [
    { from: 'agent', body: `Aurélien — I pulled three things for Sequoia at 09:30.\n\n1. Roelof opened the cap table 04:12 ago and spent 4 minutes on slide 7. He's anchoring on dilution.\n\n2. Jess Lee has never been in a Helix call. I added her LinkedIn and the four founders she's backed in the last 12 months to your brief.\n\n3. Two open threads from last call. The September close timeline is the riskier one to address.` },
    { from: 'user', body: 'What\'s my best move on the timeline?' },
    { from: 'agent', body: `Buy two weeks. Frame it as diligence depth, not hesitation. Suggested line: "We're nine days out from clean Q1 numbers and a hiring close. I'd like the term sheet in hand by August 5, signed by August 19." That gives you headroom without losing momentum.` },
  ] : [
    { from: 'agent', body: `Sana — Mae Chen at 09:30. Three things to know.\n\n1. Devon's round-1 notes landed last night: 7/10 systems design, hesitation on cross-functional conflict. I've prepped a probe for that.\n\n2. Mae is at final stage at Anthropic. Their offer hits her inbox by Friday. We have today and tomorrow.\n\n3. Comp expectation in round 1: $340 base, 1.0% equity. That's inside our band.` },
    { from: 'user', body: 'Compare Mae and Yara for me.' },
    { from: 'agent', body: `Opening the comparison view. Mae leads on cultural fit (8 vs 6), Yara on scale jump readiness (9 vs 6). Compensation ask is similar. Decision frame: do you need a builder (Mae) or a scaler (Yara)?` },
  ];
  const [messages, setMessages] = React.useState(seed);
  const [input, setInput] = React.useState('');
  const scrollRef = React.useRef(null);
  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = () => {
    if (!input.trim()) return;
    const q = input.trim();
    setMessages(m => [...m, { from: 'user', body: q }]);
    setInput('');
    setTimeout(() => {
      setMessages(m => [...m, { from: 'agent', body: `Working on it. Pulling from CRM, your inbox, and the dataroom. A draft is ready — review it in 30 seconds.`, thinking: true }]);
    }, 600);
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
      <Header back={() => go('agents')}
        title={<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--ink)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="sparkles" size={16} color="var(--canvas)" />
          </div>
          <div>
            <div style={{ fontSize: 15, fontWeight: 500, lineHeight: 1.1 }}>{agent.name}</div>
            <div style={{ fontSize: 11, color: 'var(--success)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <Dot tone="success" size={6} /> Active · {agent.skills} skills
            </div>
          </div>
        </div>}
        trailing={<button style={{ width: 40, height: 40, borderRadius: '50%', background: 'transparent', border: 'none', cursor: 'pointer' }}>
          <Icon name="sliders-horizontal" size={20} /></button>} />

      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '12px 22px 120px' }}>
        {messages.map((msg, i) => (
          <div key={i} style={{ marginBottom: 16, display: 'flex',
            justifyContent: msg.from === 'user' ? 'flex-end' : 'flex-start' }}>
            <div style={{
              maxWidth: '82%',
              padding: '14px 18px', borderRadius: 22,
              background: msg.from === 'user' ? 'var(--ink)' : 'var(--canvas-lifted)',
              color: msg.from === 'user' ? 'var(--canvas)' : 'var(--ink)',
              borderBottomRightRadius: msg.from === 'user' ? 6 : 22,
              borderBottomLeftRadius: msg.from === 'agent' ? 6 : 22,
              fontSize: 15, lineHeight: 1.45, whiteSpace: 'pre-wrap',
            }}>{msg.body}</div>
          </div>
        ))}
      </div>

      {/* Quick-action chips */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 80, padding: '0 22px 10px',
        display: 'flex', gap: 8, overflowX: 'auto' }}>
        {['Brief me on next', 'Draft a follow-up', 'Compare candidates', 'Status on Series C'].map((s, i) => (
          <button key={i} onClick={() => setInput(s)} style={{
            padding: '8px 14px', borderRadius: 999,
            border: '1.5px solid rgba(20,20,19,0.18)',
            background: 'var(--canvas-lifted)', color: 'var(--ink)',
            fontSize: 12, fontWeight: 500, cursor: 'pointer', whiteSpace: 'nowrap',
          }}>{s}</button>
        ))}
      </div>

      {/* Input */}
      <div style={{ position: 'absolute', left: 16, right: 16, bottom: 26,
        background: 'var(--canvas-lifted)', borderRadius: 26, padding: 6,
        display: 'flex', alignItems: 'center', gap: 8,
        boxShadow: '0 8px 20px rgba(0,0,0,0.06)', zIndex: 40 }}>
        <input value={input} onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && send()}
          placeholder={`Ask ${agent.name.toLowerCase()} anything`}
          style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent',
            padding: '12px 14px', fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 450 }} />
        <button onClick={send} style={{
          width: 44, height: 44, borderRadius: '50%', background: 'var(--ink)',
          color: 'var(--canvas)', border: 'none', cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <Icon name="arrow-up" size={20} color="var(--canvas)" />
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// AgentBuilderScreen — no-code agent builder
// ─────────────────────────────────────────────────────────────
function AgentBuilderScreen({ persona, go }) {
  const [name, setName] = React.useState('Fundraising radar');
  const [role, setRole] = React.useState('Track every conversation with every potential lead investor. Warn me when one goes 5+ days cold.');
  const [skills, setSkills] = React.useState(['s1', 's3', 's5']);
  const [triggers, setTriggers] = React.useState(['daily', 'meeting-end']);
  const [step, setStep] = React.useState(0);

  const allSkills = Dp().skills;
  const stepLabels = ['Identity', 'Skills', 'Triggers', 'Review'];

  const toggle = (set, val, fn) => {
    fn(set.includes(val) ? set.filter(s => s !== val) : [...set, val]);
  };

  return (
    <Screen padBottom={130}>
      <Header back={() => go('agents')} title="New agent" eyebrow={`Step ${step + 1} of ${stepLabels.length}`} />

      {/* Stepper */}
      <div style={{ padding: '8px 22px 4px', display: 'flex', gap: 6 }}>
        {stepLabels.map((_, i) => (
          <div key={i} style={{
            flex: 1, height: 3, borderRadius: 999,
            background: i <= step ? 'var(--ink)' : 'rgba(20,20,19,0.12)',
          }} />
        ))}
      </div>

      {step === 0 && (
        <Section eyebrow="Identity" title="Who is this agent?" style={{ marginTop: 16 }}>
          <Card>
            <label style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.04em',
              textTransform: 'uppercase', color: 'var(--slate)' }}>Name</label>
            <input value={name} onChange={(e) => setName(e.target.value)}
              style={{ width: '100%', marginTop: 8, padding: '12px 0', border: 'none',
                borderBottom: '1.5px solid var(--ink)', background: 'transparent',
                fontFamily: 'var(--font-sans)', fontSize: 22, fontWeight: 500,
                letterSpacing: '-0.02em', outline: 'none' }} />
            <label style={{ marginTop: 22, display: 'block', fontSize: 12, fontWeight: 700, letterSpacing: '0.04em',
              textTransform: 'uppercase', color: 'var(--slate)' }}>Role · what it owns</label>
            <textarea value={role} onChange={(e) => setRole(e.target.value)} rows={4}
              style={{ width: '100%', marginTop: 8, padding: 12, border: '1px solid rgba(20,20,19,0.15)',
                borderRadius: 16, background: 'var(--canvas)',
                fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 450, resize: 'none', outline: 'none' }} />
          </Card>
        </Section>
      )}

      {step === 1 && (
        <Section eyebrow="Skills" title="What can it do?" style={{ marginTop: 16 }}>
          <Card style={{ padding: '4px 20px' }}>
            {allSkills.map((s, i) => (
              <Row key={s.id} divider={i < allSkills.length - 1}
                leading={<div style={{ width: 26, height: 26, borderRadius: 8,
                  border: skills.includes(s.id) ? 'none' : '1.5px solid var(--ink)',
                  background: skills.includes(s.id) ? 'var(--ink)' : 'transparent',
                  color: 'var(--canvas)',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                  {skills.includes(s.id) && <Icon name="check" size={16} color="var(--canvas)" />}
                </div>}
                title={s.name} subtitle={s.desc}
                onClick={() => toggle(skills, s.id, setSkills)} />
            ))}
          </Card>
          <div style={{ marginTop: 10, fontSize: 12, color: 'var(--slate)', padding: '0 4px' }}>
            {skills.length} of {allSkills.length} selected · agents can call any skill in this list
          </div>
        </Section>
      )}

      {step === 2 && (
        <Section eyebrow="Triggers" title="When does it run?" style={{ marginTop: 16 }}>
          <Card style={{ padding: '4px 20px' }}>
            {[
              { id: 'daily', t: 'Daily — 06:30', d: 'Send a morning digest to your inbox.' },
              { id: 'meeting-end', t: 'After every meeting', d: 'Process the recap within 60 seconds.' },
              { id: 'crm', t: 'CRM event', d: 'Trigger when a deal stage changes in Salesforce.' },
              { id: 'mention', t: 'When you mention me', d: '@-mention the agent in chat or in a doc.' },
              { id: 'inbox', t: 'Inbox flag', d: 'Pick up inbound emails with a specific label.' },
            ].map((tr, i, arr) => (
              <Row key={tr.id} divider={i < arr.length - 1}
                leading={<div style={{ width: 38, height: 24, borderRadius: 999,
                  background: triggers.includes(tr.id) ? 'var(--ink)' : 'rgba(20,20,19,0.15)',
                  position: 'relative', transition: 'background 200ms' }}>
                  <div style={{ position: 'absolute', top: 2, left: triggers.includes(tr.id) ? 16 : 2,
                    width: 20, height: 20, borderRadius: '50%', background: 'var(--canvas-lifted)',
                    transition: 'left 200ms', boxShadow: '0 1px 3px rgba(0,0,0,0.1)' }} />
                </div>}
                title={tr.t} subtitle={tr.d}
                onClick={() => toggle(triggers, tr.id, setTriggers)} />
            ))}
          </Card>
        </Section>
      )}

      {step === 3 && (
        <Section eyebrow="Review" title="Ship it?" style={{ marginTop: 16 }}>
          <Card ink style={{ padding: 22 }}>
            <Eyebrow style={{ color: 'var(--canvas)' }}>Custom agent</Eyebrow>
            <h2 style={{ fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 10, lineHeight: 1.2 }}>{name}</h2>
            <p style={{ marginTop: 10, fontSize: 14, color: 'rgba(252,251,250,0.7)', lineHeight: 1.45 }}>{role}</p>
            <div style={{ marginTop: 18, display: 'flex', gap: 14, fontSize: 11,
              textTransform: 'uppercase', letterSpacing: '0.04em', color: 'rgba(252,251,250,0.5)' }}>
              <span>{skills.length} skills</span>
              <span>·</span>
              <span>{triggers.length} triggers</span>
            </div>
          </Card>
          <Card style={{ marginTop: 14 }}>
            <Eyebrow>Data access</Eyebrow>
            <div style={{ marginTop: 10, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {['Salesforce · read+write', 'Gmail · read', 'Drive · read', 'Calendar · read'].map((d, i) => (
                <Chip key={i}>{d}</Chip>
              ))}
            </div>
          </Card>
        </Section>
      )}

      <div style={{ position: 'sticky', bottom: 12, marginTop: 24, marginLeft: 0, marginRight: 0, display: 'flex', gap: 10 }}>
        {step > 0 && <Button variant="secondary" style={{ flex: 1 }} onClick={() => setStep(step - 1)}>Back</Button>}
        {step < 3 && <Button variant="primary" full style={{ flex: 2 }} onClick={() => setStep(step + 1)}
          icon={<Icon name="arrow-right" size={16} color="var(--canvas)" />}>Continue</Button>}
        {step === 3 && <Button variant="signal" full style={{ flex: 2 }} onClick={() => go('agents')}
          icon={<Icon name="sparkles" size={16} color="var(--white)" />}>Ship agent</Button>}
      </div>
    </Screen>
  );
}

Object.assign(window, { PeopleScreen, PersonScreen, AgentsScreen, AgentChatScreen, AgentBuilderScreen });
