import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useRef, useState, type FormEvent } from "react";
import bgMusic from "@/assets/aviator-background.mp3";
import crashSfx from "@/assets/plane-crash.mp3";
import { Menu, MessageCircle, MoreHorizontal, Minus, Plus, Volume2, Music, CirclePlus, WalletCards, UserRound, Home, X, SendHorizontal } from "lucide-react";
import ufcLogo from "@/assets/ufc.svg";
import spribePowered from "@/assets/spribe-powered.png";
import spribeBadge from "@/assets/spribe-2019.svg";
import { AviatorPlane } from "@/components/lotus/AviatorPlane";
import { GameTopBar } from "@/components/lotus/GameTopBar";
import { useCrashRound, useCrashBet, useFakeBets, useMyBets, pillColor, type Phase } from "@/lib/crash";
import { useBalance, fmt } from "@/lib/wallet";

export const Route = createFileRoute("/aviator")({
  head: () => ({
    meta: [
      { title: "Aviator – Lotus365" },
      { name: "description", content: "Watch the plane fly and cash out before it flies away." },
      { property: "og:title", content: "Aviator – Lotus365" },
      { property: "og:description", content: "Crash game: cash out before the plane flies away." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: AviatorPage,
});

/** Intro: black "Connecting..." screen, then "Powered by SPRIBE" fades in, then the game. */
function AviatorPage() {
  const [stage, setStage] = useState<0 | 1 | 2>(0);
  useEffect(() => {
    const t1 = setTimeout(() => setStage(1), 2200);
    const t2 = setTimeout(() => setStage(2), 3700);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);
  if (stage === 0) return (
    <div className="app-frame grid place-items-center bg-spribe-intro">
      <img src={spribePowered} alt="Powered by SPRIBE" className="w-48 animate-intro-fade" />
    </div>
  );
  if (stage === 1) return <div className="app-frame grid place-items-center bg-ink text-lg font-semibold">Connecting...</div>;
  return <div className="animate-intro-fade"><Aviator /></div>;
}

function Aviator() {
  const balance = useBalance();
  const g = useCrashRound();
  const bets = useFakeBets(g.round, g.mult, g.phase);
  const [showPlayer, setShowPlayer] = useState(false);
  const [showHist, setShowHist] = useState(false);
  const [showChat, setShowChat] = useState(false);
  const [soundOn, setSoundOn] = useState(true);
  const [musicOn, setMusicOn] = useState(true);
  const [tab, setTab] = useState("All Bets");
  const [toasts, setToasts] = useState<{ id: number; x: number; win: number }[]>([]);
  const onCash = (x: number, win: number) => {
    const id = Date.now() + Math.random();
    setToasts((t) => [...t, { id, x, win }]);
    setTimeout(() => setToasts((t) => t.filter((v) => v.id !== id)), 3000);
  };
  // Matches the reference video: plane takes off from the bottom-left corner, climbs steeply first
  // (≈60% height at 1.30x), then drifts right and settles in the top-right corner, where it hovers.
  const t = Math.min((g.mult - 1) / 1.2, 1);
  const x0 = 83 * Math.pow(t, 1.2);
  const y0 = 100 - Math.pow(Math.min((g.mult - 1) / 0.85, 1), 0.85) * 80;
  const p = t >= 1 ? 1 : 0;
  // At the top the whole plane + red line + red area drift down/left and back up/right together.
  const sway = p ? (1 - Math.cos((g.elapsed / 3000) * Math.PI * 2)) / 2 : 0;
  const x = x0 - sway * 6;
  const y = y0 + sway * 22;
  const last = useRef({ x: 0, y: 100 });
  if (g.phase === "flying") last.current = { x, y };
  useAviatorSounds(g.phase, soundOn, musicOn);
  // Bets counter like the video: "remaining/total Bets", counts down as players cash out.
  const baseBets = 2400 + ((g.round * 7919) % 300);
  // While waiting, new bets keep coming in (both numbers rise together); in flight the left number falls.
  const totalBets = g.phase === "waiting" ? Math.round(baseBets + (1 - g.waitLeft / 5000) * 350) : baseBets + 350;
  // Video pace: ~3% cashed out by 1.27x, ~14% by 2x.
  const leftBets = g.phase === "waiting" ? totalBets : Math.round(totalBets * (1 - Math.min((g.mult - 1) * 0.13, 0.9)));
  // PREVIOUS tab: snapshot of the last finished round.
  const [prev, setPrev] = useState<{ crash: number; rows: typeof bets } | null>(null);
  const betsRef = useRef(bets);
  betsRef.current = bets;
  useEffect(() => {
    if (g.phase === "crashed") setPrev({ crash: g.mult, rows: betsRef.current });
  }, [g.phase]); // eslint-disable-line react-hooks/exhaustive-deps
  const totalWin = bets.reduce((s, b) => s + (b.cashed ? b.bet * b.out : 0), 0) * 18;
  // MY BETS tab: everything this player has staked, with its result.
  const my = useMyBets();
  const staked = my.reduce((s, b) => s + b.amount, 0);
  const won = my.reduce((s, b) => s + b.win, 0);

  const listBox = "max-h-[300px] overflow-y-auto overscroll-contain pb-1 no-scrollbar";
  const rowsHead = (
    <div className="grid grid-cols-[1fr_70px_40px_80px] border-b border-ink-3 bg-ink px-1 pb-2 pt-1 text-[11px] text-muted-foreground">
      <span>User</span><span className="text-right">Bet INR</span><span className="text-center">X</span><span className="text-right">Cash out INR</span>
    </div>
  );
  const row = (b: (typeof bets)[number]) => (
    <div key={b.name} className={`mt-1 grid grid-cols-[1fr_70px_40px_80px] items-center rounded-lg px-1.5 py-1 text-xs ${b.cashed ? "border border-win/60 bg-win/15" : "bg-ink"}`}>
      <span className="flex items-center gap-1.5"><img src={avatarUrl(b.name)} alt="" className="size-6 rounded-full" />{b.name}</span>
      <span className="text-right">{b.bet.toFixed(2)}</span>
      <span className="text-center text-muted-foreground">{!b.cashed && "—"}{b.cashed && <span className={`rounded-full bg-ink-2 px-1 text-[10px] font-bold ${pillColor(b.out)}`}>{b.out.toFixed(2)}x</span>}</span>
      <span className={`text-right ${b.cashed ? "text-win" : "text-muted-foreground"}`}>{b.cashed ? (b.bet * b.out).toFixed(2) : "—"}</span>
    </div>
  );

  return (
    <div className="app-frame bg-ink pb-6">
      <GameTopBar />
      <div className="flex items-center justify-between border-b border-ink-3 bg-ink px-3 py-2">
        <span className="font-serif text-2xl italic text-lose">Aviator</span>
        <div className="flex items-center gap-3 text-sm">
          <span><b className="font-semibold text-win">{fmt(balance)}</b> <span className="text-muted-foreground">INR</span></span>
          <button aria-label="Open player menu" onClick={() => setShowPlayer(true)}><Menu className="size-5" /></button>
          <button aria-label="Open chat" onClick={() => setShowChat(true)}><MessageCircle className="size-5" /></button>
        </div>
      </div>
      <div className="flex items-center gap-3 border-b border-ink-3 px-2 py-2 text-sm font-bold">
        <div className="flex flex-1 justify-between overflow-hidden">
          {g.history.slice(0, 7).map((h, i) => <span key={g.round - i} className={`${pillColor(h)} animate-pop`}>{h.toFixed(2)}x</span>)}
        </div>
        <button aria-label="Round history" onClick={() => setShowHist((v) => !v)} className="grid size-7 place-items-center rounded-full bg-ink-3"><MoreHorizontal className="size-4" /></button>
      </div>
      {showHist && (
        <div className="grid grid-cols-6 gap-1.5 border-b border-ink-3 bg-ink-2 p-2 text-xs font-bold">
          {g.history.map((h, i) => <span key={i} className={`${pillColor(h)} rounded-full bg-ink px-1 py-0.5 text-center`}>{h.toFixed(2)}x</span>)}
        </div>
      )}
      {showChat && <ChatPanel onClose={() => setShowChat(false)} />}
      {showPlayer && (
        <PlayerPanel
          soundOn={soundOn}
          musicOn={musicOn}
          onSound={() => setSoundOn((v) => !v)}
          onMusic={() => setMusicOn((v) => !v)}
          onClose={() => setShowPlayer(false)}
        />
      )}

      <div className="relative mx-3 mt-3 aspect-[376/210] overflow-hidden rounded-xl border border-ink-3 bg-ink">
        <div className={`absolute -bottom-[250%] -left-[250%] size-[500%] animate-rays ${g.phase === "waiting" ? "bg-aviator-rays-dark" : "bg-aviator-rays"}`} />
        <div className="absolute inset-0 [background:radial-gradient(circle_at_0%_100%,transparent_45%,var(--ink)_150%)]" />
        {g.phase === "waiting" && <div className="absolute inset-0 bg-aviator-glow" />}
        {g.phase === "flying" && (
          <>
            <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 h-full w-full">
              <path d={`M0,100 C${x * 0.6},100 ${x * 0.95},${y + (100 - y) * 0.5} ${x},${y} L${x},100 Z`} className="fill-lose/45" />
              <path d={`M0,100 C${x * 0.6},100 ${x * 0.95},${y + (100 - y) * 0.5} ${x},${y}`} className="fill-none stroke-lose" strokeWidth="3" vectorEffect="non-scaling-stroke" />
            </svg>
            <div className="absolute" style={{ left: `${x}%`, top: `${y}%` }}>
              <AviatorPlane className="w-24 -translate-x-[4px] -translate-y-[80%] origin-bottom-left -rotate-[8deg]" />
            </div>
          </>
        )}
        {g.phase === "waiting" && (
          <div className="absolute bottom-[12%] left-[6%]"><AviatorPlane className="w-24 -rotate-[8deg]" /></div>
        )}
        {g.phase === "crashed" && (
          <div className="absolute" style={{ left: `${last.current.x}%`, top: `${last.current.y}%` }}>
            <AviatorPlane className="w-24 -translate-x-[20px] -translate-y-3/4 animate-fly-away" />
          </div>
        )}
        <Center phase={g.phase} mult={g.mult} waitLeft={g.waitLeft} />
        <div className="absolute inset-x-0 top-2 flex flex-col items-center gap-1">
          {toasts.map((t) => (
            <div key={t.id} className="flex animate-pop items-center gap-3 rounded-full border border-win bg-win/90 py-1 pl-4 pr-1 text-foreground">
              <div className="text-center text-[10px] leading-tight">You have<br />cashed out!<p className="text-sm font-bold">{t.x.toFixed(2)}x</p></div>
              <div className="rounded-full bg-win px-3 py-1 text-center text-[10px] leading-tight brightness-75">Win INR<p className="text-sm font-bold">{t.win.toFixed(2)}</p></div>
            </div>
          ))}
        </div>
        {<span className="absolute bottom-2 right-2 flex items-center gap-1 rounded-full bg-ink/70 py-0.5 pl-0.5 pr-2 text-xs font-bold"><Avatars small />{leftBets}</span>}
      </div>

      <BetBox phase={g.phase} mult={g.mult} onCash={onCash} />
      <BetBox phase={g.phase} mult={g.mult} onCash={onCash} second />

      <div className="mx-3 mt-4 grid grid-cols-3 rounded-full bg-ink-2 p-1 text-sm">
        {["All Bets", "Previous", "My Bets"].map((t) => (
          <button key={t} onClick={() => setTab(t)} className={`rounded-full py-2 ${tab === t ? "bg-ink-3 text-foreground" : "text-muted-foreground"}`}>{t}</button>
        ))}
      </div>
      <div className="mx-3 mt-3">
        {tab === "All Bets" && (<>
          <div className="flex items-center justify-between px-1 pb-3">
            <div className="flex items-center gap-2">
              <Avatars />
              <p className="text-sm"><span className="font-semibold">{leftBets}/{totalBets}</span> <span className="text-muted-foreground">Bets</span></p>
            </div>
            <div className="text-right">
              <p className="text-sm font-bold">{totalWin.toFixed(2)}</p>
              <p className="text-[10px] text-muted-foreground">Total win INR</p>
            </div>
          </div>
          {rowsHead}
          <div className={listBox}>{bets.map(row)}</div>
        </>)}
        {tab === "Previous" && (<>
          <div className="rounded-xl border border-ink-3 bg-ink-2 py-4 text-center">
            <p className="text-sm text-muted-foreground">Round Result</p>
            {prev ? <p className="text-3xl font-extrabold text-lose">{prev.crash.toFixed(2)}x</p> : <p className="mx-auto mt-3 h-1 w-7 rounded bg-muted-foreground" />}
          </div>
          <div className="mt-3">{rowsHead}</div>
          <div className={listBox}>
            {prev ? prev.rows.map(row) : <p className="py-4 text-center text-xs text-muted-foreground">No previous round yet.</p>}
          </div>
        </>)}
        {tab === "My Bets" && (<>
          <div className="rounded-xl border border-ink-3 bg-ink-2 p-3 text-xs">
            <div className="flex items-center justify-between"><span className="text-muted-foreground">Bets placed</span><span className="font-bold">{my.length}</span></div>
            <div className="mt-1.5 flex items-center justify-between"><span className="text-muted-foreground">Total staked INR</span><span className="font-bold">{staked.toFixed(2)}</span></div>
            <div className="mt-1.5 flex items-center justify-between"><span className="text-muted-foreground">Total won INR</span><span className={`font-bold ${won > 0 ? "text-win" : ""}`}>{won.toFixed(2)}</span></div>
          </div>
          <div className="mt-3 grid grid-cols-[64px_1fr_56px_78px] border-b border-ink-3 bg-ink px-1 pb-2 pt-1 text-[11px] text-muted-foreground">
            <span>Time</span><span className="text-right">Bet INR</span><span className="text-center">X</span><span className="text-right">Win INR</span>
          </div>
          <div className={listBox}>
            {my.length === 0 && <p className="py-4 text-center text-xs text-muted-foreground">No bets yet. Place a bet to see it here.</p>}
          {my.map((b) => (
            <div key={b.id} className={`mt-1 grid grid-cols-[64px_1fr_56px_78px] items-center rounded-lg px-1.5 py-1 text-xs ${b.out != null ? "border border-win/60 bg-win/15" : "bg-ink"}`}>
              <span>{b.time}</span>
              <span className="text-right">{b.amount.toFixed(2)}</span>
              <span className="text-center">{b.out == null ? <span className="text-muted-foreground">—</span> : <span className={`rounded-full bg-ink-2 px-1 text-[10px] font-bold ${pillColor(b.out)}`}>{b.out.toFixed(2)}x</span>}</span>
              <span className={`text-right ${b.out != null ? "text-win" : "text-muted-foreground"}`}>{b.out == null ? "—" : b.win.toFixed(2)}</span>
            </div>
          ))}
          </div>
        </>)}
      </div>
    </div>
  );
}

const avatarUrl = (seed: string) => {
  let h = 0;
  for (const c of seed) h = (h * 31 + c.charCodeAt(0)) % 72;
  return `https://aviator-demo.spribegaming.com/assets/static/avatars/v2/av-${h + 1}.png`;
};

const CHAT_LINES = [
  "Are yaar koi baat hi nahi karta", "Admin god h bhai", "Paisa to aa gya ab", "Approved ho gya",
  "Daro mat khelo bindas", "Withdrawal processing me h?", "Risk mat lo jyada", "Signal follow karo bas",
  "Haan mera aa gya abhi", "Next round 2x pakka", "Kal 5k jeeta tha", "1.5x pe nikal lo bhai",
  "Aaj luck accha hai", "Deposit kitne time me aata h?", "Bhai 10x aayega abhi", "Mera cash out ho gya",
];
type ChatMsg = { id: number; name: string; text: string; seed: string };
let chatId = 0;
const randomMsg = (): ChatMsg => {
  const a = 1 + Math.floor(Math.random() * 9), b = Math.floor(Math.random() * 10);
  const seed = String(Math.random());
  return { id: ++chatId, name: `${a}***${b}`, text: CHAT_LINES[Math.floor(Math.random() * CHAT_LINES.length)] ?? CHAT_LINES[0]!, seed };
};

/** Chat drawer like the reference: online count, fake players keep posting automatically, user can reply. */
function ChatPanel({ onClose }: { onClose: () => void }) {
  const [msgs, setMsgs] = useState<ChatMsg[]>(() => Array.from({ length: 14 }, randomMsg));
  const [online, setOnline] = useState(() => 7800 + Math.floor(Math.random() * 400));
  const [text, setText] = useState("");
  const list = useRef<HTMLDivElement>(null);
  useEffect(() => {
    let t: ReturnType<typeof setTimeout>;
    const tick = () => {
      setMsgs((m) => [...m, randomMsg()].slice(-60));
      setOnline((o) => Math.max(7000, o + Math.floor(Math.random() * 41) - 20));
      t = setTimeout(tick, 1500 + Math.random() * 2500);
    };
    t = setTimeout(tick, 1500);
    const esc = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", esc);
    return () => { clearTimeout(t); window.removeEventListener("keydown", esc); };
  }, [onClose]);
  useEffect(() => { list.current?.scrollTo({ top: list.current.scrollHeight, behavior: "smooth" }); }, [msgs]);
  const send = (e: FormEvent) => {
    e.preventDefault();
    if (!text.trim()) return;
    setMsgs((m) => [...m, { id: ++chatId, name: "You", text: text.trim(), seed: "Player" }].slice(-60));
    setText("");
  };
  return (
    <div className="fixed inset-0 z-50 flex justify-end bg-ink/60" onClick={onClose}>
      <aside role="dialog" aria-label="Chat" onClick={(e) => e.stopPropagation()} className="flex h-full w-full max-w-[423px] flex-col bg-ink text-foreground shadow-2xl">
        <header className="flex items-center justify-between border-b border-ink-3 bg-ink-2 px-3 py-3">
          <span className="flex items-center gap-2 text-base font-bold"><span className="size-2 rounded-full bg-win" />{online}</span>
          <button aria-label="Close chat" onClick={onClose} className="text-muted-foreground"><X className="size-4" /></button>
        </header>
        <div ref={list} className="flex-1 space-y-4 overflow-y-auto px-3 py-4">
          {msgs.map((m) => (
            <div key={m.id} className="flex gap-3 animate-pop">
              <img src={avatarUrl(m.seed)} alt="" className="size-8 shrink-0 rounded-full bg-ink-3 object-cover" />
              <div className="min-w-0">
                <div className="text-xs text-muted-foreground">{m.name}</div>
                <div className="text-sm font-semibold">{m.text}</div>
              </div>
            </div>
          ))}
        </div>
        <form onSubmit={send} className="flex items-center gap-2 border-t border-ink-3 bg-ink-2 px-3 py-3">
          <input value={text} onChange={(e) => setText(e.target.value)} placeholder="Reply..." className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground" />
          <button type="submit" aria-label="Send" className="text-muted-foreground"><SendHorizontal className="size-5 rotate-90" /></button>
        </form>
      </aside>
    </div>
  );
}

function PlayerPanel({ soundOn, musicOn, onSound, onMusic, onClose }: {
  soundOn: boolean;
  musicOn: boolean;
  onSound: () => void;
  onMusic: () => void;
  onClose: () => void;
}) {
  useEffect(() => {
    const close = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", close);
    return () => window.removeEventListener("keydown", close);
  }, [onClose]);

  const toggle = (label: string, on: boolean, action: () => void) => (
    <button
      type="button"
      role="switch"
      aria-label={label}
      aria-checked={on}
      onClick={action}
      className={`relative h-5 w-9 shrink-0 rounded-full transition ${on ? "bg-win" : "bg-ink-3"}`}
    >
      <span className={`absolute top-0.5 size-4 rounded-full bg-foreground shadow transition ${on ? "left-[18px]" : "left-0.5"}`} />
    </button>
  );

  return (
    <div className="fixed inset-0 z-50 flex justify-center bg-ink/75 px-4 pt-[70px] backdrop-blur-sm" onClick={onClose}>
      <section
        role="dialog"
        aria-modal="true"
        aria-label="Player menu"
        className="h-fit w-[280px] animate-pop overflow-hidden rounded-xl border border-foreground/10 bg-ink-2 text-sm shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="flex items-center gap-3 border-b border-ink-3 px-4 py-3">
          <img src={avatarUrl("Player")} alt="Player" className="size-10 rounded-full border-2 border-gold bg-ink object-cover" />
          <h2 className="flex-1 font-semibold">Player</h2>
          <button autoFocus type="button" aria-label="Close player menu" onClick={onClose} className="p-1 text-muted-foreground"><X className="size-4" /></button>
        </header>
        <div className="space-y-4 border-b border-ink-3 px-4 py-4">
          <div className="flex items-center gap-3">
            <Volume2 className="size-4 text-muted-foreground" /><span className="flex-1">Sound</span>{toggle("Sound", soundOn, onSound)}
          </div>
          <div className="flex items-center gap-3">
            <Music className="size-4 text-muted-foreground" /><span className="flex-1">Music</span>{toggle("Music", musicOn, onMusic)}
          </div>
        </div>
        <div className="space-y-4 border-b border-ink-3 px-4 py-4">
          <button type="button" className="flex w-full items-center gap-3 text-left"><CirclePlus className="size-4 text-muted-foreground" />Deposit</button>
          <button type="button" className="flex w-full items-center gap-3 text-left"><WalletCards className="size-4 text-muted-foreground" />Withdraw</button>
          <button type="button" className="flex w-full items-center gap-3 text-left"><UserRound className="size-4 text-muted-foreground" />Profile</button>
        </div>
        <Link to="/" onClick={onClose} className="flex items-center justify-center gap-2 py-4 text-muted-foreground"><Home className="size-4" />Home</Link>
      </section>
    </div>
  );
}

function Center({ phase, mult, waitLeft }: { phase: Phase; mult: number; waitLeft: number }) {
  if (phase === "waiting")
    return (
      <div className="absolute inset-0 flex flex-col items-center justify-center gap-2">
        <img src={ufcLogo} alt="UFC Aviator Official Partners" className="w-[44%]" />
        <div className="h-1 w-[42%] overflow-hidden rounded-full bg-foreground/20"><div className="h-full rounded-full bg-lose" style={{ width: `${(waitLeft / 5000) * 100}%` }} /></div>
        <img src={spribeBadge} alt="SPRIBE Official Game" className="mt-2 w-[25%]" />
      </div>
    );
  return (
    <div className="absolute inset-0 flex flex-col items-center justify-center">
      {phase === "crashed" && <p className="text-xl font-bold">FLEW AWAY!</p>}
      <p className={`text-5xl font-extrabold tracking-tight ${phase === "crashed" ? "text-lose" : ""}`}>{mult.toFixed(2)}x</p>
    </div>
  );
}

function BetBox({ phase, mult, second, onCash }: { phase: Phase; mult: number; second?: boolean; onCash: (x: number, win: number) => void }) {
  const b = useCrashBet(phase, mult);
  const seen = useRef<number | null>(null);
  useEffect(() => {
    if (b.lastWin != null && b.lastWin !== seen.current) onCash(b.lastWin / b.amount, b.lastWin);
    seen.current = b.lastWin;
  }, [b.lastWin]); // eslint-disable-line react-hooks/exhaustive-deps
  const [mode, setMode] = useState("Bet");
  const btn =
    b.status === "queued" ? { cls: "bg-lose", top: "Cancel", main: "" }
    : b.status === "active" && phase === "flying" ? { cls: "bg-cash", top: "Cash Out", main: `${(b.amount * mult).toFixed(2)} INR` }
    : { cls: "bg-win", top: "Bet", main: `${b.amount.toFixed(2)} INR` };
  return (
    <div className="relative mx-3 mt-3 rounded-xl border border-ink-3 bg-ink-2 p-2">
      {second && <span className="absolute right-2 top-2 grid size-7 place-items-center rounded-full bg-ink-3"><Minus className="size-4" /></span>}
      <div className="mx-auto flex w-32 rounded-full bg-ink p-0.5 text-xs">
        {["Bet", "Auto"].map((m) => <button key={m} onClick={() => setMode(m)} className={`flex-1 rounded-full py-1 ${mode === m ? "bg-ink-3" : "text-muted-foreground"}`}>{m}</button>)}
      </div>
      <div className="mt-2 flex gap-2">
        <div className="w-[42%]">
          <div className="flex items-center justify-between rounded-full bg-ink px-1 py-1 font-bold">
            <button aria-label="Less" onClick={() => b.setAmount(Math.max(1, b.amount - 10))} className="grid size-6 place-items-center rounded-full bg-ink-3"><Minus className="size-3" /></button>
            <span>{b.amount.toFixed(2)}</span>
            <button aria-label="More" onClick={() => b.setAmount(b.amount + 10)} className="grid size-6 place-items-center rounded-full bg-ink-3"><Plus className="size-3" /></button>
          </div>
          <div className="mt-1.5 grid grid-cols-2 gap-1.5 text-xs">
            {[100, 200, 500, 10000].map((v) => <button key={v} onClick={() => b.setAmount(v)} className="rounded-full bg-ink-3/70 py-1 text-muted-foreground">{v.toLocaleString("en-IN")}</button>)}
          </div>
        </div>
        <button onClick={b.press} className={`flex flex-1 flex-col items-center justify-center rounded-2xl border-2 border-foreground/25 ${btn.cls} font-semibold transition active:scale-95`}>
          <span className={btn.main ? "text-lg" : "text-2xl font-bold"}>{btn.top}</span>
          {btn.main && <span className="text-lg">{btn.main}</span>}
        </button>
      </div>
    </div>
  );
}

/** Background music loops while on the page (starts after first tap); crash sound when the plane flies away. */
function useAviatorSounds(phase: Phase, soundOn: boolean, musicOn: boolean) {
  const music = useRef<HTMLAudioElement | null>(null);
  const crash = useRef<HTMLAudioElement | null>(null);
  useEffect(() => {
    music.current = new Audio(bgMusic);
    music.current.loop = true;
    music.current.volume = 0.5;
    crash.current = new Audio(crashSfx);
    const start = () => { music.current?.play().catch(() => {}); };
    start();
    window.addEventListener("pointerdown", start, { once: true });
    return () => { window.removeEventListener("pointerdown", start); music.current?.pause(); crash.current?.pause(); };
  }, []);
  useEffect(() => {
    if (musicOn) music.current?.play().catch(() => {});
    else music.current?.pause();
  }, [musicOn]);
  useEffect(() => {
    if (phase === "crashed" && soundOn && crash.current) { crash.current.currentTime = 0; crash.current.play().catch(() => {}); }
  }, [phase, soundOn]);
}

function Avatars({ small }: { small?: boolean }) {
  return (
    <span className="flex -space-x-2">
      {["k***1", "m***4", "s***7"].map((n) => (
        <img key={n} src={avatarUrl(n)} alt="" className={`${small ? "size-4" : "size-7"} rounded-full border-2 border-win`} />
      ))}
    </span>
  );
}
