// 报告分享只读页 (C2)
// Route: /#/share/r/:token
// Fetches the shared report via GET /api/user/reports?op=share-view&token=...
// Renders a read-only view of the report with a PathBridge watermark footer.
// No auth required — this is a public page.

const SharePage = () => {
  const lang = useLang();

  // Extract token from hash: /#/share/r/<token>
  const token = React.useMemo(() => {
    const h = (typeof window !== 'undefined' ? window.location.hash : '') || '';
    // Strip query string, then match /share/r/<token>
    const noQs = h.indexOf('?') >= 0 ? h.slice(0, h.indexOf('?')) : h;
    const m = noQs.match(/\/share\/r\/([^/?#]+)/);
    return m ? m[1] : null;
  }, []);

  const [report, setReport] = React.useState(null);    // null=loading, false=error/notfound, obj=ok
  const [status, setStatus] = React.useState('loading'); // 'loading'|'ok'|'revoked'|'error'

  React.useEffect(() => {
    if (!token) { setStatus('error'); return; }
    fetch(`/api/user/reports?op=share-view&token=${encodeURIComponent(token)}`)
      .then((res) => {
        if (res.status === 404) { setStatus('revoked'); return null; }
        if (!res.ok) { setStatus('error'); return null; }
        return res.json();
      })
      .then((data) => {
        if (data && data.report) { setReport(data.report); setStatus('ok'); }
      })
      .catch(() => setStatus('error'));
  }, [token]);

  // ── Loading ──
  if (status === 'loading') {
    return (
      <div className="pb-scroll">
        <PBNav active="" />
        <section style={{ padding: '120px 48px', textAlign: 'center', color: 'var(--pb-fg-muted)' }} data-testid="share-loading">
          {lang === 'zh' ? '加载分享报告中…' : 'Loading shared report…'}
        </section>
        <PBFooter />
      </div>
    );
  }

  // ── Revoked / Not found ──
  if (status === 'revoked') {
    return (
      <div className="pb-scroll">
        <PBNav active="" />
        <section style={{ padding: '96px 48px', maxWidth: 720, margin: '0 auto', textAlign: 'center' }} data-testid="share-revoked">
          <div className="pb-eyebrow" style={{ marginBottom: 16 }}>PathBridge 启桥教育</div>
          <h1 className="pb-h1" style={{ fontSize: 36, marginBottom: 12 }}>
            {lang === 'zh' ? '分享已失效' : 'Share link expired'}
          </h1>
          <p style={{ fontSize: 15, color: 'var(--pb-fg-muted)', lineHeight: 1.65, marginBottom: 32 }}>
            {lang === 'zh'
              ? '该分享链接已被撤销或不存在。请联系报告所有者重新分享。'
              : 'This share link has been revoked or does not exist. Ask the report owner to re-share.'}
          </p>
          <button className="pb-btn pb-btn-primary" onClick={() => navigateTo('/')}>
            {lang === 'zh' ? '返回首页' : 'Back to home'}
          </button>
        </section>
        <PBFooter />
      </div>
    );
  }

  // ── Error ──
  if (status === 'error') {
    return (
      <div className="pb-scroll">
        <PBNav active="" />
        <section style={{ padding: '96px 48px', maxWidth: 720, margin: '0 auto', textAlign: 'center' }} data-testid="share-error">
          <h1 className="pb-h1" style={{ fontSize: 36, marginBottom: 12 }}>
            {lang === 'zh' ? '加载失败' : 'Failed to load'}
          </h1>
          <p style={{ fontSize: 15, color: 'var(--pb-fg-muted)', marginBottom: 32 }}>
            {lang === 'zh' ? '请检查网络连接后重试。' : 'Check your network connection and try again.'}
          </p>
          <button className="pb-btn pb-btn-primary" onClick={() => window.location.reload()}>
            {lang === 'zh' ? '重试' : 'Retry'}
          </button>
        </section>
        <PBFooter />
      </div>
    );
  }

  // ── Render report read-only ──
  const r = report;
  const data = r.data || {};

  if (r.type === 'gaokao' || r.type === 'gaokao-pro') {
    return <__ShareGaokaoView report={r} data={data} lang={lang} />;
  }

  // Generic fallback for other report types
  return (
    <div className="pb-scroll" data-testid="share-report-generic">
      <PBNav active="" />
      <section style={{ padding: '64px 48px', maxWidth: 900, margin: '0 auto' }}>
        <div className="pb-eyebrow" style={{ marginBottom: 12, color: 'var(--pb-gold-700)' }}>
          PathBridge · {lang === 'zh' ? '只读报告' : 'Read-only report'}
        </div>
        <h1 className="pb-h1" style={{ fontSize: 36, marginBottom: 24 }}>{r.name || (lang === 'zh' ? '报告' : 'Report')}</h1>
        <div style={{ fontSize: 14, color: 'var(--pb-fg-muted)' }}>{r.date}</div>
      </section>
      <__ShareWatermark lang={lang} />
      <PBFooter />
    </div>
  );
};

// ── Gaokao share view ─────────────────────────────────────────────────────────
const __ShareGaokaoView = ({ report, data, lang }) => {
  const totals = data.totals || { reach: 0, match: 0, safety: 0 };
  const schools = Array.isArray(data.schools) ? data.schools : [];
  const tierColor = { reach: 'var(--pb-danger)', match: 'var(--pb-navy-700)', safety: 'var(--pb-success)' };
  const tierLabel = { reach: lang === 'zh' ? '冲刺' : 'Reach', match: lang === 'zh' ? '匹配' : 'Match', safety: lang === 'zh' ? '保底' : 'Safety' };
  const provinceNames = { BJ: '北京', SH: '上海', GD: '广东', JS: '江苏', ZJ: '浙江', SD: '山东', HI: '海南' };
  const provinceLabel = lang === 'zh' ? (provinceNames[data.province] || data.province || '') : (data.province || '');

  return (
    <div className="pb-scroll" data-testid="share-report-gaokao">
      <PBNav active="" />

      {/* Header */}
      <section style={{ background: 'var(--pb-navy-900)', color: 'var(--pb-ivory)', padding: '56px 48px 64px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <div className="pb-row" style={{ justifyContent: 'space-between', marginBottom: 28 }}>
            <div className="pb-eyebrow" style={{ color: 'var(--pb-gold-500)' }}>
              {lang === 'zh' ? '高考志愿测算 · 只读分享' : 'Gaokao Report · Read-only share'}
            </div>
            <div className="pb-mono" style={{ fontSize: 11, color: 'rgba(255,255,255,0.45)', letterSpacing: '0.08em' }}>
              REPORT ID · {String(report.id).slice(0, 8).toUpperCase()} · {String(report.date || '').replace(/-/g, '.')}
            </div>
          </div>

          <h1 style={{ fontFamily: 'var(--pb-serif)', fontSize: 48, fontWeight: 500, margin: '0 0 12px', letterSpacing: '-0.005em' }}>
            {provinceLabel}{data.score != null ? ` · ${data.score} ${lang === 'zh' ? '分' : 'pts'}` : ''}{data.rank != null ? ` · ${data.rank.toLocaleString()} ${lang === 'zh' ? '名' : ''}` : ''}
          </h1>
          <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.6)', marginBottom: 40 }}>
            {(data.subjectCombo || '') + (data.year ? ' · ' + data.year : '')}
          </div>

          {/* Summary blocks */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24 }}>
            {[
              { label: lang === 'zh' ? '冲刺' : 'Reach', value: totals.reach, color: 'var(--pb-danger)' },
              { label: lang === 'zh' ? '匹配' : 'Match', value: totals.match, color: 'var(--pb-gold-500)' },
              { label: lang === 'zh' ? '保底' : 'Safety', value: totals.safety, color: '#7BC487' },
              { label: lang === 'zh' ? '总计' : 'Total', value: totals.reach + totals.match + totals.safety, color: 'var(--pb-gold-500)' },
            ].map((b, i) => (
              <div key={i} style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(201,169,104,0.2)', borderRadius: 'var(--pb-radius-lg)', padding: 24 }}>
                <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 14 }}>{b.label}</div>
                <div style={{ fontFamily: 'var(--pb-serif)', fontSize: 52, fontWeight: 500, color: b.color, lineHeight: 1 }}>{b.value}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* School list */}
      <section style={{ padding: '32px 48px 32px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <div className="pb-row" style={{ justifyContent: 'space-between', marginBottom: 20, alignItems: 'baseline' }}>
            <h2 className="pb-h2">{lang === 'zh' ? '完整院校列表' : 'Full school list'}</h2>
            <span className="pb-tag">{lang === 'zh' ? `共 ${schools.length} 所` : `${schools.length} schools`}</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {schools.map((s, i) => (
              <div key={s.schoolId || i} className="pb-card" style={{ padding: '18px 22px', display: 'grid', gridTemplateColumns: '110px 2fr 1fr 1.4fr', gap: 18, alignItems: 'center' }}>
                <span style={{ display: 'inline-flex', padding: '3px 10px', fontSize: 11, fontWeight: 600, borderRadius: 4, background: tierColor[s.bucket] + '15', color: tierColor[s.bucket], textTransform: 'uppercase', letterSpacing: '0.05em', justifySelf: 'start' }}>
                  {tierLabel[s.bucket]}
                </span>
                <div>
                  <div style={{ fontFamily: 'var(--pb-serif)', fontSize: 17, fontWeight: 600 }}>{s.name && (s.name[lang] || s.name.zh)}</div>
                  <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginTop: 2 }}>{s.location && (s.location[lang] || s.location.zh)} · {s.tier}</div>
                </div>
                <div style={{ fontFamily: 'var(--pb-mono)', fontSize: 13 }}>
                  <div>{s.cutoffScore} {lang === 'zh' ? '分' : 'pts'}</div>
                  <div style={{ fontSize: 11, color: 'var(--pb-fg-muted)' }}>#{s.cutoffRank != null ? s.cutoffRank.toLocaleString() : '—'}</div>
                </div>
                <div className="pb-prob-bar">
                  <div className="pb-prob-track">
                    <div className={`pb-prob-fill ${s.bucket}`} style={{ width: `${s.probability}%` }}/>
                  </div>
                  <span className="pb-mono" style={{ minWidth: 36, textAlign: 'right', fontWeight: 600, fontSize: 14 }}>{s.probability}%</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <__ShareWatermark lang={lang} />
      <PBFooter />
    </div>
  );
};

// ── Watermark footer ──────────────────────────────────────────────────────────
const __ShareWatermark = ({ lang }) => (
  <section style={{ padding: '24px 48px 48px', background: 'var(--pb-surface-alt)', borderTop: '1px solid var(--pb-border)' }}>
    <div style={{ maxWidth: 1280, margin: '0 auto', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ fontFamily: 'var(--pb-serif)', fontSize: 20, fontWeight: 600, color: 'var(--pb-navy-900)' }}>PathBridge</div>
        <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)' }}>启桥教育</div>
      </div>
      <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', textAlign: 'right' }}>
        <div>{lang === 'zh' ? '由 PathBridge 启桥教育生成' : 'Generated by PathBridge Education'}</div>
        <div style={{ marginTop: 4 }}>
          <button className="pb-btn pb-btn-primary pb-btn-sm" style={{ fontSize: 11 }} onClick={() => navigateTo('/gaokao')}>
            {lang === 'zh' ? '免费生成我的报告 →' : 'Generate my free report →'}
          </button>
        </div>
      </div>
    </div>
  </section>
);

window.SharePage = SharePage;
