// App shell — light theme, Chinese strings

const SHELL_NAV = [
  { id: 'overview', label: '總覽', icon: 'M3 12h18M3 6h18M3 18h18' },
  { id: 'brands', label: '品牌', icon: 'M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z' },
  { id: 'conversations', label: '對話', icon: 'M4 4h16v12H7l-3 3z' },
  { id: 'cost', label: '費用分析', icon: 'M3 21l5-9 4 4 8-12' },
  { id: 'tools', label: '工具品質', icon: 'M14 4l6 6-10 10H4v-6z', soon: true },
  { id: 'alerts', label: '警示規則', icon: 'M12 3l9 16H3z', soon: true },
  { id: 'audit', label: '稽核紀錄', icon: 'M5 4h14v16H5zM8 8h8M8 12h8M8 16h5', soon: true },
];

const TIME_PRESETS = [
  { id: 'today', label: '今天' },
  { id: '7d', label: '近 7 天' },
  { id: '30d', label: '近 30 天' },
  { id: 'month', label: '本月' },
  { id: 'last', label: '上月' },
  { id: 'custom', label: '自訂' },
];
const CHANNEL_OPTS = [
  { id: 'all', label: '全部' },
  { id: 'dashboard', label: '管理後台' },
  { id: 'line', label: 'LINE' },
];
const MODEL_OPTS = [
  { id: 'all', label: '全部' },
  { id: 'anthropic', label: 'Anthropic' },
  { id: 'openai', label: 'OpenAI' },
  { id: 'claude-haiku-4-5', label: 'claude-haiku-4-5' },
  { id: 'claude-sonnet-4-5', label: 'claude-sonnet-4-5' },
  { id: 'claude-opus-4-1', label: 'claude-opus-4-1' },
  { id: 'gpt-4.1', label: 'gpt-4.1' },
  { id: 'gpt-4.1-mini', label: 'gpt-4.1-mini' },
];

function Icon({ d, size = 14, stroke = 'currentColor', sw = 1.5 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <path d={d} />
    </svg>
  );
}

function TopBar({ env = 'staging', adminUser }) {
  const envCfg = {
    prod: { color: '#DC2626', label: '正式' },
    staging: { color: '#B45309', label: '預備' },
    dev: { color: '#15803D', label: '開發' },
  }[env];

  // 從 /api/me 拿到的真實員工資料；fallback 給 design-time 預覽
  const name = (adminUser && adminUser.name) || '—';
  const email = (adminUser && adminUser.email) || '';
  const initials = (() => {
    if (!adminUser || !adminUser.name) return '··';
    // 中文名取首字 + 英文取首字（如「謝湘漪 Vivian」→「謝V」）
    const parts = String(adminUser.name).trim().split(/\s+/);
    if (parts.length >= 2) {
      const last = parts[parts.length - 1];
      return parts[0].charAt(0) + (last.match(/[A-Za-z]/) ? last.charAt(0).toUpperCase() : '');
    }
    return String(adminUser.name).slice(0, 2);
  })();

  return (
    <header style={{
      height: 48, background: '#FFFFFF', borderBottom: '1px solid #E5E5E0',
      display: 'flex', alignItems: 'center', padding: '0 16px', flexShrink: 0,
      gap: 14,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{
          width: 22, height: 22, background: '#FFE600', borderRadius: 5,
          display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 800, color: '#17171A',
        }}>O</div>
        <span style={{ fontSize: 13, fontWeight: 600, color: '#17171A', letterSpacing: '-0.01em' }}>Ocard</span>
        <span style={{ fontSize: 11, color: '#9098A3', margin: '0 6px' }}>/</span>
        <span style={{ fontSize: 13, color: '#5C6470' }}>Agent 監控後台</span>
      </div>

      <div style={{ flex: 1 }}></div>

      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        padding: '3px 8px', borderRadius: 4,
        border: `1px solid ${envCfg.color}40`, background: `${envCfg.color}14`,
        fontSize: 10.5, color: envCfg.color, fontWeight: 600,
      }}>
        <span style={{ width: 5, height: 5, borderRadius: '50%', background: envCfg.color }}></span>
        環境：{envCfg.label}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingLeft: 12, borderLeft: '1px solid #E5E5E0' }}>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 11.5, color: '#17171A', fontWeight: 500 }}>{name}</div>
          {email && <div style={{ fontSize: 10, color: '#9098A3', fontFamily: 'JetBrains Mono' }}>{email}</div>}
        </div>
        <div style={{
          width: 28, height: 28, borderRadius: '50%',
          background: 'linear-gradient(135deg, #FFE600, #C8B400)',
          display: 'grid', placeItems: 'center',
          color: '#17171A', fontSize: 11, fontWeight: 700,
        }}>{initials}</div>
      </div>
    </header>
  );
}

