import { useEffect, useMemo, useRef, useState } from 'react';
import Avatar from './Avatar';
import Dropdown from './Dropdown';
import Icon from './Icon';
import { getTeamMemberByName } from '../teamMembers';

/**
 * NavBar — B端业务侧边导航栏（Tailwind 内联）
 *
 * 对齐 Figma 里的 OLA / ByteHi 两套业务导航结构。默认输出 OLA 平台版本；
 * 当 platform="bytehi" 时切换到 ByteHi 的默认收起、hover/focus 展开版式。
 *
 * @prop {'ola'|'bytehi'} [platform] — 平台变体；未传时可由 promptText 关键词自动推断，兜底为 ola
 * @prop {string} [promptText=''] — 供 AI / 提示词路由使用的上下文文本；默认 ola，仅明确命中“客服工作台”相关关键词时默认 bytehi
 * @prop {string} [brandName='OLA'] — 顶部品牌名；OLA 是模板占位文案，真实页面应传入对应平台名称
 * @prop {string|null} [brandLogoName=null] — 顶部品牌 logo 名（必须是 logo 分类下的 IconName，如 "西瓜视频"）；命中映射表时会自动同步 brandName 与 OLA / ByteHi 顶部 logo
 * @prop {string} [appLabel='抖音社区'] — OLA 默认业务入口名称（未传 appBusinesses 时作为首项文案）
 * @prop {Array<{id: string, label: string, iconSrc?: string}>|null} [appBusinesses=null] — OLA 业务入口下拉列表
 * @prop {string|null} currentAppId — 当前业务入口 id（受控）
 * @prop {string|null} [defaultAppId=null] — 非受控初始业务入口 id
 * @prop {(appId: string, meta: { app: {id: string, label: string, iconSrc?: string} | null }) => void} [onAppChange=null] — 业务入口切换回调
 * @prop {string} [moduleLabel='平台首页'] — OLA 首页导航文案；未传 navItems 时用于生成默认 navItems[0]
 * @prop {boolean} [activeModule=true] — 兼容旧 API；未传 selectedItemId / defaultSelectedItemId / activeNavId 时默认选中首页
 * @prop {Array<{id: string, label: string, iconName: string, active?: boolean}>|null} [navItems=null] — 主导航项
 * @prop {string|null} [activeNavId=null] — 当前激活的主导航 id
 * @prop {string|null} [activeUtilityId=null] — 当前激活的底部工具按钮 id
 * @prop {string|null} [selectedItemId=null] — 统一控制的选中菜单 id，优先级高于 activeModule / activeNavId / activeUtilityId
 * @prop {string|null} [defaultSelectedItemId=null] — 非受控模式下的初始选中菜单 id
 * @prop {boolean} [showUtilityActions=false] — 是否显示底部操作按钮；OLA 下控制铃铛/设置，ByteHi 下控制操作指南/消息
 * @prop {Array<{id: string, label: string, iconName: string}>|null} [utilityItems=null] — 底部工具按钮；OLA / ByteHi 都支持自定义
 * @prop {(itemId: string, meta: { section: 'nav'|'utility'|'status', item: object|null }) => void} [onSelect=null] — 菜单点击回调
 * @prop {'image'|'robot'|'fallback'} [avatarType='image'] — 底部头像类型
 * @prop {string|null} [avatarSrc=null] — 自定义头像地址
 * @prop {string} [avatarAlt='当前用户头像'] — 头像替代文本
 * @prop {string} [className=''] — 附加类名
 * @prop {React.CSSProperties|undefined} [style=undefined] — 附加内联样式
 */

const DEFAULT_OLA_NAV_ITEMS = [
  { id: 'home', label: '平台首页', iconName: 'home-smile-stroked' },
  { id: 'strategy', label: '策略管理', iconName: 'if-stroked' },
  { id: 'knowledge', label: '知识与案例', iconName: 'book-open-01-stroked' },
  { id: 'tools', label: '工具管理', iconName: 'tool-01-stroked' },
  { id: 'insight', label: '对话洞察', iconName: 'message-chat-circle-stroked' },
  { id: 'monitor', label: '智能盯盘', iconName: 'grid-03-stroked' },
];

const DEFAULT_OLA_UTILITY_ITEMS = [
  { id: 'notice', label: '通知消息', iconName: 'bell-03-stroked' },
  { id: 'settings', label: '系统设置', iconName: 'settings-02-stroked' },
];

const DEFAULT_OLA_APP_ICON = '抖音';

/**
 * OLA 业务方下拉默认平台列表，覆盖全部平台 logo。
 * 业务自定义 appBusinesses 时以业务传入为准；未传时下拉展示这 15 个平台。
 */
