import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import Avatar from './Avatar';
import AgentFamilyAvatar from './AgentFamilyAvatar';
import Button from './Button';
import Icon from './Icon';
import IconLoading from './IconLoading';
import Input from './Input';
import SplitButton from './SplitButton';
import Switch from './Switch';
import Tag from './Tag';
import Tooltip from './Tooltip';
import { getTeamMemberByName } from '../teamMembers';

const DEFAULT_CUSTOMER_AVATAR_SRC = getTeamMemberByName('段然')?.avatarSrc || null;

const ROOT = 'tfds-agent-status-bar relative flex w-full min-w-0 flex-col gap-2 overflow-hidden rounded-[16px] p-[7px] shadow-[0_0_30px_0_rgba(101,115,137,0.07)]';
const ROOT_EXPANDED_BG = 'bg-[linear-gradient(180deg,#f7f8f9_0%,var(--color-blueGrey-50,#f2f4f7)_100%)]';
const ROOT_COLLAPSED_BG = 'bg-blueGrey-200';
const ROOT_BORDER = 'border border-border-default';
const ROOT_BORDER_TRANSPARENT = 'border border-transparent';
const STICKY_ROOT = 'sticky bottom-0 z-10';
const HEADER = 'relative z-[3] flex min-w-0 items-center gap-2 p-1';
const TITLE = 'm-0 flex-1 min-w-0 truncate text-xs leading-4 text-foreground [font-weight:var(--font-semibold)]';
const INLINE_ACTION = '!h-auto !shrink-0 !gap-2 !rounded-md !px-2 !py-[2px] !text-sm !leading-5 hover:!bg-white/60 active:!bg-white/60';
const TOGGLE_ACTION = '!h-auto !shrink-0 !gap-2 !rounded-md !px-2 !py-[2px] !text-sm !leading-5 hover:!bg-white/60 active:!bg-white/60';
const CARD = 'relative z-[2] flex min-w-0 flex-col gap-4 rounded-[12px] border border-white bg-white/80 p-4 shadow-[0_0_30px_0_rgba(101,115,137,0.07)] backdrop-blur-[2px]';
const COMPACT_CARD = 'relative z-[2] flex min-w-0 flex-col gap-3 rounded-[12px] border border-white bg-white/80 px-4 py-3 shadow-[0_0_30px_0_rgba(101,115,137,0.07)] backdrop-blur-[2px]';
const FOOTER_STRIP = 'flex min-w-0 items-center gap-4';
const FOOTER_META = 'flex min-w-0 flex-1 flex-col gap-2';
const BADGE_ROW = 'flex min-w-0 items-center gap-[6px]';
const OWNER_ROW = 'flex min-w-0 flex-wrap items-center gap-3';
const OWNER_GROUP = 'inline-flex min-w-0 items-center gap-1';
const OWNER_TEXT = 'truncate text-xs leading-4 text-foreground-muted';
const ACTION_GROUP = 'flex shrink-0 items-center gap-3';
const ACTION_CLUSTER = 'flex shrink-0 items-center gap-2';
const OUTLINE_BUTTON = '!shrink-0';
const PLAY_BUTTON = '!shrink-0';
const INPUT_BAR = 'flex min-w-0 items-center gap-1 rounded-[12px] border border-border-default bg-white px-1 py-1';
const INPUT_FIELD_OVERRIDE = 'flex-1 [&_.tfds-input]:!border-transparent [&_.tfds-input]:!bg-transparent [&_.tfds-input]:!shadow-none [&_.tfds-input]:!rounded-none [&_.tfds-input]:!h-9 [&_.tfds-input]:!px-2 [&_.tfds-input:hover]:!border-transparent [&_.tfds-input:focus-within]:!border-transparent [&_input]:placeholder:!text-foreground-disabled [&_input:focus]:placeholder:!text-foreground-disabled';
const SEND_BUTTON = '!h-9 !shrink-0 !rounded-xl';
const DIVIDER = 'h-px w-full bg-border-default/50';
const SECTION_TITLE = 'm-0 shrink-0 bg-clip-text text-xs leading-4 text-transparent [font-weight:var(--font-semibold)] [background-image:var(--gradient-ai-fill-text)]';
const SUMMARY_HEADER = 'flex min-w-0 items-center gap-2';
const SUMMARY_TAGS = 'min-w-0 flex-1 !justify-end';
const SUMMARY_LIST = 'flex min-w-0 flex-col gap-3';
const SUMMARY_ITEM = 'flex min-w-0 items-start gap-3';
const SUMMARY_KEY = 'm-0 w-16 shrink-0 whitespace-nowrap text-xs leading-4 text-foreground [font-weight:var(--font-semibold)]';
const SUMMARY_VALUE = 'm-0 min-w-0 flex-1 text-xs leading-4 text-secondary';
const PLAN_LIST = 'flex min-w-0 max-h-[120px] flex-col overflow-y-auto pr-1';
const PLAN_ITEM = 'flex min-w-0 items-start gap-2';
const PLAN_ICON_COLUMN = 'flex w-[14px] shrink-0 flex-col items-center pt-[6px]';
const PLAN_CONNECTOR = 'mt-[6px] w-px flex-1 bg-border-default/50';
const PLAN_CONTENT = 'flex min-w-0 flex-1 items-center gap-[6px] pb-3';
const PLAN_TEXT = 'm-0 shrink-0 text-xs leading-4 text-foreground';
const GLOW_WRAP = 'pointer-events-none absolute bottom-0 left-0 z-[1] flex h-5 w-full items-center opacity-50';
const GLOW = 'h-5 w-full rounded-full bg-[linear-gradient(271deg,#FF99F8_0%,#B583FF_25%,#729CFF_48%,#75DAE7_83%,#73E6CC_100%)] blur-[15px]';
const TAG_LIST = 'flex min-w-0 items-center gap-[6px] overflow-hidden whitespace-nowrap';
const MEASURE_ROW = 'pointer-events-none absolute left-0 top-0 -z-10 flex opacity-0 gap-[6px] whitespace-nowrap';
const TAG_TOOLTIP_CONTENT = 'flex max-w-[248px] flex-wrap gap-1';
const TAG_RADIUS = 'md';
const TAG_SIZE = 'm';
const TAG_GAP = 6;

