// ─── QA 2026-06-11 清单项4 — 海南专业库目录页 ────────────────────────────────
// Route: /#/gaokao/majors
// 数据：data/gaokao-major-index/HI/<year>.json（ETL 聚合自 admissions-majors
// 的真实录取专业行，与院校详情页同源同 caveat）。这是"专业库"的真实数据
// v1：按专业看海南 2025 哪些院校招、分数区间多少；非教育部全目录，页面
// 头部如实披露覆盖面。31 个精编专业（PBMajorMeta）带「专业详情」深链。

const GaokaoMajorsPage = () => {
  const lang = useLang ? useLang() : 'zh';
  const zh = lang !== 'en';
  const [idx, setIdx] = React.useState(undefined); // undefined=loading null=miss
  const [q, setQ] = React.useState('');
  const [openName, setOpenName] = React.useState(null);

  React.useEffect(() => {
    (async () => {
      for (const season of [2025, 2024]) {
        try {
          const r = await fetch(`/data/gaokao-major-index/HI/${season}.json`);
          if (!r.ok) continue;
          const d = await r.json();
          if (d && Array.isArray(d.majors)) { setIdx(d); return; }
        } catch (_e) { /* next */ }
      }
      setIdx(null);
    })();
  }, []);

  // 31 个精编专业详情页（lib/gaokao-major-meta）按中文名建深链
  const metaByName = React.useMemo(() => {
    const m = new Map();
    try {
      const all = (window.PBMajorMeta && window.PBMajorMeta.listAllMajors && window.PBMajorMeta.listAllMajors()) || [];
      for (const x of all) if (x && x.nameZh) m.set(x.nameZh, x.code || x.id);
    } catch (_e) { /* optional */ }
    return m;
  }, []);

  const filtered = React.useMemo(() => {
    if (!idx) return [];
    const kw = q.trim();
    if (!kw) return idx.majors;
    return idx.majors.filter((m) => m.name.includes(kw));
  }, [idx, q]);

  return (
    <div className="pb-scroll" data-testid="gaokao-majors-page">
      <PBNav active="gaokao" />
      <section style={{ maxWidth: 980, margin: '0 auto', padding: '48px 24px 80px' }}>
        <div className="pb-eyebrow" style={{ marginBottom: 8 }}>{zh ? '海南 · 专业库' : 'Hainan · Major Library'}</div>
        <h1 style={{ fontFamily: 'var(--pb-serif)', fontSize: 30, margin: '0 0 10px' }}>
          {zh ? '按专业看：哪些院校在海南招、分数要多少' : 'By major: who recruits in Hainan, and at what score'}
        </h1>
        {idx && (
          <p style={{ fontSize: 13, color: 'var(--pb-fg-muted)', lineHeight: 1.7, margin: '0 0 20px' }}>
            {zh
              ? `已收录 ${idx.counts.majors} 个专业方向 · ${idx.counts.rows.toLocaleString()} 条 ${idx.year} 年海南真实录取专业行（${idx.counts.schoolFiles} 所院校）。数据与院校详情页同源：部分明细行核验进行中，覆盖面为我站已收录范围，非教育部全目录；填报前请以《海南省普通高校招生专业目录》为准。`
              : `${idx.counts.majors} majors · ${idx.counts.rows.toLocaleString()} real ${idx.year} Hainan admission rows across ${idx.counts.schoolFiles} schools. Same source (and caveats) as school pages — not the full MOE catalogue; verify against the official directory before filing.`}
          </p>
        )}

        <input
          data-testid="majors-search"
          placeholder={zh ? '搜索专业名，如：计算机 / 临床 / 法学' : 'Search majors…'}
          value={q}
          onChange={(e) => setQ(e.target.value)}
          style={{ width: '100%', maxWidth: 420, padding: '10px 14px', borderRadius: 10, border: '1px solid var(--pb-border)', fontSize: 14, marginBottom: 18, background: 'var(--pb-surface-alt)' }}
        />

        {idx === undefined && <div style={{ color: 'var(--pb-fg-muted)', fontSize: 13 }}>{zh ? '加载中…' : 'Loading…'}</div>}
        {idx === null && <div style={{ color: 'var(--pb-fg-muted)', fontSize: 13 }}>{zh ? '专业索引暂未生成。' : 'Major index not available.'}</div>}

        {idx && (
          <div style={{ border: '1px solid var(--pb-border)', borderRadius: 12, overflow: 'hidden' }}>
            {filtered.length === 0 && (
              <div style={{ padding: 24, textAlign: 'center', color: 'var(--pb-fg-muted)', fontSize: 13 }}>
                {zh ? `未找到包含「${q}」的专业` : 'No majors match your search'}
              </div>
            )}
            {filtered.map((m, i) => {
              const open = openName === m.name;
              const detailCode = metaByName.get(m.name);
              return (
                <div key={m.name} style={{ borderTop: i > 0 ? '1px solid var(--pb-border)' : 'none' }}>
                  <div
                    data-testid={`major-row-${i}`}
                    onClick={() => setOpenName(open ? null : m.name)}
                    style={{ display: 'flex', alignItems: 'baseline', gap: 14, padding: '12px 18px', cursor: 'pointer', background: open ? 'var(--pb-surface-alt)' : 'transparent' }}
                  >
                    <div style={{ fontFamily: 'var(--pb-serif)', fontWeight: 600, fontSize: 15, flex: 1 }}>
                      {m.name}
                      {detailCode && (
                        <a
                          href={`#/gaokao/major/${detailCode}`}
                          onClick={(e) => e.stopPropagation()}
                          style={{ marginLeft: 8, fontSize: 11, color: 'var(--pb-navy-700)', fontWeight: 400 }}
                        >{zh ? '专业详情 →' : 'Details →'}</a>
                      )}
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)', whiteSpace: 'nowrap' }}>
                      {zh ? `${m.schoolCount} 校开设` : `${m.schoolCount} schools`}
                    </div>
                    <div style={{ fontFamily: 'var(--pb-mono)', fontSize: 12, whiteSpace: 'nowrap' }}>
                      {m.minScore}–{m.maxScore}
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--pb-fg-muted)' }}>{open ? '▲' : '▼'}</div>
                  </div>
                  {open && (
                    <div style={{ padding: '4px 18px 14px', background: 'var(--pb-surface-alt)' }}>
                      <div style={{ fontSize: 11, color: 'var(--pb-fg-muted)', margin: '4px 0 8px' }}>
                        {zh ? `按 ${idx.year} 年专业最低分降序 · 点院校名看详情页` : `Sorted by ${idx.year} major min-score · click a school for details`}
                        {m.schools.length > 60 ? (zh ? `（共 ${m.schools.length} 校，显示前 60）` : ` (top 60 of ${m.schools.length})`) : ''}
                      </div>
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(230px, 1fr))', gap: 6 }}>
                        {m.schools.slice(0, 60).map((s, j) => (
                          <a
                            key={`${s.code}-${j}`}
                            href={`#/gaokao/school/${encodeURIComponent(s.school)}`}
                            style={{ display: 'flex', justifyContent: 'space-between', gap: 8, padding: '5px 10px', borderRadius: 6, border: '1px solid var(--pb-border)', fontSize: 12, color: 'var(--pb-fg)', textDecoration: 'none', background: 'var(--pb-bg, #fff)' }}
                          >
                            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.school}</span>
                            <span style={{ fontFamily: 'var(--pb-mono)', whiteSpace: 'nowrap' }}>
                              {s.minScore}{s.minRank != null ? ` / #${Number(s.minRank).toLocaleString()}` : ''}
                            </span>
                          </a>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </section>
      <PBFooter />
    </div>
  );
};

window.GaokaoMajorsPage = GaokaoMajorsPage;