const DEFAULT_OLA_APP_BUSINESSES = [
  { id: 'douyin-community', label: '抖音社区', iconSrc: '抖音' },
  { id: 'douyin-local-services', label: '抖音生活服务', iconSrc: '抖音' },
  { id: 'douyin-ecommerce', label: '抖音电商', iconSrc: '抖音' },
  { id: 'bytehi', label: 'ByteHi', iconSrc: 'ByteHi' },
  { id: 'service-experience', label: '体验与服务', iconSrc: '体验与服务' },
  { id: 'configuration-center', label: '运营配置中心', iconSrc: '运营配置中心' },
  { id: 'wfm', label: 'WFM', iconSrc: 'WFM' },
  { id: 'voc', label: 'VOC', iconSrc: 'VOC' },
  { id: 'hcm', label: 'HCM', iconSrc: 'HCM' },
  { id: 'ulike', label: '轻颜', iconSrc: '轻颜' },
  { id: 'cosmos', label: '可颂', iconSrc: '可颂' },
  { id: 'toutiao', label: '今日头条', iconSrc: '今日头条' },
  { id: 'feishu', label: '飞书', iconSrc: '飞书' },
  { id: 'xigua', label: '西瓜视频', iconSrc: '西瓜视频' },
  { id: 'fanqie', label: '番茄小说', iconSrc: '番茄小说' },
  { id: 'xingtu', label: '醒图', iconSrc: '醒图' },
  { id: 'jianying', label: '剪映', iconSrc: '剪映' },
];

const DEFAULT_BYTEHI_NAV_ITEMS = [
  { id: 'home', label: '首页', iconName: 'home-smile-stroked' },
  { id: 'online-workbench', label: '在线工作台', iconName: 'message-dots-circle-stroked' },
  { id: 'online-records', label: '在线会话记录', iconName: 'clock-stroked' },
  { id: 'group-workbench', label: '群聊工作台', iconName: 'message-dots-square-stroked' },
  { id: 'risk-workbench', label: '风险研判工作台', iconName: 'shield-tick-stroked' },
  { id: 'hotline-workbench', label: '热线工作台', iconName: 'menu-03-stroked' },
  { id: 'phone-workbench', label: '电话工作台', iconName: 'phone-stroked' },
  { id: 'ticket-center', label: '工单中心', iconName: 'server-01-stroked' },
  { id: 'sales-workbench', label: '售中工作台', iconName: 'server-02-stroked' },
  { id: 'knowledge-base', label: '人工知识库', iconName: 'book-open-01-stroked' },
  { id: 'system-settings', label: '系统设置', iconName: 'settings-02-stroked' },
];

const DEFAULT_BYTEHI_FOOTER_ITEMS = [
  { id: 'guide', label: '操作指南', iconName: 'help-circle-stroked' },
  { id: 'message', label: '消息', iconName: 'bell-03-stroked' },
];

const BYTEHI_DEFAULT_MEMBER = getTeamMemberByName('段然');

/**
 * 平台 logo 与 brandName 的映射表。
 * key 为 logo 分类下的 IconName，value 为该 logo 对应的默认平台展示文案（brandName）。
 * 当传入 brandLogoName 命中此表时：
 *   - OLA 顶部品牌区使用 <Icon name={brandLogoName} />
 *   - ByteHi 顶部品牌区使用 <Icon name={brandLogoName} />
 *   - 未显式传 brandName 时，brandName 自动同步为对应文案
 */
export const NAVBAR_PLATFORM_LOGOS = [
  { logoName: 'ByteHi', brandName: 'ByteHi' },
  { logoName: '抖音', brandName: '抖音' },
  { logoName: '体验与服务', brandName: '体验与服务' },
  { logoName: '运营配置中心', brandName: '运营配置中心' },
  { logoName: 'WFM', brandName: 'WFM' },
  { logoName: 'VOC', brandName: 'VOC' },
  { logoName: 'HCM', brandName: 'HCM' },
  { logoName: '轻颜', brandName: '轻颜' },
  { logoName: '可颂', brandName: '可颂' },
  { logoName: '今日头条', brandName: '今日头条' },
  { logoName: '飞书', brandName: '飞书' },
  { logoName: '西瓜视频', brandName: '西瓜视频' },
  { logoName: '番茄小说', brandName: '番茄小说' },
  { logoName: '醒图', brandName: '醒图' },
  { logoName: '剪映', brandName: '剪映' },
];

const NAVBAR_PLATFORM_LOGO_MAP = NAVBAR_PLATFORM_LOGOS.reduce((map, item) => {
  map[item.logoName] = item;
  return map;
}, {});

export function getNavBarPlatformLogo(logoName) {
  if (!logoName) return null;
  return NAVBAR_PLATFORM_LOGO_MAP[logoName] || null;
}

const OLA_PROMPT_KEYWORDS = [
  '体验与服务平台',
  '体验服务平台',
  '服务体验平台',
  '体验服务',
];

const BYTEHI_PROMPT_KEYWORDS = [
  '客服工作台',
];

const BYTEHI_METRICS = [
  { id: 'download-speed', label: '下载速度', value: '-MB/s' },
  { id: 'service-latency', label: '服务延迟', value: '8ms' },
];

const OLA_ROOT = [
  'tfds-nav-bar',
  'flex h-full min-h-0 w-[120px] self-stretch flex-col items-stretch overflow-visible px-4 pt-0',
  'select-none',
].join(' ');

const OLA_BRAND = 'flex w-full flex-col items-center gap-1 px-4 py-6';
const OLA_BRAND_TEXT = 'm-0 text-sm leading-5 text-foreground';
const OLA_BRAND_TEXT_STYLE = {
  fontFamily: '"Arial Black", Arial, sans-serif',
  fontWeight: 900,
};

