// 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>);
};

const FDTeamWall = ({ go, setLeague }) =>
  <section data-screen-label="Final — Team wall" style={{ padding: '48px 44px 48px' }}>
    <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>} />
    <div style={{ borderBottom: `1px solid ${COLORS.hairline}` }}>
      {LEAGUES.map((L) => <FDWallRow key={L.id} id={L.id} go={go} setLeague={setLeague} />)}
    </div>
  </section>;

// ─── JOIN — how a newcomer gets on the grid ──────────────────────────────────
const FD_STEAM = 'https://store.steampowered.com/search/?term=Ultimate+Racing+2D+2';
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 });
