// 专业对比页 — A4
// Route: /#/gaokao/major-compare?codes=cs,ee,ai
// Max 4 majors. Data from lib/gaokao-major-meta.js (window.PBMajorMeta).
// No new API endpoints created.

const GaokaoMajorComparePage = () => {
  const lang = useLang();
  const t = useT();

  // ── Parse URL params ────────────────────────────────────────────────────────
  const getParams = () => {
    const hash = window.location.hash || '';
    const qi = hash.indexOf('?');
    if (qi < 0) return { codes: [] };
    const q = new URLSearchParams(hash.slice(qi + 1));
    // Normalize legacy short codes ('cs') to official MOE codes ('080901') so
    // pre-migration share links keep working and dedup is code-system-agnostic.
    const norm = (window.PBMajorMeta && window.PBMajorMeta.normalizeMajorCode) || ((c) => c);
    return {
      codes: [...new Set((q.get('codes') || '').split(',').filter(Boolean).map(norm))],
    };
  };

  const [params, setParams] = React.useState(getParams);

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

  const { codes: rawCodes } = params;

  // ── Truncate to 4 ──────────────────────────────────────────────────────────
  const [truncated, setTruncated] = React.useState(false);
  const codes = React.useMemo(() => {
    if (rawCodes.length > 4) {
      setTruncated(true);
      return rawCodes.slice(0, 4);
    }
    setTruncated(false);
    return rawCodes;
  }, [rawCodes.join(',')]);

  // ── Major metadata from window.PBMajorMeta ─────────────────────────────────
  const pbMeta = window.PBMajorMeta || {};
  const getMajorMeta = pbMeta.getMajorMeta || (() => null);
  const listAllMajors = pbMeta.listAllMajors || (() => []);

  const allMajors = React.useMemo(() => listAllMajors(), []);

  // ── Selected codes state (sync with URL) ───────────────────────────────────
  const updateUrl = (newCodes) => {
    const p = new URLSearchParams();
    if (newCodes.length > 0) p.set('codes', newCodes.join(','));
    window.location.hash = '#/gaokao/major-compare' + (newCodes.length > 0 ? '?' + p.toString() : '');
  };

  const addMajor = (code) => {
    if (!code || codes.includes(code)) return;
    if (codes.length >= 4) {
      alert(lang === 'zh' ? '最多对比 4 个专业' : 'Maximum 4 majors for comparison');
      return;
    }
    updateUrl([...codes, code]);
  };

  const removeMajor = (code) => {
    updateUrl(codes.filter((c) => c !== code));
  };

  // ── Dropdown state ─────────────────────────────────────────────────────────
  const [dropdownValue, setDropdownValue] = React.useState('');

  const handleDropdownChange = (e) => {
    const code = e.target.value;
    setDropdownValue('');
    if (code) addMajor(code);
  };

  // ── Category badge colors ──────────────────────────────────────────────────
  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 ──────────────────────────────────────────────────
  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)' };

  // ── Salary bar helper ──────────────────────────────────────────────────────
  const MAX_SALARY = 25000;

  // ── Empty state ────────────────────────────────────────────────────────────
  if (codes.length === 0) {
    return (
      <div className="pb-scroll" data-testid="major-compare-page">
        <PBNav active="gaokao" />
        <section style={{ padding: '80px 48px', textAlign: 'center' }}>
          <div style={{ maxWidth: 560, margin: '0 auto' }}>
            <div style={{ fontFamily: 'var(--pb-serif)', fontSize: 28, fontWeight: 600, marginBottom: 16 }}>
              {lang === 'zh' ? '专业对比' : 'Major Comparison'}
            </div>
            <p style={{ fontSize: 15, color: 'var(--pb-fg-muted)', lineHeight: 1.65, marginBottom: 28 }}>
              {lang === 'zh'
                ? '从下方下拉菜单中添加 2–4 个专业，横向对比培养方向、就业前景与学科评估。'
                : 'Add 2–4 majors from the dropdown below to compare training directions, career prospects, and discipline rankings side by side.'}
            </p>
            {/* Add first major via dropdown */}
            <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap', marginBottom: 24 }}>
              <select
                data-testid="major-add-dropdown"
                className="pb-select"
                value={dropdownValue}
                onChange={handleDropdownChange}
                style={{ fontSize: 14, padding: '8px 14px', minWidth: 240 }}
              >
                <option value="">{lang === 'zh' ? '— 选择专业 —' : '— Select a major —'}</option>
                {allMajors.map((m) => (
                  <option key={m.code} value={m.code} disabled={codes.includes(m.code)}>
                    {lang === 'zh' ? m.nameZh : m.nameEn}
                  </option>
                ))}
              </select>
            </div>
            <button className="pb-btn pb-btn-link pb-btn-sm" onClick={() => navigateTo('/gaokao')}>
              {lang === 'zh' ? '← 返回测算页' : '← Back to calculator'}
            </button>
          </div>
        </section>
        <PBFooter />
      </div>
    );
  }

  // ── Main compare layout ────────────────────────────────────────────────────
  const colCount = codes.length;

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

      {/* Header + controls */}
      <section style={{ padding: '48px 48px 32px', background: 'var(--pb-paper)', borderBottom: '1px solid var(--pb-border)' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <div className="pb-eyebrow" style={{ marginBottom: 12 }}>
            {lang === 'zh' ? '专业对比' : 'Major Comparison'}
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
            <h1 style={{ fontFamily: 'var(--pb-serif)', fontSize: 36, fontWeight: 600, margin: 0 }}>
              {lang === 'zh' ? `${codes.length} 个专业并列对比` : `Comparing ${codes.length} Majors`}
            </h1>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
              {/* Add major dropdown */}
              {codes.length < 4 && (
                <div>
                  <label style={{ fontSize: 11, color: 'var(--pb-fg-muted)', display: 'block', marginBottom: 4 }}>
                    {lang === 'zh' ? '添加专业' : 'Add Major'}
                  </label>
                  <select
                    data-testid="major-add-dropdown"
                    className="pb-select"
                    value={dropdownValue}
                    onChange={handleDropdownChange}
                    style={{ fontSize: 13, padding: '6px 10px' }}
                  >
                    <option value="">{lang === 'zh' ? '— 选择专业 —' : '— Select —'}</option>
                    {allMajors.map((m) => (
                      <option key={m.code} value={m.code} disabled={codes.includes(m.code)}>
                        {lang === 'zh' ? m.nameZh : m.nameEn}
                      </option>
                    ))}
                  </select>
                </div>
              )}
              <div style={{ alignSelf: 'flex-end' }}>
                <button
                  className="pb-btn pb-btn-link pb-btn-sm"
                  onClick={() => navigateTo('/gaokao')}
                  style={{ marginBottom: 2 }}
                >
                  {lang === 'zh' ? '← 返回测算' : '← Back to calculator'}
                </button>
              </div>
            </div>
          </div>

          {truncated && (
            <div style={{ marginTop: 12, padding: '8px 14px', background: '#fef3c7', border: '1px solid #f59e0b', borderRadius: 6, fontSize: 13, color: '#92400e' }}>
              {lang === 'zh' ? '最多对比 4 个专业，已自动取前 4 个。' : 'Maximum 4 majors for comparison. Showing first 4.'}
            </div>
          )}
        </div>
      </section>

      {/* Comparison grid */}
      <section style={{ padding: '32px 48px 80px', background: 'var(--pb-bg)' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <style>{`
            .pb-major-compare-grid {
              display: grid;
              grid-template-columns: repeat(${colCount}, 1fr);
              gap: 20px;
            }
            @media (max-width: 768px) {
              .pb-major-compare-grid {
                grid-template-columns: repeat(2, 1fr);
              }
            }
            @media (max-width: 480px) {
              .pb-major-compare-grid {
                grid-template-columns: 1fr;
              }
            }
          `}</style>

          <div className="pb-major-compare-grid" data-testid="major-compare-grid">
            {codes.map((code) => {
              const major = getMajorMeta(code);
              if (!major) {
                return (
                  <div key={code} className="pb-card" style={{ padding: 24, opacity: 0.5 }} data-testid={`major-row-${code}`}>
                    <div style={{ fontSize: 13, color: 'var(--pb-fg-muted)' }}>
                      {lang === 'zh' ? `未知专业：${code}` : `Unknown major: ${code}`}
                    </div>
                  </div>
                );
              }

              const catStyle = getCategoryStyle(major.category);
              const topRankEntries = Object.entries(major.disciplineRank).slice(0, 4);

              return (
                <div key={code} className="pb-card" style={{ padding: 0, overflow: 'hidden', position: 'relative' }} data-testid={`major-row-${code}`}>
                  {/* Remove button */}
                  <button
                    onClick={() => removeMajor(code)}
                    title={lang === 'zh' ? '移除' : 'Remove'}
                    data-testid={`major-remove-${code}`}
                    style={{
                      position: 'absolute', top: 10, right: 10, zIndex: 2,
                      width: 24, height: 24, borderRadius: 12, border: 'none',
                      background: 'var(--pb-surface-alt)', color: 'var(--pb-fg-muted)',
                      cursor: 'pointer', display: 'grid', placeItems: 'center', fontSize: 14,
                    }}
                  >×</button>

                  {/* Major header */}
                  <div style={{ padding: '20px 20px 16px', borderBottom: '1px solid var(--pb-border)', background: 'var(--pb-paper)' }}>
                    {/* Category badge */}
                    <div style={{ marginBottom: 8 }}>
                      <span style={{
                        padding: '2px 8px', fontSize: 10, fontWeight: 600, borderRadius: 4,
                        background: catStyle.bg, color: catStyle.color,
                        letterSpacing: '0.03em',
                      }}>
                        {major.category}
                      </span>
                    </div>
                    <div style={{ fontFamily: 'var(--pb-serif)', fontSize: 17, fontWeight: 600, lineHeight: 1.3, marginBottom: 4, paddingRight: 24 }}>
                      {lang === 'zh' ? major.nameZh : major.nameEn}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--pb-fg-muted)', fontStyle: 'italic' }}>
                      {lang === 'zh' ? major.nameEn : major.nameZh}
                    </div>
                  </div>

                  {/* 就业率 + 起薪 */}
                  <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--pb-border)' }}>
                    <div style={{ fontSize: 11, color: 'var(--pb-fg-muted)', marginBottom: 10, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                      {lang === 'zh' ? '就业前景' : 'Career Outlook'}
                    </div>
                    {/* Employment rate bar */}
                    <div style={{ marginBottom: 10 }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                        <span style={{ fontSize: 11, color: 'var(--pb-fg-muted)' }}>{lang === 'zh' ? '就业率' : 'Employ. Rate'}</span>
                        <span style={{ fontFamily: 'var(--pb-mono)', fontSize: 13, fontWeight: 700, color: major.avgEmploymentRate >= 90 ? 'var(--pb-success)' : 'var(--pb-fg-muted)' }}>
                          {major.avgEmploymentRate}%
                        </span>
                      </div>
                      <div style={{ height: 6, background: 'var(--pb-border)', borderRadius: 3, overflow: 'hidden' }}>
                        <div style={{
                          height: '100%',
                          width: `${major.avgEmploymentRate}%`,
                          background: major.avgEmploymentRate >= 90 ? 'var(--pb-success)' : 'var(--pb-navy-700)',
                          borderRadius: 3,
                          transition: 'width 0.4s ease',
                        }}/>
                      </div>
                    </div>
                    {/* Avg salary bar */}
                    <div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                        <span style={{ fontSize: 11, color: 'var(--pb-fg-muted)' }}>{lang === 'zh' ? '平均月薪' : 'Avg Salary'}</span>
                        <span style={{ fontFamily: 'var(--pb-mono)', fontSize: 13, fontWeight: 700 }}>
                          {major.avgSalary >= 10000 ? `${(major.avgSalary / 1000).toFixed(1)}K` : major.avgSalary} {lang === 'zh' ? '元' : 'CNY'}
                        </span>
                      </div>
                      <div style={{ height: 6, background: 'var(--pb-border)', borderRadius: 3, overflow: 'hidden' }}>
                        <div style={{
                          height: '100%',
                          width: `${Math.min(100, Math.round((major.avgSalary / MAX_SALARY) * 100))}%`,
                          background: 'var(--pb-gold-500)',
                          borderRadius: 3,
                          transition: 'width 0.4s ease',
                        }}/>
                      </div>
                    </div>
                  </div>

                  {/* 学科评估 */}
                  <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--pb-border)' }}>
                    <div style={{ fontSize: 11, color: 'var(--pb-fg-muted)', marginBottom: 10, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                      {lang === 'zh' ? '学科评估 (A 类)' : 'Discipline Ranking'}
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                      {topRankEntries.map(([school, rank]) => {
                        const rs = getRankStyle(rank);
                        return (
                          <div key={school} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <span style={{ fontSize: 11, color: 'var(--pb-fg)', flex: 1, marginRight: 6, lineHeight: 1.3 }}>{school}</span>
                            <span style={{
                              padding: '1px 7px', fontSize: 11, fontWeight: 700, borderRadius: 4,
                              background: rs.bg, color: rs.color,
                              flexShrink: 0,
                            }}>
                              {rank}
                            </span>
                          </div>
                        );
                      })}
                    </div>
                  </div>

                  {/* 主修课程 */}
                  <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--pb-border)' }}>
                    <div style={{ fontSize: 11, color: 'var(--pb-fg-muted)', marginBottom: 8, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                      {lang === 'zh' ? '主修课程' : 'Core Courses'}
                    </div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                      {major.mainCourses.map((c) => (
                        <span key={c} style={{
                          padding: '2px 7px', fontSize: 10, borderRadius: 3,
                          background: 'var(--pb-surface-alt)', color: 'var(--pb-fg)',
                          border: '1px solid var(--pb-border)',
                          lineHeight: 1.6,
                        }}>
                          {c}
                        </span>
                      ))}
                    </div>
                  </div>

                  {/* 就业方向 */}
                  <div style={{ padding: '14px 16px' }}>
                    <div style={{ fontSize: 11, color: 'var(--pb-fg-muted)', marginBottom: 8, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                      {lang === 'zh' ? '培养方向 / 就业去向' : 'Career Directions'}
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                      {major.careerDirections.map((d, i) => (
                        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--pb-gold-500)', flexShrink: 0 }}/>
                          <span style={{ fontSize: 12, color: 'var(--pb-fg)' }}>{d}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Data source note */}
          <div style={{ marginTop: 24, padding: '12px 20px', background: 'var(--pb-paper)', borderRadius: 8, border: '1px solid var(--pb-border)', fontSize: 11, color: 'var(--pb-fg-muted)', lineHeight: 1.6 }}>
            {lang === 'zh'
              ? '就业率 / 薪资为 2022-2024 届毕业生均值估算；学科评估来源：教育部第五轮学科评估结果（2022）。'
              : 'Employment rate and salary are 2022–2024 graduate average estimates. Discipline rankings from China MOE 5th Discipline Assessment (2022).'}
          </div>
        </div>
      </section>

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

// Expose to window
Object.assign(window, { GaokaoMajorComparePage });
