// UR2D Final — TEAMS.
//   · FDTeamsLanding — every team on the CURRENT grid (roster), laid out like the Home "Grid" wall.
//     Every tile opens that team's page. Wrapped by FDBackdrop (Home's checker-flag texture) in ur2d-final.jsx.
//   · FDTeamPage — route #team/<league>/<CODE>: real profile (ur2d-final-teamdata.jsx) → TPTeamPage.
//     Teams with no results on record yet (e.g. new teams) get FDTFresh instead.
// Load order: after ur2d-final-teamdata.jsx, before ur2d-final.jsx.

const fdtCss = `
.fdt-page{padding:64px 44px 110px;min-height:calc(100vh - 72px)}
.fdt-walls{border-bottom:1px solid ${COLORS.hairline}}
.fdt-wall{border-top:1px solid ${COLORS.hairline}}
.fdt-lg{display:flex;align-items:center;gap:14px;padding:28px 0 22px}
.fdt-lg img{height:40px;width:auto;max-width:66px;object-fit:contain;display:block;flex-shrink:0}
.fdt-lgn{font-family:'Archivo',sans-serif;font-weight:800;font-size:15px;letter-spacing:.06em;text-transform:uppercase;color:${COLORS.text}}
.fdt-mono{font-family:'JetBrains Mono',monospace;font-size:12px;letter-spacing:.22em;text-transform:uppercase}
.fdt-logos{--cols:9;display:grid;grid-template-columns:repeat(var(--cols),minmax(0,1fr));overflow:hidden;border-top:1px dashed ${COLORS.hairline}}
.fdt-team{all:unset;box-sizing:border-box;cursor:pointer;position:relative;display:flex;flex-direction:column;align-items:center;gap:9px;padding:30px 8px 26px;min-width:0;text-align:center;box-shadow:-1px 0 0 ${COLORS.hairline},0 -1px 0 ${COLORS.hairline};transition:background .2s ease}
.fdt-team::after{content:'';position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tc);transform:scaleX(0);transform-origin:left;transition:transform .25s ease}
.fdt-team:hover,.fdt-team:focus-visible{background:rgba(255,255,255,.035)}
.fdt-team:hover::after,.fdt-team:focus-visible::after{transform:scaleX(1)}
.fdt-mark{--lg:clamp(40px,5.6vw,84px);height:var(--lg);width:100%;display:flex;align-items:center;justify-content:center;margin-bottom:8px}
.fdt-mark img{height:var(--lg);width:var(--lg);max-width:100%;object-fit:contain;opacity:.86;transition:opacity .2s ease,transform .2s ease}
.fdt-team:hover .fdt-mark img{opacity:1;transform:translateY(-3px)}
.fdt-mark{position:relative}
.fdt-mark img.fdt-liv{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;opacity:0;transform:translateX(-12px) scale(.96);transition:opacity .25s ease,transform .35s cubic-bezier(.2,.7,.2,1);pointer-events:none;filter:drop-shadow(0 8px 14px rgba(0,0,0,.55))}
.fdt-team:hover .fdt-mark img.fdt-liv,.fdt-team:focus-visible .fdt-mark img.fdt-liv{opacity:1;transform:none}
.fdt-team.has-liv:hover .fdt-mark img:not(.fdt-liv),.fdt-team.has-liv:focus-visible .fdt-mark img:not(.fdt-liv),.fdt-team.has-liv:hover .fdt-ph,.fdt-team.has-liv:focus-visible .fdt-ph{opacity:0}
.fdt-ph{display:flex;align-items:center;justify-content:center;width:var(--lg);height:var(--lg);max-width:100%;border:1px dashed rgba(255,255,255,.28);font-family:'Archivo',sans-serif;font-weight:900;font-stretch:62%;font-size:clamp(16px,2vw,30px);letter-spacing:.02em;color:${COLORS.text};transition:transform .2s ease,border-color .2s ease}
.fdt-team:hover .fdt-ph{transform:translateY(-3px);border-color:var(--tc)}
.fdt-mark svg.fdt-fm{height:var(--lg);width:var(--lg);max-width:100%;display:block;transition:opacity .2s ease,transform .2s ease;filter:drop-shadow(0 6px 14px rgba(0,0,0,.45))}
.fdt-team:hover .fdt-mark svg.fdt-fm{transform:translateY(-3px)}
.fdt-team.has-liv:hover .fdt-mark svg.fdt-fm,.fdt-team.has-liv:focus-visible .fdt-mark svg.fdt-fm{opacity:0}
.fdt-code{color:${COLORS.textMute};letter-spacing:.14em;transition:color .2s ease}
.fdt-team:hover .fdt-code{color:${COLORS.text}}
.fdt-name{font-family:'Archivo',sans-serif;font-weight:700;font-size:clamp(10.5px,.95vw,13px);overflow-wrap:anywhere;line-height:1.25;letter-spacing:.03em;text-transform:uppercase;color:${COLORS.text};text-wrap:balance}
.fdt-drv{font-family:'Archivo',sans-serif;font-size:12px;line-height:1.4;color:${COLORS.textMute};text-wrap:balance}
@media (max-width:1180px){.fdt-logos{--cols:5}}@media (max-width:560px){.fdt-logos{--cols:3}}
.fdt-solo{display:flex;align-items:center;padding:0 0 28px;color:${COLORS.textDim}}
.fdt-tabs{display:flex;gap:30px;margin:6px 0 24px;border-bottom:1px solid ${COLORS.hairline}}
.fdt-tab{all:unset;cursor:pointer;font-family:'JetBrains Mono',monospace;font-size:12px;letter-spacing:.22em;text-transform:uppercase;color:${COLORS.textMute};padding:0 0 12px;margin-bottom:-1px;border-bottom:2px solid transparent;transition:color .2s ease}
.fdt-tab:hover,.fdt-tab:focus-visible{color:${COLORS.text}}
.fdt-tab[aria-selected="true"]{color:${COLORS.text};border-bottom-color:${COLORS.red}}
.fdt-span{font-family:'JetBrains Mono',monospace;font-size:10.5px;line-height:1.5;letter-spacing:.08em;text-transform:uppercase;color:${COLORS.textMute}}
.fdt-ttl{font-family:'JetBrains Mono',monospace;font-size:10.5px;letter-spacing:.12em;text-transform:uppercase;color:#F0C53C}
@media (max-width:980px){.fdt-page{padding:48px 22px 80px}.fdt-lg{padding:24px 0 18px}}
`;

