// _pro-paywall-block.jsx — H1.6 Pro mode anonymous paywall preview
//
// Renders the anonymous Pro report preview:
//   • Section 0 ("成绩定位" / "Score positioning") — fully visible
//   • Sections 1-3 — blurred with a paywall overlay
//   • Schools list — first 3 rows clear, rows 4+ blurred
//   • CTA — "登录注册看完整 60 校 + 留学双轨备选" button → /#/login
//
// Props:
//   report  — the report object returned by /api/gaokao/calculate (200 anon)
//   lang    — 'zh' | 'en'
//   onLogin — optional callback, defaults to navigateTo('/login') (chrome.jsx
//             prepends '#' so the SPA hash router lands on /#/login)

const ProPaywallBlock = ({ report, lang, onLogin }) => {
  const data = (report && report.data) || {};
  const sections = Array.isArray(data.sections) ? data.sections : [];
  const schools  = Array.isArray(data.schools)  ? data.schools  : [];
  const totals   = data.totals || { reach: 0, match: 0, safety: 0 };

  const SCHOOL_PREVIEW = 3; // first N schools shown unblurred

  const zh = lang === 'zh';

  // 会员门槛总开关 (lib/access-gates.js) — when off (functional testing) the
  // anonymous report renders in full: sections clear, every school visible,
  // no lock overlay. The CTA card stays as a soft "登录保存" note because anon
  // reports genuinely aren't persisted.
  const gated = !!(window.PBAccessGates && window.PBAccessGates.gatesEnabled());

  const handleLogin = () => {
    if (typeof onLogin === 'function') return onLogin();
    navigateTo('/login');
  };

  const tierColor = { reach: 'var(--pb-danger)', match: 'var(--pb-navy-700)', safety: 'var(--pb-success)' };
  const tierLabel = {
    reach:  zh ? '冲刺' : 'Reach',
    match:  zh ? '稳妥' : 'Match',
    safety: zh ? '保底' : 'Safety',
  };

  // ─── CTA card ─────────────────────────────────────────────────────────────
  const CTACard = () => (
    <div
      data-testid="pro-anon-cta"
      style={{
        background: 'var(--pb-paper)',
        border: '1.5px solid var(--pb-gold-500)',
        borderRadius: 16,
        padding: '32px 40px',
        textAlign: 'center',
        marginTop: 32,
      }}
    >
      <div className="pb-eyebrow" style={{ color: 'var(--pb-gold-700)', marginBottom: 10 }}>
        {zh ? '完整深度报告' : 'Full deep report'}
      </div>
      <h3 style={{ fontFamily: 'var(--pb-serif)', fontSize: 22, fontWeight: 600, margin: '0 0 10px' }}>
        {zh
          ? `已匹配 ${schools.length} 所院校（冲 ${totals.reach} / 稳 ${totals.match} / 保 ${totals.safety}）`
          : `${schools.length} schools matched (reach ${totals.reach} / match ${totals.match} / safety ${totals.safety})`
        }
      </h3>
      <p style={{ fontSize: 14, color: 'var(--pb-fg-muted)', marginBottom: 24, lineHeight: 1.65 }}>
        {gated
          ? (zh
              ? '登录注册即可解锁完整 60 校志愿方案、四段式 AI 策略建议，以及留学双轨备选。'
              : 'Sign in to unlock all 60 school recommendations, full AI strategy narrative, and international dual-track options.')
          : (zh
              ? '完整报告已全部展示。登录后可将报告保存到「我的报告」，随时回看。'
              : 'The full report is shown above. Sign in to save it to My Reports for later.')
        }
      </p>
      <button
        className="pb-btn pb-btn-primary"
        onClick={handleLogin}
        data-testid="pro-anon-cta-btn"
        style={{ fontSize: 15, padding: '12px 32px', borderRadius: 100 }}
      >
        {gated
          ? (zh ? '登录 / 注册 — 解锁完整报告' : 'Sign in / Register — Unlock full report')
          : (zh ? '登录 / 注册 — 保存报告' : 'Sign in / Register — Save report')}
      </button>
    </div>
  );

  // ─── Render ────────────────────────────────────────────────────────────────
  return (
    <div data-testid="pro-paywall-block" style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>

      {/* ── Narrative sections ── */}
      <div>
        <div className="pb-eyebrow" style={{ color: 'var(--pb-gold-700)', marginBottom: 12 }}>
          {gated
            ? (zh ? '策略分析（预览）' : 'Strategy analysis (preview)')
            : (zh ? '策略分析' : 'Strategy analysis')}
        </div>

        {/* Section 0 — fully visible */}
        {sections.length > 0 && (
          <div className="pb-card" data-testid="pro-section-preview-0" style={{ marginBottom: 16 }}>
            <h3 style={{ fontFamily: 'var(--pb-serif)', fontSize: 20, fontWeight: 600, margin: '0 0 12px' }}>
              {sections[0].title}
            </h3>
            <p style={{ fontSize: 14, lineHeight: 1.75, color: 'var(--pb-fg)', margin: 0, whiteSpace: 'pre-line' }}>
              {sections[0].body}
            </p>
          </div>
        )}

        {/* Sections 1-3 — clear when gates are off, blurred paywall when on */}
        {sections.length > 1 && !gated && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} data-testid="pro-sections-full">
            {sections.slice(1).map((s, i) => (
              <div key={i} className="pb-card">
                <h3 style={{ fontFamily: 'var(--pb-serif)', fontSize: 20, fontWeight: 600, margin: '0 0 12px' }}>
                  {s.title}
                </h3>
                <p style={{ fontSize: 14, lineHeight: 1.75, color: 'var(--pb-fg)', margin: 0, whiteSpace: 'pre-line' }}>
                  {s.body}
                </p>
              </div>
            ))}
          </div>
        )}
        {sections.length > 1 && gated && (
          <div style={{ position: 'relative' }}>
            <div
              data-testid="pro-sections-blurred"
              style={{ filter: 'blur(5px)', pointerEvents: 'none', userSelect: 'none' }}
              aria-hidden="true"
            >
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                {sections.slice(1).map((s, i) => (
                  <div key={i} className="pb-card">
                    <h3 style={{ fontFamily: 'var(--pb-serif)', fontSize: 20, fontWeight: 600, margin: '0 0 12px' }}>
                      {s.title}
                    </h3>
                    <p style={{ fontSize: 14, lineHeight: 1.75, color: 'var(--pb-fg)', margin: 0, whiteSpace: 'pre-line' }}>
                      {s.body}
                    </p>
                  </div>
                ))}
              </div>
            </div>
            {/* Lock overlay */}
            <div style={{
              position: 'absolute', inset: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: 'rgba(var(--pb-bg-rgb, 15,22,36), 0.55)',
              borderRadius: 12,
            }}>
              <div style={{ textAlign: 'center', padding: '16px 24px', background: 'var(--pb-paper)', borderRadius: 12, boxShadow: '0 4px 24px rgba(0,0,0,0.18)' }}>
                <div style={{ fontSize: 28, marginBottom: 8 }}>🔒</div>
                <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 8 }}>
                  {zh ? '登录后查看完整策略建议' : 'Sign in to read full strategy'}
                </div>
                <button
                  className="pb-btn pb-btn-primary pb-btn-sm"
                  onClick={handleLogin}
                  data-testid="pro-anon-unlock-btn"
                  style={{ fontSize: 13 }}
                >
                  {zh ? '立即登录' : 'Sign in now'}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* ── Schools list ── */}
      <div>
        <div className="pb-eyebrow" style={{ color: 'var(--pb-gold-700)', marginBottom: 12 }}>
          {gated
            ? (zh ? `院校匹配（前 ${SCHOOL_PREVIEW} 所预览，共 ${schools.length} 所）`
                  : `Schools (${SCHOOL_PREVIEW} preview of ${schools.length} matched)`)
            : (zh ? `院校匹配（共 ${schools.length} 所）`
                  : `Schools (${schools.length} matched)`)}
        </div>

        <div className="pb-card" style={{ padding: 0, overflow: 'hidden' }} data-testid="pro-anon-schools">
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--pb-border)', background: 'var(--pb-surface-alt)' }}>
                <th style={{ padding: '12px 20px', textAlign: 'left', fontSize: 11, fontWeight: 600, color: 'var(--pb-fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                  {zh ? '档位' : 'Tier'}
                </th>
                <th style={{ padding: '12px 16px', textAlign: 'left', fontSize: 11, fontWeight: 600, color: 'var(--pb-fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                  {zh ? '院校' : 'School'}
                </th>
                <th style={{ padding: '12px 16px', textAlign: 'right', fontSize: 11, fontWeight: 600, color: 'var(--pb-fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                  {zh ? '录取概率' : 'Prob.'}
                </th>
              </tr>
            </thead>
            <tbody>
              {schools.slice(0, Math.max(schools.length, SCHOOL_PREVIEW)).map((s, i) => {
                const blurred = gated && i >= SCHOOL_PREVIEW;
                const rowStyle = blurred
                  ? { borderTop: '1px solid var(--pb-border)', filter: 'blur(4px)', pointerEvents: 'none', userSelect: 'none' }
                  : { borderTop: '1px solid var(--pb-border)' };
                return (
                  <tr
                    key={s.schoolId || i}
                    style={rowStyle}
                    aria-hidden={blurred ? 'true' : undefined}
                    data-testid={blurred ? 'pro-anon-school-blurred' : 'pro-anon-school-row'}
                  >
                    <td style={{ padding: '16px 20px' }}>
                      <span style={{
                        display: 'inline-flex', padding: '3px 10px', fontSize: 11, fontWeight: 600,
                        borderRadius: 4, background: (tierColor[s.bucket] || 'var(--pb-border)') + '15',
                        color: tierColor[s.bucket] || 'var(--pb-fg-muted)', textTransform: 'uppercase', letterSpacing: '0.05em',
                      }}>
                        {tierLabel[s.bucket] || s.bucket}
                      </span>
                    </td>
                    <td style={{ padding: '16px 16px' }}>
                      <div style={{ fontWeight: 600, fontSize: 15, fontFamily: 'var(--pb-serif)' }}>
                        {s.name && (s.name[lang] || s.name.zh || s.name.en || '')}
                      </div>
                      <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginTop: 2 }}>
                        {s.location && (s.location[lang] || s.location.zh || '')}
                        {s.tier ? ' · ' + s.tier : ''}
                      </div>
                      {/* QA 2026-06-11 项1 — 组级下钻：海南填报单位是院校专业组，
                          报告 60 校此前只有院校级。组号/投档线与引擎最低可达组同源。 */}
                      {(s.groupNum || s.cutoffScore != null) && (
                        <div data-testid="pro-school-group-line" style={{ fontSize: 11, color: 'var(--pb-fg-muted)', marginTop: 3, fontFamily: 'var(--pb-mono)' }}>
                          {s.groupNum ? (zh ? `专业组 ${s.groupNum}` : `Group ${s.groupNum}`) : null}
                          {s.cutoffScore != null
                            ? `${s.groupNum ? ' · ' : ''}${zh ? '投档线' : 'Cutoff'} ${s.cutoffScore}${s.cutoffRank != null ? ` / #${Number(s.cutoffRank).toLocaleString()}` : ''}`
                            : ''}
                        </div>
                      )}
                      {Array.isArray(s.topMajors) && s.topMajors.length > 0 && (
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>
                          {s.topMajors.map((m, mj) => (
                            <span key={mj} data-testid="pro-school-top-major" style={{ padding: '2px 6px', fontSize: 10, background: 'var(--pb-surface-alt)', border: '1px solid var(--pb-border)', borderRadius: 4, whiteSpace: 'nowrap' }}>
                              {m.name} {m.minScore}
                            </span>
                          ))}
                        </div>
                      )}
                    </td>
                    <td style={{ padding: '16px 16px', textAlign: 'right', fontFamily: 'var(--pb-mono)', fontWeight: 600 }}>
                      {s.probability != null ? s.probability + '%' : '—'}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>

          {/* Blurred rows CTA anchor */}
          {gated && schools.length > SCHOOL_PREVIEW && (
            <div style={{
              borderTop: '1px solid var(--pb-border)',
              padding: '12px 20px',
              background: 'var(--pb-surface-alt)',
              fontSize: 12,
              color: 'var(--pb-fg-muted)',
              textAlign: 'center',
            }}>
              {zh
                ? `还有 ${schools.length - SCHOOL_PREVIEW} 所院校被隐藏 — 登录解锁`
                : `${schools.length - SCHOOL_PREVIEW} more schools hidden — sign in to unlock`
              }
            </div>
          )}
        </div>
      </div>

      {/* ── CTA card ── */}
      <CTACard />
    </div>
  );
};

window.ProPaywallBlock = ProPaywallBlock;
