// 霍兰德职业兴趣测评页 — A6
// Route: /#/gaokao/holland
// Data: window.PBHolland (lib/gaokao-holland.js)
// Quiz → RIASEC top-3 code → recommended 专业大类 (linked to A4 major pages)
// Item bank: O*NET Interest Profiler (public domain), translated to Chinese.

const GaokaoHollandPage = () => {
  const lang = useLang();
  const pbH = (typeof window !== 'undefined' && window.PBHolland) || {};
  const ITEMS = pbH.ITEMS || [];
  const scoreAnswers = pbH.scoreAnswers || (() => ({}));
  const topCode = pbH.topCode || (() => '???');
  const recommendCategories = pbH.recommendCategories || (() => []);

  // ── State ──────────────────────────────────────────────────────────────────
  const [answers, setAnswers] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [hollandCode, setHollandCode] = React.useState('');
  const [recCats, setRecCats] = React.useState([]);

  // ── Derived ────────────────────────────────────────────────────────────────
  const answeredCount = Object.keys(answers).length;
  const allAnswered = answeredCount === ITEMS.length;

  // ── Handlers ───────────────────────────────────────────────────────────────
  const handleAnswer = (id, val) => {
    setAnswers((prev) => ({ ...prev, [id]: val }));
  };

  const handleSubmit = () => {
    const scores = scoreAnswers(answers);
    const code = topCode(scores);
    const cats = recommendCategories(code);
    setHollandCode(code);
    setRecCats(cats);
    setSubmitted(true);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleRetake = () => {
    setAnswers({});
    setSubmitted(false);
    setHollandCode('');
    setRecCats([]);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // ── Styles ─────────────────────────────────────────────────────────────────
  const cardStyle = {
    background: 'var(--pb-surface)',
    border: '1px solid var(--pb-border)',
    borderRadius: 10,
    padding: '20px 24px',
    marginBottom: 16,
  };

  const sectionLabelStyle = {
    fontSize: 11,
    fontWeight: 600,
    color: 'var(--pb-fg-muted)',
    textTransform: 'uppercase',
    letterSpacing: '0.06em',
    marginBottom: 10,
  };

  // RIASEC dimension → label
  const DIM_LABELS = {
    R: lang === 'zh' ? '实用型 (R)' : 'Realistic (R)',
    I: lang === 'zh' ? '研究型 (I)' : 'Investigative (I)',
    A: lang === 'zh' ? '艺术型 (A)' : 'Artistic (A)',
    S: lang === 'zh' ? '社会型 (S)' : 'Social (S)',
    E: lang === 'zh' ? '企业型 (E)' : 'Enterprising (E)',
    C: lang === 'zh' ? '常规型 (C)' : 'Conventional (C)',
  };

  // Dimension badge colors
  const DIM_COLORS = {
    R: { bg: '#fef3c7', color: '#92400e' },
    I: { bg: '#dbeafe', color: '#1e40af' },
    A: { bg: '#fdf4ff', color: '#7e22ce' },
    S: { bg: '#d1fae5', color: '#065f46' },
    E: { bg: '#ffedd5', color: '#9a3412' },
    C: { bg: '#f1f5f9', color: '#475569' },
  };

  // Category badge colors (mirror page-gaokao-major.jsx)
  const categoryColor = {
    '工科':  { bg: '#dbeafe', color: '#1e40af' },
    '理科':  { bg: '#d1fae5', color: '#065f46' },
    '理学':  { bg: '#ecfeff', color: '#155e75' },
    '文学':  { bg: '#fef3c7', color: '#92400e' },
    '经济学': { bg: '#ede9fe', color: '#5b21b6' },
    '管理学': { bg: '#fce7f3', color: '#9d174d' },
    '医学':  { bg: '#fee2e2', color: '#991b1b' },
    '法学':  { bg: '#ffedd5', color: '#9a3412' },
    '历史学': { bg: '#f1f5f9', color: '#475569' },
    '哲学':  { bg: '#f0fdf4', color: '#166534' },
    '社会学': { bg: '#fdf4ff', color: '#7e22ce' },
    '教育学': { bg: '#fff7ed', color: '#9a3412' },
  };
  const getCatStyle = (cat) =>
    categoryColor[cat] || { bg: 'var(--pb-surface-alt)', color: 'var(--pb-fg-muted)' };

  // ── Results view ─────────────────────────────────────────────────────────
  if (submitted) {
    const codeLetters = hollandCode.split('');

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

        {/* Hero */}
        <section style={{
          padding: '48px 48px 32px',
          background: 'var(--pb-navy-900)',
          color: '#fff',
        }}>
          <div style={{ maxWidth: 800, margin: '0 auto' }}>
            {/* Breadcrumb */}
            <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.55)', marginBottom: 20, display: 'flex', gap: 8, alignItems: 'center' }}>
              <span
                style={{ cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 3 }}
                onClick={() => { window.location.hash = '#/gaokao'; }}
              >
                {lang === 'zh' ? '高考测算' : 'Gaokao Calculator'}
              </span>
              <span>›</span>
              <span style={{ color: '#fff' }}>
                {lang === 'zh' ? '霍兰德测评结果' : 'Holland RIASEC Result'}
              </span>
            </div>

            <h1 style={{ fontFamily: 'var(--pb-serif)', fontSize: 28, fontWeight: 700, margin: '0 0 8px', lineHeight: 1.2 }}>
              {lang === 'zh' ? '你的兴趣倾向参考' : 'Your Interest Profile (Reference)'}
            </h1>
            <p style={{ fontSize: 14, color: 'rgba(255,255,255,0.6)', margin: 0 }}>
              {lang === 'zh'
                ? '以下结果仅供参考，不代表权威的心理测评结论。'
                : 'Results are for reference only, not a definitive psychological assessment.'}
            </p>
          </div>
        </section>

        {/* Body */}
        <section style={{ padding: '32px 48px 80px', background: 'var(--pb-bg)' }}>
          <div style={{ maxWidth: 800, margin: '0 auto' }}>

            {/* Holland code card */}
            <div style={{ ...cardStyle, textAlign: 'center', padding: '32px 24px' }}>
              <div style={sectionLabelStyle}>
                {lang === 'zh' ? '霍兰德兴趣代码 (Top 3)' : 'Holland Interest Code (Top 3)'}
              </div>
              <div
                data-testid="holland-code"
                style={{
                  fontFamily: 'var(--pb-mono)',
                  fontSize: 56,
                  fontWeight: 800,
                  letterSpacing: '0.12em',
                  color: 'var(--pb-navy-900)',
                  margin: '12px 0',
                }}
              >
                {hollandCode}
              </div>
              <div style={{ display: 'flex', justifyContent: 'center', gap: 8, flexWrap: 'wrap', marginTop: 8 }}>
                {codeLetters.map((letter, i) => {
                  const dc = DIM_COLORS[letter] || {};
                  return (
                    <span key={i} style={{
                      padding: '4px 14px', fontSize: 13, fontWeight: 600, borderRadius: 6,
                      background: dc.bg, color: dc.color,
                    }}>
                      {DIM_LABELS[letter] || letter}
                    </span>
                  );
                })}
              </div>
              <div style={{ marginTop: 14, fontSize: 12, color: 'var(--pb-fg-muted)' }}>
                {lang === 'zh'
                  ? '⚠ 兴趣倾向参考，仅反映你当前的自我描述，不作为升学或职业规划的唯一依据。'
                  : '⚠ Interest reference only. Reflects your self-description; not a sole basis for college or career planning.'}
              </div>
            </div>

            {/* Recommended categories */}
            {recCats.length > 0 && (
              <div style={cardStyle}>
                <div style={sectionLabelStyle}>
                  {lang === 'zh' ? '匹配专业大类' : 'Matching Major Categories'}
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                  {recCats.map((cat) => {
                    const cs = getCatStyle(cat);
                    return (
                      <span
                        key={cat}
                        data-testid="holland-category"
                        style={{
                          padding: '6px 16px', fontSize: 14, fontWeight: 600,
                          borderRadius: 8, cursor: 'default',
                          background: cs.bg, color: cs.color,
                          border: `1px solid ${cs.color}33`,
                        }}
                      >
                        {cat}
                      </span>
                    );
                  })}
                </div>
                <div style={{ marginTop: 12, fontSize: 12, color: 'var(--pb-fg-muted)' }}>
                  {lang === 'zh'
                    ? '以上大类与你的兴趣倾向较匹配，可在「专业百科」中进一步了解相关专业的课程与就业。'
                    : 'These major categories align with your interests — explore specific majors in the major encyclopedia.'}
                </div>
              </div>
            )}

            {/* Quick-link to major pages */}
            <div style={{ textAlign: 'center', marginTop: 24, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
              <button
                data-testid="holland-retake"
                className="pb-btn pb-btn-primary"
                onClick={handleRetake}
              >
                {lang === 'zh' ? '重新测评' : 'Retake Quiz'}
              </button>
              <button
                className="pb-btn pb-btn-link pb-btn-sm"
                onClick={() => { window.location.hash = '#/gaokao'; }}
              >
                {lang === 'zh' ? '← 返回测算页' : '← Back to calculator'}
              </button>
            </div>
          </div>
        </section>

        <PBFooter />
      </div>
    );
  }

  // ── Quiz view ─────────────────────────────────────────────────────────────
  return (
    <div className="pb-scroll" data-testid="holland-quiz">
      <PBNav active="gaokao" />

      {/* Hero */}
      <section style={{
        padding: '48px 48px 32px',
        background: 'var(--pb-navy-900)',
        color: '#fff',
      }}>
        <div style={{ maxWidth: 800, margin: '0 auto' }}>
          {/* Breadcrumb */}
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.55)', marginBottom: 20, display: 'flex', gap: 8, alignItems: 'center' }}>
            <span
              style={{ cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 3 }}
              onClick={() => { window.location.hash = '#/gaokao'; }}
            >
              {lang === 'zh' ? '高考测算' : 'Gaokao Calculator'}
            </span>
            <span>›</span>
            <span style={{ color: '#fff' }}>
              {lang === 'zh' ? '霍兰德职业兴趣测评' : 'Holland RIASEC Interest Quiz'}
            </span>
          </div>

          <h1 style={{ fontFamily: 'var(--pb-serif)', fontSize: 28, fontWeight: 700, margin: '0 0 10px', lineHeight: 1.2 }}>
            {lang === 'zh' ? '霍兰德职业兴趣测评' : 'Holland RIASEC Interest Profiler'}
          </h1>
          <p style={{ fontSize: 14, color: 'rgba(255,255,255,0.7)', margin: '0 0 6px' }}>
            {lang === 'zh'
              ? `共 ${ITEMS.length} 题，每题选"喜欢"或"不喜欢"，测评你在六类兴趣维度（RIASEC）上的倾向。`
              : `${ITEMS.length} items — mark each activity as "Like" or "Dislike" to reveal your RIASEC interest profile.`}
          </p>

          {/* O*NET citation */}
          <div
            data-testid="holland-citation"
            style={{
              marginTop: 12,
              padding: '8px 14px',
              background: 'rgba(255,255,255,0.08)',
              borderRadius: 6,
              fontSize: 12,
              color: 'rgba(255,255,255,0.6)',
              lineHeight: 1.5,
            }}
          >
            {lang === 'zh'
              ? '题库改编自 O*NET 兴趣测评（O*NET Interest Profiler），美国劳工部/就业培训局，公有领域。结果标注为兴趣倾向参考，非权威测评结论。'
              : 'Items adapted from the O*NET Interest Profiler, U.S. Department of Labor / Employment and Training Administration, public domain. Results are labeled as interest-tendency reference, not a definitive assessment.'}
          </div>
        </div>
      </section>

      {/* Progress bar */}
      <div style={{ background: 'var(--pb-surface)', borderBottom: '1px solid var(--pb-border)', padding: '12px 48px' }}>
        <div style={{ maxWidth: 800, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ flex: 1, height: 6, background: 'var(--pb-border)', borderRadius: 4, overflow: 'hidden' }}>
            <div style={{
              height: '100%',
              width: `${ITEMS.length > 0 ? Math.round((answeredCount / ITEMS.length) * 100) : 0}%`,
              background: 'var(--pb-navy-700)',
              borderRadius: 4,
              transition: 'width 0.2s ease',
            }} />
          </div>
          <div style={{ fontSize: 13, color: 'var(--pb-fg-muted)', flexShrink: 0 }}>
            {answeredCount} / {ITEMS.length}
          </div>
        </div>
      </div>

      {/* Questions */}
      <section style={{ padding: '32px 48px 48px', background: 'var(--pb-bg)' }}>
        <div style={{ maxWidth: 800, margin: '0 auto' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {ITEMS.map((item, idx) => {
              const ans = answers[item.id];
              const dimC = DIM_COLORS[item.dimension] || {};
              return (
                <div
                  key={item.id}
                  data-testid="holland-question"
                  style={{
                    ...cardStyle,
                    marginBottom: 0,
                    display: 'flex',
                    alignItems: 'center',
                    gap: 16,
                    border: ans === 1
                      ? '1px solid var(--pb-success)'
                      : ans === 0
                        ? '1px solid var(--pb-border)'
                        : '1px solid var(--pb-border)',
                    background: ans === 1
                      ? 'var(--pb-success-bg, #f0fdf4)'
                      : 'var(--pb-surface)',
                    padding: '14px 20px',
                  }}
                >
                  {/* Question number */}
                  <div style={{
                    flexShrink: 0, width: 28, height: 28, borderRadius: '50%',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    background: 'var(--pb-surface-alt)', fontSize: 12, fontWeight: 600,
                    color: 'var(--pb-fg-muted)',
                  }}>
                    {idx + 1}
                  </div>

                  {/* Question text */}
                  <div style={{ flex: 1, fontSize: 14, color: 'var(--pb-fg)', lineHeight: 1.4 }}>
                    {item.zh}
                  </div>

                  {/* Dimension badge */}
                  <span style={{
                    flexShrink: 0, padding: '2px 8px', fontSize: 11, fontWeight: 600,
                    borderRadius: 4, background: dimC.bg, color: dimC.color,
                  }}>
                    {item.dimension}
                  </span>

                  {/* Like / Dislike buttons */}
                  <div style={{ flexShrink: 0, display: 'flex', gap: 8 }}>
                    <button
                      data-testid="holland-btn-yes"
                      className="pb-btn pb-btn-sm"
                      style={{
                        background: ans === 1 ? 'var(--pb-success)' : 'var(--pb-surface-alt)',
                        color: ans === 1 ? '#fff' : 'var(--pb-fg)',
                        border: ans === 1 ? '1px solid var(--pb-success)' : '1px solid var(--pb-border)',
                        fontWeight: ans === 1 ? 700 : 400,
                        minWidth: 60,
                      }}
                      onClick={() => handleAnswer(item.id, 1)}
                    >
                      {lang === 'zh' ? '喜欢' : 'Like'}
                    </button>
                    <button
                      data-testid="holland-btn-no"
                      className="pb-btn pb-btn-sm"
                      style={{
                        background: ans === 0 ? 'var(--pb-fg-muted)' : 'var(--pb-surface-alt)',
                        color: ans === 0 ? '#fff' : 'var(--pb-fg)',
                        border: ans === 0 ? '1px solid var(--pb-fg-muted)' : '1px solid var(--pb-border)',
                        fontWeight: ans === 0 ? 700 : 400,
                        minWidth: 60,
                      }}
                      onClick={() => handleAnswer(item.id, 0)}
                    >
                      {lang === 'zh' ? '不喜欢' : 'Dislike'}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Submit */}
          <div style={{ marginTop: 28, textAlign: 'center' }}>
            <button
              data-testid="holland-submit"
              className="pb-btn pb-btn-primary"
              disabled={!allAnswered}
              style={{
                opacity: allAnswered ? 1 : 0.45,
                cursor: allAnswered ? 'pointer' : 'not-allowed',
                fontSize: 15,
                padding: '12px 40px',
              }}
              onClick={allAnswered ? handleSubmit : undefined}
            >
              {lang === 'zh'
                ? (allAnswered ? '查看我的兴趣代码 →' : `还剩 ${ITEMS.length - answeredCount} 题未作答`)
                : (allAnswered ? 'See My Interest Code →' : `${ITEMS.length - answeredCount} items remaining`)}
            </button>
          </div>

          <div style={{ marginTop: 16, textAlign: 'center' }}>
            <button
              className="pb-btn pb-btn-link pb-btn-sm"
              onClick={() => { window.location.hash = '#/gaokao'; }}
            >
              {lang === 'zh' ? '← 返回测算页' : '← Back to calculator'}
            </button>
          </div>
        </div>
      </section>

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

// Expose to window (mirrors sibling page-gaokao-*.jsx pattern)
Object.assign(window, { GaokaoHollandPage });
