// M43.1 — page-plans-compare.jsx
// Side-by-side draft comparison view: /#/plans/compare?a=<id>&b=<id>
// Requires authentication. Fetches plan-drafts-list, renders two columns
// with diff highlights (yellow for different schoolName, ±delta for cutoffScore).

const PlansComparePage = () => {
  const lang = (typeof window.useLang === 'function') ? window.useLang() : 'zh';
  const auth = (typeof window.useAuth === 'function') ? window.useAuth() : null;

  // Parse ?a=<id>&b=<id> from hash
  const [idA, idB] = React.useMemo(() => {
    try {
      const hash = window.location.hash || '';
      const qIdx = hash.indexOf('?');
      if (qIdx < 0) return [null, null];
      const params = new URLSearchParams(hash.slice(qIdx + 1));
      return [params.get('a') || null, params.get('b') || null];
    } catch (_) { return [null, null]; }
  }, []);

  const [drafts, setDrafts] = React.useState(null); // null=loading, {}=loaded
  const [fetchError, setFetchError] = React.useState(null);

  // Redirect anonymous users to login
  React.useEffect(() => {
    if (auth === null) return; // still resolving
    if (!auth.user) {
      navigateTo('/login?next=' + encodeURIComponent('#/plans/compare' + window.location.hash.slice(window.location.hash.indexOf('?'))));
    }
  }, [auth?.user]);

  React.useEffect(() => {
    if (!auth?.user) return;
    if (!idA || !idB) { setFetchError(lang === 'zh' ? '缺少草稿 ID 参数' : 'Missing draft ID parameters'); return; }
    let cancelled = false;
    fetch('/api/user/reports?op=plan-drafts-list', { credentials: 'same-origin' })
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error('fetch failed'))))
      .then((data) => {
        if (cancelled) return;
        const list = Array.isArray(data.drafts) ? data.drafts : [];
        const a = list.find((d) => d.id === idA);
        const b = list.find((d) => d.id === idB);
        if (!a || !b) { setFetchError(lang === 'zh' ? '未找到指定草稿（可能已被删除）' : 'One or both drafts not found'); return; }
        setDrafts({ a, b });
      })
      .catch((err) => {
        if (cancelled) return;
        setFetchError(lang === 'zh' ? '加载失败，请重试' : 'Load failed, please retry');
        if (typeof console !== 'undefined') console.error('[PathBridge] compare fetch error:', err);
      });
    return () => { cancelled = true; };
  }, [auth?.user, idA, idB]);

  if (!auth?.user) return null; // redirecting

  const BUCKET_COLOR = { reach: 'var(--pb-danger)', match: 'var(--pb-navy-700)', safety: 'var(--pb-success)' };
  const BUCKET_LABEL_ZH = { reach: '冲', match: '稳', safety: '保' };

  const renderProfile = (profile, score) => {
    if (!profile) return null;
    const subj = Array.isArray(profile.subjects) ? profile.subjects.join('') : (profile.subjects || '');
    return (
      <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', lineHeight: 1.8 }}>
        <div>{lang === 'zh' ? '省份' : 'Province'}: <strong>{profile.province || '—'}</strong></div>
        <div>{lang === 'zh' ? '年份' : 'Year'}: <strong>{profile.year || '—'}</strong></div>
        <div data-testid="compare-col-score">
          {lang === 'zh' ? '分数' : 'Score'}: <strong style={{ fontSize: 16, color: 'var(--pb-navy-900)' }}>{profile.score != null ? profile.score : '—'}</strong>
        </div>
        <div>{lang === 'zh' ? '位次' : 'Rank'}: <strong>{profile.rank != null ? ('#' + profile.rank.toLocaleString()) : '—'}</strong></div>
        {subj && <div>{lang === 'zh' ? '选科' : 'Subjects'}: <strong>{subj}</strong></div>}
      </div>
    );
  };

  const renderSummary = (summary) => {
    if (!summary) return null;
    const sm = summary;
    const parts = [
      sm.reach != null ? (lang === 'zh' ? `冲 ${sm.reach}` : `Reach ${sm.reach}`) : null,
      sm.match != null ? (lang === 'zh' ? `稳 ${sm.match}` : `Match ${sm.match}`) : null,
      sm.safety != null ? (lang === 'zh' ? `保 ${sm.safety}` : `Safety ${sm.safety}`) : null,
    ].filter(Boolean);
    if (parts.length === 0) return null;
    return (
      <div style={{ fontSize: 12, marginTop: 6, padding: '6px 10px', background: 'var(--pb-surface-alt)', borderRadius: 6, display: 'inline-block' }}>
        {parts.join(' / ')}
        {sm.localProvinceSlots && sm.localProvinceSlots.count != null && ` · ${lang === 'zh' ? '本省' : 'Local'} ${sm.localProvinceSlots.count}`}
      </div>
    );
  };

  const renderColumn = (draft, otherDraft, label) => {
    const planA = Array.isArray(draft.plan) ? draft.plan : [];
    const planB = Array.isArray(otherDraft.plan) ? otherDraft.plan : [];
    const maxSlots = Math.max(planA.length, planB.length);
    const minSlots = Math.min(planA.length, planB.length);
    const hasDifferentCount = planA.length !== planB.length;
    const createdLabel = draft.createdAt ? new Date(draft.createdAt).toLocaleDateString(lang === 'zh' ? 'zh-CN' : 'en-US') : '';

    return (
      <div style={{ flex: 1, minWidth: 0 }}>
        {/* Column header */}
        <div style={{ padding: '16px 20px', background: 'var(--pb-surface-alt)', borderBottom: '1px solid var(--pb-border)', borderRadius: '8px 8px 0 0' }}>
          <div style={{ fontFamily: 'var(--pb-serif)', fontSize: 16, fontWeight: 700, marginBottom: 6, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {label}: {draft.name}
          </div>
          <div style={{ fontSize: 11, color: 'var(--pb-fg-muted)', marginBottom: 10 }}>{createdLabel}</div>
          {renderProfile(draft.profile)}
          {renderSummary(draft.summary)}
          {hasDifferentCount && (
            <div style={{ marginTop: 8, fontSize: 11, color: '#92400e', background: '#fffbeb', padding: '4px 8px', borderRadius: 4, border: '1px solid #fcd34d' }}>
              {lang === 'zh' ? `对比仅前 ${minSlots} 槽（本方案共 ${planA.length} 槽）` : `Comparing first ${minSlots} slots (this plan has ${planA.length})`}
            </div>
          )}
        </div>

        {/* Slot rows */}
        <div style={{ border: '1px solid var(--pb-border)', borderTop: 'none', borderRadius: '0 0 8px 8px', overflow: 'hidden' }}>
          {planA.map((slot, idx) => {
            const otherSlot = planB[idx];
            // Diff: same slotIdx but different schoolName → yellow background
            const schoolDiff = otherSlot && slot.schoolName !== otherSlot.schoolName;
            // Diff: same school but different cutoffScore → show delta
            const sameName = otherSlot && slot.schoolName === otherSlot.schoolName;
            const cutoffDelta = sameName && otherSlot.cutoffScore != null && slot.cutoffScore != null
              ? slot.cutoffScore - otherSlot.cutoffScore
              : null;
            const rowBg = schoolDiff ? '#fff3c4' : (idx % 2 === 0 ? 'transparent' : 'var(--pb-surface-alt)');
            const bucket = slot.bucket || 'match';
            const bucketColor = BUCKET_COLOR[bucket] || 'var(--pb-fg-muted)';
            const bucketLabel = lang === 'zh' ? (BUCKET_LABEL_ZH[bucket] || bucket) : bucket;

            return (
              <div
                key={idx}
                data-testid={`compare-slot-${label.toLowerCase()}-${idx}`}
                style={{
                  display: 'grid',
                  gridTemplateColumns: '32px 36px 1fr 52px 52px',
                  gap: 4,
                  alignItems: 'center',
                  padding: '8px 12px',
                  borderTop: idx > 0 ? '1px solid var(--pb-border)' : 'none',
                  background: rowBg,
                  fontSize: 12,
                }}
              >
                <div style={{ fontFamily: 'var(--pb-mono)', fontSize: 11, color: 'var(--pb-fg-muted)' }}>
                  {String(slot.slotIdx || idx + 1).padStart(2, '0')}
                </div>
                <div>
                  <span style={{
                    display: 'inline-block', padding: '1px 5px', fontSize: 10, fontWeight: 700,
                    borderRadius: 3, background: bucketColor + '18', color: bucketColor,
                  }}>{bucketLabel}</span>
                </div>
                <div style={{ fontWeight: 600, fontFamily: 'var(--pb-serif)', fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
                  title={slot.schoolName}>
                  {slot.schoolName}
                  {schoolDiff && (
                    <span style={{ display: 'inline-block', marginLeft: 4, fontSize: 9, color: '#92400e', verticalAlign: 'middle' }}>●</span>
                  )}
                </div>
                <div style={{ textAlign: 'right', fontFamily: 'var(--pb-mono)', fontSize: 12, fontWeight: 600, color: bucketColor }}>
                  {slot.probability != null ? slot.probability + '%' : '—'}
                </div>
                <div style={{ textAlign: 'right', fontFamily: 'var(--pb-mono)', fontSize: 11, color: 'var(--pb-fg-muted)' }}>
                  {slot.cutoffScore != null ? (
                    <span>
                      {slot.cutoffScore}
                      {cutoffDelta !== null && cutoffDelta !== 0 && (
                        <span
                          data-testid={`compare-cutoff-delta-${idx}`}
                          style={{ marginLeft: 2, fontSize: 10, color: cutoffDelta > 0 ? 'var(--pb-success)' : 'var(--pb-danger)', fontWeight: 700 }}
                        >
                          {cutoffDelta > 0 ? '+' : ''}{cutoffDelta}
                        </span>
                      )}
                    </span>
                  ) : '—'}
                </div>
              </div>
            );
          })}
          {planA.length === 0 && (
            <div style={{ padding: '20px', textAlign: 'center', color: 'var(--pb-fg-muted)', fontSize: 12 }}>
              {lang === 'zh' ? '该草稿无方案数据' : 'No plan data in this draft'}
            </div>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="pb-scroll" style={{ background: 'var(--pb-bg)' }}>
      {typeof window.PBNav !== 'undefined' && <window.PBNav active="dashboard" />}

      <section style={{ padding: '32px 24px 96px', maxWidth: 1400, margin: '0 auto' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
          <button
            type="button"
            data-testid="compare-back-btn"
            className="pb-btn pb-btn-ghost pb-btn-sm"
            onClick={() => navigateTo('/dashboard')}
            style={{ whiteSpace: 'nowrap' }}
          >
            ← {lang === 'zh' ? '返回 Dashboard' : 'Back to Dashboard'}
          </button>
          <h2 style={{ fontFamily: 'var(--pb-serif)', fontSize: 24, fontWeight: 700, margin: 0 }}>
            {lang === 'zh' ? '志愿方案对比' : 'Plan Comparison'}
          </h2>
        </div>

        {/* Loading / Error states */}
        {!drafts && !fetchError && (
          <div style={{ padding: '40px', textAlign: 'center', color: 'var(--pb-fg-muted)', fontSize: 14 }}>
            {lang === 'zh' ? '加载草稿数据…' : 'Loading draft data…'}
          </div>
        )}
        {fetchError && (
          <div style={{ padding: '20px', background: '#fdecea', color: '#9b1c1c', borderRadius: 8, fontSize: 13 }}>
            {fetchError}
          </div>
        )}

        {/* Two-column compare layout */}
        {drafts && (
          <div>
            {/* Score delta summary banner */}
            {(() => {
              const scoreA = drafts.a.profile && drafts.a.profile.score;
              const scoreB = drafts.b.profile && drafts.b.profile.score;
              if (scoreA == null || scoreB == null || scoreA === scoreB) return null;
              const delta = scoreA - scoreB;
              return (
                <div
                  data-testid="compare-score-delta-banner"
                  style={{ marginBottom: 16, padding: '10px 16px', background: '#f0f9ff', border: '1px solid #bae6fd', borderRadius: 8, fontSize: 13, color: '#0369a1' }}
                >
                  {lang === 'zh'
                    ? `方案 A 分数 ${scoreA} vs 方案 B 分数 ${scoreB}（差 ${delta > 0 ? '+' : ''}${delta} 分）`
                    : `Plan A score ${scoreA} vs Plan B score ${scoreB} (delta ${delta > 0 ? '+' : ''}${delta})`}
                </div>
              );
            })()}

            <div
              data-testid="compare-columns"
              style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}
            >
              {renderColumn(drafts.a, drafts.b, lang === 'zh' ? '方案 A' : 'Plan A')}
              {renderColumn(drafts.b, drafts.a, lang === 'zh' ? '方案 B' : 'Plan B')}
            </div>

            {/* Legend */}
            <div style={{ marginTop: 16, fontSize: 11, color: 'var(--pb-fg-muted)', display: 'flex', gap: 20, flexWrap: 'wrap' }}>
              <span><span style={{ display: 'inline-block', width: 12, height: 12, background: '#fff3c4', border: '1px solid #fcd34d', marginRight: 4, verticalAlign: 'middle' }}></span>
                {lang === 'zh' ? '同槽位校名不同（高亮）' : 'Different school at same slot (highlighted)'}</span>
              <span>{lang === 'zh' ? '±N = 投档线差值（相对对侧方案）' : '±N = cutoff score delta vs the other plan'}</span>
            </div>
          </div>
        )}
      </section>

      {typeof window.PBFooter !== 'undefined' && <window.PBFooter />}
    </div>
  );
};

window.PlansComparePage = PlansComparePage;
