"use client";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { ArrowRight, CalendarClock, Zap } from "lucide-react";

import { CatalogDrawer } from "@/components/CatalogDrawer";
import { HeroRadar } from "@/components/HeroRadar";
import { CountUp, Reveal } from "@/components/Reveal";
import { Navbar } from "@/components/Navbar";
import { api } from "@/lib/api";
import type { Genre, ServiceType } from "@/lib/types";

/** Orden de las familias en la home. El backend agrupa con `group`; acá solo mandamos el orden. */
const GROUP_ORDER = ["Solistas", "Grupos", "Bandas por estilo", "Regionales", "Percusión", "Otros"];

export default function Home() {
  const [drawer, setDrawer] = useState(false);
  const [types, setTypes] = useState<ServiceType[]>([]);
  const [genres, setGenres] = useState<Genre[]>([]);
  const [nearby, setNearby] = useState<number | null>(null);

  useEffect(() => {
    api.serviceTypes().then(setTypes).catch(() => setTypes([]));
    api.genres().then(setGenres).catch(() => setGenres([]));
  }, []);

  // Contador del hero. Solo con la ubicación real del visitante: si dice "cerca tuyo", tiene que serlo.
  // Sin permiso de geolocalización o sin backend, la línea no se muestra en vez de inventar un número.
  useEffect(() => {
    if (!("geolocation" in navigator)) return;
    navigator.geolocation.getCurrentPosition(
      ({ coords }) => {
        api
          .search({ lat: coords.latitude, lng: coords.longitude, radius_km: 50, available_only: true })
          .then((r) => setNearby(r.length))
          .catch(() => setNearby(null));
      },
      () => setNearby(null),
      { timeout: 8000 },
    );
  }, []);

  const groups = useMemo(() => {
    const by = new Map<string, ServiceType[]>();
    types.forEach((t) => {
      const list = by.get(t.group) ?? [];
      list.push(t);
      by.set(t.group, list);
    });
    return GROUP_ORDER.filter((g) => by.has(g)).map((g) => ({ name: g, items: by.get(g)! }));
  }, [types]);

  const total = types.length + genres.length;

  return (
    <div className="min-h-screen bg-navy-void">
      <Navbar variant="over-dark" />

      {/* ── HERO ─────────────────────────────────────────────── */}
      <section className="relative isolate grid min-h-[100svh] place-items-center overflow-hidden bg-navy-void">
        <HeroRadar />
        {/* Velo: aclara el centro para que el radar respire y funde a negro arriba y abajo. */}
        <div
          aria-hidden
          className="pointer-events-none absolute inset-0 z-[1]"
          style={{
            background:
              "radial-gradient(58% 50% at 50% 42%, rgba(18,50,107,.5), transparent 72%)," +
              "radial-gradient(90% 70% at 50% 100%, rgba(5,9,15,.94), transparent 60%)," +
              "linear-gradient(to bottom, rgba(5,9,15,.86) 0%, rgba(5,9,15,.14) 26%, rgba(5,9,15,.2) 58%, #05090f 97%)",
          }}
        />
        <div className="matte pointer-events-none absolute inset-0 z-[2]" />

        <div className="relative z-[3] mx-auto w-full max-w-5xl px-4 py-28 text-center">
          {nearby !== null && (
            <span className="inline-flex items-center gap-2 rounded-full border border-white/15 bg-navy/50 px-4 py-1.5 text-xs font-semibold uppercase tracking-[0.11em] text-slate-300 backdrop-blur">
              <span className="relative flex h-2 w-2">
                <span className="absolute inline-flex h-full w-full animate-pulse-ring rounded-full bg-success" />
                <span className="relative inline-flex h-2 w-2 rounded-full bg-success" />
              </span>
              <span>
                <b className="text-white">{nearby}</b> músicos disponibles ahora cerca tuyo
              </span>
            </span>
          )}

          <h1 className="mt-6 text-balance text-5xl font-black uppercase leading-[0.92] tracking-[-0.045em] text-white sm:text-7xl lg:text-[6.4rem]">
            <span className="block overflow-hidden">
              <span className="animate-rise block">Música en vivo</span>
            </span>
            <span className="block overflow-hidden">
              <span className="animate-rise-late block text-glow-teal">a 3 km de vos</span>
            </span>
          </h1>

          <p className="animate-fade-in-slow mx-auto mt-6 max-w-xl text-lg leading-relaxed text-slate-400">
            Mirá en el mapa quién está disponible cerca y contratalo{" "}
            <strong className="font-semibold text-slate-200">ahora mismo</strong> o{" "}
            <strong className="font-semibold text-slate-200">reservá</strong> para tu evento.
          </p>

          <div className="animate-fade-in-slower mt-9 flex flex-wrap justify-center gap-3">
            <Link
              href="/buscar"
              className="group inline-flex items-center gap-2 rounded-xl bg-gradient-to-b from-blue-light to-blue-deep px-7 py-3.5 font-bold text-white shadow-glow-blue transition hover:-translate-y-0.5"
            >
              Buscar músicos cerca
              <ArrowRight size={18} className="transition-transform group-hover:translate-x-1" />
            </Link>
            <button
              onClick={() => setDrawer(true)}
              className="inline-flex items-center gap-2 rounded-xl border border-white/20 bg-navy/40 px-7 py-3.5 font-bold text-slate-200 backdrop-blur transition hover:-translate-y-0.5 hover:border-accent hover:text-white"
            >
              {total > 0 ? `Ver las ${total} opciones` : "Ver el catálogo"}
            </button>
          </div>

          <div className="animate-fade-in-slower mt-10 flex flex-wrap justify-center gap-x-7 gap-y-2 font-mono text-xs tracking-wide text-slate-500">
            {["Venezuela · Chile · Irlanda", "Radio ajustable", "Express o programado"].map((m) => (
              <span key={m} className="inline-flex items-center gap-2 uppercase">
                <i className="h-[5px] w-[5px] rounded-[1px] bg-accent" />
                {m}
              </span>
            ))}
          </div>
        </div>
      </section>

      {/* ── BANDA DE DATOS ───────────────────────────────────── */}
      <section className="border-y border-white/10 bg-navy-void">
        <div className="mx-auto grid max-w-6xl grid-cols-2 sm:grid-cols-4">
          {[
            { n: types.length, label: "Tipos de músico" },
            { n: genres.length, label: "Géneros" },
            { n: 3, label: "Países" },
            { n: 2, label: "Respuesta media", suffix: " min" },
          ].map((s, i) => (
            <div
              key={s.label}
              className="border-white/10 px-4 py-10 text-center [&:not(:first-child)]:border-l max-sm:[&:nth-child(3)]:border-l-0 max-sm:[&:nth-child(n+3)]:border-t"
            >
              <CountUp
                to={s.n}
                suffix={s.suffix}
                className="block font-mono text-3xl font-bold tabular-nums tracking-tight text-white sm:text-4xl"
              />
              <span className="mt-2 block text-[11px] uppercase tracking-[0.15em] text-slate-500">{s.label}</span>
            </div>
          ))}
        </div>
      </section>

      {/* Transición de la vidriera oscura a la app blanca */}
      <div className="h-48 bg-gradient-to-b from-navy-void to-bg" />

      <main className="bg-bg">
        {/* ── FAMILIAS ───────────────────────────────────────── */}
        <section className="mx-auto max-w-6xl px-4 py-20">
          <Reveal>
            <div className="flex items-center gap-3 font-mono text-xs font-semibold uppercase tracking-[0.2em] text-accent-deep">
              Qué necesitás
              <span className="h-px flex-1 bg-gradient-to-r from-line to-transparent" />
            </div>
            <h2 className="mt-4 text-balance text-3xl font-extrabold leading-tight tracking-tight sm:text-5xl">
              Empezá por el tipo.
              <br />
              {total > 0 ? `Los ${total} están a un clic.` : "El catálogo está a un clic."}
            </h2>
            <p className="mt-3 max-w-xl leading-relaxed text-ink-soft">
              No te tiramos una lista infinita en la cara. Elegí la familia que buscás — o abrí el catálogo
              completo y buscá por letra.
            </p>
          </Reveal>

          <div className="mt-10 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {groups.map((g, i) => (
              <Reveal key={g.name} delay={Math.min(i, 5)}>
                <button
                  onClick={() => setDrawer(true)}
                  className="group relative flex h-full min-h-[172px] w-full flex-col overflow-hidden rounded-2xl border border-line bg-bg-card p-6 text-left transition duration-300 hover:-translate-y-1 hover:border-accent/50 hover:shadow-soft"
                >
                  <span className="absolute inset-y-0 left-0 w-[3px] origin-top scale-y-0 bg-accent transition-transform duration-300 group-hover:scale-y-100" />
                  <span className="text-3xl leading-none">{g.items[0]?.emoji ?? "♪"}</span>
                  <h3 className="mt-auto pt-4 text-lg font-bold tracking-tight transition-opacity group-hover:opacity-0">
                    {g.name}
                  </h3>
                  <span className="mt-1 font-mono text-xs text-ink-mute transition-opacity group-hover:opacity-0">
                    {g.items.length} {g.items.length === 1 ? "opción" : "opciones"}
                  </span>
                  <span className="absolute inset-x-6 bottom-6 translate-y-1.5 text-sm leading-relaxed text-ink-soft opacity-0 transition duration-300 group-hover:translate-y-0 group-hover:opacity-100">
                    {g.items.slice(0, 5).map((i) => i.name).join(" · ")}
                    {g.items.length > 5 ? " …" : ""}
                  </span>
                </button>
              </Reveal>
            ))}
          </div>

          <Reveal delay={2}>
            <button
              onClick={() => setDrawer(true)}
              className="mt-7 inline-flex items-center gap-3 rounded-xl border border-line bg-bg-soft px-6 py-3.5 font-semibold transition hover:-translate-y-0.5 hover:border-accent hover:text-accent-deep"
            >
              Ver catálogo completo
              <span className="font-mono text-xs text-ink-mute">
                {types.length} tipos + {genres.length} géneros
              </span>
              <ArrowRight size={17} />
            </button>
          </Reveal>
        </section>

        {/* ── CÓMO FUNCIONA ─────────────────────────────────── */}
        <section className="border-y border-line bg-bg-soft py-20">
          <div className="mx-auto max-w-6xl px-4">
            <Reveal>
              <div className="flex items-center gap-3 font-mono text-xs font-semibold uppercase tracking-[0.2em] text-accent-deep">
                Cómo funciona
                <span className="h-px flex-1 bg-gradient-to-r from-line to-transparent" />
              </div>
              <h2 className="mt-4 text-3xl font-extrabold tracking-tight sm:text-5xl">
                De la búsqueda al escenario.
              </h2>
            </Reveal>

            <div className="mt-12 grid gap-8 sm:grid-cols-3">
              {[
                {
                  t: "Mirá quién está cerca",
                  b: "El mapa muestra los músicos disponibles dentro de tu radio, ordenados por cercanía real. Si no hay nadie, ampliás el radio a toda la ciudad o al país.",
                },
                {
                  t: "Entrá a su perfil",
                  b: "Fotos, videos de sus shows, géneros que toca y su tarifa. Sabés exactamente a quién estás contratando antes de escribirle.",
                },
                {
                  t: "Contratá y listo",
                  b: "Express si lo necesitás hoy, o programado con la fecha y hora de tu evento. La reserva queda registrada en la app.",
                },
              ].map((s, i) => (
                <Reveal key={s.t} delay={i}>
                  <span className="grid h-10 w-10 place-items-center rounded-full border border-line bg-bg-card font-mono text-sm font-bold text-accent-deep">
                    {String(i + 1).padStart(2, "0")}
                  </span>
                  <h3 className="mt-4 text-lg font-bold tracking-tight">{s.t}</h3>
                  <p className="mt-2 text-sm leading-relaxed text-ink-soft">{s.b}</p>
                </Reveal>
              ))}
            </div>
          </div>
        </section>

        {/* ── EXPRESS VS PROGRAMADO ─────────────────────────── */}
        <section className="mx-auto max-w-6xl px-4 py-20">
          <Reveal>
            <div className="flex items-center gap-3 font-mono text-xs font-semibold uppercase tracking-[0.2em] text-accent-deep">
              Dos maneras
              <span className="h-px flex-1 bg-gradient-to-r from-line to-transparent" />
            </div>
            <h2 className="mt-4 text-3xl font-extrabold tracking-tight sm:text-5xl">
              ¿Lo necesitás ya o lo estás planeando?
            </h2>
          </Reveal>

          <div className="mt-10 grid gap-4 md:grid-cols-2">
            <Reveal delay={1}>
              <div className="matte-host relative h-full overflow-hidden rounded-3xl bg-gradient-to-br from-navy to-[#08182f] p-8">
                <div className="matte pointer-events-none absolute inset-0" />
                <div className="relative z-[3]">
                  <span className="inline-flex items-center gap-2 font-mono text-xs uppercase tracking-[0.18em] text-accent">
                    <Zap size={13} /> Express
                  </span>
                  <h3 className="mt-3 text-2xl font-extrabold tracking-tight text-white">
                    Música en menos de una hora
                  </h3>
                  <p className="mt-3 leading-relaxed text-slate-400">
                    Se armó la fiesta de la nada. Buscás quién está disponible ahora mismo en tu zona y lo
                    contratás al toque.
                  </p>
                  <ul className="mt-6 grid gap-2 text-sm text-slate-300">
                    {["Solo músicos marcados como disponibles", "Ordenados por distancia real", "Ideal para serenatas y cumpleaños"].map((li) => (
                      <li key={li} className="flex items-start gap-2.5">
                        <i className="mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-accent" />
                        {li}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </Reveal>

            <Reveal delay={2}>
              <div className="h-full rounded-3xl border border-line bg-bg-soft p-8">
                <span className="inline-flex items-center gap-2 font-mono text-xs uppercase tracking-[0.18em] text-accent-deep">
                  <CalendarClock size={13} /> Programado
                </span>
                <h3 className="mt-3 text-2xl font-extrabold tracking-tight">Reservá con anticipación</h3>
                <p className="mt-3 leading-relaxed text-ink-soft">
                  Tu boda es en marzo. Elegís fecha, hora y duración, y bloqueás la agenda del músico desde hoy.
                </p>
                <ul className="mt-6 grid gap-2 text-sm text-ink-soft">
                  {["Días, semanas o meses antes", "Comparás perfiles sin apuro", "Ideal para bodas y eventos de empresa"].map((li) => (
                    <li key={li} className="flex items-start gap-2.5">
                      <i className="mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-accent" />
                      {li}
                    </li>
                  ))}
                </ul>
              </div>
            </Reveal>
          </div>
        </section>
      </main>

      {/* ── CIERRE ───────────────────────────────────────────── */}
      <section className="relative isolate overflow-hidden bg-gradient-to-br from-navy to-navy-void py-24 text-center">
        <div
          aria-hidden
          className="pointer-events-none absolute inset-x-0 -top-40 h-[520px]"
          style={{ background: "radial-gradient(50% 60% at 50% 50%, rgba(18,50,107,.65), transparent 70%)" }}
        />
        <div className="matte pointer-events-none absolute inset-0" />
        <Reveal className="relative z-[3] mx-auto max-w-3xl px-4">
          <h2 className="text-balance text-3xl font-extrabold tracking-tight text-white sm:text-5xl">
            Alguien está afinando a tres cuadras de acá.
          </h2>
          <p className="mx-auto mt-4 max-w-md leading-relaxed text-slate-400">
            Gotagig conecta a quien organiza el evento con el músico que ya está cerca. Sin intermediarios,
            sin llamar a ciegas.
          </p>
          <div className="mt-8 flex flex-wrap justify-center gap-3">
            <Link
              href="/buscar"
              className="group inline-flex items-center gap-2 rounded-xl bg-gradient-to-b from-blue-light to-blue-deep px-7 py-3.5 font-bold text-white shadow-glow-blue transition hover:-translate-y-0.5"
            >
              Buscar músicos cerca
              <ArrowRight size={18} className="transition-transform group-hover:translate-x-1" />
            </Link>
            <Link
              href="/registro"
              className="inline-flex items-center rounded-xl border border-white/20 bg-navy/40 px-7 py-3.5 font-bold text-slate-200 backdrop-blur transition hover:-translate-y-0.5 hover:border-accent hover:text-white"
            >
              Quiero registrarme como músico
            </Link>
          </div>
        </Reveal>
      </section>

      <footer className="border-t border-white/10 bg-navy-void py-9 text-sm text-slate-500">
        <div className="mx-auto flex max-w-6xl flex-col items-center justify-between gap-3 px-4 sm:flex-row">
          <span className="inline-flex items-center gap-2">
            <span className="font-music text-xl text-accent" aria-hidden>
              𝄞𝄢
            </span>
            <span className="font-bold tracking-tight">
              <span className="text-white">Gota</span>
              <span className="text-accent">gig</span>
            </span>
          </span>
          <span>Contratá músicos cerca tuyo · express o programado</span>
        </div>
      </footer>

      <CatalogDrawer open={drawer} onClose={() => setDrawer(false)} />
    </div>
  );
}