const STATUS_VARIANTS = {
  managed: {
    title: '已完成任务规划',
    statusLabel: '托管中',
    statusTone: 'managed',
    showPlanSwitch: false,
    quickCountLabel: null,
    showActionArea: false,
  },
  intervention: {
    title: '已完成任务规划',
    statusLabel: '待干预',
    statusTone: 'intervention',
    showPlanSwitch: true,
    quickCountLabel: null,
    showActionArea: true,
  },
};

const SAMPLE_PLAN_STEPS = [
  {
    id: 'intake',
    text: '接收电商客服工单，完成进线信息归集',
    agentLabel: '@ 工单调度 | 调度 Anna',
    iconName: 'check-circle-stroked',
    iconClassName: 'text-green-500',
  },
  {
    id: 'diagnosis',
    text: '对工单进行问题诊断，明确处理内容',
    agentLabel: '@ 方案研判 | 研判 Ryan',
    iconName: 'check-circle-stroked',
    iconClassName: 'text-green-500',
  },
  {
    id: 'merchant-call',
    text: '外呼商家核实订单与库存情况',
    agentLabel: '@ 商家协商 | 执行 Jack',
    iconName: 'check-circle-stroked',
    iconClassName: 'text-green-500',
  },
  {
    id: 'plan',
    text: '与用户确认补偿方案与处理口径',
    agentLabel: '@ 方案研判 | 研判 Ryan',
    iconName: 'check-circle-stroked',
    iconClassName: 'text-green-500',
  },
  {
    id: 'refund',
    text: '根据外呼结果进行对应退款操作',
    agentLabel: '@ 退款 | 执行 Jack',
    iconName: 'check-circle-stroked',
    iconClassName: 'text-green-500',
  },
  {
    id: 'notify',
    text: '电话回访用户，告知工单处理结果',
    agentLabel: '@ 用户外呼 | 执行 Jack',
    iconName: 'check-circle-stroked',
    iconClassName: 'text-green-500',
  },
  {
    id: 'archive',
    text: '完成工单结案归档与会话沉淀',
    agentLabel: '@ 工单助手 Ticko',
    iconLoadingRing: true,
    iconClassName: '',
  },
];

