import { Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import {
  Gamepad2, Server, Globe, Bot, ArrowRight, Zap, Shield,
  Clock, Cpu, MapPin, Activity, Plus, Minus,
} from "lucide-react";
import minecraftHero from "@/assets/hero/minecraft.jpg";
import vpsHero from "@/assets/hero/vps.jpg";
import webHero from "@/assets/hero/web.jpg";
import botHero from "@/assets/hero/bot.jpg";
import { useCurrency } from "@/lib/currency";
import { LocationBanners } from "@/components/LocationBanners";

type TabKey = "minecraft" | "vps" | "web" | "bot";

const tabs: { key: TabKey; label: string; icon: typeof Gamepad2; href: string; title: string; subtitle: string; priceUsd: number; bg: string }[] = [
  {
    key: "minecraft", label: "Minecraft Hosting", icon: Gamepad2, href: "/minecraft",
    title: "Minecraft Server Hosting",
    subtitle: "High-performance Minecraft server hosting with low latency, DDoS protection, and 24/7 support.",
    priceUsd: 20 / 83, bg: minecraftHero,
  },
  {
    key: "vps", label: "VPS Hosting", icon: Server, href: "/vps-hosting",
    title: "VPS Server Hosting",
    subtitle: "Full root access with dedicated resources, NVMe storage and AMD EPYC™ processors.",
    priceUsd: 4, bg: vpsHero,
  },
  {
    key: "web", label: "Web Hosting", icon: Globe, href: "/web-hosting",
    title: "Web Hosting",
    subtitle: "Lightning-fast web hosting with cPanel, free SSL and unlimited bandwidth.",
    priceUsd: 1.49, bg: webHero,
  },
  {
    key: "bot", label: "Bot Hosting", icon: Bot, href: "/bot-hosting",
    title: "Discord Bot Hosting",
    subtitle: "24/7 uptime for your Discord bots with full Node.js, Python and Java support.",
    priceUsd: 1, bg: botHero,
  },
];

const ROTATION: TabKey[] = ["minecraft", "vps", "bot"];

export function HeroSection() {
  const [active, setActive] = useState<TabKey>("minecraft");
  const [paused, setPaused] = useState(false);
  const tab = tabs.find((t) => t.key === active)!;
  const { format } = useCurrency();

  useEffect(() => {
    if (paused) return;
    const id = setInterval(() => {
      setActive((cur) => {
        const idx = ROTATION.indexOf(cur);
        const next = idx === -1 ? 0 : (idx + 1) % ROTATION.length;
        return ROTATION[next];
      });
    }, 8000);
    return () => clearInterval(id);
  }, [paused]);

  return (
    <section className="relative w-full overflow-hidden">
      {/* Crossfade background stack */}
      <div className="absolute inset-0">
        {tabs.map((t) => (
          <img
            key={t.key}
            src={t.bg}
            alt=""
            className={`absolute inset-0 h-full w-full object-cover transition-opacity duration-1000 ${
              active === t.key ? "opacity-100" : "opacity-0"
            }`}
          />
        ))}
      </div>
      <div className="absolute inset-0 bg-gradient-to-b from-background/80 via-background/65 to-background" />

      <div className="relative mx-auto flex min-h-[88vh] max-w-7xl flex-col items-center justify-center px-4 py-24 text-center">
        <div className="mb-6 inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-4 py-1.5 text-xs backdrop-blur-md">
          <tab.icon className="h-3.5 w-3.5" />
          <span>{tab.label}</span>
        </div>

        <h1 className="mb-5 max-w-4xl text-4xl font-extrabold leading-tight tracking-tight md:text-6xl lg:text-7xl">
          {tab.title}
        </h1>
        <p className="mx-auto mb-8 max-w-2xl text-base text-muted-foreground md:text-lg">
          {tab.subtitle}
        </p>

        <p className="mb-7 text-xl font-semibold">
          Starting at <span className="text-success">{format(tab.priceUsd)}</span>
          <span className="text-muted-foreground font-normal">/mo</span>
        </p>

        <Link
          to={tab.href}
          className="mb-12 inline-flex items-center gap-2 rounded-xl gradient-violet px-7 py-3.5 text-sm font-semibold text-white shadow-xl shadow-primary/30 transition hover:shadow-primary/50"
        >
          Get Started <ArrowRight className="h-4 w-4" />
        </Link>

        {/* Tab pills */}
        <div className="flex flex-wrap items-center justify-center gap-2 rounded-2xl border border-white/10 bg-black/40 p-1.5 backdrop-blur-md">
          {tabs.map((t) => (
            <button
              key={t.key}
              onClick={() => { setActive(t.key); setPaused(true); }}
              className={`inline-flex items-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium transition ${
                active === t.key
                  ? "bg-white/10 text-white ring-1 ring-white/15"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              <t.icon className="h-4 w-4" />
              {t.label}
            </button>
          ))}
        </div>

        {/* Trust badges */}
        <div className="mt-8 flex flex-wrap items-center justify-center gap-6 text-sm text-muted-foreground">
          <span className="inline-flex items-center gap-2">
            <span className="h-1.5 w-1.5 rounded-full bg-success" />
            99.9% Uptime
          </span>
          <span className="inline-flex items-center gap-2">
            <span className="h-1.5 w-1.5 rounded-full bg-cyan-400" />
            DDoS Protected
          </span>
          <span className="inline-flex items-center gap-2">
            <span className="h-1.5 w-1.5 rounded-full bg-primary" />
            24/7 Support
          </span>
        </div>
      </div>
    </section>
  );
}

const features = [
  { icon: Zap, title: "Instant Setup", desc: "Deployment in under 60 seconds. Automated provisioning the moment your payment is confirmed." },
  { icon: Shield, title: "DDoS Protection", desc: "Enterprise-grade mitigation capable of filtering up to 17Tbps+. Stay online during the most intense attacks." },
  { icon: Activity, title: "99.9% Uptime", desc: "Tier 3+ certified data centers with redundant power, cooling and network links." },
  { icon: Clock, title: "24/7 Support", desc: "Real-world experts at your service. Average response time under 15 minutes, day or night." },
  { icon: Cpu, title: "Powerful Hardware", desc: "Latest-gen AMD EPYC™ processors and enterprise NVMe Gen4 storage for maximum performance." },
  { icon: MapPin, title: "Global Locations", desc: "Globally distributed network with premium peerage for ultra-low latency gaming traffic." },
];

export function FeaturesSection() {
  return (
    <section className="mx-auto max-w-7xl px-4 py-24">
      <div className="mb-14 text-center">
        <h2 className="text-3xl font-bold tracking-tight md:text-4xl">Cutting-Edge Features</h2>
        <p className="mt-3 text-muted-foreground">Discover unparalleled server performance and security.</p>
      </div>
      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
        {features.map((f) => (
          <div
            key={f.title}
            className="group rounded-2xl border border-white/5 bg-card/40 p-6 transition hover:border-primary/30 hover:bg-card/60"
          >
            <div className="mb-4 flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary ring-1 ring-primary/20 transition group-hover:scale-110">
              <f.icon className="h-5 w-5" />
            </div>
            <h3 className="mb-2 text-lg font-semibold">{f.title}</h3>
            <p className="text-sm leading-relaxed text-muted-foreground">{f.desc}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

export function ServicesSection() {
  const services = [
    { title: "Minecraft Hosting", desc: "Build, explore, and survive in blocky worlds.", href: "/minecraft", icon: Gamepad2 },
    { title: "VPS Hosting", desc: "Full root access with dedicated resources for developers.", href: "/vps-hosting", icon: Server },
    { title: "Web Hosting", desc: "Lightning-fast hosting with cPanel included.", href: "/web-hosting", icon: Globe },
    { title: "Bot Hosting", desc: "24/7 uptime for your Discord bots.", href: "/bot-hosting", icon: Bot },
  ];
  return (
    <section className="mx-auto max-w-7xl px-4 py-16">
      <div className="mb-12 text-center">
        <p className="mb-2 text-xs font-semibold uppercase tracking-[0.25em] text-primary">Beyond Gaming</p>
        <h2 className="text-3xl font-bold md:text-4xl">Your Complete Hosting Solution</h2>
      </div>
      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
        {services.map((s) => (
          <Link
            key={s.title}
            to={s.href}
            className="group relative overflow-hidden rounded-2xl border border-white/5 bg-card/40 p-6 transition hover:-translate-y-1 hover:border-primary/30"
          >
            <div className="mb-5 flex h-12 w-12 items-center justify-center rounded-xl gradient-violet shadow-lg shadow-primary/20">
              <s.icon className="h-6 w-6 text-white" />
            </div>
            <h3 className="mb-1.5 text-lg font-semibold">{s.title}</h3>
            <p className="text-sm text-muted-foreground">{s.desc}</p>
            <ArrowRight className="absolute right-5 top-5 h-4 w-4 text-muted-foreground transition group-hover:translate-x-1 group-hover:text-primary" />
          </Link>
        ))}
      </div>
    </section>
  );
}

/* ─────────────  Game grid section  ───────────── */

import minecraftCard from "@/assets/games/minecraft-hero-wide.jpg";
import rustCard from "@/assets/games/rust.jpg";
import arkCard from "@/assets/games/ark.jpg";
import fivemCard from "@/assets/games/fivem.jpg";

const games = [
  { name: "Minecraft", img: minecraftCard, href: "/minecraft", comingSoon: false },
  { name: "Rust", img: rustCard, href: "/game-hosting", comingSoon: true },
  { name: "ARK", img: arkCard, href: "/game-hosting", comingSoon: true },
  { name: "FiveM", img: fivemCard, href: "/game-hosting", comingSoon: true },
];

export function GamesSection() {
  return (
    <section className="mx-auto max-w-7xl px-4 py-24">
      <div className="mb-12 text-center">
        <p className="mb-2 text-xs font-semibold uppercase tracking-[0.25em] text-primary">Game Hosting</p>
        <h2 className="text-3xl font-bold md:text-4xl">Servers for every game</h2>
        <p className="mt-3 text-muted-foreground">Pre-configured panels, mod support and instant deployment.</p>
      </div>
      <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
        {games.map((g) => (
          <Link
            key={g.name}
            to={g.href}
            className="group relative aspect-[4/5] overflow-hidden rounded-2xl border border-white/5 transition hover:-translate-y-1 hover:border-primary/30"
          >
            <img src={g.img} alt={g.name} loading="lazy" className="absolute inset-0 h-full w-full object-cover transition group-hover:scale-105" />
            <div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/30 to-transparent" />
            {g.comingSoon && (
              <span className="absolute right-3 top-3 rounded-full bg-yellow-500/90 px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider text-black shadow-lg">
                Coming Soon
              </span>
            )}
            <div className="absolute inset-x-0 bottom-0 p-4">
              <h3 className="text-lg font-bold">{g.name}</h3>
              <span className="mt-1 inline-flex items-center gap-1 text-xs text-primary opacity-0 transition group-hover:opacity-100">
                {g.comingSoon ? "Soon" : "Explore"} <ArrowRight className="h-3 w-3" />
              </span>
            </div>
          </Link>
        ))}
      </div>
    </section>
  );
}

export function LocationsSection() {
  return (
    <section className="mx-auto max-w-7xl px-4 py-24">
      <div className="mb-10 text-center">
        <p className="mb-2 text-xs font-semibold uppercase tracking-[0.25em] text-primary">Global Network</p>
        <h2 className="text-3xl font-bold md:text-4xl">Locations around the world</h2>
        <p className="mt-3 text-muted-foreground">Premium peering for ultra-low latency, wherever your players are.</p>
      </div>
      <LocationBanners />
    </section>
  );
}

/* ─────────────  FAQ section  ───────────── */

const faqs = [
  { q: "How fast is server setup?", a: "Most servers are deployed automatically within 60 seconds of payment confirmation." },
  { q: "Do you offer DDoS protection?", a: "Yes — every plan includes enterprise-grade DDoS mitigation capable of filtering up to 17Tbps+." },
  { q: "Can I upgrade my plan later?", a: "Absolutely. You can upgrade resources any time from the panel; we prorate the difference automatically." },
  { q: "Which payment methods do you accept?", a: "We accept all major credit cards, UPI, PayPal and crypto." },
  { q: "Is there a money-back guarantee?", a: "Yes — we offer a 7-day refund window on most services. See our refund policy for full details." },
  { q: "Do you support custom mods and plugins?", a: "Yes. You get full file access via SFTP and a one-click installer for popular mods and plugins." },
];

export function FAQSection() {
  const [open, setOpen] = useState<number | null>(0);
  return (
    <section className="mx-auto max-w-4xl px-4 py-24">
      <div className="mb-10 text-center">
        <p className="mb-2 text-xs font-semibold uppercase tracking-[0.25em] text-primary">FAQ</p>
        <h2 className="text-3xl font-bold md:text-4xl">Frequently asked questions</h2>
      </div>
      <div className="space-y-3">
        {faqs.map((f, i) => {
          const isOpen = open === i;
          return (
            <div key={f.q} className="overflow-hidden rounded-2xl border border-white/5 bg-card/40">
              <button
                onClick={() => setOpen(isOpen ? null : i)}
                className="flex w-full items-center justify-between gap-4 px-5 py-4 text-left transition hover:bg-white/[0.02]"
              >
                <span className="text-base font-medium">{f.q}</span>
                {isOpen ? <Minus className="h-4 w-4 shrink-0 text-primary" /> : <Plus className="h-4 w-4 shrink-0 text-muted-foreground" />}
              </button>
              <div className={`grid transition-all duration-300 ${isOpen ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"}`}>
                <div className="overflow-hidden">
                  <p className="px-5 pb-5 text-sm leading-relaxed text-muted-foreground">{f.a}</p>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

/* ─────────────  CTA banner  ───────────── */

export function CTASection() {
  return (
    <section className="mx-auto max-w-7xl px-4 py-16">
      <div className="relative overflow-hidden rounded-3xl border border-white/10 bg-gradient-to-br from-primary/20 via-card/60 to-card p-10 text-center md:p-16">
        <div className="pointer-events-none absolute -left-20 -top-20 h-72 w-72 rounded-full bg-primary/30 blur-3xl" />
        <div className="pointer-events-none absolute -bottom-20 -right-20 h-72 w-72 rounded-full bg-success/20 blur-3xl" />
        <div className="relative">
          <h2 className="text-3xl font-extrabold md:text-5xl">Ready to launch your server?</h2>
          <p className="mx-auto mt-3 max-w-xl text-muted-foreground">
            Deploy in under 60 seconds. No setup fees. Cancel anytime.
          </p>
          <div className="mt-7 flex flex-wrap items-center justify-center gap-3">
            <Link to="/minecraft" className="inline-flex items-center gap-2 rounded-xl gradient-violet px-7 py-3.5 text-sm font-semibold text-white shadow-xl shadow-primary/30">
              Get Started <ArrowRight className="h-4 w-4" />
            </Link>
            <Link to="/contact" className="inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-7 py-3.5 text-sm font-semibold text-white hover:bg-white/10">
              Contact Sales
            </Link>
          </div>
        </div>
      </div>
    </section>
  );
}