const FDTMark = ({ short, src, color }) => {
  const [bad, setBad] = React.useState(!src);
  React.useEffect(() => setBad(!src), [src]);
  return bad ? <URFranchiseMark className="fdt-fm" code={short} color={color} /> : <img src={src} alt="" loading="lazy" onError={() => setBad(true)} />;
};

const FDTWallRow = ({ L, go, showDrivers }) => {
  const sid = fdtCurrentSid(L.id);
  const teamBased = !UR2D_ADAPTERS[L.id] || UR2D_ADAPTERS[L.id].teamBased !== false;
  const { ready } = useFdtTeamOrder(L.id);
  const teams = React.useMemo(() => (teamBased ? fdtCurrentTeams(L.id).map((t) => ({ ...t, livery: fdtIdentity(L.id, t.short).livery })) : []), [L.id, teamBased, ready]);
  const open = (t) => go('team/' + L.id + '/' + encodeURIComponent(t.short));
  const warm = (t) => { fdtLoadProfile(L.id, t.short); };
  React.useEffect(() => { // idle-warm the shared DB lookups + this league's Mega compare before any tile is clicked
    if (!teamBased) return;
    const ric = window.requestIdleCallback || ((f) => setTimeout(f, 400));
    ric(() => fdtWarmShared([L.id]));
  }, [L.id, teamBased]);
  return (
    <div className="fdt-wall" data-league={L.id}>
      <div className="fdt-lg">
        <img src={L.logo} alt="" />
        <div style={{ minWidth: 0 }}>
          <div className="fdt-lgn">{L.name}</div>
          <div className="fdt-mono" style={{ color: L.accent, marginTop: 7 }}>{teams.length ? `${teams.length} teams` : teamBased ? 'TBA' : 'Solo drivers'}{sid ? ' · ' + sid : ''}</div>
        </div>
      </div>
      {!teams.length ?
        <div className="fdt-solo fdt-mono">{teamBased ? 'Lineups not announced yet.' : 'No constructors — every driver races for themselves.'}</div> :
        <div className="fdt-logos" style={{ visibility: ready ? 'visible' : 'hidden' }}>
          {teams.map((t) =>
            <button key={t.short} className={'fdt-team' + (t.livery ? ' has-liv' : '')} data-team={t.short} style={{ '--tc': t.color || COLORS.red }} title={`${t.name} — open team page`}
              onClick={() => open(t)} onMouseEnter={() => warm(t)} onFocus={() => warm(t)} onTouchStart={() => warm(t)}>
              <span className="fdt-mark"><FDTMark short={t.short} src={t.logo} color={t.color} />{t.livery && <img className="fdt-liv" src={t.livery} alt="" loading="lazy" decoding="async" />}</span>
              <span className="fdt-mono fdt-code">{t.short}</span>
              {t.name !== t.short && <span className="fdt-name">{t.name}</span>}
              {showDrivers && t.drivers.length > 0 && <span className="fdt-drv">{t.drivers.join(' · ')}</span>}
            </button>)}
        </div>}
    </div>);
};

