// 半月交易檢討頁
// 資料來源：web/_data/biweekly_review_latest.json（每月 1/16 號由 GHA biweekly_review.py 產出）
// 2026-05-01 新增
(function() {
const T = window.STOCK_TOKENS;

window.ReviewPage = function ReviewPage() {
  const [review, setReview] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [errorState, setErrorState] = React.useState(false);

  React.useEffect(() => {
    fetch('_data/biweekly_review_latest.json', { cache: 'no-store' })
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then(data => setReview(data))
      .catch(err => {
        console.error('biweekly_review fetch failed', err);
        setErrorState(true);
      })
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <div style={{padding: 40, textAlign: 'center', color: T.text3}}>載入中...</div>;
  if (errorState || !review) return <EmptyState />;

  return (
    <div style={{padding: 16, maxWidth: 1100, margin: '0 auto', fontFamily: T.fontSans}}>
      <PageHeader review={review} />
      <KPICards kpi={review.kpi} />
      <GroupAnalysis review={review} />
      <LLMReview review={review.review} />
      <IndividualReview items={review.individual_items} />
      <DeepPromptArea data={review} />
    </div>
  );
};

function EmptyState() {
  return (
    <div style={{padding: 60, textAlign: 'center'}}>
      <div style={{fontSize: 36, marginBottom: 12}}>📊</div>
      <h2 style={{fontSize: 18, color: T.text, margin: '0 0 8px'}}>尚未產出半月檢討</h2>
      <p style={{fontSize: 13, color: T.text3, lineHeight: 1.6}}>
        每月 1 號 + 16 號自動產出。<br/>
        需累積至少 14 天結算的推薦才有意義。
      </p>
    </div>
  );
}

function PageHeader({review}) {
  const asOf = review.as_of?.slice(0, 10) || '—';
  return (
    <div style={{marginBottom: 24}}>
      <h1 style={{fontSize: 28, fontWeight: 700, margin: '0 0 4px'}}>半月交易檢討</h1>
      <div style={{fontSize: 13, color: T.text3}}>
        {asOf} · 近 {review.period_days} 天 · {review.kpi?.count || 0} 筆結算
      </div>
    </div>
  );
}

function KPICards({kpi}) {
  if (!kpi) return null;
  const items = [
    {label: '勝率', value: `${(kpi.win_rate * 100).toFixed(0)}%`, color: kpi.win_rate >= 0.5 ? T.up : T.down},
    {label: '平均報酬', value: `${kpi.avg_return.toFixed(2)}%`, color: kpi.avg_return > 0 ? T.up : T.down},
    {label: '最大回撤', value: `${kpi.max_drawdown.toFixed(2)}%`, color: T.down},
    {label: '平均持有', value: `${kpi.avg_hold_days.toFixed(1)} 天`, color: T.text},
  ];
  return (
    <div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 12, marginBottom: 24}}>
      {items.map((it, i) => (
        <div key={i} style={{padding: 16, background: T.surface, border: '1px solid ' + T.border, borderRadius: 8}}>
          <div style={{fontSize: 11, color: T.text3, marginBottom: 6}}>{it.label}</div>
          <div style={{fontSize: 24, fontWeight: 700, color: it.color}}>{it.value}</div>
        </div>
      ))}
    </div>
  );
}

function GroupAnalysis({review}) {
  const groups = [
    {title: '按產業分群', data: review.by_industry},
    {title: '按波段分群', data: review.by_horizon},
    {title: '按來源分群', data: review.by_source},
  ];
  return (
    <div style={{marginBottom: 24}}>
      <h2 style={{fontSize: 16, color: T.text, margin: '0 0 12px'}}>分群勝率分析</h2>
      <div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12}}>
        {groups.map((g, i) => (
          <div key={i} style={{padding: 12, background: T.surface, border: '1px solid ' + T.border, borderRadius: 8}}>
            <div style={{fontSize: 12, color: T.text3, marginBottom: 8}}>{g.title}</div>
            {Object.entries(g.data || {}).map(([k, v]) => (
              <div key={k} style={{display: 'flex', justifyContent: 'space-between', padding: '4px 0', fontSize: 12}}>
                <span style={{color: T.text}}>{k}</span>
                <span style={{color: v.win_rate >= 0.5 ? T.up : T.down, fontFamily: T.fontMono}}>
                  {(v.win_rate * 100).toFixed(0)}% ({v.wins}/{v.count})
                </span>
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

function LLMReview({review}) {
  if (!review) return null;
  return (
    <div style={{marginBottom: 24, padding: 20, background: T.surface, border: '1px solid ' + T.border, borderRadius: 8}}>
      <h2 style={{fontSize: 16, color: T.text, margin: '0 0 12px'}}>🤖 AI 評語</h2>
      <p style={{fontSize: 14, color: T.text, lineHeight: 1.7, margin: '0 0 16px'}}>{review.overall}</p>

      {review.strengths?.length > 0 && (
        <div style={{marginBottom: 12}}>
          <div style={{fontSize: 12, color: T.up, marginBottom: 4}}>✅ 優點</div>
          <ul style={{margin: 0, paddingLeft: 20, fontSize: 13, color: T.text2}}>
            {review.strengths.map((s, i) => <li key={i}>{s}</li>)}
          </ul>
        </div>
      )}

      {review.weaknesses?.length > 0 && (
        <div style={{marginBottom: 12}}>
          <div style={{fontSize: 12, color: T.down, marginBottom: 4}}>⚠️ 弱點</div>
          <ul style={{margin: 0, paddingLeft: 20, fontSize: 13, color: T.text2}}>
            {review.weaknesses.map((s, i) => <li key={i}>{s}</li>)}
          </ul>
        </div>
      )}

      {review.improvements?.length > 0 && (
        <div>
          <div style={{fontSize: 12, color: T.warn, marginBottom: 4}}>💡 改進建議</div>
          <ul style={{margin: 0, paddingLeft: 20, fontSize: 13, color: T.text2}}>
            {review.improvements.map((s, i) => <li key={i}>{s}</li>)}
          </ul>
        </div>
      )}
    </div>
  );
}

function IndividualReview({items}) {
  if (!items || items.length === 0) return null;
  return (
    <div style={{marginBottom: 24}}>
      <h2 style={{fontSize: 16, color: T.text, margin: '0 0 12px'}}>個股逐支對照</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}>代號</th>
              <th style={thStyle}>名稱</th>
              <th style={thStyle}>波段</th>
              <th style={thStyle}>結果</th>
              <th style={{...thStyle, textAlign: 'right'}}>報酬</th>
            </tr>
          </thead>
          <tbody>
            {items.map((it, i) => (
              <tr key={i}>
                <td style={tdStyle}>{it.code}</td>
                <td style={tdStyle}>{it.name}</td>
                <td style={{...tdStyle, color: T.text3}}>{it.horizon || '-'}</td>
                <td style={tdStyle}>
                  <StatusBadge status={it.status} />
                </td>
                <td style={{...tdStyle, textAlign: 'right', color: (it.return_pct || 0) > 0 ? T.up : T.down, fontFamily: T.fontMono}}>
                  {it.return_pct != null ? `${it.return_pct.toFixed(1)}%` : '—'}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function StatusBadge({status}) {
  const map = {
    win:     {label: '✅ 命中', color: T.up},
    loss:    {label: '❌ 停損', color: T.down},
    neutral: {label: '⚪ 平盤', color: T.text3},
  };
  const c = map[status] || {label: '—', color: T.text3};
  return <span style={{color: c.color, fontSize: 11, fontWeight: 500}}>{c.label}</span>;
}

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};

function DeepPromptArea({data}) {
  const DeepBtn = window.DeepPromptButton;
  if (!DeepBtn) return null;
  return (
    <div style={{marginTop: 24, textAlign: 'center'}}>
      <DeepBtn template="review" data={data} size="md" variant="primary" />
    </div>
  );
}

})();
