/**
 * ChatInput — B端设计系统 · 业务组件 (Tailwind 内联)
 *
 * AI 对话输入框主体，三层结构：底层氛围背景 → 输入区域 → 猫条。
 * 内置默认工具栏（@Agent 36px Select 风 + @/指令/附件 36×36 图标钮）。
 * 内置三态发送按钮：disabled / active / running。
 * 所有图标统一走 b-end Icon 组件，颜色对齐 token。
 * variant 决定初始视图，组件内部自管理交互流转。
 *
 * 变体（6 个，按场景归类）：
 *   default-sm  — 收起态，点击展开为 default
 *   default     — 可编辑态，输入文字 → 发送 → 内部进入 replying
 *   im-basic    — 纯 IM 基础输入框：无猫条与 AI 语境；四周留白一致；左下按钮支持声明式自定义；默认「图片 / 表情」两钮；发送后不进入 replying（不受 autoReplyOnSend 影响）
 *   replying    — AI 正在回复（短任务）：状态文案 + 36×36 停止按钮
 *   busy        — AI 忙碌：执行中 / 排队中。渐变背景 + 状态文案 + 36×36 停止按钮
 *   readonly    — 无编辑权限：任务分享只读 / 抢单引导。白底 + 状态文案 + 36px 文字按钮
 *
 * 内置交互（default 态）：
 *   - Agent 按钮：点击弹下拉，单选切换当前 Agent
 *   - @ 按钮  ：点击弹下拉，添加 Mention chip（可重复添加，X 删除）
 *   - / 按钮  ：点击弹下拉，添加 Command chip（可重复添加，X 删除）
 *   - 附件按钮：唤起本地文件选择器，多选；选中后以文件卡形式展示，X 删除
 *   - 已选 Mention/Command 以浅青色 chip 行显示在 textarea 上方
 *   - 已选附件以 180px 文件卡（多列折行）显示在 chip 行上方
 *   - 列表数据通过 props 注入（agentOptions/mentionOptions/commandOptions），不传则用内置示例数据
 *
 * Props:
 *   variant         — 'default-sm'|'default'|'im-basic'|'replying'|'busy'|'readonly'（受控，外部切换 variant 会同步内部 view 并清空编辑器；im-basic 内部固定为可编辑 default 视图）
 *   agentName       — @Agent 按钮初始文字，默认 'Auto'
 *   agentOptions    — Agent 选项，[{ id, label, desc? }]
 *   mentionOptions  — @ 选项，[{ id, label, icon? }]
 *   commandOptions  — / 选项，[{ id, label, icon? }]
 *   acceptFiles     — 文件选择器 accept 属性，默认 '*'
 *   multipleFiles   — 是否允许多选，默认 true
 *   catBarText      — 猫条提示文字（不传则用各 variant 的默认文案）
 *   catBarIcon      — ReactNode（猫条左侧图标插槽，不传则显示内置猫咪头像）
 *   placeholder     — 输入占位文字，默认 '需要我为你做什么'
 *   statusText      — replying/busy/readonly 三态下的提示说明文字
 *   actionText      — readonly 态按钮文案（默认"继续对话"）
 *   onSend          — 发送回调 (text, ctx) => void；ctx = { agent, segments, mentions, commands, attachments }
 *                     · segments：按 DOM 顺序排好的 token 列表（text + entity 混排），可直接对接 ChatMessage.userContent
 *                     · text：纯文本拼接（chip label 也算进去），兼容旧调用方
 *   onStop          — replying/busy 停止回调
 *   onAction        — readonly 操作按钮回调
 *   onAgentChange   — Agent 切换回调 (agent) => void
 *   onMentionsChange/ onCommandsChange / onAttachmentsChange — 选中态变化回调
 *   toolbar         — ReactNode（自定义工具栏，传入则覆盖内置默认工具栏，附带浮层/文件选择器也将一并禁用）
 *   children        — ReactNode（覆盖内置 textarea）
 *   className       — 额外类名
 *   style           — 内联样式
 *   autoReplyOnSend — 默认 true。true 时发送后内部自动 setView('replying')（im-basic 恒不进入 replying）；外部完全受控状态机时传 false 让外部 variant 决定
 *   imActions       — 仅 im-basic 生效。声明式左下角按钮数组，单项形如 { id, icon, ariaLabel, onClick? }；
 *                     默认 [{ id:'image', icon:'image-01-stroked', ariaLabel:'图片' }, { id:'emoji', icon:'face-smile-stroked', ariaLabel:'表情' }]
 *                     最多展示 5 个；传 [] 可隐藏左下角按钮区
 *   onImImageClick  — 可选。variant=im-basic 时覆盖左下「图片」钮默认行为（默认等同附件：触发隐藏 file input）
 *   onImEmojiClick  — 可选。variant=im-basic 时点击「表情」钮回调（未传则无操作，由业务接表情面板）
 *   prefillText     — 外部回填到编辑器的文本（搭配 prefillSeed 使用）
 *   prefillSeed     — 数字 seed，每次变化时把 prefillText 覆盖塞进编辑器并聚焦（用于推荐 chip / 追问 chip 回填草稿）
 */

import { useState, useRef, useCallback, useEffect, useLayoutEffect, useMemo } from 'react';
import { createRoot } from 'react-dom/client';
import Button from './Button';
import Dropdown from './Dropdown';
import Icon from './Icon';
/* 文件类型图标统一从 ./file-type-assets 共享 lookup 取，
 * 与 ChatMessage（用户消息附件 / 产物卡）保持视觉一致 */
import { getFileTypeIcon } from './file-type-assets';

/* ── 外层容器 ── */
const WRAPPER = [
  'tfds-chat-input',
  'flex flex-col isolate items-start justify-end',
  'relative w-full pt-2 px-2 text-left',
].join(' ');

/* im-basic：无猫条，外层四边留白一致（与默认输入白卡视觉对齐） */
const WRAPPER_IM_BASIC = [
  'tfds-chat-input',
  'flex flex-col isolate items-stretch justify-end',
  'relative w-full p-2 text-left',
].join(' ');

/* ── 底层氛围背景 ── */
const BACKDROP = [
  'absolute inset-0 -bottom-2 rounded-[20px] z-[1]',
  'bg-[rgba(80,99,168,0.05)] border border-white',
].join(' ');

/* im-basic：无猫条时底层背景不再向下外扩，避免上下不对称 */
const BACKDROP_SYMMETRIC = [
  'absolute inset-0 rounded-[20px] z-[1]',
  'bg-[rgba(80,99,168,0.05)] border border-white',
].join(' ');

/* ── 猫条 ── */
const CAT_BAR = [
  'flex items-start gap-5 shrink-0 w-full',
  'h-[36px] pt-1 px-4',
  'relative z-[3] text-left',
].join(' ');

const CAT_BAR_TEXT = [
  'flex flex-1 min-w-0 h-6 items-center',
  'text-left text-xs leading-4 font-normal text-foreground-secondary',
].join(' ');

/* ── 输入区域（默认态多行 py-14；其它单行态 py-12，让纵向更紧凑）
 *  不加 overflow-hidden：让 Agent/@/指令 浮层可以从工具栏向上延伸到输入区外部
 *  z 高于猫条（z-[3]）：弹窗向上弹时不会被猫条遮挡
 */
const INPUT_AREA_BASE = [
  'relative shrink-0 w-full z-[4]',
  'rounded-xl bg-surface',
  'px-[14px] text-left',
].join(' ');
const INPUT_PAD_LG = 'py-[14px]';
const INPUT_PAD_SM = 'py-[12px]';

/* 青紫光晕（共用阴影值）
 *  ⚠️ Tailwind v4 是纯字符串扫描器，类名必须以**完整字面量**出现在源码里才能生成 CSS。
 *  焦点态光晕不能写成 `focus-within:${GLOW_SHADOW}` 拼接 —— 那样扫描器看不到 `focus-within:shadow-[...]`。
 *  所以下面把焦点变体写成独立字面量字符串。两条阴影值需保持同步。
 */
const GLOW_SHADOW = 'shadow-[-12px_20px_30px_-27px_rgba(46,202,180,0.8),12px_20px_30px_-27px_rgba(184,46,202,0.8)]';

/* 焦点光晕：default 态 focus-within 时出现 */
const FOCUS_SHADOW = 'transition-shadow tfds-motion-ui-normal focus-within:shadow-[-12px_20px_30px_-27px_rgba(46,202,180,0.8),12px_20px_30px_-27px_rgba(184,46,202,0.8)]';

/* 忙碌态：透明 1px 边 + 双层 background-clip = 淡彩底 + 柔彩描边（贴合圆角） */
const BUSY_BORDER = 'border border-transparent';
const BUSY_BG = [
  'var(--gradient-ai-fill-1) padding-box',
  'linear-gradient(#fff, #fff) padding-box',
  'linear-gradient(67deg, #C5F6F3 0%, #C6DEF6 37%, #D5D2FD 70%, #F3DAF9 100%) border-box',
].join(', ');

