// chat-deep.jsx — §04c Chat · Deep states
// Real surfaces from src/renderer/windows/main/components/{chat,tools,web-search}.
// Each component is a single-screen ChatLayout instance focused on one
// recurring runtime state (approval, streaming tool, multi-step, etc).

// ── Approval card (permission=confirm fires this every tool call) ──
function DeepApprovalCard({ dark, variant = 'prompt' }) {
  const t = dark ? G.d : G.l;
  const isDanger = variant === 'danger';
  const isDeny = variant === 'deny';

  return (
    <ChatLayout dark={dark} title="Refactor auth middleware"
      composerProps={{ permissionMode: 'confirm', contextFile: 'auth.ts', contextUsed: 47 }}>
      <UserMsg dark={dark}>Audit auth.ts and remove the unsafe header bypass.</UserMsg>
      <AssistantMsg dark={dark}>I'll edit lines 5–7 to drop the bypass.</AssistantMsg>

      {/* The approval card itself */}
      <div style={{
        maxWidth: 560, padding: '14px 16px', marginTop: 4,
        background: t.surface,
        border: `1px solid ${isDanger ? '#ff5f57' : t.border}`,
        borderRadius: 14,
        boxShadow: '0 2px 6px rgba(15,23,42,0.06), 0 6px 18px rgba(15,23,42,0.04)',
      }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
          <div style={{
            width: 24, height: 24, borderRadius: 6,
            background: isDanger ? 'rgba(255,95,87,0.12)' : t.surface2,
            border: `1px solid ${isDanger ? '#ff5f57' : t.border}`,
            color: isDanger ? '#ff5f57' : t.fg2,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}><Icon name="warn" size={13} /></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11, fontFamily: G.mono, letterSpacing: 1, color: t.fg3, marginBottom: 2, textTransform: 'uppercase' }}>Permission Request</div>
            <div style={{ fontSize: 13, fontWeight: 600 }}>
              {isDanger ? 'Run shell · rm -rf node_modules' : 'Edit src/middleware/auth.ts'}
            </div>
            <pre style={{
              margin: '8px 0 0', padding: '8px 10px',
              background: t.surface2, border: `1px solid ${t.border2}`, borderRadius: 8,
              fontFamily: G.mono, fontSize: 11, color: t.fg2,
              whiteSpace: 'pre-wrap', maxHeight: 90, overflow: 'auto',
            }}>{isDanger
              ? '$ rm -rf node_modules\n# this will delete 412 files'
              : '- if (req.headers[\'x-internal-trust\'] === \'true\') {\n-   return next();\n- }'}</pre>

            {/* Deny reason input variant */}
            {isDeny && (
              <div style={{
                marginTop: 10, padding: 10,
                background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 8,
              }}>
                <div style={{ fontSize: 11, color: t.fg3, marginBottom: 4 }}>Reason for denial (optional)</div>
                <div style={{ fontSize: 12, color: t.fg2, fontStyle: 'italic' }}>
                  Use a signed proxy assertion instead — internal-trust headers can be spoofed by any client.
                </div>
              </div>
            )}

            <div style={{ display: 'flex', gap: 6, marginTop: 12, flexWrap: 'wrap' }}>
              {isDeny ? (
                <>
                  <Button variant="primary" size="sm">Send denial</Button>
                  <Button variant="ghost" size="sm">Cancel</Button>
                </>
              ) : (
                <>
                  <Button variant={isDanger ? 'secondary' : 'primary'} size="sm" icon={<Icon name="check" size={11} color={isDanger ? t.fg : t.bg} />}>{isDanger ? 'Allow once' : 'Allow'}</Button>
                  {!isDanger && <Button variant="secondary" size="sm">Allow always</Button>}
                  <Button variant="ghost" size="sm">Deny with reason</Button>
                  <Button variant="ghost" size="sm">Deny</Button>
                </>
              )}
            </div>
          </div>
        </div>
      </div>
    </ChatLayout>
  );
}


