import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { supabaseExt as supabase } from "@/integrations/external-supabase/client";
import { Header } from "@/components/site/Header";
import { Footer } from "@/components/site/Footer";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Minus, Plus, Zap, ShieldCheck, Mail, CheckCircle2 } from "lucide-react";
import { formatBDT } from "@/lib/format";
import heroLovable from "@/assets/hero-lovable.png";
import TrueFocus from "@/components/site/TrueFocus";
import { LovableMark } from "@/components/site/LovableMark";
import ClickSpark from "@/components/site/ClickSpark";

export const Route = createFileRoute("/")({ component: Index });

function Index() {
  const { data: packages } = useQuery({
    queryKey: ["public-packages"],
    queryFn: async () => {
      const { data, error } = await supabase.from("packages").select("*").eq("is_active", true).order("sort_order");
      if (error) throw error;
      return data;
    },
  });

  return (
    <ClickSpark sparkColor="oklch(0.68 0.2 295)" sparkSize={18} sparkRadius={40} sparkCount={10} duration={500}>
      <div className="min-h-screen flex flex-col bg-background">
        <Header />
        <main className="flex-1">
          <Hero />
          <PackagesSection packages={packages ?? []} />
          <HowItWorks />
          <FAQ />
        </main>
        <Footer />
      </div>
    </ClickSpark>
  );
}

function Hero() {
  return (
    <section className="relative overflow-hidden">
      <div className="absolute inset-0 bg-gradient-to-b from-[oklch(0.97_0.04_295)] via-background to-background -z-10" />
      <div className="absolute top-20 -left-20 w-72 h-72 rounded-full bg-primary/20 blur-3xl -z-10" />
      <div className="absolute top-40 right-0 w-96 h-96 rounded-full bg-[oklch(0.7_0.2_320/0.2)] blur-3xl -z-10" />
      <div className="container max-w-7xl mx-auto px-4 pt-12 pb-8 md:pt-16 md:pb-10 grid lg:grid-cols-12 gap-8 items-center">
        <div className="lg:col-span-7 order-2 lg:order-1 text-center lg:text-left">
          <div className="text-4xl md:text-6xl lg:text-7xl font-extrabold tracking-tight leading-[1.15] text-foreground flex flex-col items-center lg:items-start">
            <div
              style={{
                ["--gradient-primary" as any]:
                  "linear-gradient(90deg, oklch(0.7 0.24 25), oklch(0.62 0.26 10), oklch(0.58 0.24 355))",
              }}
            >
              <TrueFocus
                sentence="Loveable Credit"
                borderColor="oklch(0.62 0.24 15)"
                glowColor="oklch(0.72 0.22 25 / 0.7)"
                animationDuration={0.6}
                pauseBetweenAnimations={1.2}
                blurAmount={4}
              />
            </div>
            <span className="block mt-3 bg-gradient-to-r from-primary to-[oklch(0.68_0.2_295)] bg-clip-text text-transparent leading-[1.4] pb-2">কিনুন সেরা দামে</span>
          </div>
          <p className="mt-6 text-base md:text-lg text-muted-foreground max-w-xl leading-[1.8] mx-auto lg:mx-0">
            Best Value For Money
          </p>
          <div className="mt-8 flex flex-col sm:flex-row flex-wrap gap-4 justify-center lg:justify-start items-stretch sm:items-center w-full max-w-sm mx-auto lg:mx-0">
            <Button asChild size="lg" className="bg-gradient-to-r from-primary to-[oklch(0.68_0.2_295)] text-primary-foreground shadow-lg hover:opacity-90 rounded-full px-10 h-14 text-lg font-semibold w-full sm:w-auto">
              <a href="#packages">Order Now →</a>
            </Button>
            <Button asChild size="lg" variant="outline" className="rounded-full px-10 h-14 text-lg font-semibold w-full sm:w-auto">
              <a href="https://wa.me/8801813896400" target="_blank" rel="noopener noreferrer">Contact with us</a>
            </Button>
          </div>
          <div className="mt-10 flex flex-wrap gap-6 text-sm text-muted-foreground justify-center lg:justify-start">
            <div className="flex items-center gap-2"><Zap className="size-4 text-primary" /> Instant</div>
            <div className="flex items-center gap-2"><ShieldCheck className="size-4 text-primary" /> Trusted</div>
            <div className="flex items-center gap-2"><Mail className="size-4 text-primary" /> Delivery on Personal Email</div>
          </div>
        </div>
        <div className="lg:col-span-5 relative order-1 lg:order-2">
          <HeroVisual />
        </div>
      </div>
    </section>
  );
}

