/* ГОНКА STING / STING POYGASI — miniapp screens (механика 5-А).
   Built on the STING design system tokens/fonts/assets. Russian + Uzbek.
   Big, simple, one-screen-first. No emoji — line icons + lightning only.
   Replaces the generic loyalty reference. See APP-SPEC.md. */
const A = "/ds/assets/";
const KV_CAR = A + "keyvisuals/kv1-f1-car-9x16.jpg";
const KV_HELMET = A + "keyvisuals/kv3-helmet-9x16.jpg";
const KV_HERO = A + "keyvisuals/kv2-hero-male-9x16.jpg";
const BOTTLE = A + "f1/bottle.png";
const BOLID = A + "f1/bolid.webp";
const HERO = A + "f1/f1-hero.webp";
const F1LOGO = A + "f1/f1-logo.svg";
const VID = A + "f1/bg-video.webm";
const POSTER = A + "f1/bg-poster.webp";
const PRODUCT_BOTTLE = A + "products/bottle-clean.png";
const PATTERN = A + "patterns/sting-pattern-red.svg";

/* ---------- i18n (UZ overrides RU; missing keys fall back to RU) ---------- */
const RU = {
  nav_home:"Главная", nav_team:"Команда", nav_baku:"F1", nav_cab:"Кабинет", nav_scan:"Скан",
  hello:"Привет", points:"очки", toPay:"до выплаты", pay20:"20 000 сум", pay100:"100 000 сум",
  pit_open:"Пит-стоп открыт", pit_sub:"Болид встал — у тебя час", play:"К БОЛИДУ",
  pit_next:"Пит-стоп", pit_done_sub:"Пройден · жди следующий", pit_soon_sub:"Скоро открытие",
  tank:"Бак команды", tank_sub:"Полный бак — и ты в Баку", your_in:"твой вклад",
  scan_tile:"Скан чека", scan_hint:"+билет команде", team_tile:"Команда", team_hint:"позвать своих",
  tickets_tile:"Мои билеты", tickets_hint:"коды в игре", until_baku:"до розыгрыша Баку",
  team_title:"Команда", members:"участники", invite:"ПОЗВАТЬ СВОИХ", need_more:"Добери до 4 — и команда в розыгрыше Баку",
  full:"Команда укомплектована", contribution:"билетов", captain:"капитан", leave:"Выйти из команды",
  baku_title:"Гран-при Баку", until_draw:"до розыгрыша", your_chance:"Чем полнее бак, тем выше шанс",
  schedule:"Расписание", winners:"Уже летят", prize_name:"Поездка на двоих на Гран-при, Баку",
  cab_title:"Кабинет", scans:"сканы", pitstops:"пит-стопы", my_tickets:"Мои билеты",
  pay_card:"Карта для выплат", language:"Язык", rules:"Правила", offer:"Оферта", support:"Поддержка", logout:"Выйти",
  tk_title:"Мои билеты", in_game:"в игре", tk_empty:"Сканируй чек — каждая бутылка даёт билет в бак команды",
  scan_title:"Скан чека", scan_aim:"Наведи на QR-код чека", scan_manual:"Или введи код вручную",
  scan_btn:"ЗАЧЕСТЬ ЧЕК", accepted:"Чек принят", limits:"До 5 бутылок в чеке, до 3 чеков в день",
  pit_ready:"Болид заходит…", pit_work:"Болид встал — работай!", pit_gone:"Болид ушёл!",
  pit_hint:"Тапай по зелёным точкам — работай за всё пит-крю",
  results:"Пит-стоп закрыт", you:"Ты", oc:"оч.", again:"Скан чека", x2:"очки ×2", dots:"точки",
  card_title:"Карта для выплат", card_hint:"20 000 сум придут на карту в ближайшую выплатную пятницу",
  card_btn:"СОХРАНИТЬ", back:"Назад", continue:"Продолжить", level:"Гонщик",
};
const UZ = {
  nav_home:"Asosiy", nav_team:"Jamoa", nav_baku:"F1", nav_cab:"Kabinet", nav_scan:"Skan",
  hello:"Salom", points:"ball", toPay:"toʻlovgacha",
  pit_open:"Pit-stop ochiq", pit_sub:"Bolid turdi — bir soating bor", play:"BOLIDGA",
  pit_next:"Pit-stop", pit_done_sub:"Oʻtilgan · keyingisini kut", pit_soon_sub:"Tez orada ochiladi",
  tank:"Jamoa baki", tank_sub:"Bak toʻla — Baku kutadi", your_in:"sening hissang",
  scan_tile:"Chekni skanlash", team_tile:"Jamoa", tickets_tile:"Mening chiptalarim", until_baku:"Baku qurʼasigacha",
  team_title:"Jamoa", invite:"OʻZINGNIKILARNI CHAQIR", baku_title:"Baku Gran-prisi",
  cab_title:"Kabinet", my_tickets:"Mening chiptalarim", language:"Til", rules:"Qoidalar", offer:"Oferta",
  support:"Yordam", logout:"Chiqish", tk_title:"Mening chiptalarim", in_game:"oʻyinda",
  scan_title:"Chekni skanlash", scan_btn:"CHEKNI HISOBLASH", accepted:"Chek qabul qilindi",
  pit_work:"Bolid turdi — ishla!", results:"Pit-stop yopildi", you:"Sen", again:"Chekni skanlash",
  card_title:"Toʻlov kartasi", card_btn:"SAQLASH", back:"Orqaga", continue:"Davom etish",
};
const L = (lang) => (lang === "uz" ? Object.assign({}, RU, UZ) : RU);

/* ---------- mock data ---------- */
const MY_TICKETS = [
  { code:"STG-8F3K-92", date:"14 июня", bottles:2, shop:"Korzinka" },
  { code:"STG-2Q7M-14", date:"13 июня", bottles:1, shop:"Makro" },
  { code:"STG-9X4D-70", date:"12 июня", bottles:2, shop:"Havas" },
  { code:"STG-5B1J-38", date:"10 июня", bottles:3, shop:"Korzinka" },
];
const TEAM = {
  name:"БОЛИДЫ 211", bak:84,
  members:[
    { name:"Ты", tickets:8, captain:true, you:true },
    { name:"Тимур", tickets:21, captain:false },
    { name:"Азиз", tickets:17, captain:false },
    { name:"Жасур", tickets:14, captain:false },
    { name:"Санжар", tickets:12, captain:false },
    { name:"Дима", tickets:12, captain:false },
  ],
};
const WINNERS = [
  { team:"СКОРОСТЬ", city:"Ташкент" },
  { team:"ПИТ-КРЮ 7", city:"Самарканд" },
];
const SCHEDULE = ["05 июля", "19 июля", "02 августа", "16 августа"];

/* ---------- shared bits ---------- */
function inject(){
  if (document.getElementById("sting-app-css")) return;
  const s = document.createElement("style"); s.id = "sting-app-css";
  s.textContent = `
  .posnode{cursor:pointer}
  .posnode .hit{fill:transparent}
  .posnode .c{fill:var(--ink-700);stroke:#3a0b0e;stroke-width:1.5;transition:.15s}
  .posnode text{fill:var(--text-muted);font-family:var(--font-body);font-weight:700;font-size:11px;text-anchor:middle;pointer-events:none}
  .posnode.active .c{fill:var(--success);stroke:#9dffc4;animation:pn 0.7s ease infinite}
  .posnode.active text{fill:#fff}
  .posnode.done .c{fill:#fff;stroke:#fff;animation:none}
  .posnode.miss .c{fill:#7a0009;stroke:var(--brand);animation:none}
  @keyframes pn{50%{stroke-width:6}}
  .lite{width:17px;height:17px;border-radius:50%;background:#2a0608;border:1px solid #3a0b0e;transition:.1s}
  .lite.on{background:radial-gradient(circle at 40% 35%,#ff6a6a,var(--brand) 60%,#7a0009);box-shadow:0 0 12px 3px var(--brand-glow)}
  .pclock.pen{animation:pf .35s ease}
  @keyframes pf{30%{color:var(--brand)}}
  .tilepress:active{transform:scale(.97)}
  `;
  document.head.appendChild(s);
}

