// components/_report-diff-block.jsx — Wave 12-D
// 报告版本对比 block: dropdown 选第二份报告 → 显示 diff table
//
// Props:
//   currentReport  {object}  — the report currently being viewed
//   allReports     {Array}   — all of the user's gaokao reports
//   lang           {string}  — 'zh' | 'en'

const ReportDiffBlock = ({ currentReport, allReports, lang }) => {
  const [otherId, setOtherId]   = React.useState('');
  const [diff, setDiff]         = React.useState(null);
  const [otherReport, setOtherReport] = React.useState(null);

  // Only show gaokao reports that are NOT the current report
  const candidates = React.useMemo(() => {
    if (!Array.isArray(allReports)) return [];
    return allReports.filter(
      (r) => r.type === 'gaokao' && r.id !== (currentReport && currentReport.id)
    ).sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
  }, [allReports, currentReport]);

  // Compute diff whenever selection changes
  React.useEffect(() => {
    if (!otherId) { setDiff(null); setOtherReport(null); return; }
    const other = candidates.find((r) => r.id === otherId);
    if (!other) { setDiff(null); setOtherReport(null); return; }
    setOtherReport(other);
    const fn = (typeof window !== 'undefined' && window.PB_diffReports)
      ? window.PB_diffReports
      : null;
    if (!fn) { setDiff(null); return; }
    try {
      setDiff(fn(other, currentReport));
    } catch (_) {
      setDiff(null);
    }
  }, [otherId, candidates, currentReport]);

  // i18n helpers
  const i = (zh, en) => lang === 'zh' ? zh : en;

  // Colour helpers
  const deltaColor = (n) =>
    n > 0 ? 'var(--pb-success)' : n < 0 ? 'var(--pb-danger)' : 'var(--pb-fg-muted)';
  const deltaPrefix = (n) => (n > 0 ? '+' : '');

  const bucketLabel = (b) => {
    if (b === 'reach')  return i('冲刺', 'Reach');
    if (b === 'match')  return i('匹配', 'Match');
    if (b === 'safety') return i('保底', 'Safety');
    return b || '-';
  };
  const bucketColor = { reach: 'var(--pb-danger)', match: 'var(--pb-gold-500)', safety: 'var(--pb-success)' };

  const formatDate = (iso) => {
    if (!iso) return '';
    try {
      const d = new Date(iso);
      if (isNaN(d)) return iso.slice(0, 10);
      const p = (n) => String(n).padStart(2, '0');
      return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
    } catch (_) { return iso.slice(0, 10); }
  };

  // Top-5 schools from a report (reach first, then match, then safety)
  const top5 = (report) => {
    if (!report || !report.data) return [];
    const schools = Array.isArray(report.data.schools) ? report.data.schools : [];
    const reach  = schools.filter((s) => s.bucket === 'reach').slice(0, 2);
    const match  = schools.filter((s) => s.bucket === 'match').slice(0, 2);
    const safety = schools.filter((s) => s.bucket === 'safety').slice(0, 1);
    return [...reach, ...match, ...safety];
  };

  const schoolDisplayName = (s) => {
    if (!s) return '';
    if (typeof s.name === 'string') return s.name;
    if (s.name) return s.name.zh || s.name.en || '';
    return String(s.schoolId || '');
  };

  // Summary counts for a report
  const sumOf = (report) => {
    if (!report || !report.data) return { reach: 0, match: 0, safety: 0 };
    const t = report.data.totals;
    if (t) return { reach: Number(t.reach || 0), match: Number(t.match || 0), safety: Number(t.safety || 0) };
    const sc = Array.isArray(report.data.schools) ? report.data.schools : [];
    return {
      reach:  sc.filter((s) => s.bucket === 'reach').length,
      match:  sc.filter((s) => s.bucket === 'match').length,
      safety: sc.filter((s) => s.bucket === 'safety').length,
    };
  };

  // ── Styles ──────────────────────────────────────────────────────────────
  const blockStyle = {
    background: 'var(--pb-surface)',
    border: '1px solid var(--pb-border)',
    borderRadius: 'var(--pb-radius-lg)',
    padding: '24px 28px',
    marginBottom: 0,
  };
  const labelStyle = {
    fontSize: 11,
    fontWeight: 600,
    textTransform: 'uppercase',
    letterSpacing: '0.09em',
    color: 'var(--pb-fg-muted)',
    marginBottom: 6,
  };
  const selectStyle = {
    width: '100%',
    padding: '8px 10px',
    fontSize: 13,
    border: '1px solid var(--pb-border)',
    borderRadius: 6,
    background: 'var(--pb-bg)',
    color: 'var(--pb-fg)',
    cursor: 'pointer',
  };
  const thStyle = {
    fontSize: 11,
    fontWeight: 600,
    textTransform: 'uppercase',
    letterSpacing: '0.07em',
    color: 'var(--pb-fg-muted)',
    padding: '8px 12px',
    textAlign: 'left',
    borderBottom: '1px solid var(--pb-border)',
  };
  const tdStyle = {
    fontSize: 13,
    padding: '8px 12px',
    borderBottom: '1px solid var(--pb-border)',
    verticalAlign: 'middle',
  };

  // ── No candidates ────────────────────────────────────────────────────────
  if (candidates.length === 0) return null;

  const curSum  = sumOf(currentReport);
  const otherSum = otherReport ? sumOf(otherReport) : null;

  return (
    <section data-testid="report-diff-block" style={{ padding: '24px 48px', background: 'var(--pb-paper)', borderBottom: '1px solid var(--pb-border)' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div style={{ marginBottom: 16 }}>
          <div className="pb-eyebrow" style={{ color: 'var(--pb-gold-700)', marginBottom: 6 }}>
            {i('报告版本对比', 'Report Comparison')}
          </div>
          <p style={{ fontSize: 13, color: 'var(--pb-fg-muted)', margin: 0 }}>
            {i(
              '选择一份历史报告，对比分数/位次变化后 reach/match/safety 的改变。',
              'Select a past report to compare how reach/match/safety counts and top schools changed.'
            )}
          </p>
        </div>

        {/* Dropdown */}
        <div style={{ maxWidth: 480, marginBottom: diff ? 24 : 0 }}>
          <div style={labelStyle}>{i('选择对比报告', 'Compare with')}</div>
          <select
            data-testid="diff-select-other"
            value={otherId}
            onChange={(e) => setOtherId(e.target.value)}
            style={selectStyle}
          >
            <option value="">{i('— 请选择历史报告 —', '— Select a past report —')}</option>
            {candidates.map((r) => (
              <option key={r.id} value={r.id}>
                {r.name || i('高考报告', 'Gaokao Report')}
                {' '}({formatDate(r.createdAt || r.date)})
                {r.data && r.data.score ? ` · ${r.data.score}分` : ''}
              </option>
            ))}
          </select>
        </div>

        {/* Diff summary */}
        {diff && otherReport && (
          <div data-testid="diff-summary">

            {/* Summary counts table */}
            <div style={{ marginBottom: 24 }}>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>
                {i('录取概率分布对比', 'Admission Tier Comparison')}
              </div>
              <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, minWidth: 480 }}>
                  <thead>
                    <tr>
                      <th style={thStyle}>{i('指标', 'Metric')}</th>
                      <th style={{ ...thStyle, textAlign: 'right' }}>
                        {otherReport.name || i('历史报告', 'Past report')}
                        <span style={{ display: 'block', fontWeight: 400, fontSize: 11 }}>
                          {otherReport.data && otherReport.data.score ? `${otherReport.data.score}分` : ''}
                          {otherReport.data && otherReport.data.rank ? ` #${otherReport.data.rank.toLocaleString()}` : ''}
                        </span>
                      </th>
                      <th style={{ ...thStyle, textAlign: 'right' }}>
                        {currentReport.name || i('当前报告', 'Current report')}
                        <span style={{ display: 'block', fontWeight: 400, fontSize: 11 }}>
                          {currentReport.data && currentReport.data.score ? `${currentReport.data.score}分` : ''}
                          {currentReport.data && currentReport.data.rank ? ` #${currentReport.data.rank.toLocaleString()}` : ''}
                        </span>
                      </th>
                      <th style={{ ...thStyle, textAlign: 'right' }}>{i('变化', 'Delta')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {[
                      { key: 'reach',  label: i('冲刺', 'Reach'),  color: 'var(--pb-danger)'  },
                      { key: 'match',  label: i('匹配', 'Match'),  color: 'var(--pb-gold-500)' },
                      { key: 'safety', label: i('保底', 'Safety'), color: 'var(--pb-success)' },
                      { key: 'total',  label: i('总计', 'Total'),  color: 'var(--pb-fg)'       },
                    ].map(({ key, label, color }) => {
                      const ov = key === 'total'
                        ? (otherSum.reach + otherSum.match + otherSum.safety)
                        : otherSum[key];
                      const cv = key === 'total'
                        ? (curSum.reach + curSum.match + curSum.safety)
                        : curSum[key];
                      const d = key === 'total' ? diff.summaryDelta.total : diff.summaryDelta[key];
                      return (
                        <tr key={key}>
                          <td style={{ ...tdStyle, color, fontWeight: 600 }}>{label}</td>
                          <td style={{ ...tdStyle, textAlign: 'right' }}>{ov}</td>
                          <td style={{ ...tdStyle, textAlign: 'right' }}>{cv}</td>
                          <td style={{ ...tdStyle, textAlign: 'right', fontWeight: 700, color: deltaColor(d), fontFamily: 'var(--pb-mono)' }}>
                            {d === 0 ? '—' : `${deltaPrefix(d)}${d}`}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Top-5 schools side by side */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 24 }}>
              {[
                { report: otherReport,   label: otherReport.name  || i('历史报告', 'Past report')   },
                { report: currentReport, label: currentReport.name || i('当前报告', 'Current report') },
              ].map(({ report, label }, ci) => {
                const schools = top5(report);
                return (
                  <div key={ci} style={{ background: 'var(--pb-surface)', border: '1px solid var(--pb-border)', borderRadius: 8, padding: 16 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--pb-fg-muted)', marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.07em' }}>
                      {label} — Top {schools.length}
                    </div>
                    {schools.length === 0 ? (
                      <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)' }}>{i('暂无院校数据', 'No school data')}</div>
                    ) : (
                      <ol style={{ margin: 0, paddingLeft: 18 }}>
                        {schools.map((s, idx) => (
                          <li key={idx} style={{ fontSize: 13, marginBottom: 6, lineHeight: 1.5 }}>
                            <span style={{ fontWeight: 600 }}>{schoolDisplayName(s)}</span>
                            {' '}
                            <span style={{ fontSize: 11, color: bucketColor[s.bucket] || 'var(--pb-fg-muted)' }}>
                              [{bucketLabel(s.bucket)}]
                            </span>
                            {' '}
                            <span style={{ fontFamily: 'var(--pb-mono)', fontSize: 12, color: 'var(--pb-fg-muted)' }}>
                              {s.probability}%
                            </span>
                          </li>
                        ))}
                      </ol>
                    )}
                  </div>
                );
              })}
            </div>

            {/* Probability changes (top 5 by |delta|) */}
            {diff.probabilityChanges.length > 0 && (
              <div style={{ marginBottom: 20 }}>
                <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>
                  {i('概率变动最大的院校（前 5）', 'Largest probability changes (top 5)')}
                </div>
                <div style={{ overflowX: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                    <thead>
                      <tr>
                        <th style={thStyle}>{i('院校', 'School')}</th>
                        <th style={{ ...thStyle, textAlign: 'center' }}>{i('类别', 'Tier')}</th>
                        <th style={{ ...thStyle, textAlign: 'right' }}>{i('历史概率', 'Past %')}</th>
                        <th style={{ ...thStyle, textAlign: 'right' }}>{i('当前概率', 'Now %')}</th>
                        <th style={{ ...thStyle, textAlign: 'right' }}>{i('变化', 'Delta')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {diff.probabilityChanges.slice(0, 5).map((ch, idx) => (
                        <tr key={idx}>
                          <td style={tdStyle}>{ch.name}</td>
                          <td style={{ ...tdStyle, textAlign: 'center' }}>
                            <span style={{ color: bucketColor[ch.bucket] || 'var(--pb-fg-muted)', fontWeight: 600, fontSize: 12 }}>
                              {bucketLabel(ch.bucket)}
                            </span>
                            {ch.bucketChanged && (
                              <span style={{ fontSize: 10, color: 'var(--pb-fg-muted)', display: 'block' }}>
                                {i('曾为', 'was')} {bucketLabel(ch.bucketFrom)}
                              </span>
                            )}
                          </td>
                          <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'var(--pb-mono)' }}>{ch.from}%</td>
                          <td style={{ ...tdStyle, textAlign: 'right', fontFamily: 'var(--pb-mono)' }}>{ch.to}%</td>
                          <td style={{ ...tdStyle, textAlign: 'right', fontWeight: 700, color: deltaColor(ch.delta), fontFamily: 'var(--pb-mono)' }}>
                            {ch.delta > 0 ? '+' : ''}{ch.delta}%
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* Added / removed schools */}
            {(diff.addedSchools.length > 0 || diff.removedSchools.length > 0) && (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                {diff.addedSchools.length > 0 && (
                  <div style={{ background: '#ecfdf5', border: '1px solid #a7f3d0', borderRadius: 8, padding: 14 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--pb-success)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.07em' }}>
                      + {i('新增院校', 'Added schools')} ({diff.addedSchools.length})
                    </div>
                    <ul style={{ margin: 0, paddingLeft: 16 }}>
                      {diff.addedSchools.slice(0, 5).map((s, i) => (
                        <li key={i} style={{ fontSize: 12, marginBottom: 4 }}>
                          {s.name}
                          <span style={{ color: bucketColor[s.bucket], marginLeft: 6, fontSize: 11 }}>[{bucketLabel(s.bucket)}]</span>
                        </li>
                      ))}
                      {diff.addedSchools.length > 5 && (
                        <li style={{ fontSize: 11, color: 'var(--pb-fg-muted)' }}>…{i(`共 ${diff.addedSchools.length} 所`, `${diff.addedSchools.length} total`)}</li>
                      )}
                    </ul>
                  </div>
                )}
                {diff.removedSchools.length > 0 && (
                  <div style={{ background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 8, padding: 14 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--pb-danger)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.07em' }}>
                      - {i('移出院校', 'Removed schools')} ({diff.removedSchools.length})
                    </div>
                    <ul style={{ margin: 0, paddingLeft: 16 }}>
                      {diff.removedSchools.slice(0, 5).map((s, idx) => (
                        <li key={idx} style={{ fontSize: 12, marginBottom: 4 }}>
                          {s.name}
                          <span style={{ color: bucketColor[s.bucket], marginLeft: 6, fontSize: 11 }}>[{bucketLabel(s.bucket)}]</span>
                        </li>
                      ))}
                      {diff.removedSchools.length > 5 && (
                        <li style={{ fontSize: 11, color: 'var(--pb-fg-muted)' }}>…{i(`共 ${diff.removedSchools.length} 所`, `${diff.removedSchools.length} total`)}</li>
                      )}
                    </ul>
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </section>
  );
};

// Make available on window for browser bundle (loaded via script tag)
if (typeof window !== 'undefined') {
  window.ReportDiffBlock = ReportDiffBlock;
}
