'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import {
  Bot,
  Check,
  ChevronDown,
  ChevronRight,
  LayoutTemplate,
  Loader2,
  Maximize2,
  Mic,
  Send,
  Sparkles,
  Square,
  Wrench,
  X,
  ExternalLink,
} from 'lucide-react';
import { io, type Socket } from 'socket.io-client';
import { cn } from '@/lib/utils';
import { env } from '@/lib/env';
import { useAuthStore } from '@/stores/auth-store';
import {
  bytesToBase64,
  downsampleTo16k,
  floatToPcm16,
} from '@/components/realtime-coach/audio-utils';
import {
  useAssistantChat,
  type Artifact,
  type Block,
  type ChatMessage,
  type ToolStep,
} from './use-assistant-chat';

const MODELS = [
  { value: 'deepseek', label: 'DeepSeek' },
  { value: 'gemini', label: 'Gemini' },
  { value: 'qwen', label: '通义千问' },
];

const EXAMPLES = [
  '今日推荐:挑几个该优先跟进的患者,并说明理由',
  '查一下患者孙柯的信息、就诊事实和画像',
  '现在有哪些应治未治、值得召回的患者?',
];

// ── 工具结果格式化 + 轻量摘要 ──────────────────────────────
function pretty(v: unknown): string {
  if (v == null) return '';
  if (typeof v === 'string') {
    try {
      return JSON.stringify(JSON.parse(v), null, 2);
    } catch {
      return v;
    }
  }
  return JSON.stringify(v, null, 2);
}
function resultSummary(result: unknown): string {
  if (result == null) return '';
  let v: unknown = result;
  if (typeof result === 'string') {
    try {
      v = JSON.parse(result);
    } catch {
      return '已返回';
    }
  }
  if (Array.isArray(v)) return `返回 ${v.length} 项`;
  if (v && typeof v === 'object') {
    const o = v as Record<string, unknown>;
    if (Array.isArray(o.items)) return `返回 ${o.items.length} 条`;
    if (o.recallPlan !== undefined || o.persona !== undefined) return '已返回患者数据';
    return '已返回数据';
  }
  return '已返回';
}

// ── 工具调用折叠卡(对齐设计稿)─────────────────────────────
function ToolCallView({ step }: { step: ToolStep }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="overflow-hidden rounded-lg border border-slate-100 bg-slate-50/70">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-slate-100/60"
      >
        <ChevronRight
          className={cn('h-3.5 w-3.5 flex-none text-slate-400 transition-transform', open && 'rotate-90')}
        />
        <Wrench className="h-3.5 w-3.5 flex-none text-slate-400" />
        <span className="flex-none text-[12px] text-slate-500">调用工具</span>
        <code className="flex-none rounded border border-slate-100 bg-white px-1.5 py-0.5 font-mono text-[11.5px] text-slate-700">
          {step.tool}
        </code>
        <span className="ml-1 truncate text-[11px] text-slate-400">
          {step.status === 'done' ? resultSummary(step.result) : ''}
        </span>
        <span className="ml-auto flex-none">
          {step.status === 'running' ? (
            <Loader2 className="h-3.5 w-3.5 animate-spin text-slate-400" />
          ) : step.status === 'error' ? (
            <span className="text-[11px] text-rose-600">出错</span>
          ) : (
            <Check className="h-3.5 w-3.5 text-emerald-600" />
          )}
        </span>
      </button>
      {open && (
        <div className="space-y-2 border-t border-slate-100/70 px-3 pb-3 pt-1">
          <CodeBlock label="入参" code={pretty(step.args) || '{}'} />
          {step.result !== undefined && <CodeBlock label="返回" code={pretty(step.result)} muted />}
        </div>
      )}
    </div>
  );
}

function CodeBlock({ label, code, muted }: { label: string; code: string; muted?: boolean }) {
  return (
    <div>
      <div className="mb-1 mt-1.5 text-[10.5px] font-medium uppercase tracking-wide text-slate-400">
        {label}
      </div>
      <pre
        className={cn(
          'overflow-x-auto rounded-md border border-slate-100 bg-white px-3 py-2 text-[11.5px] leading-relaxed text-slate-600',
          muted && 'max-h-44 overflow-y-auto',
        )}
      >
        <code>{code}</code>
      </pre>
    </div>
  );
}