const OLA_BLOCK = 'flex w-full shrink-0 flex-col gap-1';
const OLA_APP_WRAP = 'relative flex w-full shrink-0 flex-col items-center';
const OLA_DIVIDER_WRAP = 'flex h-10 w-full items-center justify-center';
const OLA_DIVIDER = 'h-px w-full bg-fill';
const OLA_MAIN_NAV = 'flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto overscroll-contain';
const OLA_APP_CARD = [
  'group relative flex h-[60px] w-[88px] shrink-0 flex-col items-center justify-center gap-1 overflow-hidden rounded-md border border-white bg-card-secondary',
  'transition-colors tfds-motion-ui-fast hover:bg-surface',
  'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blueGrey-300',
].join(' ');

const OLA_NAV_BUTTON = [
  'group relative flex shrink-0 flex-col items-center justify-center gap-1 overflow-hidden rounded-md',
  'transition-colors tfds-motion-ui-fast',
  'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blueGrey-300',
].join(' ');

const OLA_NAV_BUTTON_TONE_CLASS = {
  solid: 'border border-white bg-card-secondary hover:bg-surface',
  active: 'border border-white bg-card-secondary hover:bg-surface',
  default: 'border border-transparent hover:bg-card-secondary',
  utility: 'border border-transparent hover:bg-card-secondary',
};

const OLA_NAV_LABEL_BASE = 'text-xs leading-4';

const OLA_NAV_LABEL_CLASS = {
  solid: 'text-foreground font-normal',
  active: 'text-foreground [font-weight:var(--font-semibold)]',
  default: 'text-foreground-muted font-normal',
  utility: 'text-foreground-secondary font-normal',
};

const OLA_NAV_ICON_CLASS = {
  solid: 'text-foreground',
  active: 'text-brand-500',
  default: 'text-foreground-muted',
  utility: 'text-foreground-muted',
};

const OLA_NAV_HEIGHT_CLASS = {
  labeled: 'h-[60px] min-h-[60px] max-h-[60px]',
  icon: 'h-[52px] min-h-[52px] max-h-[52px]',
};

const OLA_NAV_WIDTH_CLASS = {
  labeled: 'w-[88px] min-w-[88px] max-w-[88px]',
  icon: 'w-[88px] min-w-[88px] max-w-[88px]',
};

const OLA_AVATAR_WRAP = 'flex w-full shrink-0 items-center justify-center px-4 py-4';
const OLA_NAV_TEXT_CLAMP = 'max-w-full text-center';

