/* ===== Shared components: icons, sidebar, topbar, thinking panel ===== */

const Icon = ({ name, className = 'icon' }) => {
  const paths = {
    home:    <><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></>,
    memory:  <><circle cx="12" cy="5" r="2"/><circle cx="5" cy="12" r="2"/><circle cx="19" cy="12" r="2"/><circle cx="12" cy="19" r="2"/><path d="M12 7v10M7 12h10"/></>,
    radar:   <><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1"/><path d="M12 3v3M21 12h-3"/></>,
    strategy:<><path d="M3 12h3l3-8 6 16 3-8h3"/></>,
    creator: <><circle cx="9" cy="8" r="3"/><circle cx="17" cy="10" r="2"/><path d="M3 20c0-3 3-5 6-5s6 2 6 5M15 18c0-2 2-3 4-3s3 1 3 3"/></>,
    brief:   <><rect x="4" y="3" width="16" height="18" rx="1"/><path d="M8 8h8M8 12h8M8 16h5"/></>,
    content: <><rect x="3" y="4" width="14" height="10" rx="1"/><path d="M7 18h14M7 18l2-4M21 18l-2-4"/></>,
    monitor: <><path d="M3 12l4-4 4 4 4-8 6 12"/></>,
    review:  <><path d="M21 12a9 9 0 11-3-6.7M21 4v5h-5"/></>,
    report:  <><rect x="4" y="3" width="16" height="18" rx="1.5"/><path d="M8 8h8M8 17V12M12 17v-7M16 17v-4"/></>,
    search:  <><circle cx="11" cy="11" r="6"/><path d="M16 16l4 4"/></>,
    settings:<><path d="M4 6h10M18 6h2M4 12h2M10 12h10M4 18h11M19 18h1"/><circle cx="16" cy="6" r="2"/><circle cx="8" cy="12" r="2"/><circle cx="17" cy="18" r="2"/></>,
    edit:    <><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 013 3L7 19l-4 1 1-4z"/></>,
    save:    <><path d="M5 3h12l2 2v16H5z"/><path d="M8 3v6h8V3M8 21v-7h8v7"/></>,
    bell:    <><path d="M6 8a6 6 0 1112 0c0 7 3 8 3 8H3s3-1 3-8zM10 21a2 2 0 004 0"/></>,
    plus:    <><path d="M12 5v14M5 12h14"/></>,
    arrow:   <><path d="M5 12h14M13 6l6 6-6 6"/></>,
    check:   <><path d="M5 12l5 5 9-11"/></>,
    x:       <><path d="M6 6l12 12M6 18L18 6"/></>,
    upload:  <><path d="M12 4v12M6 10l6-6 6 6M4 20h16"/></>,
    refresh: <><path d="M21 12a9 9 0 11-2.6-6.4M21 4v6h-6"/></>,
    moon:    <><path d="M21 14.5A8.5 8.5 0 119.5 3a6.5 6.5 0 0011.5 11.5z"/></>,
    sun:     <><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></>,
    doc:     <><path d="M14 3H7a2 2 0 00-2 2v14a2 2 0 002 2h10a2 2 0 002-2V8zM14 3v5h5"/></>,
    spark:   <><path d="M12 3l2 5 5 2-5 2-2 5-2-5-5-2 5-2z"/></>,
    chevron: <><path d="M8 4l7 8-7 8"/></>,
    drag:    <><circle cx="9" cy="6" r="1.3"/><circle cx="15" cy="6" r="1.3"/><circle cx="9" cy="12" r="1.3"/><circle cx="15" cy="12" r="1.3"/><circle cx="9" cy="18" r="1.3"/><circle cx="15" cy="18" r="1.3"/></>,
    play:    <><path d="M6 4l14 8-14 8z"/></>,
    warn:    <><path d="M12 3l10 18H2zM12 10v5M12 18v.5"/></>,
    lightning:<><path d="M13 2L4 14h7l-1 8 9-12h-7z"/></>,
    external:<><path d="M15 3h6v6M21 3l-8 8M19 13v7H5V5h7"/></>,
    filter:  <><path d="M3 5h18l-7 8v6l-4-2v-4z"/></>,
  };
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      {paths[name]}
    </svg>
  );
};

