// 专业百科页 — A4
// Route: /#/gaokao/major/:code
// Data: window.PBMajorMeta (lib/gaokao-major-meta.js)
// Shows: 中文/英文名, 大类, 主修课程, 就业方向, 就业率(估算), 起薪(估算), 学科评估A类

// ── major legacyCode → 一级学科 discipline key (教育部第四轮 2017) ───────────
// Keyed by the pre-migration short code (entry.legacyCode); values must match
// round4-2017.json "disciplines" entries exactly.
const MAJOR_TO_DISCIPLINE = {
  cs:    '0812 计算机科学与技术',
  ee:    '0808 电气工程',
  me:    '0802 机械工程',
  ce:    '0814 土木工程',
  med:   '1002 临床医学',
  law:   '0301 法学',
  math:  '0701 数学',
  phys:  '0702 物理学',
  chem:  '0703 化学',
  bio:   '0710 生物学',
  fin:   '0202 应用经济学',
  eco:   '0201 理论经济学',
  mgmt:  '1202 工商管理',
  chi:   '0501 中国语言文学',
  eng:   '0502 外国语言文学',
  hist:  '0602 中国史',
  phil:  '0101 哲学',
  soc:   '0303 社会学',
  psy:   '0402 心理学',
  edu:   '0401 教育学',
  nurs:  '1011 护理学',
};

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

  // ── Parse route: extract code from hash path ────────────────────────────────
  const getCode = () => {
    const h = window.location.hash || '';
    const m = h.match(/\/gaokao\/major\/([^/?#]+)/);
    return m ? decodeURIComponent(m[1]) : null;
  };

  const [code, setCode] = React.useState(getCode);

  React.useEffect(() => {
    const onHash = () => setCode(getCode());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // ── Fetch 第四轮学科评估 JSON (once, cached in module-level var) ──────────────
  const [round4Data, setRound4Data] = React.useState(null);
  React.useEffect(() => {
    if (GaokaoMajorPage._round4Cache) {
      setRound4Data(GaokaoMajorPage._round4Cache);
      return;
    }
    fetch('/data/discipline-assessment/round4-2017.json')
      .then((r) => r.ok ? r.json() : null)
      .then((json) => {
        if (json && json.disciplines) {
          GaokaoMajorPage._round4Cache = json;
          setRound4Data(json);
        }
      })
      .catch(() => { /* silent — fall back to sample */ });
  }, []);

  // ── Fetch 教育部 2024 本科专业目录 (catalog-level entries, once) ──────────────
  // undefined = loading, null = unavailable, object = { byCode, source }
  const [catalog, setCatalog] = React.useState(
    GaokaoMajorPage._catalogCache !== undefined ? GaokaoMajorPage._catalogCache : undefined
  );
  React.useEffect(() => {
    if (GaokaoMajorPage._catalogCache !== undefined) return;
    fetch('/data/gaokao/majors/catalog.json')
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => {
        let val = null;
        if (json && Array.isArray(json.majors)) {
          const byCode = new Map();
          for (const m of json.majors) byCode.set(m.code, m);
          val = { byCode, source: json.source || null };
        }
        GaokaoMajorPage._catalogCache = val;
        setCatalog(val);
      })
      .catch(() => { GaokaoMajorPage._catalogCache = null; setCatalog(null); });
  }, []);

  // ── Fetch 专业类级 国标 详情 index (培养目标/核心课程, once) ───────────────────
  // undefined = loading, null = unavailable, object = { byClass, codeToClass }
  const [classDetail, setClassDetail] = React.useState(
    GaokaoMajorPage._classDetailCache !== undefined ? GaokaoMajorPage._classDetailCache : undefined
  );
  React.useEffect(() => {
    if (GaokaoMajorPage._classDetailCache !== undefined) return;
    fetch('/data/gaokao/majors/major-class-detail/index.json')
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => {
        const val = json && json.byClass ? json : null;
        GaokaoMajorPage._classDetailCache = val;
        setClassDetail(val);
      })
      .catch(() => { GaokaoMajorPage._classDetailCache = null; setClassDetail(null); });
  }, []);

  // ── Lookup from window.PBMajorMeta ──────────────────────────────────────────
  const pbMeta = (typeof window !== 'undefined' && window.PBMajorMeta) || {};
  const getMajorMeta = pbMeta.getMajorMeta || (() => null);
  const normalizeCode = pbMeta.normalizeMajorCode || ((c) => c);

  const major = code ? getMajorMeta(code) : null;
  // Catalog-level entry (official MOE 2024 directory) — used as the rendering
  // basis when there is no curated detail entry for this code.
  const catalogEntry = code && catalog ? catalog.byCode.get(normalizeCode(code)) || null : null;

  // ── Resolve 专业类级 国标 详情 for this major ──────────────────────────────
  // majorClass comes from: catalogEntry (official) → catalog lookup by code →
  // the detail index's own code→class map. The 国标 detail is keyed by majorClass.
  const resolveGuobiao = () => {
    if (!classDetail || !classDetail.byClass) return null;
    const nc = code ? normalizeCode(code) : null;
    let mClass =
      (catalogEntry && catalogEntry.majorClass) ||
      (catalog && nc && catalog.byCode.get(nc) && catalog.byCode.get(nc).majorClass) ||
      (nc && classDetail.codeToClass && classDetail.codeToClass[nc]) ||
      null;
    if (!mClass) return null;
    const d = classDetail.byClass[mClass] || null;
    if (!d) return null;
    // Per-major core-course view (some classes give per-major示例); else class list.
    const majorName = (catalogEntry && catalogEntry.name) || (major && major.nameZh) || null;
    let perMajorCourses = null;
    let perMajorKey = null;
    if (d.coreCoursesByMajor && majorName) {
      if (d.coreCoursesByMajor[majorName]) { perMajorCourses = d.coreCoursesByMajor[majorName]; perMajorKey = majorName; }
      else if (d.coreCoursesByMajor[majorName + '专业']) { perMajorCourses = d.coreCoursesByMajor[majorName + '专业']; perMajorKey = majorName + '专业'; }
    }
    return { detail: d, majorClass: mClass, perMajorCourses, perMajorKey };
  };
  const guobiao = resolveGuobiao();

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

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

  // ── Category badge colors (mirror page-gaokao-major-compare.jsx) ────────────
  const categoryColor = {
    '工科':  { bg: '#dbeafe', color: '#1e40af' },
    '理科':  { bg: '#d1fae5', color: '#065f46' },
    '文学':  { 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: '#ecfeff', color: '#155e75' },
    '教育学': { bg: '#fff7ed', color: '#9a3412' },
  };

  const getCategoryStyle = (cat) =>
    categoryColor[cat] || { bg: 'var(--pb-surface-alt)', color: 'var(--pb-fg-muted)' };

  // ── Discipline rank badge colors (mirror page-gaokao-major-compare.jsx) ──────
  const rankColor = {
    'A+': { bg: '#fef3c7', color: '#92400e' },
    'A':  { bg: '#d1fae5', color: '#065f46' },
    'A-': { bg: '#dbeafe', color: '#1e40af' },
  };
  const getRankStyle = (rank) =>
    rankColor[rank] || { bg: 'var(--pb-surface-alt)', color: 'var(--pb-fg-muted)' };

  // ── 国标 专业类详情 card (培养目标 + 核心课程 + 数据来源) ──────────────────────
  // Renders ONLY 国标-sourced content (verbatim). 5 core-course shapes supported:
  // per-major示例 / class-level array / "N+X" pool / 核心知识单元 / honest null.
  // Returns null when no 国标 detail exists for this 专业类 (caller shows 暂无).
  const renderGuobiaoCard = () => {
    if (!guobiao) return null;
    const d = guobiao.detail;
    const courses = guobiao.perMajorCourses || (Array.isArray(d.coreCourses) ? d.coreCourses : null);
    const chip = (label, key) => (
      <span key={key} style={{
        padding: '4px 12px', fontSize: 13, borderRadius: 5,
        background: 'var(--pb-surface-alt)', color: 'var(--pb-fg)',
        border: '1px solid var(--pb-border)',
      }}>{label}</span>
    );
    const src = d.source || {};
    return (
      <div style={cardStyle} data-testid="major-wiki-guobiao">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14, flexWrap: 'wrap' }}>
          <div style={sectionLabelStyle}>
            {lang === 'zh' ? '国标专业类详情' : 'National-Standard Class Details'}
          </div>
          <span
            data-testid="major-wiki-guobiao-badge"
            style={{
              padding: '2px 8px', fontSize: 10, fontWeight: 700, borderRadius: 4,
              background: '#d1fae5', color: '#065f46', border: '1px solid #6ee7b7',
              letterSpacing: '0.04em',
            }}
          >
            {lang === 'zh' ? `国标 · ${guobiao.majorClass}` : `National Std · ${guobiao.majorClass}`}
          </span>
        </div>

        {/* 培养目标 */}
        {d.trainingGoal && (
          <div style={{ marginBottom: courses || d.coreCoursesByMajor || d.coreCoursesPool || d.coreKnowledgeUnits ? 18 : 4 }}>
            <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginBottom: 6, fontWeight: 600 }}>
              {lang === 'zh' ? '培养目标（专业类）' : 'Training Goal (Major Class)'}
            </div>
            <p data-testid="major-wiki-guobiao-goal" style={{ fontSize: 14, lineHeight: 1.8, color: 'var(--pb-fg)', margin: 0 }}>
              {d.trainingGoal}
            </p>
          </div>
        )}

        {/* 核心课程 — per-major or class-level array */}
        {courses && courses.length > 0 && (
          <div style={{ marginBottom: 4 }}>
            <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginBottom: 8, fontWeight: 600 }}>
              {lang === 'zh'
                ? (guobiao.perMajorCourses ? '核心课程（本专业示例）' : '核心课程（专业类）')
                : (guobiao.perMajorCourses ? 'Core Courses (this major)' : 'Core Courses (class)')}
            </div>
            <div data-testid="major-wiki-guobiao-courses" style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {courses.map((c, i) => chip(c.hours ? `${c.name} (${c.hours})` : c.name, c.name + i))}
            </div>
          </div>
        )}

        {/* "N+X" 候选课程池 */}
        {!courses && Array.isArray(d.coreCoursesPool) && d.coreCoursesPool.length > 0 && (
          <div style={{ marginBottom: 4 }}>
            <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginBottom: 8, fontWeight: 600 }}>
              {lang === 'zh' ? '核心课程候选池' : 'Core-Course Pool'}
            </div>
            <div data-testid="major-wiki-guobiao-pool" style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {d.coreCoursesPool.map((c, i) => chip(c, 'p' + i))}
            </div>
          </div>
        )}

        {/* 核心知识单元（无固定课程名时） */}
        {!courses && (!d.coreCoursesPool || !d.coreCoursesPool.length) && Array.isArray(d.coreKnowledgeUnits) && d.coreKnowledgeUnits.length > 0 && (
          <div style={{ marginBottom: 4 }}>
            <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginBottom: 8, fontWeight: 600 }}>
              {lang === 'zh' ? '核心知识单元' : 'Core Knowledge Units'}
            </div>
            <div data-testid="major-wiki-guobiao-units" style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {d.coreKnowledgeUnits.map((c, i) => chip(c, 'k' + i))}
            </div>
          </div>
        )}

        {/* coreCoursesNote (国标说明，逐字) */}
        {d.coreCoursesNote && (
          <div style={{ marginTop: 10, fontSize: 11, color: 'var(--pb-fg-muted)', lineHeight: 1.6 }}>
            {d.coreCoursesNote}
          </div>
        )}

        {/* 数据来源 line */}
        <div data-testid="major-wiki-guobiao-source" style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--pb-border)', fontSize: 11, color: 'var(--pb-fg-muted)', lineHeight: 1.6 }}>
          {lang === 'zh' ? '数据来源：' : 'Source: '}
          {src.url ? (
            <a href={src.url} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--pb-fg-muted)', textDecoration: 'underline', textUnderlineOffset: 2 }}>
              {src.title || '国标'}
            </a>
          ) : (src.title || '国标')}
          {src.section ? `（${src.section}）` : ''}
          {src.publisher ? `，${src.publisher}` : ''}
          {'。'}
          {lang === 'zh' ? '国标原文逐字提取，未经改写。' : ' Extracted verbatim from the national standard.'}
        </div>
      </div>
    );
  };

  // ── Catalog still loading (no curated entry yet to show) ────────────────────
  if (!major && code && catalog === undefined) {
    return (
      <div className="pb-scroll" data-testid="major-wiki-loading">
        <PBNav active="gaokao" />
        <section style={{ padding: '120px 48px', textAlign: 'center', color: 'var(--pb-fg-muted)', fontSize: 14 }}>
          {lang === 'zh' ? '加载中…' : 'Loading…'}
        </section>
        <PBFooter />
      </div>
    );
  }

  // ── Catalog-level entry (official MOE directory, no curated detail yet) ─────
  if (!major && catalogEntry) {
    const ce = catalogEntry;
    return (
      <div className="pb-scroll" data-testid="major-wiki-catalog-page">
        <PBNav active="gaokao" />
        <section style={{ padding: '48px 48px 32px', background: 'var(--pb-navy-900)', color: '#fff' }}>
          <div style={{ maxWidth: 900, margin: '0 auto' }}>
            <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' }}>{ce.name}</span>
            </div>
            <div style={{ marginBottom: 12, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <span style={{ padding: '3px 10px', fontSize: 11, fontWeight: 600, borderRadius: 4, background: 'rgba(255,255,255,0.12)', color: '#fff', letterSpacing: '0.03em' }}>
                {ce.category}
              </span>
              {ce.majorClass && (
                <span style={{ padding: '3px 10px', fontSize: 11, fontWeight: 600, borderRadius: 4, background: 'rgba(255,255,255,0.12)', color: '#fff', letterSpacing: '0.03em' }}>
                  {ce.majorClass}
                </span>
              )}
            </div>
            <h1 data-testid="major-wiki-name-zh" style={{ fontFamily: 'var(--pb-serif)', fontSize: 34, fontWeight: 700, margin: '0 0 8px', lineHeight: 1.2 }}>
              {ce.name}
            </h1>
            <div style={{ fontFamily: 'var(--pb-mono)', fontSize: 14, color: 'rgba(255,255,255,0.65)' }}>
              {lang === 'zh' ? `专业代码 ${ce.code}` : `Major code ${ce.code}`}
            </div>
          </div>
        </section>
        <section style={{ padding: '32px 48px 80px', background: 'var(--pb-bg)' }}>
          <div style={{ maxWidth: 900, margin: '0 auto' }}>
            <div style={cardStyle}>
              <div style={sectionLabelStyle}>{lang === 'zh' ? '官方目录信息' : 'Official Catalog Info'}</div>
              <div data-testid="major-wiki-catalog-facts" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 16 }}>
                {[
                  [lang === 'zh' ? '学科门类' : 'Discipline', ce.category],
                  [lang === 'zh' ? '专业类' : 'Major Class', ce.majorClass],
                  [lang === 'zh' ? '授予学位' : 'Degree', ce.degree],
                  [lang === 'zh' ? '修业年限' : 'Duration', ce.years],
                ].filter(([, v]) => v).map(([k, v]) => (
                  <div key={k}>
                    <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginBottom: 4 }}>{k}</div>
                    <div style={{ fontSize: 15, fontWeight: 600 }}>{v}</div>
                  </div>
                ))}
              </div>
              {Array.isArray(ce.flags) && ce.flags.length > 0 && (
                <div style={{ marginTop: 12, fontSize: 12, color: 'var(--pb-fg-muted)' }}>
                  {ce.flags.includes('K') && (lang === 'zh' ? '「K」国家控制布点专业。' : '"K": state-controlled program. ')}
                  {ce.flags.includes('T') && (lang === 'zh' ? '「T」特设专业。' : '"T": special-purpose program.')}
                </div>
              )}
              <div style={{ marginTop: 14, fontSize: 11, color: 'var(--pb-fg-muted)', lineHeight: 1.5 }}>
                {lang === 'zh'
                  ? '数据来源：教育部《普通高等学校本科专业目录（2024年）》。'
                  : 'Source: MOE Undergraduate Major Catalog (2024 edition).'}
              </div>
            </div>
            {/* 国标专业类详情 (培养目标/核心课程) — only when 国标 covers this 专业类 */}
            {renderGuobiaoCard()}
            {/* Honest pending note — only when NO 国标 detail exists for this class */}
            {!guobiao && (
              <div style={cardStyle} data-testid="major-wiki-pending-note">
                <div style={sectionLabelStyle}>{lang === 'zh' ? '详情待补充' : 'Details Pending'}</div>
                <p style={{ fontSize: 13, color: 'var(--pb-fg-muted)', lineHeight: 1.7, margin: 0 }}>
                  {lang === 'zh'
                    ? '该专业所属专业类暂无国标详情（培养目标、核心课程正按官方来源逐步补充；宁缺勿错：无可靠来源的数据我们不展示）。当前页面仅展示教育部官方目录信息。'
                    : 'No national-standard details are available yet for this major class (training goals & core courses are being added from official sources). We only publish sourced data — this page currently shows official MOE catalog facts only.'}
                </p>
              </div>
            )}
            <div style={{ textAlign: 'center', marginTop: 24 }}>
              <button className="pb-btn pb-btn-link pb-btn-sm" onClick={() => { window.location.hash = '#/gaokao/majors'; }}>
                {lang === 'zh' ? '← 返回专业库' : '← Back to major library'}
              </button>
            </div>
          </div>
        </section>
        <PBFooter />
      </div>
    );
  }

  // ── Not found ───────────────────────────────────────────────────────────────
  if (!major) {
    return (
      <div className="pb-scroll" data-testid="major-wiki-not-found">
        <PBNav active="gaokao" />
        <section style={{ padding: '120px 48px', textAlign: 'center' }}>
          <div style={{ fontSize: 48, marginBottom: 16 }}>📚</div>
          <div style={{ fontFamily: 'var(--pb-serif)', fontSize: 24, fontWeight: 600, marginBottom: 12 }}>
            {lang === 'zh' ? '该专业暂无数据' : 'Major not found'}
          </div>
          <p style={{ fontSize: 15, color: 'var(--pb-fg-muted)', marginBottom: 24 }}>
            {lang === 'zh'
              ? (code
                ? `专业代码「${code}」暂未收录，请返回查看其他专业。`
                : '未指定专业。请从测算页的结果列表或专业对比页进入查看具体专业。')
              : (code
                ? `Major code "${code}" is not in our database. Try another major.`
                : 'No major specified. Open a major from the calculator results or the major-compare page.')}
          </p>
          <button
            className="pb-btn pb-btn-primary"
            onClick={() => { window.location.hash = '#/gaokao'; }}
          >
            {lang === 'zh' ? '返回测算页' : 'Back to Calculator'}
          </button>
        </section>
        <PBFooter />
      </div>
    );
  }

  const catStyle = getCategoryStyle(major.category);

  // ── Resolve discipline rank: prefer real 第四轮 data, fall back to sample ─────
  const disciplineKey = MAJOR_TO_DISCIPLINE[major.legacyCode || code];
  const realDisciplineData =
    round4Data && disciplineKey ? round4Data.disciplines[disciplineKey] : null;
  const isRealData = !!realDisciplineData;
  const rankEntries = isRealData
    ? Object.entries(realDisciplineData)
    : Object.entries(major.disciplineRank || {});

  const MAX_SALARY = 25000;

  return (
    <div className="pb-scroll" data-testid="major-wiki-page">
      <PBNav active="gaokao" />

      {/* ── Hero ────────────────────────────────────────────────────────────── */}
      <section style={{
        padding: '48px 48px 32px',
        background: 'var(--pb-navy-900)',
        color: '#fff',
      }}>
        <div style={{ maxWidth: 900, 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' ? major.nameZh : major.nameEn}
            </span>
          </div>

          {/* Category badge */}
          <div style={{ marginBottom: 12 }}>
            <span style={{
              padding: '3px 10px', fontSize: 11, fontWeight: 600, borderRadius: 4,
              background: catStyle.bg, color: catStyle.color,
              letterSpacing: '0.03em',
            }}>
              {major.category}
            </span>
          </div>

          {/* Major names */}
          <h1
            data-testid="major-wiki-name-zh"
            style={{ fontFamily: 'var(--pb-serif)', fontSize: 34, fontWeight: 700, margin: '0 0 8px', lineHeight: 1.2 }}
          >
            {major.nameZh}
          </h1>
          <div style={{ fontSize: 16, color: 'rgba(255,255,255,0.65)', fontStyle: 'italic', marginBottom: 4 }}>
            {major.nameEn}
          </div>
        </div>
      </section>

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

          {/* ── 国标专业类详情 (培养目标/核心课程 + 数据来源) — 国标覆盖时显示 ──── */}
          {renderGuobiaoCard()}

          {/* ── 主修课程 ───────────────────────────────────────────────────── */}
          <div style={cardStyle}>
            <div style={sectionLabelStyle}>
              {lang === 'zh' ? '主修课程 · Core Courses' : 'Core Courses'}
            </div>
            <div
              data-testid="major-wiki-courses"
              style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}
            >
              {(major.mainCourses || []).map((c) => (
                <span key={c} style={{
                  padding: '4px 12px', fontSize: 13, borderRadius: 5,
                  background: 'var(--pb-surface-alt)', color: 'var(--pb-fg)',
                  border: '1px solid var(--pb-border)',
                }}>
                  {c}
                </span>
              ))}
            </div>
          </div>

          {/* ── 就业方向 ───────────────────────────────────────────────────── */}
          <div style={cardStyle}>
            <div style={sectionLabelStyle}>
              {lang === 'zh' ? '就业方向 · Career Directions' : 'Career Directions'}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {(major.careerDirections || []).map((d, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{
                    width: 6, height: 6, borderRadius: '50%',
                    background: 'var(--pb-gold-500)', flexShrink: 0,
                  }} />
                  <span style={{ fontSize: 14, color: 'var(--pb-fg)' }}>{d}</span>
                </div>
              ))}
            </div>
          </div>

          {/* ── 就业率 + 起薪 (ESTIMATE — 宁缺勿错) ──────────────────────── */}
          <div style={cardStyle}>
            {/* Section header with 估算 badge — ALWAYS visible to prevent data misread */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
              <div style={sectionLabelStyle}>
                {lang === 'zh' ? '就业前景' : 'Career Outlook'}
              </div>
              <span
                data-testid="major-wiki-estimate-badge"
                style={{
                  padding: '2px 8px', fontSize: 10, fontWeight: 700, borderRadius: 4,
                  background: '#fef3c7', color: '#92400e', border: '1px solid #f59e0b',
                  letterSpacing: '0.04em',
                }}
              >
                {lang === 'zh' ? '估算' : 'Estimate'}
              </span>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
              {/* 就业率 */}
              <div>
                <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginBottom: 6 }}>
                  {lang === 'zh' ? '就业率（估算）' : 'Employment Rate (est.)'}
                </div>
                <div style={{ fontFamily: 'var(--pb-mono)', fontSize: 28, fontWeight: 700, marginBottom: 8, color: major.avgEmploymentRate >= 90 ? 'var(--pb-success)' : 'var(--pb-fg)' }}>
                  {major.avgEmploymentRate}%
                </div>
                <div style={{ height: 8, background: 'var(--pb-border)', borderRadius: 4, overflow: 'hidden' }}>
                  <div style={{
                    height: '100%',
                    width: `${major.avgEmploymentRate}%`,
                    background: major.avgEmploymentRate >= 90 ? 'var(--pb-success)' : 'var(--pb-navy-700)',
                    borderRadius: 4,
                    transition: 'width 0.4s ease',
                  }} />
                </div>
              </div>

              {/* 起薪 */}
              <div>
                <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginBottom: 6 }}>
                  {lang === 'zh' ? '平均起薪（估算）' : 'Avg. Starting Salary (est.)'}
                </div>
                <div style={{ fontFamily: 'var(--pb-mono)', fontSize: 28, fontWeight: 700, marginBottom: 8 }}>
                  {major.avgSalary >= 10000
                    ? `${(major.avgSalary / 1000).toFixed(1)}K`
                    : major.avgSalary}
                  <span style={{ fontSize: 14, fontWeight: 400, marginLeft: 4, color: 'var(--pb-fg-muted)' }}>
                    {lang === 'zh' ? '元/月' : 'CNY/mo'}
                  </span>
                </div>
                <div style={{ height: 8, background: 'var(--pb-border)', borderRadius: 4, overflow: 'hidden' }}>
                  <div style={{
                    height: '100%',
                    width: `${Math.min(100, Math.round((major.avgSalary / MAX_SALARY) * 100))}%`,
                    background: 'var(--pb-gold-500)',
                    borderRadius: 4,
                    transition: 'width 0.4s ease',
                  }} />
                </div>
              </div>
            </div>

            {/* Disclaimer note */}
            <div style={{ marginTop: 14, fontSize: 11, color: 'var(--pb-fg-muted)', lineHeight: 1.5 }}>
              {lang === 'zh'
                ? '⚠ 就业率与起薪为 2022–2024 届毕业生均值估算，非权威统计。仅供参考，请以教育部就业质量报告等官方发布为准。'
                : '⚠ Employment rate and salary are 2022–2024 graduate average estimates, not authoritative statistics. For reference only.'}
            </div>
          </div>

          {/* ── 学科评估 A 类高校 ──────────────────────────────────────────── */}
          {rankEntries.length > 0 && (
            <div style={cardStyle}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
                <div style={sectionLabelStyle}>
                  {lang === 'zh' ? '学科评估 A 类高校' : 'A-Class Discipline Rankings'}
                </div>
                {isRealData ? (
                  <span
                    data-testid="discipline-rank-source-badge"
                    style={{
                      padding: '2px 8px', fontSize: 10, fontWeight: 600, borderRadius: 4,
                      background: '#d1fae5', color: '#065f46',
                      border: '1px solid #6ee7b7',
                    }}
                  >
                    {lang === 'zh'
                      ? `教育部第四轮(2017) · ${disciplineKey}`
                      : `MOE Round 4 (2017) · ${disciplineKey}`}
                  </span>
                ) : (
                  <span
                    data-testid="discipline-rank-source-badge"
                    style={{
                      padding: '2px 8px', fontSize: 10, fontWeight: 600, borderRadius: 4,
                      background: 'var(--pb-surface-alt)', color: 'var(--pb-fg-muted)',
                      border: '1px solid var(--pb-border)',
                    }}
                  >
                    {lang === 'zh' ? '样例数据' : 'Sample data'}
                  </span>
                )}
              </div>

              <div
                data-testid="major-wiki-discipline-rank"
                style={{ display: 'flex', flexDirection: 'column', gap: 8 }}
              >
                {rankEntries.map(([school, rank]) => {
                  const rs = getRankStyle(rank);
                  return (
                    <div key={school} style={{
                      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                      padding: '8px 12px',
                      background: 'var(--pb-surface-alt)',
                      borderRadius: 6,
                      border: '1px solid var(--pb-border)',
                    }}>
                      <span style={{ fontSize: 14, color: 'var(--pb-fg)', flex: 1, marginRight: 12 }}>
                        {school}
                      </span>
                      <span style={{
                        padding: '2px 10px', fontSize: 13, fontWeight: 700, borderRadius: 4,
                        background: rs.bg, color: rs.color,
                        flexShrink: 0,
                      }}>
                        {rank}
                      </span>
                    </div>
                  );
                })}
              </div>

              <div style={{ marginTop: 12, fontSize: 11, color: 'var(--pb-fg-muted)' }}>
                {isRealData
                  ? (lang === 'zh'
                    ? `数据来源：教育部第四轮学科评估（2017）。仅展示 A+/A/A- 等级高校。`
                    : 'Source: MOE 4th-Round Discipline Assessment (2017). Shows A+/A/A- tier schools only.')
                  : (lang === 'zh'
                    ? '样例数据：A+/A/A- 等级高校样本，待接入教育部官方学科评估后替换为权威数据。'
                    : 'Sample data: illustrative A+/A/A- tier schools, pending official MOE discipline-assessment ingestion.')}
              </div>
            </div>
          )}

          {/* ── 对比其他专业 quick link ──────────────────────────────────── */}
          <div style={{ textAlign: 'center', marginTop: 24 }}>
            <button
              className="pb-btn pb-btn-link pb-btn-sm"
              onClick={() => {
                window.location.hash = `#/gaokao/major-compare?codes=${code}`;
              }}
            >
              {lang === 'zh' ? '与其他专业对比 →' : 'Compare with other majors →'}
            </button>
            <span style={{ margin: '0 12px', color: 'var(--pb-border)' }}>|</span>
            <button
              className="pb-btn pb-btn-link pb-btn-sm"
              onClick={() => { window.location.hash = '#/gaokao'; }}
            >
              {lang === 'zh' ? '← 返回测算页' : '← Back to calculator'}
            </button>
          </div>

          {/* ── 方法论 / 数据说明 teaser (B2 discoverability) ────────────── */}
          <div style={{
            marginTop: 20,
            padding: '14px 20px',
            background: 'var(--pb-surface)',
            border: '1px solid var(--pb-border)',
            borderRadius: 10,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 16,
            flexWrap: 'wrap',
          }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--pb-fg)', marginBottom: 4 }}>
                {lang === 'zh' ? '想了解概率是怎么算的？' : 'Curious how admission probability is calculated?'}
              </div>
              <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)' }}>
                {lang === 'zh'
                  ? '查看我们的方法论与数据说明——数据来源、算法原理、宁缺勿错的诚信原则。'
                  : 'See our methodology & data page — data provenance, algorithm, and our accuracy-first policy.'}
              </div>
            </div>
            <button
              data-testid="method-page-link"
              className="pb-btn pb-btn-link pb-btn-sm"
              onClick={() => { window.location.hash = '#/gaokao/method'; }}
            >
              {lang === 'zh' ? '方法论 / 数据说明 →' : 'Methodology & Data →'}
            </button>
          </div>

          {/* ── 霍兰德测评 teaser ─────────────────────────────────────────── */}
          <div style={{
            marginTop: 28,
            padding: '16px 20px',
            background: 'var(--pb-surface)',
            border: '1px solid var(--pb-border)',
            borderRadius: 10,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 16,
            flexWrap: 'wrap',
          }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--pb-fg)', marginBottom: 4 }}>
                {lang === 'zh' ? '不确定哪类专业适合你？' : 'Not sure which major type suits you?'}
              </div>
              <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)' }}>
                {lang === 'zh'
                  ? '做个霍兰德职业兴趣测评，30题测出你的 RIASEC 兴趣代码。'
                  : 'Take the Holland RIASEC Interest Quiz (30 items) to find your interest profile.'}
              </div>
            </div>
            <button
              data-testid="holland-teaser-link"
              className="pb-btn pb-btn-primary pb-btn-sm"
              onClick={() => { window.location.hash = '#/gaokao/holland'; }}
            >
              {lang === 'zh' ? '测测哪类专业适合你 · 霍兰德测评 →' : 'Holland RIASEC Quiz →'}
            </button>
          </div>
        </div>
      </section>

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

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