// page-calendar.jsx — 法說會日曆（NEW，1:1 對齊設計檔，2026-05-10）
// 設計檔結構：MonthGrid + ListView + DetailPanel + filter (all/high/watchlist) + view switch (month/list)
// D1 接線：events_calendar.events / macro_calendar.events （自動過濾個股事件）
// 重要 export：window.CalendarPage
(function(){
  const T = window.STOCK_TOKENS;

  // ── helpers ──────────────────────────────────────────────────────
  function parseDate(s) {
    if (!s) return new Date();
    if (s.includes('-')) return new Date(s.slice(0, 10));
    const parts = s.split('/').map(Number);
    if (parts.length === 2) {
      const [m, d] = parts;
      return new Date(new Date().getFullYear(), m - 1, d);
    }
    return new Date(s);
  }
  function sameDay(a, b) {
    return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
  }
  function weekdayLabel(d) {
    return ['週日', '週一', '週二', '週三', '週四', '週五', '週六'][d.getDay()];
  }
  function fmtDateMD(d) {
    return `${String(d.getMonth() + 1).padStart(2, '0')}/${String(d.getDate()).padStart(2, '0')}`;
  }

  // ── normalize event from D1 → design schema ─────────────────────
  // D1 events_calendar.events 可能 schema：{ date, title, scope, importance, region, expected_time, impact, code?, name? }
  // 設計 schema：{ date "MM/DD", time, code, name, kind, weight, title, note, expectations[], history[] }
  function normalizeEvent(ev) {
    const dt = parseDate(ev.date);
    const dateMD = fmtDateMD(dt);
    let kind = 'other';
    const title = (ev.title || '').toLowerCase();
    if (title.includes('法說')) kind = 'earnings';
    else if (title.includes('營收')) kind = 'revenue';
    else if (title.includes('除息') || title.includes('除權') || title.includes('股利')) kind = 'dividend';
    else if (title.includes('股東')) kind = 'agm';
    else if (ev.kind) kind = ev.kind;
    return {
      date: dateMD,
      _date: dt,
      time: ev.expected_time || ev.time || '盤後',
      code: ev.code || '',
      name: ev.name || '',
      kind,
      weight: ev.importance === 'high' || ev.importance === 'critical' ? 'high'
            : ev.importance === 'medium' ? 'mid'
            : ev.weight || 'mid',
      title: ev.title || '',
      note: ev.impact || ev.note || '',
      expectations: ev.expectations,
      history: ev.history,
    };
  }

  function CalendarPage() {
    const live = window.STOCK_DATA_LIVE || {};
    const today = new Date();
    const [cursor, setCursor] = React.useState(new Date(today.getFullYear(), today.getMonth(), 1));
    const [selected, setSelected] = React.useState(null);
    const [filter, setFilter] = React.useState('all');
    const [view, setView] = React.useState('month');

    // 自選股 codes（for ★ 標記）
    const watchSet = new Set();
    (live.portfolio?.holdings || []).forEach(h => watchSet.add(h.code));
    (live.watchlist?.items || []).forEach(it => { if (it.code !== '__tab_placeholder__') watchSet.add(it.code); });

    const rawEvents = live.events_calendar?.events || live.macro_calendar?.events || [];
    const events = rawEvents.map(normalizeEvent).filter(e => e.code || e.title);

    const filtered = events.filter(e => {
      if (filter === 'watchlist') return watchSet.has(e.code);
      if (filter === 'high') return e.weight === 'high';
      return true;
    });

    const monthLabel = `${cursor.getFullYear()}年 ${String(cursor.getMonth() + 1).padStart(2, '0')} 月`;
    const prev = () => setCursor(new Date(cursor.getFullYear(), cursor.getMonth() - 1, 1));
    const next = () => setCursor(new Date(cursor.getFullYear(), cursor.getMonth() + 1, 1));
    const goToday = () => setCursor(new Date(today.getFullYear(), today.getMonth(), 1));

    const monthEvents = filtered.filter(e => e._date.getFullYear() === cursor.getFullYear() && e._date.getMonth() === cursor.getMonth());

    return (
      <div style={{ padding: 16, maxWidth: 1400, margin: '0 auto' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', paddingBottom: 16, borderBottom: '1px solid var(--line)' }}>
          <div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--fg-3)', letterSpacing: '.1em' }}>
              EARNINGS CALENDAR · UPDATED {today.toLocaleDateString('en-CA')}
            </div>
            <div style={{ fontSize: 22, fontWeight: 600, color: 'var(--fg-0)', marginTop: 4 }}>法說會日曆</div>
            <div style={{ fontSize: 12.5, color: 'var(--fg-2)', marginTop: 2 }}>
              追蹤本月所有上市櫃法說會、財報、股利公告，點擊任一筆查看完整資訊
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Stat label="本月事件" value={monthEvents.length} />
            <Stat label="高權重" value={monthEvents.filter(e => e.weight === 'high').length} cls="up" />
            <Stat label="自選股相關" value={monthEvents.filter(e => watchSet.has(e.code)).length} cls="accent" />
          </div>
        </div>

        {/* Toolbar */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14, flexWrap: 'wrap', gap: 8 }}>
          <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
            <button onClick={prev} className="btn" style={{ padding: '5px 10px' }}>‹</button>
            <button onClick={goToday} className="btn" style={{ padding: '5px 12px' }}>今天</button>
            <button onClick={next} className="btn" style={{ padding: '5px 10px' }}>›</button>
            <div style={{ marginLeft: 14, fontSize: 16, color: 'var(--fg-0)', fontWeight: 600, minWidth: 130 }}>{monthLabel}</div>
          </div>
          <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
            <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '.08em', marginRight: 8 }}>篩選</span>
            {[{ k: 'all', l: '全部' }, { k: 'high', l: '高權重' }, { k: 'watchlist', l: '自選股' }].map(f => (
              <button key={f.k} onClick={() => setFilter(f.k)} style={{
                background: filter === f.k ? 'var(--bg-2)' : 'transparent',
                border: `1px solid ${filter === f.k ? 'var(--accent)' : 'var(--line)'}`,
                color: filter === f.k ? 'var(--fg-0)' : 'var(--fg-2)',
                padding: '4px 10px', fontSize: 11, cursor: 'pointer', borderRadius: 2,
              }}>{f.l}</button>
            ))}
            <span style={{ width: 1, height: 18, background: 'var(--line)', margin: '0 8px' }}></span>
            {[{ k: 'month', l: '月曆' }, { k: 'list', l: '列表' }].map(v => (
              <button key={v.k} onClick={() => setView(v.k)} style={{
                background: view === v.k ? 'var(--bg-2)' : 'transparent',
                border: `1px solid ${view === v.k ? 'var(--accent)' : 'var(--line)'}`,
                color: view === v.k ? 'var(--fg-0)' : 'var(--fg-2)',
                padding: '4px 10px', fontSize: 11, cursor: 'pointer', borderRadius: 2,
              }}>{v.l}</button>
            ))}
          </div>
        </div>

        {/* Body */}
        <div style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 360px' : '1fr', gap: 12, marginTop: 12 }}>
          <div>
            {events.length === 0 ? (
              <div className="panel" style={{ padding: '60px 20px', textAlign: 'center' }}>
                <div className="mono" style={{ fontSize: 11, color: 'var(--fg-3)', letterSpacing: '.08em', marginBottom: 6 }}>// NO EARNINGS DATA</div>
                <div style={{ fontSize: 12, color: 'var(--fg-2)' }}>
                  本機可手動產生：<code className="mono" style={{ background: 'var(--bg-2)', padding: '2px 6px', borderRadius: 3 }}>python tools/events_calendar.py</code>
                </div>
              </div>
            ) : view === 'month' ? (
              <MonthGrid cursor={cursor} today={today} events={filtered} onSelect={setSelected} watchSet={watchSet} />
            ) : (
              <ListView events={filtered} today={today} onSelect={setSelected} watchSet={watchSet} />
            )}
          </div>
          {selected && <DetailPanel event={selected} onClose={() => setSelected(null)} watchSet={watchSet} />}
        </div>

        {/* Legend */}
        <div style={{ display: 'flex', gap: 16, marginTop: 14, padding: '10px 14px', background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 3, fontSize: 11, color: 'var(--fg-2)', flexWrap: 'wrap' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 8, height: 8, background: 'var(--down)' }}></span>法說會</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 8, height: 8, background: 'var(--accent)' }}></span>營收 / 財報</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 8, height: 8, background: 'var(--up)' }}></span>除權息</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 8, height: 8, background: 'var(--accent-2)' }}></span>股東會</span>
          <span style={{ marginLeft: 'auto', color: 'var(--fg-3)' }}>★ 為自選股相關 · 紅框為高權重</span>
        </div>
      </div>
    );
  }
  window.CalendarPage = CalendarPage;

  // ── helpers ──────────────────────────────────────────────────────
  function Stat({ label, value, cls }) {
    return (
      <div style={{ background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 3, padding: '6px 14px', textAlign: 'right', minWidth: 90 }}>
        <div className="mono" style={{ fontSize: 9.5, color: 'var(--fg-3)', letterSpacing: '.08em' }}>{label}</div>
        <div className={`num ${cls === 'up' ? 'up' : ''}`} style={{ fontSize: 18, fontWeight: 600, color: cls === 'accent' ? 'var(--accent)' : (cls === 'up' ? null : 'var(--fg-0)') }}>{value}</div>
      </div>
    );
  }

  function kindFg(k) {
    return k === 'earnings' ? 'var(--down)'
      : k === 'revenue' ? 'var(--accent)'
      : k === 'dividend' ? 'var(--up)'
      : k === 'agm' ? 'var(--accent-2)'
      : 'var(--fg-2)';
  }
  function kindBg(k) {
    return k === 'earnings' ? 'var(--down-bg)'
      : k === 'dividend' ? 'var(--up-bg)'
      : 'var(--bg-2)';
  }
  function kindLabel(k) {
    return k === 'earnings' ? '法說會'
      : k === 'revenue' ? '營收'
      : k === 'dividend' ? '除權息'
      : k === 'agm' ? '股東會'
      : '其他';
  }

  // ── MonthGrid ────────────────────────────────────────────────────
  function MonthGrid({ cursor, today, events, onSelect, watchSet }) {
    const year = cursor.getFullYear();
    const month = cursor.getMonth();
    const firstDay = new Date(year, month, 1);
    const startWeekday = firstDay.getDay();
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    const cells = [];
    const prevMonthDays = new Date(year, month, 0).getDate();
    for (let i = 0; i < startWeekday; i++) {
      cells.push({ day: prevMonthDays - startWeekday + 1 + i, dim: true, date: null });
    }
    for (let d = 1; d <= daysInMonth; d++) {
      const date = new Date(year, month, d);
      const dateStr = fmtDateMD(date);
      const dayEvents = events.filter(e => e.date === dateStr);
      cells.push({ day: d, date, events: dayEvents, isToday: sameDay(date, today) });
    }
    while (cells.length % 7 !== 0) {
      cells.push({ day: cells.length - daysInMonth - startWeekday + 1, dim: true, date: null });
    }
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];

    return (
      <div className="panel" style={{ overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', borderBottom: '1px solid var(--line)', background: 'var(--bg-2)' }}>
          {weekdays.map((w, i) => (
            <div key={w} className="mono" style={{
              padding: '8px 12px', fontSize: 10.5,
              color: i === 0 || i === 6 ? 'var(--fg-3)' : 'var(--fg-2)',
              letterSpacing: '.08em', textAlign: 'left',
            }}>{w}</div>
          ))}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gridAutoRows: 'minmax(120px, auto)' }}>
          {cells.map((c, i) => (
            <div key={i} style={{
              borderRight: (i + 1) % 7 !== 0 ? '1px solid var(--line)' : 'none',
              borderBottom: i < cells.length - 7 ? '1px solid var(--line)' : 'none',
              padding: 6,
              background: c.isToday ? 'var(--bg-2)' : 'transparent',
              opacity: c.dim ? 0.35 : 1,
              display: 'flex', flexDirection: 'column', gap: 3,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 2 }}>
                <span className="mono" style={{
                  fontSize: c.isToday ? 13 : 11.5,
                  color: c.isToday ? 'var(--accent)' : (i % 7 === 0 || i % 7 === 6 ? 'var(--fg-3)' : 'var(--fg-1)'),
                  fontWeight: c.isToday ? 700 : 400,
                }}>
                  {c.isToday && <span style={{
                    display: 'inline-block', width: 6, height: 6, borderRadius: '50%',
                    background: 'var(--accent)', marginRight: 4, verticalAlign: 'middle',
                  }}></span>}
                  {c.day}
                </span>
                {c.events?.length > 0 && <span className="mono" style={{ fontSize: 9, color: 'var(--fg-3)' }}>{c.events.length}</span>}
              </div>
              {c.events?.slice(0, 3).map((e, ei) => (
                <button key={ei} onClick={() => onSelect(e)} style={{
                  display: 'block', width: '100%', textAlign: 'left',
                  padding: '3px 6px',
                  background: kindBg(e.kind),
                  color: kindFg(e.kind),
                  border: e.weight === 'high' ? `1px solid ${kindFg(e.kind)}` : '1px solid transparent',
                  borderLeft: `2px solid ${kindFg(e.kind)}`,
                  borderRadius: 2, cursor: 'pointer',
                  fontSize: 10.5, lineHeight: 1.3,
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                  fontFamily: 'inherit',
                }}>
                  {watchSet.has(e.code) && <span style={{ color: 'var(--accent)', marginRight: 3 }}>★</span>}
                  {e.code && <span className="mono" style={{ fontSize: 9.5, opacity: .8, marginRight: 4 }}>{e.code}</span>}
                  {e.name || e.title}
                </button>
              ))}
              {c.events?.length > 3 && (
                <span className="mono" style={{ fontSize: 9.5, color: 'var(--fg-3)', paddingLeft: 4 }}>+{c.events.length - 3} 更多</span>
              )}
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── ListView ─────────────────────────────────────────────────────
  function ListView({ events, today, onSelect, watchSet }) {
    const sorted = [...events].sort((a, b) => a._date - b._date);
    const groups = {};
    sorted.forEach(e => { (groups[e.date] = groups[e.date] || []).push(e); });
    const dates = Object.keys(groups);
    if (dates.length === 0) {
      return (
        <div className="panel" style={{ padding: '60px 20px', textAlign: 'center' }}>
          <div className="mono" style={{ fontSize: 11, color: 'var(--fg-3)', letterSpacing: '.08em' }}>// NO EVENTS IN FILTER</div>
        </div>
      );
    }
    return (
      <div className="panel" style={{ overflow: 'hidden' }}>
        {dates.map(d => {
          const dt = parseDate(d);
          const isPast = dt < today;
          const isToday = sameDay(dt, today);
          return (
            <div key={d} style={{ borderBottom: '1px solid var(--line)' }}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '10px 14px', background: 'var(--bg-2)',
                borderBottom: '1px solid var(--line)',
              }}>
                <div className="mono" style={{
                  fontSize: 14,
                  color: isToday ? 'var(--accent)' : (isPast ? 'var(--fg-3)' : 'var(--fg-0)'),
                  fontWeight: 600, minWidth: 60,
                }}>{d}</div>
                <div style={{ fontSize: 12, color: 'var(--fg-2)' }}>{weekdayLabel(dt)}</div>
                {isToday && <span className="mono" style={{ fontSize: 9.5, padding: '1px 6px', background: 'var(--accent)', color: '#fff', borderRadius: 2, letterSpacing: '.08em' }}>TODAY</span>}
                <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', marginLeft: 'auto' }}>{groups[d].length} 個事件</span>
              </div>
              {groups[d].map((e, ei) => (
                <div key={ei} onClick={() => onSelect(e)} style={{
                  display: 'grid', gridTemplateColumns: '60px 80px 1fr 100px 28px',
                  padding: '10px 14px', alignItems: 'center', cursor: 'pointer',
                  borderTop: ei > 0 ? '1px solid var(--line)' : 'none',
                  opacity: isPast ? 0.6 : 1,
                }}
                onMouseEnter={(ev) => ev.currentTarget.style.background = 'var(--hover)'}
                onMouseLeave={(ev) => ev.currentTarget.style.background = 'transparent'}>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--fg-2)' }}>{e.time}</span>
                  <span style={{
                    padding: '2px 8px', fontSize: 10.5, color: kindFg(e.kind),
                    border: `1px solid ${kindFg(e.kind)}`, borderRadius: 2,
                    textAlign: 'center', letterSpacing: '.04em', background: kindBg(e.kind),
                  }}>{kindLabel(e.kind)}</span>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, minWidth: 0 }}>
                    {watchSet.has(e.code) && <span style={{ color: 'var(--accent)' }}>★</span>}
                    {e.code && <span className="mono" style={{ fontSize: 11, color: 'var(--fg-3)' }}>{e.code}</span>}
                    {e.name && <span style={{ fontSize: 13, color: 'var(--fg-0)', fontWeight: 500 }}>{e.name}</span>}
                    <span style={{ fontSize: 12, color: 'var(--fg-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>· {e.title}</span>
                  </div>
                  {e.weight === 'high'
                    ? <span className="mono" style={{ fontSize: 10, color: 'var(--up)', border: '1px solid var(--up)', padding: '1px 6px', borderRadius: 2, textAlign: 'center', letterSpacing: '.04em' }}>HIGH</span>
                    : <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>—</span>}
                  <span style={{ color: 'var(--fg-3)', textAlign: 'center' }}>›</span>
                </div>
              ))}
            </div>
          );
        })}
      </div>
    );
  }

  // ── DetailPanel ──────────────────────────────────────────────────
  function DetailPanel({ event, onClose, watchSet }) {
    const live = window.STOCK_DATA_LIVE || {};
    const daily = event.code ? live.daily_analysis?.[event.code] : null;
    const isWatch = watchSet.has(event.code);
    return (
      <div className="panel" style={{ position: 'sticky', top: 12, alignSelf: 'start', maxHeight: 'calc(100vh - 80px)', overflowY: 'auto' }}>
        <div style={{
          padding: '12px 14px', borderBottom: '1px solid var(--line)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
          background: 'var(--bg-2)',
        }}>
          <div>
            <div className="mono" style={{ fontSize: 9.5, color: 'var(--fg-3)', letterSpacing: '.1em' }}>EVENT DETAIL · {event.date} {event.time}</div>
            <div style={{ fontSize: 14, color: 'var(--fg-0)', marginTop: 4, fontWeight: 600 }}>{event.title}</div>
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--fg-3)', cursor: 'pointer', fontSize: 16, padding: 0, lineHeight: 1 }}>×</button>
        </div>
        <div style={{ padding: 14 }}>
          {event.code && (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingBottom: 12, borderBottom: '1px dashed var(--line)' }}>
              <div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                  <span className="mono" style={{ fontSize: 12, color: 'var(--fg-3)' }}>{event.code}</span>
                  <span style={{ fontSize: 16, color: 'var(--fg-0)', fontWeight: 600 }}>{event.name}</span>
                  {isWatch && <span className="mono" style={{ fontSize: 9.5, color: 'var(--accent)', border: '1px solid var(--accent)', padding: '1px 5px', borderRadius: 2 }}>★ 自選</span>}
                </div>
                {daily && (
                  <div style={{ marginTop: 4, display: 'flex', alignItems: 'baseline', gap: 8 }}>
                    <span className="num" style={{ fontSize: 18, color: 'var(--fg-0)' }}>{daily.price}</span>
                    {daily.change_pct != null && (
                      <span className={`num ${daily.change_pct >= 0 ? 'up' : 'down'}`} style={{ fontSize: 12 }}>
                        {daily.change_pct >= 0 ? '+' : ''}{daily.change_pct.toFixed(2)}%
                      </span>
                    )}
                  </div>
                )}
              </div>
              <span style={{
                padding: '4px 10px', fontSize: 11, color: kindFg(event.kind),
                border: `1px solid ${kindFg(event.kind)}`, background: kindBg(event.kind),
                borderRadius: 2, fontWeight: 600,
              }}>{kindLabel(event.kind)}</span>
            </div>
          )}

          <div style={{ marginTop: 14 }}>
            <div className="mono" style={{ fontSize: 9.5, color: 'var(--fg-3)', letterSpacing: '.08em', marginBottom: 6 }}>事件內容</div>
            <div style={{ fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.7 }}>{event.note || '—'}</div>
          </div>

          {event.expectations && (
            <div style={{ marginTop: 14 }}>
              <div className="mono" style={{ fontSize: 9.5, color: 'var(--fg-3)', letterSpacing: '.08em', marginBottom: 6 }}>市場預期</div>
              <div style={{ display: 'grid', gap: 6 }}>
                {event.expectations.map((x, i) => (
                  <div key={i} style={{ display: 'grid', gridTemplateColumns: '100px 1fr', gap: 8, fontSize: 12 }}>
                    <span style={{ color: 'var(--fg-3)' }}>{x.k}</span>
                    <span style={{ color: 'var(--fg-1)' }}>{x.v}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {event.history && (
            <div style={{ marginTop: 14 }}>
              <div className="mono" style={{ fontSize: 9.5, color: 'var(--fg-3)', letterSpacing: '.08em', marginBottom: 6 }}>近期同類事件後股價反應</div>
              <table style={{ width: '100%', fontSize: 11.5 }}>
                <thead>
                  <tr style={{ color: 'var(--fg-3)' }}>
                    <th style={{ textAlign: 'left', padding: '4px 6px', borderBottom: '1px solid var(--line)' }}>日期</th>
                    <th style={{ textAlign: 'left', padding: '4px 6px', borderBottom: '1px solid var(--line)' }}>事件</th>
                    <th style={{ textAlign: 'right', padding: '4px 6px', borderBottom: '1px solid var(--line)' }}>次日</th>
                    <th style={{ textAlign: 'right', padding: '4px 6px', borderBottom: '1px solid var(--line)' }}>+5 日</th>
                  </tr>
                </thead>
                <tbody>
                  {event.history.map((h, i) => (
                    <tr key={i}>
                      <td className="mono" style={{ padding: '4px 6px', color: 'var(--fg-2)' }}>{h.date}</td>
                      <td style={{ padding: '4px 6px', color: 'var(--fg-1)' }}>{h.title}</td>
                      <td className={`num ${h.d1 >= 0 ? 'up' : 'down'}`} style={{ padding: '4px 6px', textAlign: 'right' }}>
                        {h.d1 >= 0 ? '+' : ''}{h.d1}%
                      </td>
                      <td className={`num ${h.d5 >= 0 ? 'up' : 'down'}`} style={{ padding: '4px 6px', textAlign: 'right' }}>
                        {h.d5 >= 0 ? '+' : ''}{h.d5}%
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          <div style={{ marginTop: 16, display: 'grid', gap: 6 }}>
            <button className="btn-primary btn" style={{ justifyContent: 'center' }}>🔔 設定提醒</button>
            {event.code && !isWatch && <button className="btn" style={{ justifyContent: 'center' }}>＋ 加入自選股</button>}
            <button className="btn" style={{ justifyContent: 'center', color: 'var(--fg-3)' }}>📅 加入 Google 行事曆</button>
          </div>
        </div>
      </div>
    );
  }

})();