function Eyebrow({ children, color }) {
  return <div style={{ fontFamily:"var(--font-body)", fontSize:11, fontWeight:700, textTransform:"uppercase", letterSpacing:"0.12em", color: color || "var(--text-muted)" }}>{children}</div>;
}
function H1({ children, size }) {
  return <h1 style={{ fontFamily:"var(--font-display)", fontWeight:900, fontSize:size||30, textTransform:"uppercase", letterSpacing:"-0.01em", lineHeight:.95, color:"var(--text-strong)", margin:0 }}>{children}</h1>;
}
function BigButton({ children, onClick, tone, icon }) {
  const gold = tone === "gold";
  return (
    <button onClick={onClick} className="tilepress" style={{
      width:"100%", border:"none", cursor:"pointer", height:58, borderRadius:"var(--r-lg)",
      background: gold ? "var(--grad-gold)" : "var(--grad-red)",
      color: gold ? "#000" : "#fff", boxShadow:"var(--shadow-brand)",
      fontFamily:"var(--font-heading)", fontSize:16, textTransform:"uppercase", letterSpacing:"0.02em",
      display:"flex", alignItems:"center", justifyContent:"center", gap:10, transition:"transform .12s",
    }}>
      {icon && <Icon name={icon} size={20} color={gold ? "#000" : "#fff"} fill={icon==="bolt"?(gold?"#000":"#fff"):"none"} />}
      {children}
    </button>
  );
}

/* big number hero */
function StatHero({ value, label }) {
  return (
    <div style={{ display:"flex", alignItems:"flex-end", gap:10 }}>
      <Icon name="bolt" size={34} color="var(--sting-gold)" fill="var(--sting-gold)" />
      <div style={{ fontFamily:"var(--font-display)", fontWeight:900, fontSize:64, lineHeight:.82, color:"#fff" }}>{value}</div>
      <div style={{ fontFamily:"var(--font-heading)", fontSize:13, textTransform:"uppercase", letterSpacing:"0.1em", color:"rgba(255,255,255,.75)", paddingBottom:8 }}>{label}</div>
    </div>
  );
}
/* progress to payout with two milestones */
function GoalBar({ value }) {
  const goal = value < 100 ? 100 : 600;
  const lbl = value < 100 ? "20 000 сум" : "100 000 сум";
  const pct = Math.min(100, value / goal * 100);
  return (
    <div style={{ marginTop:14 }}>
      <div style={{ display:"flex", justifyContent:"space-between", marginBottom:6, fontFamily:"var(--font-body)", fontSize:12, fontWeight:700 }}>
        <span style={{ color:"rgba(255,255,255,.8)" }}>{value} / {goal} очков</span>
        <span style={{ color:"var(--sting-gold)" }}>{lbl}</span>
      </div>
      <div style={{ height:10, background:"rgba(0,0,0,.35)", borderRadius:"var(--r-pill)", overflow:"hidden" }}>
        <div style={{ width:pct+"%", height:"100%", background:"var(--sting-gold)", borderRadius:"var(--r-pill)" }} />
      </div>
    </div>
  );
}
function TimerPill({ children }) {
  return (
    <div style={{ display:"inline-flex", alignItems:"center", gap:7, background:"rgba(0,0,0,.4)", borderRadius:"var(--r-pill)", padding:"7px 13px" }}>
      <Icon name="clock" size={15} color="var(--text-muted)" />
      <span style={{ fontFamily:"var(--font-heading)", fontSize:13, color:"#fff" }}>{children}</span>
    </div>
  );
}
function Tile({ icon, title, hint, onClick, done }) {
  return (
    <button onClick={onClick} className="tilepress" style={{
      flex:1, border:"1px solid var(--border-subtle)", background:"var(--surface-card)", cursor:"pointer",
      borderRadius:"var(--r-xl)", padding:"16px 14px", textAlign:"left", display:"flex", flexDirection:"column", gap:10, transition:"transform .12s",
    }}>
      <div style={{ width:44, height:44, borderRadius:"var(--r-md)", background: done ? "rgba(24,178,107,.15)" : "rgba(214,35,0,.14)", display:"flex", alignItems:"center", justifyContent:"center" }}>
        <Icon name={done ? "check" : icon} size={24} color={done ? "var(--success)" : "var(--brand)"} />
      </div>
      <div>
        <div style={{ fontFamily:"var(--font-heading)", fontSize:15, color:"var(--text-strong)", textTransform:"uppercase" }}>{title}</div>
        <div style={{ fontFamily:"var(--font-body)", fontSize:12, color:"var(--text-muted)", marginTop:2 }}>{hint}</div>
      </div>
    </button>
  );
}

/* looping muted video backdrop (autoplay) */
function VideoBg({ src, poster, style }) {
  const ref = React.useRef(null);
  React.useEffect(()=>{ const v=ref.current; if(!v) return; v.muted=true; const p=v.play(); if(p&&p.catch) p.catch(()=>{}); },[]);
  return (
    <video ref={ref} autoPlay muted loop playsInline poster={poster}
      style={Object.assign({ position:"absolute", pointerEvents:"none", objectFit:"cover" }, style)}>
      <source src={src} type="video/webm" />
    </video>
  );
}

/* electric bottle — Current: discharge hugs the product contour (DS guidelines/brand-electricity) */
function ElectricBottle({ src, flavour="red", height=340, active=true, style }) {
  const uid = React.useId().replace(/[:]/g,"");
  const red = "var(--sting-red)", dred = "var(--dark-red)";
  const kP = "ebp"+uid, kA1 = "eba1"+uid, kA2 = "eba2"+uid, kA3 = "eba3"+uid, cI = "ebi"+uid, cA = "eba"+uid;
  const baseF = "drop-shadow(0 0 1px #fff) drop-shadow(0 0 3px "+red+") drop-shadow(0 0 6px "+red+")";
  const css =
    "@keyframes "+kP+"{0%,100%{filter:"+baseF+"}50%{filter:drop-shadow(0 0 2px #fff) drop-shadow(0 0 6px "+red+") drop-shadow(0 0 13px "+dred+")}}"
    +"@keyframes "+kA1+"{0%{stroke-dashoffset:320;opacity:0}12%{opacity:1}60%{opacity:1}100%{stroke-dashoffset:0;opacity:0}}"
    +"@keyframes "+kA2+"{0%{stroke-dashoffset:0;opacity:0}15%{opacity:1}65%{opacity:1}100%{stroke-dashoffset:320;opacity:0}}"
    +"@keyframes "+kA3+"{0%{stroke-dashoffset:300;opacity:0}20%{opacity:1}70%{opacity:.9}100%{stroke-dashoffset:-20;opacity:0}}"
    +"."+cI+"{animation:"+kP+" 2.4s var(--ease-out) infinite}"
    +"."+cA+"{fill:none;stroke:#fff;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;filter:drop-shadow(0 0 3px "+red+") drop-shadow(0 0 6px "+red+");stroke-dasharray:60 260}"
    +"@media(prefers-reduced-motion:reduce){."+cI+"{animation:none}."+cA+"{animation:none;opacity:.85}}";
  return (
    <div style={Object.assign({ position:"relative", height:height, aspectRatio:"200 / 340" }, style)}>
      <style>{css}</style>
      <div style={{ position:"absolute", inset:0, display:"flex", alignItems:"center", justifyContent:"center" }}>
        <img className={cI} src={src} alt="STING" style={{ height:"97%", display:"block", filter:baseF }} />
      </div>
      {active && (
        <svg viewBox="0 0 200 340" preserveAspectRatio="none" style={{ position:"absolute", inset:0, width:"100%", height:"100%", overflow:"visible", pointerEvents:"none" }} aria-hidden="true">
          <path className={cA} style={{ animation:kA1+" 2.1s linear infinite" }} d="M70 70 L60 96 L72 104 L58 134 L70 150 L56 188 L68 206 L54 250 L66 270 L58 300" />
          <path className={cA} style={{ animation:kA2+" 1.7s linear infinite .4s" }} d="M138 84 L150 110 L138 122 L152 150 L140 172 L150 210 L138 232 L150 268 L140 292" />
          <path className={cA} style={{ animation:kA3+" 2.6s linear infinite .9s" }} d="M84 60 L74 74 L88 82 L78 100 L92 112" />
        </svg>
      )}
    </div>
  );
}

