// ─────────────────────────────────────────────────────────────────────────────
// UR2D — CALENDAR POSTER (standalone page component)
// Fullscreen 1920×1080 poster: one vertical slab per round, lined up in race
// order. Track image gradients down from the top of each slab, country flag
// gradients up from the bottom — the two fade into each other mid-slab.
// Loaded by "Calendar Poster.html" after shared → store.
// ─────────────────────────────────────────────────────────────────────────────

const POSTER_BG = '#000000';
// Milestone rounds (race.special) reveal a gold tag on hover — same gold as the P1 podium metal.
const POSTER_SPECIAL_GOLD = '#F0C53C';

// GP → flagcdn ISO code (flagcdn serves crisp wide rasters, unlike twemoji 72px)
const POSTER_GP_ISO = {
  'Japanese Grand Prix': 'jp',
  'Belgian Grand Prix': 'be',
  'Swedish Grand Prix': 'se',
  'Dutch Grand Prix': 'nl',
  'Italian Grand Prix': 'it',
  'Gold Coast Grand Prix': 'au-qld',
  'Sapporo International Grand Prix': 'jp-01',
  'Canadian Grand Prix': 'ca',
  'Australian Grand Prix': 'au',
  'Arcana East Flanders Grand Prix': 'be-vov',
  'Qatar Grand Prix': 'qa',
  'South African Grand Prix': 'za',
  'Spanish Grand Prix': 'es',
  'Ukrainian Grand Prix': 'ua',
  'German Grand Prix': 'de',
  'Indonesian Grand Prix': 'id',
  'Slovakian Grand Prix': 'sk',
  'British Grand Prix': 'gb',
  'Malaysian Grand Prix': 'my',
  'Welsh Grand Prix': 'gb-wls',
  'French Grand Prix': 'fr',
  'Monaco Grand Prix': 'mc',
  'Russian Grand Prix': 'ru',
  'United States Grand Prix': 'us',
  'Romanian Grand Prix': 'ro',
  'Canarian Grand Prix': 'ic', // local asset (not on flagcdn) via urFlagImg
};

// Track → short slab name (vertical type wants ≤ ~11 chars)
const POSTER_SHORT_TRACK = {
  'Spa-Francorchamps': 'SPA',
  "Winnipeg's Pass": 'WINNIPEG',
  'Highlands Park': 'HIGHLANDS',
  'Albert Park': 'ALBERT PARK',
  'Batavia Park': 'BATAVIA',
  'Circuit of Wales': 'WALES',
};
function posterTrackName(track) {
  return (POSTER_SHORT_TRACK[track] || track).toUpperCase();
}
function posterNameSize(name) {
  return 60;
}
function posterDate(iso) {
  if (!iso) return 'TBA';
  const d = new Date(iso + 'T12:00:00Z');
  const months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
  return String(d.getUTCDate()).padStart(2, '0') + ' ' + months[d.getUTCMonth()];
}