// ── LLM 文本 → markdown 渲染(用户要求:不复用设计的结构卡,改 markdown 解析)──
function Markdown({ text }: { text: string }) {
  return (
    <div className="text-[13.5px] leading-relaxed text-slate-700">
      <ReactMarkdown
        remarkPlugins={[remarkGfm]}
        components={{
          h1: ({ children }) => <h1 className="mb-2 mt-3 text-[16px] font-semibold text-slate-900">{children}</h1>,
          h2: ({ children }) => <h2 className="mb-1.5 mt-3 text-[15px] font-semibold text-slate-900">{children}</h2>,
          h3: ({ children }) => <h3 className="mb-1 mt-2.5 text-[14px] font-semibold text-slate-800">{children}</h3>,
          p: ({ children }) => <p className="my-1.5">{children}</p>,
          ul: ({ children }) => <ul className="my-1.5 ml-4 list-disc space-y-1">{children}</ul>,
          ol: ({ children }) => <ol className="my-1.5 ml-4 list-decimal space-y-1">{children}</ol>,
          li: ({ children }) => <li className="leading-relaxed">{children}</li>,
          strong: ({ children }) => <strong className="font-semibold text-slate-900">{children}</strong>,
          a: ({ children, href }) => (
            <a href={href} className="text-teal-700 underline" target="_blank" rel="noreferrer">
              {children}
            </a>
          ),
          hr: () => <hr className="my-3 border-slate-100" />,
          blockquote: ({ children }) => (
            <blockquote className="my-2 border-l-2 border-teal-300 bg-teal-50/40 py-1 pl-3 text-slate-600">
              {children}
            </blockquote>
          ),
          code: ({ children, className }) =>
            className ? (
              <code className={className}>{children}</code>
            ) : (
              <code className="rounded bg-slate-100 px-1 py-0.5 font-mono text-[12px] text-slate-700">
                {children}
              </code>
            ),
          pre: ({ children }) => (
            <pre className="my-2 overflow-x-auto rounded-md border border-slate-100 bg-slate-50 p-3 text-[12px]">
              {children}
            </pre>
          ),
          table: ({ children }) => (
            <div className="my-2 overflow-x-auto">
              <table className="w-full border-collapse text-[12.5px]">{children}</table>
            </div>
          ),
          thead: ({ children }) => <thead className="bg-slate-50">{children}</thead>,
          th: ({ children }) => (
            <th className="border border-slate-100 px-2 py-1 text-left font-medium text-slate-600">{children}</th>
          ),
          td: ({ children }) => <td className="border border-slate-100 px-2 py-1 text-slate-700">{children}</td>,
        }}
      >
        {text}
      </ReactMarkdown>
    </div>
  );
}

function BlockView({ block }: { block: Block }) {
  if (block.kind === 'tool') return <ToolCallView step={block.step} />;
  if (block.kind === 'artifact') return <ArtifactView artifact={block.artifact} />;
  return <Markdown text={block.text} />;
}

// ── Artifact:模型产出的 HTML 在隔离沙箱 iframe 渲染(即用即焚)──────────────
// 安全:sandbox="allow-scripts" 不含 allow-same-origin → 脚本在 null origin,
//   碰不到父页 cookie/localStorage、无法带凭证调 PAC;CSP 只放行 Tailwind/Chart.js CDN
//   且 connect-src 'none' 堵死任何外传(患者数据不会被偷渡)。
const ARTIFACT_CSP = [
  "default-src 'none'",
  "script-src 'unsafe-inline' 'unsafe-eval' https://cdn.tailwindcss.com https://cdn.jsdelivr.net",
  "style-src 'unsafe-inline' https://cdn.tailwindcss.com https://fonts.googleapis.com",
  'font-src https://fonts.gstatic.com',
  'img-src data:',
  "connect-src 'none'",
  "base-uri 'none'",
  "form-action 'none'",
].join('; ');

