import { useEffect, useMemo, useRef, useState } from 'react';
import type { Card } from '../../lib/kanbanApi';
import type { UseOrchestrator } from './useOrchestrator';
import { DiffModal } from './DiffModal';
import { RunEventList } from './RunEventList';
import { useRunStream } from './useRunStream';

/**
 * Inline agentic console for one kanban card.
 *
 * Lets the operator launch a `pi` run against the card, watch its live
 * tool/thought stream, steer it mid-flight, and stop it — all while the rest of
 * the board stays interactive. Settled runs show their outcome, commit, and
 * summary, with the worktree-backed changes recorded back onto the card and the
 * documentation by the agent itself.
 *
 * The run is presented as a small "mission console": a live stats header, a
 * prominent status banner, an action bar, and a rich grouped activity log
 * (assistant chat bubbles + a tool/bevy timeline).
 */

interface AgentRunBarProps {
  card: Card;
  orch: UseOrchestrator;
}

const STATUS_META: Record<
  string,
  { label: string; color: string; glyph: string; sub: string }
> = {
  queued: { label: 'Queued', color: 'var(--muted)', glyph: '○', sub: 'Waiting to start…' },
  running: { label: 'Running', color: 'var(--accent)', glyph: '●', sub: 'Agent is working' },
  completed: { label: 'Completed', color: 'var(--green)', glyph: '✓', sub: 'Run finished successfully' },
  failed: { label: 'Failed', color: 'var(--red)', glyph: '⚠', sub: 'Run ended with an error' },
  stopped: { label: 'Stopped', color: 'var(--fg-dim)', glyph: '■', sub: 'Run was stopped' },
};

