(function(){
// 產業/題材分析
// 接線：live.themes.themes（產業熱度從 heat 欄位取）
const T = window.STOCK_TOKENS;

// ── DataMode 標示 ────────────────────────────────────────────────────────────
function DataModeBadge() {
  const live = window.STOCK_DATA_LIVE;
  const isLive = live.loaded && live.themes;
  const dateStr = live.themes && live.themes.date ? live.themes.date : '';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 4,
      fontSize: 10, color: T.text3, fontFamily: T.fontMono }}>
      <span style={{
        display: 'inline-block', width: 6, height: 6, borderRadius: 3,
        background: isLive ? 'oklch(0.7 0.15 155)' : 'oklch(0.7 0 0)',
      }} />
      {isLive ? ('LIVE ' + dateStr) : 'DEMO'}
    </div>
  );
}

function SectorPage() {
  const vp = window.useViewport();
  const live = window.STOCK_DATA_LIVE;

  // 優先用 live.themes 轉換成 sectors 格式，無資料則空陣列
  const sectors = (live.loaded && live.themes && live.themes.themes)
    ? live.themes.themes.map(th => ({
        name: th.name,
        chg: +(th.heat * 0.5).toFixed(2),   // heat(1-10) → 估算漲幅
        momentum: th.heat * 10,
        news: th.stocks ? th.stocks.length : 0,
        hot: th.heat >= 7,
        stocks: th.stocks || [],
        trigger: th.trigger || '',
      }))
    : [];

  const [selected, setSelected] = React.useState(sectors[0] ? sectors[0].name : '');
  const selectedSector = sectors.find(s => s.name === selected) || sectors[0];

  if (sectors.length === 0) {
    return (
      <div style={{ padding: 24 }}>
        <window.EmptyState
          title="題材資料尚未更新"
          hint="明天 08:00 自動更新"
        />
      </div>
    );
  }

  const pad = vp.isMobile ? 12 : 24;
  const tileCount = vp.isMobile ? Math.min(sectors.length, 3) : Math.min(sectors.length, 9);

  return (
    <div style={{ padding: pad, display: 'flex', flexDirection: 'column', gap: vp.isMobile ? 12 : 16 }}>
      {/* AI 輪動雷達 */}
      <window.Card title="AI 題材輪動雷達" ai
        subtitle="動能 = 法人買超 × 新聞熱度 × 漲幅"
        action={<div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          <DataModeBadge />
          {!vp.isMobile && <><window.Btn variant="ghost" active>3 日</window.Btn>
          <window.Btn variant="ghost">1 週</window.Btn>
          <window.Btn variant="ghost">1 月</window.Btn></>}
        </div>}
        padding={vp.isMobile ? 12 : 20}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: vp.isMobile
            ? 'repeat(2, 1fr)'
            : 'repeat(' + tileCount + ', 1fr)',
          gap: vp.isMobile ? 8 : 8,
        }}>
          {sectors.map(s => (
            <SectorTile key={s.name} s={s} active={selected === s.name} onClick={() => setSelected(s.name)} vp={vp} />
          ))}
        </div>
        <window.AINote title="本週輪動觀察" compact>
          {live.loaded && live.themes && live.themes.themes
            ? (live.themes.themes[0]
                ? ('熱門題材：' + live.themes.themes.slice(0, 3).map(t => t.name).join('、') + '。')
                : '暫無題材資料。')
            : '暫無題材資料。'}
        </window.AINote>
      </window.Card>

      {/* 題材詳情 */}
      {selectedSector && (
        <div style={{
          display: 'grid',
          gridTemplateColumns: vp.isMobile ? '1fr' : '1fr 360px',
          gap: 16,
        }}>
          <window.Card title={selected + ' · 題材詳情'} padding={0}>
            <div style={{
              padding: vp.isMobile ? '12px 16px' : 20,
              borderBottom: '1px solid ' + T.border,
              display: 'grid',
              gridTemplateColumns: vp.isMobile ? '1fr 1fr' : 'repeat(4, 1fr)',
              gap: vp.isMobile ? 8 : 12,
            }}>
              <Kpi label="題材動能" v={String(selectedSector ? selectedSector.momentum : '—')} sub="/100" up />
              <Kpi label="今日漲幅" v={(selectedSector ? (window.sign(selectedSector.chg) + selectedSector.chg.toFixed(2)) : '—') + '%'} up />
              <Kpi label="相關個股" v={String(selectedSector && selectedSector.stocks ? selectedSector.stocks.length : '—')} sub="檔" />
              <Kpi label="觸發事件" v={selectedSector && selectedSector.trigger ? selectedSector.trigger.slice(0, 10) : '—'} />
            </div>

            <div style={{ padding: '12px 20px', borderBottom: '1px solid ' + T.border,
              fontSize: 11, color: T.text3, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>
              {selectedSector && selectedSector.trigger ? ('觸發：' + selectedSector.trigger) : '產業鏈 · 個股清單'}
            </div>

            {selectedSector && selectedSector.stocks && selectedSector.stocks.length > 0 ? (
              <LiveSectorChain stocks={selectedSector.stocks} name={selected} />
            ) : (
              <div style={{ padding: 24, textAlign: 'center', color: T.text3, fontSize: 12 }}>
                此題材暫無個股清單
              </div>
            )}
          </window.Card>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <window.Card title="輪動歷史" padding={14}>
              <div style={{ fontSize: 11, color: T.text3, marginBottom: 8 }}>近 30 天動能變化</div>
              <window.Sparkline data={window.genSeries(30, 92, 0.005, 0.04)} w={310} h={60} fill strokeWidth={2} />
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 10,
                fontFamily: T.fontMono, color: T.text3 }}>
                <span>03/29</span><span>04/13</span><span>04/28</span>
              </div>
            </window.Card>

            <window.Card title="AI 輪動推斷" ai padding={14}>
              <div style={{ fontSize: 11, color: T.text3, marginBottom: 6, fontWeight: 600,
                letterSpacing: 0.3, textTransform: 'uppercase' }}>下一個可能熱題</div>
              {(live.loaded && live.themes && live.themes.themes
                ? live.themes.themes.slice(1, 4).map(t => ({
                    name: t.name,
                    conf: t.heat * 9,
                    why: t.trigger || '題材延伸',
                  }))
                : []
              ).map(r => (
                <div key={r.name} style={{ marginBottom: 10 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 3 }}>
                    <span style={{ fontWeight: 600, color: T.text }}>{r.name}</span>
                    <span style={{ fontFamily: T.fontMono, color: T.ai, fontWeight: 600 }}>{r.conf}%</span>
                  </div>
                  <div style={{ height: 4, background: T.hover, borderRadius: 2, marginBottom: 4 }}>
                    <div style={{ width: r.conf + '%', height: '100%', background: T.ai, borderRadius: 2 }} />
                  </div>
                  <div style={{ fontSize: 10, color: T.text3 }}>{r.why}</div>
                </div>
              ))}
            </window.Card>
          </div>
        </div>
      )}
    </div>
  );
}
window.SectorPage = SectorPage;

