import cloudsAsset from "@/assets/clouds.svg";
import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { History, ChevronLeft } from "lucide-react";
import jetGuy from "@/assets/lucky-jet-guy.png";
import cover from "@/assets/cover-luckyjet.jpg";
import { useCrashRound, useCrashBet, useFakeBets, type Phase } from "@/lib/crash";
import { useBalance, fmt } from "@/lib/wallet";

export const Route = createFileRoute("/lucky-jet")({
  head: () => ({
    meta: [
      { title: "Lucky Jet – Lotus365" },
      { name: "description", content: "Fly with Lucky Joe and cash out before he flies away." },
      { property: "og:title", content: "Lucky Jet – Lotus365" },
      { property: "og:description", content: "Jetpack crash game with live bets." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: LuckyJetPage,
});

function LuckyJetPage() {
  const [pct, setPct] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setPct((p) => Math.min(100, p + 4)), 50);
    return () => clearInterval(t);
  }, []);
  if (pct < 100)
    return (
      <div className="app-frame relative flex flex-col items-center justify-end bg-jet-bg pb-16">
        <img src={cover} alt="" className="absolute inset-0 h-full w-full object-cover" />
        <div className="relative h-2 w-64 overflow-hidden rounded-full bg-foreground/20"><div className="h-full bg-cash" style={{ width: `${pct}%` }} /></div>
        <p className="relative mt-2 text-sm font-bold">{pct}%</p>
      </div>
    );
  return <LuckyJet />;
}

function LuckyJet() {
  const balance = useBalance();
  const g = useCrashRound();
  const bets = useFakeBets(g.round, g.mult, g.phase);
  const [showHist, setShowHist] = useState(false);
  // Video: jet shoots in from bottom-left in ~1.2s, then hovers top-right with a soft bob
  // Video: ~0.5s fast dash to top-right (overshoot), ~0.4s settle back, then hover
  const ms = g.elapsed;
  const lerp = (a: number, b: number, k: number) => a + (b - a) * k;
  let x: number, y: number;
  if (ms < 500) { const k = 1 - Math.pow(1 - ms / 500, 2); x = lerp(-12, 76, k); y = lerp(112, 14, k); }
  else if (ms < 900) { const k0 = (ms - 500) / 400; const k = k0 * k0 * (3 - 2 * k0); x = lerp(76, 60, k); y = lerp(14, 30, k); }
  else { x = 60; y = 30; }
  const t = ms >= 900 ? 1 : 0;
  const multTop = ms < 500 ? 28 : ms < 900 ? lerp(28, 50, (ms - 500) / 400) : 50;

  return (
    <div className="app-frame bg-jet-bg pb-6">
      <div className="flex items-center justify-between px-3 py-3">
        <Link to="/" aria-label="Back" className="flex items-center gap-1"><ChevronLeft className="size-5" /><span className="text-xl font-black italic tracking-tight text-jet-2">LUCKY<span className="text-foreground">JET</span></span></Link>
        <span className="rounded-lg bg-jet-card px-3 py-1.5 text-sm font-bold">{fmt(balance)} ₹</span>
      </div>
      <div className="flex items-center gap-2 overflow-hidden px-3 text-xs font-bold">
        <button aria-label="History" onClick={() => setShowHist((v) => !v)} className="rounded-full border border-jet/40 bg-jet-card p-1"><History className="size-3.5" /></button>
        {g.history.slice(0, 6).map((h, i) => <span key={i} className="animate-pop rounded-full border border-jet/40 bg-jet-card px-2.5 py-1">{h.toFixed(2)}x</span>)}
      </div>
      {showHist && (
        <div className="mx-3 mt-2 rounded-xl bg-jet-card p-3">
          <p className="mb-2 text-xs font-bold">HISTORY OF ROUNDS</p>
          <div className="flex flex-wrap gap-1.5 text-xs">{g.history.map((h, i) => <span key={i} className="rounded-full border border-jet/40 px-2 py-0.5">{h.toFixed(2)}x</span>)}</div>
        </div>
      )}

      <div className="relative mx-3 mt-3 h-52 overflow-hidden rounded-2xl border border-jet/20 bg-jet-night">
        <div className={`absolute inset-0 bg-jet-stars ${g.phase === "flying" ? "animate-jet-run-slow" : ""}`} />
        <div className={`absolute inset-x-0 bottom-0 h-[70px] bg-repeat-x bg-bottom ${g.phase === "flying" ? "animate-jet-clouds" : ""}`} style={{ backgroundImage: `url(${cloudsAsset})`, backgroundSize: "217px 70px" }} />
        {g.phase === "waiting" && (
          <div className="absolute inset-0 flex flex-col items-center justify-center gap-2">
            <JetLoader />
            <p className="text-center text-sm font-extrabold leading-tight text-foreground/80">WAITING FOR THE<br />NEXT ROUND</p>
            <div className="mt-1 h-1.5 w-40 overflow-hidden rounded-full bg-foreground/10"><div className="h-full rounded-full bg-jet-bet transition-[width] duration-100 ease-linear" style={{ width: `${(1 - g.waitLeft / 5000) * 100}%` }} /></div>
          </div>
        )}
        {g.phase === "flying" && (
          <>
            <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 h-full w-full">
              <defs><linearGradient id="jf" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="var(--jet-2)" stopOpacity=".35" /><stop offset="1" stopColor="var(--jet-2)" stopOpacity="0" /></linearGradient></defs>
              <path d={`M0,100 Q${x * 0.55},${100 - (100 - y) * 0.15} ${x + 6},${y + 6} L${x + 6},100 Z`} fill="url(#jf)" />
              <path d={`M0,100 Q${x * 0.55},${100 - (100 - y) * 0.15} ${x + 6},${y + 6}`} className="fill-none stroke-jet-2" strokeWidth="2" vectorEffect="non-scaling-stroke" />
            </svg>
            <img src={jetGuy} alt="Lucky Joe" className={`absolute w-24 ${t >= 1 ? "animate-jet-bob" : "-translate-y-1/2"}`} draggable={false} style={{ left: `${x}%`, top: `${y}%` }} />
            <p style={{ top: `${multTop}%` }} className="text-jet-grad absolute left-4 -translate-y-1/2 text-6xl font-black tracking-tight">x{g.mult.toFixed(2)}</p>
          </>
        )}
        {g.phase === "crashed" && (
          <>
            <img src={jetGuy} alt="" className="absolute w-24 -translate-y-1/2 animate-fly-away" style={{ left: "58%", top: "35%" }} />
            <div className="absolute inset-0 flex animate-pop flex-col items-center justify-center">
              <p className="text-jet-grad text-6xl font-black tracking-tight">x{g.mult.toFixed(2)}</p>
              <p className="mt-1 text-sm font-black tracking-[0.3em]">FLEW AWAY</p>
            </div>
          </>
        )}
      </div>

      <JetBet phase={g.phase} mult={g.mult} />
      <JetBet phase={g.phase} mult={g.mult} />

      <div className="mx-3 mt-3 grid grid-cols-2 rounded-xl bg-jet-card p-1 text-sm"><span className="rounded-lg bg-jet-bg py-2 text-center font-bold">All</span><span className="py-2 text-center text-muted-foreground">My</span></div>
      <p className="mx-3 mt-3 text-xs text-muted-foreground">Total bets:</p>
      <p className="mx-3 font-bold">{(3448 + g.round * 7).toLocaleString()}</p>
      {bets.map((b, i) => (
        <div key={b.name} className="mx-3 mt-1.5 flex items-center gap-2 rounded-lg bg-jet-card px-2 py-2 text-xs">
          <span className={`grid size-7 place-items-center rounded-md font-bold ${["bg-lose", "bg-jet", "bg-cash", "bg-win"][i % 4]}`}>{b.name.slice(0, 2).toUpperCase()}</span>
          <span className="w-20 text-muted-foreground">{b.name}</span>
          <span className="w-16 font-bold">{b.bet.toFixed(2)}</span>
          <span className="rounded-full bg-jet/30 px-2 py-0.5 text-pill-blue">{b.cashed ? b.out.toFixed(2) : "0.00"}x</span>
          <span className="ml-auto font-bold text-cash">{b.cashed ? `${(b.bet * b.out).toFixed(2)} ₹` : "-"}</span>
        </div>
      ))}
    </div>
  );
}

function JetBet({ phase, mult }: { phase: Phase; mult: number }) {
  const b = useCrashBet(phase, mult);
  const label = b.status === "queued" ? "CANCEL" : b.status === "active" && phase === "flying" ? `TAKE ${(b.amount * mult).toFixed(2)}` : "BET";
  const cls = b.status === "queued" ? "bg-lose" : b.status === "active" && phase === "flying" ? "bg-cash" : "bg-jet-bet";
  return (
    <div className="mx-3 mt-3 rounded-2xl bg-jet-card p-3">
      <div className="flex items-center gap-4 text-xs text-muted-foreground">
        <label className="flex items-center gap-1.5"><input type="checkbox" className="accent-jet" /> Autobet</label>
        <label className="flex items-center gap-1.5"><input type="checkbox" className="accent-jet" /> Autowithdrawal</label>
        <span className="ml-auto rounded bg-jet-bg px-2 py-0.5 font-bold text-foreground">x 2.00</span>
      </div>
      <div className="mt-3 flex gap-3">
        <div className="w-1/2">
          <div className="flex items-center justify-between rounded-lg bg-jet-bg px-2 py-2 text-lg font-bold">
            <button onClick={() => b.setAmount(Math.max(1, b.amount - 1))} className="size-7 rounded bg-jet-card text-sm">-</button>
            {b.amount}
            <button onClick={() => b.setAmount(b.amount + 1)} className="size-7 rounded bg-jet-card text-sm">+</button>
          </div>
          <div className="mt-1.5 grid grid-cols-4 gap-1 text-[10px] text-muted-foreground">
            {[[425, "425"], [2100, "2.1K"], [4200, "4.2K"], [8500, "8.5K"]].map(([v, l]) => <button key={l} onClick={() => b.setAmount(v as number)} className="rounded bg-jet-bg py-1">{l}</button>)}
          </div>
        </div>
        <button onClick={b.press} className={`flex-1 rounded-xl text-xl font-black ${cls} transition active:scale-95`}>{label}</button>
      </div>
      {b.lastWin && <p className="mt-2 animate-pop text-center text-sm font-bold text-cash">+{b.lastWin.toFixed(2)} ₹</p>}
    </div>
  );
}

/** Loading icon from the video: small jetpack inside two spinning broken rings */
function JetLoader() {
  return (
    <div className="relative size-14 text-jet-2">
      <svg viewBox="0 0 56 56" className="absolute inset-0 size-full animate-spin [animation-duration:1.6s]">
        <circle cx="28" cy="28" r="25" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeDasharray="34 10 18 12 40 43" />
      </svg>
      <svg viewBox="0 0 56 56" className="absolute inset-0 size-full animate-spin [animation-direction:reverse] [animation-duration:2.4s]">
        <circle cx="28" cy="28" r="19" fill="none" stroke="currentColor" strokeOpacity=".7" strokeWidth="2" strokeLinecap="round" strokeDasharray="22 14 30 54" />
      </svg>
      <svg viewBox="0 0 56 56" className="absolute inset-0 size-full">
        <g fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinejoin="round">
          <rect x="20" y="18" width="7" height="14" rx="3" /><rect x="29" y="18" width="7" height="14" rx="3" />
          <path d="M23.5 18v-2a4.5 4.5 0 0 1 9 0v2" />
        </g>
        <path d="M23.5 34l-1.5 4h3zM32.5 34l-1.5 4h3z" fill="currentColor" className="animate-pulse" />
      </svg>
    </div>
  );
}