// ── Streaming tool card (tool still running, partial output flowing) ──
function DeepStreamingTool({ dark, variant = 'mid' }) {
  const t = dark ? G.d : G.l;
  const partial = {
    early: 'Reading auth.ts...',
    mid: `import type { NextFunction, Request, Response } from 'express';
import { verifyJwt } from '../lib/jwt';

export async function auth(req, res, next) {
  // ⚠ unverified header bypass
  if (req.headers['x-internal-trust'] === 'true') {
    ret`,
    stderr: 'parsing 412 files...\n  ✓ src/main/index.ts\n  ✓ src/preload/index.cjs\nEACCES /restricted/file.ts',
  }[variant];

  return (
    <ChatLayout dark={dark} title="Audit auth middleware">
      <UserMsg dark={dark}>Show me the bypass code in auth.ts</UserMsg>
      <div style={{
        maxWidth: 720, padding: '12px 14px',
        background: t.surface, border: `1px solid ${t.border}`, borderRadius: 14,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
          <span style={{
            width: 12, height: 12, borderRadius: 6,
            border: `1.5px solid ${t.fg2}`, borderTopColor: 'transparent',
            animation: 'gh-spin .8s linear infinite',
          }} />
          <span style={{ fontSize: 12, fontFamily: G.mono, color: t.fg }}>read_file</span>
          <span style={{ fontSize: 11, color: t.fg3 }}>· auth.ts</span>
          <span style={{ flex: 1 }} />
          <span style={{ fontSize: 10, fontFamily: G.mono, color: t.fg3 }}>1.2s · streaming</span>
        </div>
        <pre style={{
          margin: 0, padding: '8px 10px', maxHeight: 200, overflow: 'auto',
          background: t.surface2, border: `1px solid ${t.border2}`, borderRadius: 8,
          fontFamily: G.mono, fontSize: 11, color: variant === 'stderr' ? '#ff5f57' : t.fg2,
          whiteSpace: 'pre',
        }}>{partial}<span style={{
          display: 'inline-block', width: 6, height: 12,
          background: t.fg, marginLeft: 1, verticalAlign: -2,
          animation: 'gh-blink 1s infinite',
        }} /></pre>
        {variant === 'stderr' && (
          <div style={{ marginTop: 6, fontSize: 10, color: '#ff5f57', fontFamily: G.mono }}>
            stderr · 1 file skipped
          </div>
        )}
      </div>
    </ChatLayout>
  );
}


// ── Multi-step tool chain (think → tool → think → tool → answer) ──
function DeepMultiStepChain({ dark }) {
  const t = dark ? G.d : G.l;
  const StepConnector = () => (
    <div style={{ marginLeft: 10, width: 1, height: 16, background: t.border2 }} />
  );
  const Step = ({ icon, title, desc, status = 'done', body }) => (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
      <div style={{
        width: 22, height: 22, borderRadius: 11,
        background: status === 'active' ? t.fg : t.surface2,
        color: status === 'active' ? t.bg : t.fg2,
        border: `1px solid ${t.border}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        {status === 'active' ? (
          <span style={{ width: 9, height: 9, border: `1.5px solid ${t.bg}`, borderTopColor: 'transparent', borderRadius: 5, animation: 'gh-spin .8s linear infinite' }} />
        ) : <Icon name={icon} size={11} />}
      </div>
      <div style={{ flex: 1, minWidth: 0, paddingTop: 2 }}>
        <div style={{ fontSize: 12, fontWeight: 600 }}>{title}</div>
        <div style={{ fontSize: 11, color: t.fg3, marginTop: 1 }}>{desc}</div>
        {body}
      </div>
    </div>
  );

  return (
    <ChatLayout dark={dark} title="Refactor auth middleware">
      <UserMsg dark={dark}>Find and fix the auth bypass + add a regression test.</UserMsg>
      <AssistantMsg dark={dark}>
        Plan: locate the bypass, edit auth.ts to remove it, then write a test that asserts the header is ignored.
      </AssistantMsg>

      {/* The chain */}
      <div style={{
        maxWidth: 720, padding: 14,
        background: t.surface, border: `1px solid ${t.border}`, borderRadius: 14,
        display: 'flex', flexDirection: 'column', gap: 0,
      }}>
        <Step icon="search" title="grep · 'x-internal-trust'" desc="2 matches in src/middleware" />
        <StepConnector />
        <Step icon="docs" title="read_file · auth.ts" desc="Read 19 lines" />
        <StepConnector />
        <Step icon="sparkle" title="Reasoning" desc="The bypass is on lines 5–7. Remove the if block, keep the JWT path." />
        <StepConnector />
        <Step icon="edit" title="edit_file · auth.ts" desc="Removed 4 lines, added 1 comment" />
        <StepConnector />
        <Step icon="sparkle" title="Reasoning" desc="Now write a regression test that mocks the header." />
        <StepConnector />
        <Step icon="plus" title="write_file · auth.test.ts" desc="22 lines, 3 assertions"
          status="active"
          body={
            <div style={{ marginTop: 6, padding: 8, background: t.surface2, borderRadius: 6, fontFamily: G.mono, fontSize: 11, color: t.fg3 }}>
              writing line 14 of 22…
            </div>
          }
        />
      </div>
    </ChatLayout>
  );
}


// ── Bash terminal output (real BashOutputDisplay vibe) ──
function DeepBashTool({ dark, variant = 'success' }) {
  const t = dark ? G.d : G.l;
  const isErr = variant === 'error';
  const isLong = variant === 'long';

  const lines = isErr ? [
    { c: '$ pnpm test', tone: t.fg },
    { c: '> jest --watch=false', tone: t.fg3 },
    { c: '', tone: t.fg },
    { c: 'FAIL  src/auth.test.ts', tone: '#ff5f57' },
    { c: '  ● should reject spoofed x-internal-trust header', tone: t.fg2 },
    { c: '    Expected: 401', tone: t.fg2 },
    { c: '    Received: 200', tone: t.fg2 },
    { c: '      at Object.<anonymous> (src/auth.test.ts:18:23)', tone: t.fg3 },
    { c: '', tone: t.fg },
    { c: 'Tests: 1 failed, 8 passed, 9 total', tone: '#ff5f57' },
  ] : isLong ? [
    { c: '$ pnpm install', tone: t.fg },
    ...Array.from({ length: 14 }).map((_, i) => ({
      c: `progress ${i + 1}/14 · resolving @org/pkg-${(i * 13) % 999}@^4.${i}.0`,
      tone: t.fg3,
    })),
    { c: '… 432 lines truncated · click to expand', tone: t.fg4 },
    { c: 'added 412 packages in 18s', tone: '#28c840' },
  ] : [
    { c: '$ npm run lint', tone: t.fg },
    { c: '  ✓ 412 files, 0 errors, 3 warnings', tone: '#28c840' },
    { c: '$ ghast scan auth', tone: t.fg },
    { c: '  → 2 high-severity issues, see thread #4112', tone: t.fg },
    { c: '$ ', tone: t.fg },
  ];

  return (
    <ChatLayout dark={dark} title="Refactor auth middleware">
      <UserMsg dark={dark}>{isErr ? 'Run the auth tests' : 'Run lint and audit'}</UserMsg>
      <div style={{
        maxWidth: 720, padding: 0,
        background: t.surface, border: `1px solid ${t.border}`, borderRadius: 14, overflow: 'hidden',
      }}>
        <div style={{
          padding: '8px 14px', background: t.surface2,
          borderBottom: `0.5px solid ${t.border2}`,
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 11, fontFamily: G.mono, color: t.fg2,
        }}>
          <Icon name="terminal" size={12} color={t.fg2} />
          <span>shell · zsh</span>
          <span style={{ flex: 1 }} />
          <span style={{ color: isErr ? '#ff5f57' : '#28c840' }}>
            {isErr ? 'exit 1' : 'exit 0'} · {isLong ? '18.2s' : '0.4s'}
          </span>
        </div>
        <pre style={{
          margin: 0, padding: '10px 14px', maxHeight: 220, overflow: 'auto',
          fontFamily: G.mono, fontSize: 11, lineHeight: 1.55,
          background: dark ? '#0a0a0a' : '#fafaf9',
        }}>
          {lines.map((l, i) => (
            <div key={i} style={{ color: l.tone, whiteSpace: 'pre' }}>{l.c || ' '}</div>
          ))}
        </pre>
        {isLong && (
          <div style={{ padding: '6px 14px', borderTop: `0.5px solid ${t.border2}`, fontSize: 10, color: t.fg3, fontFamily: G.mono, textAlign: 'center', cursor: 'pointer' }}>
            Show all 432 lines ↓
          </div>
        )}
      </div>
    </ChatLayout>
  );
}


// ── File edit tool — inline diff (real EditToolDiff vibe) ──
function DeepFileEditDiff({ dark, variant = 'edit' }) {
  const t = dark ? G.d : G.l;
  const isMulti = variant === 'multi';
  const isConflict = variant === 'conflict';

  const Hunk = ({ file, oldLines, newLines }) => (
    <div style={{
      background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12,
      overflow: 'hidden', marginBottom: 10,
    }}>
      <div style={{
        padding: '7px 12px', background: t.surface2,
        borderBottom: `0.5px solid ${t.border2}`,
        display: 'flex', alignItems: 'center', gap: 8,
        fontFamily: G.mono, fontSize: 11, color: t.fg2,
      }}>
        <Icon name="edit" size={11} color={t.fg2} />
        <span>{file}</span>
        <span style={{ flex: 1 }} />
        <span style={{ color: '#ff5f57' }}>−{oldLines.length}</span>
        <span style={{ color: '#28c840' }}>+{newLines.length}</span>
      </div>
      <div style={{ padding: '6px 0', fontFamily: G.mono, fontSize: 11, lineHeight: 1.7 }}>
        {oldLines.map((line, i) => (
          <div key={`o${i}`} style={{
            padding: '0 14px', background: dark ? 'rgba(255,95,87,0.08)' : 'rgba(255,95,87,0.06)',
            color: '#d44', whiteSpace: 'pre',
          }}>− {line}</div>
        ))}
        {newLines.map((line, i) => (
          <div key={`n${i}`} style={{
            padding: '0 14px', background: dark ? 'rgba(40,200,64,0.08)' : 'rgba(40,200,64,0.06)',
            color: '#3a8', whiteSpace: 'pre',
          }}>+ {line}</div>
        ))}
      </div>
    </div>
  );

  return (
    <ChatLayout dark={dark} title="Refactor auth middleware">
      <UserMsg dark={dark}>{isConflict ? 'Apply your fix even though the file changed' : 'Remove the bypass'}</UserMsg>

      <Hunk
        file={isMulti ? 'auth.ts · 2 of 3' : 'auth.ts'}
        oldLines={[
          "if (req.headers['x-internal-trust'] === 'true') {",
          "  return next();",
          "}",
        ]}
        newLines={[
          "// removed unsafe bypass — see ADR-002",
        ]}
      />

      {isMulti && (
        <Hunk
          file="auth.test.ts · 3 of 3"
          oldLines={[]}
          newLines={[
            "test('rejects spoofed x-internal-trust', () => {",
            "  const req = mockReq({ headers: { 'x-internal-trust': 'true' } });",
            "  expect(() => auth(req, res, next)).toThrow();",
            "});",
          ]}
        />
      )}

      {isConflict && (
        <div style={{
          maxWidth: 720, padding: '10px 14px', marginTop: -4,
          background: dark ? 'rgba(254,188,46,0.08)' : 'rgba(254,188,46,0.08)',
          border: `1px solid #febc2e`, borderRadius: 12,
          display: 'flex', alignItems: 'flex-start', gap: 10,
        }}>
          <Icon name="warn" size={14} color="#febc2e" style={{ flexShrink: 0, marginTop: 2 }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, fontWeight: 600 }}>File changed since I last read it</div>
            <div style={{ fontSize: 11, color: t.fg3, marginTop: 2 }}>
              Lines 5–7 were modified by another tool. Re-read or apply with conflict markers?
            </div>
            <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
              <Button variant="primary" size="sm">Re-read & retry</Button>
              <Button variant="secondary" size="sm">Apply with conflicts</Button>
              <Button variant="ghost" size="sm">Cancel</Button>
            </div>
          </div>
        </div>
      )}

      {!isConflict && (
        <div style={{ display: 'flex', gap: 6 }}>
          <Button variant="primary" size="sm">Apply {isMulti ? '3 edits' : ''}</Button>
          <Button variant="secondary" size="sm">Discuss</Button>
          <Button variant="ghost" size="sm">Reject</Button>
        </div>
      )}
    </ChatLayout>
  );
}


