import { createFileRoute, Link } from "@tanstack/react-router";
import { useState } from "react";
import { Gem, Bomb, HelpCircle, Volume2, Gamepad2, UserPlus, Wallet, User, Plus, Headphones } from "lucide-react";
import { GameLoader, Logo } from "@/components/lotus/Loader";
import { minesMultiplier } from "@/lib/games";
import { addBalance, trySpend, useBalance, fmt } from "@/lib/wallet";

export const Route = createFileRoute("/mines")({
  head: () => ({
    meta: [
      { title: "Mines – Lotus365" },
      { name: "description", content: "Open tiles, find gems, avoid the mines and cash out." },
      { property: "og:title", content: "Mines – Lotus365" },
      { property: "og:description", content: "5x5 mines game with rising multipliers." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: () => <GameLoader><Mines /></GameLoader>,
});

type Row = { time: string; bet: number; mult: number; win: number };

function Mines() {
  const balance = useBalance();
  const [mines, setMines] = useState(3);
  const [amount, setAmount] = useState(10);
  const [playing, setPlaying] = useState(false);
  const [bombs, setBombs] = useState<Set<number>>(new Set());
  const [open, setOpen] = useState<Set<number>>(new Set());
  const [boom, setBoom] = useState<number | null>(null);
  const [rows, setRows] = useState<Row[]>([]);
  const picks = open.size;
  const cur = minesMultiplier(mines, picks);
  const next = minesMultiplier(mines, picks + 1);

  const finish = (mult: number, win: number) => {
    setRows((r) => [{ time: new Date().toLocaleTimeString().slice(0, 5), bet: amount, mult, win }, ...r].slice(0, 10));
    setPlaying(false);
  };
  const start = () => {
    if (playing) {
      if (picks === 0) return;
      const win = Math.floor(amount * cur * 100) / 100;
      addBalance(win); finish(cur, win); return;
    }
    if (!trySpend(amount)) return;
    const s = new Set<number>();
    while (s.size < mines) s.add(Math.floor(Math.random() * 25));
    setBombs(s); setOpen(new Set()); setBoom(null); setPlaying(true);
  };
  const tap = (i: number) => {
    if (!playing || open.has(i)) return;
    if (bombs.has(i)) { setBoom(i); finish(0, 0); return; }
    const o = new Set(open); o.add(i); setOpen(o);
    if (o.size === 25 - mines) { const m = minesMultiplier(mines, o.size); const w = amount * m; addBalance(w); finish(m, w); }
  };
  const ended = !playing && (boom !== null || open.size > 0);

  return (
    <div className="app-frame bg-ink pb-24">
      <div className="flex items-center justify-between px-3 py-2">
        <Link to="/" aria-label="Back" className="grid size-8 place-items-center rounded-full border-2 border-cash bg-ink-3 text-xs">←</Link>
        <Logo className="text-base" />
        <span className="flex items-center gap-1 rounded-full bg-ink-3 px-2 py-1 text-sm font-bold text-win">₹ {fmt(balance)} <Plus className="size-4 rounded-full bg-win text-ink" /></span>
      </div>
      <div className="flex items-center gap-2 overflow-hidden px-3 text-xs">
        <div className="flex-1 overflow-hidden whitespace-nowrap"><p className="animate-marquee">Rahul J. won <b className="text-cash">₹1867</b> (4.80x) · Varun C. won <b className="text-cash">₹4863</b> (2.66x) · Priya S. won <b className="text-cash">₹922</b> (1.42x)</p></div>
        <HelpCircle className="size-6 rounded-full bg-ink-3 p-1" /><Volume2 className="size-6 rounded-full bg-win/20 p-1 text-win" />
      </div>
      <div className="mx-2 mt-2 flex items-center justify-between rounded-xl bg-win px-3 py-2.5 font-extrabold text-ink">
        <label className="flex items-center gap-2">Mines:
          <select disabled={playing} value={mines} onChange={(e) => setMines(Number(e.target.value))} className="rounded-md bg-win-dark px-2 py-1 text-foreground">
            {Array.from({ length: 24 }, (_, i) => i + 1).map((n) => <option key={n} value={n}>{n}</option>)}
          </select>
        </label>
        <span className="rounded-full bg-ink/20 px-3 py-1 text-sm">Next: {next.toFixed(2)}x</span>
      </div>

      <div className={`mx-2 mt-2 grid grid-cols-5 gap-2 rounded-xl bg-ink-2 p-2 ${boom !== null ? "animate-shake" : ""}`}>
        {Array.from({ length: 25 }, (_, i) => {
          const isOpen = open.has(i);
          const reveal = ended && !isOpen;
          const isBomb = bombs.has(i);
          return (
            <button key={i} onClick={() => tap(i)} aria-label={`Tile ${i + 1}`}
              className={`grid aspect-square place-items-center rounded-lg border border-foreground/5 transition-all duration-200 ${isOpen ? "bg-win/20" : boom === i ? "bg-lose/40" : "bg-ink-3 hover:brightness-125 active:scale-90"}`}>
              {isOpen && <Gem className="size-8 animate-pop fill-win/40 text-win" />}
              {reveal && (isBomb ? <Bomb className={`size-7 animate-pop text-lose ${boom === i ? "" : "opacity-50"}`} /> : <Gem className="size-6 animate-pop text-win opacity-30" />)}
            </button>
          );
        })}
      </div>

      <div className="mx-2 mt-2 flex gap-2 rounded-xl bg-ink-2 p-2">
        <div className="flex-1">
          <div className="flex items-center justify-between rounded-full bg-ink px-3 py-1.5 font-bold">
            <button disabled={playing} onClick={() => setAmount(Math.max(1, amount - 10))}>−</button>{amount}<button disabled={playing} onClick={() => setAmount(amount + 10)}>+</button>
          </div>
          <div className="mt-1.5 grid grid-cols-4 gap-1 text-xs font-bold">
            {[10, 50, 500, 5000].map((v) => <button key={v} disabled={playing} onClick={() => setAmount(v)} className="rounded-md bg-ink-3 py-1.5">{v === 5000 ? "5k" : v}</button>)}
          </div>
        </div>
        <button onClick={start} className={`flex w-28 flex-col items-center justify-center rounded-xl font-bold transition active:scale-95 ${playing ? "bg-cash" : "bg-win"}`}>
          <span className="text-xs">{playing ? "Cash Out" : "Bet"}</span>
          <span className="text-lg">{(playing ? amount * cur : amount).toFixed(2)}₹</span>
        </button>
      </div>
      {boom !== null && <p className="mt-2 animate-pop text-center font-bold text-lose">Boom! Mine mil gayi 💥</p>}

      <div className="mx-2 mt-2 rounded-xl bg-ink-2 p-3 text-xs">
        <p className="text-center text-sm font-extrabold">MY BETS</p>
        <div className="mt-2 grid grid-cols-4 text-muted-foreground"><span>TIME</span><span>BET</span><span>MULT</span><span className="text-right">WIN</span></div>
        {rows.length === 0 ? <p className="py-4 text-center text-muted-foreground">No games yet</p> : rows.map((r, i) => (
          <div key={i} className="mt-1 grid grid-cols-4"><span>{r.time}</span><span>{r.bet}</span><span>{r.mult.toFixed(2)}x</span><span className={`text-right ${r.win ? "text-win" : "text-lose"}`}>{r.win.toFixed(2)}</span></div>
        ))}
      </div>

      <button aria-label="Support" className="fixed bottom-20 right-[max(1rem,calc(50%-200px))] grid size-12 place-items-center rounded-full bg-gold text-gold-foreground"><Headphones className="size-6" /></button>
      <nav className="fixed bottom-0 left-1/2 grid w-full max-w-[430px] -translate-x-1/2 grid-cols-4 bg-ink-2 py-2 text-[10px] font-bold text-muted-foreground">
        {[["GAMES", Gamepad2], ["INVITE", UserPlus], ["WALLET", Wallet], ["PROFILE", User]].map(([l, I]) => { const Ic = I as typeof User; return <Link key={l as string} to="/" className="flex flex-col items-center gap-1"><Ic className="size-5" />{l as string}</Link>; })}
      </nav>
    </div>
  );
}
