// 產業分類頁（2026-05-10 新增）
// 列出 29 個 v8 題材，每張卡顯示股數、5 日強弱、手動覆寫數
// 點卡片 → 展開該題材所有股票（reuse SectorStockList 邏輯）

(function () {
  'use strict';

  const T = window.STOCK_TOKENS;

  function PageIndustry() {
    const vp = window.useViewport ? window.useViewport() : { isMobile: false };
    const live = window.STOCK_DATA_LIVE;
    const fullPool = live?.industry_pool_full;
    const sectorStrength = live?.sector_strength;
    const overrides = live?.industry_overrides;

    const [expanded, setExpanded] = React.useState(null);
    const [sortBy, setSortBy] = React.useState('strength'); // strength | count | name | overrides
    const [showAddTheme, setShowAddTheme] = React.useState(false);

    // 使用者新增的題材（localStorage 暫存，下版本升級成 D1）
    const [userThemes, setUserThemes] = React.useState(() => {
      try {
        return JSON.parse(localStorage.getItem('stocksense_user_themes') || '[]');
      } catch {
        return [];
      }
    });

    // 從 industry_pool.json 拿題材清單（label + aliases）
    // industry_pool.json 沒被前端 fetch，從 industry_pool_full._meta.themes_used 拿
    const baseThemes = fullPool?._meta?.themes_used
      || ['CPO', '特用化學', 'AI散熱', 'AI電源', 'HBM記憶體', '衛星通訊',
          '機械工具機', 'PCB', '台積電設備商', '晶圓代工', 'IC設計', 'IC封測',
          '被動元件', '連接器', '記憶體DRAM', '電動車供應鏈', '網通5G',
          '石英元件', '重電', 'MicroLED', '探針卡', '軍工', 'AI伺服器',
          'IC載板', '矽晶圓材料', '光學鏡頭', '化合物半導體', '無塵室廠務',
          '工業電腦'];

    // 合併：base + user-added（去重）
    const themeIds = [...baseThemes];
    for (const ut of userThemes) {
      if (!themeIds.includes(ut.id)) themeIds.push(ut.id);
    }

    const handleAddTheme = (newTheme) => {
      const next = [...userThemes, newTheme];
      setUserThemes(next);
      try {
        localStorage.setItem('stocksense_user_themes', JSON.stringify(next));
      } catch {}
      setShowAddTheme(false);
      if (window.showToast) {
        window.showToast(`✓ 已新增題材「${newTheme.id}」（暫存本機，重整後仍在）`, 'success');
      }
    };

    // 統計每題材
    const themeStats = themeIds
      .filter(id => id !== 'other')
      .map(id => {
        let count = 0;
        let overrideCount = 0;
        if (fullPool?.stocks) {
          for (const [code, info] of Object.entries(fullPool.stocks)) {
            if ((info.themes || []).includes(id)) {
              count++;
              if (info._user_overridden) overrideCount++;
            }
          }
        }
        const sectorData = (sectorStrength?.sectors || []).find(s => s.industry === id);
        const strength = sectorData?.strength_score || null;
        const chg5d = sectorData?.avg_chg_5d ?? null;

        return { id, count, overrideCount, strength, chg5d };
      });

    // 排序
    const sorted = [...themeStats].sort((a, b) => {
      if (sortBy === 'strength') {
        return (b.strength ?? -1) - (a.strength ?? -1);
      } else if (sortBy === 'count') {
        return b.count - a.count;
      } else if (sortBy === 'overrides') {
        return b.overrideCount - a.overrideCount;
      }
      return a.id.localeCompare(b.id);
    });

    const totalStocks = themeStats.reduce((s, t) => s + t.count, 0);
    const totalOverrides = themeStats.reduce((s, t) => s + t.overrideCount, 0);

    // 強弱顏色
    const strengthColor = (score) => {
      if (score == null) return { bg: T.surface2, fg: T.text3 };
      if (score >= 70) return { bg: 'oklch(0.92 0.10 30)', fg: 'oklch(0.45 0.18 30)' };
      if (score >= 55) return { bg: 'oklch(0.94 0.07 60)', fg: 'oklch(0.45 0.15 60)' };
      if (score >= 45) return { bg: 'oklch(0.95 0 0)', fg: 'oklch(0.40 0 0)' };
      if (score >= 30) return { bg: 'oklch(0.94 0.06 200)', fg: 'oklch(0.45 0.13 240)' };
      return { bg: 'oklch(0.93 0.10 245)', fg: 'oklch(0.40 0.18 245)' };
    };

    const SortBtn = ({ value, label }) => (
      <button onClick={() => setSortBy(value)} style={{
        padding: '5px 10px', fontSize: 11, fontWeight: 600,
        background: sortBy === value ? 'oklch(0.55 0.18 240)' : T.surface2,
        color: sortBy === value ? 'white' : T.text2,
        border: '1px solid ' + (sortBy === value ? 'oklch(0.55 0.18 240)' : T.border),
        borderRadius: 4, cursor: 'pointer', fontFamily: T.fontSans,
      }}>{label}</button>
    );

    return (
      <div style={{ padding: vp.isMobile ? 12 : 28 }}>
        <window.Card
          title="🗂 產業分類"
          subtitle={`v8 共 ${themeIds.length - 1} 個熱門題材 · ${totalStocks} 支股已分類 · ${totalOverrides} 支手動覆寫`}
        >
          {/* 排序切換 */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6, marginBottom: 16,
            paddingBottom: 12, borderBottom: '1px solid ' + T.border,
          }}>
            <span style={{ fontSize: 11, color: T.text3, marginRight: 4 }}>排序：</span>
            <SortBtn value="strength" label="強弱分數" />
            <SortBtn value="count" label="股數" />
            <SortBtn value="overrides" label="手動覆寫數" />
            <SortBtn value="name" label="題材名" />
          </div>

          {/* 「+ 新增題材」按鈕 */}
          <div style={{ marginBottom: 12, display: 'flex', justifyContent: 'flex-end' }}>
            <button onClick={() => setShowAddTheme(true)} style={{
              padding: '6px 14px', fontSize: 12, fontWeight: 600,
              background: 'oklch(0.55 0.18 240)', color: 'white',
              border: 'none', borderRadius: 4, cursor: 'pointer',
              fontFamily: T.fontSans,
            }}>+ 新增題材</button>
          </div>

          {/* 題材卡片 grid（inline 展開：點到的卡片下方用 grid-column: 1/-1 跨 row 展開）*/}
          <div style={{
            display: 'grid',
            gridTemplateColumns: vp.isMobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)',
            gap: 10,
          }}>
            {sorted.map(t => {
              const colors = strengthColor(t.strength);
              const isOpen = expanded === t.id;
              return (
                <React.Fragment key={t.id}>
                  <button
                    onClick={() => setExpanded(isOpen ? null : t.id)}
                    style={{
                      background: colors.bg,
                      border: '2px solid ' + (isOpen ? colors.fg : colors.fg + '33'),
                      borderRadius: 8, padding: '10px 12px',
                      cursor: 'pointer', textAlign: 'left',
                      fontFamily: 'inherit',
                      transition: 'border-color 0.15s',
                    }}>
                    <div style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                      marginBottom: 4,
                    }}>
                      <span style={{ fontSize: 12, fontWeight: 700, color: T.text }}>
                        {t.id}
                      </span>
                      <span style={{ fontSize: 10, color: colors.fg, fontWeight: 600 }}>
                        {isOpen ? '▼' : '▶'}
                      </span>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                      {t.strength != null ? (
                        <span style={{
                          fontSize: 18, fontWeight: 700, color: colors.fg,
                          fontFamily: T.fontMono,
                        }}>{t.strength.toFixed(0)}</span>
                      ) : (
                        <span style={{ fontSize: 11, color: T.text4 }}>無強弱資料</span>
                      )}
                      <span style={{ fontSize: 11, color: T.text3, fontFamily: T.fontMono }}>
                        {t.count} 支
                      </span>
                    </div>
                    {t.chg5d != null && (
                      <div style={{ fontSize: 10, color: T.text3, fontFamily: T.fontMono, marginTop: 3 }}>
                        5d {t.chg5d >= 0 ? '+' : ''}{t.chg5d}%
                      </div>
                    )}
                    {t.overrideCount > 0 && (
                      <div style={{
                        marginTop: 4, fontSize: 10,
                        color: 'oklch(0.40 0.18 130)',
                      }}>
                        ✏️ {t.overrideCount} 支手動覆寫
                      </div>
                    )}
                  </button>

                  {/* Inline 展開：跨整 row 顯示，緊接在被點的卡片下方 */}
                  {isOpen && window.SectorStockList && (
                    <div style={{ gridColumn: '1 / -1' }}>
                      <window.SectorStockList
                        industry={t.id}
                        onClose={() => setExpanded(null)}
                        editable={true}
                      />
                    </div>
                  )}
                </React.Fragment>
              );
            })}
          </div>

          {/* 新增題材 modal */}
          {showAddTheme && (
            <AddThemeModal
              existingIds={themeIds}
              onClose={() => setShowAddTheme(false)}
              onAdd={handleAddTheme}
            />
          )}
        </window.Card>
      </div>
    );
  }

  // 新增題材 modal
  function AddThemeModal({ existingIds, onClose, onAdd }) {
    const [id, setId] = React.useState('');
    const [label, setLabel] = React.useState('');
    const [aliases, setAliases] = React.useState('');
    const [error, setError] = React.useState('');

    const handleSubmit = () => {
      const trimmedId = id.trim();
      if (!trimmedId) {
        setError('題材 ID 必填');
        return;
      }
      if (existingIds.includes(trimmedId)) {
        setError(`題材「${trimmedId}」已存在`);
        return;
      }
      if (trimmedId === 'other') {
        setError('「other」是保留字，不能用');
        return;
      }
      onAdd({
        id:      trimmedId,
        label:   label.trim() || trimmedId,
        aliases: aliases.split(/[、,，\s]+/).filter(Boolean),
      });
    };

    return (
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
        zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16,
      }}>
        <div onClick={(e) => e.stopPropagation()} style={{
          background: T.surface, borderRadius: 8, padding: 20,
          maxWidth: 460, width: '100%',
          boxShadow: '0 20px 50px rgba(0,0,0,0.3)',
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginBottom: 16, paddingBottom: 12, borderBottom: '1px solid ' + T.border,
          }}>
            <div style={{ fontSize: 16, fontWeight: 700, color: T.text }}>
              + 新增題材
            </div>
            <button onClick={onClose} style={{
              background: 'none', border: 'none', fontSize: 20, cursor: 'pointer',
              color: T.text3,
            }}>✕</button>
          </div>

          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 12, color: T.text2, marginBottom: 4, fontWeight: 600 }}>
              題材 ID（必填，將用於分類）：
            </div>
            <input value={id} onChange={(e) => setId(e.target.value)}
              placeholder="例：量子運算 / 太陽能 / AI軟體" style={{
              width: '100%', padding: 8, fontSize: 13,
              border: '1px solid ' + T.border, borderRadius: 4,
              fontFamily: T.fontSans, background: T.surface, color: T.text,
            }} />
          </div>

          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 12, color: T.text2, marginBottom: 4, fontWeight: 600 }}>
              題材標籤（顯示用，可空 = 用 ID）：
            </div>
            <input value={label} onChange={(e) => setLabel(e.target.value)}
              placeholder="例：量子運算 / Quantum Computing" style={{
              width: '100%', padding: 8, fontSize: 13,
              border: '1px solid ' + T.border, borderRadius: 4,
              fontFamily: T.fontSans, background: T.surface, color: T.text,
            }} />
          </div>

          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 12, color: T.text2, marginBottom: 4, fontWeight: 600 }}>
              別名 / 關鍵字（用逗號或空格分隔，給 LLM 分類用）：
            </div>
            <input value={aliases} onChange={(e) => setAliases(e.target.value)}
              placeholder="例：量子, quantum, Q-bit, 量子電腦" style={{
              width: '100%', padding: 8, fontSize: 13,
              border: '1px solid ' + T.border, borderRadius: 4,
              fontFamily: T.fontSans, background: T.surface, color: T.text,
            }} />
          </div>

          <div style={{
            padding: 8, fontSize: 11, color: T.text3,
            background: T.surface2, borderRadius: 4, marginBottom: 12,
          }}>
            💡 提示：此版本暫存本機 localStorage（重整仍在，但不跨裝置）。
            下次升級會同步 D1 雲端 + 影響 LLM 分類。
          </div>

          {error && (
            <div style={{
              marginBottom: 12, padding: 8, fontSize: 11, color: T.down,
              background: T.downSoft, borderRadius: 4,
            }}>{error}</div>
          )}

          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={handleSubmit} style={{
              flex: 1, padding: '8px 16px', fontSize: 12, fontWeight: 600,
              background: 'oklch(0.55 0.18 240)', color: 'white',
              border: 'none', borderRadius: 4, cursor: 'pointer',
            }}>+ 新增</button>
            <button onClick={onClose} style={{
              padding: '8px 16px', fontSize: 12,
              background: T.surface2, color: T.text2,
              border: '1px solid ' + T.border, borderRadius: 4, cursor: 'pointer',
            }}>取消</button>
          </div>
        </div>
      </div>
    );
  }

  window.PageIndustry = PageIndustry;
  window.IndustryPage = PageIndustry;
  window.AddThemeModal = AddThemeModal;
})();