/* ── 工具栏图标按钮（@ / 指令 / 附件 共用） ── */
const TOOL_ICON_BTN = [
  'inline-flex items-center justify-center shrink-0',
  'w-[36px] h-[36px] rounded-lg border border-border-default',
  'bg-surface text-foreground-muted',
  'cursor-pointer select-none transition-colors tfds-motion-ui-fast',
  'hover:bg-blueGrey-50 hover:border-border-strong active:bg-blueGrey-100',
  'focus-visible:[outline:2px_solid] focus-visible:outline-brand-200 focus-visible:outline-offset-2',
].join(' ');

/* ── 品牌选中态（与 Filter selected 一致：brand-50 底 / brand-300 边 / brand-800 字） ── */
const BRAND_SELECTED_SURFACE = 'bg-brand-50 border-brand-300 text-brand-800';
const BRAND_SELECTED_HOVER = 'hover:bg-brand-100 hover:border-brand-400';
const BRAND_SELECTED_ICON = 'text-brand-800';

/* ── Agent 选择器（高度对齐 Select md，圆角对齐工具栏 IconButton）
 *  AGENT_BTN          → 默认态（Auto / 第一项）：白底 + 灰边 + 灰图标
 *  AGENT_BTN_ACTIVE   → 选中具体模型：与 Filter 选中胶囊同色值
 */
const AGENT_BTN = [
  'inline-flex items-center shrink-0',
  'h-[36px] gap-2 px-3 rounded-lg border border-border-default',
  'bg-surface text-sm text-foreground',
  'cursor-pointer select-none transition-colors tfds-motion-ui-fast',
  'hover:border-border-strong',
  'focus-visible:[outline:2px_solid] focus-visible:outline-brand-200 focus-visible:outline-offset-2',
].join(' ');

const AGENT_BTN_ACTIVE = [
  'inline-flex items-center shrink-0',
  'h-[36px] gap-2 px-3 rounded-lg border text-sm',
  BRAND_SELECTED_SURFACE,
  'cursor-pointer select-none transition-colors tfds-motion-ui-fast',
  BRAND_SELECTED_HOVER,
  'focus-visible:[outline:2px_solid] focus-visible:outline-brand-200 focus-visible:outline-offset-2',
].join(' ');

/* ── 发送按钮（三态：disabled / active / running） ──
 *  disabled  → 视觉对齐工具栏 IconButton（白底、border、muted 图标）
 *  active    → 视觉对齐 Button primary（黑底胶囊 + 文字 + 标准 hover/active）
 *  running   → 视觉对齐 Button primary（黑底方钮 + 停止图标）
 */
const SEND_BTN_BASE = [
  'inline-flex items-center justify-center shrink-0',
  'h-[36px] rounded-lg border cursor-pointer select-none',
  'transition-colors transition-transform tfds-motion-ui-fast',
  '[outline:2px_solid_transparent] outline-offset-2',
].join(' ');

/* 无内容：与工具栏 IconButton 同款（白底、border、muted 图标），不可点击 */
const SEND_DISABLED = [
  'w-[36px] bg-surface border-border-default',
  'text-foreground-muted',
  'cursor-not-allowed opacity-60',
].join(' ');

/* 有内容：primary 胶囊 + 文字 */
const SEND_ACTIVE = [
  'gap-1.5 px-3 bg-grey-950 text-white border-transparent',
  '[font-weight:var(--font-semibold)]',
  'hover:bg-grey-900',
  'active:bg-grey-800 active:scale-[0.97]',
  'focus-visible:outline-grey-400',
].join(' ');

/* 运行中：primary 方钮 + 停止图标 */
const SEND_RUNNING = [
  'w-[36px] bg-grey-950 text-white border-transparent',
  'hover:bg-grey-900',
  'active:bg-grey-800 active:scale-[0.97]',
  'focus-visible:outline-grey-400',
].join(' ');

/* ── 收起单行布局 ── */
const COLLAPSED = 'flex items-center gap-3';

/* ── 展开多行布局 ── */
const EXPANDED = 'flex flex-col items-start gap-3';

/* ── 操作行 ── */
const TOOLBAR_ROW = 'flex items-center gap-3 w-full';

/* ── 占位文字 ── */
const PLACEHOLDER_CLS = [
  'flex-1 min-w-0 m-0 px-[2px]',
  'text-left text-sm leading-[26px] font-normal',
  'text-foreground-disabled select-none',
].join(' ');

/* ── 富文本编辑区（contentEditable）：支持 chip 与文字混排
 *  - text-sm 14px
 *  - leading-[30px] = 26 文字行高 + 4 行间距，与 chip h-26 配合得到行间距 4px
 *  - max-h-[300px] + overflow-y-auto：超长文本内部滚动
 *  - whitespace-pre-wrap：保留换行 + 自动折行
 */
const EDITOR_CLS = [
  'w-full outline-none border-0 bg-transparent',
  'text-left text-sm leading-[30px] font-normal text-foreground',
  'min-h-[26px] max-h-[300px] overflow-y-auto',
  'px-[2px] [font-family:inherit] whitespace-pre-wrap break-words',
].join(' ');

/* 占位符：编辑器为空时悬浮显示，不参与点击 */
const PLACEHOLDER_OVERLAY = [
  'absolute left-[2px] top-0 pointer-events-none select-none',
  'text-left text-sm leading-[30px] font-normal text-foreground-disabled',
].join(' ');

/* ── 单行文本插槽（回复中等态使用，高度与 default 编辑器空态对齐：30px = leading-[30px]） ── */
const SINGLE_LINE_SLOT = 'w-full min-h-[30px] flex items-center px-[2px] text-left';

/* ── 状态提示文字 ── */
const STATUS_TEXT_CLS = [
  'flex-1 min-w-0 m-0',
  'text-left text-sm leading-6 font-normal text-foreground',
].join(' ');

/* ── 内置示例数据：用户未传 props 时使用，便于演示 ── */
const DEFAULT_AGENT_OPTIONS = [
  { id: 'auto',          label: 'Auto',           desc: '自动选择最合适的模型' },
  { id: 'gpt-4o',        label: 'GPT-4o',         desc: '通用强项，速度快' },
  { id: 'claude-sonnet', label: 'Claude Sonnet 4', desc: '推理与代码能力强' },
  { id: 'gemini-2-5',    label: 'Gemini 2.5',     desc: '长上下文场景' },
  { id: 'doubao',        label: '豆包 Pro',        desc: '中文场景优化' },
];

const DEFAULT_MENTION_OPTIONS = [
  { id: 'm1', label: '节点：如何取消实名认证Agent', icon: 'git-branch-01-stroked' },
  { id: 'm2', label: '节点：意图分流',              icon: 'git-branch-01-stroked' },
  { id: 'm3', label: '知识：社交-私信',             icon: 'book-open-01-stroked' },
  { id: 'm4', label: '会话：社交-私信冲人工 v8',     icon: 'message-chat-square-stroked' },
  { id: 'm5', label: '报告：近 7 天指标异常分析',    icon: 'file-01-stroked' },
];

const DEFAULT_COMMAND_OPTIONS = [
  { id: 'c1', label: '选择服务标签', icon: 'tag-03-stroked' },
  { id: 'c2', label: '输入需求',     icon: 'brackets-check-stroked' },
  { id: 'c3', label: '总结对话',     icon: 'ai-divider' },
  { id: 'c4', label: '生成报告',     icon: 'file-01-stroked' },
];

const DEFAULT_IM_ACTIONS = [
  { id: 'image', icon: 'image-01-stroked', ariaLabel: '图片' },
  { id: 'emoji', icon: 'face-smile-stroked', ariaLabel: '表情' },
];

/* ── Chip：已选 Mention / Command 的展示样式（参考 Figma：浅青底 + 浅青边）
 *  布局对齐：
 *   - align-middle：baseline + x-height/2 居中（浏览器原生算法，与文字几何中心几乎重合）
 *     ⚠️ 不使用 position:relative + top 或正向 vertical-align —— 它们会在 contentEditable
 *     中引起 chip 行起始 X 缩进、或 chip 顶部超出 line-box
 *   - 不加外部 margin：chip 起始位置严格与纯文本行对齐；chip 与文字间距由 chip 自身 px-2
 *     的 8px 内边距提供视觉呼吸（足够清晰，不会显得粘连）
 *   - gap-1：chip 内部 icon-文字-X 间距 4px
 *   - leading-[26px]：chip 内文字行高与 chip 同高，内容自然垂直居中
 *   - rounded-md：圆角 8px（b-end token: md=8 / lg=12，Figma 要的是 8）
 */