// ── File write tool — whole-file create ──
function DeepFileWrite({ dark, variant = 'create' }) {
  const t = dark ? G.d : G.l;
  const isReplace = variant === 'replace';
  return (
    <ChatLayout dark={dark} title="Refactor auth middleware">
      <UserMsg dark={dark}>Add a regression test</UserMsg>
      <div style={{
        maxWidth: 720, padding: 0,
        background: t.surface, border: `1px solid ${t.border}`, borderRadius: 14, overflow: 'hidden',
      }}>
        <div style={{
          padding: '8px 14px', background: t.surface2,
          borderBottom: `0.5px solid ${t.border2}`,
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 11, fontFamily: G.mono, color: t.fg2,
        }}>
          <Icon name="plus" size={11} color="#28c840" />
          <span style={{ color: t.fg }}>{isReplace ? 'rewrite' : 'create'}</span>
          <span>· src/middleware/auth.test.ts</span>
          <span style={{ flex: 1 }} />
          <Tag style={{ height: 18, fontSize: 9 }}>{isReplace ? '−42 / +28' : 'new file · 28 lines'}</Tag>
        </div>
        <pre style={{
          margin: 0, padding: '10px 14px', maxHeight: 200, overflow: 'auto',
          fontFamily: G.mono, fontSize: 11, lineHeight: 1.6, color: t.fg2,
          whiteSpace: 'pre',
        }}>{`import { auth } from './auth';
import { mockReq, mockRes } from '../test/helpers';

describe('auth middleware', () => {
  test('rejects spoofed x-internal-trust', () => {
    const req = mockReq({
      headers: { 'x-internal-trust': 'true' },
    });
    const res = mockRes();
    const next = jest.fn();
    auth(req, res, next);
    expect(next).not.toHaveBeenCalled();
    expect(res.status).toHaveBeenCalledWith(401);
  });
});`}</pre>
        <div style={{ padding: '10px 14px', borderTop: `0.5px solid ${t.border2}`, display: 'flex', gap: 6 }}>
          <Button variant="primary" size="sm">{isReplace ? 'Apply rewrite' : 'Create file'}</Button>
          <Button variant="secondary" size="sm">Edit before writing</Button>
          <Button variant="ghost" size="sm">Reject</Button>
        </div>
      </div>
    </ChatLayout>
  );
}