/* ---------- bottom nav: Главная · Команда · [СКАН] · Баку · Кабинет ---------- */
function BottomNav({ active, onNav, lang }) {
  const l = L(lang);
  const left = [ {id:"home",icon:"home",label:l.nav_home}, {id:"team",icon:"users",label:l.nav_team} ];
  const right = [ {id:"baku",icon:"flag",label:l.nav_baku, f1:true}, {id:"cabinet",icon:"user",label:l.nav_cab} ];
  const item = (it) => {
    const on = active === it.id;
    return (
      <button key={it.id} onClick={()=>onNav(it.id)} style={{ border:"none", background:"transparent", cursor:"pointer", display:"flex", flexDirection:"column", alignItems:"center", gap:4, width:58 }}>
        {it.f1
          ? <img src={F1LOGO} alt="F1" style={{ width:40, height:23, objectFit:"contain", opacity:on?1:.55 }} />
          : <Icon name={it.icon} size={23} color={on ? "var(--brand)" : "var(--text-muted)"} />}
        <span style={{ fontFamily:"var(--font-body)", fontSize:10, fontWeight:700, color:on?"var(--brand)":"var(--text-muted)", textTransform:"uppercase" }}>{it.label}</span>
      </button>
    );
  };
  return (
    <div style={{ flex:"none", display:"flex", alignItems:"flex-end", justifyContent:"space-around", padding:"10px 12px 24px", background:"var(--ink-800)", borderTop:"1px solid var(--border-subtle)" }}>
      {left.map(item)}
      <button onClick={()=>onNav("scan")} className="tilepress" style={{ border:"none", cursor:"pointer", width:64, height:64, marginTop:-28, borderRadius:"50%", background:"var(--grad-red)", boxShadow:"var(--shadow-brand)", display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", gap:1, transition:"transform .12s" }}>
        <Icon name="scan" size={24} color="#fff" />
        <span style={{ fontFamily:"var(--font-heading)", fontSize:8, color:"#fff", textTransform:"uppercase", letterSpacing:"0.05em" }}>{L(lang).nav_scan}</span>
      </button>
      {right.map(item)}
    </div>
  );
}

/* ---------- LOGIN ---------- */
function LoginScreen({ onLogin, lang }) {
  const l = L(lang);
  return (
    <div style={{ flex:1, display:"flex", flexDirection:"column", position:"relative", backgroundImage:`url(${PATTERN})`, backgroundSize:"cover", backgroundPosition:"center", overflow:"hidden" }}>
      <div style={{ position:"absolute", inset:0, background:"var(--grad-scrim)" }} />
      {/* animated electric bottle */}
      <div style={{ position:"relative", flex:1, display:"flex", alignItems:"center", justifyContent:"center", padding:"20px 0 0" }}>
        <ElectricBottle src={PRODUCT_BOTTLE} flavour="red" height={360} />
      </div>
      {/* brand + cta */}
      <div style={{ position:"relative", padding:"0 24px 34px", textAlign:"center" }}>
        <img src={A+"logo/sting-logo-black.svg"} alt="STING" style={{ height:44, marginBottom:8, filter:"drop-shadow(0 6px 16px rgba(0,0,0,.45))" }} />
        <H1 size={42}>{lang==="uz"?"POYGASI":"ГОНКА"}</H1>
        <p style={{ fontFamily:"var(--font-body)", fontSize:14, color:"var(--text-body)", lineHeight:1.45, margin:"12px auto 20px", maxWidth:300 }}>
          {lang==="uz"
            ? "Sting sotib ol, chekni skanla va Bakuga uchish uchun jamoa yigʻ."
            : "Покупай Sting, сканируй чеки, собери команду — деньги на карту и Гран-при в Баку."}
        </p>
        <BigButton onClick={onLogin} icon="chevron">{lang==="uz"?"KIRISH":"ВОЙТИ"}</BigButton>
        <div style={{ marginTop:14, fontFamily:"var(--font-body)", fontSize:10, color:"var(--text-muted)", lineHeight:1.5 }}>Официальный энергетик Formula 1®. Логотип F1 — товарный знак Formula One Licensing BV.</div>
      </div>
    </div>
  );
}

/* ---------- HOME ---------- */
function HomeScreen({ points, tickets, pitOpen, pitPlayed, onNav, onPlay, lang }) {
  const l = L(lang);
  return (
    <div style={{ flex:1, overflowY:"auto", background:"var(--surface-base)" }}>
      {/* header */}
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"4px 20px 12px" }}>
        <div style={{ display:"flex", alignItems:"center", gap:8 }}>
          <div style={{ width:34, height:34, borderRadius:"var(--r-md)", background:"var(--grad-red)", display:"flex", alignItems:"center", justifyContent:"center" }}><Icon name="users" size={18} color="#fff" /></div>
          <div style={{ fontFamily:"var(--font-heading)", fontSize:13, color:"var(--text-strong)", textTransform:"uppercase" }}>{TEAM.name}</div>
        </div>
        <LangToggle lang={lang} onLang={()=>onNav("__lang")} />
      </div>

      {/* hero */}
      <div style={{ padding:"0 16px" }}>
        <div style={{ position:"relative", borderRadius:"var(--r-xl)", overflow:"hidden", background:"var(--grad-kv)", padding:"20px 20px 22px", minHeight:230 }}>
          <VideoBg src={VID} poster={POSTER} style={{ right:"-4%", top:"-8px", width:"72%", height:"auto", maxHeight:"86%", WebkitMaskImage:"radial-gradient(110% 130% at 76% 26%, #000 16%, rgba(0,0,0,0.5) 52%, rgba(0,0,0,0) 90%)", maskImage:"radial-gradient(110% 130% at 76% 26%, #000 16%, rgba(0,0,0,0.5) 52%, rgba(0,0,0,0) 90%)" }} />
          <div style={{ position:"absolute", inset:0, background:"linear-gradient(90deg, var(--brand-dark) 0%, rgba(158,26,14,.62) 24%, rgba(158,26,14,.18) 56%, rgba(158,26,14,0) 100%)", pointerEvents:"none" }} />
          <div style={{ position:"relative" }}>
            <Eyebrow color="rgba(255,255,255,.8)">{l.hello}, Азиз</Eyebrow>
            <div style={{ marginTop:10 }}><StatHero value={points} label={l.points} /></div>
            <GoalBar value={points} />
            <div style={{ marginTop:16 }}>
              {pitOpen
                ? <button onClick={onPlay} className="tilepress" style={{ width:"100%", border:"none", cursor:"pointer", borderRadius:"var(--r-lg)", padding:"14px 16px", background:"#fff", display:"flex", alignItems:"center", justifyContent:"space-between", transition:"transform .12s" }}>
                    <span style={{ textAlign:"left" }}>
                      <span style={{ display:"block", fontFamily:"var(--font-heading)", fontSize:15, color:"#000", textTransform:"uppercase" }}>{l.play}</span>
                      <span style={{ display:"block", fontFamily:"var(--font-body)", fontSize:12, color:"var(--ink-500)" }}>{l.pit_sub}</span>
                    </span>
                    <span style={{ width:38, height:38, borderRadius:"50%", background:"var(--grad-red)", display:"flex", alignItems:"center", justifyContent:"center" }}><Icon name="flag" size={19} color="#fff" /></span>
                  </button>
                : <div style={{ width:"100%", borderRadius:"var(--r-lg)", padding:"14px 16px", background:"rgba(255,255,255,.08)", border:"1px solid var(--border-subtle)", display:"flex", alignItems:"center", justifyContent:"space-between" }}>
                    <span style={{ textAlign:"left" }}>
                      <span style={{ display:"block", fontFamily:"var(--font-heading)", fontSize:15, color:"#fff", textTransform:"uppercase" }}>{l.pit_next}</span>
                      <span style={{ display:"block", fontFamily:"var(--font-body)", fontSize:12, color:"rgba(255,255,255,.7)" }}>{pitPlayed ? l.pit_done_sub : l.pit_soon_sub}</span>
                    </span>
                    <span style={{ width:38, height:38, borderRadius:"50%", background:"rgba(214,35,0,.5)", display:"flex", alignItems:"center", justifyContent:"center" }}><Icon name="flag" size={19} color="#fff" /></span>
                  </div>}
            </div>
          </div>
        </div>
      </div>

      {/* team tank */}
      <div style={{ padding:"14px 16px 0" }}>
        <button onClick={()=>onNav("team")} className="tilepress" style={{ width:"100%", border:"1px solid var(--border-subtle)", background:"var(--surface-card)", cursor:"pointer", borderRadius:"var(--r-xl)", padding:"16px 18px", display:"flex", alignItems:"center", gap:14, transition:"transform .12s" }}>
          <Icon name="fuel" size={30} color="var(--brand)" />
          <div style={{ flex:1, textAlign:"left" }}>
            <div style={{ display:"flex", alignItems:"baseline", gap:8 }}>
              <span style={{ fontFamily:"var(--font-display)", fontWeight:900, fontSize:30, color:"var(--text-strong)" }}>{TEAM.bak}</span>
              <span style={{ fontFamily:"var(--font-heading)", fontSize:12, color:"var(--text-muted)", textTransform:"uppercase" }}>{l.tank}</span>
            </div>
            <div style={{ fontFamily:"var(--font-body)", fontSize:12, color:"var(--text-muted)", marginTop:2 }}>{l.tank_sub}</div>
          </div>
          <Icon name="chevron" size={20} color="var(--text-muted)" />
        </button>
      </div>

      {/* actions */}
      <div style={{ display:"flex", gap:12, padding:"12px 16px 22px" }}>
        <Tile icon="scan" title={l.scan_tile} hint={l.scan_hint} onClick={()=>onNav("scan")} />
        <Tile icon="ticket" title={l.tickets_tile} hint={tickets+" "+l.in_game} onClick={()=>onNav("tickets")} />
      </div>
    </div>
  );
}

