// UR2D — Home v2: intro lights, top nav, race-week hero, pixel-car marquee.
// Loaded after shared + store + roster. Consumes: COLORS, LEAGUES, LEAGUE_BY_ID,
// getCalendar, UR2D_CALENDAR, getCountdown, FlagSvg.

// ─── helpers ─────────────────────────────────────────────────────────────────
const ur2Reduced = () =>
  window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

function ur2ScrollTo(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - 8;
  window.scrollTo({ top, behavior: ur2Reduced() ? 'auto' : 'smooth' });
}

// Split a track name into 1–2 display lines: prefer the hyphen, else mid-word-count.
function ur2SplitTrack(track) {
  if (!track) return ['TBA'];
  if (track.includes('-')) {
    const i = track.indexOf('-');
    return [track.slice(0, i + 1), track.slice(i + 1)];
  }
  const words = track.split(' ');
  if (words.length === 1 || track.length <= 10) return [track];
  const mid = Math.ceil(words.length / 2);
  return [words.slice(0, mid).join(' '), words.slice(mid).join(' ')];
}

function ur2FmtDate(iso) {
  if (!iso) return 'TBA';
  const d = new Date(iso + 'T00:00:00Z');
  return d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' }).toUpperCase();
}

// ─── INTRO — start-light gantry overlay ──────────────────────────────────────
// 5 pods light up left→right, hold, then all out at once; overlay lifts.
const UR2IntroLights = ({ onDone }) => {
  const [lit, setLit] = React.useState(0);      // 0..5
  const [phase, setPhase] = React.useState('run'); // run | out | fade
  const timers = React.useRef([]);

  const finish = React.useCallback(() => {
    timers.current.forEach(clearTimeout);
    onDone();
  }, [onDone]);

  React.useEffect(() => {
    const T = (fn, ms) => timers.current.push(setTimeout(fn, ms));
    for (let i = 1; i <= 5; i++) T(() => setLit(i), 350 + (i - 1) * 260);
    T(() => setPhase('out'), 2150);
    T(() => setPhase('fade'), 2600);
    T(finish, 3150);
    return () => timers.current.forEach(clearTimeout);
  }, [finish]);

  return (
    <div
      onClick={finish}
      role="presentation"
      style={{
        position: 'fixed', inset: 0, zIndex: 999, background: '#050507',
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        gap: 44, cursor: 'pointer',
        opacity: phase === 'fade' ? 0 : 1, transition: 'opacity .5s ease'
      }}>
      <div style={{ display: 'flex', gap: 22 }}>
        {[1, 2, 3, 4, 5].map((i) => {
          const on = phase === 'run' && lit >= i;
          return (
            <div key={i} style={{
              display: 'flex', flexDirection: 'column', gap: 12,
              padding: '14px 10px', background: '#0e0e10',
              border: `1px solid ${COLORS.hairline}`, borderRadius: 8
            }}>
              {[0, 1].map((j) => (
                <span key={j} style={{
                  width: 42, height: 42, borderRadius: '50%',
                  background: on ? COLORS.red : '#17171b',
                  boxShadow: on ? `0 0 24px 6px ${COLORS.red}88, inset 0 0 8px rgba(0,0,0,.35)` : 'inset 0 0 8px rgba(0,0,0,.6)',
                  transition: 'background .12s ease, box-shadow .12s ease'
                }}></span>
              ))}
            </div>
          );
        })}
      </div>
      <div style={{
        fontFamily: 'JetBrains Mono', fontSize: 12, letterSpacing: '0.42em',
        textTransform: 'uppercase', color: phase === 'run' ? COLORS.textDim : COLORS.text,
        transition: 'color .2s ease'
      }}>
        {phase === 'run' ? 'Race control · stand by' : 'Lights out.'}
      </div>
    </div>
  );
};