// Historic tab: every former team (not on any league's current grid) from the results DB, all leagues mixed, ranked by
// constructors' titles top league first (fdtFormerTeams). Every tile opens #team/old/<DB id> (full DB history page).
// Logos only where the code isn't shared by two teams; hover shows the newest archived car, like the current grid.
const FDTHistoric = ({ go }) => {
  const { status, teams: former } = useFdtFormer();
  const TIERS = ['UL', 'CL', 'JL', 'AL'];
  const titlesIn = (t, lg) => t.titles.filter((x) => x.startsWith(lg + ' ')).length;
  const tiles = React.useMemo(() => former.map((t) => ({ t, id: fdtOldIdentity(t) })), [former]);
  const warm = (t) => { fdtLoadProfile('old', String(t.id)); };
  const titleLabel = (t) => { const lg = TIERS.find((l) => titlesIn(t, l)); return lg ? `${titlesIn(t, lg)} ${lg} title${titlesIn(t, lg) > 1 ? 's' : ''}` : null; };
  const winsLabel = (t) => { const lg = TIERS.find((l) => (t.winsBy || {})[l]); return lg ? `${t.winsBy[lg]} ${lg} win${t.winsBy[lg] > 1 ? 's' : ''}` : 'No wins'; };
  const span = (t) => `${t.first.lg} ${t.first.label}${t.seasons > 1 ? ` → ${t.last.lg === t.first.lg ? '' : t.last.lg + ' '}${t.last.label}` : ''}`;
  if (status !== 'ready') return <div className="fdt-solo fdt-mono">{status === 'error' ? 'The results archive is unreachable right now.' : 'Loading the archive…'}</div>;
  return (
    <div className="fdt-walls">
      <div className="fdt-wall">
        <div className="fdt-lg"><div className="fdt-mono" style={{ color: COLORS.red }}>{former.length} former teams · by titles, top league first</div></div>
        <div className="fdt-logos">
          {tiles.map(({ t, id }) =>
            <button key={t.id} className={'fdt-team' + (id.livery ? ' has-liv' : '')} data-team={t.code} style={{ '--tc': id.color }} title={`${t.name} — ${t.seasons} season${t.seasons > 1 ? 's' : ''} (${t.leagues.join(', ')})${t.titles.length ? ' · champions ' + t.titles.join(', ') : ''} — open team page`}
              onClick={() => go('team/old/' + t.id)} onMouseEnter={() => warm(t)} onFocus={() => warm(t)} onTouchStart={() => warm(t)}>
              <span className="fdt-mark"><FDTMark short={t.code} src={id.logo} color={id.color} />{id.livery && <img className="fdt-liv" src={id.livery} alt="" loading="lazy" decoding="async" />}</span>
              <span className="fdt-mono fdt-code">{t.code}</span>
              <span className="fdt-name">{t.name}</span>
              <span className="fdt-span">{span(t)}<br />{t.seasons} season{t.seasons > 1 ? 's' : ''} · {titleLabel(t) || winsLabel(t)}</span>
              {t.titles.length > 0 && <span className="fdt-ttl">{t.titles.length > 1 ? t.titles.length + '× ' : ''}Champions</span>}
            </button>)}
        </div>
      </div>
    </div>);
};

