// UR2D Final — Home "newcomer" sections: what UR2D is + the four leagues (staircase),
// the team logo wall (live team lists per league), and the join block.
// Load order: after ur2d-home2-sections.jsx (UR2SectionHead), before ur2d-final.jsx.

const FD_LG_ROUNDS = { al: 5, jl: 5, hl: 10, ul: 10 };
const FD_CLIMB = ['al', 'jl', 'hl', 'ul']; // beginner → top, left → right

const fdHomeCss = `
.fdh-stairs{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));align-items:end;border-bottom:1px solid ${COLORS.hairline}}
.fdh-step{display:flex;flex-direction:column;gap:16px;padding:24px 24px 24px;border-left:1px solid ${COLORS.hairline};min-width:0}
.fdh-step:first-child{border-left:0;padding-left:0}
.fdh-wall{display:grid;grid-template-columns:220px minmax(0,1fr);gap:0 28px;border-top:1px solid ${COLORS.hairline}}
.fdh-logos{--cols:9;display:grid;grid-template-columns:repeat(var(--cols),minmax(0,1fr));overflow:hidden}
.fdh-logo{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:22px 6px 16px;box-shadow:-1px 0 0 ${COLORS.hairline},0 -1px 0 ${COLORS.hairline};min-width:0}
.fdh-logo img{--lg:clamp(36px,4.2vw,64px);height:var(--lg);width:var(--lg);max-width:100%;object-fit:contain;opacity:.86;transition:opacity .2s ease,transform .2s ease}
.fdh-logo:hover img{opacity:1;transform:translateY(-3px)}
.fdh-logo span{font-family:'JetBrains Mono',monospace;font-size:clamp(10px,.85vw,12px);letter-spacing:.14em;color:${COLORS.textMute};text-transform:uppercase}
.fdh-logo:hover span{color:${COLORS.text}}
@media (max-width:1180px){.fdh-logos{--cols:5}}
@media (max-width:980px){.fdh-stairs{grid-template-columns:repeat(2,minmax(0,1fr))}.fdh-step{min-height:0!important}.fdh-step:nth-child(3){border-left:0;padding-left:0}.fdh-step:nth-child(n+3){border-top:1px solid ${COLORS.hairline}}.fdh-wall{grid-template-columns:1fr}.fdh-logos{border-top:1px dashed ${COLORS.hairline}}}
@media (max-width:560px){.fdh-logos{--cols:3}}
@media (max-width:560px){.fdh-stairs{grid-template-columns:1fr}.fdh-step{border-left:0!important;padding-left:0}.fdh-step+.fdh-step{border-top:1px solid ${COLORS.hairline}}}
`;

const fdMono = (c = COLORS.textMute, s = 11) => ({ fontFamily: 'JetBrains Mono', fontSize: s, letterSpacing: '0.22em', textTransform: 'uppercase', color: c });
const fdLink = { all: 'unset', cursor: 'pointer', ...fdMono(COLORS.text, 11), borderBottom: `1px solid ${COLORS.red}`, paddingBottom: 4, alignSelf: 'flex-start' };

// ─── WHAT IS UR2D + THE LEAGUES — four steps rising left → right ─────────────
const FDAbout = ({ go, setLeague }) => {
  const times = (typeof UR2D_CALENDAR !== 'undefined' && UR2D_CALENDAR.times) || {};
  return (
    <section data-screen-label="Final — What is UR2D" style={{ padding: '64px 44px 48px' }}>
      <style>{fdHomeCss}</style>
      <UR2SectionHead
        kicker="What is UR2D"
        title={<span>An online racing league<br /><span style={{ color: COLORS.red }}>for Ultimate Racing 2D 2.</span></span>}
        right={<div style={{ maxWidth: 380, color: COLORS.textMute, fontSize: 15, lineHeight: 1.55 }}>Four leagues race the same track every Sunday. Everyone starts in the Apprentice League and climbs through promotion to the Ultimate League.</div>} />
      <div className="fdh-stairs">
        {FD_CLIMB.map((id, i) => {
          const L = LEAGUE_BY_ID[id], tier = (L.tier.split('·')[1] || L.tier).trim();
          return (
            <div key={id} className="fdh-step" style={{ alignSelf: 'stretch', boxShadow: `inset 0 3px 0 ${L.accent}` }}>
              <img src={id === 'ul' ? 'assets/ul-mark.png' : L.logo} alt={L.short} style={{ height: 60, width: 'auto', maxWidth: id === 'ul' ? 'none' : 104, objectFit: 'contain', display: 'block', alignSelf: 'flex-start' }} />
              <div>
                <div style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 'clamp(22px, 2.2vw, 30px)', lineHeight: 0.95, letterSpacing: '-0.01em', textTransform: 'uppercase', color: COLORS.text }}>{id === 'ul' ? <React.Fragment>Ultimate<br></br>League</React.Fragment> : L.name}</div>
                <div style={{ ...fdMono(L.accent, 12), marginTop: 9 }}>{tier}</div>
              </div>
              <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 8 }}>
                <li style={fdMono(COLORS.textMute, 13)}>{FD_LG_ROUNDS[id]} rounds</li>
                {times[id] && <li style={fdMono(COLORS.text, 13)}>Sundays · {times[id]} UTC</li>}
              </ul>
              <button style={{ ...fdLink, fontSize: 12, marginTop: 'auto' }} onClick={() => { setLeague(id); go('standings'); }}>Standings →</button>
            </div>);
        })}
      </div>
    </section>);
};