// ── Task tool — nested todo list ──
function DeepTaskTool({ dark, variant = 'list' }) {
  const t = dark ? G.d : G.l;
  const todos = [
    { name: 'grep for x-internal-trust references', status: variant === 'list' ? 'pending' : 'done' },
    { name: 'remove the bypass from auth.ts', status: variant === 'progress' ? 'active' : (variant === 'list' ? 'pending' : 'done') },
    { name: 'add regression test in auth.test.ts', status: variant === 'progress' ? 'pending' : (variant === 'list' ? 'pending' : 'done') },
    { name: 'document the change in CHANGELOG.md', status: variant === 'list' ? 'pending' : (variant === 'done' ? 'done' : 'pending') },
  ];
  const StatusDot = ({ s }) => (
    s === 'done' ? <Icon name="check" size={12} color="#28c840" /> :
    s === 'active' ? <span style={{ width: 12, height: 12, border: `1.5px solid ${t.fg2}`, borderTopColor: 'transparent', borderRadius: 6, animation: 'gh-spin .8s linear infinite' }} /> :
    <span style={{ width: 10, height: 10, borderRadius: 5, border: `1.5px solid ${t.fg4}` }} />
  );
  return (
    <ChatLayout dark={dark} title="Refactor auth middleware">
      <UserMsg dark={dark}>Plan and execute the auth refactor</UserMsg>
      <div style={{
        maxWidth: 560, padding: 0,
        background: t.surface, border: `1px solid ${t.border}`, borderRadius: 14, overflow: 'hidden',
      }}>
        <div style={{
          padding: '8px 14px', background: t.surface2,
          borderBottom: `0.5px solid ${t.border2}`,
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 11, fontFamily: G.mono, color: t.fg2,
        }}>
          <Icon name="check" size={11} />
          <span style={{ color: t.fg }}>todos</span>
          <span style={{ flex: 1 }} />
          <span>{todos.filter(t => t.status === 'done').length} / {todos.length} done</span>
        </div>
        {todos.map((td, i) => (
          <div key={i} style={{
            padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10,
            borderBottom: i === todos.length - 1 ? 'none' : `0.5px solid ${t.border2}`,
            opacity: td.status === 'pending' ? 0.7 : 1,
          }}>
            <StatusDot s={td.status} />
            <span style={{ flex: 1, fontSize: 13, textDecoration: td.status === 'done' ? 'line-through' : 'none', color: td.status === 'done' ? t.fg3 : t.fg }}>
              {td.name}
            </span>
            {td.status === 'active' && <Tag style={{ height: 18, fontSize: 9 }}>in progress</Tag>}
          </div>
        ))}
      </div>
    </ChatLayout>
  );
}