function LangToggle({ lang, onLang }) {
  return (
    <button onClick={onLang} style={{ border:"1px solid var(--border-subtle)", background:"var(--surface-card)", cursor:"pointer", borderRadius:"var(--r-pill)", padding:"5px 11px", display:"flex", alignItems:"center", gap:6 }}>
      <Icon name="globe" size={14} color="var(--text-muted)" />
      <span style={{ fontFamily:"var(--font-heading)", fontSize:12, color:"var(--text-strong)" }}>{lang==="uz"?"UZ":"RU"}</span>
    </button>
  );
}

/* ---------- TEAM ---------- */
function TeamScreen({ lang, state, onChangeTeam, onSoon }) {
  const l = L(lang);
  const team = state?.team;
  const members = team?.members?.map((m)=>({
    name:m.name,
    tickets: state?.tickets?.filter((t)=>t.team_id===team.id).length || m.points || 0,
    captain:m.id===team.captain_user_id,
    you:m.id===state?.user?.id,
    played:!!m.played_current_window,
  })) || TEAM.members;
  return (
    <div style={{ flex:1, overflowY:"auto", background:"var(--surface-base)", padding:"4px 20px 24px" }}>
      <Eyebrow>{team?.name || TEAM.name}</Eyebrow>
      <H1>{l.team_title}</H1>
      <div style={{ marginTop:16, borderRadius:"var(--r-xl)", background:"var(--grad-kv)", padding:"18px 20px", display:"flex", alignItems:"center", gap:14 }}>
        <Icon name="fuel" size={34} color="#fff" />
        <div>
          <div style={{ display:"flex", alignItems:"baseline", gap:8 }}>
            <span style={{ fontFamily:"var(--font-display)", fontWeight:900, fontSize:40, color:"#fff" }}>{team?.playedCount ?? TEAM.bak}</span>
            <span style={{ fontFamily:"var(--font-heading)", fontSize:12, color:"rgba(255,255,255,.8)", textTransform:"uppercase" }}>{team?.boostActive ? "x2 включён" : "до x2"}</span>
          </div>
          <div style={{ fontFamily:"var(--font-body)", fontSize:12, color:"rgba(255,255,255,.85)" }}>Пригласите друзей: 4 игрока в пит-стопе дают x2.</div>
        </div>
      </div>

      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", margin:"20px 0 10px" }}>
        <span style={{ fontFamily:"var(--font-heading)", fontSize:14, color:"var(--text-strong)", textTransform:"uppercase" }}>{members.length}/20 · {l.members}</span>
        <span style={{ fontFamily:"var(--font-body)", fontSize:12, color:team?.boostActive?"var(--success)":"var(--sting-gold)", fontWeight:700 }}>{team?.boostActive ? "x2" : `ещё ${team?.missingForBoost ?? 4}`}</span>
      </div>
      <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
        {members.map((m,i)=>(
          <div key={i} style={{ display:"flex", alignItems:"center", gap:12, padding:"11px 14px", borderRadius:"var(--r-md)", background:m.you?"var(--ink-700)":"transparent", border:m.you?"1px solid var(--brand)":"1px solid var(--border-subtle)" }}>
            <span style={{ width:22, fontFamily:"var(--font-heading)", fontSize:14, color:"var(--text-muted)" }}>{i+1}</span>
            <span style={{ flex:1, fontFamily:"var(--font-body)", fontSize:14, fontWeight:700, color:"var(--text-strong)" }}>
              {m.name}{m.captain && <span style={{ marginLeft:8, fontFamily:"var(--font-heading)", fontSize:10, color:"var(--sting-gold)", textTransform:"uppercase" }}>{l.captain}</span>}
            </span>
            <span style={{ fontFamily:"var(--font-body)", fontSize:11, color:m.played?"var(--success)":"var(--text-muted)", textTransform:"uppercase" }}>{m.played?"сыграл":"ждём"}</span>
            <span style={{ display:"flex", alignItems:"center", gap:5 }}>
              <Icon name="ticket" size={14} color="var(--brand)" />
              <span style={{ fontFamily:"var(--font-heading)", fontSize:14, color:"var(--text-strong)" }}>{m.tickets}</span>
            </span>
          </div>
        ))}
      </div>
      <div style={{ marginTop:18 }}><BigButton icon="share" onClick={onSoon}>{l.invite}</BigButton></div>
      <button onClick={onChangeTeam} style={{ width:"100%", marginTop:12, background:"transparent", border:"none", cursor:"pointer", color:"var(--text-muted)", fontFamily:"var(--font-body)", fontSize:13, fontWeight:600 }}>{l.leave}</button>
    </div>
  );
}