// ─── TOP NAV — slim, anchors into this page + escape hatch to the full site ──
const UR2TopNav = () => {
  const items = [
    ['standings', 'Standings'],
    ['calendar', 'Calendar'],
    ['thegrid', 'The Grid'],
    ['leagues', 'Leagues']
  ];
  return (
    <div style={{
      position: 'relative', zIndex: 5, display: 'flex', alignItems: 'center', gap: 22,
      padding: '26px 44px', flexWrap: 'wrap'
    }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 13 }}>
        <img src="assets/ur2d-logo.png" alt="UR2D" style={{ height: 40, width: 'auto', display: 'block', mixBlendMode: 'screen' }} />
        <span style={{ display: 'flex', flexDirection: 'column', lineHeight: 0.95 }}>
          <span style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 17, letterSpacing: '0.05em', color: COLORS.text, textTransform: 'uppercase' }}>Ultimate Racing</span>
          <span style={{ fontFamily: 'Archivo', fontWeight: 800, fontSize: 10, letterSpacing: '0.46em', color: COLORS.red, textTransform: 'uppercase', marginTop: 3 }}>Esports</span>
        </span>
      </span>
      <span style={{ flex: 1 }}></span>
      <nav style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
        {items.map(([id, label]) => (
          <button key={id} onClick={() => ur2ScrollTo(id)} style={{
            all: 'unset', cursor: 'pointer', padding: '9px 12px',
            fontFamily: 'Archivo', fontWeight: 700, fontSize: 12, letterSpacing: '0.14em',
            textTransform: 'uppercase', color: COLORS.textMute
          }}>{label}</button>
        ))}
        <a href="Ultimate Racing Esports.html" style={{
          marginLeft: 14, padding: '11px 18px', background: COLORS.red, color: '#fff',
          fontFamily: 'Archivo', fontWeight: 800, fontSize: 12, letterSpacing: '0.2em',
          textTransform: 'uppercase', textDecoration: 'none'
        }}>Full site →</a>
      </nav>
    </div>
  );
};