function LeftRail({ route, setRoute }) {
  return (
    <nav style={{
      width: 200, background: '#F7F7F5', borderRight: '1px solid #E5E5E0',
      flexShrink: 0, display: 'flex', flexDirection: 'column',
      padding: '12px 0',
    }}>
      <div style={{ padding: '6px 16px 8px', fontSize: 9.5, color: '#9098A3', textTransform: 'uppercase', letterSpacing: '0.12em', fontFamily: 'JetBrains Mono' }}>
        Monitoring
      </div>
      {SHELL_NAV.map(n => {
        const active = route === n.id;
        return (
          <button key={n.id} onClick={() => !n.soon && setRoute(n.id)} disabled={n.soon}
            style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '7px 14px', margin: '0 8px',
              borderRadius: 5,
              fontSize: 12.5, color: active ? '#17171A' : n.soon ? '#C5C5C0' : '#5C6470',
              background: active ? '#FFFFFF' : 'transparent',
              borderLeft: active ? '2px solid #FFE600' : '2px solid transparent',
              paddingLeft: active ? 12 : 14,
              cursor: n.soon ? 'not-allowed' : 'pointer',
              fontWeight: active ? 600 : 400,
              boxShadow: active ? '0 1px 2px rgba(0,0,0,0.04)' : 'none',
              textAlign: 'left',
            }}
            onMouseEnter={(e) => { if (!active && !n.soon) e.currentTarget.style.background = '#F0F0EE'; }}
            onMouseLeave={(e) => { if (!active && !n.soon) e.currentTarget.style.background = 'transparent'; }}
          >
            <Icon d={n.icon} size={14} sw={1.5} />
            <span style={{ flex: 1 }}>{n.label}</span>
            {n.soon && <span style={{ fontSize: 9, color: '#C5C5C0', fontFamily: 'JetBrains Mono' }}>即將推出</span>}
          </button>
        );
      })}

      <div style={{ marginTop: 'auto', padding: '12px 16px', borderTop: '1px solid #E5E5E0' }}>
        <div style={{ fontSize: 9.5, color: '#9098A3', textTransform: 'uppercase', letterSpacing: '0.12em', fontFamily: 'JetBrains Mono', marginBottom: 6 }}>系統狀態</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: '#5C6470' }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#15803D' }}></span>
          全部端點正常
        </div>
        <div style={{ marginTop: 4, fontSize: 10, color: '#9098A3', fontFamily: 'JetBrains Mono' }}>p99 延遲 1.4s</div>
      </div>
    </nav>
  );
}