// Landing tab survives a round trip through a team page ("← All teams" returns to the tab you came from).
const FDT_TAB_KEY = 'ur2d-teams-tab';
const fdtGetTab = () => { try { return sessionStorage.getItem(FDT_TAB_KEY) === 'historic' ? 'historic' : 'current'; } catch (e) { return 'current'; } };
const fdtSetTab = (v) => { try { sessionStorage.setItem(FDT_TAB_KEY, v); } catch (e) {} };

const FDTeamsLanding = ({ go, showDrivers = false }) => {
  const cur = getCalendarSeasons().find((s) => s.isCurrent);
  const [tab, setTabState] = React.useState(fdtGetTab);
  const setTab = (k) => { setTabState(k); fdtSetTab(k); };
  return (
    <section className="fdt-page" data-screen-label="Final — Teams">
      <style>{fdtCss}</style>
      <UR2SectionHead
        kicker={`Teams${cur && cur.period ? ' · ' + cur.period : ''}`}
        title={<span>Pick a <span style={{ color: COLORS.red }}>team.</span></span>}
        right={<div style={{ maxWidth: 360, color: COLORS.textMute, fontSize: 15, lineHeight: 1.55 }}>{tab === 'current' ? 'Every constructor on the current grid, league by league. Open one for its drivers, results and trophies.' : 'Every team that has raced in UR2D but isn’t on a grid today, all leagues together, ranked by championships in the top leagues.'}</div>} />
      <div className="fdt-tabs" role="tablist">
        {[['current', 'Current grid'], ['historic', 'Historic']].map(([k, label]) =>
          <button key={k} className="fdt-tab" role="tab" aria-selected={tab === k ? 'true' : 'false'} onClick={() => setTab(k)}>{label}</button>)}
      </div>
      {tab === 'current' ?
        <div className="fdt-walls">{LEAGUES.map((L) => <FDTWallRow key={L.id} L={L} go={go} showDrivers={showDrivers} />)}</div> :
        <FDTHistoric go={go} />}
    </section>);
};