// ─── TEAM LOGO WALL — live team list per league (AL races without teams) ─────
const FDWallRow = ({ id, go, setLeague }) => {
  const L = LEAGUE_BY_ID[id];
  const data = useStandings(id, defaultDataSeasonId(id));
  // Previous season's constructors' order (champion first) — same order as the Teams landing; hidden until known.
  const { ready } = window.useFdtTeamOrder(id);
  const order = React.useMemo(() => window.fdtCurrentTeams(id).map((t) => t.short), [id, ready]);
  const rank = (s) => { const i = order.indexOf(s); return i < 0 ? Infinity : i; };
  const teams = ready ? (data.teams || []).slice().sort((a, b) => rank(a.short) - rank(b.short) || a.short.localeCompare(b.short)) : [];
  const solo = !data.teams && data.status !== 'loading';
  return (
    <div className="fdh-wall">
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '22px 0' }}>
        <img src={L.logo} alt="" style={{ height: 34, width: 'auto', maxWidth: 58, objectFit: 'contain', display: 'block' }} />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: 'Archivo', fontWeight: 800, fontSize: 15, letterSpacing: '0.06em', textTransform: 'uppercase', color: COLORS.text }}>{L.name}</div>
          <div style={{ ...fdMono(L.accent, 10), marginTop: 6, lineHeight: 1.6 }}>{solo ? 'Solo drivers' : teams.length ? <React.Fragment><span style={{ display: 'block' }}>{teams.length} constructors</span>{data.season && <span style={{ display: 'block' }}>{data.season.label}</span>}</React.Fragment> : 'Loading…'}</div>
        </div>
      </div>
      {solo ?
        <div style={{ display: 'flex', alignItems: 'center', padding: '22px 0', ...fdMono(COLORS.textDim, 11) }}>No constructors — every driver races for themselves.</div> :
        <div className="fdh-logos">
          {teams.map((tm) => {
            const src = (typeof UR_TEAM_LOGO !== 'undefined' && UR_TEAM_LOGO[tm.short]) || `assets/minilogos/${tm.short}.png`;
            return (
              <button key={tm.short} className="fdh-logo" title={tm.name} onClick={() => { setLeague(id); go('team/' + id + '/' + encodeURIComponent(tm.short)); }} onMouseEnter={() => { if (window.fdtLoadProfile) window.fdtLoadProfile(id, tm.short); }}>
                <img src={src} alt={tm.name} loading="lazy" onError={(e) => { e.currentTarget.style.visibility = 'hidden'; }} />
                <span>{tm.short}</span>
              </button>);
          })}
        </div>}
    </div>);
};

// ─── PHONE CAROUSEL (Home Preview only, user 2026-10-11) — ≤640px a row of league blocks becomes a swipe carousel
// with league tabs. on=false (the Final site) renders the plain wrapper, unchanged.
const fdSnapCss = `
.fd-snap-tabs{display:none}
@media (max-width:640px){
.fd-snap{display:flex!important;flex-wrap:nowrap;overflow-x:auto;overscroll-behavior-x:contain;scroll-snap-type:x mandatory;gap:14px!important;margin:0 -44px;padding:0 44px 4px;scroll-padding:0 44px;scrollbar-width:none;border-bottom:0!important;position:relative}
.fd-snap::-webkit-scrollbar{display:none}
.fd-snap>*{flex:0 0 calc(100% - 28px);min-width:0;scroll-snap-align:start;scroll-snap-stop:always}
.fd-snap-tabs{display:flex;gap:6px;margin:0 0 16px}
.fd-snap-tabs button{all:unset;box-sizing:border-box;cursor:pointer;flex:1;display:flex;align-items:center;justify-content:center;min-height:44px;font:800 12px/1 'Archivo',sans-serif;letter-spacing:.16em;text-transform:uppercase;color:${COLORS.textMute};border-bottom:2px solid rgba(255,255,255,.14)}
.fd-snap-tabs button[aria-current="true"]{color:${COLORS.text};border-bottom-color:${COLORS.red}}
.fd-snap-tabs button:focus-visible{outline:2px solid #fff;outline-offset:2px}
.fd-snap .fdh-wall{grid-template-columns:minmax(0,1fr);border:1px solid ${COLORS.hairline};padding:0 16px 10px;background:rgba(8,8,10,.6)}
}`;
if (typeof document !== 'undefined' && !document.getElementById('fd-snap-css')) {
  const s = document.createElement('style'); s.id = 'fd-snap-css'; s.textContent = fdSnapCss; document.head.appendChild(s);
}
const FDSnapRow = ({ on, labels = [], style, className, children }) => {
  const ref = React.useRef(null);
  const [idx, setIdx] = React.useState(0);
  React.useEffect(() => {
    const el = ref.current; if (!on || !el) return;
    let raf = 0;
    const calc = () => {
      raf = 0;
      const kids = Array.from(el.children); if (!kids.length) return;
      if (el.scrollLeft >= el.scrollWidth - el.clientWidth - 4) { setIdx(kids.length - 1); return; }
      const padL = parseFloat(getComputedStyle(el).paddingLeft) || 0;
      let best = 0, bd = Infinity;
      kids.forEach((k, i) => { const d = Math.abs(k.offsetLeft - padL - el.scrollLeft); if (d < bd) { bd = d; best = i; } });
      setIdx(best);
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(calc); };
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => { el.removeEventListener('scroll', onScroll); if (raf) cancelAnimationFrame(raf); };
  }, [on]);
  if (!on) return <div className={className} style={style}>{children}</div>;
  const jump = (i) => {
    const el = ref.current, k = el && el.children[i]; if (!k) return;
    el.scrollTo({ left: k.offsetLeft - (parseFloat(getComputedStyle(el).paddingLeft) || 0), behavior: 'smooth' });
  };
  return (
    <React.Fragment>
      <div className="fd-snap-tabs">{labels.map((l, i) => <button key={l} type="button" aria-current={i === idx} onClick={() => jump(i)}>{l}</button>)}</div>
      <div ref={ref} className={(className ? className + ' ' : '') + 'fd-snap'} style={style}>{children}</div>
    </React.Fragment>);
};