const ENTITY_CHIP = [
  'inline-flex items-center gap-1 shrink-0 align-middle',
  'h-[26px] px-2 rounded-md border',
  BRAND_SELECTED_SURFACE,
  'text-sm leading-[26px]',
].join(' ');

/* ── 附件卡：参考 Figma 180px 文件卡
 *  group：让内部按钮根据卡片 hover 切换显示
 *  hover 整卡背景加深；同时左侧文件图标变成"删除 X"
 */
const ATTACH_CARD = [
  'group inline-flex items-center gap-2 shrink-0',
  'w-[180px] max-w-[180px] p-2 rounded-lg',
  'bg-fill border border-border-default transition-colors tfds-motion-ui-fast',
  'hover:bg-blueGrey-100',
].join(' ');

/* ── 文件大小格式化 ── */
function formatFileSize(bytes) {
  if (bytes == null || isNaN(bytes)) return '';
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
  return `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`;
}

/* ── 猫条默认文案映射 ── */
const DEFAULT_CAT_TEXT = {
  'default-sm': 'Hi~ 我是 AI 小助手，快来试试和我交流吧~',
  'default':    'Hi~ 我是 AI 小助手，快来试试和我交流吧~',
  'replying':   '回复中...',
  'busy':       '正在查询数据接口「execute_agent/API/interface/Function call Name」',
  'readonly':   '🎉 任务已完成~',
};

/* ── 发送按钮：disabled / active / running 三态 ──
 *  统一加 onMouseDown preventDefault：阻止按钮抢焦点，textarea 保持 focus-within，光晕不会闪烁
 */
const keepFocus = (e) => e.preventDefault();

function SendButton({ mode = 'disabled', onClick, label = '发送', ariaLabel }) {
  if (mode === 'running') {
    return (
      <button
        type="button"
        className={`${SEND_BTN_BASE} ${SEND_RUNNING}`}
        onMouseDown={keepFocus}
        onClick={onClick}
        aria-label={ariaLabel || '停止'}
        data-tfds-component="ChatInput.Send"
      >
        <Icon name="square-stroked" size="sm" color="currentColor" />
      </button>
    );
  }
  if (mode === 'active') {
    return (
      <button
        type="button"
        className={`${SEND_BTN_BASE} ${SEND_ACTIVE}`}
        onMouseDown={keepFocus}
        onClick={onClick}
        aria-label={ariaLabel || label}
        data-tfds-component="ChatInput.Send"
      >
        <Icon name="send-03-stroked" size="sm" color="currentColor" />
        <span className="text-sm whitespace-nowrap">{label}</span>
      </button>
    );
  }
  return (
    <button
      type="button"
      className={`${SEND_BTN_BASE} ${SEND_DISABLED}`}
      onMouseDown={keepFocus}
      disabled
      aria-label={ariaLabel || label}
      data-tfds-component="ChatInput.Send"
    >
      <Icon name="send-03-stroked" size="sm" color="currentColor" />
    </button>
  );
}

/* ── 猫条头像：始终眨眼，营造活生生的角色感 ──
 *  眨眼原理：
 *  - 身体用 evenodd 在眼睛位置挖洞（眼眶透明，露出背景作"眼白"）
 *  - 在洞内放黑色小圆点作瞳孔
 *  - 叠一层与身体同色的椭圆"眼皮"，默认 scaleY(0) 不可见
 *  - 眨眼时眼皮从顶部展开到 scaleY(1)，盖住整个眼眶 = 闭眼
 *  - transform-origin 用 SVG 用户坐标系的明确像素值，跨浏览器稳定
 */
function CatAvatar() {
  return (
    <div className="shrink-0" aria-hidden="true">
      <svg width="25" height="32" viewBox="0 0 25 32" fill="none" xmlns="http://www.w3.org/2000/svg">
        {/* 瞳孔 */}
        <path d="M17.5 9.8773C16.727 9.8773 16.0999 10.5048 16.0996 11.2777C16.0996 12.0509 16.7268 12.6781 17.5 12.6781C18.2732 12.6781 18.9004 12.0509 18.9004 11.2777C18.9001 10.5048 18.273 9.8773 17.5 9.8773Z" fill="currentColor"/>
        <path d="M7.5 9.8773C6.72699 9.8773 6.09992 10.5048 6.09961 11.2777C6.09961 12.0509 6.7268 12.6781 7.5 12.6781C8.2732 12.6781 8.90039 12.0509 8.90039 11.2777C8.90008 10.5048 8.27301 9.8773 7.5 9.8773Z" fill="currentColor"/>
        {/* 身体（evenodd 在眼睛位置挖洞） */}
        <path fillRule="evenodd" clipRule="evenodd" d="M1.49609 0.133156C0.829529 -0.247634 0.000182045 0.233686 0 1.00132V31.2777H25V1.00132C24.9998 0.233686 24.1705 -0.247634 23.5039 0.133156L18 3.27769H7L1.49609 0.133156ZM17.5 8.67808C18.9357 8.67808 20.0993 9.84201 20.0996 11.2777C20.0996 12.7136 18.9359 13.8773 17.5 13.8773C16.0641 13.8773 14.9004 12.7136 14.9004 11.2777C14.9007 9.84201 16.0643 8.67808 17.5 8.67808ZM7.5 8.67808C8.93575 8.67808 10.0993 9.84201 10.0996 11.2777C10.0996 12.7136 8.93594 13.8773 7.5 13.8773C6.06406 13.8773 4.90039 12.7136 4.90039 11.2777C4.9007 9.84201 6.06425 8.67808 7.5 8.67808Z" fill="currentColor"/>
        {/* 眼皮：始终循环眨眼 */}
        <ellipse cx="17.5" cy="11.277" rx="2.65" ry="2.65" fill="currentColor" className="tfds-cat-eyelid tfds-cat-eyelid--right"/>
        <ellipse cx="7.5"  cy="11.277" rx="2.65" ry="2.65" fill="currentColor" className="tfds-cat-eyelid tfds-cat-eyelid--left"/>
      </svg>
    </div>
  );
}

/* ── 工具栏下拉：复用 Dropdown 基础组件，向上展开 ── */
function ToolbarMenuDropdown({
  menuKey,
  openMenu,
  setOpenMenu,
  selectedId,
  items = [],
  emptyText = '暂无可选项',
  onPick,
  selectionIndicator = 'none',
  showDesc = false,
  showIcon = false,
  trigger,
}) {
  const isOpen = openMenu === menuKey;
  const dropdownItems = useMemo(
    () => items.map((item) => ({
      id: item.id,
      value: item.id,
      label: item.label,
      desc: item.desc,
      iconName: item.icon,
    })),
    [items],
  );

  return (
    <Dropdown
      className="inline-flex"
      open={isOpen}
      onOpenChange={(next) => setOpenMenu(next ? menuKey : null)}
      placement="top"
      gap={8}
      selectionIndicator={selectionIndicator}
      showIcon={showIcon}
      showDesc={showDesc}
      selectedValue={selectedId}
      matchTriggerWidth={false}
      minWidth={240}
      style={{ maxWidth: 320 }}
      emptyText={emptyText}
      items={dropdownItems}
      onItemSelect={(item) => {
        const picked = items.find((it) => it.id === item.id) || item;
        onPick?.(picked);
      }}
      trigger={trigger}
    />
  );
}

/* ── 已选实体 chip：浅青底，带图标 + 标签 + 关闭 X ── */
function EntityChip({ icon, label, onRemove }) {
  return (
    <span className={ENTITY_CHIP}>
      {icon && (
        <span className={`shrink-0 flex ${BRAND_SELECTED_ICON}`}>
          <Icon name={icon} size={14} color="currentColor" />
        </span>
      )}
      <span className="truncate max-w-[220px]">{label}</span>
      <button
        type="button"
        className="shrink-0 inline-flex items-center justify-center text-foreground-muted"
        onMouseDown={keepFocus}
        onClick={onRemove}
        aria-label="移除"
      >
        <Icon name="x-close-stroked" size={14} color="currentColor" />
      </button>
    </span>
  );
}

/* ── 附件卡：参考 Figma，180px，左图右文
 *  默认：左侧显示文件类型图标（彩色）
 *  hover：左侧整体切换为"删除 X"按钮（灰底方框 + X icon），右侧不再放独立 X
 *  彩色文件类型图标当前用 PDF 兜底，未来扩展见 FILE_TYPE_ICONS
 */