// ─── TEAM PAGE ROUTE ─────────────────────────────────────────────────────────
const fdtPageCss = `
/* No motion when moving between teams / seasons (final site) */
.tp-root.embed .tp-clogo,.tp-root.embed .tp-cine .tp-name>span,.tp-root.embed .tp-ccar,.tp-root.embed .tp-part,.tp-root.embed .tp-hist i,.tp-root.embed .tp-sbx .bar i,.tp-root.embed .tp-mx .bars i{animation:none!important}
.fdt-crumbw{border-bottom:1px solid var(--line)}
/* Hero: identity block (logo · kicker · name) and the car sit on one level — the spacer row spans both columns (user 2026-10-09) */
@media (min-width:901px){.tp-root.embed .tp-ctop,.tp-root.embed .tp-cine:has(.tp-reign) .tp-ctop{grid-template-areas:"sp sp" "logo car" "kick car" "name car"!important}}
/* Checkered-flag texture behind the whole team page (Home's sticky layer; Tweak "Flag texture on team pages") */
.fdt-tex{position:sticky;top:0;height:100vh;margin-bottom:-100vh;z-index:0;pointer-events:none;background:url("assets/textures/checker-flag.jpg") center/cover;will-change:transform}
.fdt-texc{position:relative;z-index:1}
.fdt-page.tex .tp-root.embed{background:transparent}
.fdt-page.tex .tp-root.embed.fdt-crumbw{background:#070707}
.fdt-page.tex .tp-root .tp-cbg,.fdt-page.tex .tp-root .tp-poster{background-color:transparent}
.fdt-page.tex .tp-root .tp-cbg:after{background:linear-gradient(transparent,rgba(6,6,6,.55) 92%)}
.fdt-load .nm{line-height:1;text-wrap:balance;max-width:min(900px,90vw)}
.fdt-page{position:relative}
.fdt-crumb{display:flex;align-items:center;gap:12px;min-height:46px;flex-wrap:wrap;font-family:'JetBrains Mono',monospace;font-size:11px;letter-spacing:.16em;text-transform:uppercase;color:var(--mute)}
.fdt-crumb>button{all:unset;cursor:pointer;color:var(--ink);transition:color .2s}
.fdt-crumb>button:hover{color:var(--tc)}
.fdt-crumb{padding-top:8px;padding-bottom:8px}
.fdt-crumb .slot{margin-left:auto;display:flex;align-items:center}
.tp-root .fdt-crumb .tp-ctx,.tp-root .fdt-crumb .tp-ctx.inl{position:relative;top:auto;right:auto;left:auto;margin:0;padding:0;max-width:none;text-transform:none;letter-spacing:normal}
.fdt-crumb .sep{color:var(--dim)}
.fdt-crumb b{font-weight:500;color:var(--ink)}
.tp-root .tp-logoph{display:flex;align-items:center;justify-content:center;width:clamp(84px,9vw,132px);height:clamp(84px,9vw,132px);border:1px dashed var(--line2);font-weight:900;font-stretch:62%;font-size:clamp(28px,3.2vw,46px);letter-spacing:.02em;color:var(--ink)}
.tp-root .tp-popm .ph,.tp-root .tp-ddm .ph,.tp-root .tp-hvt .ph{display:flex;align-items:center;justify-content:center;width:28px;height:28px;border:1px dashed var(--line2);font-size:8px;letter-spacing:.04em}
.fdt-fmbig{width:clamp(84px,9vw,132px);height:clamp(84px,9vw,132px);display:block;filter:drop-shadow(0 0 30px color-mix(in oklab,var(--tc) 45%,transparent))}
.fdt-load{min-height:64vh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;text-align:center;padding:60px 24px}
.fdt-load img{height:96px;width:auto;max-width:180px;object-fit:contain}
.fdt-load .nm{font-weight:800;font-stretch:64%;font-size:clamp(34px,4vw,56px);line-height:.9;text-transform:uppercase}
.fdt-load .bar{position:relative;width:180px;height:2px;background:var(--line);overflow:hidden}
.fdt-load .bar i{position:absolute;top:0;bottom:0;left:0;width:40%;background:var(--tc);animation:fdtSweep 1.1s cubic-bezier(.6,0,.4,1) infinite}
@keyframes fdtSweep{from{transform:translateX(-100%)}to{transform:translateX(250%)}}
.fdt-fresh{position:relative;overflow:hidden;padding:clamp(40px,6vw,88px) 0 clamp(56px,7vw,104px);background:radial-gradient(70% 90% at 0% 0%,color-mix(in oklab,var(--tc) 22%,transparent),transparent 70%)}
.fdt-fgrid{display:grid;grid-template-columns:minmax(0,1.05fr) minmax(0,1fr);gap:var(--pad);align-items:center}
.fdt-flogo{height:clamp(84px,9vw,132px);width:auto;max-width:220px;object-fit:contain;filter:drop-shadow(0 0 30px color-mix(in oklab,var(--tc) 55%,transparent))}
.fdt-fkick{display:block;color:var(--mute);margin:clamp(18px,2vw,28px) 0 14px}.fdt-fkick b{color:var(--tc);font-weight:500}
.fdt-fname{margin:0;font-stretch:64%;font-weight:800;text-transform:uppercase;font-size:clamp(52px,7.6vw,128px);line-height:.82}
.fdt-fname span{display:block}
.fdt-fcar img{width:100%;max-width:600px;height:auto;margin-left:auto;filter:drop-shadow(0 26px 40px rgba(0,0,0,.6))}
.fdt-fband{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:28px 40px;margin-top:clamp(40px,5vw,72px);padding-top:28px;border-top:1px solid var(--line)}
.fdt-fband .k{display:block;color:var(--dim);margin-bottom:12px}
.fdt-fband b{display:block;font-weight:800;font-size:20px;line-height:1.2}
.fdt-fband i{display:block;font-style:normal;color:var(--mute);margin-top:6px}
.fdt-flu{display:grid;gap:10px}.fdt-flu span{display:flex;align-items:center;gap:10px;font-weight:800;font-size:20px}
.fdt-flu em{font-style:normal;font-family:'JetBrains Mono',monospace;font-size:12px;color:var(--tc);min-width:30px}
.fdt-fnote{margin:40px 0 0;color:var(--mute);display:flex;align-items:center;gap:16px;flex-wrap:wrap}
.fdt-fnote button{all:unset;cursor:pointer;color:var(--ink);border-bottom:1px solid var(--tc);padding-bottom:2px}
.fdt-page.old .tp-tmrow{max-width:min(620px,58vw);overflow-x:auto;scrollbar-width:none}.fdt-page.old .tp-tmrow::-webkit-scrollbar{display:none}
.fdt-page.old .tp-tmrow a{flex-shrink:0}
@media (max-width:900px){.fdt-fgrid{grid-template-columns:1fr}.fdt-fcar img{margin:0}}
`;