const FDTeamWall = ({ go, setLeague, carousel }) =>
  <section data-screen-label="Final — Team wall" style={{ padding: '48px 44px 48px' }}>
    <style>{fdHomeCss}</style>
    <UR2SectionHead
      kicker="Who races here"
      title={<span>The <span style={{ color: COLORS.red }}>Grid.</span></span>}
      right={<div style={{ maxWidth: 340, color: COLORS.textMute, fontSize: 15, lineHeight: 1.55 }}>Every constructor on the current grid, by league. Open a team for its drivers, results and trophies.</div>} />
    <FDSnapRow on={carousel} labels={LEAGUES.map((L) => L.short)} style={{ borderBottom: `1px solid ${COLORS.hairline}` }}>
      {LEAGUES.map((L) => <FDWallRow key={L.id} id={L.id} go={go} setLeague={setLeague} />)}
    </FDSnapRow>
  </section>;

// ─── JOIN — how a newcomer gets on the grid ──────────────────────────────────
const FD_STEAM = 'https://store.steampowered.com/app/1285230/Ultimate_Racing_2D_2/'; // the store page, not search (review 2026-10-11)
const FDJoin = () =>
  <section data-screen-label="Final — Join" style={{ padding: '48px 44px 80px' }}>
    <UR2SectionHead kicker="Join" title={<span>Want to race?<br /><span style={{ color: COLORS.red }}>Start in Apprentice.</span></span>} />
    <ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', borderTop: `1px solid ${COLORS.hairline}` }}>
      {[['01', 'Get the game', 'Ultimate Racing 2D 2 on Steam.'], ['02', 'Join the Discord', 'Signups, schedules and race control all run there.'], ['03', 'Sign up for Apprentice', 'Race your first season and earn promotion.']].map(([n, h, p]) =>
        <li key={n} style={{ padding: '26px 24px 8px 0', display: 'grid', gap: 10, alignContent: 'start' }}>
          <span style={{ fontFamily: 'Archivo', fontWeight: 900, fontStretch: '62%', fontSize: 'clamp(64px, 6vw, 96px)', lineHeight: 0.8, color: COLORS.red, marginBottom: 8 }}>{n}</span>
          <span style={{ fontFamily: 'Archivo', fontWeight: 900, fontSize: 24, textTransform: 'uppercase', letterSpacing: '-0.01em', color: COLORS.text }}>{h}</span>
          <span style={{ fontFamily: 'Archivo', fontSize: 15, lineHeight: 1.5, color: COLORS.textMute }}>{p}</span>
        </li>)}
    </ol>
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 14, marginTop: 40 }}>
      <a href={URL_LEAGUE.brand.discord} target="_blank" rel="noopener" style={{ padding: '16px 26px', background: COLORS.red, color: '#fff', fontFamily: 'Archivo', fontWeight: 800, fontSize: 13, letterSpacing: '0.2em', textTransform: 'uppercase', textDecoration: 'none' }}>Join the Discord →</a>
      <a href={FD_STEAM} target="_blank" rel="noopener" style={{ padding: '15px 25px', border: `1px solid ${COLORS.hairline}`, color: COLORS.text, fontFamily: 'Archivo', fontWeight: 800, fontSize: 13, letterSpacing: '0.2em', textTransform: 'uppercase', textDecoration: 'none' }}>Find it on Steam ↗</a>
    </div>
  </section>;

// Thin section divider, inset to the content margins
const FDRule = () => <div aria-hidden style={{ height: 1, margin: '0 44px', background: 'rgba(255,255,255,0.09)' }}></div>;

Object.assign(window, { FDAbout, FDTeamWall, FDJoin, FDRule, FDSnapRow });
