// Active Chat screen — streaming Claude Code output, with inline tool blocks

function ChatScreen({ theme }) {
  const t = theme;
  const [msgs, setMsgs] = React.useState([
    { role: 'user', text: 'Refactor the auth middleware — use the new session lib and make sure the tests still pass.' },
    { role: 'assistant', text: "I'll start by reading the current middleware and the new session lib to understand both sides." },
    { role: 'tool', kind: 'Read', name: 'middleware/withAuth.ts', meta: '182 lines · typescript', status: 'done' },
    { role: 'tool', kind: 'Read', name: 'lib/session.ts', meta: '94 lines · typescript', status: 'done' },
    { role: 'assistant', text: 'Replacing the token check with `session.verify()` — this preserves the existing cookie refresh behavior.' },
    { role: 'diff', file: 'middleware/withAuth.ts', added: 6, removed: 4, hunks: [
      { old: '12', new: '12', type: 'rm', text: "-  const token = req.cookies.get('auth')?.value" },
      { old: '-',  new: '12', type: 'add', text: "+  const session = await verify(req)" },
      { old: '13', new: '13', type: 'rm', text: "-  if (!token) return redirect('/login')" },
      { old: '-',  new: '13', type: 'add', text: "+  if (!session) return redirect('/login')" },
    ]},
    { role: 'assistant', text: 'Running the auth test suite.' },
    { role: 'tool', kind: 'Bash', name: 'pnpm test auth', meta: '14 passed · 3.2s', status: 'done', output: '✓ withAuth · redirects unauthenticated  (84ms)\n✓ withAuth · refreshes stale sessions  (112ms)\n✓ session · verify returns null on bad sig' },
    { role: 'assistant', text: 'Before I touch the API routes, I need to confirm which provider is live.', streaming: false },
    { role: 'tool', kind: 'Read', name: '.env.local', meta: 'needs your approval', status: 'pending' },
  ]);

  const [input, setInput] = React.useState('');
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs.length]);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: t.bg, color: t.ink, fontFamily: SEEDEX_FONTS.sans }}>
      {/* Custom header (no iOS nav — replaced) */}
      <div style={{ padding: '58px 20px 14px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: `1px solid ${t.line}`, background: t.bg, position: 'relative', zIndex: 2 }}>
        <div style={{ width: 36, height: 36, borderRadius: 12, background: t.accentSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Sprout stage={2} size={28} color={t.accent} soft={t.isDark ? t.accent + '44' : '#FFFFFF88'} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 600, letterSpacing: -0.2 }}>auth-refactor</div>
          <div style={{ fontFamily: SEEDEX_FONTS.mono, fontSize: 10, color: t.inkSoft, marginTop: 2, display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: t.accent }} />
            studio.local · ~/work/api
          </div>
        </div>
        <button style={{ background: 'none', border: `1px solid ${t.line}`, borderRadius: 99, padding: '6px 10px', fontFamily: SEEDEX_FONTS.mono, fontSize: 10, color: t.inkSoft, letterSpacing: 1, textTransform: 'uppercase', cursor: 'pointer' }}>
          pause
        </button>
      </div>

      {/* Scroll area */}
      <div ref={scrollRef} style={{ flex: 1, overflow: 'auto', padding: '16px 16px 20px' }}>
        {msgs.map((m, i) => <Message key={i} m={m} t={t} />)}
        {/* streaming cursor */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 4px', fontFamily: SEEDEX_FONTS.mono, fontSize: 11, color: t.inkFaint }}>
          <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: t.accent, animation: 'seedex-pulse 1.2s ease-in-out infinite' }} />
          awaiting your decision on .env.local
        </div>
      </div>

      {/* Input bar */}
      <div style={{ padding: '10px 14px 28px', borderTop: `1px solid ${t.line}`, background: t.surface, display: 'flex', gap: 10, alignItems: 'flex-end' }}>
        <button style={{ width: 38, height: 38, borderRadius: '50%', background: 'none', border: `1px solid ${t.lineStrong}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, cursor: 'pointer' }}>
          {SeedexIcons.plus(t.inkSoft)}
        </button>
        <div style={{ flex: 1, background: t.surfaceRaised, borderRadius: 22, border: `1px solid ${t.line}`, padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 8 }}>
          <input
            value={input}
            onChange={e => setInput(e.target.value)}
            placeholder="Reply to your twin…"
            style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontFamily: SEEDEX_FONTS.sans, fontSize: 14, color: t.ink }}
          />
          <div style={{ width: 1, height: 18, background: t.line }} />
          {SeedexIcons.mic(t.inkSoft)}
        </div>
        <button style={{ width: 38, height: 38, borderRadius: '50%', background: t.accent, border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, cursor: 'pointer' }}>
          {SeedexIcons.arrowUp('#fff')}
        </button>
      </div>
    </div>
  );
}

function Message({ m, t }) {
  if (m.role === 'user') {
    return (
      <div style={{ display: 'flex', justifyContent: 'flex-end', margin: '8px 0 14px' }}>
        <div style={{ background: t.ink, color: t.bg, padding: '10px 14px', borderRadius: 18, borderBottomRightRadius: 4, maxWidth: '80%', fontSize: 14, lineHeight: 1.45 }}>
          {m.text}
        </div>
      </div>
    );
  }
  if (m.role === 'assistant') {
    return (
      <div style={{ margin: '10px 0 14px', padding: '0 4px' }}>
        <div style={{ fontFamily: SEEDEX_FONTS.mono, fontSize: 9, letterSpacing: 1.4, color: t.inkFaint, textTransform: 'uppercase', marginBottom: 6 }}>Claude</div>
        <div style={{ fontSize: 14.5, lineHeight: 1.5, color: t.ink }}>{m.text}</div>
      </div>
    );
  }
  if (m.role === 'tool') return <ToolBlock m={m} t={t} />;
  if (m.role === 'diff') return <DiffBlock m={m} t={t} />;
  return null;
}

function ToolBlock({ m, t }) {
  const statusColor = m.status === 'pending' ? t.warn : m.status === 'done' ? t.accent : t.inkFaint;
  const statusLabel = m.status === 'pending' ? 'awaiting' : m.status === 'done' ? 'done' : 'running';
  return (
    <div style={{ margin: '8px 0', borderRadius: 16, border: `1px solid ${m.status === 'pending' ? t.warn + '55' : t.line}`, background: m.status === 'pending' ? (t.isDark ? '#2a1a0e' : '#FBF3EC') : t.surface, overflow: 'hidden' }}>
      <div style={{ padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: m.output ? `1px solid ${t.line}` : 'none' }}>
        <div style={{ fontFamily: SEEDEX_FONTS.mono, fontSize: 9, letterSpacing: 1.4, color: statusColor, textTransform: 'uppercase' }}>{m.kind}</div>
        <div style={{ flex: 1, fontFamily: SEEDEX_FONTS.mono, fontSize: 12, color: t.ink, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.name}</div>
        <div style={{ fontFamily: SEEDEX_FONTS.mono, fontSize: 10, color: statusColor, letterSpacing: 0.8 }}>{statusLabel}</div>
      </div>
      {m.output && (
        <div style={{ padding: '10px 14px', fontFamily: SEEDEX_FONTS.mono, fontSize: 11, color: t.inkSoft, lineHeight: 1.55, whiteSpace: 'pre-wrap' }}>
          {m.output}
        </div>
      )}
      <div style={{ padding: '6px 14px 10px', fontFamily: SEEDEX_FONTS.mono, fontSize: 10, color: t.inkFaint }}>{m.meta}</div>
      {m.status === 'pending' && (
        <div style={{ padding: '4px 10px 12px', display: 'flex', gap: 8 }}>
          <button style={{ flex: 1, padding: '10px', background: t.accent, color: '#fff', border: 'none', borderRadius: 12, fontFamily: SEEDEX_FONTS.mono, fontSize: 11, letterSpacing: 1, textTransform: 'uppercase', cursor: 'pointer' }}>Allow</button>
          <button style={{ flex: 1, padding: '10px', background: 'transparent', color: t.ink, border: `1px solid ${t.lineStrong}`, borderRadius: 12, fontFamily: SEEDEX_FONTS.mono, fontSize: 11, letterSpacing: 1, textTransform: 'uppercase', cursor: 'pointer' }}>Deny</button>
        </div>
      )}
    </div>
  );
}

function DiffBlock({ m, t }) {
  return (
    <div style={{ margin: '8px 0', borderRadius: 16, border: `1px solid ${t.line}`, background: t.surface, overflow: 'hidden' }}>
      <div style={{ padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: `1px solid ${t.line}` }}>
        <div style={{ fontFamily: SEEDEX_FONTS.mono, fontSize: 9, letterSpacing: 1.4, color: t.accent, textTransform: 'uppercase' }}>Edit</div>
        <div style={{ flex: 1, fontFamily: SEEDEX_FONTS.mono, fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.file}</div>
        <div style={{ fontFamily: SEEDEX_FONTS.mono, fontSize: 10 }}>
          <span style={{ color: t.accent }}>+{m.added}</span>{' '}
          <span style={{ color: t.warn }}>−{m.removed}</span>
        </div>
      </div>
      <div style={{ fontFamily: SEEDEX_FONTS.mono, fontSize: 11, lineHeight: 1.6 }}>
        {m.hunks.map((h, i) => (
          <div key={i} style={{
            display: 'flex',
            background: h.type === 'add' ? (t.isDark ? '#1f2e1a' : '#E8F0DD') : h.type === 'rm' ? (t.isDark ? '#2e1a1a' : '#F5DDD5') : 'transparent',
            color: t.ink,
            padding: '2px 0',
          }}>
            <div style={{ width: 30, textAlign: 'right', color: t.inkFaint, paddingRight: 6, flexShrink: 0 }}>{h.old}</div>
            <div style={{ width: 30, textAlign: 'right', color: t.inkFaint, paddingRight: 10, flexShrink: 0, borderRight: `1px solid ${t.line}` }}>{h.new}</div>
            <div style={{ paddingLeft: 10, flex: 1, whiteSpace: 'pre', overflow: 'hidden' }}>{h.text}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ChatScreen });