// One vertical slab = one round
function PosterSlab({ race, intensity, showLaps, showTime, highlight, scale = 1, nameChars, lift = false, freezeW = null }) {
  // freezeW: set while this slab expands open. Images stop object-fit:cover (which re-scaled them every frame as the slab
  // widened → zoom + pixelation) and hold their click-time scale, so the widening slab just reveals more of the same
  // flag / track image, soft-edged at its natural sides (user 2026-10-09: old open animation, no zoom, no sweep).
  const frzEdge = 'linear-gradient(to right, transparent, #000 16%, #000 84%, transparent)';
  const frzTrackImg = freezeW ? { position: 'absolute', top: 0, left: '50%', width: 'auto', maxWidth: 'none', transform: 'translateX(-50%)', WebkitMaskImage: frzEdge, maskImage: frzEdge } : null;
  const frzFlagBox = freezeW ? { height: 'auto', WebkitMaskImage: frzEdge.replace('to right', 'to bottom'), maskImage: frzEdge.replace('to right', 'to bottom') } : null;
  const iso = race.iso || POSTER_GP_ISO[race.grandPrix] || null; // archive rounds carry their own iso (data/ul-schedules.js)
  const name = posterTrackName(race.track);
  const nameSize = posterNameSize(name) * scale;
  const isNext = highlight && race.status === 'next';
  const isDone = highlight && race.status === 'done';
  const roundColor = isNext ? COLORS.red : isDone ? '#55555C' : COLORS.text;
  const k = intensity / 100;
  const up = lift ? 1.28 : 1; // hover brighten — opacity only (cheap), no CSS filter

  return (
    <div data-screen-label={'R' + race.round + ' ' + race.track} style={{ position: 'relative', flex: 1, minWidth: 0, overflow: 'hidden', borderRight: '1px solid ' + COLORS.hairline, background: 'transparent' }}>
      {/* TOP BG: track image, fading down into the slab */}
      {race.trackImage ? (
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: '58%', zIndex: 0, WebkitMaskImage: 'linear-gradient(to top, #000 55%, transparent 100%)', maskImage: 'linear-gradient(to top, #000 55%, transparent 100%)' }}>
          <img src={race.trackImage} alt="" decoding="async" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', opacity: Math.min(1, 0.41 * k * up), transition: 'opacity .25s ease', ...frzTrackImg }}></img>
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(10,10,12,0.45) 0%, rgba(10,10,12,0.6) 100%)' }}></div>
        </div>
      ) : null}
      {/* BOTTOM BG: country flag, fading up into the slab */}
      {iso ? (
        <div style={{ position: 'absolute', left: 0, right: 0, top: 0, height: '66.7%', zIndex: 0, overflow: 'hidden', containerType: 'size', WebkitMaskImage: 'linear-gradient(to bottom, #000 58%, transparent 100%)', maskImage: 'linear-gradient(to bottom, #000 58%, transparent 100%)' }}>
          <div style={{ position: 'absolute', top: '50%', left: '50%', width: '100cqh', height: '100cqw', transform: 'translate(-50%, -50%) rotate(90deg)', ...frzFlagBox }}>
            <img src={urFlagImg(iso, 640)} alt="" crossOrigin="anonymous" decoding="async" style={{ width: '100%', height: freezeW ? 'auto' : '100%', objectFit: 'cover', display: 'block', opacity: Math.min(1, 0.76 * k * up), transition: 'opacity .25s ease' }}></img>
          </div>
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, rgba(10,10,12,0.18) 0%, rgba(10,10,12,0.55) 100%)' }}></div>
        </div>
      ) : null}

      {/* CONTENT */}
      <div style={{ position: 'relative', zIndex: 1, height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between', padding: '26px 0 22px' }}>
        {/* Round number, big + bold on top */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <div style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 88 * scale, lineHeight: 0.85, letterSpacing: '-0.04em', color: roundColor, textShadow: '0 2px 14px rgba(0,0,0,0.7)' }}>
            {String(race.round).padStart(2, '0')}
          </div>
          <div style={{ fontFamily: 'JetBrains Mono', fontSize: Math.max(9, 11 * scale), letterSpacing: '0.28em', textTransform: 'uppercase', color: isNext ? COLORS.red : '#8A8A92' }}>
            {highlight ? (isNext ? 'NEXT' : isDone ? 'DONE' : 'ROUND') : 'ROUND'}
          </div>
          {race.special ? (
            <div aria-hidden={!lift} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, marginTop: 6, overflow: 'hidden', maxHeight: lift ? 60 : 0, opacity: lift ? 1 : 0, transform: lift ? 'translateY(0)' : 'translateY(-8px)', transition: 'max-height .35s ease, opacity .3s ease .08s, transform .35s ease .08s' }}>
              <div style={{ width: lift ? 28 : 0, height: 2, background: POSTER_SPECIAL_GOLD, transition: 'width .4s ease .15s' }}></div>
              <div style={{ fontFamily: 'JetBrains Mono', fontWeight: 700, fontSize: Math.max(9, 11 * scale), letterSpacing: '0.2em', textTransform: 'uppercase', color: POSTER_SPECIAL_GOLD, textAlign: 'center', lineHeight: 1.35, textShadow: '0 1px 10px rgba(0,0,0,0.85)', padding: '0 6px' }}>{race.special}</div>
            </div>
          ) : null}
        </div>

        {/* Vertical track name */}
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 0, padding: '14px 0', containerType: 'size' }}>
          <div style={{ writingMode: 'vertical-rl', transform: 'rotate(180deg)', fontFamily: 'Archivo', fontWeight: 900, fontSize: `min(${nameSize}px, calc(100cqh / ${((nameChars || name.length) * 0.7).toFixed(2)}))`, lineHeight: 0.82, letterSpacing: '-0.03em', textTransform: 'uppercase', color: (highlight && isDone) ? 'rgba(250,250,250,0.55)' : COLORS.text, textShadow: '0 2px 16px rgba(0,0,0,0.75)', whiteSpace: 'nowrap' }}>
            {name}
          </div>
        </div>

        {/* Date + optional laps / time, over the flag */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, textShadow: '0 1px 10px rgba(0,0,0,0.85)' }}>
          <div style={{ fontFamily: 'JetBrains Mono', fontWeight: 700, fontSize: Math.max(11, 17 * scale), letterSpacing: '0.14em', color: COLORS.text }}>{posterDate(race.date)}</div>
          {showLaps && race.laps ? (
            <div style={{ fontFamily: 'JetBrains Mono', fontSize: Math.max(9, 11 * scale), letterSpacing: '0.22em', color: 'rgba(250,250,250,0.75)' }}>{race.laps} LAPS</div>
          ) : null}
          {showTime ? (
            <div style={{ fontFamily: 'JetBrains Mono', fontSize: Math.max(9, 11 * scale), letterSpacing: '0.22em', color: 'rgba(250,250,250,0.75)' }}>{race.utcTime}</div>
          ) : null}
        </div>
      </div>

      {/* Next-race accent: thin red rule across the top of the slab */}
      {isNext ? <div style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 4, background: COLORS.red, zIndex: 2 }}></div> : null}
    </div>
  );
}