const ARTIFACT_HEAD = `<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="${ARTIFACT_CSP}">
<meta name="viewport" content="width=device-width,initial-scale=1">
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>body{margin:0;font-family:"PingFang SC","Noto Sans CJK SC",system-ui,sans-serif;background:#f8fafc;color:#0f172a}
/* 切断 Chart.js 响应式 ↔ 自适应 iframe 高度的正反馈环:画布层高写死上限,
   无论模型用 maintainAspectRatio:false 还是百分比容器,canvas 都不会随 body 增高而无限拉长。*/
canvas{max-height:360px!important}</style>`;

// 持久壳:iframe 只加载一次(Tailwind/Chart.js 不重载),内容经 postMessage 注入 #root。
// 流式中只 set innerHTML(Tailwind 的 MutationObserver 自动上样式);final 时重建 <script> 让 Chart.js 执行。
function artifactShell(): string {
  return `<!DOCTYPE html><html lang="zh"><head>${ARTIFACT_HEAD}</head><body class="p-4"><div id="root"></div>
<script>
(function(){
  var root=document.getElementById('root');
  function h(){parent.postMessage({__artifactHeight:document.documentElement.scrollHeight},'*');}
  new ResizeObserver(h).observe(document.body);
  window.addEventListener('message',function(e){
    var d=e.data||{}; if(!d.__artifact)return;
    root.innerHTML=d.html||'';
    if(d.final){root.querySelectorAll('script').forEach(function(o){var s=document.createElement('script');for(var i=0;i<o.attributes.length;i++){s.setAttribute(o.attributes[i].name,o.attributes[i].value);}s.textContent=o.textContent;o.parentNode.replaceChild(s,o);});}
    setTimeout(h, d.final?150:0);
  });
  parent.postMessage({__ready:true},'*');
})();
</script>
</body></html>`;
}

// openFull / 兜底:自包含整页(内容内联,脚本随页面加载执行)。
function buildStandaloneDoc(inner: string): string {
  return `<!DOCTYPE html><html lang="zh"><head>${ARTIFACT_HEAD}</head><body class="p-4">${inner}</body></html>`;
}