const SAMPLE_SUMMARY_SECTIONS = [
  {
    key: '问题诉求',
    value:
      '用户反馈 dou+ 投放显示异常，对处理结果存疑，称只接到一次电话却被告知多次联系，并询问某视频能否发布，希望通过电话联系告知处理结果。',
  },
  {
    key: '服务历程',
    value:
      '2025 年 7 月 1 日 14:32 系统创建工单，14:33 转交至新工单 IM_安全风控_一线_BPO_抖音社区，承接人叶玲于 16:47 创建升级，16:57 升级处理结论为作品可能涉嫌违反相关规范，暂不支持投放 DOU+。',
  },
  {
    key: '解决方案',
    value:
      '建议更换视频后重投。由于用户希望通过电话告知处理结果，需在确认最终口径后由执行 Agent 继续外呼说明，并同步回写工单记录。',
  },
];

const SAMPLE_SUMMARY_TAGS = ['重复进线 3 次', '有风险', '转交 2 次', '外呼商家 3 次'];
const SAMPLE_META_TAGS = [
  { label: '退款审核中' },
  { label: '催 4' },
  { label: '商家未回复' },
];

const SAMPLE_PRIMARY_MENU_ITEMS = [
  { id: 'finish-and-notify', label: '完结并通知人工', iconName: 'message-check-circle-stroked' },
  { id: 'finish-and-archive', label: '完结并归档', iconName: 'folder-check-stroked' },
  { id: 'transfer', label: '转交人工继续处理', iconName: 'share-01-stroked' },
];

function stopEvent(event) {
  event.stopPropagation();
}

function normalizeTagItems(items = [], fallbackVariant = 'grey') {
  return (Array.isArray(items) ? items : []).map((item, index) => {
    if (typeof item === 'string') {
      return {
        key: `${item}-${index}`,
        label: item,
        variant: fallbackVariant,
      };
    }

    return {
      key: item.key || item.value || item.label || `tag-${index}`,
      label: item.label || '',
      variant: item.variant || fallbackVariant,
      iconName: item.iconName || null,
      closable: Boolean(item.closable),
      iconOnly: Boolean(item.iconOnly),
      fontWeight: item.fontWeight || 'regular',
    };
  });
}

function getVisibleTagCount(tagWidths, moreWidth, availableWidth, pinnedLeadingCount, pinnedTrailingCount) {
  const leadingWidth = tagWidths.slice(0, pinnedLeadingCount).reduce((sum, width) => sum + width, 0);
  const trailingWidth = pinnedTrailingCount > 0
    ? tagWidths.slice(tagWidths.length - pinnedTrailingCount).reduce((sum, width) => sum + width, 0)
    : 0;
  const middleWidths = tagWidths.slice(pinnedLeadingCount, tagWidths.length - pinnedTrailingCount);
  const baseVisibleCount = pinnedLeadingCount + pinnedTrailingCount;
  const middleMax = middleWidths.length;

  for (let visibleMiddleCount = middleMax; visibleMiddleCount >= 0; visibleMiddleCount -= 1) {
    const hiddenCount = middleMax - visibleMiddleCount;
    const visibleMiddleWidth = middleWidths.slice(0, visibleMiddleCount).reduce((sum, width) => sum + width, 0);
    const visibleTagCount = baseVisibleCount + visibleMiddleCount + (hiddenCount > 0 ? 1 : 0);
    const totalGapWidth = Math.max(0, visibleTagCount - 1) * TAG_GAP;
    const totalWidth = leadingWidth + trailingWidth + visibleMiddleWidth + (hiddenCount > 0 ? moreWidth : 0) + totalGapWidth;

    if (totalWidth <= availableWidth) {
      return visibleMiddleCount;
    }
  }

  return 0;
}

