/* ========== 主應用：KaiOS Studio ========== */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "kai",
  "density": "comfortable",
  "startPage": "today",
  "showActivity": true
}/*EDITMODE-END*/;

const REPO = { owner: 'pei760730', name: 'KaiOS-ContentSystem', branch: 'main', commit: '7b7df43a', version: '6.2' };

/* ========== 鎖定全域資料 ========== */
const ITEMS = window.__PIPELINE__;
const PATTERNS = window.__PATTERNS__;

const STATUSES = ['inbox', 'selected', '待拍', '剪輯中', '已上線', 'archived'];
const STAGE_LABELS = { inbox: '靈感箱', selected: '已選定', '待拍': '待拍', '剪輯中': '剪輯中', '已上線': '已上線', archived: '封存' };

const THRESHOLDS = { inbox: 7, selected: 14, '待拍': 7, '剪輯中': 7 };

/* ===== 計算逾期 ===== */
const isStuck = (item) => {
  const lim = THRESHOLDS[item.status];
  return lim && item.age != null && item.age > lim;
};

/* ===== 待辦資料 ===== */
const TODOS = [
  { text: '追蹤：買車進度（他們會去買車，持續追蹤）', emoji: '🚗', due: '2026-03-10', overdue: 57, note: '待 Kai 確認' },
  { text: '追蹤：Ruby 拍片意願（Round 4 題目已準備）', emoji: '🎬', due: '2026-03-10', overdue: 57, note: '待 Ruby 回覆' },
  { text: '釐清：VID-013 搬新辦公室與 VID-068 搬家啦的關係', emoji: '🔗', due: '2026-04-15', overdue: 21 },
  { text: '釐清：IG 51 則貼文 vs pipeline 54 已上線的差異', emoji: '📐', due: '2026-04-15', overdue: 21 },
  { text: '每週整理：IG/FB/YT 總粉絲、每部片觀看、後台截圖、逐字稿', emoji: '📊', due: null, routine: true },
];

/* ===== Skill 資料 ===== */
const SKILLS = [
  { name: 'flow-operator', tier: 'T1', desc: '四版腳本生成 (A/B/C/D)', uses: 8, can_run: true },
  { name: 'title-generator', tier: 'T1', desc: '爆款封面標題（10 組 5 類）', uses: 12, can_run: true },
  { name: 'humanizer', tier: 'T1', desc: '去 AI 味（24 模式偵測）', uses: 6, can_run: true },
  { name: 'hook-killer', tier: 'T1', desc: '三秒開頭金句（3 句精選）', uses: 9, can_run: true },
  { name: 'script-verifier', tier: 'T2', desc: '腳本品質驗證（5 項檢查）', uses: 4, can_run: true },
  { name: 'viral-knowledge', tier: 'T2', desc: '知識型短影音公式', uses: 2, can_run: true },
  { name: 'topic-researcher', tier: 'T2', desc: '靈感探索 + 品牌輿情', uses: 3, can_run: true },
  { name: 'sync-to-sheets', tier: 'T0', desc: '5 個分頁同步至 Google Sheets', uses: 24, can_run: true },
];

/* ========== Command Bar：頂部指揮列 ========== */
function CommandBar({ now, view, setView, query, setQuery, openCmdK, narrow }) {
  const tabs = [
    { id: 'today', icon: 'home', label: '命令室' },
    { id: 'pipeline', icon: 'flow', label: 'Pipeline' },
    { id: 'performance', icon: 'radar', label: '表現' },
    { id: 'formula', icon: 'formula', label: '公式' },
    { id: 'skills', icon: 'bolt', label: 'Skills' },
    { id: 'todo', icon: 'todo', label: '待辦' },
  ];

  return (
    <header style={{
      height: 52, flexShrink: 0,
      background: 'var(--bg-1)',
      borderBottom: '1px solid var(--line)',
      display: 'flex', alignItems: 'center', padding: '0 14px', gap: 14,
    }}>
      {/* Logo */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, flexShrink: 0 }}>
        <div style={{
          width: 28, height: 28, borderRadius: 7,
          background: 'linear-gradient(135deg, var(--kai-bright), var(--kai-deep))',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--mono)', fontWeight: 800, fontSize: 13, color: '#fff',
          boxShadow: '0 2px 8px var(--kai-glow)',
        }}>K</div>
        <div style={{ lineHeight: 1.1 }}>
          <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: '-0.01em' }}>KaiOS Studio</div>
          <div className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)' }}>v{REPO.version} · {REPO.commit}</div>
        </div>
      </div>

      {/* 主導航 Tab */}
      <nav style={{ display: 'flex', gap: 2, marginLeft: 14, padding: 3, background: 'var(--bg-2)', borderRadius: 8, border: '1px solid var(--line)', flexShrink: 0 }}>
        {tabs.map(t => {
          const active = view === t.id;
          return (
            <button
              key={t.id}
              onClick={() => setView(t.id)}
              style={{
                padding: narrow ? '6px 10px' : '6px 13px',
                borderRadius: 6,
                background: active ? 'var(--bg-4)' : 'transparent',
                color: active ? 'var(--ink-0)' : 'var(--ink-2)',
                fontSize: 12.5, fontWeight: active ? 600 : 500,
                display: 'inline-flex', alignItems: 'center', gap: 7,
                transition: 'all 0.15s var(--ease-out)',
                position: 'relative',
              }}
            >
              <Icon name={t.icon} size={14} />
              {!narrow && t.label}
              {active && <div style={{
                position: 'absolute', left: 12, right: 12, bottom: -4,
                height: 2, background: 'var(--kai-bright)', borderRadius: 2,
              }} />}
            </button>
          );
        })}
      </nav>

      {/* 全域搜尋 */}
      <button
        onClick={openCmdK}
        style={{
          flex: 1, maxWidth: 360, height: 32, padding: '0 12px',
          background: 'var(--bg-2)', border: '1px solid var(--line)',
          borderRadius: 8,
          display: 'flex', alignItems: 'center', gap: 9,
          color: 'var(--ink-3)', fontSize: 12.5,
          transition: 'border-color 0.12s',
        }}
        onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--line-strong)'}
        onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--line)'}
      >
        <Icon name="search" size={14} />
        <span style={{ flex: 1, textAlign: 'left' }}>搜尋影片、靈感、Skill、指令…</span>
        <Pill color="var(--ink-3)" bg="var(--bg-3)" border="var(--line)">⌘K</Pill>
      </button>

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

      {/* 右側狀態 */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 10px', background: 'var(--high-tint)', borderRadius: 6, border: '1px solid var(--high-glow)' }}>
          <Dot color="var(--high)" pulse size={6} />
          <span className="mono" style={{ fontSize: 11, color: 'var(--high)', fontWeight: 600 }}>已連線</span>
        </div>
        {!narrow && <div className="mono" style={{ fontSize: 11.5, color: 'var(--ink-2)' }}>{now}</div>}
        <a href="#" style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-2)', fontSize: 11.5, textDecoration: 'none' }}>
          <Icon name="git" size={13} />
          {!narrow && <span className="mono">{REPO.owner}/{REPO.name}</span>}
        </a>
      </div>
    </header>
  );
}

Object.assign(window, { CommandBar, TWEAK_DEFAULTS, REPO, ITEMS, PATTERNS, STATUSES, STAGE_LABELS, THRESHOLDS, isStuck, TODOS, SKILLS });
