// 美股動態頁
// 資料來源：window.STOCK_DATA_LIVE.us_signals（fetch_us_signals.py 產出）
//           live.us_signals.signals[]、live.us_signals.themes_triggered[]
// 2026-05-01 新增
(function() {
const T = window.STOCK_TOKENS;

window.USMarketPage = function USMarketPage() {
  const live = window.STOCK_DATA_LIVE || {};
  // us_signals 可能在 live.us_signals 或 live.news.us_signals（相容兩種掛載方式）
  const signals = live.us_signals?.signals || live.news?.us_signals || [];
  const themes  = live.us_signals?.themes_triggered || [];

  return (
    <div style={{padding: 16, maxWidth: 1100, margin: '0 auto', fontFamily: T.fontSans}}>
      <h1 style={{fontSize: 28, fontWeight: 700, margin: '0 0 4px'}}>美股動態</h1>
      <div style={{fontSize: 13, color: T.text3, marginBottom: 24}}>
        昨夜美股訊號 + 觸發題材 → 台股供應鏈對應
      </div>

      <USIndicesSection signals={signals} />
      <ThemesTriggeredSection themes={themes} />
      <USStocksTable signals={signals} />
    </div>
  );
};

// 主要指數 ETF
const INDEX_SYMBOLS = ['SPY', 'QQQ', 'DIA', 'IWM', 'SOXX', 'XLK'];

function USIndicesSection({signals}) {
  const indices = signals.filter(s => INDEX_SYMBOLS.includes(s.symbol));

  return (
    <section style={{marginBottom: 24}}>
      <h2 style={{fontSize: 15, color: T.text, margin: '0 0 12px'}}>📊 主要指數</h2>
      {indices.length === 0 ? (
        <div style={{padding: 16, background: T.surface, border: '1px solid ' + T.border, borderRadius: 8, color: T.text3, fontSize: 12}}>
          尚無資料
        </div>
      ) : (
        <div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 12}}>
          {indices.map((idx, i) => {
            const chg = idx.change_pct || 0;
            return (
              <div key={i} style={{padding: 16, background: T.surface, border: '1px solid ' + T.border, borderRadius: 8}}>
                <div style={{fontSize: 14, fontWeight: 600, color: T.text}}>{idx.symbol}</div>
                <div style={{fontSize: 11, color: T.text3, marginBottom: 6}}>{idx.name || ''}</div>
                <div style={{fontSize: 18, fontWeight: 700, color: chg > 0 ? T.up : T.down, fontFamily: T.fontMono}}>
                  {chg > 0 ? '+' : ''}{chg.toFixed(2)}%
                </div>
              </div>
            );
          })}
        </div>
      )}
    </section>
  );
}

function ThemesTriggeredSection({themes}) {
  return (
    <section style={{marginBottom: 24}}>
      <h2 style={{fontSize: 15, color: T.text, margin: '0 0 12px'}}>🔥 昨夜觸發的美股題材</h2>
      {themes.length === 0 ? (
        <div style={{padding: 16, background: T.surface, border: '1px solid ' + T.border, borderRadius: 8, color: T.text3, fontSize: 12}}>
          無題材觸發（市場平淡）
        </div>
      ) : (
        <div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12}}>
          {themes.map((th, i) => (
            <div key={i} style={{padding: 16, background: T.surface, border: '1px solid ' + T.border, borderRadius: 8}}>
              <div style={{fontSize: 14, fontWeight: 600, color: T.text, marginBottom: 6}}>{th.theme_name || th.name}</div>
              <div style={{fontSize: 11, color: T.text3, marginBottom: 8}}>觸發 ETF：{th.trigger_symbols?.join(', ') || '-'}</div>
              {th.tw_mapping?.length > 0 && (
                <div>
                  <div style={{fontSize: 11, color: T.text3, marginBottom: 4}}>對應台股：</div>
                  <div style={{fontSize: 12, color: T.text2}}>{th.tw_mapping.slice(0, 8).join(', ')}</div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </section>
  );
}

function USStocksTable({signals}) {
  // 排除指數 ETF，只顯示個股，取前 30 強勢
  const stocks = signals.filter(s => !INDEX_SYMBOLS.includes(s.symbol)).slice(0, 30);
  if (stocks.length === 0) return null;

  return (
    <section style={{marginBottom: 24}}>
      <h2 style={{fontSize: 15, color: T.text, margin: '0 0 12px'}}>📈 美股個股訊號（前 30 強勢）</h2>
      <div style={{background: T.surface, border: '1px solid ' + T.border, borderRadius: 8, overflow: 'hidden'}}>
        <table style={{width: '100%', borderCollapse: 'collapse', fontSize: 12}}>
          <thead>
            <tr style={{background: T.bg}}>
              <th style={thStyle}>Symbol</th>
              <th style={thStyle}>名稱</th>
              <th style={thStyle}>題材</th>
              <th style={{...thStyle, textAlign: 'right'}}>漲跌幅</th>
            </tr>
          </thead>
          <tbody>
            {stocks.map((s, i) => {
              const chg = s.change_pct || 0;
              return (
                <tr key={i}>
                  <td style={tdStyle}>{s.symbol}</td>
                  <td style={{...tdStyle, color: T.text2}}>{s.name || '—'}</td>
                  <td style={{...tdStyle, color: T.text3, fontSize: 11}}>{s.theme || '-'}</td>
                  <td style={{...tdStyle, textAlign: 'right', color: chg > 0 ? T.up : T.down, fontFamily: T.fontMono}}>
                    {chg > 0 ? '+' : ''}{chg.toFixed(2)}%
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </section>
  );
}

const thStyle = {padding: '10px 8px', textAlign: 'left', fontSize: 11, color: T.text3, fontWeight: 500, borderBottom: '1px solid ' + T.border};
const tdStyle = {padding: '8px', borderBottom: '1px solid ' + T.border, color: T.text};

})();