const Sidebar = ({ current, onNav, collapsed = false, onToggleCollapsed, workspace, workspaceBrands = WORKSPACE_BRANDS, onWorkspaceChange }) => {
  const [workspaceOpen, setWorkspaceOpen] = React.useState(false);
  const brand = workspaceBrands.find(item => item.id === workspace?.brandId) || workspaceBrands[0];
  const updateBrand = (brandId) => {
    const nextBrand = workspaceBrands.find(item => item.id === brandId) || workspaceBrands[0];
    onWorkspaceChange?.({ brandId: nextBrand.id });
  };
  return (
  <aside className={`sidebar ${collapsed ? 'collapsed' : ''}`}>
    <div className="brand-mark">
      <div className="logo">A</div>
      <div className="wordmark">
        <b>WantAi OS</b>
        <small>Workspace OS · v{window.APP_VERSION || '0.80'}</small>
      </div>
      <button className="sidebar-toggle" title={collapsed ? '展开侧边栏' : '折叠侧边栏'} aria-label={collapsed ? '展开侧边栏' : '折叠侧边栏'} onClick={onToggleCollapsed}>
        <Icon name="chevron" className="icon sm" style={collapsed ? {} : {transform:'rotate(180deg)'}}/>
      </button>
    </div>

    <div className="workspace-switcher">
      <button
        className="workspace-trigger"
        onClick={() => setWorkspaceOpen(v => !v)}
        title={brand?.name || 'Workspace'}
        aria-label="切换 Workspace 品牌"
      >
        <Icon name="brief" className="icon sm"/>
        <span>
          <b>{brand?.name || 'Workspace'}</b>
          <small>Brand Memory</small>
        </span>
        <Icon name="chevron" className="icon sm workspace-caret"/>
      </button>
      {workspaceOpen && (
        <div className="workspace-popover">
          <div className="workspace-popover-head">
            <b>Workspace</b>
            <button className="btn-icon" title="关闭" onClick={() => setWorkspaceOpen(false)}>
              <Icon name="x" className="icon sm"/>
            </button>
          </div>
          <label>品牌</label>
          <div className="workspace-choice-list">
            {workspaceBrands.map(item => (
              <button key={item.id} className={item.id === brand.id ? 'active' : ''} onClick={() => updateBrand(item.id)}>
                <b>{item.name}</b>
                <small>{item.cn || item.name} · {(item.products || []).length} products</small>
              </button>
            ))}
          </div>
          <div className="workspace-note">产品不在 Workspace 层切换；同一品牌下的多个产品共用同一份品牌记忆，并在具体任务中绑定。</div>
        </div>
      )}
    </div>

    <div className="nav-section-title">Workspace</div>
    {NAV.slice(0, 1).map(n => (
      <div key={n.id} className={`nav-item ${current === n.id ? 'active' : ''}`} onClick={() => onNav(n.id)}>
        <span className="nav-num">{n.num}</span>
        <Icon name="home" className="icon sm"/>
        <span>仪表盘</span>
      </div>
    ))}

    <div className="nav-section-title">记忆 · 感知</div>
    {NAV.slice(1, 3).map(n => (
      <div key={n.id} className={`nav-item ${current === n.id ? 'active' : ''}`} onClick={() => onNav(n.id)}>
        <span className="nav-num">{n.num}</span>
        <Icon name={n.id === 'memory' ? 'memory' : 'radar'} className="icon sm"/>
        <span>{n.label.split(' · ')[0]}</span>
        {n.badge && <span className="nav-badge">{n.badge}</span>}
      </div>
    ))}

    <div className="nav-section-title">Campaign 中枢</div>
    {NAV.slice(3, 4).map(n => (
      <div key={n.id} className={`nav-item ${current === n.id ? 'active' : ''}`} onClick={() => onNav(n.id)}>
        <span className="nav-num">{n.num}</span>
        <Icon name="strategy" className="icon sm"/>
        <span>策略推演</span>
        {n.badge && <span className="nav-badge">{n.badge}</span>}
      </div>
    ))}

    <div className="nav-section-title">执行编排</div>
    {NAV.slice(4, 8).map(n => (
      <div key={n.id} className={`nav-item ${current === n.id ? 'active' : ''}`} onClick={() => onNav(n.id)}>
        <span className="nav-num">{n.num}</span>
        <Icon name={{creators:'creator',brief:'brief',content:'content',monitor:'monitor'}[n.id]} className="icon sm"/>
        <span>{n.label.split(' · ')[0]}</span>
        {n.badge && <span className="nav-badge">{n.badge}</span>}
      </div>
    ))}

    <div className="nav-section-title">学习闭环</div>
    {NAV.slice(8, 10).map(n => (
      <div key={n.id} className={`nav-item ${current === n.id ? 'active' : ''}`} onClick={() => onNav(n.id)}>
        <span className="nav-num">{n.num}</span>
        <Icon name={n.id === 'reports' ? 'report' : 'review'} className="icon sm"/>
        <span>{n.label.split(' · ')[0]}</span>
      </div>
    ))}

    <div className="nav-section-title">内容工厂</div>
    {NAV.slice(10).map(n => (
      <div key={n.id} className={`nav-item ${current === n.id ? 'active' : ''}`} onClick={() => onNav(n.id)}>
        <span className="nav-num">{n.num}</span>
        <Icon name="doc" className="icon sm"/>
        <span>{n.label.split(' · ')[0]}</span>
        {n.badge && <span className="nav-badge">{n.badge}</span>}
      </div>
    ))}

    <div className="sidebar-footer">
      <div className="avatar">QH</div>
      <div style={{display:'flex', flexDirection:'column', lineHeight:1.15}}>
        <span style={{fontSize:12}}>启航 · 策略</span>
        <small>STUDIO · MONTX</small>
      </div>
    </div>
  </aside>
  );
};