function AttachmentCard({ file, onRemove }) {
  const typeIcon = getFileTypeIcon(file.name);
  return (
    <span className={ATTACH_CARD}>
      <button
        type="button"
        className="shrink-0 relative w-8 h-[34px] inline-flex items-center justify-center cursor-pointer"
        onMouseDown={keepFocus}
        onClick={onRemove}
        aria-label="移除附件"
      >
        {/* 默认态：彩色文件图标 */}
        <img
          src={typeIcon}
          alt=""
          className="block w-8 h-[34px] object-contain group-hover:hidden"
        />
        {/* hover 态：灰底圆角 + X 图标，整块就是删除按钮 */}
        <span className="hidden group-hover:inline-flex items-center justify-center w-8 h-8 rounded-md bg-blueGrey-200 text-foreground-secondary">
          <Icon name="x-close-stroked" size="md" color="currentColor" />
        </span>
      </button>
      <span className="flex-1 min-w-0 flex flex-col gap-0.5">
        <span className="text-xs leading-4 text-foreground truncate" title={file.name}>{file.name}</span>
        <span className="text-[10px] leading-3 text-foreground-muted">{formatFileSize(file.size)}</span>
      </span>
    </span>
  );
}

const TOOLBAR_ITEM_GAP = 8;
const TOOLBAR_MORE_BTN_WIDTH = 36;

/* 溢出子菜单锚点：与「更多」按钮同位，供隐藏项从 overflow 打开二级面板 */
function AnchoredDropdownTrigger({ anchorRef }) {
  const ref = useRef(null);

  useLayoutEffect(() => {
    const anchor = anchorRef?.current;
    const el = ref.current;
    if (!anchor || !el) return undefined;

    const sync = () => {
      const rect = anchor.getBoundingClientRect();
      el.style.cssText = [
        'position:fixed',
        `left:${rect.left}px`,
        `top:${rect.top}px`,
        `width:${rect.width}px`,
        `height:${rect.height}px`,
        'opacity:0',
        'pointer-events:none',
        'border:0',
        'padding:0',
        'background:transparent',
      ].join(';');
    };

    sync();
    const observer = new ResizeObserver(sync);
    observer.observe(anchor);
    window.addEventListener('scroll', sync, true);
    window.addEventListener('resize', sync);
    return () => {
      observer.disconnect();
      window.removeEventListener('scroll', sync, true);
      window.removeEventListener('resize', sync);
    };
  }, [anchorRef]);

  return <button ref={ref} type="button" tabIndex={-1} aria-hidden="true" />;
}

/* ── 工具栏宽度自适应：空间不足时右侧项收入「更多」，hover 展开标准 Dropdown 行 ── */
function ToolbarOverflowLayout({
  items,
  moreButtonRef,
  onHiddenIdsChange,
  onOverflowSubmenu,
}) {
  const containerRef = useRef(null);
  const measureRef = useRef(null);
  const moreBtnRef = useRef(null);
  const [visibleCount, setVisibleCount] = useState(items.length);
  const [overflowOpen, setOverflowOpen] = useState(false);

  const recompute = useCallback(() => {
    const container = containerRef.current;
    const measure = measureRef.current;
    if (!container || !measure) return;

    const available = container.getBoundingClientRect().width;
    const childEls = measure.querySelectorAll('[data-toolbar-measure-item]');
    if (!childEls.length) {
      setVisibleCount(0);
      return;
    }

    const widths = Array.from(childEls).map((el) => el.getBoundingClientRect().width);
    const gap = TOOLBAR_ITEM_GAP;
    const moreWidth = moreBtnRef.current?.getBoundingClientRect().width || TOOLBAR_MORE_BTN_WIDTH;
    const total = widths.reduce((sum, width) => sum + width, 0)
      + Math.max(0, widths.length - 1) * gap;

    if (total <= available) {
      setVisibleCount(widths.length);
      return;
    }

    for (let visible = widths.length - 1; visible >= 0; visible -= 1) {
      const hiddenCount = widths.length - visible;
      if (hiddenCount <= 0) continue;
      const visibleWidth = widths.slice(0, visible).reduce((sum, width) => sum + width, 0);
      const gapCount = visible > 0 ? visible : 0;
      const needed = visibleWidth + gapCount * gap + moreWidth;
      if (needed <= available) {
        setVisibleCount(visible);
        return;
      }
    }
    setVisibleCount(0);
  }, [items.length]);

  useLayoutEffect(() => {
    recompute();
  }, [items, recompute]);

  useEffect(() => {
    const container = containerRef.current;
    const measure = measureRef.current;
    if (!container) return undefined;
    const observer = new ResizeObserver(recompute);
    observer.observe(container);
    if (measure) observer.observe(measure);
    return () => observer.disconnect();
  }, [recompute]);

  useEffect(() => {
    if (visibleCount >= items.length) setOverflowOpen(false);
  }, [visibleCount, items.length]);

  useEffect(() => {
    if (moreButtonRef) moreButtonRef.current = moreBtnRef.current;
  }, [moreButtonRef, overflowOpen, visibleCount]);

  const visibleItems = useMemo(
    () => items.slice(0, visibleCount),
    [items, visibleCount],
  );
  const hiddenItems = useMemo(
    () => items.slice(visibleCount),
    [items, visibleCount],
  );
  const hiddenIdsKey = useMemo(
    () => hiddenItems.map((item) => item.id).join('|'),
    [hiddenItems],
  );

  useEffect(() => {
    if (!onHiddenIdsChange) return;
    const ids = hiddenIdsKey ? hiddenIdsKey.split('|') : [];
    onHiddenIdsChange(ids);
  }, [hiddenIdsKey, onHiddenIdsChange]);

  const overflowDropdownItems = useMemo(
    () => hiddenItems.map((item) => ({
      id: item.id,
      value: item.id,
      label: item.overflowLabel ?? item.id,
      iconName: item.overflowIconName,
      onClick: () => {
        setOverflowOpen(false);
        if (item.overflowMenuKey) {
          onOverflowSubmenu?.(item.overflowMenuKey);
        } else {
          item.onOverflowClick?.();
        }
      },
    })),
    [hiddenItems, onOverflowSubmenu],
  );

  return (
    <div ref={containerRef} className="relative flex flex-1 min-w-0">
      <div
        ref={measureRef}
        className="pointer-events-none fixed top-0 left-[-10000px] flex gap-2 opacity-0"
        aria-hidden="true"
      >
        {items.map((item) => (
          <div key={item.id} data-toolbar-measure-item className="inline-flex shrink-0">
            {item.measure ?? item.node}
          </div>
        ))}
        <button
          ref={moreBtnRef}
          type="button"
          tabIndex={-1}
          className={TOOL_ICON_BTN}
          aria-hidden="true"
        >
          <Icon name="dots-horizontal-stroked" size="sm" color="currentColor" />
        </button>
      </div>

      <div className="flex flex-1 min-w-0 items-center gap-2">
        {visibleItems.map((item) => (
          <div key={item.id} className="inline-flex shrink-0">
            {item.node}
          </div>
        ))}
        {hiddenItems.length > 0 ? (
          <Dropdown
            className="inline-flex shrink-0"
            open={overflowOpen}
            onOpenChange={setOverflowOpen}
            triggerMode="hover"
            hoverCloseDelay={150}
            placement="top"
            gap={8}
            mode="action"
            selectionIndicator="none"
            showIcon
            matchTriggerWidth={false}
            minWidth={168}
            items={overflowDropdownItems}
            panelClassName="tfds-chat-input-toolbar-overflow"
            trigger={(
              <button
                ref={moreBtnRef}
                type="button"
                className={TOOL_ICON_BTN}
                onMouseDown={keepFocus}
                aria-label="更多"
                title="更多"
                data-tfds-component="ChatInput.ToolbarMore"
              >
                <Icon name="dots-horizontal-stroked" size="sm" color="currentColor" />
              </button>
            )}
          />
        ) : null}
      </div>
    </div>
  );
}

/* ── 内置默认工具栏左侧功能按钮 ──
 *  compact = true 时（如 default-sm），Agent 按钮收缩为 36×36 图标钮，与其它工具栏按钮等宽
 *  内置浮层：Agent / @ / 指令；附件触发隐藏 file input
 *  宽度不足时右侧按钮自动收入「更多」下拉（hover 展开）
 */