const FDTLoading = ({ id }) =>
  <div className="fdt-load" aria-live="polite">
    {id && (id.logo ? <img src={id.logo} alt="" /> : <URFranchiseMark className="fdt-fmbig" code={id.short} color={id.color} title={id.name} />)}
    {id && <div className="nm">{id.name}</div>}
    <span className="bar"><i></i></span>
    <span className="mono" style={{ color: 'var(--mute)' }}>{!id || id.old ? 'Loading results from the archive' : 'Loading results from the league sheets'}</span>
  </div>;

// No results on record yet (new team) — or the sheets couldn't be reached.
const FDTFresh = ({ id, failed, retry }) => {
  const L = LEAGUE_BY_ID[id.league], tr = id.roster;
  const nm = (p) => fdtPersonName(p);
  const flag = (p) => p ? <img className="tp-flag" src={urFlagImg(p.country || 'un')} alt="" /> : null;
  const cal = getCalendar(id.league), opener = cal && cal.races ? cal.races[id.suffix === 'B' ? 5 : 0] : null;
  return (
    <section className="fdt-fresh" data-screen-label={`Team ${id.short} — no results yet`}>
      <div className="tp-wrap fdt-fgrid">
        <div>
          {id.logo ? <img className="fdt-flogo" src={id.logo} alt={id.name + ' logo'} /> : <URFranchiseMark className="fdt-fmbig" code={id.short} color={id.color} title={id.name} />}
          <span className="mono fdt-fkick">{L ? L.name : ''}{id.sid ? ' · ' + id.sid : ''} · <b>{failed ? 'Results unavailable' : 'No results yet'}</b></span>
          <h1 className="fdt-fname"><span>{id.lines[0]}</span>{id.lines[1] && <span>{id.lines[1]}</span>}</h1>
        </div>
        <div className="fdt-fcar">{id.livery && <img src={id.livery} alt={`${id.name} ${id.sid || ''} livery`} />}</div>
      </div>
      <div className="tp-wrap">
        <div className="fdt-fband">
          {tr && tr.mains.length > 0 && <div><span className="mono k">Lineup · {id.sid}</span><div className="fdt-flu">{tr.mains.filter(Boolean).map((p) => <span key={p.handle}><em>{p.carNumber != null ? '#' + p.carNumber : '—'}</em>{flag(p)}{nm(p)}</span>)}</div></div>}
          {tr && tr.reserve && <div><span className="mono k">Reserve</span><div className="fdt-flu"><span><em>{tr.reserve.carNumber != null ? '#' + tr.reserve.carNumber : '—'}</em>{flag(tr.reserve)}{nm(tr.reserve)}</span></div></div>}
          {tr && tr.owners.length > 0 && <div><span className="mono k">{tr.owners.length > 1 ? 'Owners' : 'Owner'}</span><b>{tr.owners.map(nm).join(' · ')}</b>{tr.principal && <i className="mono">Principal · {nm(tr.principal)}</i>}</div>}
          {id.livery && <div><span className="mono k">Livery</span><b>{id.lname || `${id.short}-${String(id.sid || '').replace(/^S/, '')}`}</b></div>}
          {opener && <div><span className="mono k">Season opener</span><b>R{opener.round} · {opener.track}</b><i className="mono">{opener.localDate}</i></div>}
        </div>
        <p className="mono fdt-fnote">
          {failed ? "Couldn't reach the league sheets." : "Results, trophies and stats fill in here once this team's first race is in the league sheets."}
          {failed && <button onClick={retry}>Try again</button>}
        </p>
      </div>
    </section>);
};

