// ─── Wave 14-A — CompEvalBlock ─────────────────────────────────────────────────
// Displays 综合评价 + 高校专项/国家专项/地方专项 information for schools near the
// user's score. Data is fetched from:
//   /data/gaokao-comp-eval/<province>/<year>.json
//   /data/gaokao-special-program/<province>/<year>.json
//
// Props:
//   province  (string)  — province code e.g. 'HI'
//   year      (number)  — gaokao year e.g. 2024
//   score     (number)  — user's gaokao score
//   lang      (string)  — 'zh' | 'en'
//
// data-testid: "comp-eval-block" / "comp-eval-card-{schoolCode}"
//              "special-program-block" / "special-program-card-{idx}"

// F7 silent 404 fallback: known available years for these two endpoints. Must
// stay in sync with the inline `_DATA_BY_PROVINCE_YEAR` maps inside
// lib/gaokao-comp-eval-loader.js and lib/gaokao-special-program-loader.js.
// When the requested year is not listed here the component skips the HTTP
// fetch entirely (no red 404 in the browser console) and renders a
// 数据建设中 placeholder section.
const COMP_EVAL_AVAILABLE_YEARS = {
  HI: [2024],
};
const SPECIAL_PROGRAM_AVAILABLE_YEARS = {
  HI: [2024],
};