function TagSummaryList({
  items = [],
  pinnedLeadingCount = 0,
  pinnedTrailingCount = 0,
  className = '',
}) {
  const rootRef = useRef(null);
  const measureRef = useRef(null);
  const moreMeasureRef = useRef(null);
  const [visibleMiddleCount, setVisibleMiddleCount] = useState(null);
  const normalizedItems = useMemo(() => normalizeTagItems(items), [items]);

  const renderTag = useCallback((item) => {
    const hasIcon = Boolean(item.iconName);
    return (
      <Tag
        key={item.key}
        variant={item.variant || 'grey'}
        size={TAG_SIZE}
        radius={TAG_RADIUS}
        fontWeight={item.fontWeight || 'regular'}
        showIcon={hasIcon}
        iconName={item.iconName || 'tag-01-stroked'}
        closable={item.closable}
        className={item.iconOnly ? '!pl-[6px] !pr-[6px] [&>.tag-text]:hidden' : ''}
      >
        {item.label}
      </Tag>
    );
  }, []);

  const measure = useCallback(() => {
    const root = rootRef.current;
    const row = measureRef.current;
    if (!root || !row) return;

    const tagWidths = Array.from(row.querySelectorAll('[data-measure-tag]')).map((node) => Math.ceil(node.getBoundingClientRect().width));
    const moreWidth = Math.ceil(moreMeasureRef.current?.getBoundingClientRect().width || 34);
    const availableWidth = Math.max(0, root.clientWidth);
    setVisibleMiddleCount(getVisibleTagCount(tagWidths, moreWidth, availableWidth, pinnedLeadingCount, pinnedTrailingCount));
  }, [pinnedLeadingCount, pinnedTrailingCount]);

  useLayoutEffect(() => {
    measure();
  }, [measure, normalizedItems]);

  useEffect(() => {
    if (!rootRef.current || typeof ResizeObserver === 'undefined') return undefined;
    const observer = new ResizeObserver(() => measure());
    observer.observe(rootRef.current);
    return () => observer.disconnect();
  }, [measure]);

  const safeVisibleMiddleCount = visibleMiddleCount == null
    ? Math.max(0, normalizedItems.length - pinnedLeadingCount - pinnedTrailingCount)
    : visibleMiddleCount;
  const leadingItems = normalizedItems.slice(0, pinnedLeadingCount);
  const trailingItems = pinnedTrailingCount > 0 ? normalizedItems.slice(normalizedItems.length - pinnedTrailingCount) : [];
  const middleItems = normalizedItems.slice(pinnedLeadingCount, normalizedItems.length - pinnedTrailingCount);
  const visibleMiddleItems = middleItems.slice(0, safeVisibleMiddleCount);
  const hiddenItems = middleItems.slice(safeVisibleMiddleCount);
  const hiddenContent = hiddenItems.length > 0 ? (
    <div className={TAG_TOOLTIP_CONTENT}>
      {hiddenItems.map((item) => renderTag(item))}
    </div>
  ) : null;

  return (
    <div ref={rootRef} className={[TAG_LIST, className].filter(Boolean).join(' ')}>
      {leadingItems.map((item) => renderTag(item))}
      {visibleMiddleItems.map((item) => renderTag(item))}
      {hiddenItems.length > 0 ? (
        <Tooltip
          content={hiddenContent}
          tone="light"
          placement="top"
          triggerClassName="inline-flex shrink-0"
          className="!max-w-[280px]"
        >
          <Tag variant="grey" size={TAG_SIZE} radius={TAG_RADIUS}>+{hiddenItems.length}</Tag>
        </Tooltip>
      ) : null}
      {trailingItems.map((item) => renderTag(item))}

      <div ref={measureRef} className={MEASURE_ROW} aria-hidden>
        {normalizedItems.map((item) => (
          <span key={`measure-${item.key}`} data-measure-tag>
            {renderTag(item)}
          </span>
        ))}
        <span ref={moreMeasureRef}>
          <Tag variant="grey" size={TAG_SIZE} radius={TAG_RADIUS}>+99</Tag>
        </span>
      </div>
    </div>
  );
}