/* ---------- BAKU ---------- */
function BakuScreen({ lang, state }) {
  const l = L(lang);
  const races = state?.f1?.races || [];
  const baku = races.find((race)=>race.highlight) || races[0];
  return (
    <div style={{ flex:1, overflowY:"auto", background:"var(--surface-base)", padding:"4px 20px 24px" }}>
      <Eyebrow>Formula 1 calendar</Eyebrow>
      <img src={F1LOGO} alt="F1" style={{ height:30, marginTop:4, display:"block" }} />

      {/* prize card */}
      <div style={{ marginTop:16, borderRadius:"var(--r-xl)", overflow:"hidden", position:"relative", height:170 }}>
        <img src={KV_HELMET} alt="" style={{ width:"100%", height:"100%", objectFit:"cover" }} />
        <div style={{ position:"absolute", inset:0, background:"var(--grad-scrim)" }} />
        <div style={{ position:"absolute", left:16, right:16, bottom:14 }}>
          <span style={{ display:"inline-block", background:"var(--grad-gold)", color:"#000", fontFamily:"var(--font-heading)", fontSize:11, textTransform:"uppercase", padding:"4px 9px", borderRadius:"var(--r-sm)", marginBottom:8 }}>Round {baku?.round || 15}</span>
          <div style={{ fontFamily:"var(--font-heading)", fontSize:16, color:"#fff", textTransform:"uppercase", lineHeight:1.1 }}>{baku?.title || l.prize_name}</div>
        </div>
      </div>

      {/* countdown + chance */}
      <div style={{ marginTop:14, borderRadius:"var(--r-xl)", background:"var(--surface-card)", border:"1px solid var(--border-subtle)", padding:"18px 20px" }}>
        <Eyebrow>Azerbaijan GP</Eyebrow>
        <div style={{ fontFamily:"var(--font-display)", fontWeight:900, fontSize:44, color:"#fff", lineHeight:.9, marginTop:6 }}>{baku?.dates || "24-26 Sep"}</div>
        <div style={{ display:"flex", alignItems:"center", gap:8, marginTop:12, paddingTop:12, borderTop:"1px solid var(--border-subtle)" }}>
          <Icon name="ticket" size={20} color="var(--brand)" />
          <span style={{ fontFamily:"var(--font-body)", fontSize:13, color:"var(--text-body)" }}>{state?.tickets?.length || 0} личных билетов · без randomizer на среду</span>
        </div>
      </div>

      <div style={{ marginTop:20, fontFamily:"var(--font-heading)", fontSize:14, color:"var(--text-strong)", textTransform:"uppercase", marginBottom:10 }}>F1 2026</div>
      <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
        {races.map((race,i)=>(
          <div key={i} style={{ display:"flex", alignItems:"center", gap:12, padding:"11px 14px", borderRadius:"var(--r-md)", border:"1px solid var(--border-subtle)" }}>
            <Icon name={race.highlight?"trophy":"flag"} size={18} color={race.highlight?"var(--sting-gold)":"var(--brand)"} />
            <span style={{ flex:1, fontFamily:"var(--font-body)", fontSize:14, fontWeight:700, color:"var(--text-strong)" }}>R{race.round} · {race.country}</span>
            <span style={{ fontFamily:"var(--font-body)", fontSize:12, color:"var(--text-muted)" }}>{race.dates}</span>
          </div>
        ))}
      </div>

      <div style={{ marginTop:20, fontFamily:"var(--font-heading)", fontSize:14, color:"var(--text-strong)", textTransform:"uppercase", marginBottom:10 }}>{l.my_tickets}</div>
      <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
        {(state?.tickets || []).slice(0,8).map((ticket,i)=>(
          <span key={i} style={{ fontFamily:"var(--font-heading)", fontSize:13, color:i===0?"#fff":"var(--text-muted)", background:i===0?"var(--grad-red)":"var(--ink-800)", border:"1px solid var(--border-subtle)", borderRadius:"var(--r-pill)", padding:"8px 13px" }}>{ticket.code}</span>
        ))}
      </div>
    </div>
  );
}