const BYTEHI_ROOT = 'tfds-nav-bar relative z-30 h-full min-h-0 w-[60px] min-w-[60px] max-w-[60px] shrink-0 self-stretch overflow-visible select-none';
const BYTEHI_PANEL = 'absolute inset-y-0 left-0 flex min-h-0 flex-col overflow-hidden bg-blueGrey-200 transition-[width,box-shadow] tfds-motion-ui-normal';
const BYTEHI_EXPANDED_SHADOW = '0 1px 6px 0 rgba(0,0,0,0.1), 0 0 1px 0 rgba(0,0,0,0.15)';
const BYTEHI_HEADER = 'relative h-[48px] min-h-[48px] shrink-0 px-[14px] pt-3';
const BYTEHI_BRAND = 'flex min-w-0 items-start gap-1';
const BYTEHI_LOGO_MARK = 'size-8 shrink-0';
const BYTEHI_WORD = 'flex min-w-0 flex-col items-start overflow-hidden pt-px transition-[max-width,opacity] tfds-motion-ui-normal';
const BYTEHI_WORD_STATE = {
  expanded: 'max-w-[104px] opacity-100',
  collapsed: 'max-w-0 opacity-0',
};
const BYTEHI_BRAND_TITLE = 'm-0 text-[17px] leading-6 [font-weight:var(--font-semibold)] text-foreground';
const BYTEHI_BRAND_SUBTITLE = 'm-0 text-[10px] leading-[12px] text-foreground opacity-65';
const BYTEHI_SWITCH = 'absolute right-[11px] top-3 inline-flex items-center justify-center rounded-avatar p-1 text-foreground-secondary transition-[opacity,color,background-color] tfds-motion-ui-normal hover:bg-surface hover:text-foreground';
const BYTEHI_SWITCH_STATE = {
  expanded: 'opacity-100',
  collapsed: 'pointer-events-none opacity-0',
};
const BYTEHI_MAIN_NAV = 'flex min-h-0 flex-1 flex-col overflow-y-auto px-2 pb-3';
const BYTEHI_NAV_LIST = 'flex flex-col gap-2 pt-[var(--spacing-4)]';
const BYTEHI_NAV_BUTTON = [
  'group flex overflow-hidden rounded-md py-2 text-left',
  'transition-colors tfds-motion-ui-fast',
  'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blueGrey-300',
].join(' ');
const BYTEHI_NAV_BUTTON_LAYOUT = {
  expanded: 'w-full items-center gap-3 px-3',
  collapsed: 'w-full items-center justify-start px-3',
};
const BYTEHI_NAV_TONE_CLASS = {
  active: 'bg-surface text-foreground',
  default: 'text-foreground-muted hover:bg-card-secondary',
};
const BYTEHI_NAV_ICON_CLASS = {
  active: 'text-foreground opacity-100',
  default: 'text-foreground-secondary opacity-45',
};
const BYTEHI_NAV_LABEL_BASE = 'm-0 truncate text-sm leading-5';
const BYTEHI_NAV_LABEL_CLASS = {
  active: '[font-weight:var(--font-semibold)]',
  default: '[font-weight:var(--font-medium)]',
};
const BYTEHI_BOTTOM = 'shrink-0';
const BYTEHI_FADE = 'h-2 w-full bg-gradient-to-b from-transparent to-blueGrey-200';
const BYTEHI_METRICS_WRAP = 'px-2 pb-0';
const BYTEHI_METRICS_CARD = [
  'relative h-[56px] min-h-[56px] w-full overflow-hidden rounded-avatar px-3 py-2 text-left',
  'transition-colors tfds-motion-ui-fast',
  'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blueGrey-300',
].join(' ');
const BYTEHI_METRICS_ICON = 'text-success';
const BYTEHI_METRICS_ICON_SLOT = 'absolute left-3 top-1/2 flex h-5 w-5 -translate-y-1/2 items-center justify-center';
const BYTEHI_METRICS_BODY = 'absolute left-[44px] top-1/2 flex w-[104px] -translate-y-1/2 flex-col gap-1 overflow-hidden transition-[opacity] tfds-motion-ui-fast';
const BYTEHI_METRICS_BODY_STATE = {
  expanded: 'opacity-100',
  collapsed: 'opacity-0',
};
const BYTEHI_METRICS_ROW = 'flex items-start justify-between gap-3 text-xs leading-4';
const BYTEHI_METRICS_LABEL = 'm-0 [font-weight:var(--font-semibold)] text-foreground-secondary opacity-65';
const BYTEHI_METRICS_VALUE = 'm-0 [font-weight:var(--font-semibold)] text-foreground-secondary';
const BYTEHI_FOOTER_SECTION = 'flex flex-col gap-2 px-2 py-2';
const BYTEHI_FOOTER_ACTION = [
  'flex w-full overflow-hidden rounded-md py-2 text-left',
  'transition-colors tfds-motion-ui-fast',
  'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blueGrey-300',
].join(' ');
const BYTEHI_FOOTER_ACTION_LAYOUT = {
  expanded: 'items-start gap-3 px-3',
  collapsed: 'items-center justify-start px-3',
};
const BYTEHI_FOOTER_ACTION_TONE = {
  active: 'bg-surface text-foreground',
  default: 'text-foreground-muted hover:bg-card-secondary',
};
const BYTEHI_AVATAR_ROW = 'flex w-full px-2 py-2';
const BYTEHI_AVATAR_ROW_LAYOUT = {
  expanded: 'items-center gap-2',
  collapsed: 'items-center justify-center',
};
const BYTEHI_AVATAR_SLOT = 'flex shrink-0 items-center py-[6px]';
const BYTEHI_AVATAR_SLOT_LAYOUT = {
  expanded: 'pl-[6px]',
  collapsed: 'justify-center',
};
const BYTEHI_AVATAR_META = 'flex min-w-0 flex-1 flex-col gap-0.5';
const BYTEHI_AVATAR_NAME = 'm-0 truncate text-sm leading-5 text-foreground opacity-65';
const BYTEHI_AVATAR_SUBTITLE = 'm-0 truncate text-xs leading-4 text-foreground opacity-65';

function resolveInitialSelectedKey({
  platform,
  selectedItemId,
  defaultSelectedItemId,
  activeUtilityId,
  activeNavId,
  activeModule,
  navItems,
  utilityItems,
}) {
  if (selectedItemId) return selectedItemId;
  if (defaultSelectedItemId) return defaultSelectedItemId;
  if (activeUtilityId && utilityItems.some((item) => item.id === activeUtilityId)) return activeUtilityId;
  if (activeNavId) return activeNavId;
  const explicitNav = navItems.find((item) => item.active);
  if (explicitNav) return explicitNav.id;
  const explicitUtility = utilityItems.find((item) => item.active);
  if (explicitUtility) return explicitUtility.id;
  if (platform === 'ola' && activeModule) return navItems[0]?.id ?? 'home';
  return platform === 'bytehi' ? navItems[0]?.id ?? null : null;
}

function getDefaultOlaNavItems(moduleLabel, moduleIconName) {
  return DEFAULT_OLA_NAV_ITEMS.map((item, index) => {
    if (index !== 0) return item;
    return {
      ...item,
      label: moduleLabel || item.label,
      iconName: moduleIconName || item.iconName,
    };
  });
}

function getResolvedOlaAppBusinesses(appBusinesses, appLabel) {
  const fallbackBusinesses = DEFAULT_OLA_APP_BUSINESSES.map((item, index) => ({
    ...item,
    label: index === 0 ? (appLabel || item.label) : item.label,
  }));
  const list = Array.isArray(appBusinesses) && appBusinesses.length > 0 ? appBusinesses : fallbackBusinesses;

  return list.map((item, index) => ({
    id: item.id || `app-${index + 1}`,
    label: item.label || (index === 0 ? (appLabel || '抖音社区') : `业务${index + 1}`),
    iconSrc: item.iconSrc || DEFAULT_OLA_APP_ICON,
  }));
}

