// 高考志愿深度报告 — 12 题向导 (M3.7 / H1.6)
// Wired to /api/gaokao/calculate.
// H1.6: anonymous preview allowed — unauthenticated users see the wizard,
// submit, and receive an inline paywall preview (ProPaywallBlock) instead of
// being redirected to /login. Authenticated users still land on /#/report?id=.

const GaokaoProPage = () => {
  const t = useT();
  const lang = useLang();
  const g = t.gk;
  const p = g.pro;
  const auth = (typeof window.useAuth === 'function') ? window.useAuth() : null;
  // 会员门槛总开关 — when off (functional testing) anon users get the full
  // report inline (ProPaywallBlock renders clear); notices drop 解锁 claims.
  const gatesOn = !!(window.PBAccessGates && window.PBAccessGates.gatesEnabled());

  // ─── Base form fields (pre-filled from URL hash) ──────────────────────────
  const initialBase = React.useMemo(() => {
    const h = (typeof window !== 'undefined' && window.location && window.location.hash) || '';
    const qi = h.indexOf('?');
    const params = qi >= 0 ? new URLSearchParams(h.slice(qi + 1)) : new URLSearchParams();
    const PROVINCE_CODES = ['BJ', 'SH', 'GD', 'ZJ', 'JS', 'SD', 'HA', 'HE', 'SC', 'HB', 'HN', 'HI', 'TJ', 'LN', 'FJ', 'CQ', 'AH', 'JX', 'GZ', 'GX', 'HL', 'JL', 'GS', 'SX', 'SN', 'YN', 'QH', 'NX', 'NM', 'XJ', null];
    const provinceCodeFromIdx = (idx) => PROVINCE_CODES[Number(idx) || 0] || 'BJ';
    const province = params.get('province');
    // Distinguish a numeric index ("11") from a literal code ("HI"). Pure
    // digits → index lookup; anything alpha → uppercase code.
    const provinceCode = province
      ? (/^\d+$/.test(province) ? provinceCodeFromIdx(province) : province.toUpperCase())
      : 'HI';
    return {
      province: provinceCode,
      year: Number(params.get('year')) || 2024,
      score: Number(params.get('score')) || 580,
      rank: Number(params.get('rank')) || 20000,
      subjectCombo: params.get('subjectCombo') || ['物化生', '物化政', '史政地'][Number(params.get('subjectIdx')) || 0],
      majorCategory: params.get('majorCategory') || ['default','cs','electronics','finance','medicine','liberalArts','cs','electronics','math','engineering','liberalArts'][Number(params.get('majorIdx')) || 1] || 'cs',
    };
  }, []);

  // Wave 9-C — mobile responsive: JS-driven layout
  const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' && window.innerWidth < 640);
  React.useEffect(() => {
    const handler = () => setIsMobile(window.innerWidth < 640);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);

  const [base, setBase] = React.useState(initialBase);

  // ─── 12-Q intake state ────────────────────────────────────────────────────
  const Q = (p && Array.isArray(p.questions)) ? p.questions : [];

  const initialIntake = React.useMemo(() => ({
    schoolPref: [],
    majorInterest: [],
    careerPlan: '',
    geo: [],
    schoolTier: 'm211',
    antiAdjust: 'group',
    family: 'pub',
    gender: 'any',
    body: ['none'],
    holland: { R: 5, I: 5, A: 5, S: 5, E: 5, C: 5 },
    subjectStable: 'stable',
    abroadOpenness: 'no',
  }), []);

  const [intake, setIntake] = React.useState(initialIntake);
  const [step, setStep] = React.useState(0);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  // H1.6 — anonymous preview result (set after successful 200 anon response)
  const [anonReport, setAnonReport] = React.useState(null);

  // ─── 生成进度反馈（QA 2026-06-10）──────────────────────────────────────────
  // 报告生成实测约 60 秒（服务端检索+概率+叙述），此前全程只有"生成中…"
  // 三个字。按耗时分四个阶段提示并显示已用秒数；阶段文案描述真实流水线
  // 步骤，非装饰动画。Hooks 必须位于下方 auth.loading 早退之前（Rules of
  // Hooks——首版放在早退之后触发过 "Rendered more hooks" 崩溃）。
  const [genElapsed, setGenElapsed] = React.useState(0);
  React.useEffect(() => {
    if (!submitting) { setGenElapsed(0); return undefined; }
    const t0 = Date.now();
    const iv = setInterval(() => setGenElapsed(Math.round((Date.now() - t0) / 1000)), 1000);
    return () => clearInterval(iv);
  }, [submitting]);
  const genStage = () => {
    const zh = lang === 'zh';
    if (genElapsed < 12) return zh ? '① 检索真实投档线与候选院校' : '① Retrieving real cutoffs & candidates';
    if (genElapsed < 30) return zh ? '② 计算 60 校录取概率与置信区间' : '② Computing 60-school probabilities & confidence bands';
    if (genElapsed < 50) return zh ? '③ 撰写策略叙述与海外备选' : '③ Writing strategy narrative & overseas section';
    return zh ? '④ 汇总报告，即将完成' : '④ Finalizing the report';
  };

  const buildLoginNext = () => {
    const h = (typeof window !== 'undefined' && window.location && window.location.hash) || '';
    const target = h.startsWith('#/gaokao/pro') ? h : '#/gaokao/pro';
    return '/login?next=' + encodeURIComponent(target);
  };

  // H1.6: no auth gate redirect — anonymous users can access the wizard.
  // Only show a loading spinner while auth context is initializing.
  if (!auth || auth.loading) {
    return (
      <div className="pb-scroll" data-testid="gaokao-pro-loading">
        <PBNav active="gaokao" />
        <section style={{ padding: '120px 48px', textAlign: 'center', color: 'var(--pb-fg-muted)' }}>
          {lang === 'zh' ? '加载中…' : 'Loading…'}
        </section>
        <PBFooter />
      </div>
    );
  }

  // ─── Helpers: per-question field updaters ─────────────────────────────────
  const toggleMulti = (qid, value) => {
    setIntake((prev) => {
      const cur = Array.isArray(prev[qid]) ? prev[qid] : [];
      const has = cur.includes(value);
      const nextArr = has ? cur.filter((v) => v !== value) : cur.concat([value]);
      return { ...prev, [qid]: nextArr };
    });
  };
  const setSingle = (qid, value) => setIntake((prev) => ({ ...prev, [qid]: value }));
  const setHollandKey = (key, value) => {
    const v = Math.max(1, Math.min(10, Number(value) || 0));
    setIntake((prev) => ({ ...prev, holland: { ...prev.holland, [key]: v } }));
  };

  // ─── Step structure: 3 questions / step → 4 steps total ───────────────────
  const STEPS = [
    Q.slice(0, 3),
    Q.slice(3, 6),
    Q.slice(6, 9),
    Q.slice(9, 12),
  ];
  const totalSteps = STEPS.length;
  const isLast = step === totalSteps - 1;
  const onPrev = () => { setError(null); setStep((s) => Math.max(0, s - 1)); };
  const onNext = () => { setError(null); setStep((s) => Math.min(totalSteps - 1, s + 1)); };

  // ─── Submit ───────────────────────────────────────────────────────────────
  const onSubmit = async () => {
    setError(null);
    setSubmitting(true);
    try {
      const r = await fetch('/api/gaokao/calculate', {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          baseFormFields: base,
          twelveQuestions: intake,
          lang,
        }),
      });
      let data = {};
      try { data = await r.json(); } catch (_) {}

      // 201 — authenticated, report persisted → navigate to report page
      if (r.status === 201 && data.report && data.report.id) {
        navigateTo('/report?id=' + encodeURIComponent(data.report.id));
        return;
      }

      // 200 — anonymous preview (H1.6) → show inline paywall block
      if (r.status === 200 && data.report) {
        setAnonReport(data.report);
        return;
      }

      if (r.status === 400) {
        setError(lang === 'zh' ? '请检查表单字段' : 'Please review the form');
        return;
      }
      if (r.status === 429) {
        setError(lang === 'zh' ? '请求过于频繁，请稍后再试' : 'Too many requests, try again later');
        return;
      }
      setError(lang === 'zh' ? '生成失败，请稍后再试' : 'Generation failed, please try again');
    } catch (err) {
      setError(lang === 'zh' ? '网络错误' : 'Network error');
    } finally {
      setSubmitting(false);
    }
  };

  // ─── Render: single question (kind-aware) ─────────────────────────────────
  const renderQuestion = (q) => {
    if (!q) return null;
    if (q.kind === 'multi') {
      const cur = Array.isArray(intake[q.id]) ? intake[q.id] : [];
      return (
        <div key={q.id} data-testid={'q-' + q.id} style={{ marginBottom: 28 }}>
          <label className="pb-label" style={{ fontSize: 14, marginBottom: 12, display: 'block' }}>{q.label}</label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {q.options.map((opt) => {
              const on = cur.includes(opt.value);
              return (
                <span
                  key={opt.value}
                  data-testid={'q-' + q.id + '-' + opt.value}
                  onClick={() => toggleMulti(q.id, opt.value)}
                  style={{
                    padding: '8px 14px', fontSize: 13, borderRadius: 100,
                    border: '1px solid var(--pb-border-strong)',
                    background: on ? 'var(--pb-navy-900)' : 'transparent',
                    color: on ? 'var(--pb-gold-500)' : 'var(--pb-fg)',
                    cursor: 'pointer', userSelect: 'none',
                  }}
                >{opt.label}</span>
              );
            })}
          </div>
        </div>
      );
    }
    if (q.kind === 'single') {
      const cur = intake[q.id] || '';
      return (
        <div key={q.id} data-testid={'q-' + q.id} style={{ marginBottom: 28 }}>
          <label className="pb-label" style={{ fontSize: 14, marginBottom: 12, display: 'block' }}>{q.label}</label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {q.options.map((opt) => {
              const on = cur === opt.value;
              return (
                <span
                  key={opt.value}
                  data-testid={'q-' + q.id + '-' + opt.value}
                  onClick={() => setSingle(q.id, opt.value)}
                  style={{
                    padding: '8px 14px', fontSize: 13, borderRadius: 100,
                    border: '1px solid var(--pb-border-strong)',
                    background: on ? 'var(--pb-navy-900)' : 'transparent',
                    color: on ? 'var(--pb-gold-500)' : 'var(--pb-fg)',
                    cursor: 'pointer', userSelect: 'none',
                  }}
                >{opt.label}</span>
              );
            })}
          </div>
        </div>
      );
    }
    if (q.kind === 'holland') {
      return (
        <div key={q.id} data-testid={'q-' + q.id} style={{ marginBottom: 28 }}>
          <label className="pb-label" style={{ fontSize: 14, marginBottom: 12, display: 'block' }}>{q.label}</label>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
            {q.options.map((opt) => (
              <div key={opt.value} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <span style={{ minWidth: 80, fontSize: 13 }}>{opt.label}</span>
                <input
                  type="range" min={1} max={10}
                  value={intake.holland[opt.value]}
                  onChange={(e) => setHollandKey(opt.value, e.target.value)}
                  data-testid={'q-holland-' + opt.value}
                  style={{ flex: 1 }}
                />
                <span className="pb-mono" style={{ minWidth: 24, textAlign: 'right', fontSize: 13 }}>{intake.holland[opt.value]}</span>
              </div>
            ))}
          </div>
        </div>
      );
    }
    return null;
  };

  // ─── Step indicator ───────────────────────────────────────────────────────
  const StepIndicator = () => (
    <div className="pb-row" style={{ gap: 8, marginBottom: 24, alignItems: 'center' }} data-testid="gaokao-pro-step-indicator">
      {STEPS.map((_s, i) => (
        <div key={i} style={{
          flex: 1, height: 4, borderRadius: 2,
          background: i <= step ? 'var(--pb-gold-500)' : 'var(--pb-border)'
        }}/>
      ))}
      <span className="pb-mono" style={{ marginLeft: 12, fontSize: 11, color: 'var(--pb-fg-muted)' }}>
        {p.step} {step + 1} {p.of} {totalSteps}
      </span>
    </div>
  );

  // ─── Base form summary (shown atop the wizard so user sees what'll be sent) ─
  const BaseSummary = () => (
    <div className="pb-card" style={{ background: 'var(--pb-surface-alt)', padding: 20, marginBottom: 20 }} data-testid="gaokao-pro-base-summary">
      <div className="pb-eyebrow" style={{ marginBottom: 8 }}>{lang === 'zh' ? '基础信息' : 'Basics'}</div>
      <div className="pb-pro-base-grid" style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4, 1fr)', gap: 12, fontSize: 13 }}>
        <div><div style={{ fontSize: 11, color: 'var(--pb-fg-muted)' }}>{g.formProvince}</div><div className="pb-mono" style={{ fontWeight: 600 }}>{(() => {
          // Show 海南, not the raw code "HI" — PBPlanRules carries per-province names.
          const r = typeof window !== 'undefined' && window.PBPlanRules && window.PBPlanRules.PLAN_RULES;
          const entry = r && r[base.province];
          if (entry) return lang === 'zh' ? (entry.nameZh || base.province) : (entry.nameEn || base.province);
          return base.province;
        })()}</div></div>
        <div><div style={{ fontSize: 11, color: 'var(--pb-fg-muted)' }}>{g.formYear}</div><div className="pb-mono" style={{ fontWeight: 600 }}>{base.year}</div></div>
        <div><div style={{ fontSize: 11, color: 'var(--pb-fg-muted)' }}>{g.formScore}</div><div className="pb-mono" style={{ fontWeight: 600 }}>{base.score}</div></div>
        <div><div style={{ fontSize: 11, color: 'var(--pb-fg-muted)' }}>{g.formRank}</div><div className="pb-mono" style={{ fontWeight: 600 }}>{Number(base.rank).toLocaleString()}</div></div>
      </div>
    </div>
  );

  // ─── H1.6 — Anonymous preview result ─────────────────────────────────────
  // When an anonymous user submits the wizard, show the paywall inline.
  if (anonReport) {
    return (
      <div className="pb-scroll" data-testid="gaokao-pro-anon-result">
        <PBNav active="gaokao" />

        <section style={{ padding: '64px 48px 40px', background: 'var(--pb-paper)', borderBottom: '1px solid var(--pb-border)' }}>
          <div style={{ maxWidth: 880, margin: '0 auto' }}>
            <div className="pb-eyebrow" style={{ marginBottom: 12 }}>{p.eyebrow}</div>
            <h1 className="pb-h1" style={{ fontSize: 44, whiteSpace: 'pre-line', maxWidth: 720, marginBottom: 14 }}>{p.title}</h1>
            <p style={{ fontSize: 15, color: 'var(--pb-fg-muted)', maxWidth: 640, lineHeight: 1.65 }}>{p.sub}</p>
          </div>
        </section>

        <section style={{ padding: '40px 48px 96px', background: 'var(--pb-bg)' }}>
          <div style={{ maxWidth: 880, margin: '0 auto' }}>
            {/* Anonymous preview notice */}
            <div style={{
              marginBottom: 24, padding: '12px 16px',
              background: 'var(--pb-gold-500)15',
              border: '1px solid var(--pb-gold-500)',
              borderRadius: 8, fontSize: 13, color: 'var(--pb-fg)',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
            }} data-testid="pro-anon-notice">
              <span>
                {gatesOn
                  ? (lang === 'zh'
                      ? '以下为匿名预览，报告未保存。登录后可查看完整 60 校方案并保存报告。'
                      : 'Anonymous preview — report not saved. Sign in to view all 60 schools and save your report.')
                  : (lang === 'zh'
                      ? '完整报告已生成（未保存）。登录后可将报告保存到「我的报告」。'
                      : 'Full report generated (not saved). Sign in to save it to My Reports.')
                }
              </span>
              <button
                className="pb-btn pb-btn-primary pb-btn-sm"
                onClick={() => navigateTo(buildLoginNext())}
                data-testid="pro-anon-notice-login"
              >
                {lang === 'zh' ? '登录' : 'Sign in'}
              </button>
            </div>

            <ProPaywallBlock
              report={anonReport}
              lang={lang}
              onLogin={() => navigateTo(buildLoginNext())}
            />
          </div>
        </section>

        <PBFooter />
      </div>
    );
  }

  // ─── Render: wizard (shown to all users — auth and anon) ─────────────────
  return (
    <div className="pb-scroll" data-testid="gaokao-pro-page">
      <PBNav active="gaokao" />

      {/* Wave 9-C: mobile styles handled via JS isMobile state */}

      <section className="pb-pro-header" style={{ padding: isMobile ? '40px 20px 24px' : '64px 48px 40px', background: 'var(--pb-paper)', borderBottom: '1px solid var(--pb-border)' }}>
        <div style={{ maxWidth: 880, margin: '0 auto' }}>
          <div className="pb-eyebrow" style={{ marginBottom: 12 }}>{p.eyebrow}</div>
          <h1 className="pb-h1" style={{ fontSize: isMobile ? 30 : 44, whiteSpace: 'pre-line', maxWidth: 720, marginBottom: 14 }}>{p.title}</h1>
          <p style={{ fontSize: 15, color: 'var(--pb-fg-muted)', maxWidth: 640, lineHeight: 1.65 }}>{p.sub}</p>
        </div>
      </section>

      <section className="pb-pro-section" style={{ padding: isMobile ? '20px 16px 64px' : '40px 48px 96px', background: 'var(--pb-bg)' }}>
        <div style={{ maxWidth: 880, margin: '0 auto' }}>
          <BaseSummary />

          {/* H1.6 — soft CTA for anonymous users above the wizard */}
          {!auth.user && (
            <div className="pb-pro-anon-cta" style={{
              marginBottom: 20, padding: '12px 16px',
              background: 'var(--pb-surface-alt)',
              border: '1px solid var(--pb-border)',
              borderRadius: 8, fontSize: 13, color: 'var(--pb-fg-muted)',
              display: 'flex', flexDirection: isMobile ? 'column' : 'row',
              alignItems: isMobile ? 'stretch' : 'center',
              justifyContent: 'space-between', gap: isMobile ? 8 : 16,
            }} data-testid="pro-anon-soft-cta">
              <span>
                {gatesOn
                  ? (lang === 'zh'
                      ? '💡 登录后可保存报告并解锁完整 60 校推荐'
                      : '💡 Sign in to save your report and unlock all 60 recommendations')
                  : (lang === 'zh'
                      ? '💡 登录后可保存生成的报告，随时回看'
                      : '💡 Sign in to save your generated reports for later')
                }
              </span>
              <button
                className="pb-btn pb-btn-ghost pb-btn-sm"
                onClick={() => navigateTo(buildLoginNext())}
                data-testid="pro-anon-wizard-login"
              >
                {lang === 'zh' ? '登录 / 注册' : 'Sign in'}
              </button>
            </div>
          )}

          <div className="pb-card pb-pro-wizard" style={{ padding: isMobile ? '20px 16px' : 32 }} data-testid="gaokao-pro-wizard">
            <StepIndicator />

            {STEPS[step] && STEPS[step].map((q) => renderQuestion(q))}

            {error && (
              <div data-testid="gaokao-pro-error" style={{ marginTop: 12, padding: '10px 12px', background: '#fdecea', color: '#9b1c1c', border: '1px solid #f3b5b1', borderRadius: 8, fontSize: 13 }}>
                {error}
              </div>
            )}

            <div className="pb-row pb-pro-nav-row" style={{ justifyContent: 'space-between', marginTop: 24, flexWrap: isMobile ? 'wrap' : 'nowrap', gap: isMobile ? 8 : undefined }}>
              <button
                className="pb-btn pb-btn-ghost"
                onClick={onPrev}
                disabled={step === 0 || submitting}
                data-testid="gaokao-pro-prev"
                style={{ visibility: step === 0 ? 'hidden' : 'visible' }}
              >{p.prev}</button>

              {!isLast ? (
                <button
                  className="pb-btn pb-btn-primary"
                  onClick={onNext}
                  data-testid="gaokao-pro-next"
                >{p.next}</button>
              ) : (
                <button
                  className="pb-btn pb-btn-primary"
                  onClick={onSubmit}
                  disabled={submitting}
                  data-testid="gaokao-pro-submit"
                >{submitting ? p.submitting : p.submit}</button>
              )}
            </div>
            {submitting && (
              <div data-testid="gaokao-pro-progress" style={{
                marginTop: 14, padding: '10px 14px', borderRadius: 10,
                border: '1px solid var(--pb-border)', background: 'var(--pb-surface-alt)',
                fontSize: 12, color: 'var(--pb-fg-muted)', lineHeight: 1.6,
              }}>
                <span style={{ fontWeight: 600 }}>{genStage()}</span>
                <span style={{ fontFamily: 'var(--pb-mono)', marginLeft: 8 }}>{genElapsed}s</span>
                <span style={{ marginLeft: 8 }}>
                  {lang === 'zh' ? '· 首次生成约需 60–90 秒，请勿关闭页面' : '· First run takes 60–90s — keep this page open'}
                </span>
              </div>
            )}
          </div>

          <div style={{ marginTop: 24, fontSize: 12, color: 'var(--pb-fg-muted)', textAlign: 'center' }}>
            {p.poweredTemplate}
          </div>
        </div>
      </section>

      <PBFooter />
    </div>
  );
};

window.GaokaoProPage = GaokaoProPage;