// league 'old' = a former team (Historic tab): short is its DB team id, everything comes from the results DB.
const FDTeamPage = ({ league, short, go, tp }) => {
  const old = league === 'old', L = old ? null : LEAGUE_BY_ID[league], k = league + ':' + short;
  useFdtTeamOrder(league); // switcher lists teams in last season's constructors' order
  const oe = useFdtOldEntry(old, short);
  const id = React.useMemo(() => (old ? (oe.t ? fdtOldIdentity(oe.t) : null) : L && short ? fdtIdentity(league, short) : null), [k, oe.t]);
  const [prof, setProf] = React.useState(() => fdtProfileReady[k] || null);
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    if (!id) return;
    if (fdtProfileReady[k]) { setProf(fdtProfileReady[k]); return; }
    let alive = true;
    setProf(null);
    fdtLoadProfile(league, short).then((p) => { if (alive) setProf(p); });
    return () => { alive = false; };
  }, [k, tick, !!id]);
  // Warm the league's other teams so switching between them is instant.
  React.useEffect(() => { if (!old && prof && !prof.fresh) fdtCurrentTeams(league).forEach((t) => { if (t.short !== short) fdtLoadProfile(league, t.short); }); }, [prof]);
  const back = () => { fdtSetTab(old ? 'historic' : 'current'); go('teamdrv'); };
  return (
    <div data-screen-label={`Final — Team ${(id && id.short) || short || ''}`} className={'fdt-page' + (old ? ' old' : '') + (tp && tp.texture ? ' tex' : '')} style={{ background: '#070707', minHeight: '60vh', '--tc': (id && id.color) || COLORS.red }}>
      <style>{fdtPageCss}</style>
      {tp && tp.texture && <div className="fdt-tex" aria-hidden="true" style={{ opacity: tp.texOpacity != null ? tp.texOpacity : 0.05 }}></div>}
      <div className="fdt-texc">
      <div className="tp-root embed fdt-crumbw" style={{ '--tc': (id && id.color) || COLORS.red }}>
        <div className="tp-wrap fdt-crumb">
          <button onClick={back}>← All teams</button>
          {(L || old) && <React.Fragment><span className="sep">/</span><span>{L ? L.name : 'Historic'}</span></React.Fragment>}
          {id && <React.Fragment><span className="sep">/</span><b>{id.name}</b></React.Fragment>}
          <span className="slot" id="fdt-switch-slot"></span>
        </div>
      </div>
      {!id && old && oe.st === 'loading' ?
        <div className="tp-root embed"><FDTLoading id={null} /></div> :
      !id ?
        <div className="tp-root embed"><div className="fdt-load"><div className="nm">{oe.st === 'error' ? 'Archive unreachable' : 'Team not found'}</div><button className="mono" onClick={back} style={{ color: 'var(--ink)' }}>← All teams</button></div></div> :
      !prof ?
        <div className="tp-root embed" style={{ '--tc': id.color }}><FDTLoading id={id} /></div> :
      prof.fresh ?
        <div className="tp-root embed" style={{ '--tc': id.color }}><FDTFresh id={id} failed={prof.failed} retry={() => setTick((x) => x + 1)} /></div> :
        <TPTeamPage embed t={{ ...tp, team: 'real:' + k }} />}
      </div>
    </div>);
};

Object.assign(window, { FDTeamsLanding, FDTeamPage, FDTMark, fdtCss, fdtPageCss });