function getAppBusiness(appBusinesses, appId) {
  return appBusinesses.find((item) => item.id === appId) || appBusinesses[0] || null;
}

function OlaBusinessIcon({ iconName }) {
  return (
    <span className="inline-flex h-4 w-4 shrink-0 items-center justify-center overflow-hidden">
      <Icon name={iconName || '抖音'} size="sm" aria-hidden="true" />
    </span>
  );
}

export function inferNavBarPlatformFromPrompt(promptText = '') {
  const normalizedPrompt = String(promptText).replace(/\s+/g, '');
  if (!normalizedPrompt) return null;
  if (BYTEHI_PROMPT_KEYWORDS.some((keyword) => normalizedPrompt.includes(keyword))) return 'bytehi';
  if (OLA_PROMPT_KEYWORDS.some((keyword) => normalizedPrompt.includes(keyword))) return 'ola';
  return null;
}

function OlaNavButton({
  icon,
  iconName,
  label,
  tone = 'default',
  iconSize = 'sm',
  ariaLabel,
  current = false,
  onClick,
}) {
  const isIconOnly = !label;
  const heightClass = isIconOnly ? OLA_NAV_HEIGHT_CLASS.icon : OLA_NAV_HEIGHT_CLASS.labeled;
  const widthClass = isIconOnly ? OLA_NAV_WIDTH_CLASS.icon : OLA_NAV_WIDTH_CLASS.labeled;
  const resolvedTone = Object.prototype.hasOwnProperty.call(OLA_NAV_BUTTON_TONE_CLASS, tone) ? tone : 'default';

  return (
    <button
      type="button"
      className={[OLA_NAV_BUTTON, widthClass, heightClass, OLA_NAV_BUTTON_TONE_CLASS[resolvedTone]].join(' ')}
      aria-label={ariaLabel || label}
      aria-current={current ? 'page' : undefined}
      onClick={onClick}
      data-tfds-component="NavBar.Item"
    >
      <span className={OLA_NAV_ICON_CLASS[resolvedTone]}>
        {icon || <Icon name={iconName} size={iconSize} />}
      </span>
      {label ? <span className={[OLA_NAV_LABEL_BASE, OLA_NAV_LABEL_CLASS[resolvedTone], OLA_NAV_TEXT_CLAMP].join(' ')}>{label}</span> : null}
    </button>
  );
}

function ByteHiNavButton({
  iconName,
  label,
  expanded = true,
  current = false,
  onClick,
  ariaLabel,
}) {
  const tone = current ? 'active' : 'default';
  const layoutClass = expanded ? BYTEHI_NAV_BUTTON_LAYOUT.expanded : BYTEHI_NAV_BUTTON_LAYOUT.collapsed;

  return (
    <button
      type="button"
      className={[BYTEHI_NAV_BUTTON, layoutClass, BYTEHI_NAV_TONE_CLASS[tone]].join(' ')}
      aria-label={ariaLabel || label}
      aria-current={current ? 'page' : undefined}
      onClick={onClick}
      data-tfds-component="NavBar.Item"
    >
      <span className={BYTEHI_NAV_ICON_CLASS[tone]}>
        <Icon name={iconName} size="md" />
      </span>
      {label ? <p className={[BYTEHI_NAV_LABEL_BASE, BYTEHI_NAV_LABEL_CLASS[tone]].join(' ')}>{label}</p> : null}
    </button>
  );
}

function ByteHiFooterButton({
  iconName,
  label,
  expanded = true,
  current = false,
  onClick,
}) {
  const tone = current ? 'active' : 'default';
  const layoutClass = expanded ? BYTEHI_FOOTER_ACTION_LAYOUT.expanded : BYTEHI_FOOTER_ACTION_LAYOUT.collapsed;

  return (
    <button
      type="button"
      className={[BYTEHI_FOOTER_ACTION, layoutClass, BYTEHI_FOOTER_ACTION_TONE[tone]].join(' ')}
      aria-label={label}
      aria-current={current ? 'page' : undefined}
      onClick={onClick}
      data-tfds-component="NavBar.Utility"
    >
      <span className={BYTEHI_NAV_ICON_CLASS[tone]}>
        <Icon name={iconName} size="md" />
      </span>
      {label ? <p className={[BYTEHI_NAV_LABEL_BASE, BYTEHI_NAV_LABEL_CLASS[tone]].join(' ')}>{label}</p> : null}
    </button>
  );
}

function ByteHiMetricsCard({ current = false, onClick, expanded = true }) {
  const tone = current ? 'active' : 'default';
  const bodyClass = expanded ? BYTEHI_METRICS_BODY_STATE.expanded : BYTEHI_METRICS_BODY_STATE.collapsed;

  return (
    <button
      type="button"
      className={[BYTEHI_METRICS_CARD, BYTEHI_FOOTER_ACTION_TONE[tone]].join(' ')}
      aria-label="网络状态信息"
      aria-current={current ? 'page' : undefined}
      onClick={onClick}
      data-tfds-component="NavBar.Status"
    >
      <span className={[BYTEHI_METRICS_ICON_SLOT, BYTEHI_METRICS_ICON].join(' ')}>
        <Icon name="wifi-stroked" size="md" />
      </span>
      <div className={[BYTEHI_METRICS_BODY, bodyClass].join(' ')} aria-hidden={!expanded}>
        {BYTEHI_METRICS.map((item) => (
          <div key={item.id} className={BYTEHI_METRICS_ROW}>
            <p className={BYTEHI_METRICS_LABEL}>{item.label}</p>
            <p className={BYTEHI_METRICS_VALUE}>{item.value}</p>
          </div>
        ))}
      </div>
    </button>
  );
}