function HeroVisual() {
  return (
    <div className="relative w-full aspect-square max-w-[560px] mx-auto">
      <div className="absolute -top-8 -right-6 w-56 h-56 rounded-full bg-gradient-to-br from-primary/40 to-[oklch(0.7_0.2_320/0.3)] blur-3xl" />
      <div className="absolute bottom-10 -left-8 w-48 h-48 rounded-full bg-[oklch(0.85_0.12_310/0.5)] blur-3xl" />

      {/* Gradient pool under the character's feet */}
      <div className="absolute bottom-[6%] left-1/2 -translate-x-1/2 w-[70%] h-[18%] rounded-[50%] bg-gradient-to-r from-primary to-[oklch(0.68_0.2_295)] blur-2xl opacity-80 z-0" />
      <div className="absolute bottom-[8%] left-1/2 -translate-x-1/2 w-[55%] h-[10%] rounded-[50%] bg-gradient-to-r from-primary to-[oklch(0.68_0.2_295)] blur-xl opacity-90 z-0" />

      <img
        src={heroLovable}
        alt="Lovable Credit mascot"
        width={1024}
        height={1024}
        className="relative z-10 w-full h-full object-contain drop-shadow-2xl"
      />

      {/* Speech bubble from cartoon's head — glassmorphism, positioned above to avoid covering face */}
      <div
        className="absolute -top-4 right-0 sm:-top-6 sm:right-2 md:-right-4 z-30 origin-bottom-left animate-[bubblePop_0.9s_cubic-bezier(0.34,1.56,0.64,1)_0.3s_both]"
      >
        <div className="relative rounded-3xl px-5 py-3 sm:px-6 sm:py-4 max-w-[220px] sm:max-w-[260px]
          bg-white/30 backdrop-blur-xl border border-white/50
          shadow-[0_8px_32px_0_oklch(0.5_0.22_285/0.35),inset_0_1px_0_0_rgba(255,255,255,0.6)]
          ring-1 ring-primary/20">
          <p className="text-sm sm:text-base font-bold text-foreground text-center leading-tight drop-shadow-sm">
            Full Time Replacement
            <span className="block mt-1.5 text-xl sm:text-2xl font-extrabold bg-gradient-to-r from-[oklch(0.7_0.24_35)] via-[oklch(0.62_0.26_15)] to-[oklch(0.58_0.24_355)] bg-clip-text text-transparent uppercase tracking-wider animate-[pulse_2s_ease-in-out_infinite]">
              Guarantee
            </span>
          </p>
          {/* Glass tail pointing down toward cartoon's head */}
          <div className="absolute -bottom-[10px] left-8 w-5 h-5 rotate-45 bg-white/30 backdrop-blur-xl border-r border-b border-white/50" />
        </div>
      </div>

      {/* Floating Lovable logo */}
      <div className="absolute top-2 left-0 md:top-6 md:-left-2 z-20 animate-[float_4s_ease-in-out_infinite] drop-shadow-2xl">
        <LovableMark size={110} />
      </div>
      <div className="absolute bottom-16 right-0 md:bottom-20 md:right-2 z-20 animate-[float_5s_ease-in-out_infinite_0.6s] drop-shadow-2xl">
        <LovableMark size={80} />
      </div>
    </div>
  );
}