export function AgentRunBar({ card, orch }: AgentRunBarProps) {
  const run = orch.runForCard(card.id);
  const isActive = run?.status === 'running';

  const [promptDraft, setPromptDraft] = useState('');
  const [steerDraft, setSteerDraft] = useState('');
  const [showPrompt, setShowPrompt] = useState(false);
  const [refineDraft, setRefineDraft] = useState('');
  const [showRefine, setShowRefine] = useState(false);
  const [showDiff, setShowDiff] = useState(false);
  const [mergeResult, setMergeResult] = useState<{ ok: boolean; text: string } | null>(null);
  const [mergeBusy, setMergeBusy] = useState(false);
  const [busy, setBusy] = useState(false);
  const logRef = useRef<HTMLDivElement>(null);
  const now = useNow(isActive);

  const bevyRunning = run ? orch.bevyIsRunning(run.id) : false;

  // (The live event stream is owned locally by `useRunStream` below, so a burst
  // of agent events re-renders only this console — never the board or modal.)

  // Sync Bevy status from the server when the run changes (truth after a
  // reconnect/refresh; live lifecycle is mirrored via `bevy` events).
  useEffect(() => {
    if (run) void orch.refreshBevyStatus(run.id);
  }, [run, orch]);

  const events = useRunStream(run?.id ?? null, orch);
  useEffect(() => {
    if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
  }, [events.length]);

  // --- derived stats ---
  const toolCount = useMemo(() => events.filter((e) => e.type === 'tool_start').length, [events]);
  const durationLabel = useMemo(() => {
    if (!run?.startedAt) return null;
    const start = Date.parse(run.startedAt);
    if (!Number.isFinite(start)) return null;
    const end = run.finishedAt ? Date.parse(run.finishedAt) : now;
    return fmtDuration((Number.isFinite(end) ? end : now) - start);
  }, [run, now]);

  // --- handlers (unchanged behavior, clearer presentation) ---
  const start = async () => {
    setBusy(true);
    try {
      await orch.start({ cardId: card.id, prompt: promptDraft.trim() || undefined });
      setPromptDraft('');
      setShowPrompt(false);
    } catch (e) {
      alert(e instanceof Error ? e.message : 'Failed to start run');
    } finally {
      setBusy(false);
    }
  };

  /**
   * Start a refinement run: continues this run's branch (prior commits present)
   * seeded with the operator's feedback. The new run replaces this one in the
   * console since `runForCard` returns the active run.
   */
  const refine = async () => {
    if (!run) return;
    setBusy(true);
    try {
      await orch.start({
        cardId: card.id,
        prompt: refineDraft.trim() || undefined,
        refineRunId: run.id,
      });
      setRefineDraft('');
      setShowRefine(false);
    } catch (e) {
      alert(e instanceof Error ? e.message : 'Failed to start refinement');
    } finally {
      setBusy(false);
    }
  };

  const steer = async () => {
    if (!run || !steerDraft.trim()) return;
    setBusy(true);
    try {
      await orch.message(run.id, steerDraft.trim(), 'steer');
      setSteerDraft('');
    } catch (e) {
      alert(e instanceof Error ? e.message : 'Failed to steer');
    } finally {
      setBusy(false);
    }
  };

  const stop = async () => {
    if (!run) return;
    setBusy(true);
    try {
      await orch.stop(run.id);
    } finally {
      setBusy(false);
    }
  };

  const dismiss = async () => {
    if (!run) return;
    try {
      await orch.remove(run.id);
    } catch (e) {
      alert(e instanceof Error ? e.message : 'Failed to remove run');
    }
  };

  const onMerge = async () => {
    if (!run) return;
    setMergeBusy(true);
    setMergeResult(null);
    try {
      const r = await orch.mergeRun(run.id);
      if (r.alreadyMerged) setMergeResult({ ok: true, text: `Already in ${r.target}.` });
      else if (r.ok) setMergeResult({ ok: true, text: `Merged into ${r.target} — review & mark the card done.` });
      else setMergeResult({ ok: false, text: r.output });
    } catch (e) {
      setMergeResult({ ok: false, text: e instanceof Error ? e.message : 'merge failed' });
    } finally {
      setMergeBusy(false);
    }
  };

  const settled = run && !isActive;
  const hasWorktree = Boolean(run?.branch && run.worktreePath);

  return (
    <div style={panelStyle(isActive)}>
      {/* Animated gradient edge while the agent is working. */}
      {isActive && <span style={topGlowStyle} aria-hidden />}

      <Header
        run={run}
        toolCount={toolCount}
        eventCount={events.length}
        durationLabel={durationLabel}
        bevyRunning={bevyRunning}
      />

      {run && <StatusBanner status={run.status} error={run.error} bevyRunning={bevyRunning} />}

      {/* Action bar */}
      <div style={actionBarStyle}>
        {!run && !showPrompt && (
          <button type="button" style={primaryBtn} onClick={() => setShowPrompt(true)}>
            ▶ Run agent
          </button>
        )}
        {isActive && (
          <button type="button" style={dangerBtn} onClick={stop} disabled={busy}>
            ■ Stop
          </button>
        )}
        {settled && (
          <>
            <button
              type="button"
              style={ghostBtn}
              onClick={() => {
                setShowPrompt((s) => !s);
                setShowRefine(false);
              }}
            >
              ↻ Re-run
            </button>
            {hasWorktree && run.sessionFile && (
              <button
                type="button"
                style={accentBtn}
                onClick={() => {
                  setShowRefine((s) => !s);
                  setShowPrompt(false);
                }}
                title="Continue this run's conversation with feedback"
              >
                ✎ Refine
              </button>
            )}
            <button type="button" style={ghostBtn} onClick={dismiss} title="Remove this run">
              Dismiss
            </button>
          </>
        )}
        {run?.branch && (
          <span style={chipStyle} title={run.worktreePath ?? undefined}>
            ⎇ {run.branch}
          </span>
        )}
        {run?.commitSha && (
          <span style={{ ...chipStyle, fontFamily: 'var(--font-mono)' }} title="Agent commit">
            ◉ {run.commitSha.slice(0, 7)}
          </span>
        )}
      </div>

      {/* Start prompt (create or re-run) */}
      {showPrompt && (
        <div style={blockStyle}>
          <textarea
            placeholder="Optional extra instructions for this run (e.g. 'focus on the Rust client', 'also update the economy doc')…"
            value={promptDraft}
            onChange={(e) => setPromptDraft(e.target.value)}
            onClick={(e) => e.stopPropagation()}
            style={{ ...inputStyle, width: '100%', minHeight: '60px', resize: 'vertical' }}
            spellCheck={false}
          />
          <div style={{ marginTop: '6px', display: 'flex', gap: '6px', alignItems: 'center' }}>
            <button type="button" style={primaryBtn} onClick={start} disabled={busy}>
              {busy ? 'Starting…' : '▶ Start'}
            </button>
            <button type="button" style={ghostBtn} onClick={() => setShowPrompt(false)}>
              Cancel
            </button>
            <span style={hintStyle}>
              Runs in an isolated git worktree. The agent reads the docs, implements,
              verifies with cargo/pnpm, then updates the card & docs.
            </span>
          </div>
        </div>
      )}

      {/* Refinement: resume this run's conversation with operator feedback */}
      {showRefine && settled && hasWorktree && run.sessionFile && (
        <div style={blockStyle}>
          <textarea
            placeholder="Ask for changes — this continues the same conversation (e.g. 'the jump feels too floaty', 'also handle the empty-list case', 'split the large function')…"
            value={refineDraft}
            onChange={(e) => setRefineDraft(e.target.value)}
            onClick={(e) => e.stopPropagation()}
            style={{ ...inputStyle, width: '100%', minHeight: '60px', resize: 'vertical' }}
            spellCheck={false}
            autoFocus
          />
          <div style={{ marginTop: '6px', display: 'flex', gap: '6px', alignItems: 'center' }}>
            <button type="button" style={primaryBtn} onClick={refine} disabled={busy}>
              {busy ? 'Starting…' : '✎ Refine'}
            </button>
            <button type="button" style={ghostBtn} onClick={() => setShowRefine(false)}>
              Cancel
            </button>
            <span style={hintStyle}>
              Resumes this run's chat in the same worktree — the agent keeps the
              full prior context and appends your request as the next message.
            </span>
          </div>
        </div>
      )}

      {/* Steer box while running */}
      {isActive && (
        <div style={{ ...blockStyle, display: 'flex', gap: '6px' }}>
          <input
            type="text"
            placeholder="Steer the agent mid-run… (Enter to send)"
            value={steerDraft}
            onChange={(e) => setSteerDraft(e.target.value)}
            onKeyDown={(e) => {
              e.stopPropagation();
              if (e.key === 'Enter' && steerDraft.trim()) void steer();
            }}
            onClick={(e) => e.stopPropagation()}
            style={{ ...inputStyle, flex: 1 }}
          />
          <button type="button" style={accentBtn} onClick={steer} disabled={busy || !steerDraft.trim()}>
            ➤ Steer
          </button>
        </div>
      )}

      {/* Settled summary */}
      {settled && (run.summary || run.commitSha) && (
        <div style={summaryStyle(run.status)}>
          {run.summary && <div style={{ whiteSpace: 'pre-wrap' }}>{run.summary}</div>}
          <div style={{ marginTop: '4px', fontSize: '0.64rem', color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>
            {run.commitSha && <>commit {run.commitSha}</>}
            {run.finishedAt && <> · finished {new Date(run.finishedAt).toLocaleTimeString()}</>}
          </div>
        </div>
      )}

      {/* Worktree actions: review the diff, merge into main, or playtest with Bevy */}
      {hasWorktree && (
        <div style={{ ...blockStyle, display: 'flex', flexWrap: 'wrap', gap: '6px', alignItems: 'center' }}>
          <span style={sectionLabelStyle}>Worktree</span>
          <button
            type="button"
            style={ghostBtn}
            onClick={(e) => {
              e.stopPropagation();
              setShowDiff(true);
            }}
          >
            △ Diff
          </button>
          <button
            type="button"
            style={ghostBtn}
            onClick={(e) => {
              e.stopPropagation();
              void onMerge();
            }}
            disabled={mergeBusy}
          >
            {mergeBusy ? 'Merging…' : '⬇ Merge'}
          </button>
          {bevyRunning ? (
            <button
              type="button"
              style={dangerBtn}
              onClick={(e) => {
                e.stopPropagation();
                if (run) void orch.stopBevy(run.id);
              }}
            >
              ■ Stop Bevy
            </button>
          ) : (
            <button
              type="button"
              style={accentBtn}
              onClick={(e) => {
                e.stopPropagation();
                if (run) void orch.startBevy(run.id);
              }}
            >
              ▶ Bevy
            </button>
          )}
          {mergeResult && (
            <span
              style={{
                fontSize: '0.66rem',
                fontFamily: 'var(--font-mono)',
                color: mergeResult.ok ? 'var(--green)' : 'var(--red)',
                whiteSpace: 'pre-wrap',
                flex: '1 1 100%',
              }}
            >
              {mergeResult.ok ? '✓ ' : '⚠ '}
              {mergeResult.text}
            </span>
          )}
        </div>
      )}

      {/* Live activity log */}
      {run && (
        <div style={logLabelStyle}>
          <span>Activity</span>
          {events.length > 0 && <span style={{ color: 'var(--muted)' }}> · {events.length} event{events.length === 1 ? '' : 's'}</span>}
        </div>
      )}
      {run && (
        <div ref={logRef} style={logStyle}>
          <RunEventList
            events={events}
            startedAtIso={run.startedAt}
            active={isActive}
            bevyRunning={bevyRunning}
          />
        </div>
      )}

      {showDiff && run && (
        <DiffModal onClose={() => setShowDiff(false)} load={() => orch.getDiff(run.id)} />
      )}
    </div>
  );
}

// --- header & banner -------------------------------------------------------

function Header({
  run,
  toolCount,
  eventCount,
  durationLabel,
  bevyRunning,
}: {
  run: ReturnType<UseOrchestrator['runForCard']>;
  toolCount: number;
  eventCount: number;
  durationLabel: string | null;
  bevyRunning: boolean;
}) {
  const status = run?.status ?? 'queued';
  const meta = STATUS_META[status] ?? STATUS_META.queued;
  const live = status === 'running';
  return (
    <div style={headerStyle}>
      <div style={{ display: 'flex', alignItems: 'center', gap: '8px', minWidth: 0 }}>
        <span style={titleStyle}>
          <span style={titleBarStyle(meta.color)} />
          AGENT
        </span>
        {run && (
          <span style={statusPillStyle(meta.color, live)}>
            <span style={pillDotStyle(meta.color, live)} />
            {meta.label}
          </span>
        )}
        {live && (
          <span style={workingStyle}>
            <Dots color={meta.color} />
            {bevyRunning ? 'Bevy live' : 'working'}
          </span>
        )}
      </div>
      <div style={statsStyle}>
        {durationLabel && <Stat icon="◷" label={durationLabel} title="Elapsed" />}
        {run && toolCount > 0 && <Stat icon="⚒" label={String(toolCount)} title="Tool calls" />}
        {run && eventCount > 0 && <Stat icon="≣" label={String(eventCount)} title="Events" />}
      </div>
    </div>
  );
}

function Stat({ icon, label, title }: { icon: string; label: string; title: string }) {
  return (
    <span style={statStyle} title={title}>
      <span style={{ opacity: 0.7 }}>{icon}</span> {label}
    </span>
  );
}

function StatusBanner({ status, error, bevyRunning }: { status: string; error: string | null; bevyRunning: boolean }) {
  const meta = STATUS_META[status] ?? STATUS_META.queued;
  const live = status === 'running';
  return (
    <div style={bannerStyle(meta.color, live)}>
      {live && <span style={sweepStyle(meta.color)} aria-hidden />}
      <span style={bannerGlyphStyle(meta.color, live)}>{meta.glyph}</span>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
          <strong style={{ color: meta.color, fontSize: '0.78rem' }}>{meta.label}</strong>
          <span style={{ fontSize: '0.72rem', color: 'var(--fg-dim)' }}>{meta.sub}</span>
        </div>
        {bevyRunning && (
          <div style={{ fontSize: '0.68rem', color: 'var(--purple)', fontFamily: 'var(--font-mono)' }}>
            ● Bevy playtest running
          </div>
        )}
        {error && (
          <div style={{ marginTop: '3px', fontSize: '0.68rem', color: status === 'failed' ? 'var(--red)' : 'var(--accent)', fontFamily: 'var(--font-mono)', whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
            {status === 'failed' ? '⚠ ' : 'ⓘ '}{error}
          </div>
        )}
      </div>
    </div>
  );
}

function Dots({ color }: { color: string }) {
  return (
    <span style={{ display: 'inline-flex', gap: '3px', alignItems: 'center' }}>
      {[0, 1, 2].map((i) => (
        <span
          key={i}
          style={{
            width: '4px',
            height: '4px',
            borderRadius: '50%',
            background: color,
            animation: 'vn-dots 1.1s ease-in-out infinite',
            animationDelay: `${i * 0.16}s`,
          }}
        />
      ))}
    </span>
  );
}

/** Ticks once a second while active so the elapsed-time stat stays live. */
function useNow(active: boolean): number {
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    if (!active) return;
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, [active]);
  return now;
}

function fmtDuration(ms: number): string {
  const s = Math.max(0, Math.floor(ms / 1000));
  if (s < 60) return `${s}s`;
  const m = Math.floor(s / 60);
  if (m < 60) return `${m}m ${String(s % 60).padStart(2, '0')}s`;
  const h = Math.floor(m / 60);
  return `${h}h ${String(m % 60).padStart(2, '0')}m`;
}

// --- styles ----------------------------------------------------------------

function panelStyle(active: boolean): React.CSSProperties {
  return {
    position: 'relative',
    marginTop: 'var(--sp-3)',
    padding: '12px',
    border: '1px solid var(--border)',
    borderRadius: 'var(--radius-lg)',
    background: 'var(--surface-raised)',
    boxShadow: active ? '0 0 0 1px rgba(240,160,48,0.25), 0 0 22px rgba(240,160,48,0.08)' : 'none',
    overflow: 'hidden',
  };
}

const topGlowStyle: React.CSSProperties = {
  position: 'absolute',
  left: 0,
  right: 0,
  top: 0,
  height: '2px',
  background: 'linear-gradient(90deg, var(--accent), var(--cyan), var(--purple), var(--accent))',
  backgroundSize: '200% 100%',
  animation: 'vn-flow 3s linear infinite',
};

const headerStyle: React.CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'space-between',
  gap: '8px',
  marginBottom: '8px',
  flexWrap: 'wrap',
};

const titleStyle: React.CSSProperties = {
  display: 'inline-flex',
  alignItems: 'center',
  gap: '6px',
  fontFamily: 'var(--font-display)',
  fontSize: '0.72rem',
  fontWeight: 700,
  letterSpacing: '0.12em',
  color: 'var(--fg-bright)',
};

function titleBarStyle(color: string): React.CSSProperties {
  return {
    width: '3px',
    height: '14px',
    borderRadius: '2px',
    background: color,
    boxShadow: `0 0 6px ${color}`,
  };
}

function statusPillStyle(color: string, pulse: boolean): React.CSSProperties {
  return {
    display: 'inline-flex',
    alignItems: 'center',
    gap: '5px',
    fontSize: '0.66rem',
    fontWeight: 600,
    padding: '2px 8px',
    borderRadius: 'var(--radius-pill)',
    border: `1px solid ${color}`,
    background: `${color}1a`,
    color,
    textTransform: 'capitalize',
  };
}

function pillDotStyle(color: string, pulse: boolean): React.CSSProperties {
  return {
    width: '6px',
    height: '6px',
    borderRadius: '50%',
    background: color,
    boxShadow: pulse ? `0 0 6px ${color}` : 'none',
    animation: pulse ? 'vn-pulse 1.1s ease-in-out infinite' : undefined,
  };
}

const workingStyle: React.CSSProperties = {
  display: 'inline-flex',
  alignItems: 'center',
  gap: '5px',
  fontFamily: 'var(--font-mono)',
  fontSize: '0.64rem',
  color: 'var(--accent)',
  textTransform: 'lowercase',
};

const statsStyle: React.CSSProperties = {
  display: 'inline-flex',
  alignItems: 'center',
  gap: '6px',
  flexWrap: 'wrap',
};

const statStyle: React.CSSProperties = {
  display: 'inline-flex',
  alignItems: 'center',
  gap: '4px',
  fontFamily: 'var(--font-mono)',
  fontSize: '0.64rem',
  color: 'var(--fg-dim)',
  padding: '2px 7px',
  background: 'var(--surface)',
  border: '1px solid var(--border)',
  borderRadius: 'var(--radius-sm)',
};

function bannerStyle(color: string, live: boolean): React.CSSProperties {
  return {
    position: 'relative',
    display: 'flex',
    alignItems: 'flex-start',
    gap: '8px',
    padding: '7px 10px',
    marginBottom: '8px',
    borderRadius: 'var(--radius-md)',
    border: `1px solid ${color}${live ? '' : '33'}`,
    background: live
      ? `linear-gradient(90deg, ${color}1f, ${color}07)`
      : `${color}0f`,
    overflow: 'hidden',
  };
}

function sweepStyle(color: string): React.CSSProperties {
  return {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '40%',
    height: '100%',
    background: `linear-gradient(90deg, transparent, ${color}33, transparent)`,
    animation: 'vn-sweep 2.8s ease-in-out infinite',
  };
}

function bannerGlyphStyle(color: string, live: boolean): React.CSSProperties {
  return {
    fontSize: '0.85rem',
    color,
    lineHeight: 1.4,
    animation: live ? 'vn-pulse 1.1s ease-in-out infinite' : undefined,
  };
}

const actionBarStyle: React.CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  gap: '6px',
  flexWrap: 'wrap',
  marginBottom: '8px',
};

const blockStyle: React.CSSProperties = {
  marginBottom: '8px',
};

const chipStyle: React.CSSProperties = {
  fontFamily: 'var(--font-mono)',
  fontSize: '0.62rem',
  color: 'var(--fg-dim)',
  background: 'var(--surface)',
  padding: '2px 7px',
  borderRadius: 'var(--radius-sm)',
  border: '1px solid var(--border)',
  maxWidth: '200px',
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  whiteSpace: 'nowrap',
};

function summaryStyle(status: string): React.CSSProperties {
  const color = status === 'failed' ? 'var(--red)' : status === 'completed' ? 'var(--green)' : 'var(--accent)';
  return {
    fontSize: '0.76rem',
    color: 'var(--fg-dim)',
    background: `${color}0f`,
    border: `1px solid ${color}33`,
    borderLeft: `2px solid ${color}`,
    borderRadius: 'var(--radius-sm)',
    padding: '7px 9px',
    marginBottom: '8px',
  };
}

const sectionLabelStyle: React.CSSProperties = {
  fontFamily: 'var(--font-mono)',
  fontSize: '0.6rem',
  textTransform: 'uppercase',
  letterSpacing: '0.08em',
  color: 'var(--muted)',
};

const logLabelStyle: React.CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  gap: '2px',
  fontFamily: 'var(--font-mono)',
  fontSize: '0.6rem',
  textTransform: 'uppercase',
  letterSpacing: '0.08em',
  color: 'var(--fg-dim)',
  margin: '2px 0 4px',
};