function ByteHiBrand({ brandName, brandLogoName = null, expanded = true }) {
  const wordClass = expanded ? BYTEHI_WORD_STATE.expanded : BYTEHI_WORD_STATE.collapsed;
  const platformLogo = getNavBarPlatformLogo(brandLogoName);
  const iconName = platformLogo ? platformLogo.logoName : 'ByteHi';

  return (
    <div className={BYTEHI_BRAND}>
      <Icon name={iconName} size={32} className={BYTEHI_LOGO_MARK} aria-hidden="true" />
      <div className={[BYTEHI_WORD, wordClass].join(' ')}>
        <p className={BYTEHI_BRAND_TITLE}>{brandName}</p>
        <p className={BYTEHI_BRAND_SUBTITLE}>客服工作台</p>
      </div>
    </div>
  );
}

function ByteHiAvatarInfo({ avatarType, avatarSrc, avatarAlt }) {
  return (
    <div className={[BYTEHI_AVATAR_ROW, BYTEHI_AVATAR_ROW_LAYOUT.expanded].join(' ')}>
      <div className={[BYTEHI_AVATAR_SLOT, BYTEHI_AVATAR_SLOT_LAYOUT.expanded].join(' ')}>
        <Avatar
          type={avatarType}
          size="s"
          shape="round"
          src={avatarSrc}
          alt={avatarAlt}
        />
      </div>
      <div className={BYTEHI_AVATAR_META}>
        <p className={BYTEHI_AVATAR_NAME}>哆来咪</p>
        <p className={BYTEHI_AVATAR_SUBTITLE}>抖音主端</p>
      </div>
    </div>
  );
}

function ByteHiCompactAvatar({ avatarType, avatarSrc, avatarAlt }) {
  return (
    <div className={[BYTEHI_AVATAR_ROW, BYTEHI_AVATAR_ROW_LAYOUT.collapsed].join(' ')}>
      <div className={[BYTEHI_AVATAR_SLOT, BYTEHI_AVATAR_SLOT_LAYOUT.collapsed].join(' ')}>
        <Avatar
          type={avatarType}
          size="s"
          shape="round"
          src={avatarSrc}
          alt={avatarAlt}
        />
      </div>
    </div>
  );
}

function OlaBusinessSwitcher({
  businesses,
  currentApp,
  onAppChange,
}) {
  const items = useMemo(
    () => businesses.map((business) => ({
      id: business.id,
      value: business.id,
      label: business.label,
      iconName: business.iconSrc,
    })),
    [businesses],
  );

  return (
    <Dropdown
      className={OLA_APP_WRAP}
      data-tfds-component="NavBar.AppSwitcher"
      selectionIndicator="leading-check"
      showIcon
      selectedValue={currentApp?.id}
      matchTriggerWidth={false}
      minWidth={220}
      maxHeight={400}
      items={items}
      onItemSelect={(item) => onAppChange(item.value ?? item.id)}
      trigger={(
        <button
          type="button"
          className={OLA_APP_CARD}
          aria-label={`${currentApp?.label || '业务入口'}业务入口`}
          data-tfds-component="NavBar.AppSwitcher"
        >
          <OlaBusinessIcon iconName={currentApp?.iconSrc} />
          <span className={[OLA_NAV_LABEL_BASE, OLA_NAV_LABEL_CLASS.solid, OLA_NAV_TEXT_CLAMP].join(' ')}>
            {currentApp?.label || '抖音社区'}
          </span>
        </button>
      )}
    />
  );
}