/// 单个 artifact 的沙箱 iframe 渲染器(持久壳 + postMessage 增量注入;可多实例:
/// 内联卡 + 居中放大窗同时挂,各自吃同一份流式 html → 放大窗也实时"长")。
/// autoHeight:内联卡随内容增高;放大窗 false(锁满容器,内部滚动)。
function ArtifactFrame({
  artifact,
  autoHeight,
  className,
}: {
  artifact: Artifact;
  autoHeight: boolean;
  className?: string;
}) {
  const ref = useRef<HTMLIFrameElement>(null);
  const [height, setHeight] = useState(120);
  const shell = useMemo(() => artifactShell(), []);
  const readyRef = useRef(false);
  const htmlRef = useRef(artifact.html);
  const finalRef = useRef(!artifact.streaming);
  const lastPostRef = useRef(0);

  const post = () => {
    const win = ref.current?.contentWindow;
    if (!win || !readyRef.current) return;
    win.postMessage({ __artifact: true, html: htmlRef.current, final: finalRef.current }, '*');
    lastPostRef.current = Date.now();
  };

  useEffect(() => {
    htmlRef.current = artifact.html;
    finalRef.current = !artifact.streaming;
    if (!readyRef.current) return;
    if (finalRef.current) {
      post();
      return;
    }
    const since = Date.now() - lastPostRef.current;
    if (since >= 500) {
      post();
      return;
    }
    const t = setTimeout(post, 500 - since);
    return () => clearTimeout(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [artifact.html, artifact.streaming]);

  useEffect(() => {
    const onMsg = (e: MessageEvent) => {
      if (e.source !== ref.current?.contentWindow) return;
      const d = e.data as { __ready?: boolean; __artifactHeight?: number };
      if (d?.__ready) {
        readyRef.current = true;
        post();
      }
      if (autoHeight && typeof d?.__artifactHeight === 'number') {
        setHeight(Math.min(Math.max(d.__artifactHeight, 60), 1600));
      }
    };
    window.addEventListener('message', onMsg);
    return () => window.removeEventListener('message', onMsg);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [autoHeight]);

  return (
    <iframe
      ref={ref}
      title={artifact.title || 'artifact'}
      sandbox="allow-scripts"
      srcDoc={shell}
      className={cn('w-full', className)}
      style={autoHeight ? { height, border: 0 } : { border: 0 }}
    />
  );
}

function ArtifactView({ artifact }: { artifact: Artifact }) {
  const [expanded, setExpanded] = useState(false);

  const openTab = () => {
    const w = window.open('', '_blank');
    w?.document.write(buildStandaloneDoc(artifact.html));
    w?.document.close();
  };

  return (
    <div className="overflow-hidden rounded-lg border border-slate-100 bg-white shadow-sm">
      <div className="flex items-center gap-1.5 border-b border-slate-100 bg-slate-50/60 px-3 py-1.5">
        <LayoutTemplate className="h-3.5 w-3.5 text-teal-600" />
        <span className="text-[11.5px] font-medium text-slate-500">{artifact.title || '可视化卡片'}</span>
        <button
          type="button"
          onClick={() => setExpanded(true)}
          title="放大查看"
          className="ml-auto inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10.5px] text-slate-400 hover:bg-slate-100 hover:text-slate-600"
        >
          <Maximize2 className="h-3 w-3" />
        </button>
      </div>
      <ArtifactFrame artifact={artifact} autoHeight />

      {/* 居中放大窗:与内联卡同源同流(streaming 时这里同步在"长")。
          ⚠️ portal 到 body —— 助手小窗容器带 transform(滑出动画),CSS 规定 transform 祖先
          会把后代 fixed 圈进自己坐标系 → 不 portal 大窗就被困在小窗里(2026-06 实测)。 */}
      {expanded &&
        typeof document !== 'undefined' &&
        createPortal(
        <div className="fixed inset-0 z-[70] flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/40" onClick={() => setExpanded(false)} />
          <div className="relative z-10 flex h-[min(86vh,920px)] w-[min(980px,94vw)] flex-col overflow-hidden rounded-xl border border-slate-100 bg-white shadow-2xl">
            <div className="flex flex-none items-center gap-1.5 border-b border-slate-100 bg-slate-50/60 px-3 py-2">
              <LayoutTemplate className="h-4 w-4 text-teal-600" />
              <span className="text-[12.5px] font-medium text-slate-600">{artifact.title || '可视化卡片'}</span>
              {artifact.streaming && (
                <span className="ml-1 inline-flex items-center gap-1 text-[10.5px] text-teal-600">
                  <Loader2 className="h-3 w-3 animate-spin" />
                  生成中
                </span>
              )}
              <button
                type="button"
                onClick={openTab}
                title="新窗口打开"
                className="ml-auto inline-flex h-6 w-6 items-center justify-center rounded text-slate-400 hover:bg-slate-100 hover:text-slate-600"
              >
                <ExternalLink className="h-3.5 w-3.5" />
              </button>
              <button
                type="button"
                onClick={() => setExpanded(false)}
                title="关闭"
                className="inline-flex h-6 w-6 items-center justify-center rounded text-slate-400 hover:bg-slate-100 hover:text-slate-600"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
            <ArtifactFrame artifact={artifact} autoHeight={false} className="min-h-0 flex-1" />
          </div>
        </div>,
        document.body,
      )}
    </div>
  );
}

// 生成中指示:覆盖"工具已返回但下一段(文字/artifact)还在整段生成"的空档。
function GeneratingHint() {
  return (
    <div className="flex items-center gap-1.5 text-[12px] text-slate-400">
      <Loader2 className="h-3.5 w-3.5 animate-spin text-teal-500" />
      <span>生成中…</span>
    </div>
  );
}

function MessageView({ message, streaming }: { message: ChatMessage; streaming?: boolean }) {
  if (message.role === 'user') {
    return (
      <div className="flex justify-end gap-2.5">
        <div className="max-w-[80%] rounded-2xl rounded-tr-sm bg-slate-800 px-3.5 py-2 text-[13.5px] leading-relaxed text-white">
          {message.blocks.map((b) => (b.kind === 'text' ? b.text : '')).join('')}
        </div>
      </div>
    );
  }
  // 流式中:若最后一块不是正在增长的文字(即在调工具/生成 artifact 的空档),补一个"生成中"。
  const last = message.blocks[message.blocks.length - 1];
  const showHint = streaming && (!last || last.kind !== 'text');
  return (
    <div className="flex gap-2.5">
      <span className="mt-0.5 inline-flex h-7 w-7 flex-none items-center justify-center rounded-full bg-teal-600 text-white">
        <Bot className="h-4 w-4" />
      </span>
      <div className="min-w-0 flex-1 space-y-2.5 pt-0.5">
        {message.blocks.map((b, i) => (
          <BlockView key={i} block={b} />
        ))}
        {showHint && <GeneratingHint />}
      </div>
    </div>
  );
}

function ModelSelect({
  model,
  setModel,
  disabled,
}: {
  model: string;
  setModel: (m: string) => void;
  disabled?: boolean;
}) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const h = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  const label = MODELS.find((m) => m.value === model)?.label ?? model;
  return (
    <div className="relative" ref={ref}>
      <button
        type="button"
        disabled={disabled}
        onClick={() => setOpen((o) => !o)}
        className="inline-flex items-center gap-1.5 rounded-md border border-slate-100 bg-white px-2.5 py-1.5 text-[12.5px] text-slate-700 transition-colors hover:bg-slate-50 disabled:opacity-50"
      >
        <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
        {label}
        <ChevronDown className={cn('h-3.5 w-3.5 text-slate-400 transition-transform', open && 'rotate-180')} />
      </button>
      {open && (
        <div className="absolute right-0 z-50 mt-1 w-40 rounded-lg border border-slate-100 bg-white py-1 shadow-lg">
          {MODELS.map((m) => (
            <button
              key={m.value}
              type="button"
              onClick={() => {
                setModel(m.value);
                setOpen(false);
              }}
              className={cn(
                'flex w-full items-center gap-2 px-3 py-1.5 text-left text-[12.5px] hover:bg-slate-50',
                m.value === model ? 'font-medium text-teal-700' : 'text-slate-700',
              )}
            >
              {m.value === model ? <Check className="h-3.5 w-3.5" /> : <span className="w-3.5" />}
              {m.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

export function AssistantChat({
  variant = 'page',
  onClose,
  examples,
}: {
  /** page = /assistant 整页;widget = 详情页右下角吸附小窗(紧凑头部 + 可收起) */
  variant?: 'page' | 'widget';
  onClose?: () => void;
  /** 空态开场建议(规则生成,调用方按场景定制);不传用页面版默认 */
  examples?: string[];
} = {}) {
  const { messages, status, model, setModel, send, stop } = useAssistantChat();
  const [input, setInput] = useState('');
  const scrollRef = useRef<HTMLDivElement>(null);
  const taRef = useRef<HTMLTextAreaElement>(null);
  // 是否"贴底":用户在底部附近时跟随自动滚;一旦上滚阅读则停,直到滚回底部。
  const stickRef = useRef(true);

  // 流式/新消息时,仅在贴底状态才滚到底(否则尊重用户当前阅读位置)。
  useEffect(() => {
    const el = scrollRef.current;
    if (el && stickRef.current) el.scrollTop = el.scrollHeight;
  }, [messages]);

  // 用户滚动 → 据是否接近底部(<80px)更新贴底状态。
  const onScroll = () => {
    const el = scrollRef.current;
    if (!el) return;
    stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
  };

  // 发起新提问 → 重新贴底(让用户看到自己的消息 + 回答)。
  const fire = (text: string) => {
    stickRef.current = true;
    void send(text);
  };

  const submit = () => {
    if (!input.trim() || status === 'streaming') return;
    fire(input);
    setInput('');
    if (taRef.current) taRef.current.style.height = 'auto';
  };

  // ── 实时听写:点击开启 → 边说边出字到输入框;再点 = 纯退出(已上屏文字保留)──
  // 链路:麦克风 PCM16 16k(RMS 静音门控)→ socket.io → 网关按停顿断句调 SenseVoice
  //   dictation:partial = 当前句滚动识别(覆盖式);dictation:final = 本句定稿(累加)
  const [voice, setVoice] = useState<'idle' | 'live'>('idle');
  const [voiceErr, setVoiceErr] = useState<string | null>(null);
  const dictRef = useRef<{
    socket: Socket;
    stream: MediaStream;
    ctx: AudioContext;
    base: string;
    finalized: string;
  } | null>(null);

  const stopVoice = () => {
    const d = dictRef.current;
    dictRef.current = null;
    if (d) {
      d.socket.disconnect();
      d.ctx.close().catch(() => undefined);
      d.stream.getTracks().forEach((t) => t.stop());
    }
    setVoice('idle');
  };

  const toggleVoice = async () => {
    setVoiceErr(null);
    if (voice === 'live') {
      stopVoice();
      return;
    }
    const token = useAuthStore.getState().accessToken;
    if (!token) {
      setVoiceErr('未鉴权,请重新登录');
      return;
    }
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
      });
      const socket = io(`${env.apiBaseUrl}/pac/v1/assistant/dictation`, {
        query: { token },
        transports: ['websocket'],
        forceNew: true,
      });
      const ctx = new AudioContext();
      const source = ctx.createMediaStreamSource(stream);
      const proc = ctx.createScriptProcessor(4096, 1, 1);
      // 静音门控:无声不发帧 → 帧间隙就是网关的断句信号(同 realtime-coach 参数)
      const SILENCE_RMS = 0.03;
      const ONSET_FRAMES = 2;
      const HANGOVER_FRAMES = 6;
      let hangover = 0;
      let loudStreak = 0;
      proc.onaudioprocess = (e) => {
        if (socket.disconnected) return;
        const f32 = e.inputBuffer.getChannelData(0);
        let sum = 0;
        for (let i = 0; i < f32.length; i++) sum += f32[i]! * f32[i]!;
        const rms = Math.sqrt(sum / f32.length);
        if (rms > SILENCE_RMS) {
          loudStreak++;
          if (loudStreak >= ONSET_FRAMES) hangover = HANGOVER_FRAMES;
        } else {
          loudStreak = 0;
        }
        if (hangover <= 0) return;
        hangover--;
        const pcm = floatToPcm16(downsampleTo16k(f32, ctx.sampleRate));
        socket.emit('audio:frame', { frame: bytesToBase64(pcm) });
      };
      source.connect(proc);
      proc.connect(ctx.destination);

      const d = { socket, stream, ctx, base: input.trim() ? `${input.trimEnd()} ` : '', finalized: '' };
      dictRef.current = d;
      const render = (partial: string) => setInput(`${d.base}${d.finalized}${partial}`);
      socket.on('dictation:partial', ({ text }: { text: string }) => render(text));
      socket.on('dictation:final', ({ text }: { text: string }) => {
        if (text) d.finalized += text;
        render('');
      });
      socket.on('dictation:error', ({ message }: { message: string }) => setVoiceErr(message));
      socket.on('connect_error', () => {
        setVoiceErr('听写连接失败');
        stopVoice();
      });
      setVoice('live');
      taRef.current?.focus();
    } catch {
      setVoiceErr('无法访问麦克风(请检查浏览器授权)');
      stopVoice();
    }
  };

  const isWidget = variant === 'widget';
  return (
    <div className={cn('flex flex-col bg-slate-50', isWidget ? 'h-full' : 'h-[100dvh]')}>
      {/* Header */}
      <header className="flex-none border-b border-slate-100 bg-white/90 backdrop-blur">
        <div
          className={cn(
            'mx-auto flex items-center gap-2.5',
            isWidget ? 'h-10 px-2.5' : 'h-[3.25rem] max-w-3xl px-4 py-2.5',
          )}
        >
          <span
            className={cn(
              'inline-flex flex-none items-center justify-center rounded-lg bg-teal-600 text-white',
              isWidget ? 'h-6 w-6' : 'h-7 w-7',
            )}
          >
            <Bot className={isWidget ? 'h-3.5 w-3.5' : 'h-4 w-4'} />
          </span>
          <h1 className={cn('font-semibold text-slate-900', isWidget ? 'text-[13px]' : 'text-[14px]')}>
            {isWidget ? '助手' : '外部助手'}
          </h1>
          <div className="ml-auto flex items-center gap-1.5">
            <ModelSelect model={model} setModel={setModel} disabled={status === 'streaming'} />
            {onClose && (
              <button
                type="button"
                onClick={onClose}
                title="收起"
                className="inline-flex h-6 w-6 items-center justify-center rounded-md text-slate-400 hover:bg-slate-100 hover:text-slate-600"
              >
                <ChevronDown className="h-4 w-4" />
              </button>
            )}
          </div>
        </div>
      </header>

      {/* Messages */}
      <div ref={scrollRef} onScroll={onScroll} className="flex-1 overflow-y-auto">
        <div className="mx-auto max-w-3xl space-y-5 px-4 py-5">
          {messages.length === 0 ? (
            <div className={cn('flex flex-col items-center justify-center gap-4 text-center', isWidget ? 'py-8' : 'py-20')}>
              <span className="inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-teal-600 text-white">
                <Bot className="h-6 w-6" />
              </span>
              <div className="max-w-md text-[13.5px] text-slate-500">
                问我关于患者的问题，我会查询 PAC 实时数据。
              </div>
              <div className="flex flex-wrap justify-center gap-1.5">
                {(examples ?? EXAMPLES).map((ex) => (
                  <button
                    key={ex}
                    type="button"
                    onClick={() => fire(ex)}
                    className="rounded-full border border-slate-100 bg-white px-3 py-1.5 text-[11.5px] text-slate-600 transition-colors hover:border-teal-300 hover:bg-teal-50/50 hover:text-teal-700"
                  >
                    {ex}
                  </button>
                ))}
              </div>
            </div>
          ) : (
            messages.map((m, i) => (
              <MessageView
                key={m.id}
                message={m}
                streaming={status === 'streaming' && i === messages.length - 1 && m.role === 'assistant'}
              />
            ))
          )}
        </div>
      </div>

      {/* Composer */}
      <div className="flex-none border-t border-slate-100 bg-white">
        <div className="mx-auto max-w-3xl px-4 py-3">
          <div className="flex items-end gap-2 rounded-xl border border-slate-100 bg-white px-3 py-2 transition-all focus-within:border-teal-300 focus-within:ring-2 focus-within:ring-teal-200">
            <textarea
              ref={taRef}
              rows={1}
              value={input}
              onChange={(e) => {
                setInput(e.target.value);
                e.target.style.height = 'auto';
                e.target.style.height = Math.min(e.target.scrollHeight, 140) + 'px';
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault();
                  submit();
                }
              }}
              placeholder="问关于患者画像 / 事实 / 召回计划的问题…  (Enter 发送,Shift+Enter 换行)"
              className="max-h-[140px] flex-1 resize-none bg-transparent py-1 text-[13.5px] leading-relaxed text-slate-800 placeholder:text-slate-400 focus:outline-none"
            />
            <button
              type="button"
              onClick={toggleVoice}
              title={voice === 'live' ? '结束听写' : '语音输入(边说边出字)'}
              className={cn(
                'mb-0.5 inline-flex h-8 w-8 flex-none items-center justify-center rounded-lg transition-colors',
                voice === 'live'
                  ? 'animate-pulse bg-rose-100 text-rose-600 ring-1 ring-inset ring-rose-300'
                  : 'bg-slate-100 text-slate-500 hover:bg-teal-50 hover:text-teal-700',
              )}
            >
              <Mic className="h-4 w-4" />
            </button>
            {status === 'streaming' ? (
              <button
                type="button"
                onClick={stop}
                title="停止"
                className="mb-0.5 inline-flex h-8 w-8 flex-none items-center justify-center rounded-lg bg-slate-100 text-slate-500 transition-colors hover:bg-slate-200"
              >
                <Square className="h-3.5 w-3.5" />
              </button>
            ) : (
              <button
                type="button"
                onClick={submit}
                disabled={!input.trim()}
                title="发送"
                className={cn(
                  'mb-0.5 inline-flex h-8 w-8 flex-none items-center justify-center rounded-lg transition-colors',
                  input.trim() ? 'bg-teal-600 text-white hover:bg-teal-700' : 'bg-slate-100 text-slate-400',
                )}
              >
                <Send className="h-4 w-4" />
              </button>
            )}
          </div>
          <p className="mt-1.5 text-center text-[10.5px] text-slate-400">
            结果仅供参考 请核对后使用
          </p>
        </div>
      </div>
    </div>
  );
}