function FilterBar({ filters, setFilters, brandsList }) {
  const [brandOpen, setBrandOpen] = React.useState(false);
  const [brandQuery, setBrandQuery] = React.useState('');
  const filteredBrands = brandsList.filter(b =>
    b.name.toLowerCase().includes(brandQuery.toLowerCase()) || b.id.includes(brandQuery.toLowerCase())
  );
  const selectedCount = filters.brands.length;

  return (
    <div style={{
      height: 48, background: '#FFFFFF', borderBottom: '1px solid #E5E5E0',
      display: 'flex', alignItems: 'center', padding: '0 16px', gap: 8,
      flexShrink: 0, position: 'sticky', top: 0, zIndex: 10,
    }}>
      <div style={{ display: 'flex', background: '#F7F7F5', border: '1px solid #E5E5E0', borderRadius: 5, overflow: 'hidden' }}>
        {TIME_PRESETS.map(p => {
          const isCustom = p.id === 'custom';
          return (
            <button key={p.id}
              disabled={isCustom}
              title={isCustom ? '即將推出：自訂日期區間' : ''}
              onClick={() => { if (!isCustom) setFilters({ ...filters, range: p.id }); }}
              style={{
                padding: '5px 10px', fontSize: 11.5,
                color: isCustom ? '#C5C5C0' : (filters.range === p.id ? '#7A6E00' : '#5C6470'),
                background: filters.range === p.id ? '#FFFAB8' : 'transparent',
                borderRight: '1px solid #E5E5E0',
                fontWeight: filters.range === p.id ? 600 : 400,
                cursor: isCustom ? 'not-allowed' : 'pointer',
              }}
            >{p.label}</button>
          );
        })}
      </div>

      {/* 以下三個 dropdown 後端尚未支援篩選參數（brands / channel / model），先 disable 以免誤導 */}
      <div style={{ position: 'relative' }}>
        <button
          disabled
          title="即將推出：依品牌篩選資料"
          style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '5px 10px', fontSize: 11.5,
            background: '#F7F7F5', border: '1px solid #E5E5E0', borderRadius: 5,
            color: '#C5C5C0', cursor: 'not-allowed',
          }}>
          品牌：<span>全部</span>
          <Icon d="M6 9l6 6 6-6" size={10} />
        </button>
        {false && brandOpen && (
          <div style={{
            position: 'absolute', top: 32, left: 0, width: 280,
            background: '#FFFFFF', border: '1px solid #D4D4CF', borderRadius: 6,
            boxShadow: '0 12px 32px rgba(0,0,0,0.12)', zIndex: 50, padding: 6,
          }}>
            <input value={brandQuery} onChange={(e) => setBrandQuery(e.target.value)}
              placeholder="搜尋品牌..."
              style={{
                width: '100%', padding: '6px 8px', fontSize: 12,
                background: '#F7F7F5', border: '1px solid #E5E5E0', borderRadius: 4,
                color: '#17171A', outline: 'none', marginBottom: 4,
              }} />
            <div style={{ maxHeight: 240, overflow: 'auto' }} className="scroll">
              {filteredBrands.slice(0, 30).map(b => {
                const checked = filters.brands.includes(b.id);
                return (
                  <label key={b.id} style={{
                    display: 'flex', alignItems: 'center', gap: 8,
                    padding: '4px 6px', borderRadius: 3, cursor: 'pointer',
                    fontSize: 11.5, color: '#17171A',
                  }}
                    onMouseEnter={(e) => e.currentTarget.style.background = '#F7F7F5'}
                    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                  >
                    <input type="checkbox" checked={checked} onChange={() => {
                      const next = checked ? filters.brands.filter(x => x !== b.id) : [...filters.brands, b.id];
                      setFilters({ ...filters, brands: next });
                    }} style={{ accentColor: '#FFE600' }} />
                    <span style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{b.name}</span>
                    <span style={{ fontFamily: 'JetBrains Mono', fontSize: 10, color: '#9098A3' }}>{b.id}</span>
                  </label>
                );
              })}
            </div>
            {filters.brands.length > 0 && (
              <button onClick={() => setFilters({ ...filters, brands: [] })}
                style={{ width: '100%', padding: '6px 8px', fontSize: 11, color: '#9098A3', borderTop: '1px solid #E5E5E0', marginTop: 4 }}>
                清除選擇
              </button>
            )}
          </div>
        )}
      </div>

      <Dropdown label="渠道" value={filters.channel} options={CHANNEL_OPTS}
        onChange={v => setFilters({ ...filters, channel: v })} disabled hint="即將推出：依渠道篩選" />
      <Dropdown label="模型" value={filters.model} options={MODEL_OPTS}
        onChange={v => setFilters({ ...filters, model: v })} disabled hint="即將推出：依模型篩選" />

      <div style={{ flex: 1 }}></div>

      <div style={{ fontSize: 10.5, color: '#9098A3', fontFamily: 'JetBrains Mono' }}>
        ?range={filters.range}&brands={filters.brands.length || 'all'}&channel={filters.channel}&model={filters.model}
      </div>
    </div>
  );
}

function Dropdown({ label, value, options, onChange, disabled, hint }) {
  const [open, setOpen] = React.useState(false);
  const cur = options.find(o => o.id === value) || options[0];
  return (
    <div style={{ position: 'relative' }}>
      <button
        disabled={disabled}
        title={disabled ? (hint || '') : ''}
        onClick={() => { if (!disabled) setOpen(!open); }}
        style={{
          display: 'flex', alignItems: 'center', gap: 6,
          padding: '5px 10px', fontSize: 11.5,
          background: '#F7F7F5', border: '1px solid #E5E5E0', borderRadius: 5,
          color: disabled ? '#C5C5C0' : '#5C6470',
          cursor: disabled ? 'not-allowed' : 'pointer',
        }}>
        {label}：<span style={{ color: disabled ? '#C5C5C0' : (cur.id === 'all' ? '#9098A3' : '#17171A') }}>{cur.label}</span>
        <Icon d="M6 9l6 6 6-6" size={10} />
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: 32, left: 0, minWidth: 180,
          background: '#FFFFFF', border: '1px solid #D4D4CF', borderRadius: 6,
          boxShadow: '0 12px 32px rgba(0,0,0,0.12)', zIndex: 50, padding: 4,
        }}>
          {options.map(o => (
            <button key={o.id} onClick={() => { onChange(o.id); setOpen(false); }}
              style={{
                display: 'block', width: '100%', textAlign: 'left',
                padding: '5px 8px', fontSize: 11.5, borderRadius: 3,
                color: value === o.id ? '#7A6E00' : '#17171A',
                background: value === o.id ? '#FFFAB8' : 'transparent',
                fontFamily: o.id.includes('-') || o.id.includes('.') ? 'JetBrains Mono' : 'inherit',
                fontWeight: value === o.id ? 600 : 400,
              }}
              onMouseEnter={(e) => { if (value !== o.id) e.currentTarget.style.background = '#F7F7F5'; }}
              onMouseLeave={(e) => { if (value !== o.id) e.currentTarget.style.background = 'transparent'; }}
            >{o.label}</button>
          ))}
        </div>
      )}
    </div>
  );
}

window.Icon = Icon;
window.TopBar = TopBar;
window.LeftRail = LeftRail;
window.FilterBar = FilterBar;