// ─── COUNTDOWN — big broadcast digits, ticking against the real clock ────────
const UR2Countdown = ({ toIso }) => {
  const [, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), 1000);
    return () => clearInterval(id);
  }, []);
  const c = getCountdown(toIso);
  const cells = [['Days', c.d], ['Hrs', c.h], ['Min', c.m], ['Sec', c.s]];
  return (
    <div style={{ display: 'flex', alignItems: 'stretch' }}>
      {cells.map(([label, v], i) => (
        <div key={label} style={{
          display: 'flex', flexDirection: 'column', gap: 8,
          padding: '0 30px 0 ' + (i === 0 ? '0' : '30px'),
          borderLeft: i > 0 ? `1px solid ${COLORS.hairline}` : 'none'
        }}>
          <span style={{
            fontFamily: 'Archivo', fontWeight: 900, fontSize: 74, lineHeight: 0.9,
            letterSpacing: '-0.03em', color: COLORS.text, fontVariantNumeric: 'tabular-nums'
          }}>{String(v).padStart(2, '0')}</span>
          <span style={{ fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.36em', textTransform: 'uppercase', color: i === 3 ? COLORS.red : COLORS.textDim }}>{label}</span>
        </div>
      ))}
    </div>
  );
};

// ─── SESSION BAR — one raceday, four grids, bottom of the hero ───────────────
// Click a league to retarget the hero countdown to that grid's start time.
const UR2SessionBar = ({ active = 'ul', onPick, round }) => {
  const order = ['al', 'jl', 'hl', 'ul']; // chronological on race day
  const timeFor = (id) => { const r = round != null && getCalendar(id).races.find((x) => x.round === round); return (r && r.utcHHMM) || UR2D_CALENDAR.times[id]; };
  return (
    <div style={{
      position: 'relative', zIndex: 4,
      display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
      borderTop: `1px solid ${COLORS.hairline}`,
      background: 'rgba(5,5,7,0.78)', backdropFilter: 'blur(8px)'
    }}>
      {order.map((id, i) => {
        const L = LEAGUE_BY_ID[id];
        const t = timeFor(id);
        const top = id === active;
        return (
          <button key={id} type="button" onClick={() => onPick && onPick(id)} aria-pressed={top} style={{
            all: 'unset', boxSizing: 'border-box', minWidth: 0, cursor: onPick ? 'pointer' : 'default', transition: 'background .2s ease',
            display: 'flex', alignItems: 'center', gap: 14, padding: '20px 26px',
            borderRight: i < 3 ? `1px solid ${COLORS.hairline}` : 'none',
            background: top ? `linear-gradient(180deg, ${L.accent}14, transparent)` : 'transparent',
            position: 'relative'
          }}>
            <span style={{ position: 'absolute', left: 0, top: 0, right: 0, height: 2, background: top ? L.accent : 'transparent' }}></span>
            <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 52, height: 52, flexShrink: 0 }}>
              <img src={id === 'ul' ? 'assets/ul-mark.png' : L.logo} alt={L.short} style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }} />
            </span>
            <span style={{ display: 'flex', flexDirection: 'column', gap: 3, minWidth: 0 }}>
              <span style={{ fontFamily: 'Archivo', fontWeight: 800, fontSize: 13, letterSpacing: '0.08em', textTransform: 'uppercase', color: COLORS.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{L.name}</span>
              <span style={{ fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.18em', color: top ? L.accent : COLORS.textMute }}>{t} UTC · Sunday</span>
            </span>
          </button>
        );
      })}
    </div>
  );
};

// ─── HERO — race week splash ─────────────────────────────────────────────────
const UR2Hero = ({ motion = true, nav }) => {
  const cal = getCalendar('ul');
  const race = cal.races.find((r) => r.status === 'next') || null;
  const hasDate = !!(race && race.date);
  const bg = (race && race.trackImage) || 'assets/tracks/sm/spa.jpg';
  const lines = ur2SplitTrack(race ? race.track : null);
  const [lg, setLg] = React.useState('ul');
  const lgRace = (race && getCalendar(lg).races.find((r) => r.round === race.round)) || race;
  const lgTime = (lgRace && lgRace.utcHHMM) || UR2D_CALENDAR.times[lg] || '17:50';
  const toIso = hasDate ? `${race.date}T${lgTime.padStart(5, '0')}:00Z` : null;
  const flagKind = (race && typeof UR_GP_FLAG !== 'undefined' && UR_GP_FLAG[race.grandPrix]) || 'pacific';
  const animate = motion && !ur2Reduced();
  // Panoramic track art (wider than ~2:1, e.g. Barcelona 2.6:1) would be cropped to its middle and
  // upscaled ~2× by `cover` on a 100vh hero → shown zoomed out instead, over a blurred fill of itself.
  const [bgPano, setBgPano] = React.useState(false);

  return (
    <section data-screen-label="Home v2 — Hero" style={{
      position: 'relative', minHeight: '100vh', background: '#000',
      overflow: 'hidden', display: 'flex', flexDirection: 'column'
    }}>
      {/* Track backdrop */}
      <div aria-hidden style={{
        position: 'absolute', inset: '-4%',
        filter: 'saturate(0.85) contrast(1.04) brightness(0.9)',
        animation: animate ? 'ur2-kb 46s ease-in-out infinite alternate' : 'none'
      }}>
        {bgPano && <div style={{ position: 'absolute', inset: 0, backgroundImage: `url(${bg})`, backgroundSize: 'cover', backgroundPosition: 'center 40%', filter: 'blur(28px) brightness(0.55)', transform: 'scale(1.1)' }}></div>}
        <img src={bg} alt="" onLoad={(e) => setBgPano(e.currentTarget.naturalWidth / e.currentTarget.naturalHeight > 2.05)}
          style={bgPano ? {
            position: 'absolute', left: '50%', top: '47%', height: '80%', width: 'auto', minWidth: '100%', maxWidth: 'none',
            transform: 'translate(-50%, -50%)', objectFit: 'cover', objectPosition: 'center 40%',
            WebkitMaskImage: 'linear-gradient(180deg, transparent 0%, #000 14%, #000 86%, transparent 100%)',
            maskImage: 'linear-gradient(180deg, transparent 0%, #000 14%, #000 86%, transparent 100%)'
          } : { position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 40%' }}></img>
      </div>
      {/* Scrims */}
      <div aria-hidden style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(0,0,0,0.88) 0%, rgba(0,0,0,0.42) 30%, rgba(0,0,0,0.34) 60%, rgba(0,0,0,0.95) 100%)' }}></div>
      <div aria-hidden style={{ position: 'absolute', inset: 0, background: 'linear-gradient(90deg, rgba(0,0,0,0.78) 0%, rgba(0,0,0,0.25) 46%, transparent 74%)' }}></div>

      {nav === undefined ? <UR2TopNav /> : nav}

      {/* Main brief */}
      <div style={{ position: 'relative', zIndex: 4, flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '110px 48px 40px' }}>
        {/* RACE WEEK banner — red plate + round counter + season progress ticks */}
        <div style={{ position: 'absolute', top: 30, left: 48, right: 48, display: 'flex', alignItems: 'stretch', gap: 2, flexWrap: 'wrap', zIndex: 1 }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 10, padding: '11px 18px',
            background: COLORS.red, color: '#fff', fontFamily: 'Archivo', fontWeight: 900,
            fontSize: 11, letterSpacing: '0.26em', textTransform: 'uppercase', whiteSpace: 'nowrap',
            boxShadow: `0 0 34px ${COLORS.red}55`
          }}>
            <span aria-hidden style={{ width: 8, height: 8, borderRadius: '50%', background: '#fff', animation: animate ? 'ur2-pulse 1.4s ease-in-out infinite' : 'none' }}></span>
            Race week
          </span>
          <span style={{
            display: 'inline-flex', alignItems: 'baseline', gap: 7, padding: '11px 18px',
            background: 'rgba(5,5,7,0.72)', border: `1px solid ${COLORS.hairline}`, borderLeft: 'none',
            fontFamily: 'Archivo', textTransform: 'uppercase', whiteSpace: 'nowrap'
          }}>
            <span style={{ fontWeight: 700, fontSize: 11, letterSpacing: '0.24em', color: COLORS.textDim }}>Round</span>
            <span style={{ fontWeight: 900, fontSize: 11, letterSpacing: '0.24em', color: COLORS.text, fontVariantNumeric: 'tabular-nums' }}>
              {race ? String(race.round).padStart(2, '0') : '--'}
            </span>
            <span style={{ fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.24em', color: COLORS.textDim }}>/ {cal.races.length}</span>
          </span>
          <span style={{
            display: 'inline-flex', alignItems: 'center', padding: '11px 18px',
            background: 'rgba(5,5,7,0.72)', border: `1px solid ${COLORS.hairline}`, borderLeft: 'none',
            fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.24em',
            textTransform: 'uppercase', color: COLORS.textMute, whiteSpace: 'nowrap'
          }}>{((typeof getCalendar !== 'undefined' && getCalendar('ul').seasonPeriod) || 'Autumn 2026') + ' Season'}</span>
        </div>

        <h1 style={{
          margin: 0, fontFamily: 'Archivo', fontWeight: 900,
          fontSize: 'clamp(64px, 9.5vw, 148px)', lineHeight: 0.88, letterSpacing: '-0.045em',
          color: COLORS.text, textTransform: 'uppercase', textShadow: '0 6px 40px rgba(0,0,0,0.75)'
        }}>
          {lines.map((ln, i) => (
            <span key={i} style={{ display: 'block' }}>{ln}</span>
          ))}
        </h1>

        <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginTop: 24, flexWrap: 'wrap' }}>
          <span style={{ display: 'inline-flex', flexShrink: 0, boxShadow: '0 6px 22px rgba(0,0,0,0.6)' }}>
            <FlagSvg kind={flagKind} w={72} h={48} radius={3} />
          </span>
          <span style={{
            fontFamily: 'Archivo', fontWeight: 900, fontSize: 'clamp(28px, 3vw, 48px)',
            lineHeight: 1, letterSpacing: '-0.02em', textTransform: 'uppercase', color: COLORS.text
          }}>
            {race ? race.grandPrix.replace(' Grand Prix', '') : 'Next'}{' '}
            <span style={{ color: COLORS.red }}>Grand Prix</span>
          </span>
        </div>

        {race && race.laps != null && (
          <div style={{ marginTop: 14, fontFamily: 'JetBrains Mono', fontSize: 12, letterSpacing: '0.22em', color: COLORS.textMute, textTransform: 'uppercase' }}>
            {race.laps} laps{race.creator ? ` · track by ${race.creator}` : ''} · {ur2FmtDate(race.date)}
          </div>
        )}

        <div style={{ marginTop: 44 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 18, flexWrap: 'wrap', marginBottom: 18 }}>
            <span style={{ fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.34em', color: (LEAGUE_BY_ID[lg] && LEAGUE_BY_ID[lg].accent) || COLORS.red, textTransform: 'uppercase', transition: 'color .25s ease' }}>
              {hasDate ? 'Lights out in' : 'Lights out'}
            </span>
            {hasDate && (
              <span style={{ fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.22em', color: COLORS.textDim, textTransform: 'uppercase' }}>
                {LEAGUE_BY_ID[lg].name} · {lgTime} UTC
              </span>
            )}
          </div>
          {hasDate
            ? <UR2Countdown toIso={toIso} />
            : <div style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 74, color: COLORS.text, letterSpacing: '-0.03em', lineHeight: 0.9 }}>TBA</div>}
        </div>
      </div>

      <UR2SessionBar active={lg} onPick={setLg} round={race ? race.round : null} />

      <style>{`
        @keyframes ur2-kb { 0% { transform: scale(1.0) } 100% { transform: scale(1.07) translateY(-1.5%) } }
        @keyframes ur2-pulse { 0%, 100% { opacity: 1; transform: scale(1) } 50% { opacity: 0.3; transform: scale(0.8) } }
      `}</style>
    </section>
  );
};

// ─── PIXEL-CAR MARQUEE — the actual league liveries, in-game sprites ─────────
const UR2_MARQUEE_LANES = [
  {
    id: 'ul', label: 'UL · S25',
    cars: ['ONE', 'LSA', 'FLF', 'MAY', 'RKA', 'SCP', 'SGP', 'KMP', 'MZM'].map((a) => `assets/UL S25 Liveries/UL_S25_${a}.png`),
    h: 78, reverse: false, opacity: 1
  },
  {
    id: 'hl', label: 'HL · S22',
    cars: ['VLP', 'ARR', 'PRO', 'HKB', 'CPR', 'RGT', 'RSR', 'SWR'].map((a) => `assets/HL S22 Liveries/HL_S22_${a}.png`),
    h: 54, reverse: true, opacity: 0.85
  }
];

const UR2CarMarquee = ({ speed = 36, bare = false }) => (
  <section data-screen-label="Home v2 — Car marquee" style={{ background: bare ? 'transparent' : COLORS.base, borderBottom: bare ? 'none' : `1px solid ${COLORS.hairline}`, position: 'relative', overflow: 'hidden' }}>
    {UR2_MARQUEE_LANES.slice(0, 1).map((lane, li) => (
      <div key={lane.id} style={{ position: 'relative', overflow: 'hidden', borderTop: li > 0 ? `1px dashed ${COLORS.hairline}` : 'none', padding: '26px 0' }}>
        {/* lane asphalt line */}
        <div aria-hidden style={{ position: 'absolute', left: 0, right: 0, top: '50%', height: 3, marginTop: 12 + lane.h / 2, background: `repeating-linear-gradient(90deg, ${COLORS.hairline} 0 34px, transparent 34px 62px)`, opacity: 0.7 }}></div>
        <div style={{
          display: 'flex', whiteSpace: 'nowrap', willChange: 'transform',
          animation: `ur2-marquee ${lane.reverse ? speed * 1.35 : speed}s linear infinite normal`
        }}>
          {[0, 1].map((k) => (
            <div key={k} style={{ display: 'flex', gap: 120, padding: '0 60px', alignItems: 'center', flexShrink: 0 }}>
              {lane.cars.map((src, i) => (
                <img key={i} src={src} alt="" style={{ height: lane.h, width: 'auto', imageRendering: 'pixelated', opacity: lane.opacity, transform: 'scaleX(-1)', filter: 'drop-shadow(0 10px 14px rgba(0,0,0,0.5))' }} />
              ))}
            </div>
          ))}
        </div>
      </div>
    ))}
    <style>{`@keyframes ur2-marquee { 0% { transform: translateX(0) } 100% { transform: translateX(-50%) } }`}</style>
  </section>
);

Object.assign(window, { UR2IntroLights, UR2TopNav, UR2Hero, UR2CarMarquee, UR2SessionBar, ur2ScrollTo, ur2FmtDate, ur2Reduced });