// ── Web search results + inline citation ──
function DeepWebSearch({ dark, variant = 'sources' }) {
  const t = dark ? G.d : G.l;
  const sources = [
    { n: 1, title: 'OWASP — HTTP Header Injection', url: 'owasp.org/www-community/attacks/HTTP_Header_Injection', cited: true },
    { n: 2, title: "Why X-Forwarded-For can't be trusted", url: 'snyk.io/blog/x-forwarded-for-header-injection', cited: true },
    { n: 3, title: 'CVE-2023-44487: HTTP/2 Rapid Reset', url: 'nvd.nist.gov/vuln/detail/CVE-2023-44487', cited: false },
    { n: 4, title: 'Stack Overflow · "x-internal-trust header"', url: 'stackoverflow.com/q/82342211', cited: true },
  ];
  if (variant === 'empty') {
    return (
      <ChatLayout dark={dark} title="Audit auth middleware">
        <UserMsg dark={dark}>Are there CVEs about x-internal-trust spoofing?</UserMsg>
        <div style={{
          maxWidth: 600, padding: 18, textAlign: 'center',
          background: t.surface, border: `1px solid ${t.border}`, borderRadius: 14,
          color: t.fg3, fontSize: 13,
        }}>
          <Icon name="search" size={20} color={t.fg4} style={{ marginBottom: 6 }} />
          <div>No web results matched "x-internal-trust spoofing"</div>
          <div style={{ fontSize: 11, marginTop: 4 }}>Searched: web · 0 sources</div>
        </div>
      </ChatLayout>
    );
  }
  return (
    <ChatLayout dark={dark} title="Audit auth middleware">
      <UserMsg dark={dark}>Are there CVEs about header trust spoofing?</UserMsg>
      <AssistantMsg dark={dark}>
        Yes — this is a known anti-pattern. <sup style={{ fontFamily: G.mono, color: t.fg2, padding: '0 3px', background: t.surface2, borderRadius: 3, marginLeft: 1 }}>1</sup> OWASP classifies it under HTTP Header Injection. Snyk's writeup on X-Forwarded-For applies almost verbatim: <sup style={{ fontFamily: G.mono, color: t.fg2, padding: '0 3px', background: t.surface2, borderRadius: 3, marginLeft: 1 }}>2</sup> any client can set this header at the edge unless the proxy strips it. Stack Overflow has a discussion on the specific pattern. <sup style={{ fontFamily: G.mono, color: t.fg2, padding: '0 3px', background: t.surface2, borderRadius: 3, marginLeft: 1 }}>4</sup>
      </AssistantMsg>

      {/* Sources card */}
      <div style={{
        maxWidth: 720, padding: 0,
        background: t.surface, border: `1px solid ${t.border}`, borderRadius: 14, overflow: 'hidden',
      }}>
        <div style={{
          padding: '8px 14px', background: t.surface2,
          borderBottom: `0.5px solid ${t.border2}`,
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 11, fontFamily: G.mono, color: t.fg2,
        }}>
          <Icon name="globe" size={11} color={t.fg2} />
          <span style={{ color: t.fg }}>web search</span>
          <span style={{ flex: 1 }} />
          <span>{sources.length} sources · {sources.filter(s => s.cited).length} cited</span>
        </div>
        {sources.map((s, i) => (
          <div key={s.n} style={{
            padding: '10px 14px', display: 'flex', alignItems: 'flex-start', gap: 10,
            borderBottom: i === sources.length - 1 ? 'none' : `0.5px solid ${t.border2}`,
            opacity: s.cited ? 1 : 0.55,
          }}>
            <span style={{
              width: 18, height: 18, borderRadius: 4,
              background: s.cited ? t.fg : t.surface2,
              color: s.cited ? t.bg : t.fg3,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 10, fontFamily: G.mono, fontWeight: 600,
              flexShrink: 0, marginTop: 1,
            }}>{s.n}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{s.title}</div>
              <div style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.url}</div>
            </div>
            <Icon name="ext" size={12} color={t.fg3} style={{ flexShrink: 0, marginTop: 4 }} />
          </div>
        ))}
      </div>
    </ChatLayout>
  );
}