function PlanItem({ item, isLast = false }) {
  return (
    <div className={PLAN_ITEM}>
      <div className={PLAN_ICON_COLUMN}>
        {item.iconLoadingRing ? (
          <IconLoading size="sm" aria-hidden="true" />
        ) : (
          <Icon name={item.iconName} size={14} aria-hidden="true" className={item.iconClassName} />
        )}
        {!isLast ? <span className={PLAN_CONNECTOR} /> : null}
      </div>
      <div className={PLAN_CONTENT}>
        <p className={PLAN_TEXT}>{item.text}</p>
        <Tag variant="grey" size="l" radius="full" fontWeight="regular">{item.agentLabel}</Tag>
      </div>
    </div>
  );
}

function PlanList({ steps }) {
  const listRef = useRef(null);
  useLayoutEffect(() => {
    const node = listRef.current;
    if (node) node.scrollTop = node.scrollHeight;
  }, [steps]);
  return (
    <div ref={listRef} className={PLAN_LIST}>
      {steps.map((item, index) => (
        <PlanItem key={item.id} item={item} isLast={index === steps.length - 1} />
      ))}
    </div>
  );
}

function SummarySection({ title = '工单总结', tags = SAMPLE_SUMMARY_TAGS, sections = SAMPLE_SUMMARY_SECTIONS }) {
  return (
    <div className="flex min-w-0 flex-col gap-3">
      <div className={SUMMARY_HEADER}>
        <p className={SECTION_TITLE}>{title}</p>
        <TagSummaryList items={tags} className={SUMMARY_TAGS} />
      </div>
      <div className={SUMMARY_LIST}>
        {sections.map((section) => (
          <div key={section.key} className={SUMMARY_ITEM}>
            <p className={SUMMARY_KEY}>{section.key}</p>
            <p className={SUMMARY_VALUE}>{section.value}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

function FooterMetaRow({
  statusLabel,
  statusTone,
  metaTags = SAMPLE_META_TAGS,
  quickCountLabel = null,
  customerName = '海阔**天空',
  customerId = '2918575148379876',
  customerAvatarSrc = DEFAULT_CUSTOMER_AVATAR_SRC,
  actionArea = null,
}) {
  /**
   * 工单状态标签排序与去重规则（FooterMetaRow）：
   *   ① 工单状态类「彩色」标签（variant !== 'grey'，如红色「待干预」、绿色「托管中」、橙色
   *      「已挂起」、蓝色「已处理」等）必须 **置于最左侧**，并通过 `pinnedLeadingCount`
   *      固定占位，截断时优先保留。
   *   ② 其余「灰色」工单类型/属性标签（如「异常提醒」/「催 4」/「重复进线」/「商家未回复」
   *      等）排在彩色标签的右侧。
   *   ③ 同 label 仅保留一次：避免出现「待干预 / 异常提醒 / 待干预」这种因为 statusLabel
   *      与 metaTags 并存导致的重复。
   *   ④ `statusLabel` 仅在 metaTags 没有任何彩色项时作为兜底（单组件预览场景），
   *      在「工单 Agent 工作台」模板里数据源已是 ConversationList tags 数组，
   *      不应再触发兜底。
   */
  const summaryItems = useMemo(() => normalizeTagItems(metaTags, 'grey'), [metaTags]);
  const coloredTags = useMemo(() => summaryItems.filter((tag) => tag.variant && tag.variant !== 'grey'), [summaryItems]);
  const greyTags = useMemo(() => summaryItems.filter((tag) => !tag.variant || tag.variant === 'grey'), [summaryItems]);

  const footerTags = useMemo(() => {
    const statusVariant = statusTone === 'intervention' ? 'red' : statusTone === 'managed' ? 'green' : 'grey';
    const statusFallback = coloredTags.length === 0 && statusLabel
      ? [{ key: 'status', label: statusLabel, variant: statusVariant }]
      : [];
    const quickSummaryItem = quickCountLabel
      ? [{ key: 'quick-count', label: quickCountLabel, variant: 'grey' }]
      : [];

    const seen = new Set();
    const out = [];
    for (const tag of [...statusFallback, ...coloredTags, ...greyTags, ...quickSummaryItem]) {
      if (!tag?.label || seen.has(tag.label)) continue;
      seen.add(tag.label);
      out.push(tag);
    }
    return out;
  }, [coloredTags, greyTags, quickCountLabel, statusLabel, statusTone]);

  const pinnedLeadingCount = useMemo(() => {
    if (coloredTags.length > 0) {
      const seen = new Set();
      return coloredTags.filter((tag) => {
        if (!tag?.label || seen.has(tag.label)) return false;
        seen.add(tag.label);
        return true;
      }).length;
    }
    return statusLabel ? 1 : 0;
  }, [coloredTags, statusLabel]);

  return (
    <div className={FOOTER_STRIP}>
      <div className={FOOTER_META}>
        <TagSummaryList items={footerTags} pinnedLeadingCount={pinnedLeadingCount} pinnedTrailingCount={0} className={BADGE_ROW} />
        <div className={OWNER_ROW}>
          <span className={OWNER_GROUP}>
            <Avatar type="image" shape="round" size="xxs" src={customerAvatarSrc} alt={`${customerName} 用户昵称头像`} />
            <span className={OWNER_TEXT} title={customerName} aria-label={`用户昵称：${customerName}`}>{customerName}</span>
          </span>
          <span className={OWNER_GROUP}>
            <Icon name="file-05-stroked" size={12} aria-hidden="true" className="text-foreground-disabled" />
            <span className={OWNER_TEXT} title={`工单 ID：${customerId}`} aria-label={`工单 ID：${customerId}`}>{customerId}</span>
          </span>
        </div>
      </div>
      {actionArea}
    </div>
  );
}

export default function AgentStatusBar({
  statusVariant = 'managed',
  title,
  collapsed,
  defaultCollapsed = false,
  onCollapsedChange = null,
  detailActionLabel = '查看详情',
  onDetailClick = null,
  planSwitchLabel = '显示规划',
  showPlan,
  defaultShowPlan = true,
  onShowPlanChange = null,
  planSteps = SAMPLE_PLAN_STEPS,
  summaryTitle = '工单总结',
  summaryTags = SAMPLE_SUMMARY_TAGS,
  summarySections = SAMPLE_SUMMARY_SECTIONS,
  statusLabel,
  metaTags = SAMPLE_META_TAGS,
  quickCountLabel,
  customerName = '海阔**天空',
  customerId = '2918575148379876',
  customerAvatarSrc = DEFAULT_CUSTOMER_AVATAR_SRC,
  toolActionLabel = '工具',
  primaryActionLabel = '完结',
  primaryMenuItems = SAMPLE_PRIMARY_MENU_ITEMS,
  onPrimaryMenuItemClick = null,
  inputPlaceholder = '可以输入指令，随时调整 Ticko 处理流程',
  onToolAction = null,
  onPrimaryAction = null,
  onSubmitInput = null,
  /**
   * 顶部头像所属的 Agent 家族 id（'planner' | 'analysis' | 'outbound' | 'execution' | 'alert'）。
   * 在「工单 Agent 工作台框架」里，本头像必须代表 Agent Flow 中**最新节点**（视口底部那一条）
   * 的 Agent 家族；不传则回退 'planner'，仅作单组件预览态使用。
   */
  headerAgentFamilyAvatar = 'planner',
  sticky = true,
  className = '',
  style = null,
}) {
  const variantConfig = STATUS_VARIANTS[statusVariant] || STATUS_VARIANTS.managed;
  const isCollapsedControlled = collapsed !== undefined;
  const [innerCollapsed, setInnerCollapsed] = useState(defaultCollapsed);
  const isPlanControlled = showPlan !== undefined;
  const [innerShowPlan, setInnerShowPlan] = useState(defaultShowPlan);

  const [inputValue, setInputValue] = useState('');

  useEffect(() => {
    if (!isCollapsedControlled) setInnerCollapsed(defaultCollapsed);
  }, [defaultCollapsed, isCollapsedControlled]);

  useEffect(() => {
    if (!isPlanControlled) setInnerShowPlan(defaultShowPlan);
  }, [defaultShowPlan, isPlanControlled]);

  const isCollapsed = isCollapsedControlled ? collapsed : innerCollapsed;
  const isPlanVisible = isPlanControlled ? showPlan : innerShowPlan;
  const resolvedTitle = title || variantConfig.title;
  const resolvedStatusLabel = statusLabel || variantConfig.statusLabel;
  const resolvedQuickCountLabel = quickCountLabel === undefined ? variantConfig.quickCountLabel : quickCountLabel;

  const rootClassName = [ROOT, isCollapsed ? ROOT_COLLAPSED_BG : ROOT_EXPANDED_BG, isCollapsed ? ROOT_BORDER_TRANSPARENT : ROOT_BORDER, sticky ? STICKY_ROOT : '', className].filter(Boolean).join(' ');

  const footerActionArea = useMemo(() => {
    if (!variantConfig.showActionArea) return null;

    return (
      <div className={ACTION_GROUP}>
        <div className={ACTION_CLUSTER}>
          <Button
            type="button"
            variant="outline-black"
            size="md"
            className={OUTLINE_BUTTON}
            icon={<Icon name="tool-01-stroked" size={16} aria-hidden="true" />}
            onClick={onToolAction}
          >
            {toolActionLabel}
          </Button>
          <SplitButton
            variant="outline-black"
            size="md"
            primaryLabel={primaryActionLabel}
            onPrimaryClick={onPrimaryAction}
            menuItems={primaryMenuItems}
            onMenuItemClick={onPrimaryMenuItemClick}
            placement="auto"
            secondaryTooltip="更多操作"
            secondaryAriaLabel={`${primaryActionLabel}更多操作`}
          />
        </div>
        <span className="h-5 w-px shrink-0 bg-border-default" />
        <Button
          type="button"
          variant="primary"
          size="md"
          radius="rounded"
          iconOnly
          tooltip="执行"
          className={PLAY_BUTTON}
          icon={<Icon name="play-stroked" size={16} aria-hidden="true" />}
          aria-label="执行"
        />
      </div>
    );
  }, [onPrimaryAction, onPrimaryMenuItemClick, onToolAction, primaryActionLabel, primaryMenuItems, toolActionLabel, variantConfig.showActionArea]);

  const footerMetaRow = (
    <FooterMetaRow
      statusLabel={resolvedStatusLabel}
      statusTone={variantConfig.statusTone}
      metaTags={metaTags}
      quickCountLabel={resolvedQuickCountLabel}
      customerName={customerName}
      customerId={customerId}
      customerAvatarSrc={customerAvatarSrc}
      actionArea={footerActionArea}
    />
  );

  function updateCollapsed(nextValue) {
    if (!isCollapsedControlled) setInnerCollapsed(nextValue);
    onCollapsedChange?.(nextValue);
  }

  function handleToggle(event) {
    stopEvent(event);
    updateCollapsed(!isCollapsed);
  }

  function handleDetailClick(event) {
    stopEvent(event);
    onDetailClick?.();
  }

  function handlePlanToggle(nextValue, event) {
    event?.stopPropagation?.();
    if (!isPlanControlled) setInnerShowPlan(nextValue);
    onShowPlanChange?.(nextValue);
  }

  function handleInputChange(event) {
    setInputValue(event.target.value);
  }

  function handleInputKeyDown(event) {
    if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent?.isComposing) {
      event.preventDefault();
      handleSubmitInput();
    }
  }

  function handleSubmitInput() {
    onSubmitInput?.(inputValue);
    setInputValue('');
  }

  function renderInputBar() {
    return (
      <div className={INPUT_BAR}>
        <div className={INPUT_FIELD_OVERRIDE}>
          <Input
            value={inputValue}
            onChange={handleInputChange}
            onKeyDown={handleInputKeyDown}
            placeholder={inputPlaceholder}
            aria-label="干预指令输入框"
          />
        </div>
        <Button
          type="button"
          variant="ghost-black"
          size="md"
          iconOnly
          tooltip="发送干预指令"
          className={SEND_BUTTON}
          icon={<Icon name="send-03-stroked" size={16} aria-hidden="true" />}
          aria-label="发送干预指令"
          disabled={!inputValue.trim()}
          onClick={handleSubmitInput}
        />
      </div>
    );
  }

  function renderManagedBody() {
    if (isCollapsed) {
      return <div className={COMPACT_CARD}>{footerMetaRow}</div>;
    }

    return (
      <div className={CARD}>
        <div className="flex min-w-0 flex-col gap-2">
          <div className="flex min-w-0 items-start gap-2">
            <Icon name="check-circle-stroked" size={14} aria-hidden="true" className="mt-[1px] shrink-0 text-green-500" />
            <p className="m-0 text-xs leading-4 text-foreground">根据外呼结果进行对应退款操作，并回写工单状态。</p>
          </div>
          <div className="flex min-w-0 items-start gap-2">
            <Icon name="check-circle-stroked" size={14} aria-hidden="true" className="mt-[1px] shrink-0 text-green-500" />
            <p className="m-0 text-xs leading-4 text-foreground">推送外呼任务给执行 Agent，并同步通知人工关注后续处理结果。</p>
          </div>
        </div>
        <span className={DIVIDER} />
        <SummarySection title={summaryTitle} tags={summaryTags} sections={summarySections} />
        <span className={DIVIDER} />
        {footerMetaRow}
      </div>
    );
  }

  function renderInterventionBody() {
    if (isCollapsed) {
      return (
        <div className={COMPACT_CARD}>
          {footerMetaRow}
          {renderInputBar()}
        </div>
      );
    }

    return (
      <div className={CARD}>
        {isPlanVisible ? (
          <>
            <PlanList steps={planSteps} />
            <span className={DIVIDER} />
          </>
        ) : null}
        <SummarySection title={summaryTitle} tags={summaryTags} sections={summarySections} />
        <span className={DIVIDER} />
        {footerMetaRow}
        {renderInputBar()}
      </div>
    );
  }

  return (
    <section className={rootClassName} style={style} data-tfds-component="AgentStatusBar" data-variant={statusVariant} data-collapsed={isCollapsed ? 'true' : 'false'}>
      <div className={HEADER}>
        <AgentFamilyAvatar avatar={headerAgentFamilyAvatar} size={24} className="shrink-0" />
        <p className={TITLE}>{resolvedTitle}</p>
        {variantConfig.showPlanSwitch && !isCollapsed ? (
          <span className="inline-flex shrink-0 items-center gap-2 rounded-md px-2 py-[2px]">
            <span className="text-sm leading-5 text-foreground [font-weight:var(--font-semibold)]">{planSwitchLabel}</span>
            <Switch variant="black" size="sm" checked={isPlanVisible} onChange={handlePlanToggle} />
          </span>
        ) : null}
        <Button
          type="button"
          variant="ghost-black"
          size="sm"
          className={INLINE_ACTION}
          icon={<Icon name="file-05-stroked" size={16} aria-hidden="true" />}
          onClick={handleDetailClick}
        >
          {detailActionLabel}
        </Button>
        <Button
          type="button"
          variant="ghost-black"
          size="sm"
          className={TOGGLE_ACTION}
          icon={<Icon name={isCollapsed ? 'chevron-up-stroked' : 'chevron-down-stroked'} size={16} aria-hidden="true" />}
          onClick={handleToggle}
          aria-expanded={!isCollapsed}
          aria-label={isCollapsed ? '展开 Agent 状态栏' : '收起 Agent 状态栏'}
        >
          {isCollapsed ? '展开' : '收起'}
        </Button>
      </div>

      {statusVariant === 'managed' ? renderManagedBody() : renderInterventionBody()}

      <div className={GLOW_WRAP} aria-hidden="true">
        <div className={GLOW} />
      </div>
    </section>
  );
}

export { SAMPLE_PLAN_STEPS, SAMPLE_SUMMARY_SECTIONS, SAMPLE_SUMMARY_TAGS, SAMPLE_META_TAGS };