const logStyle: React.CSSProperties = {
  maxHeight: '340px',
  overflowY: 'auto',
  background: 'var(--bg)',
  border: '1px solid var(--border)',
  borderRadius: 'var(--radius-sm)',
  padding: '8px 10px',
};

const inputStyle: React.CSSProperties = {
  padding: '5px 9px',
  fontSize: '0.78rem',
  background: 'var(--surface)',
  border: '1px solid var(--border)',
  borderRadius: 'var(--radius-sm)',
  color: 'var(--fg)',
  fontFamily: 'var(--font-mono)',
};

const primaryBtn: React.CSSProperties = {
  padding: '4px 12px',
  fontSize: '0.74rem',
  background: 'var(--accent)',
  border: 'none',
  borderRadius: 'var(--radius-sm)',
  cursor: 'pointer',
  color: 'var(--surface)',
  fontWeight: 600,
};

const dangerBtn: React.CSSProperties = {
  ...primaryBtn,
  background: 'var(--red)',
};

const accentBtn: React.CSSProperties = {
  ...primaryBtn,
  background: 'var(--cyan)',
  color: 'var(--bg)',
};

const ghostBtn: React.CSSProperties = {
  padding: '4px 12px',
  fontSize: '0.74rem',
  background: 'var(--surface)',
  border: '1px solid var(--border)',
  borderRadius: 'var(--radius-sm)',
  cursor: 'pointer',
  color: 'var(--fg-dim)',
};

const hintStyle: React.CSSProperties = {
  fontSize: '0.62rem',
  color: 'var(--muted)',
  fontFamily: 'var(--font-mono)',
  flex: 1,
  minWidth: 0,
};
