// UR2D Final — Calendar gate: poster-first calendar. Opens on a full-viewport
// interactive season poster (reuses PosterSlab from ur2d-calposter.jsx); hovering
// a round lifts it, clicking expands it over its neighbours, then the regular
// Calendar & Results view fades in. "Full calendar" (top right) reverses it.
// Load order: after ur2d-calposter.jsx, before ur2d-final.jsx.

const FDCAL_EASE = 'cubic-bezier(.7, 0, .25, 1)';
const FDCAL_BG = {
  backgroundColor: '#000',
  backgroundImage: [
    "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='26' height='26'%3E%3Cpath d='M13 9.5v7M9.5 13h7' stroke='rgba(255,255,255,0.045)' stroke-width='1'/%3E%3C/svg%3E\")",
    'radial-gradient(ellipse at 22% 12%, rgba(225,6,0,0.10), transparent 55%)',
    'radial-gradient(ellipse at 88% 96%, rgba(225,6,0,0.08), transparent 52%)',
    'linear-gradient(135deg, #000000 0%, #0b0203 46%, #150305 100%)'
  ].join(', '),
  backgroundSize: '26px 26px, cover, cover, cover'
};

const FDPosterSlab = React.memo(PosterSlab);

const FDCalendarGate = ({ t, matrixStrip }) => {
  const [calVer, setCalVer] = React.useState(0); // bumps when older seasons arrive from the DB (ur2d-db.jsx)
  React.useEffect(() => { const f = () => setCalVer((v) => v + 1); window.addEventListener('ur2d-calendars', f); return () => window.removeEventListener('ur2d-calendars', f); }, []);
  const calSeasons = React.useMemo(() => (typeof getCalendarSeasons === 'function' ? getCalendarSeasons() : []), [calVer]);
  const [calSid, setCalSid] = React.useState(null); // null = current season
  const cal = React.useMemo(() => getCalendar('ul', calSid || undefined), [calSid, calVer]);
  const canOpen = !cal.fromDb; // older DB seasons: rounds only — their results view isn't wired yet
  const nameChars = React.useMemo(() => Math.max(...cal.races.map((r) => posterTrackName(r.track).length)), [cal]);
  const breakAfter = cal.midSeasonBreakAfter;
  const [mode, setMode] = React.useState('poster'); // 'poster' | 'results'
  const [sel, setSel] = React.useState(null);       // expanded round (kept while in results)
  const [hov, setHov] = React.useState(null);
  const [selW, setSelW] = React.useState(null);     // clicked slab's width at click time (PosterSlab freezeW)
  const timer = React.useRef(null);
  React.useEffect(() => () => clearTimeout(timer.current), []);
  // Slab type scale: PosterSlab's fixed sizes assume 1920px-wide poster (~187px slabs).
  const [vw, setVw] = React.useState(() => window.innerWidth);
  React.useEffect(() => {
    const onR = () => setVw(window.innerWidth);
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);
  const slabScale = Math.max(0.42, Math.min(1, vw / 1920));
  const hs = Math.max(0.6, Math.min(1, vw / 1920));
  const times = (typeof UR2D_CALENDAR !== 'undefined' && UR2D_CALENDAR.times) || { ul: '17:50', hl: '16:10', jl: '15:15', al: '14:30' };

  const pick = (round, w) => {
    if (sel != null || !canOpen) return;
    setSelW(w || null);
    setSel(round);
    timer.current = setTimeout(() => setMode('results'), 760);
  };
  // Nav "Calendar & Results" clicked while already here → back to the full poster (ur2d-final.jsx dispatches).
  React.useEffect(() => { window.__fdCalInResults = mode === 'results'; return () => { window.__fdCalInResults = false; }; }, [mode]);
  React.useEffect(() => {
    const f = () => ReactDOM.flushSync(() => { clearTimeout(timer.current); setMode('poster'); setSel(null); setHov(null); });
    window.addEventListener('fd-calres-reset', f);
    return () => window.removeEventListener('fd-calres-reset', f);
  }, []);
  const backToPoster = () => {
    if (window.fdGo) return window.fdGo('calres'); // same wipe as the nav item
    setMode('poster');
    requestAnimationFrame(() => requestAnimationFrame(() => setSel(null)));
  };

  if (mode === 'results') {
    return (
      <div style={{ position: 'relative', animation: 'fdcal-in .5s ease both' }}>
        <div style={{ position: 'fixed', top: 'calc(var(--fd-nav-h, 72px) + 16px)', right: 20, zIndex: 60, display: 'flex', alignItems: 'center', gap: 14 }}>{/* top-right bar: round nav (portal) + Full cal (user 2026-10-09) */}
        <span id="fdcal-tr-slot" style={{ display: 'flex', alignItems: 'center' }}></span>
        <button onClick={backToPoster} style={{
          all: 'unset', cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', gap: 9, padding: '9px 14px',
          background: 'rgba(5,5,7,0.8)', border: `1px solid ${COLORS.hairline}`, backdropFilter: 'blur(8px)',
          fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.24em', textTransform: 'uppercase', color: COLORS.textMute
        }}
          onMouseEnter={(e) => { e.currentTarget.style.color = COLORS.text; e.currentTarget.style.borderColor = COLORS.red; }}
          onMouseLeave={(e) => { e.currentTarget.style.color = COLORS.textMute; e.currentTarget.style.borderColor = COLORS.hairline; }}>
          <span aria-hidden style={{ display: 'inline-grid', gridTemplateColumns: 'repeat(3, 4px)', gap: 2 }}>
            {[0, 1, 2, 3, 4, 5].map((i) => <span key={i} style={{ width: 4, height: 4, background: 'currentColor' }}></span>)}
          </span>
          Full cal
        </button>
        </div>
        <URCalendarResults version={t.calres} podiumColors={t.podiumColors} initialRound={sel} initialSeason={cal.season} posterRows={true} resultsView={t.resultsView || 'scroll'} />
        {matrixStrip}
        <style>{`@keyframes fdcal-in { from { opacity: 0 } to { opacity: 1 } }`}</style>
      </div>
    );
  }

  const open = sel != null;
  return (
    <section data-screen-label="Final — Calendar poster" style={{ ...FDCAL_BG, height: 'calc(100vh - 64px)', minHeight: 620, display: 'flex', flexDirection: 'column', overflow: 'hidden', animation: 'fdcal-in .4s ease both' }}>
      <div style={{ flexShrink: 0, minHeight: 128 * hs, display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 24 * hs, padding: `${14 * hs}px 44px`, borderBottom: `1px solid ${COLORS.hairline}`, opacity: open ? 0 : 1, transition: 'opacity .4s ease' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ fontFamily: 'JetBrains Mono', fontSize: Math.max(11, 15 * hs), fontWeight: 700, letterSpacing: '0.32em', textTransform: 'uppercase', color: COLORS.red }}>{cal.seasonPeriod} Season</div>
          <div style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 68 * hs, letterSpacing: '-0.03em', textTransform: 'uppercase', color: COLORS.text, lineHeight: 0.9 }}>Race Calendar</div>
        </div>
        <div style={{ width: 1, height: 60 * hs, background: COLORS.hairline, flexShrink: 0 }}></div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 20 * hs }}>
          {LEAGUES.map((L) => (
            <div key={L.id} style={{ height: 48 * hs, width: 56 * hs, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <img src={L.logo} alt={L.short} style={{ maxHeight: '100%', maxWidth: '100%', objectFit: 'contain', display: 'block' }}></img>
            </div>
          ))}
        </div>
        <div style={{ flex: 1 }}></div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 * hs, fontFamily: 'JetBrains Mono', fontSize: Math.max(10, 14 * hs), letterSpacing: '0.26em', textTransform: 'uppercase', color: '#8A8A92' }}>
          <div style={{ position: 'relative' }}>
            <select aria-label="Season" value={cal.season} onChange={(e) => { setCalSid(e.target.value); setHov(null); }} style={{
              appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none', height: Math.max(34, 42 * hs), boxSizing: 'border-box',
              background: 'rgba(255,255,255,0.04)', color: COLORS.text, border: `1px solid ${COLORS.hairline}`, borderRadius: 0,
              padding: '0 34px 0 14px', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'inherit', fontWeight: 700, letterSpacing: 'inherit', textTransform: 'uppercase'
            }}>
              {calSeasons.map((s) => <option key={s.id} value={s.id} style={{ background: COLORS.ink, color: COLORS.text }}>Season {s.id.replace(/^S/, '')}</option>)}
            </select>
            <span aria-hidden="true" style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: COLORS.red, fontSize: 8 }}>▼</span>
          </div>
          <span>{cal.races.length} Rounds</span>
        </div>
      </div>

      <div style={{ flex: 1, minHeight: 0, display: 'flex', borderLeft: `1px solid ${COLORS.hairline}` }}>
        {cal.races.map((race) => {
          const isSel = sel === race.round;
          const hovered = canOpen && !open && hov === race.round;
          return (
            <React.Fragment key={race.round}>
              <div
                onClick={(e) => pick(race.round, e.currentTarget.offsetWidth)}
                onMouseEnter={() => setHov(race.round)}
                onMouseLeave={() => setHov(null)}
                style={{
                  display: 'flex', minWidth: 0, overflow: 'hidden', position: 'relative',
                  cursor: open || !canOpen ? 'default' : 'pointer', flexBasis: 0,
                  flexGrow: open ? (isSel ? 1 : 0.0001) : (hovered ? 1.45 : 1),
                  opacity: open && !isSel ? 0 : 1,
                  boxShadow: hovered ? `inset 0 0 0 1px ${COLORS.red}66` : 'none',
                  contain: 'layout paint',
                  transition: `flex-grow .7s ${FDCAL_EASE}, opacity .45s ease, box-shadow .25s ease`
                }}>
                <FDPosterSlab race={race} intensity={82} showLaps={true} showTime={false} highlight={true} scale={slabScale} nameChars={nameChars} lift={hovered} freezeW={isSel ? selW : null}></FDPosterSlab>
              </div>
              {breakAfter && race.round === breakAfter ? (
                <div style={{ width: open ? 0 : 34, opacity: open ? 0 : 1, overflow: 'hidden', flexShrink: 0, transition: `width .7s ${FDCAL_EASE}, opacity .35s ease` }}>
                  <div style={{ width: 34, height: '100%' }}><PosterBreak></PosterBreak></div>
                </div>
              ) : null}
            </React.Fragment>
          );
        })}
      </div>
      <div style={{ height: 58, flexShrink: 0, display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '6px 34px', padding: '0 44px', borderTop: `1px solid ${COLORS.hairline}`, background: '#050506', opacity: open ? 0 : 1, transition: 'opacity .4s ease' }}>
        {canOpen ? (
        <React.Fragment>
        <div style={{ fontFamily: 'JetBrains Mono', fontSize: 12, letterSpacing: '0.26em', textTransform: 'uppercase', color: COLORS.red }}>All Rounds · Sundays</div>
        <div style={{ width: 1, height: 22, background: COLORS.hairline }}></div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 26 }}>
          {[['AL', times.al], ['JL', times.jl], ['CL', times.hl], ['UL', times.ul]].map(([lg, tm]) => (
            <div key={lg} style={{ fontFamily: 'JetBrains Mono', fontSize: 12, letterSpacing: '0.14em', color: '#B8B8C0' }}><span style={{ color: COLORS.text, fontWeight: 700 }}>{lg}</span> {tm}</div>
          ))}
          <div style={{ fontFamily: 'JetBrains Mono', fontSize: 12, letterSpacing: '0.14em', color: '#8A8A92' }}>UTC</div>
        </div>
        <div style={{ flex: 1 }}></div>
        <div style={{ fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.24em', textTransform: 'uppercase', color: COLORS.textMute }}>Click a round for results →</div>
        </React.Fragment>
        ) : (
        <div style={{ fontFamily: 'JetBrains Mono', fontSize: 12, letterSpacing: '0.26em', textTransform: 'uppercase', color: COLORS.textMute }}>Archive season{(() => {
          const on = (code) => (typeof urTimeLabelOn === 'function' ? urTimeLabelOn(code, cal.season) : null);
          const parts = [['JL', on('JL')], ['CL', on('CL')], ['UL', cal.ulTimeLabel]].filter(([, tm]) => tm);
          return parts.length ? <span>{parts.map(([code, tm]) => <span key={code}> · <span style={{ color: COLORS.text, fontWeight: 700 }}>{code}</span> {tm}</span>)} UTC</span> : ' · track & date only';
        })()}</div>
        )}
      </div>
      <style>{`@keyframes fdcal-in { from { opacity: 0 } to { opacity: 1 } }`}</style>
    </section>
  );
};

Object.assign(window, { FDCalendarGate });