function DefaultToolbarLeft({
  agentLabel,
  compact = false,
  agentOptions,
  mentionOptions,
  commandOptions,
  selectedAgentId,
  onPickAgent,
  onPickMention,
  onPickCommand,
  onAttachClick,
}) {
  const [openMenu, setOpenMenu] = useState(null);
  const [hiddenToolbarIds, setHiddenToolbarIds] = useState([]);
  const moreButtonRef = useRef(null);

  /* Agent 默认态识别：第一项视为"默认/Auto"，其它都按"已选具体模型"显示绿色高亮 */
  const isAutoAgent = !selectedAgentId || selectedAgentId === agentOptions?.[0]?.id;

  const handlePick = (kind) => (item) => {
    if (kind === 'agent') onPickAgent?.(item);
    if (kind === 'mention') onPickMention?.(item);
    if (kind === 'command') onPickCommand?.(item);
    setOpenMenu(null);
  };

  const agentHasDesc = agentOptions?.some((item) => item.desc);
  const agentHasIcon = agentOptions?.some((item) => item.icon);
  const mentionHasIcon = mentionOptions?.some((item) => item.icon);
  const commandHasIcon = commandOptions?.some((item) => item.icon);

  const renderAgentTrigger = () => (compact ? (
    <button
      type="button"
      className={TOOL_ICON_BTN}
      onMouseDown={keepFocus}
      aria-label={`Agent：${agentLabel}`}
      data-tfds-component="ChatInput.Agent"
    >
      <Icon name="bot-01-stroked" size="sm" color="currentColor" />
    </button>
  ) : (
    <button
      type="button"
      className={isAutoAgent ? AGENT_BTN : AGENT_BTN_ACTIVE}
      onMouseDown={keepFocus}
      aria-label="选择 Agent"
      data-tfds-component="ChatInput.Agent"
    >
      <span className={`shrink-0 flex ${isAutoAgent ? 'text-foreground-muted' : BRAND_SELECTED_ICON}`}>
        <Icon name="bot-01-stroked" size="sm" color="currentColor" />
      </span>
      <span className="whitespace-nowrap">{agentLabel}</span>
      <span className={`shrink-0 flex ${isAutoAgent ? 'text-foreground-muted' : BRAND_SELECTED_ICON}`}>
        <Icon name="chevron-down-stroked" size="sm" color="currentColor" />
      </span>
    </button>
  ));

  const renderMentionTrigger = () => (
    <button
      type="button"
      className={TOOL_ICON_BTN}
      onMouseDown={keepFocus}
      aria-label="@ 提及"
      data-tfds-component="ChatInput.Mention"
    >
      <Icon name="at-sign-stroked" size="sm" color="currentColor" />
    </button>
  );

  const renderCommandTrigger = () => (
    <button
      type="button"
      className={TOOL_ICON_BTN}
      onMouseDown={keepFocus}
      aria-label="指令"
      data-tfds-component="ChatInput.Command"
    >
      <Icon name="ai-divider" size="sm" color="currentColor" />
    </button>
  );

  const renderAttachTrigger = () => (
    <button
      type="button"
      className={TOOL_ICON_BTN}
      onMouseDown={keepFocus}
      onClick={onAttachClick}
      aria-label="附件"
      data-tfds-component="ChatInput.Attach"
    >
      <Icon name="paperclip-stroked" size="sm" color="currentColor" />
    </button>
  );

  const toolbarItems = useMemo(() => [
    {
      id: 'agent',
      measure: renderAgentTrigger(),
      overflowLabel: compact ? 'Agent' : agentLabel,
      overflowIconName: 'bot-01-stroked',
      overflowMenuKey: 'agent',
      node: (
        <ToolbarMenuDropdown
          menuKey="agent"
          openMenu={openMenu}
          setOpenMenu={setOpenMenu}
          selectedId={selectedAgentId}
          items={agentOptions}
          onPick={handlePick('agent')}
          selectionIndicator="leading-check"
          showDesc={agentHasDesc}
          showIcon={agentHasIcon}
          trigger={renderAgentTrigger()}
        />
      ),
    },
    {
      id: 'mention',
      measure: renderMentionTrigger(),
      overflowLabel: '@ 提及',
      overflowIconName: 'at-sign-stroked',
      overflowMenuKey: 'mention',
      node: (
        <ToolbarMenuDropdown
          menuKey="mention"
          openMenu={openMenu}
          setOpenMenu={setOpenMenu}
          items={mentionOptions}
          emptyText="暂无可选实体"
          onPick={handlePick('mention')}
          showIcon={mentionHasIcon}
          trigger={renderMentionTrigger()}
        />
      ),
    },
    {
      id: 'command',
      measure: renderCommandTrigger(),
      overflowLabel: '指令',
      overflowIconName: 'ai-divider',
      overflowMenuKey: 'command',
      node: (
        <ToolbarMenuDropdown
          menuKey="command"
          openMenu={openMenu}
          setOpenMenu={setOpenMenu}
          items={commandOptions}
          emptyText="暂无可用指令"
          onPick={handlePick('command')}
          showIcon={commandHasIcon}
          trigger={renderCommandTrigger()}
        />
      ),
    },
    {
      id: 'attach',
      measure: renderAttachTrigger(),
      overflowLabel: '附件',
      overflowIconName: 'paperclip-stroked',
      onOverflowClick: onAttachClick,
      node: renderAttachTrigger(),
    },
  ], [
    agentHasDesc,
    agentHasIcon,
    agentLabel,
    agentOptions,
    commandHasIcon,
    commandOptions,
    compact,
    isAutoAgent,
    mentionHasIcon,
    mentionOptions,
    onAttachClick,
    openMenu,
    selectedAgentId,
  ]);

  const handleOverflowSubmenu = useCallback((menuKey) => {
    setOpenMenu(menuKey);
  }, []);

  const handleHiddenIdsChange = useCallback((ids) => {
    setHiddenToolbarIds((prev) => {
      if (prev.length === ids.length && prev.every((id, index) => id === ids[index])) {
        return prev;
      }
      return ids;
    });
  }, []);

  return (
    <>
      <ToolbarOverflowLayout
        items={toolbarItems}
        moreButtonRef={moreButtonRef}
        onHiddenIdsChange={handleHiddenIdsChange}
        onOverflowSubmenu={handleOverflowSubmenu}
      />
      {hiddenToolbarIds.includes('agent') && openMenu === 'agent' ? (
        <ToolbarMenuDropdown
          menuKey="agent"
          openMenu={openMenu}
          setOpenMenu={setOpenMenu}
          selectedId={selectedAgentId}
          items={agentOptions}
          onPick={handlePick('agent')}
          selectionIndicator="leading-check"
          showDesc={agentHasDesc}
          showIcon={agentHasIcon}
          trigger={<AnchoredDropdownTrigger anchorRef={moreButtonRef} />}
        />
      ) : null}
      {hiddenToolbarIds.includes('mention') && openMenu === 'mention' ? (
        <ToolbarMenuDropdown
          menuKey="mention"
          openMenu={openMenu}
          setOpenMenu={setOpenMenu}
          items={mentionOptions}
          emptyText="暂无可选实体"
          onPick={handlePick('mention')}
          showIcon={mentionHasIcon}
          trigger={<AnchoredDropdownTrigger anchorRef={moreButtonRef} />}
        />
      ) : null}
      {hiddenToolbarIds.includes('command') && openMenu === 'command' ? (
        <ToolbarMenuDropdown
          menuKey="command"
          openMenu={openMenu}
          setOpenMenu={setOpenMenu}
          items={commandOptions}
          emptyText="暂无可用指令"
          onPick={handlePick('command')}
          showIcon={commandHasIcon}
          trigger={<AnchoredDropdownTrigger anchorRef={moreButtonRef} />}
        />
      ) : null}
    </>
  );
}

/* ── im-basic：左下角声明式按钮区（默认图片 + 表情，最多 5 个；宽度不足时收入「更多」） ── */
function ImBasicToolbarLeft({ actions = [] }) {
  const toolbarItems = useMemo(() => actions.map((action) => {
    const renderButton = () => (
      <button
        type="button"
        className={TOOL_ICON_BTN}
        onMouseDown={keepFocus}
        onClick={action.onClick}
        aria-label={action.ariaLabel}
        title={action.ariaLabel}
        data-tfds-component="ChatInput.ImAction"
      >
        <Icon name={action.icon} size="sm" color="currentColor" />
      </button>
    );
    return {
      id: action.id,
      measure: renderButton(),
      node: renderButton(),
      overflowLabel: action.ariaLabel,
      overflowIconName: action.icon,
      onOverflowClick: action.onClick,
    };
  }), [actions]);

  return <ToolbarOverflowLayout items={toolbarItems} />;
}