// ── Reasoning effort segmented control ──
function DeepReasoningEffort({ dark, level = 'medium' }) {
  const t = dark ? G.d : G.l;
  const tokens = { low: 1024, medium: 4096, high: 16384 }[level];
  return (
    <ChatLayout dark={dark} title="Refactor auth middleware">
      <UserMsg dark={dark}>Audit auth.ts for security issues</UserMsg>

      {/* Reasoning header with effort selector */}
      <div style={{
        maxWidth: 720, padding: '10px 14px',
        background: t.surface, border: `1px solid ${t.border}`, borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <Icon name="sparkle" size={14} color={t.fg2} />
        <span style={{ fontSize: 12, fontWeight: 500 }}>Thinking</span>
        <span style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono }}>·</span>
        <span style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono }}>{tokens.toLocaleString()} tokens</span>
        <span style={{ flex: 1 }} />
        <div style={{ display: 'flex', gap: 0, padding: 2, background: t.surface2, borderRadius: 999, border: `1px solid ${t.border}` }}>
          {['low', 'medium', 'high'].map((l) => (
            <div key={l} style={{
              padding: '4px 12px', borderRadius: 999,
              background: l === level ? t.fg : 'transparent',
              color: l === level ? t.bg : t.fg2,
              fontSize: 11, fontWeight: 500, cursor: 'pointer',
              textTransform: 'capitalize',
            }}>{l}</div>
          ))}
        </div>
      </div>

      <AssistantMsg dark={dark}>
        Looking at auth.ts… {level === 'low' ? 'I see one bypass on line 5.' :
        level === 'medium' ? 'Three concerns: (1) the x-internal-trust bypass on line 5–7, (2) no rate limit on the JWT verify path, (3) cookie session ID isn\'t marked HttpOnly.' :
        'I want to map this against the entire auth surface — let me trace from the edge proxy through to JWT verify, then cross-reference with our CSRF and session handling. (continuing for ~12s...)'}
      </AssistantMsg>
    </ChatLayout>
  );
}