// Narrow spacer column marking the mid-season break
function PosterBreak() {
  return (
    <div style={{ width: 34, height: '100%', boxSizing: 'border-box', flexShrink: 0, borderRight: '1px solid ' + COLORS.hairline, background: '#050506', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ writingMode: 'vertical-rl', fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.34em', textTransform: 'uppercase', color: '#55555C', whiteSpace: 'nowrap' }}>
        MID-SEASON BREAK
      </div>
    </div>
  );
}

// The full 1920×1080 poster
function URCalendarPoster({ season, showLaps, sharedInfo, intensity, highlight = true, logoPlacement = 'left' }) {
  const cal = getCalendar('ul', season);
  const times = (typeof UR2D_CALENDAR !== 'undefined' && UR2D_CALENDAR.times) || { ul: '17:50', hl: '16:10', jl: '15:15', al: '14:30' };
  const breakAfter = cal.midSeasonBreakAfter;

  const logoRow = (
    <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
      {LEAGUES.map((L) => (
        <div key={L.id} style={{ height: 48, width: 56, 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>
  );
  const divider = <div style={{ width: 1, height: 60, background: COLORS.hairline, flexShrink: 0 }}></div>;

  return (
    <div data-screen-label={'Calendar Poster ' + cal.season} style={{ width: 1920, height: 1080, 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', display: 'flex', flexDirection: 'column', overflow: 'hidden', fontFamily: 'Archivo, sans-serif' }}>
      {/* HEADER */}
      <div style={{ height: 128, flexShrink: 0, display: 'flex', alignItems: 'center', gap: 24, padding: '0 44px', borderBottom: '1px solid ' + COLORS.hairline }}>
        {logoPlacement === 'left' ? (<React.Fragment>{logoRow}{divider}</React.Fragment>) : null}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ fontFamily: 'JetBrains Mono', fontSize: 15, fontWeight: 700, letterSpacing: '0.32em', textTransform: 'uppercase', color: COLORS.red }}>
            {cal.seasonPeriod} Season
          </div>
          <div style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 68, letterSpacing: '-0.03em', textTransform: 'uppercase', color: COLORS.text, lineHeight: 0.9 }}>
            Race Calendar
          </div>
        </div>
        {logoPlacement === 'right' ? (<React.Fragment>{divider}{logoRow}</React.Fragment>) : null}
        <div style={{ flex: 1 }}></div>
        <div style={{ flex: 1 }}></div>
        <div style={{ fontFamily: 'JetBrains Mono', fontSize: 14, letterSpacing: '0.26em', textTransform: 'uppercase', color: '#8A8A92' }}>
          Season {cal.season.replace(/^S/, '')} · {cal.races.length} Rounds
        </div>
      </div>

      {/* SLAB ROW */}
      <div style={{ flex: 1, minHeight: 0, display: 'flex', borderLeft: '1px solid ' + COLORS.hairline }}>
        {cal.races.map((race, i) => (
          <React.Fragment key={race.round}>
            <PosterSlab race={race} intensity={intensity} showLaps={showLaps} showTime={sharedInfo === 'columns'} highlight={highlight}></PosterSlab>
            {breakAfter && race.round === breakAfter ? <PosterBreak></PosterBreak> : null}
          </React.Fragment>
        ))}
      </div>

      {/* SHARED-INFO STRIP (blended: data common to every round, stated once) */}
      {sharedInfo === 'strip' ? (
        <div style={{ height: 58, flexShrink: 0, display: 'flex', alignItems: 'center', gap: 34, padding: '0 44px', borderTop: '1px solid ' + COLORS.hairline, background: '#050506' }}>
          <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', gap: 26 }}>
            {[['AL', times.al], ['JL', times.jl], ['HL', times.hl], ['UL', times.ul]].map(([lg, t]) => (
              <div key={lg} style={{ fontFamily: 'JetBrains Mono', fontSize: 12, letterSpacing: '0.14em', color: '#B8B8C0' }}>
                <span style={{ color: COLORS.text, fontWeight: 700 }}>{lg}</span> {t}
              </div>
            ))}
            <div style={{ fontFamily: 'JetBrains Mono', fontSize: 12, letterSpacing: '0.14em', color: '#8A8A92' }}>UTC</div>
          </div>
          <div style={{ flex: 1 }}></div>
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { URCalendarPoster, PosterSlab, PosterBreak, POSTER_GP_ISO });