/* ---------- CABINET (личный кабинет) ---------- */
function CabinetScreen({ points, onNav, onLogout, onBindCard, cardBound, lang, state, onSoon }) {
  const l = L(lang);
  const rows = [
    { icon:"ticket", label:l.my_tickets, go:()=>onNav("tickets") },
    { icon:"creditCard", label:l.pay_card, sub: state?.card?.card_mask || (cardBound ? "•• 4022" : "—"), go:onBindCard },
    { icon:"globe", label:l.language, sub: lang==="uz"?"Oʻzbekcha":"Русский", go:()=>onNav("__lang") },
    { icon:"file", label:l.rules, go:onSoon },
    { icon:"shield", label:l.offer, go:onSoon },
    { icon:"help", label:l.support, go:onSoon },
  ];
  return (
    <div style={{ flex:1, overflowY:"auto", background:"var(--surface-base)" }}>
      <div style={{ position:"relative", padding:"10px 20px 18px", background:"var(--grad-kv)" }}>
        <div style={{ display:"flex", alignItems:"center", gap:14 }}>
          <div style={{ width:64, height:64, borderRadius:"50%", background:"rgba(0,0,0,.3)", border:"2px solid rgba(255,255,255,.4)", display:"flex", alignItems:"center", justifyContent:"center" }}><Icon name="user" size={30} color="#fff" /></div>
          <div>
            <div style={{ fontFamily:"var(--font-heading)", fontSize:20, color:"#fff", textTransform:"uppercase" }}>Азиз Каримов</div>
          <div style={{ fontFamily:"var(--font-body)", fontSize:13, color:"rgba(255,255,255,.85)" }}>{state?.team?.name || TEAM.name} · {l.level}</div>
          </div>
        </div>
        <div style={{ display:"flex", gap:10, marginTop:16 }}>
          {[{k:l.points,v:points},{k:l.scans,v:state?.receipts?.length || 0},{k:l.pitstops,v:state?.pitStop?.attempts || 0}].map((s,i)=>(
            <div key={i} style={{ flex:1, background:"rgba(0,0,0,.28)", borderRadius:"var(--r-lg)", padding:"12px 8px", textAlign:"center" }}>
              <div style={{ fontFamily:"var(--font-display)", fontWeight:900, fontSize:24, color:"#fff" }}>{s.v}</div>
              <div style={{ fontFamily:"var(--font-body)", fontSize:11, fontWeight:700, textTransform:"uppercase", letterSpacing:"0.06em", color:"rgba(255,255,255,.7)" }}>{s.k}</div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ padding:"14px 16px 24px" }}>
        <div style={{ borderRadius:"var(--r-xl)", overflow:"hidden", border:"1px solid var(--border-subtle)" }}>
          {rows.map((r,i)=>(
            <button key={i} onClick={r.go} style={{ width:"100%", border:"none", borderBottom:"1px solid var(--border-subtle)", background:"var(--surface-card)", cursor:"pointer", padding:"15px 16px", display:"flex", alignItems:"center", gap:14 }}>
              <Icon name={r.icon} size={20} color="var(--text-muted)" />
              <span style={{ flex:1, textAlign:"left", fontFamily:"var(--font-body)", fontSize:15, fontWeight:600, color:"var(--text-strong)" }}>{r.label}</span>
              {r.sub && <span style={{ fontFamily:"var(--font-body)", fontSize:13, color:"var(--text-muted)" }}>{r.sub}</span>}
              <Icon name="chevron" size={18} color="var(--text-muted)" />
            </button>
          ))}
        </div>
        <button onClick={onLogout} style={{ width:"100%", marginTop:14, background:"transparent", border:"1px solid var(--border-subtle)", borderRadius:"var(--r-lg)", cursor:"pointer", padding:"14px", display:"flex", alignItems:"center", justifyContent:"center", gap:8, color:"var(--text-muted)", fontFamily:"var(--font-heading)", fontSize:14, textTransform:"uppercase" }}>
          <Icon name="logout" size={18} color="var(--text-muted)" />{l.logout}
        </button>
      </div>
    </div>
  );
}

/* ---------- MY TICKETS (коды) ---------- */
function TicketsScreen({ onBack, lang, state }) {
  const l = L(lang);
  const tickets = state?.tickets || MY_TICKETS;
  const total = tickets.length;
  return (
    <div style={{ flex:1, overflowY:"auto", background:"var(--surface-base)", padding:"4px 20px 24px" }}>
      <button onClick={onBack} style={{ background:"transparent", border:"none", cursor:"pointer", display:"flex", alignItems:"center", gap:8, color:"var(--text-muted)", fontFamily:"var(--font-body)", fontSize:14, padding:"4px 0 10px" }}>
        <Icon name="arrowLeft" size={18} color="var(--text-muted)" />{l.back}
      </button>
      <Eyebrow>{total} {l.points==="ball"?"chipta":"билетов"} {l.in_game}</Eyebrow>
      <H1>{l.tk_title}</H1>
      <div style={{ marginTop:16, display:"flex", flexDirection:"column", gap:8 }}>
        {tickets.map((t,i)=>(
          <div key={i} style={{ display:"flex", alignItems:"center", gap:13, padding:"14px 16px", borderRadius:"var(--r-lg)", background:"var(--surface-card)", border:"1px solid var(--border-subtle)" }}>
            <Icon name="ticket" size={20} color="var(--brand)" />
            <div style={{ flex:1 }}>
              <div style={{ fontFamily:"var(--font-heading)", fontSize:15, color:"var(--text-strong)", letterSpacing:"0.03em" }}>{t.code}</div>
              <div style={{ fontFamily:"var(--font-body)", fontSize:12, color:"var(--text-muted)", marginTop:2 }}>{t.date || (t.created_at || "").slice(0,10)} · {t.shop || "receipt"} · {t.bottles || 1} бут.</div>
            </div>
            <span style={{ fontFamily:"var(--font-body)", fontSize:11, fontWeight:700, color:"var(--success)", textTransform:"uppercase", letterSpacing:"0.06em" }}>{l.in_game}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- SCAN (sheet) ---------- */
function ScanScreen({ onClose, onReward, lang }) {
  const l = L(lang);
  const [code,setCode] = React.useState("");
  return (
    <div style={{ flex:1, display:"flex", flexDirection:"column", background:"var(--surface-base)" }}>
      <div style={{ display:"flex", alignItems:"center", gap:14, padding:"6px 20px 10px" }}>
        <button onClick={onClose} style={{ background:"var(--ink-700)", border:"1px solid var(--border-subtle)", borderRadius:"50%", width:40, height:40, display:"flex", alignItems:"center", justifyContent:"center", cursor:"pointer" }}><Icon name="arrowLeft" size={20} color="var(--text-strong)" /></button>
        <H1 size={24}>{l.scan_title}</H1>
      </div>
      <div style={{ margin:"10px 20px 0", borderRadius:"var(--r-xl)", overflow:"hidden", position:"relative", aspectRatio:"1/1", background:"var(--ink-800)", border:"1px solid var(--border-subtle)" }}>
        <div style={{ position:"absolute", inset:"15%", borderRadius:"var(--r-lg)", boxShadow:"0 0 0 2px var(--brand)" }}>
          {["tl","tr","bl","br"].map((c)=>{
            const pos={ tl:{top:-3,left:-3,borderRight:0,borderBottom:0}, tr:{top:-3,right:-3,borderLeft:0,borderBottom:0}, bl:{bottom:-3,left:-3,borderRight:0,borderTop:0}, br:{bottom:-3,right:-3,borderLeft:0,borderTop:0} }[c];
            return <span key={c} style={Object.assign({ position:"absolute", width:26, height:26, border:"3px solid var(--sting-gold)", borderRadius:4 }, pos)} />;
          })}
          <div style={{ position:"absolute", left:0, right:0, top:0, height:2, background:"var(--brand)", boxShadow:"0 0 12px 2px var(--brand-glow)" }} />
        </div>
        <Icon name="qr" size={54} color="var(--ink-500)" style={{ position:"absolute", left:"50%", top:"50%", transform:"translate(-50%,-50%)" }} />
        <div style={{ position:"absolute", bottom:14, left:0, right:0, textAlign:"center", fontFamily:"var(--font-body)", fontSize:12, color:"var(--text-muted)" }}>{l.scan_aim}</div>
      </div>
      <div style={{ padding:20, display:"flex", flexDirection:"column", gap:14, flex:1 }}>
        <div>
          <div style={{ fontFamily:"var(--font-body)", fontSize:12, color:"var(--text-muted)", marginBottom:7 }}>{l.scan_manual}</div>
          <input value={code} onChange={(e)=>setCode(e.target.value)} placeholder="STG-0000-00" style={{ width:"100%", boxSizing:"border-box", background:"var(--ink-800)", border:"1px solid var(--border-subtle)", borderRadius:"var(--r-md)", padding:"14px 16px", color:"#fff", fontFamily:"var(--font-heading)", fontSize:16, letterSpacing:"0.05em", outline:"none" }} />
        </div>
        <div style={{ flex:1 }} />
        <BigButton icon="bolt" onClick={()=>onReward(code)}>{l.scan_btn}</BigButton>
      </div>
    </div>
  );
}
function RewardOverlay({ onClose, lang, reward }) {
  const l = L(lang);
  const accepted = reward?.acceptedBottles ?? 2;
  const raw = reward?.rawBottles ?? accepted;
  const attempts = reward?.attemptsAdded ?? accepted*2;
  const capped = reward?.capped;
  return (
    <div style={{ position:"absolute", inset:0, zIndex:60, background:"var(--surface-overlay)", backdropFilter:"blur(8px)", WebkitBackdropFilter:"blur(8px)", display:"flex", alignItems:"center", justifyContent:"center", padding:26 }}>
      <div style={{ width:"100%", background:"var(--surface-card)", border:"1px solid var(--border-subtle)", borderRadius:"var(--r-xl)", padding:26, textAlign:"center" }}>
        <div style={{ width:76, height:76, borderRadius:"50%", background:"var(--grad-red)", boxShadow:"var(--shadow-brand)", display:"flex", alignItems:"center", justifyContent:"center", margin:"0 auto 16px" }}><Icon name="check" size={38} color="#fff" /></div>
        <Eyebrow color="var(--sting-gold)">{l.accepted}</Eyebrow>
        <div style={{ fontFamily:"var(--font-display)", fontWeight:900, fontSize:34, color:"#fff", textTransform:"uppercase", margin:"8px 0 4px" }}>+{accepted} билетов</div>
        <p style={{ fontFamily:"var(--font-body)", fontSize:14, color:"var(--text-muted)", margin:"0 0 6px" }}>личные билеты · +{attempts} пит-стопов тебе</p>
        <p style={{ fontFamily:"var(--font-body)", fontSize:12, color:capped?"var(--sting-gold)":"var(--text-muted)", margin:"0 0 20px" }}>{capped ? `В чеке ${raw}, зачли максимум 5.` : l.limits}</p>
        <BigButton onClick={onClose}>{l.continue}</BigButton>
      </div>
    </div>
  );
}

/* ---------- CARD SHEET (привязка карты) ---------- */
function CardSheet({ onClose, onSave, lang }) {
  const l = L(lang);
  const [v,setV] = React.useState("");
  return (
    <div style={{ position:"absolute", inset:0, zIndex:60, background:"var(--surface-overlay)", backdropFilter:"blur(8px)", WebkitBackdropFilter:"blur(8px)", display:"flex", alignItems:"flex-end" }}>
      <div style={{ width:"100%", background:"var(--ink-900)", borderTopLeftRadius:"var(--r-xl)", borderTopRightRadius:"var(--r-xl)", borderTop:"1px solid var(--border-subtle)", padding:"22px 20px calc(24px + env(safe-area-inset-bottom))" }}>
        <div style={{ width:40, height:4, borderRadius:2, background:"var(--ink-600)", margin:"0 auto 18px" }} />
        <H1 size={24}>{l.card_title}</H1>
        <p style={{ fontFamily:"var(--font-body)", fontSize:13, color:"var(--text-muted)", margin:"8px 0 16px" }}>Проверьте номер карты дважды. Выплата придёт только на эту карту. Вы сами отвечаете за номер, который вводите.</p>
        <input value={v} onChange={(e)=>setV(e.target.value)} placeholder="8600 •••• •••• ••••" style={{ width:"100%", boxSizing:"border-box", background:"var(--ink-800)", border:"1px solid var(--border-subtle)", borderRadius:"var(--r-md)", padding:"14px 16px", color:"#fff", fontFamily:"var(--font-heading)", fontSize:17, letterSpacing:"0.08em", outline:"none", marginBottom:14 }} />
        <BigButton icon="creditCard" onClick={()=>onSave(v)}>{l.card_btn}</BigButton>
        <button onClick={onClose} style={{ width:"100%", marginTop:10, background:"transparent", border:"none", cursor:"pointer", color:"var(--text-muted)", fontFamily:"var(--font-body)", fontSize:13 }}>{l.back}</button>
      </div>
    </div>
  );
}

/* ---------- PIT-STOP GAME (imperative, ported) ---------- */
const SPOTS = [
  { id:"jackF", label:"Домкрат", x:160, y:34 },
  { id:"jackR", label:"Домкрат", x:160, y:524 },
  { id:"gunFL", label:"Гайка", x:38, y:189, wheel:"FL" },
  { id:"gunFR", label:"Гайка", x:282, y:189, wheel:"FR" },
  { id:"gunRL", label:"Гайка", x:38, y:387, wheel:"RL" },
  { id:"gunRR", label:"Гайка", x:282, y:387, wheel:"RR" },
  { id:"whFL", label:"Колесо", x:64, y:112, wheel:"FL", fresh:true },
  { id:"whFR", label:"Колесо", x:256, y:112, wheel:"FR", fresh:true },
  { id:"whRL", label:"Колесо", x:64, y:466, wheel:"RL", fresh:true },
  { id:"whRR", label:"Колесо", x:256, y:466, wheel:"RR", fresh:true },
];
function PitStopGame({ onFinish, onExit, lang }) {
  const l = L(lang);
  const ref = React.useRef(null);
  React.useEffect(()=>{
    const root = ref.current;
    const NS = "http://www.w3.org/2000/svg";
    const $ = (s) => root.querySelector(s);
    const nodes = $("#pnodes"), clock = $("#pclock"), phase = $("#pphase"), fin = $("#pfin"), lights = root.querySelectorAll(".lite");
    const WINDOW = 1150, PEN_MISS = 1000, PEN_WILD = 300;
    const fmt = (ms) => (ms/1000).toFixed(2);
    const rnd = (a,b)=>a+Math.random()*(b-a);
    const timers = new Set();
    const after = (fn,ms)=>{ const t=setTimeout(()=>{ timers.delete(t); fn(); }, ms); timers.add(t); return t; };
    let raf = 0, dead = false;
    const G = { queue:[...SPOTS].sort(()=>Math.random()-0.5), idx:-1, cur:null, hits:0, pen:0, t0:0, state:"lights", win:null };

    SPOTS.forEach((s)=>{
      const g = document.createElementNS(NS,"g");
      g.setAttribute("class","posnode"); g.setAttribute("data-id",s.id);
      g.innerHTML = `<circle class="hit" cx="${s.x}" cy="${s.y}" r="30"/><circle class="c" cx="${s.x}" cy="${s.y}" r="13"/><text x="${s.x}" y="${s.y+33}">${s.label}</text>`;
      nodes.appendChild(g);
    });
    const paintWheel = (s)=>{ if(!s.wheel) return; const w=$("#wh"+s.wheel); if(!w) return; w.setAttribute("fill", s.fresh ? "#D62300" : "#2a0608"); };
    const addPen = (ms)=>{ G.pen+=ms; clock.classList.remove("pen"); void clock.offsetWidth; clock.classList.add("pen"); };

    // start lights
    lights.forEach((li,i)=> after(()=>li.classList.add("on"), 320*i+250));
    after(()=>{
      if(dead) return;
      lights.forEach((li)=>li.classList.remove("on"));
      G.state="play"; G.t0=performance.now(); phase.textContent=l.pit_work;
      const tick=()=>{ if(dead||G.state!=="play") return; clock.textContent=fmt(performance.now()-G.t0+G.pen); raf=requestAnimationFrame(tick); };
      tick(); next();
    }, 320*5+rnd(600,1300));

    function next(){
      G.idx++;
      if(G.idx>=G.queue.length){ finish(); return; }
      after(()=>{
        if(dead||G.state!=="play") return;
        const s=G.queue[G.idx]; G.cur=s;
        const n=nodes.querySelector('[data-id="'+s.id+'"]'); n.classList.add("active");
        G.win=after(()=>{
          if(dead||G.cur!==s) return;
          n.classList.remove("active"); n.classList.add("miss"); G.cur=null; addPen(PEN_MISS); next();
        }, WINDOW);
      }, G.idx===0 ? rnd(250,500) : rnd(150,400));
    }
    function onDown(e){
      if(G.state!=="play") return;
      const node = e.target.closest && e.target.closest(".posnode");
      if(node && G.cur && node.getAttribute("data-id")===G.cur.id){
        clearTimeout(G.win); const s=G.cur; G.cur=null; G.hits++;
        node.classList.remove("active"); node.classList.add("done"); paintWheel(s); next();
      } else { addPen(PEN_WILD); }
    }
    root.querySelector("#pstage").addEventListener("pointerdown", onDown);
    function finish(){
      G.state="done"; cancelAnimationFrame(raf);
      const total = performance.now()-G.t0+G.pen;
      phase.textContent=l.pit_gone; clock.textContent=fmt(total);
      $("#pfinMs").textContent=fmt(total);
      $("#pfinDet").textContent=`${l.dots} ${G.hits}/10`+(G.pen?` · +${(G.pen/1000).toFixed(1)} сек`:"");
      fin.style.display="flex";
      after(()=> onFinish(total, { hits:G.hits, pen:G.pen }), 1900);
    }
    return ()=>{ dead=true; timers.forEach(clearTimeout); cancelAnimationFrame(raf); };
  }, []);

  return (
    <div ref={ref} style={{ position:"absolute", inset:0, zIndex:55, display:"flex", flexDirection:"column", background:"var(--surface-base)" }}>
      <div style={{ flex:"none", display:"flex", alignItems:"center", gap:12, padding:"12px 18px 8px", borderBottom:"1px solid var(--border-subtle)" }}>
        <button onClick={onExit} style={{ background:"transparent", border:"none", cursor:"pointer" }}><Icon name="arrowLeft" size={22} color="var(--text-muted)" /></button>
        <div id="pphase" style={{ fontFamily:"var(--font-heading)", fontSize:12, letterSpacing:"0.12em", textTransform:"uppercase", color:"var(--brand)" }}>{l.pit_ready}</div>
        <div id="pclock" className="pclock" style={{ marginLeft:"auto", fontFamily:"var(--font-display)", fontWeight:900, fontSize:26, color:"#fff" }}>0.00</div>
      </div>
      <div id="pstage" style={{ flex:1, position:"relative", display:"flex", alignItems:"center", justifyContent:"center", overflow:"hidden", touchAction:"manipulation" }}>
        <div style={{ position:"absolute", top:10, left:"50%", transform:"translateX(-50%)", display:"flex", gap:8, zIndex:2 }}>
          {[0,1,2,3,4].map(i=><span key={i} className="lite" />)}
        </div>
        <svg viewBox="0 0 320 560" style={{ height:"100%", maxHeight:"100%", width:"auto", maxWidth:"96%" }}>
          <rect x="36" y="22" width="248" height="516" fill="none" stroke="#2a2a32" strokeWidth="2" strokeDasharray="10 8" rx="10"/>
          <image href={BOLID} x="0" y="0" width="320" height="560" preserveAspectRatio="xMidYMid meet" style={{ pointerEvents:"none" }}/>
          <g id="pnodes"></g>
        </svg>
        <div id="pfin" style={{ display:"none", position:"absolute", inset:0, zIndex:3, flexDirection:"column", alignItems:"center", justifyContent:"center", gap:8, background:"radial-gradient(circle at 50% 45%, #ff2b33, #a3000a 80%)" }}>
          <div id="pfinMs" style={{ fontFamily:"var(--font-display)", fontWeight:900, fontSize:64, color:"#fff" }}>0.00</div>
          <div style={{ fontFamily:"var(--font-heading)", fontSize:14, color:"#fff", textTransform:"uppercase", letterSpacing:"0.1em" }}>{l.pit_gone}</div>
          <div id="pfinDet" style={{ fontFamily:"var(--font-body)", fontSize:13, color:"#ffd9da" }} />
        </div>
      </div>
      <div style={{ flex:"none", padding:"12px 18px calc(16px + env(safe-area-inset-bottom))", textAlign:"center", fontFamily:"var(--font-body)", fontSize:13, color:"var(--text-muted)" }}>{l.pit_hint}</div>
    </div>
  );
}

/* ---------- RESULTS ---------- */
function ResultsScreen({ result, points, onClose, lang }) {
  const l = L(lang);
  const my = result ? result.time : 7820;
  const rows = TEAM.members.filter((m)=>!m.you).slice(0,4).map((m,i)=>({ name:m.name, ms: 6500+i*900+Math.random()*800 }));
  rows.push({ name:l.you, ms:my, you:true });
  rows.sort((a,b)=>a.ms-b.ms);
  const PLACE=[12,8,6,4]; const x2 = result?.backend?.multiplier ? result.backend.multiplier > 1 : rows.length>=4;
  const myPos = rows.findIndex(r=>r.you);
  const gained = result?.backend?.points || ((PLACE[myPos] ?? 2) * (x2?2:1));
  return (
    <div style={{ position:"absolute", inset:0, zIndex:60, background:"var(--surface-overlay)", backdropFilter:"blur(8px)", WebkitBackdropFilter:"blur(8px)", display:"flex", alignItems:"center", justifyContent:"center", padding:22 }}>
      <div style={{ width:"100%", background:"var(--surface-card)", border:"1px solid var(--border-subtle)", borderRadius:"var(--r-xl)", padding:22 }}>
        <Eyebrow color="var(--sting-gold)">{l.results}</Eyebrow>
        <div style={{ display:"flex", alignItems:"baseline", gap:10, margin:"6px 0 4px" }}>
          <div style={{ fontFamily:"var(--font-display)", fontWeight:900, fontSize:44, color:"#fff" }}>{(my/1000).toFixed(2)}</div>
          <div style={{ fontFamily:"var(--font-heading)", fontSize:13, color:"var(--text-muted)", textTransform:"uppercase" }}>сек {x2 && "· "} {x2 && <span style={{ color:"var(--sting-gold)" }}>{l.x2}</span>}</div>
        </div>
        {result && <div style={{ fontFamily:"var(--font-body)", fontSize:12, color:"var(--text-muted)", marginBottom:12 }}>{l.dots} {result.hits}/10{result.pen?` · штрафы +${(result.pen/1000).toFixed(1)} сек`:""}</div>}
        <div style={{ borderTop:"1px solid var(--border-subtle)", paddingTop:10, display:"flex", flexDirection:"column", gap:3 }}>
          {rows.slice(0,6).map((r,i)=>(
            <div key={i} style={{ display:"flex", alignItems:"center", gap:10, padding:"5px 0", fontSize:14 }}>
              <span style={{ width:18, fontFamily:"var(--font-heading)", fontSize:13, color:i<4?"var(--brand)":"var(--text-muted)" }}>{i+1}</span>
              <span style={{ flex:1, fontFamily:"var(--font-body)", fontWeight:r.you?700:600, color:r.you?"#fff":"var(--text-body)" }}>{r.name}</span>
              <span style={{ fontFamily:"var(--font-heading)", fontSize:13, color:"var(--text-muted)" }}>{(r.ms/1000).toFixed(2)}</span>
              <span style={{ width:42, textAlign:"right", fontFamily:"var(--font-heading)", fontSize:13, color:i<4?"var(--text-strong)":"var(--text-muted)" }}>{(PLACE[i]??2)*(x2?2:1)} {l.oc}</span>
            </div>
          ))}
        </div>
        <div style={{ margin:"12px 0 14px", fontFamily:"var(--font-body)", fontSize:14, color:"var(--text-body)" }}>Тебе: <b style={{ color:"var(--sting-gold)" }}>+{gained} очков</b></div>
        <BigButton icon="scan" onClick={onClose}>{l.again}</BigButton>
      </div>
    </div>
  );
}

inject();
window.StingScreens = {
  BottomNav, LoginScreen, HomeScreen, TeamScreen, BakuScreen,
  CabinetScreen, TicketsScreen, ScanScreen, RewardOverlay, CardSheet, PitStopGame, ResultsScreen,
};