function PackagesSection({ packages }: { packages: Array<{ id: string; name: string; credits: number; price_bdt: number; description: string | null }> }) {
  return (
    <section id="packages" className="py-10 md:py-16 bg-secondary/30">
      <div className="container max-w-7xl mx-auto px-4">
        <div className="text-center max-w-2xl mx-auto mb-12">
          <h2 className="text-3xl md:text-4xl font-bold tracking-tight">Packages</h2>
          <p className="mt-3 text-muted-foreground">Quantity বাড়ালে credit ও price দুটোই বাড়বে।</p>
        </div>
        <div className="flex flex-wrap justify-center gap-6 max-w-5xl mx-auto">
          {packages.map((p) => (
            <div key={p.id} className="w-full sm:w-[340px]">
              <PackageCard pkg={p} />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function PackageCard({ pkg }: { pkg: { id: string; name: string; credits: number; price_bdt: number; description: string | null } }) {
  const navigate = useNavigate();
  const [qty, setQty] = useState(1);
  const total = pkg.price_bdt * qty;
  const totalCredits = pkg.credits * qty;

  return (
    <div className="relative pt-10 pl-6">
      {/* Logo bursting out of top-left corner */}
      <div className="absolute -top-2 -left-2 z-20 drop-shadow-xl animate-[float_4s_ease-in-out_infinite]">
        <LovableMark size={90} />
      </div>
      <Card className="p-7 pt-12 rounded-3xl border-2 border-primary/20 bg-card shadow-[0_20px_50px_-15px_oklch(0.5_0.22_285/0.25)] hover:shadow-[0_25px_60px_-15px_oklch(0.5_0.22_285/0.4)] transition-all hover:-translate-y-1 hover:border-primary/40 relative overflow-hidden text-center">
        <div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-br from-primary/30 to-transparent rounded-bl-full -z-0" />
        <div className="relative flex flex-col items-center">
          <h3 className="text-2xl font-bold">{pkg.name}</h3>
          <p className="text-sm text-muted-foreground mt-2 min-h-[2.5rem]">{pkg.description}</p>

          <div className="mt-6 flex items-baseline gap-2 justify-center">
            <span className="text-5xl font-extrabold bg-gradient-to-r from-primary to-[oklch(0.68_0.2_295)] bg-clip-text text-transparent">{totalCredits}</span>
            <span className="text-muted-foreground font-medium">Credits</span>
          </div>
          <div className="text-2xl font-bold mt-1">{formatBDT(total)}</div>

          <div className="mt-6 w-full flex items-center justify-between bg-secondary/60 rounded-full p-1.5">
            <Button size="icon" variant="ghost" className="rounded-full h-9 w-9" onClick={() => setQty((q) => Math.max(1, q - 1))} disabled={qty <= 1}>
              <Minus className="size-4" />
            </Button>
            <div className="text-sm font-semibold">Qty: {qty}</div>
            <Button size="icon" variant="ghost" className="rounded-full h-9 w-9" onClick={() => setQty((q) => Math.min(20, q + 1))}>
              <Plus className="size-4" />
            </Button>
          </div>

          <Button
            className="w-full mt-5 rounded-full bg-gradient-to-r from-primary to-[oklch(0.68_0.2_295)] text-primary-foreground shadow-md hover:opacity-90 h-11 text-base font-semibold"
            onClick={() => navigate({ to: "/order/$packageId", params: { packageId: pkg.id }, search: { qty } })}
          >
            Order Now
          </Button>
        </div>
      </Card>
    </div>
  );
}

function HowItWorks() {
  const steps = [
    { num: 1, title: "Package বেছে নিন", desc: "205 / 410 / 615 ... যত খুশি quantity" },
    { num: 2, title: "bKash / Nagad payment", desc: "Send Money করে transaction ID দিন" },
    { num: 3, title: "Email এ credit", desc: "Verify হওয়ার পর সরাসরি ইমেইলে ডেলিভারি" },
  ];
  return (
    <section id="how-it-works" className="py-16 md:py-24">
      <div className="container max-w-5xl mx-auto px-4">
        <div className="text-center mb-12">
          <h2 className="text-3xl md:text-4xl font-bold tracking-tight">How it works</h2>
        </div>
        <div className="grid md:grid-cols-3 gap-6">
          {steps.map((s) => (
            <Card key={s.num} className="p-7 rounded-2xl text-center bg-card border-border/60">
              <div className="mx-auto w-12 h-12 rounded-full bg-gradient-to-br from-primary to-[oklch(0.68_0.2_295)] text-primary-foreground flex items-center justify-center font-bold text-lg shadow-md">{s.num}</div>
              <h3 className="mt-4 font-semibold text-lg">{s.title}</h3>
              <p className="mt-2 text-sm text-muted-foreground">{s.desc}</p>
            </Card>
          ))}
        </div>
        <div className="mt-12 flex flex-col items-center gap-3 text-muted-foreground">
          <LovableMark size={64} />
          <span className="text-sm">Genuine Lovable.dev credits, delivered straight to your account</span>
        </div>
      </div>
    </section>
  );
}

function FAQ() {
  const faqs = [
    { q: "Credit কতক্ষণে পাবো?", a: "Payment verify হওয়ার 5–30 মিনিটের মধ্যে ইমেইলে চলে যায়।" },
    { q: "কোন payment method support করেন?", a: "bKash ও Nagad — personal এবং merchant দুটোই।" },
    { q: "Bulk order এ discount আছে?", a: "হ্যাঁ, 5+ package নিলে WhatsApp এ মেসেজ করুন।" },
    { q: "Refund policy কী?", a: "Delivery না হলে 100% refund। Delivery এর পর refund নেই।" },
  ];
  return (
    <section id="faq" className="py-16 md:py-24 bg-secondary/30">
      <div className="container max-w-3xl mx-auto px-4">
        <div className="flex flex-col items-center gap-3 mb-10">
          <LovableMark size={56} />
          <h2 className="text-3xl md:text-4xl font-bold tracking-tight text-center">FAQ</h2>
        </div>
        <div className="space-y-3">
          {faqs.map((f, i) => (
            <Card key={i} className="p-5 rounded-xl border-border/60">
              <div className="flex items-start gap-3">
                <CheckCircle2 className="size-5 text-primary mt-0.5 shrink-0" />
                <div>
                  <div className="font-semibold">{f.q}</div>
                  <p className="text-sm text-muted-foreground mt-1">{f.a}</p>
                </div>
              </div>
            </Card>
          ))}
        </div>
      </div>
    </section>
  );
}