function SectorTile({ s, active, onClick, vp }) {
  const intensity = Math.min(1, s.momentum / 100);
  const bg = s.chg > 0
    ? 'oklch(' + (0.97 - intensity * 0.3) + ' ' + (0.04 + intensity * 0.16) + ' 25)'
    : 'oklch(' + (0.95 - Math.abs(s.chg) * 0.05) + ' ' + (0.03 + Math.abs(s.chg) * 0.04) + ' 155)';
  const fg = intensity > 0.5 && s.chg > 0 ? 'white' : T.text;
  return (
    <button onClick={onClick} style={{
      background: bg, border: active ? '2px solid ' + T.text : '1px solid ' + T.border,
      borderRadius: 6, padding: (vp && vp.isMobile) ? 10 : 12, cursor: 'pointer', textAlign: 'left',
      color: fg, fontFamily: T.fontSans, position: 'relative',
      minHeight: (vp && vp.isMobile) ? 70 : 84,
    }}>
      {s.hot && <span style={{ position: 'absolute', top: 6, right: 6, fontSize: 11 }}>🔥</span>}
      <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 6, letterSpacing: -0.1 }}>{s.name}</div>
      <div style={{ fontSize: 16, fontWeight: 700, fontFamily: T.fontMono, fontVariantNumeric: 'tabular-nums' }}>
        {window.sign(s.chg)}{s.chg.toFixed(2)}%
      </div>
      <div style={{ fontSize: 10, opacity: 0.7, marginTop: 2 }}>動能 {s.momentum}</div>
    </button>
  );
}

function Kpi({ label, v, sub, up, mono }) {
  return (
    <div>
      <div style={{ fontSize: 10, color: T.text3, marginBottom: 4 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
        <span style={{ fontSize: 22, fontWeight: 700, color: up ? T.up : T.text,
          fontFamily: mono ? T.fontMono : T.fontSans, letterSpacing: -0.4,
          fontVariantNumeric: 'tabular-nums' }}>{v}</span>
        {sub && <span style={{ fontSize: 11, color: T.text3 }}>{sub}</span>}
      </div>
    </div>
  );
}

// live 個股清單（代號列表）
function LiveSectorChain({ stocks, name }) {
  return (
    <div>
      <div style={{ padding: '8px 20px', background: T.surface2, fontSize: 11,
        color: T.text2, fontWeight: 600 }}>相關個股</div>
      {stocks.map((code, i) => (
        <div key={code + i} style={{
          padding: '10px 20px', borderBottom: i < stocks.length - 1 ? '1px solid ' + T.border : 'none',
          display: 'flex', alignItems: 'center', gap: 16, cursor: 'pointer',
        }}>
          <span style={{ fontFamily: T.fontMono, fontSize: 12, color: T.text3, width: 56 }}>{code}</span>
          <span style={{ fontSize: 12, color: T.text, flex: 1 }}>—</span>
          <window.Sparkline data={window.genSeries(20, code.charCodeAt ? code.charCodeAt(0) : i, 0.003)} w={80} h={20} fill />
        </div>
      ))}
    </div>
  );
}

})();