const Topbar = ({ crumb, campaign, onToggleThinking, thinkingOpen, theme = 'light', themeMode = 'system', onToggleTheme }) => (
    <div className="topbar">
      <div className="breadcrumb">
        <span className="current">{crumb}</span>
      </div>
      <span className="chip live"><span className="dot"></span>{/报表中心|社媒资产/.test(crumb || '') ? '社媒资产同步 · Live' : /仪表盘/.test(crumb || '') ? 'Workspace 同步 · Live' : 'Campaign 中枢 · Active'}</span>
      <div className="topbar-actions">
        <div className="search" style={{width:220}}>
          <Icon name="search" className="icon sm"/>
          <input className="input" placeholder="搜索品牌记忆 / 达人 / 内容…"/>
        </div>
        <button className="btn-icon" title="通知"><Icon name="bell" className="icon sm"/></button>
        <button className="btn-icon" title="设置"><Icon name="settings" className="icon sm"/></button>
        <button
          className={`btn-icon theme-toggle ${theme === 'dark' ? 'active' : ''}`}
          title={theme === 'dark' ? `切换到日间模式${themeMode === 'system' ? ' · 当前跟随系统' : ''}` : `切换到黑夜模式${themeMode === 'system' ? ' · 当前跟随系统' : ''}`}
          aria-label={theme === 'dark' ? '切换到日间模式' : '切换到黑夜模式'}
          aria-pressed={theme === 'dark'}
          onClick={onToggleTheme}
        >
          <Icon name={theme === 'dark' ? 'sun' : 'moon'} className="icon sm"/>
        </button>
        <button className={`btn ${thinkingOpen ? '' : 'primary'} sm`} onClick={onToggleThinking}>
          <span className="orb" style={{width:6,height:6,borderRadius:'50%',background:'oklch(0.75 0.15 155)', display:'inline-block', marginRight:4}}></span>
          {thinkingOpen ? '隐藏思考' : '显示思考'}
        </button>
      </div>
    </div>
);

const ThinkingPanel = ({ page }) => {
  const CustomRail = page === 'longform' ? window.LongformThinkingRail : null;
  if (CustomRail) return <CustomRail/>;

  const lines = THINKING[page] || [];
  const [visible, setVisible] = React.useState(0);
  const [tick, setTick] = React.useState(0);

  React.useEffect(() => {
    setVisible(0);
    const int = setInterval(() => {
      setVisible(v => {
        if (v >= lines.length) { clearInterval(int); return v; }
        return v + 1;
      });
    }, 220);
    return () => clearInterval(int);
  }, [page]);

  React.useEffect(() => {
    const int = setInterval(() => setTick(t => t + 1), 1000);
    return () => clearInterval(int);
  }, []);

  const bodyRef = React.useRef(null);
  React.useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [visible]);

  return (
    <aside className="thinking">
      <div className="thinking-header">
        <span className="orb"></span>
        <h3>Orchestrator · 思考过程</h3>
        <span style={{marginLeft:'auto',color:'oklch(0.55 0.008 80)',fontSize:10}}>{page.toUpperCase()}</span>
      </div>
      <div className="thinking-body" ref={bodyRef}>
        {lines.slice(0, visible).map((l, i) => (
          <div key={i} className={`think-line ${l.head ? 'head' : ''} ${l.warn ? 'warn' : ''} ${l.ok ? 'ok' : ''}`}>
            {!l.head && <span className="t">{l.t}</span>}
            {!l.head && <span className="src">{l.src}</span>}
            <span className="msg">{l.head ? `━ ${l.msg} ━━━━━━━━━━━` : l.msg}</span>
          </div>
        ))}
        {visible < lines.length && (
          <div className="think-line">
            <span className="t">·</span>
            <span className="src">orchestrator</span>
            <span className="msg">思考中{'.'.repeat((tick % 3) + 1)}</span>
          </div>
        )}
      </div>
      <div className="think-status">
        <span className="stat-dot"></span>
        <span>12 agents online</span>
        <span style={{marginLeft:'auto'}}>tokens: 42,180</span>
      </div>
    </aside>
  );
};

Object.assign(window, { Icon, Sidebar, Topbar, ThinkingPanel });
