// ─── QA 2026-06-11 清单项5 — GaokaoCalendarBlock 填报日历 ─────────────────────
// 「📆 填报日历」chip → modal 显示官方志愿填报/录取/征集志愿时间线。
// 数据：data/gaokao-calendar/<prov>/<season>.json —— 全部日期逐格解析自
// 海南省考试局官网正文 HTML 表格（2026 实施办法附件），带来源 URL；
// 征集志愿官方自标「预计」，UI 必须保留该措辞。季节文件按 [2026, 2025]
// 回退加载，与页面年份下拉解耦（日历永远显示最近一季官方安排）。
// 跟随 GaokaoEventsBlock 的 chip+modal 模式。

const GaokaoCalendarBlock = ({ lang, province }) => {
  const [open, setOpen] = React.useState(false);
  const [cal, setCal] = React.useState(undefined); // undefined=未加载 null=无数据
  const prov = province || 'HI';
  const zh = lang !== 'en';

  React.useEffect(() => {
    if (!open || cal !== undefined) return;
    (async () => {
      for (const season of [2026, 2025]) {
        try {
          const r = await fetch(`/data/gaokao-calendar/${prov}/${season}.json`);
          if (!r.ok) continue;
          const d = await r.json();
          if (d && Array.isArray(d.events)) { setCal(d); return; }
        } catch (_e) { /* try next season */ }
      }
      setCal(null);
    })();
  }, [open]);

  const today = new Date();
  const todayKey = today.toISOString().slice(0, 10);
  const dayDiff = (iso) => Math.ceil((new Date(iso + 'T00:00:00+08:00') - today) / 86400000);
  const status = (ev) => {
    if (!ev.date) return 'tbd';
    const end = ev.endDate || ev.date;
    if (end < todayKey) return 'past';
    if (ev.date <= todayKey && todayKey <= end) return 'ongoing';
    return 'upcoming';
  };
  const ACTION_COLOR = { '填报志愿': 'var(--pb-navy-700)', '录取': 'var(--pb-success)', '军检': 'var(--pb-gold-700)' };

  const fmtRange = (ev) => {
    if (!ev.date) return zh ? '待官方公告' : 'TBA';
    const d = (s) => s.slice(5).replace('-', '/');
    return ev.endDate && ev.endDate !== ev.date ? `${d(ev.date)} – ${d(ev.endDate)}` : d(ev.date);
  };

  return (
    <React.Fragment>
      <button
        type="button"
        className="pb-btn pb-btn-ghost pb-btn-sm"
        data-testid="gaokao-calendar-chip"
        onClick={() => setOpen(true)}
        style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}
      >
        <span>📆</span>{zh ? '填报日历' : 'Filing Calendar'}
      </button>

      {open && (
        <div
          style={{ position: 'fixed', inset: 0, zIndex: 2147483647, background: 'rgba(15,23,42,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}
          onClick={() => setOpen(false)}
        >
          <div
            data-testid="gaokao-calendar-modal"
            onClick={(e) => e.stopPropagation()}
            style={{ background: 'var(--pb-bg, #fff)', borderRadius: 14, border: '1px solid var(--pb-border)', width: 'min(860px, 96vw)', maxHeight: '86vh', overflowY: 'auto', boxShadow: '0 24px 64px rgba(0,0,0,0.25)' }}
          >
            <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--pb-border)', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, position: 'sticky', top: 0, background: 'var(--pb-bg, #fff)' }}>
              <div>
                <div className="pb-eyebrow" style={{ marginBottom: 4 }}>{zh ? '官方时间安排' : 'Official schedule'}</div>
                <h3 style={{ margin: 0, fontFamily: 'var(--pb-serif)', fontSize: 19 }}>
                  {cal ? `${cal.year} ` : ''}{zh ? '海南志愿填报与录取日历' : 'Hainan Filing & Admission Calendar'}
                </h3>
                {cal && cal.source && cal.source[0] && (
                  <div style={{ fontSize: 11, color: 'var(--pb-fg-muted)', marginTop: 4 }}>
                    {zh ? '来源：' : 'Source: '}
                    <a href={cal.source[0].url} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--pb-navy-700)' }}>
                      {cal.source[0].publisher}
                    </a>
                    {cal.published ? ` · ${zh ? '发布' : 'published'} ${cal.published}` : ''}
                  </div>
                )}
              </div>
              <button type="button" className="pb-btn pb-btn-ghost pb-btn-sm" onClick={() => setOpen(false)}>{zh ? '关闭' : 'Close'}</button>
            </div>

            {cal === undefined && (
              <div style={{ padding: 32, textAlign: 'center', color: 'var(--pb-fg-muted)', fontSize: 13 }}>{zh ? '加载中…' : 'Loading…'}</div>
            )}
            {cal === null && (
              <div style={{ padding: 32, textAlign: 'center', color: 'var(--pb-fg-muted)', fontSize: 13 }}>
                {zh ? '该省份官方填报日历暂未收录。' : 'No official calendar ingested for this province yet.'}
              </div>
            )}

            {cal && (
              <div style={{ padding: '14px 24px 22px' }}>
                {cal.events.map((ev, i) => {
                  const st = status(ev);
                  const c = ACTION_COLOR[ev.action] || 'var(--pb-fg-muted)';
                  return (
                    <div
                      key={i}
                      data-testid="calendar-event-row"
                      style={{
                        display: 'flex', gap: 12, padding: '10px 12px', borderRadius: 8, alignItems: 'baseline',
                        opacity: st === 'past' ? 0.45 : 1,
                        background: st === 'ongoing' ? 'rgba(4,120,87,0.08)' : (st === 'upcoming' && ev.action === '填报志愿' ? 'rgba(30,64,175,0.06)' : 'transparent'),
                      }}
                    >
                      <div style={{ fontFamily: 'var(--pb-mono)', fontSize: 12, fontWeight: 600, minWidth: 96, whiteSpace: 'nowrap' }}>{fmtRange(ev)}</div>
                      <span style={{ flexShrink: 0, padding: '1px 8px', fontSize: 11, fontWeight: 700, borderRadius: 4, background: c + '18', color: c, whiteSpace: 'nowrap' }}>
                        {ev.action}
                      </span>
                      <div style={{ fontSize: 13, lineHeight: 1.5 }}>
                        {ev.batch}
                        {st === 'upcoming' && ev.date && (
                          <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--pb-navy-700)', fontWeight: 600, whiteSpace: 'nowrap' }}>
                            {zh ? `还有 ${dayDiff(ev.date)} 天` : `in ${dayDiff(ev.date)}d`}
                          </span>
                        )}
                        {st === 'ongoing' && (
                          <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--pb-success)', fontWeight: 700, whiteSpace: 'nowrap' }}>
                            {zh ? '进行中' : 'Now'}
                          </span>
                        )}
                        {ev.note && <div style={{ fontSize: 11, color: 'var(--pb-fg-muted)', marginTop: 2 }}>{ev.note}</div>}
                      </div>
                    </div>
                  );
                })}

                {Array.isArray(cal.zhengji) && cal.zhengji.length > 0 && (
                  <div style={{ marginTop: 16 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 6 }}>
                      {zh ? '征集志愿' : 'Supplementary rounds'}
                      <span style={{ marginLeft: 8, fontSize: 11, fontWeight: 400, color: 'var(--pb-gold-700)' }}>
                        {zh ? '官方预计时间 · 以考试局录取期间逐批公告为准' : 'Official estimates — confirmed batch-by-batch during admission'}
                      </span>
                    </div>
                    {cal.zhengji.map((z, i) => (
                      <div key={i} data-testid="calendar-zhengji-row" style={{ display: 'flex', gap: 12, padding: '6px 12px', alignItems: 'baseline', opacity: z.date && z.date < todayKey ? 0.45 : 1 }}>
                        <div style={{ fontFamily: 'var(--pb-mono)', fontSize: 12, minWidth: 96 }}>{z.date ? z.date.slice(5).replace('-', '/') : (zh ? '不安排' : '—')}</div>
                        <div style={{ fontSize: 12, color: 'var(--pb-fg)' }}>{z.batch}</div>
                      </div>
                    ))}
                  </div>
                )}

                {Array.isArray(cal.caveats) && cal.caveats.length > 0 && (
                  <div style={{ marginTop: 16, padding: '10px 12px', borderRadius: 8, background: 'var(--pb-surface-alt)', fontSize: 11, color: 'var(--pb-fg-muted)', lineHeight: 1.6 }}>
                    {cal.caveats.map((c, i) => <div key={i}>* {c}</div>)}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      )}
    </React.Fragment>
  );
};

window.GaokaoCalendarBlock = GaokaoCalendarBlock;
