(function(){
// 新聞 + 情緒 + Watchlist 頁
// 接線：live.news.items；impact_score 對應「影響度」
const T = window.STOCK_TOKENS;

// ── DataMode 標示 ────────────────────────────────────────────────────────────
function DataModeBadge() {
  const live = window.STOCK_DATA_LIVE;
  const isLive = live.loaded && live.news && live.news.items &&
    (live.news._status === 'live' || !live.news.not_implemented);
  const dateStr = live.news && live.news.date ? live.news.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 NewsPage() {
  const [filter, setFilter] = React.useState('all');
  const vp = window.useViewport();
  const live = window.STOCK_DATA_LIVE;

  // 優先用 live.news.items：_status==='live' 或有 items 且未標示 not_implemented
  const hasLiveNews = live.loaded && live.news && live.news.items &&
    Array.isArray(live.news.items) &&
    (live.news._status === 'live' || !live.news.not_implemented);

  const allNews = hasLiveNews
    ? live.news.items.map(n => ({
        time: n.time || '—',
        src: n.src || n.source || '—',
        title: n.title,
        sentiment: n.sentiment || 0,
        related: n.related || [],
        _impact: n.impact_score != null ? n.impact_score / 100 : Math.abs(n.sentiment || 0),
      }))
    : [];

  const pad = vp.isMobile ? 12 : 24;

  return (
    <div style={{
      padding: pad,
      display: 'grid',
      gridTemplateColumns: vp.isMobile ? '1fr' : '1fr 360px',
      gap: 16,
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* AI 影響度雷達 */}
        <window.Card title="AI 新聞影響度評估" ai
          subtitle="針對你的持股，AI 評估每則新聞的衝擊強度"
          action={<DataModeBadge />}
          padding={0}>
          <div style={{
            padding: '12px 14px', borderBottom: '1px solid ' + T.border,
            display: 'flex', gap: 4, flexWrap: 'nowrap',
            overflowX: 'auto', scrollbarWidth: 'none',
          }}>
            {[
              { k: 'all', l: '全部' },
              { k: 'pos', l: '利多' },
              { k: 'neg', l: '利空' },
              { k: 'mine', l: '與我相關' },
              { k: 'macro', l: '總經' },
            ].map(f => (
              <window.Btn key={f.k} variant="ghost" active={filter === f.k}
                onClick={() => setFilter(f.k)}>{f.l}</window.Btn>
            ))}
          </div>
          {allNews.length > 0
            ? allNews.map((n, i) => (
                <NewsItem key={i} n={n} last={i === allNews.length - 1} />
              ))
            : (
              <div style={{ padding: '40px 20px', textAlign: 'center', color: T.text3, fontSize: 13 }}>
                <div style={{ fontSize: 14, color: T.text2, fontWeight: 500, marginBottom: 6 }}>新聞收集器尚未實作</div>
                <div>pipeline 尚未實作，預計後續加入</div>
              </div>
            )
          }
        </window.Card>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {/* 整體情緒 */}
        <window.Card title="今日市場情緒" ai padding={16}>
          {hasLiveNews ? (
            <>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
                <span style={{ fontSize: 13, color: T.text2 }}>分析 {allNews.length} 則新聞</span>
              </div>
              <div style={{ fontSize: 11, color: T.text2, lineHeight: 1.5 }}>
                正向情緒主要來自 AI 供應鏈。
              </div>
            </>
          ) : (
            <div style={{ padding: '20px 0', textAlign: 'center', color: T.text3, fontSize: 12 }}>
              新聞收集器尚未實作，暫無情緒分析
            </div>
          )}
        </window.Card>

        {/* Watchlist */}
        <window.Card title="自選股 Watchlist" padding={0}>
          {window.STOCK_DATA && window.STOCK_DATA.watchlist && window.STOCK_DATA.watchlist.length > 0
            ? window.STOCK_DATA.watchlist.map((w, i) => (
              <div key={w.code} style={{
                padding: '10px 14px', borderBottom: i < window.STOCK_DATA.watchlist.length - 1 ? '1px solid ' + T.border : 'none',
                cursor: 'pointer',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontFamily: T.fontMono, fontSize: 10, color: T.text3 }}>{w.code}</span>
                  <span style={{ fontSize: 12, fontWeight: 600, color: T.text, flex: 1 }}>{w.name}</span>
                  <span style={{ fontFamily: T.fontMono, fontSize: 12, fontWeight: 500, color: T.text }}>{window.fmt(w.price, w.price < 100 ? 2 : 1)}</span>
                  <window.ChangeChip value={w.chg} />
                </div>
                {w.sig && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
                    <window.AIBadge />
                    <span style={{ fontSize: 11, color: T.ai }}>{w.sig.replace('AI: ', '')}</span>
                    <span style={{ flex: 1 }} />
                    <span style={{ fontSize: 10, color: T.text3, fontFamily: T.fontMono }}>vol {w.vol}</span>
                  </div>
                )}
              </div>
            ))
            : (
              <div style={{ padding: 24, textAlign: 'center', color: T.text3, fontSize: 12 }}>
                自選股清單尚未設定
              </div>
            )
          }
        </window.Card>
      </div>
    </div>
  );
}
window.NewsPage = NewsPage;

function NewsItem({ n, last }) {
  const vp = window.useViewport();
  const sentColor = n.sentiment > 0.3 ? T.up : n.sentiment < -0.3 ? T.down : T.text3;
  const sentLabel = n.sentiment > 0.6 ? '強利多' : n.sentiment > 0.3 ? '利多' : n.sentiment < -0.3 ? '利空' : '中性';
  const impact = n._impact != null ? n._impact * 100 : Math.abs(n.sentiment) * 100;

  // 共用：點擊時開新分頁（若有 url）
  const handleClick = () => {
    if (n.url) window.open(n.url, '_blank', 'noopener,noreferrer');
  };

  if (vp.isMobile) {
    return (
      <div onClick={handleClick} style={{
        padding: '12px 16px', borderBottom: last ? 'none' : '1px solid ' + T.border,
        cursor: n.url ? 'pointer' : 'default',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
          <span style={{ fontSize: 9, fontWeight: 700, color: sentColor,
            background: window.dirSoft(n.sentiment > 0 ? 1 : -1),
            padding: '2px 6px', borderRadius: 3 }}>{sentLabel}</span>
          <span style={{ fontSize: 10, color: T.text3, fontFamily: T.fontMono }}>{n.time} · {n.src}</span>
        </div>
        <div style={{ fontSize: 13, fontWeight: 500, color: T.text, lineHeight: 1.45 }}>{n.title}</div>
        {n.related && n.related.length > 0 && (
          <div style={{ fontSize: 10, color: T.primary, fontFamily: T.fontMono, marginTop: 4 }}>
            關聯 {n.related.join(' · ')}
          </div>
        )}
      </div>
    );
  }

  return (
    <div onClick={handleClick} style={{
      padding: '14px 20px', borderBottom: last ? 'none' : '1px solid ' + T.border,
      display: 'grid', gridTemplateColumns: '70px 1fr 90px', gap: 14, alignItems: 'flex-start',
      cursor: n.url ? 'pointer' : 'default',
    }}>
      <div style={{ fontSize: 10, color: T.text3, fontFamily: T.fontMono }}>
        {n.time}
        <div style={{ marginTop: 2, color: T.text2 }}>{n.src}</div>
      </div>
      <div>
        <div style={{ fontSize: 13, fontWeight: 600, color: T.text, lineHeight: 1.45, marginBottom: 6 }}>
          {n.title}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontSize: 9, fontWeight: 700, color: sentColor, background: window.dirSoft(n.sentiment > 0 ? 1 : -1),
            padding: '2px 6px', borderRadius: 3 }}>{sentLabel}</span>
          {n.related && n.related.length > 0 && (
            <span style={{ fontSize: 10, color: T.primary, fontFamily: T.fontMono }}>
              關聯 {n.related.join(' · ')}
            </span>
          )}
          {n.url && (
            <span style={{ fontSize: 10, color: T.text4 }}>↗</span>
          )}
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontSize: 9, color: T.text3, marginBottom: 3, fontWeight: 500 }}>對你影響</div>
        <div style={{ height: 6, background: T.hover, borderRadius: 3, marginBottom: 4 }}>
          <div style={{ width: impact + '%', height: '100%', background: sentColor, borderRadius: 3 }} />
        </div>
        <div style={{ fontSize: 11, color: sentColor, fontFamily: T.fontMono, fontWeight: 600 }}>
          {(n._impact != null ? (n.sentiment >= 0 ? '+' : '') + (n._impact * 100).toFixed(0) : (n.sentiment > 0 ? '+' : '') + (n.sentiment * 100).toFixed(0))}
        </div>
      </div>
    </div>
  );
}

})();