const CompEvalBlock = ({ province, year, score, lang }) => {
  const [compEvalData, setCompEvalData] = React.useState([]);
  const [specialData, setSpecialData] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [activeTab, setActiveTab] = React.useState('compEval'); // 'compEval' | 'special'
  const [specialFilter, setSpecialFilter] = React.useState('all'); // 'all'|'高校专项'|'国家专项'|'地方专项'

  const prov = (province || 'HI').toUpperCase();
  const yr = Number(year) || 2024;
  const targetScore = Number(score);
  const SCORE_BUFFER = 60; // show schools with requiredScore within ±60 of user score

  const dict = React.useMemo(() => {
    const d = (window.I18N && window.I18N[lang] && window.I18N[lang].gk && window.I18N[lang].gk.compEval)
      || (window.I18N && window.I18N.zh && window.I18N.zh.gk && window.I18N.zh.gk.compEval)
      || {};
    return {
      eyebrow:            d.eyebrow            || (lang === 'zh' ? '多元录取通道' : 'Alternative Admission'),
      title:              d.title              || (lang === 'zh' ? '综合评价 & 专项计划' : 'Comp. Eval & Special Programs'),
      subtitle:           d.subtitle           || (lang === 'zh' ? '综合评价招生与专项计划为高考外加分/降分通道，可扩大志愿选择空间' : 'Alternative admission tracks that may lower required scores'),
      tabCompEval:        d.tabCompEval        || (lang === 'zh' ? '综合评价' : 'Comp. Eval'),
      tabSpecial:         d.tabSpecial         || (lang === 'zh' ? '专项计划' : 'Special Programs'),
      programName:        d.programName        || (lang === 'zh' ? '项目名称' : 'Program'),
      requiredScore:      d.requiredScore      || (lang === 'zh' ? '参考分数线' : 'Score threshold'),
      evalMethods:        d.evalMethods        || (lang === 'zh' ? '评价方式' : 'Evaluation methods'),
      majors:             d.majors             || (lang === 'zh' ? '适用专业' : 'Applicable majors'),
      advantages:         d.advantages         || (lang === 'zh' ? '项目亮点' : 'Highlights'),
      programType:        d.programType        || (lang === 'zh' ? '计划类型' : 'Program type'),
      enrollment:         d.enrollment         || (lang === 'zh' ? '招生规模' : 'Enrollment'),
      origin:             d.origin             || (lang === 'zh' ? '报名资格' : 'Eligibility'),
      scorePolicy:        d.scorePolicy        || (lang === 'zh' ? '降分政策' : 'Score reduction policy'),
      filterAll:          d.filterAll          || (lang === 'zh' ? '全部' : 'All'),
      filterGaoxiao:      d.filterGaoxiao      || (lang === 'zh' ? '高校专项' : 'University'),
      filterNational:     d.filterNational     || (lang === 'zh' ? '国家专项' : 'National'),
      filterLocal:        d.filterLocal        || (lang === 'zh' ? '地方专项' : 'Local'),
      noData:             d.noData             || (lang === 'zh' ? '暂无符合分数段的综合评价院校' : 'No schools found for this score range'),
      noSpecialData:      d.noSpecialData      || (lang === 'zh' ? '暂无专项计划数据' : 'No special program data'),
      dataInProgress:     d.dataInProgress     || (lang === 'zh' ? '数据建设中' : 'Data coming soon'),
      sourceNote:         d.sourceNote         || (lang === 'zh' ? '* 数据基于2024年政策，仅供参考，请以官方简章为准' : '* Data based on 2024 policies. Always verify with official school announcements.'),
      pts:                d.pts                || (lang === 'zh' ? '分' : 'pts'),
      persons:            d.persons            || (lang === 'zh' ? '人' : 'ppl'),
    };
  }, [lang]);

  // F7 silent 404 fallback: derive year-availability per endpoint. Skipping the
  // fetch entirely is the only reliable way to avoid red 404 entries in the
  // browser console — a fetch().catch() handler can swallow the rejected
  // promise but cannot suppress the network log.
  const compEvalAvailable = React.useMemo(() => {
    const years = COMP_EVAL_AVAILABLE_YEARS[prov] || [];
    return years.includes(yr);
  }, [prov, yr]);
  const specialAvailable = React.useMemo(() => {
    const years = SPECIAL_PROGRAM_AVAILABLE_YEARS[prov] || [];
    return years.includes(yr);
  }, [prov, yr]);

  React.useEffect(() => {
    setLoading(true);
    setError(null);

    const fetchCompEval = compEvalAvailable
      ? fetch(`/data/gaokao-comp-eval/${prov}/${yr}.json`)
          .then((r) => (r.ok ? r.json() : []))
          .catch(() => [])
      : Promise.resolve([]);

    const fetchSpecial = specialAvailable
      ? fetch(`/data/gaokao-special-program/${prov}/${yr}.json`)
          .then((r) => (r.ok ? r.json() : []))
          .catch(() => [])
      : Promise.resolve([]);

    Promise.all([fetchCompEval, fetchSpecial])
      .then(([ceData, spData]) => {
        setCompEvalData(Array.isArray(ceData) ? ceData : []);
        setSpecialData(Array.isArray(spData) ? spData : []);
        setLoading(false);
      })
      .catch(() => {
        // Defensive: keep empty arrays + clear loading. Don't surface errors
        // for known-missing-year cases — those are silent by design.
        setCompEvalData([]);
        setSpecialData([]);
        setLoading(false);
      });
  }, [prov, yr, compEvalAvailable, specialAvailable]);

  // Filter comp-eval by score proximity
  const filteredCompEval = React.useMemo(() => {
    if (!Number.isFinite(targetScore) || targetScore <= 0) return compEvalData;
    return compEvalData.filter((e) => {
      if (typeof e.requiredScore !== 'number') return true;
      return e.requiredScore <= targetScore + SCORE_BUFFER;
    });
  }, [compEvalData, targetScore]);

  // Filter special programs
  const filteredSpecial = React.useMemo(() => {
    if (specialFilter === 'all') return specialData;
    return specialData.filter((e) => e.programType === specialFilter);
  }, [specialData, specialFilter]);

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

  const tagStyle = (color) => ({
    display: 'inline-block',
    fontSize: 11,
    fontWeight: 600,
    padding: '2px 8px',
    borderRadius: 20,
    marginRight: 4,
    marginBottom: 4,
    background: color || 'var(--pb-surface-2)',
    color: 'var(--pb-fg)',
  });

  const programTypeColor = {
    '高校专项': '#e8f4fd',
    '国家专项': '#fef3e2',
    '地方专项': '#e8fdf0',
  };

  if (loading) {
    return (
      <div data-testid="comp-eval-block" style={{ padding: '32px 0', textAlign: 'center', color: 'var(--pb-fg-muted)' }}>
        <div className="pb-spinner" style={{ marginBottom: 8 }} />
        {lang === 'zh' ? '加载综合评价数据…' : 'Loading comp-eval data…'}
      </div>
    );
  }

  if (error) {
    return (
      <div data-testid="comp-eval-block" style={{ padding: '20px', color: 'var(--pb-error)', textAlign: 'center' }}>
        {lang === 'zh' ? `加载失败: ${error}` : `Load error: ${error}`}
      </div>
    );
  }

  const hasCompEval = filteredCompEval.length > 0;
  const hasSpecial = filteredSpecial.length > 0;

  // Nothing to show: silently hide the section. When the year itself is
  // unavailable on disk we never fetched, so this branch covers both
  // "year missing" and "year present but no entries matched filters".
  if (!hasCompEval && !hasSpecial) {
    return null;
  }

  return (
    <section data-testid="comp-eval-block" style={{ margin: '32px 0' }}>
      {/* Header */}
      <div style={{ marginBottom: 20 }}>
        <div className="pb-eyebrow" style={{ marginBottom: 6 }}>{dict.eyebrow}</div>
        <h3 style={{ fontFamily: 'var(--pb-serif)', fontSize: 22, fontWeight: 600, margin: '0 0 6px' }}>
          {dict.title}
        </h3>
        <p style={{ fontSize: 13, color: 'var(--pb-fg-muted)', margin: 0, lineHeight: 1.6 }}>
          {dict.subtitle}
        </p>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 20, borderBottom: '1px solid var(--pb-border)', paddingBottom: 0 }}>
        {[
          { key: 'compEval', label: dict.tabCompEval, count: filteredCompEval.length },
          { key: 'special', label: dict.tabSpecial, count: specialData.length },
        ].map(({ key, label, count }) => (
          <button
            key={key}
            onClick={() => setActiveTab(key)}
            style={{
              padding: '8px 16px',
              border: 'none',
              background: 'none',
              cursor: 'pointer',
              fontSize: 13,
              fontWeight: activeTab === key ? 700 : 400,
              color: activeTab === key ? 'var(--pb-primary)' : 'var(--pb-fg-muted)',
              borderBottom: activeTab === key ? '2px solid var(--pb-primary)' : '2px solid transparent',
              marginBottom: -1,
            }}
          >
            {label} <span style={{ opacity: 0.6 }}>({count})</span>
          </button>
        ))}
      </div>

      {/* Comp-Eval Tab */}
      {activeTab === 'compEval' && (
        <div>
          {!hasCompEval ? (
            <p style={{ color: 'var(--pb-fg-muted)', fontSize: 13, textAlign: 'center', padding: '20px 0' }}>{dict.noData}</p>
          ) : (
            filteredCompEval.map((entry) => (
              <div
                key={`${entry.schoolCode}-${entry.programName}`}
                data-testid={`comp-eval-card-${entry.schoolCode}`}
                style={cardStyle}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 8, marginBottom: 10 }}>
                  <div>
                    <span style={{ fontWeight: 700, fontSize: 15 }}>{entry.schoolName}</span>
                    <span style={{ marginLeft: 8, fontSize: 13, color: 'var(--pb-primary)', fontWeight: 600 }}>
                      {entry.programName}
                    </span>
                  </div>
                  {typeof entry.requiredScore === 'number' && (
                    <div style={{ fontSize: 13, color: 'var(--pb-fg-muted)', whiteSpace: 'nowrap' }}>
                      {dict.requiredScore}: <strong style={{ color: 'var(--pb-fg)' }}>{entry.requiredScore}</strong> {dict.pts}
                    </div>
                  )}
                </div>

                {/* Evaluation Methods */}
                {Array.isArray(entry.evaluationMethods) && entry.evaluationMethods.length > 0 && (
                  <div style={{ marginBottom: 8 }}>
                    <span style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginRight: 6 }}>{dict.evalMethods}:</span>
                    {entry.evaluationMethods.map((m) => (
                      <span key={m} style={tagStyle('#e8f4fd')}>{m}</span>
                    ))}
                  </div>
                )}

                {/* Applicable Majors */}
                {Array.isArray(entry.applicableMajors) && entry.applicableMajors.length > 0 && (
                  <div style={{ marginBottom: 8 }}>
                    <span style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginRight: 6 }}>{dict.majors}:</span>
                    {entry.applicableMajors.map((m) => (
                      <span key={m} style={tagStyle()}>{m}</span>
                    ))}
                  </div>
                )}

                {/* Advantages */}
                {entry.advantages && (
                  <p style={{ fontSize: 12, color: 'var(--pb-fg-muted)', margin: 0, lineHeight: 1.6 }}>
                    {entry.advantages}
                  </p>
                )}
              </div>
            ))
          )}
        </div>
      )}

      {/* Special Programs Tab */}
      {activeTab === 'special' && (
        <div>
          {/* Filter buttons */}
          <div style={{ display: 'flex', gap: 6, marginBottom: 16, flexWrap: 'wrap' }}>
            {[
              { key: 'all', label: dict.filterAll },
              { key: '高校专项', label: dict.filterGaoxiao },
              { key: '国家专项', label: dict.filterNational },
              { key: '地方专项', label: dict.filterLocal },
            ].map(({ key, label }) => (
              <button
                key={key}
                onClick={() => setSpecialFilter(key)}
                style={{
                  padding: '4px 12px',
                  fontSize: 12,
                  border: `1px solid ${specialFilter === key ? 'var(--pb-primary)' : 'var(--pb-border)'}`,
                  borderRadius: 20,
                  background: specialFilter === key ? 'var(--pb-primary)' : 'var(--pb-surface)',
                  color: specialFilter === key ? '#fff' : 'var(--pb-fg)',
                  cursor: 'pointer',
                  fontWeight: specialFilter === key ? 600 : 400,
                }}
              >
                {label}
              </button>
            ))}
          </div>

          {!hasSpecial ? (
            <p style={{ color: 'var(--pb-fg-muted)', fontSize: 13, textAlign: 'center', padding: '20px 0' }}>{dict.noSpecialData}</p>
          ) : (
            filteredSpecial.map((entry, idx) => (
              <div
                key={`${entry.schoolCode}-${entry.programType}-${idx}`}
                data-testid={`special-program-card-${idx}`}
                style={cardStyle}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 8, marginBottom: 10 }}>
                  <div>
                    <span style={{ fontWeight: 700, fontSize: 15 }}>{entry.schoolName}</span>
                    <span
                      style={{
                        marginLeft: 8,
                        fontSize: 11,
                        fontWeight: 600,
                        padding: '2px 8px',
                        borderRadius: 20,
                        background: programTypeColor[entry.programType] || '#f5f5f5',
                        color: 'var(--pb-fg)',
                      }}
                    >
                      {entry.programType}
                    </span>
                  </div>
                  {typeof entry.enrollmentScale === 'number' && (
                    <div style={{ fontSize: 13, color: 'var(--pb-fg-muted)', whiteSpace: 'nowrap' }}>
                      {dict.enrollment}: <strong style={{ color: 'var(--pb-fg)' }}>{entry.enrollmentScale}</strong> {dict.persons}
                    </div>
                  )}
                </div>

                {/* Origin/Eligibility */}
                {entry.requiredOrigin && (
                  <div style={{ marginBottom: 8, fontSize: 12 }}>
                    <span style={{ color: 'var(--pb-fg-muted)', marginRight: 6 }}>{dict.origin}:</span>
                    <span>{entry.requiredOrigin}</span>
                  </div>
                )}

                {/* Applicable Majors */}
                {Array.isArray(entry.applicableMajors) && entry.applicableMajors.length > 0 && (
                  <div style={{ marginBottom: 8 }}>
                    <span style={{ fontSize: 12, color: 'var(--pb-fg-muted)', marginRight: 6 }}>{dict.majors}:</span>
                    {entry.applicableMajors.map((m) => (
                      <span key={m} style={tagStyle()}>{m}</span>
                    ))}
                  </div>
                )}

                {/* Score Reduction Policy */}
                {entry.scoreReductionPolicy && (
                  <p style={{ fontSize: 12, color: 'var(--pb-fg-muted)', margin: 0, lineHeight: 1.6 }}>
                    {dict.scorePolicy}: {entry.scoreReductionPolicy}
                  </p>
                )}
              </div>
            ))
          )}
        </div>
      )}

      {/* Source note */}
      <p style={{ fontSize: 11, color: 'var(--pb-fg-muted)', marginTop: 12, lineHeight: 1.5 }}>
        {dict.sourceNote}
      </p>
    </section>
  );
};