export default function ChatInput({
  variant = 'default',
  agentName = 'Auto',
  agentOptions = DEFAULT_AGENT_OPTIONS,
  mentionOptions = DEFAULT_MENTION_OPTIONS,
  commandOptions = DEFAULT_COMMAND_OPTIONS,
  acceptFiles = '*',
  multipleFiles = true,
  catBarText,
  catBarIcon,
  placeholder = '需要我为你做什么',
  statusText,
  actionText,
  onSend,
  onStop,
  onAction,
  onAgentChange,
  onMentionsChange,
  onCommandsChange,
  onAttachmentsChange,
  toolbar,
  children,
  className = '',
  style,
  /* 仅供平台预览页使用：true 时挂载后自动注入示例 mention/command/附件，方便看"已选内容"样式 */
  _seedContent = false,
  /* 状态机受控：默认 true 保留旧行为；传 false 让外部 variant 完全决定状态切换 */
  autoReplyOnSend = true,
  imActions,
  /* im-basic：可选覆盖左下「图片 / 表情」默认行为 */
  onImImageClick,
  onImEmojiClick,
  /* 草稿回填：每次 prefillSeed 变化时把 prefillText 覆盖塞进编辑器并聚焦 */
  prefillText = '',
  prefillSeed = 0,
}) {
  const [view, setView] = useState(() => (variant === 'im-basic' ? 'default' : variant));
  /* 编辑器的"是否为空"态：决定占位符显示 + 发送按钮可点 */
  const [isEditorEmpty, setIsEditorEmpty] = useState(true);
  /* 内置选中态：Agent 单选 + 附件多选；mention/command chip 直接活在 contentEditable DOM 里，不进 React state */
  const initAgent = agentOptions.find((o) => o.label === agentName) || agentOptions[0] || { id: 'auto', label: agentName };
  const [selectedAgent, setSelectedAgent] = useState(initAgent);
  const [attachments, setAttachments] = useState([]);

  const editorRef = useRef(null);
  const fileInputRef = useRef(null);
  /* 最外层 wrapper：用于"焦点离开组件 + 内容为空时收起"判断 */
  const rootRef = useRef(null);
  /* chip 的 React Root 实例字典：chip wrapper DOM → root，方便卸载时 unmount */
  const chipRootsRef = useRef(new Map());
  /* 最近一次编辑器内的 selection range，用于在浮层关闭后恢复光标 */
  const savedRangeRef = useRef(null);

  useEffect(() => {
    setView(variant === 'im-basic' ? 'default' : variant);
    /* variant 切换时清空编辑器 */
    if (editorRef.current) {
      chipRootsRef.current.forEach((root) => root.unmount());
      chipRootsRef.current.clear();
      editorRef.current.innerHTML = '';
    }
    setIsEditorEmpty(true);
  }, [variant]);

  /* 焦点离开整个 ChatInput + 编辑器为空 + 无附件 → 自动收起到 default-sm
   *  ⚠️ 仅当 variant === 'default-sm' 时启用（即"小→展开→输入→缩回"场景）
   *  variant === 'default' 是常驻展开场景，不应被该逻辑干扰
   *  其它态（busy / readonly / replying）也不参与
   */
  useEffect(() => {
    if (variant !== 'default-sm') return;
    if (view !== 'default') return;
    const collapseIfEmpty = () => {
      if (!rootRef.current) return;
      if (rootRef.current.contains(document.activeElement)) return;
      if (!isEditorEmpty) return;
      if (attachments.length > 0) return;
      setView('default-sm');
    };
    const onFocusIn = () => { setTimeout(collapseIfEmpty, 0); };
    const onMouseDown = (e) => {
      if (rootRef.current && rootRef.current.contains(e.target)) return;
      setTimeout(collapseIfEmpty, 0);
    };
    document.addEventListener('focusin', onFocusIn);
    document.addEventListener('mousedown', onMouseDown);
    return () => {
      document.removeEventListener('focusin', onFocusIn);
      document.removeEventListener('mousedown', onMouseDown);
    };
  }, [variant, view, isEditorEmpty, attachments.length]);

  /* 卸载时清掉所有 chip 的 React root，防止内存泄漏 */
  useEffect(() => () => {
    chipRootsRef.current.forEach((root) => root.unmount());
    chipRootsRef.current.clear();
  }, []);

  /* 草稿回填：每次 prefillSeed 变化时把 prefillText 覆盖塞进编辑器并聚焦
   * 用途：推荐 chip / 追问 chip 点击时把文案写入输入框，等用户主动点发送 */
  useEffect(() => {
    if (prefillSeed <= 0) return;
    if (view !== 'default') return;
    const el = editorRef.current;
    if (!el) return;
    /* 先清掉所有 chip root，再覆盖文本 */
    chipRootsRef.current.forEach((root) => root.unmount());
    chipRootsRef.current.clear();
    el.innerHTML = '';
    el.appendChild(document.createTextNode(prefillText || ''));
    setIsEditorEmpty(!(prefillText || '').trim());
    /* 聚焦并把光标放到末尾 */
    el.focus();
    const range = document.createRange();
    range.selectNodeContents(el);
    range.collapse(false);
    const sel = window.getSelection();
    sel?.removeAllRanges();
    sel?.addRange(range);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [prefillSeed]);

  const resolvedCatText = catBarText || DEFAULT_CAT_TEXT[view] || '';

  /* ── 编辑器空态检测：有文字 or 有 chip 都算非空 ── */
  const refreshEmpty = useCallback(() => {
    const el = editorRef.current;
    if (!el) {
      setIsEditorEmpty(true);
      return;
    }
    const hasText = (el.innerText || '').replace(/\u00a0/g, ' ').trim().length > 0;
    const hasChip = el.querySelector('[data-chip="1"]') != null;
    setIsEditorEmpty(!hasText && !hasChip);
  }, []);

  /* ── 收集编辑器当前内容（用于 onSend 回调） ──
   * 返回值：
   *   · text     纯文本拼接（兼容旧调用方），chip label 也会被算进去
   *   · segments 按 DOM 顺序排好的 token 列表 [{type:'text',value} | {type:'entity',kind,icon,label,id}]
   *              ↳ 直接对接 ChatMessage.userContent，保留 chip 与文字混排结构
   *   · mentions / commands 分类后的 chip 列表（兼容旧调用方）
   */
  const collectContext = useCallback(() => {
    const el = editorRef.current;
    if (!el) return { text: '', segments: [], mentions: [], commands: [] };

    /* 深度优先遍历编辑器，按 DOM 顺序产出 segments */
    const segments = [];
    const pushText = (val) => {
      if (!val) return;
      const last = segments[segments.length - 1];
      if (last && last.type === 'text') {
        last.value += val;
      } else {
        segments.push({ type: 'text', value: val });
      }
    };
    const walk = (node) => {
      if (node.nodeType === Node.TEXT_NODE) {
        pushText((node.textContent || '').replace(/\u00a0/g, ' '));
        return;
      }
      if (node.nodeType !== Node.ELEMENT_NODE) return;
      /* chip wrapper：data-chip="1" → 当作 entity token，停止下钻 */
      if (node.getAttribute && node.getAttribute('data-chip') === '1') {
        const kind = node.getAttribute('data-kind') || 'mention';
        segments.push({
          type: 'entity',
          kind,
          id: node.getAttribute('data-id') || undefined,
          icon: node.getAttribute('data-icon') || undefined,
          label: node.getAttribute('data-label') || '',
        });
        return;
      }
      /* 块级换行（div / br）→ 补一个换行符 */
      const tag = node.tagName;
      if (tag === 'BR') {
        pushText('\n');
        return;
      }
      const isBlock = tag === 'DIV' || tag === 'P';
      if (isBlock && segments.length > 0) pushText('\n');
      node.childNodes.forEach(walk);
    };
    el.childNodes.forEach(walk);

    /* segments 收尾：去掉首尾空白文本 token；空 text 段落丢弃 */
    while (segments.length && segments[0].type === 'text' && !segments[0].value.trim()) segments.shift();
    while (segments.length && segments[segments.length - 1].type === 'text' && !segments[segments.length - 1].value.trim()) segments.pop();

    const chips = segments
      .filter((s) => s.type === 'entity')
      .map(({ kind, id, label, icon }) => ({ kind, id, label, icon }));

    return {
      text: (el.innerText || '').replace(/\u00a0/g, ' ').trim(),
      segments,
      mentions: chips.filter((c) => c.kind === 'mention'),
      commands: chips.filter((c) => c.kind === 'command'),
    };
  }, []);

  /* ── 保存 / 恢复编辑器光标位置 ── */
  const saveSelection = useCallback(() => {
    const sel = typeof window !== 'undefined' ? window.getSelection() : null;
    if (!sel || !sel.rangeCount) return;
    const range = sel.getRangeAt(0);
    const el = editorRef.current;
    if (el && el.contains(range.commonAncestorContainer)) {
      savedRangeRef.current = range.cloneRange();
    }
  }, []);

  const restoreSelectionToEnd = useCallback(() => {
    const el = editorRef.current;
    if (!el) return null;
    const sel = window.getSelection();
    sel.removeAllRanges();
    if (savedRangeRef.current && el.contains(savedRangeRef.current.commonAncestorContainer)) {
      sel.addRange(savedRangeRef.current);
      return savedRangeRef.current;
    }
    const range = document.createRange();
    range.selectNodeContents(el);
    range.collapse(false);
    sel.addRange(range);
    return range;
  }, []);

  /* ── 在光标位置插入 chip（核心：富文本混排关键能力） ──
   *  - 用 createRoot 把 React EntityChip 渲染进一个 contentEditable=false 的 wrapper span
   *  - wrapper 上挂 data-* 标记，方便后续提取
   *  - chip 前后按需插入 NBSP：
   *      · 后置 NBSP 总是加 → 让光标可以落在 chip 后继续输入
   *      · 前置 NBSP 仅在光标前一个字符非空白时加 → 让 chip 与前面已有文字保持 4px 视觉间距，
   *        避免编辑器开头/换行后的多余缩进
   */
  const insertChip = useCallback((kind, item) => {
    const el = editorRef.current;
    if (!el) return;
    el.focus();

    const wrapper = document.createElement('span');
    wrapper.setAttribute('data-chip', '1');
    wrapper.setAttribute('data-kind', kind);
    wrapper.setAttribute('data-id', String(item.id));
    wrapper.setAttribute('data-label', item.label);
    if (item.icon) wrapper.setAttribute('data-icon', item.icon);
    wrapper.contentEditable = 'false';
    wrapper.style.userSelect = 'none';

    const range = restoreSelectionToEnd();
    const spaceAfter = document.createTextNode('\u00a0');

    if (range) {
      /* 判断是否需要前置空格：光标前是文本且最后一个字符不是空白 → 需要补 */
      let needSpaceBefore = false;
      const sc = range.startContainer;
      if (sc.nodeType === Node.TEXT_NODE && range.startOffset > 0) {
        const prev = sc.textContent[range.startOffset - 1];
        if (prev && prev !== '\u00a0' && prev !== ' ' && prev !== '\n') needSpaceBefore = true;
      } else if (sc.nodeType === Node.ELEMENT_NODE && range.startOffset > 0) {
        /* 光标紧跟在某个非文本节点之后（如另一个 chip wrapper），也补一个空格 */
        const prevNode = sc.childNodes[range.startOffset - 1];
        if (prevNode && prevNode.nodeType === Node.ELEMENT_NODE) needSpaceBefore = true;
      }

      range.collapse(false);
      range.insertNode(spaceAfter);
      range.insertNode(wrapper);
      if (needSpaceBefore) {
        range.insertNode(document.createTextNode('\u00a0'));
      }
      range.setStartAfter(spaceAfter);
      range.collapse(true);
      const sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
      savedRangeRef.current = range.cloneRange();
    } else {
      el.appendChild(wrapper);
      el.appendChild(spaceAfter);
    }

    /* 用 React 渲染 chip 内容到 wrapper：复用 EntityChip 组件 */
    const root = createRoot(wrapper);
    chipRootsRef.current.set(wrapper, root);
    const handleChipRemove = () => {
      const r = chipRootsRef.current.get(wrapper);
      if (r) {
        r.unmount();
        chipRootsRef.current.delete(wrapper);
      }
      const next = wrapper.nextSibling;
      if (next && next.nodeType === Node.TEXT_NODE && next.textContent === '\u00a0') {
        next.parentNode.removeChild(next);
      }
      if (wrapper.parentNode) wrapper.parentNode.removeChild(wrapper);
      refreshEmpty();
      editorRef.current?.focus();
    };
    root.render(<EntityChip icon={item.icon} label={item.label} onRemove={handleChipRemove} />);

    refreshEmpty();
  }, [restoreSelectionToEnd, refreshEmpty]);

  /* ── 交互处理 ── */
  const handleExpand = useCallback(() => {
    setView('default');
    requestAnimationFrame(() => editorRef.current?.focus());
  }, []);

  /* ── 容器级聚焦热区：点击整个 ChatInput 的非交互空白区都会聚焦到编辑器
   * · 仅 default 态生效（其他态没有可输入区）
   * · 排除真正的交互元素：button / a / input / select / textarea / [role=button]
   *   / 编辑器内 chip wrapper / 自定义 [data-no-focus]
   * · 排除编辑器自身：让原生光标定位逻辑接管（点哪个字光标就在哪）
   * · 用 mousedown + preventDefault 阻止默认聚焦切换，再手动 focus 编辑器并把光标置末尾 */
  const handleContainerMouseDown = useCallback((e) => {
    /* 直接读 view（在本函数下方才声明 isDefault，避免 TDZ ReferenceError） */
    if (view !== 'default') return;
    const target = e.target;
    if (!(target instanceof Element)) return;
    const editor = editorRef.current;
    if (editor && editor.contains(target)) return;
    if (target.closest('button, a, input, select, textarea, [role="button"], [data-chip="1"], [data-no-focus="1"]')) return;
    e.preventDefault();
    if (!editor) return;
    editor.focus();
    const range = document.createRange();
    range.selectNodeContents(editor);
    range.collapse(false);
    const sel = window.getSelection();
    sel?.removeAllRanges();
    sel?.addRange(range);
  }, [view]);

  /* default-sm 下选了工具栏功能项后，自动展开为 default 态（已有内容已经在 editor / state 里） */
  const expandIfCollapsed = useCallback(() => {
    setView((prev) => (prev === 'default-sm' ? 'default' : prev));
  }, []);

  const handleSend = useCallback(() => {
    const ctx = collectContext();
    const hasAtt = attachments.length > 0;
    const hasCtx = !!(ctx.text || ctx.mentions.length || ctx.commands.length);
    /* im-basic：允许仅选图片附件后发送（纯 IM） */
    if (!hasCtx && !(variant === 'im-basic' && hasAtt)) return;
    onSend?.(ctx.text, {
      agent: selectedAgent,
      segments: ctx.segments,
      mentions: ctx.mentions,
      commands: ctx.commands,
      attachments: attachments.map((a) => a.file),
    });
    /* 清空编辑器 */
    chipRootsRef.current.forEach((root) => root.unmount());
    chipRootsRef.current.clear();
    if (editorRef.current) editorRef.current.innerHTML = '';
    setIsEditorEmpty(true);
    if (variant === 'im-basic' && hasAtt) {
      setAttachments([]);
      onAttachmentsChange?.([]);
    }
    /* autoReplyOnSend=true（默认）→ 内部自动跳 replying；im-basic 永不进入 AI 回复态 */
    if (autoReplyOnSend && variant !== 'im-basic') setView('replying');
  }, [collectContext, onSend, selectedAgent, attachments, autoReplyOnSend, variant, onAttachmentsChange]);

  /* ── 工具栏选择回调（选中后若处于 default-sm，自动展开为 default 并带入选中值） ── */
  const handlePickAgent = useCallback((item) => {
    setSelectedAgent(item);
    onAgentChange?.(item);
    expandIfCollapsed();
  }, [onAgentChange, expandIfCollapsed]);

  const handlePickMention = useCallback((item) => {
    expandIfCollapsed();
    /* 等下一帧 default 态的 editor 挂载完，再插 chip，否则插不到目标 DOM */
    requestAnimationFrame(() => {
      insertChip('mention', item);
      onMentionsChange?.(collectContext().mentions);
    });
  }, [insertChip, collectContext, onMentionsChange, expandIfCollapsed]);

  const handlePickCommand = useCallback((item) => {
    expandIfCollapsed();
    requestAnimationFrame(() => {
      insertChip('command', item);
      onCommandsChange?.(collectContext().commands);
    });
  }, [insertChip, collectContext, onCommandsChange, expandIfCollapsed]);

  const handleAttachClick = useCallback(() => {
    fileInputRef.current?.click();
  }, []);

  const handleFileChange = useCallback((e) => {
    const files = Array.from(e.target.files || []);
    if (!files.length) return;
    setAttachments((prev) => {
      const next = [...prev, ...files.map((f) => ({ file: f, _key: `${f.name}-${f.size}-${Date.now()}-${Math.random()}` }))];
      onAttachmentsChange?.(next.map((x) => x.file));
      return next;
    });
    e.target.value = '';
    expandIfCollapsed();
  }, [onAttachmentsChange, expandIfCollapsed]);

  const handleRemoveAttachment = useCallback((key) => {
    setAttachments((prev) => {
      const next = prev.filter((it) => it._key !== key);
      onAttachmentsChange?.(next.map((x) => x.file));
      return next;
    });
  }, [onAttachmentsChange]);

  const handleStop = useCallback(() => {
    onStop?.();
    setView('default');
  }, [onStop]);

  const handleEditorKeyDown = useCallback((e) => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); }
  }, [handleSend]);

  const handleEditorInput = useCallback(() => {
    refreshEmpty();
    saveSelection();
  }, [refreshEmpty, saveSelection]);

  /* ── 视图判断 ── */
  const isCollapsed = view === 'default-sm';
  const isDefault   = view === 'default';
  const isReplying  = view === 'replying';
  const isBusy      = view === 'busy';
  const isReadonly  = view === 'readonly';
  const isImBasic   = variant === 'im-basic';

  const resolvedImActions = (
    Array.isArray(imActions)
      ? imActions
      : imActions === undefined
        ? DEFAULT_IM_ACTIONS
        : []
  )
    .slice(0, 5)
    .map((action) => {
      const id = String(action?.id || '');
      const icon = action?.icon || (id === 'image'
        ? 'image-01-stroked'
        : id === 'emoji'
          ? 'face-smile-stroked'
          : 'plus-stroked');
      const ariaLabel = action?.ariaLabel || action?.label || id || '快捷操作';
      const fallbackClick = id === 'image'
        ? (onImImageClick || handleAttachClick)
        : id === 'emoji'
          ? (onImEmojiClick || (() => {}))
          : (() => {});
      return {
        id: id || `im-action-${icon}`,
        icon,
        ariaLabel,
        onClick: action?.onClick || fallbackClick,
      };
    });

  /* 大状态（default + replying，双行结构）用 py-14；单行态（default-sm / busy / readonly）用 py-12 */
  const isLarge = isDefault || isReplying;

  /* 青紫光晕：默认态聚焦时点亮；忙碌态常驻 */
  const inputAreaCls = [
    INPUT_AREA_BASE,
    isLarge ? INPUT_PAD_LG : INPUT_PAD_SM,
    isDefault && FOCUS_SHADOW,
    isBusy && `${BUSY_BORDER} ${GLOW_SHADOW}`,
  ].filter(Boolean).join(' ');

  /* 忙碌态：渐变描边 + 淡彩内底，由 background + border-clip 合成 */
  const inputAreaStyle = isBusy ? { background: BUSY_BG } : undefined;

  /* ── 工具栏左侧（default-sm 收起态把 Agent 按钮收成图标钮） ── */
  const toolbarLeft = toolbar
    ? <div className="flex flex-1 min-w-0 items-center gap-2">{toolbar}</div>
    : isImBasic
      ? (
        <ImBasicToolbarLeft
          actions={resolvedImActions}
        />
      )
      : (
        <DefaultToolbarLeft
          agentLabel={selectedAgent.label}
          compact={isCollapsed}
          agentOptions={agentOptions}
          mentionOptions={mentionOptions}
          commandOptions={commandOptions}
          selectedAgentId={selectedAgent.id}
          onPickAgent={handlePickAgent}
          onPickMention={handlePickMention}
          onPickCommand={handlePickCommand}
          onAttachClick={handleAttachClick}
        />
      );

  /* ── 附件行（仅 default 态展示，独立于编辑器位于其上方） ── */
  const hasAttachments = attachments.length > 0;
  const showAttachments = isDefault && !toolbar && hasAttachments;

  const attachmentsBlock = showAttachments && (
    <div className="flex flex-wrap gap-2 w-full">
      {attachments.map((att) => (
        <AttachmentCard
          key={att._key}
          file={att.file}
          onRemove={() => handleRemoveAttachment(att._key)}
        />
      ))}
    </div>
  );

  /* ── 平台预览页 seed：挂载后注入示例 mention/command/附件，方便看"已选内容"样态
   *  仅 _seedContent=true 时生效；不影响业务接入
   */
  useEffect(() => {
    if (!_seedContent) return;
    /* 仅 default 系变体支持注入；其它变体（busy/readonly）由 mapProps 已自动跳过 */
    if (variant !== 'default' && variant !== 'default-sm' && variant !== 'replying' && variant !== 'im-basic') return;
    setView('default');
    const t = setTimeout(() => {
      const m = mentionOptions[0];
      const c = commandOptions[0];
      if (m) insertChip('mention', m);
      if (c) insertChip('command', c);
      setAttachments([
        { _key: 'demo-1', file: { name: '火花诊断（火花规则文档V3）.pdf', size: 379187, type: 'application/pdf' } },
      ]);
    }, 30);
    return () => clearTimeout(t);
    /* eslint-disable-next-line react-hooks/exhaustive-deps */
  }, [_seedContent, variant]);

  /* ── 隐藏文件选择器：附件按钮触发 ── */
  const hiddenFileInput = !toolbar && (
    <input
      ref={fileInputRef}
      type="file"
      hidden
      multiple={multipleFiles}
      accept={acceptFiles}
      onChange={handleFileChange}
    />
  );

  const wrapperCls = isImBasic ? WRAPPER_IM_BASIC : WRAPPER;
  const backdropCls = isImBasic ? BACKDROP_SYMMETRIC : BACKDROP;

  return (
    <div
      ref={rootRef}
      className={[wrapperCls, className].filter(Boolean).join(' ')}
      style={style}
      onMouseDown={handleContainerMouseDown}
      data-tfds-component="ChatInput"
    >

      {/* ── 猫条（im-basic 无 AI 场景，不展示） ── */}
      {!isImBasic && (
        <div className={CAT_BAR}>
          {catBarIcon
            ? <div className="flex items-center justify-center shrink-0">{catBarIcon}</div>
            : <CatAvatar />
          }
          <div className={CAT_BAR_TEXT}>
            <span className="flex-1 min-w-0 truncate">{resolvedCatText}</span>
          </div>
        </div>
      )}

      {/* ── 输入区域 ── */}
      <div className={inputAreaCls} style={inputAreaStyle} data-tfds-component="ChatInput.Surface">

        {/* 收起态：点击占位文字区域才展开；点工具栏 / 发送按钮区域走各自的浮层 / 文件选择 */}
        {isCollapsed && (
          <div
            className={`${COLLAPSED} cursor-text`}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => e.key === 'Enter' && handleExpand()}
            data-tfds-component="ChatInput.Collapsed"
          >
            <div className="flex flex-1 min-w-0 items-center gap-3" onClick={(e) => e.stopPropagation()}>
              {toolbarLeft}
            </div>
            <p
              className={`${PLACEHOLDER_CLS} cursor-text`}
              onClick={handleExpand}
            >
              {children || placeholder}
            </p>
            <span onClick={(e) => e.stopPropagation()}>
              <SendButton mode="disabled" />
            </span>
          </div>
        )}

        {/* 展开默认态：富文本 contentEditable 编辑器，chip 与文字混排 */}
        {isDefault && (
          <div className={EXPANDED}>
            {attachmentsBlock}
            <div className="w-full relative">
              {children || (
                <>
                  {isEditorEmpty && (
                    <span className={PLACEHOLDER_OVERLAY}>{placeholder}</span>
                  )}
                  <div
                    ref={editorRef}
                    className={EDITOR_CLS}
                    contentEditable
                    suppressContentEditableWarning
                    role="textbox"
                    aria-multiline="true"
                    aria-label={placeholder}
                    onInput={handleEditorInput}
                    onKeyDown={handleEditorKeyDown}
                    onKeyUp={saveSelection}
                    onMouseUp={saveSelection}
                    onBlur={saveSelection}
                    data-tfds-component="ChatInput.Editor"
                  />
                </>
              )}
            </div>
            <div className={TOOLBAR_ROW} data-tfds-component="ChatInput.Toolbar">
              {toolbarLeft}
              <SendButton
                mode={isEditorEmpty && !(isImBasic && attachments.length > 0) ? 'disabled' : 'active'}
                onClick={handleSend}
              />
            </div>
          </div>
        )}

        {/* 回复中：保持与默认态相同高度，仅文案换为状态提示 */}
        {isReplying && (
          <div className={EXPANDED}>
            <div className={SINGLE_LINE_SLOT}>
              <span className="text-sm leading-[30px] text-foreground-disabled select-none truncate">
                {statusText || placeholder}
              </span>
            </div>
            <div className={TOOLBAR_ROW}>
              {toolbarLeft}
              <SendButton mode="running" onClick={handleStop} />
            </div>
          </div>
        )}

        {/* 忙碌：执行中 / 排队中 — 渐变背景 + 状态文案 + 36×36 停止按钮 */}
        {isBusy && (
          <div className="flex items-center gap-3 w-full">
            <p className={STATUS_TEXT_CLS}>
              {statusText || '已耗时 3 min，运行结束后会通过飞书消息告知'}
            </p>
            <SendButton mode="running" onClick={handleStop} />
          </div>
        )}

        {/* 只读：分享预览 / 抢单引导 — 白底 + 状态文案 + md 文字按钮 */}
        {isReadonly && (
          <div className="flex items-center gap-3 w-full">
            <p className={STATUS_TEXT_CLS}>
              {statusText || '来自其他成员的任务分享，当前页面仅支持预览'}
            </p>
            <Button variant="primary" size="md" onClick={onAction} className="shrink-0">
              {actionText || '继续对话'}
            </Button>
          </div>
        )}

      </div>

      {/* ── 底层氛围背景 ── */}
      <div className={backdropCls} aria-hidden="true" />

      {/* ── 隐藏文件选择器（用内置工具栏时启用） ── */}
      {hiddenFileInput}
    </div>
  );
}