export default function NavBar({
  platform,
  promptText = '',
  brandName,
  brandLogoName = null,
  appLabel = '抖音社区',
  appBusinesses = null,
  currentAppId,
  defaultAppId = null,
  onAppChange = null,
  moduleLabel = '平台首页',
  moduleIconName = 'home-smile-stroked',
  activeModule = true,
  navItems = null,
  activeNavId = null,
  activeUtilityId = null,
  selectedItemId = null,
  defaultSelectedItemId = null,
  showUtilityActions = false,
  utilityItems = null,
  onSelect = null,
  avatarType = 'image',
  avatarSrc = null,
  avatarAlt = '当前用户头像',
  className = '',
  style,
}) {
  const inferredPlatform = inferNavBarPlatformFromPrompt(promptText);
  const resolvedPlatform = platform === 'bytehi' ? 'bytehi' : (platform === 'ola' ? 'ola' : (inferredPlatform || 'ola'));
  const resolvedNavItems = Array.isArray(navItems) && navItems.length > 0
    ? navItems
    : (resolvedPlatform === 'bytehi' ? DEFAULT_BYTEHI_NAV_ITEMS : getDefaultOlaNavItems(moduleLabel, moduleIconName));
  const resolvedAppBusinesses = getResolvedOlaAppBusinesses(appBusinesses, appLabel);
  const resolvedUtilityItems = showUtilityActions
    ? (Array.isArray(utilityItems) && utilityItems.length > 0
        ? utilityItems
        : (resolvedPlatform === 'bytehi' ? DEFAULT_BYTEHI_FOOTER_ITEMS : DEFAULT_OLA_UTILITY_ITEMS))
    : [];
  const resolvedAvatarType = ['image', 'robot', 'fallback'].includes(avatarType) ? avatarType : 'image';
  const resolvedAvatarSrc = resolvedPlatform === 'bytehi' && resolvedAvatarType === 'image'
    ? (avatarSrc || BYTEHI_DEFAULT_MEMBER?.avatarSrc || null)
    : avatarSrc;
  const resolvedPlatformLogo = getNavBarPlatformLogo(brandLogoName);
  const platformDefaultBrandName = resolvedPlatform === 'bytehi' ? 'ByteHi' : 'OLA';
  const resolvedBrandName = (() => {
    if (typeof brandName === 'string' && brandName.length > 0) {
      // ByteHi 历史兼容：旧调用方常常会把 OLA 当占位文案，逐步引导改用真实名称或 brandLogoName
      if (resolvedPlatform === 'bytehi' && brandName === 'OLA') {
        return resolvedPlatformLogo ? resolvedPlatformLogo.brandName : 'ByteHi';
      }
      return brandName;
    }
    if (resolvedPlatformLogo) return resolvedPlatformLogo.brandName;
    return platformDefaultBrandName;
  })();
  const isAppControlled = currentAppId !== undefined;
  const isControlled = typeof selectedItemId === 'string' && selectedItemId.length > 0;
  const navItemsSignature = resolvedNavItems.map((item) => `${item.id}:${item.active ? '1' : '0'}`).join('|');
  const utilityItemsSignature = resolvedUtilityItems.map((item) => `${item.id}:${item.active ? '1' : '0'}`).join('|');
  const [isByteHiExpanded, setIsByteHiExpanded] = useState(false);
  const [internalAppId, setInternalAppId] = useState(defaultAppId || resolvedAppBusinesses[0]?.id || null);
  const [internalSelectedKey, setInternalSelectedKey] = useState(() => resolveInitialSelectedKey({
    platform: resolvedPlatform,
    selectedItemId,
    defaultSelectedItemId,
    activeUtilityId,
    activeNavId,
    activeModule,
    navItems: resolvedNavItems,
    utilityItems: resolvedUtilityItems,
  }));

  useEffect(() => {
    if (isControlled) return;
    setInternalSelectedKey(resolveInitialSelectedKey({
      platform: resolvedPlatform,
      selectedItemId,
      defaultSelectedItemId,
      activeUtilityId,
      activeNavId,
      activeModule,
      navItems: resolvedNavItems,
      utilityItems: resolvedUtilityItems,
    }));
  }, [
    isControlled,
    resolvedPlatform,
    selectedItemId,
    defaultSelectedItemId,
    activeUtilityId,
    activeNavId,
    activeModule,
    navItemsSignature,
    utilityItemsSignature,
  ]);

  useEffect(() => {
    if (isAppControlled) return;
    if (resolvedAppBusinesses.some((item) => item.id === internalAppId)) return;
    setInternalAppId(defaultAppId || resolvedAppBusinesses[0]?.id || null);
  }, [defaultAppId, internalAppId, isAppControlled, resolvedAppBusinesses]);

  const resolvedCurrentAppId = isAppControlled ? currentAppId : internalAppId;
  const currentApp = getAppBusiness(resolvedAppBusinesses, resolvedCurrentAppId);
  const selectedKey = isControlled ? selectedItemId : internalSelectedKey;

  function handleSelect(nextKey, section, item = null) {
    if (!isControlled) {
      setInternalSelectedKey(nextKey);
    }
    onSelect?.(nextKey, { section, item });
  }

  function handleAppChange(nextAppId) {
    const nextApp = getAppBusiness(resolvedAppBusinesses, nextAppId);
    if (!isAppControlled) {
      setInternalAppId(nextApp?.id || null);
    }
    onAppChange?.(nextApp?.id || null, { app: nextApp });
  }

  function handleByteHiExpand() {
    if (resolvedPlatform === 'bytehi') {
      setIsByteHiExpanded(true);
    }
  }

  function handleByteHiCollapse(event) {
    if (resolvedPlatform !== 'bytehi') return;
    if (event?.currentTarget?.contains?.(event.relatedTarget)) return;
    setIsByteHiExpanded(false);
  }

  if (resolvedPlatform === 'bytehi') {
    const widthClass = isByteHiExpanded ? 'w-[180px]' : 'w-[60px]';
    const isStatusActive = selectedKey === 'status';

    return (
      <aside
        className={[BYTEHI_ROOT, className].filter(Boolean).join(' ')}
        style={style}
        aria-label="ByteHi 业务导航栏"
        data-tfds-component="NavBar"
        onMouseEnter={handleByteHiExpand}
        onMouseLeave={() => setIsByteHiExpanded(false)}
        onFocusCapture={handleByteHiExpand}
        onBlurCapture={handleByteHiCollapse}
      >
        <div
          className={[BYTEHI_PANEL, widthClass].join(' ')}
          style={{ boxShadow: isByteHiExpanded ? BYTEHI_EXPANDED_SHADOW : 'none' }}
          data-tfds-component="NavBar.Panel"
        >
          <div className={BYTEHI_HEADER}>
            <ByteHiBrand brandName={resolvedBrandName} brandLogoName={brandLogoName} expanded={isByteHiExpanded} />
            <button
              type="button"
              className={[BYTEHI_SWITCH, isByteHiExpanded ? BYTEHI_SWITCH_STATE.expanded : BYTEHI_SWITCH_STATE.collapsed].join(' ')}
              aria-label="平台切换"
              data-tfds-component="NavBar.Switch"
            >
              <Icon name="dots-grid-stroked" size="sm" />
            </button>
          </div>

          <div className={BYTEHI_MAIN_NAV}>
            <div className={BYTEHI_NAV_LIST}>
              {resolvedNavItems.map((item) => {
                const isActive = selectedKey ? item.id === selectedKey : Boolean(item.active);
                return (
                  <ByteHiNavButton
                    key={item.id}
                    iconName={item.iconName}
                    expanded={isByteHiExpanded}
                    label={isByteHiExpanded ? item.label : ''}
                    current={isActive}
                    ariaLabel={item.label}
                    onClick={() => handleSelect(item.id, 'nav', item)}
                  />
                );
              })}
            </div>
          </div>

          <div className={BYTEHI_BOTTOM}>
            <div className={BYTEHI_FADE} aria-hidden="true" />

            <div className={BYTEHI_METRICS_WRAP}>
              <ByteHiMetricsCard
                current={isStatusActive}
                expanded={isByteHiExpanded}
                onClick={() => handleSelect('status', 'status', null)}
              />
            </div>

            {resolvedUtilityItems.length > 0 ? (
              <div className={BYTEHI_FOOTER_SECTION}>
                {resolvedUtilityItems.map((item) => {
                  const isActive = selectedKey ? item.id === selectedKey : item.id === activeUtilityId;
                  return (
                    <ByteHiFooterButton
                      key={item.id}
                      iconName={item.iconName}
                      expanded={isByteHiExpanded}
                      label={isByteHiExpanded ? item.label : ''}
                      current={isActive}
                      onClick={() => handleSelect(item.id, 'utility', item)}
                    />
                  );
                })}
              </div>
            ) : null}

            {isByteHiExpanded ? (
              <ByteHiAvatarInfo
                avatarType={resolvedAvatarType}
                avatarSrc={resolvedAvatarSrc}
                avatarAlt={avatarAlt}
              />
            ) : (
              <ByteHiCompactAvatar
                avatarType={resolvedAvatarType}
                avatarSrc={resolvedAvatarSrc}
                avatarAlt={avatarAlt}
              />
            )}
          </div>
        </div>
      </aside>
    );
  }

  return (
    <aside
      className={[OLA_ROOT, className].filter(Boolean).join(' ')}
      style={style}
      aria-label="业务导航栏"
      data-tfds-component="NavBar"
    >
      <div className={OLA_BRAND}>
        <Icon name={resolvedPlatformLogo ? resolvedPlatformLogo.logoName : 'hiai-logo'} size={28} aria-hidden="true" />
        <p className={OLA_BRAND_TEXT} style={OLA_BRAND_TEXT_STYLE}>{resolvedBrandName}</p>
      </div>

      <div className={OLA_BLOCK} style={{ overflow: 'visible' }}>
        <OlaBusinessSwitcher
          businesses={resolvedAppBusinesses}
          currentApp={currentApp}
          onAppChange={handleAppChange}
        />
      </div>

      <div className={OLA_DIVIDER_WRAP} aria-hidden="true">
        <div className={OLA_DIVIDER} />
      </div>

      <div className={OLA_MAIN_NAV}>
        {resolvedNavItems.map((item) => {
          const isActive = selectedKey ? item.id === selectedKey : Boolean(item.active);
          return (
            <OlaNavButton
              key={item.id}
              iconName={item.iconName}
              label={item.label}
              tone={isActive ? 'active' : 'default'}
              ariaLabel={item.label}
              current={isActive}
              onClick={() => handleSelect(item.id, 'nav', item)}
            />
          );
        })}
      </div>

      {resolvedUtilityItems.length > 0 ? (
        <div className={OLA_BLOCK}>
          {resolvedUtilityItems.map((item) => {
            const isActive = selectedKey ? item.id === selectedKey : item.id === activeUtilityId;
            return (
              <OlaNavButton
                key={item.id}
                iconName={item.iconName}
                iconSize="md"
                tone={isActive ? 'active' : 'utility'}
                ariaLabel={item.label}
                current={isActive}
                onClick={() => handleSelect(item.id, 'utility', item)}
              />
            );
          })}
        </div>
      ) : null}

      <div className={OLA_AVATAR_WRAP}>
        <Avatar
          type={resolvedAvatarType}
          size="xs"
          shape="round"
          src={avatarSrc}
          alt={avatarAlt}
        />
      </div>
    </aside>
  );
}