// ── Collapsed tool group — long thread, many small tools collapsed ──
function DeepCollapsedToolGroup({ dark, variant = 'collapsed' }) {
  const t = dark ? G.d : G.l;
  const isExpanded = variant === 'expanded';
  const calls = [
    { tool: 'list_dir', arg: 'src/middleware', dur: '0.1s' },
    { tool: 'read_file', arg: 'auth.ts', dur: '0.1s' },
    { tool: 'read_file', arg: 'session.ts', dur: '0.1s' },
    { tool: 'grep', arg: '"x-internal-trust"', dur: '0.3s' },
    { tool: 'read_file', arg: 'jwt.ts', dur: '0.1s' },
    { tool: 'read_file', arg: 'errors.ts', dur: '0.1s' },
    { tool: 'list_dir', arg: 'src/test', dur: '0.1s' },
    { tool: 'read_file', arg: 'auth.test.ts', dur: '0.1s' },
  ];
  return (
    <ChatLayout dark={dark} title="Refactor auth middleware">
      <UserMsg dark={dark}>Investigate the auth pipeline end-to-end</UserMsg>
      <div style={{
        maxWidth: 720, padding: 0,
        background: t.surface, border: `1px solid ${t.border}`, borderRadius: 14, overflow: 'hidden',
      }}>
        <div style={{
          padding: '8px 14px', background: t.surface2,
          borderBottom: isExpanded ? `0.5px solid ${t.border2}` : 'none',
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 12, color: t.fg2, cursor: 'pointer',
        }}>
          <Icon name={isExpanded ? 'chevronDown' : 'chevronRight'} size={11} color={t.fg3} />
          <Icon name="layers" size={12} color={t.fg2} />
          <span style={{ fontWeight: 500 }}>{calls.length} tool calls</span>
          <span style={{ flex: 1 }} />
          <span style={{ fontSize: 11, fontFamily: G.mono, color: t.fg3 }}>1.0s · all succeeded</span>
        </div>
        {isExpanded && (
          <div style={{ padding: '4px 0' }}>
            {calls.map((c, i) => (
              <div key={i} style={{
                padding: '6px 14px 6px 36px', display: 'flex', alignItems: 'center', gap: 8,
                fontSize: 11, fontFamily: G.mono, color: t.fg2,
              }}>
                <Icon name="check" size={11} color="#28c840" />
                <span style={{ color: t.fg }}>{c.tool}</span>
                <span style={{ color: t.fg3 }}>{c.arg}</span>
                <span style={{ flex: 1 }} />
                <span style={{ color: t.fg3 }}>{c.dur}</span>
              </div>
            ))}
          </div>
        )}
      </div>
      <AssistantMsg dark={dark}>
        Read 6 files and grep'd the codebase. The auth bypass is isolated to lines 5–7 of auth.ts. Ready to fix.
      </AssistantMsg>
    </ChatLayout>
  );
}


Object.assign(window, {
  DeepApprovalCard, DeepStreamingTool, DeepMultiStepChain,
  DeepBashTool, DeepFileEditDiff, DeepFileWrite, DeepTaskTool,
  DeepWebSearch, DeepReasoningEffort, DeepCollapsedToolGroup,
});
