import Link from "next/link";
import { db } from "@/lib/db";
import { getCurrentUser, isOrganizer } from "@/lib/auth";
import { btn, Card, Logo, Badge } from "@/components/ui";
import { dateRange, fmtDate, formatMoney } from "@/lib/utils";
import { CountUp } from "@/components/fx";

const FEATURES: [string, string, string, string][] = [
  ["🎟️", "Registration & ticketing", "Early-bird, student, VIP and free passes with quantities, sale windows, coupons and instant QR tickets.", "from-indigo-500/15 to-violet-500/15"],
  ["🌐", "Instant conference website", "Every conference gets a branded public site — schedule, speakers, sponsors, SEO-ready pages — with zero code.", "from-sky-500/15 to-cyan-500/15"],
  ["🗓️", "Agenda builder", "Tracks, rooms and parallel sessions with automatic room & speaker conflict detection. Attendees star their own schedule.", "from-emerald-500/15 to-teal-500/15"],
  ["💳", "Payments & finance", "Gateway-shaped checkout, coupons and discounts, revenue tracking and CSV exports for reconciliation.", "from-amber-500/15 to-orange-500/15"],
  ["📄", "Call for Papers", "Submissions, reviewer assignment, blind scoring and one-click accept / revise / reject decisions with notifications.", "from-violet-500/15 to-fuchsia-500/15"],
  ["✅", "Check-in & attendance", "Scanner-friendly check-in desk, live attendance rates, and per-session tracking for physical, virtual and hybrid modes.", "from-emerald-500/15 to-lime-500/15"],
  ["🤝", "Sponsors & exhibitors", "Tiered sponsorships with booths and commitments that appear automatically across the public site.", "from-pink-500/15 to-rose-500/15"],
  ["🏅", "Verified certificates", "Bulk-generated participation and speaker certificates, each with a unique ID, QR and public verification URL.", "from-cyan-500/15 to-sky-500/15"],
  ["📊", "Live analytics", "Registration funnel, revenue, check-in rates and program stats on role-specific dashboards.", "from-orange-500/15 to-amber-500/15"],
];

const STEPS: [string, string, string][] = [
  ["Create & brand", "Set up your conference — dates, venue, tracks, ticket types — and pick your brand color.", "🎨"],
  ["Publish your site", "One click puts a full public website live: schedule, speakers, sponsors, registration.", "🚀"],
  ["Sell passes", "Attendees register with coupons and instant QR tickets; payments and approvals flow in.", "🎟️"],
  ["Run the event", "Check-in desk, live agenda, announcements, and hybrid streaming links on event days.", "🎤"],
  ["Close & certify", "Generate verified certificates, export reports, and archive the edition for the next year.", "🏅"],
];

export default async function Home() {
  const [user, conferences, stats] = await Promise.all([
    getCurrentUser(),
    db.conference.findMany({
      where: { status: { in: ["PUBLISHED", "LIVE"] } },
      orderBy: { startAt: "asc" },
      include: {
        org: true,
        ticketTypes: { where: { active: true }, orderBy: { price: "asc" }, take: 1 },
        _count: { select: { registrations: { where: { status: "CONFIRMED" } }, sessions: true, speakers: true } },
      },
    }),
    db.$transaction([
      db.conference.count(),
      db.registration.count({ where: { status: "CONFIRMED" } }),
      db.session.count(),
      db.certificate.count(),
    ]),
  ]);
  const [confCount, regCount, sessionCount, certCount] = stats;
  const featured = conferences[0];
  const rest = conferences.slice(1, 4);
  const organizer = !!user && isOrganizer(user);

  return (
    <main className="min-h-screen">
      {/* Glass nav */}
      <header className="fx-header sticky top-0 z-30 border-b border-white/60 bg-white/55 backdrop-blur-xl">
        <div className="mx-auto flex h-14 max-w-6xl items-center justify-between px-4">
          <Logo />
          <nav className="flex items-center gap-2">
            <a href="#how" className="hidden rounded-lg px-3 py-1.5 text-sm font-medium text-zinc-400 transition hover:bg-white/70 hover:text-zinc-100 sm:block">How it works</a>
            <a href="#features" className="hidden rounded-lg px-3 py-1.5 text-sm font-medium text-zinc-400 transition hover:bg-white/70 hover:text-zinc-100 sm:block">Features</a>
            <a href="#conferences" className="hidden rounded-lg px-3 py-1.5 text-sm font-medium text-zinc-400 transition hover:bg-white/70 hover:text-zinc-100 sm:block">Conferences</a>
            {user ? (
              organizer ? (
                <>
                  <Link href="/me" className={btn.ghost}>My conferences</Link>
                  <Link href="/dashboard" className={btn.primary}>Dashboard</Link>
                </>
              ) : (
                <Link href="/me" className={btn.primary}>My conferences</Link>
              )
            ) : (
              <>
                <Link href="/login" className={btn.ghost}>Sign in</Link>
                <Link href="/signup" className={btn.primary}>Get started</Link>
              </>
            )}
          </nav>
        </div>
      </header>

      {/* Hero */}
      <section className="mx-auto max-w-6xl px-4 pt-16 text-center sm:pt-20">
        <Badge className="fx-in border border-indigo-200/70 bg-white/60 text-indigo-600 shadow-sm backdrop-blur">
          ✨ The conference operating system
        </Badge>
        <h1 className="fx-in fx-d1 mx-auto mt-5 max-w-3xl text-4xl font-extrabold tracking-tight text-zinc-50 sm:text-6xl">
          Run your entire conference{" "}
          <span className="fx-gradient-text bg-gradient-to-r from-indigo-500 via-violet-500 to-fuchsia-500 bg-clip-text text-transparent">
            from one platform
          </span>
        </h1>
        <p className="fx-in fx-d2 mx-auto mt-5 max-w-2xl text-lg text-zinc-400">
          Physical, virtual, or hybrid — Confexe covers the full lifecycle: creation, websites,
          registration & ticketing, agendas, CFP & reviews, check-in, certificates, and analytics.
        </p>
        <div className="fx-in fx-d3 mt-8 flex flex-wrap justify-center gap-3">
          {user && !organizer ? (
            <a href="#conferences" className={`${btn.primary} px-6 py-2.5`}>Browse conferences</a>
          ) : (
            <>
              <Link href={organizer ? "/dashboard/conferences/new" : "/signup"} className={`${btn.primary} px-6 py-2.5`}>
                Create a conference — it's free
              </Link>
              <a href="#conferences" className={`${btn.secondary} px-6 py-2.5`}>Browse conferences</a>
            </>
          )}
        </div>
        <div className="fx-in fx-d4 mx-auto mt-10 grid max-w-3xl grid-cols-2 gap-3 sm:grid-cols-4">
          {[[confCount, "Conferences"], [regCount, "Registrations"], [sessionCount, "Sessions"], [certCount, "Certificates"]].map(([n, l]) => (
            <Card key={l as string} className="fx-lift px-4 py-3">
              <CountUp value={n as number} className="text-2xl font-extrabold text-zinc-100 tabular-nums" />
              <div className="text-[11px] font-semibold uppercase tracking-wider text-zinc-500">{l}</div>
            </Card>
          ))}
        </div>
      </section>

      {/* Featured conference hero banner */}
      {featured && (
        <section className="mx-auto max-w-6xl px-4 pt-14">
          <div
            className="fx-pop-in fx-d3 relative overflow-hidden rounded-3xl border border-white/60 shadow-[0_20px_60px_rgba(80,90,180,0.18)]"
            style={{
              background: `linear-gradient(120deg, ${featured.primaryColor} 0%, ${featured.primaryColor}cc 45%, #7c3aed 100%)`,
            }}
          >
            <div className="absolute inset-0" style={{ background: "radial-gradient(40rem 20rem at 85% -20%, rgba(255,255,255,0.35), transparent 60%)" }} />
            <div className="relative grid gap-6 p-8 sm:p-12 lg:grid-cols-5">
              <div className="lg:col-span-3">
                <div className="flex flex-wrap items-center gap-2">
                  <Badge className="bg-white/25 text-white backdrop-blur">FEATURED</Badge>
                  <Badge className="bg-white/25 text-white backdrop-blur">{featured.type}</Badge>
                  {featured.status === "LIVE" && (
                    <Badge className="bg-emerald-400/90 text-white">● LIVE NOW</Badge>
                  )}
                </div>
                <h2 className="mt-4 text-3xl font-extrabold text-white sm:text-4xl">{featured.name}</h2>
                {featured.tagline && <p className="mt-3 max-w-xl text-white/85">{featured.tagline}</p>}
                <div className="mt-5 flex flex-wrap gap-x-6 gap-y-2 text-sm font-medium text-white/90">
                  <span>📅 {dateRange(featured.startAt, featured.endAt)}</span>
                  {featured.city && <span>📍 {featured.venueName ? `${featured.venueName}, ` : ""}{featured.city}</span>}
                  {featured.type !== "PHYSICAL" && <span>🖥️ Online access available</span>}
                </div>
                <div className="mt-7 flex flex-wrap gap-3">
                  <Link
                    href={`/c/${featured.slug}/register`}
                    className="fx-shine rounded-xl bg-white px-6 py-2.5 text-sm font-bold shadow-lg transition hover:scale-[1.02]"
                    style={{ color: featured.primaryColor }}
                  >
                    Register now{featured.ticketTypes[0] ? ` · from ${formatMoney(featured.ticketTypes[0].price)}` : ""}
                  </Link>
                  <Link href={`/c/${featured.slug}`} className="rounded-xl border border-white/50 bg-white/15 px-6 py-2.5 text-sm font-semibold text-white backdrop-blur transition hover:bg-white/25">
                    Explore the conference →
                  </Link>
                </div>
              </div>
              <div className="grid grid-cols-3 gap-3 self-end lg:col-span-2 lg:grid-cols-1 lg:justify-self-end">
                {[[featured._count.sessions, "Sessions"], [featured._count.speakers, "Speakers"], [featured._count.registrations, "Registered"]].map(([n, l], i) => (
                  <div key={l as string} className={`fx-float fx-d rounded-2xl border border-white/40 bg-white/20 px-5 py-3 text-center backdrop-blur-md lg:min-w-40 lg:text-left`}>
                    <CountUp value={n as number} className="text-2xl font-extrabold text-white tabular-nums" />
                    <div className="text-[11px] font-semibold uppercase tracking-wider text-white/75">{l}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {rest.length > 0 && (
            <div className="mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {rest.map((c) => (
                <Link key={c.id} href={`/c/${c.slug}`} className="group">
                  <Card className="fx-reveal fx-lift flex h-full items-center gap-4 p-4">
                    <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl text-lg font-bold text-white shadow-md" style={{ background: c.primaryColor }}>
                      {c.name[0]}
                    </span>
                    <div className="min-w-0">
                      <div className="truncate font-bold text-zinc-100">{c.name}</div>
                      <div className="text-xs text-zinc-500">{dateRange(c.startAt, c.endAt)} · {c.city ?? "Online"}</div>
                    </div>
                  </Card>
                </Link>
              ))}
            </div>
          )}
        </section>
      )}

      {/* How it works */}
      <section id="how" className="mx-auto max-w-6xl scroll-mt-20 px-4 pt-20">
        <div className="text-center">
          <Badge className="bg-violet-500/10 text-violet-600">HOW IT WORKS</Badge>
          <h2 className="mt-3 text-3xl font-extrabold text-zinc-100">From idea to certificates in five steps</h2>
          <p className="mx-auto mt-2 max-w-xl text-zinc-500">One connected lifecycle — every step feeds the next, nothing lives in a silo.</p>
        </div>
        <div className="mt-10 grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
          {STEPS.map(([title, body, icon], i) => (
            <Card key={title} className="fx-reveal fx-lift relative p-5">
              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-indigo-500/15 to-fuchsia-500/15 text-xl">{icon}</div>
              <div className="absolute right-4 top-4 text-3xl font-black text-indigo-500/15">{i + 1}</div>
              <h3 className="mt-3 font-bold text-zinc-100">{title}</h3>
              <p className="mt-1.5 text-sm leading-relaxed text-zinc-500">{body}</p>
            </Card>
          ))}
        </div>
      </section>

      {/* Features */}
      <section id="features" className="mx-auto max-w-6xl scroll-mt-20 px-4 pt-20">
        <div className="text-center">
          <Badge className="bg-sky-500/10 text-sky-600">EVERYTHING INCLUDED</Badge>
          <h2 className="mt-3 text-3xl font-extrabold text-zinc-100">One platform, every module</h2>
          <p className="mx-auto mt-2 max-w-2xl text-zinc-500">
            Built for organizers, attendees, speakers, reviewers, sponsors and volunteers — with role-based
            access and isolated workspaces per conference.
          </p>
        </div>
        <div className="mt-10 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {FEATURES.map(([icon, title, body, grad]) => (
            <Card key={title} className="fx-reveal fx-lift p-5">
              <div className={`flex h-11 w-11 items-center justify-center rounded-2xl bg-gradient-to-br text-xl ${grad}`}>{icon}</div>
              <h3 className="mt-3 font-bold text-zinc-100">{title}</h3>
              <p className="mt-1.5 text-sm leading-relaxed text-zinc-500">{body}</p>
            </Card>
          ))}
        </div>
      </section>

      {/* Conference directory */}
      <section id="conferences" className="mx-auto max-w-6xl scroll-mt-20 px-4 py-20">
        <div className="flex items-end justify-between">
          <div>
            <Badge className="bg-emerald-500/10 text-emerald-600">DISCOVER</Badge>
            <h2 className="mt-3 text-3xl font-extrabold text-zinc-100">Upcoming conferences</h2>
          </div>
        </div>
        <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {conferences.length === 0 && <p className="text-sm text-zinc-500">No published conferences yet — create the first one.</p>}
          {conferences.map((c) => (
            <Link key={c.id} href={`/c/${c.slug}`} className="group">
              <Card className="fx-reveal fx-lift h-full overflow-hidden">
                <div className="h-28 w-full" style={{ background: `linear-gradient(120deg, ${c.primaryColor}, ${c.primaryColor}99), radial-gradient(circle at 80% 0%, rgba(255,255,255,0.5), transparent 55%)` }} />
                <div className="p-4">
                  <div className="flex items-center gap-2 text-[11px] font-bold uppercase tracking-wider text-zinc-500">
                    {c.type} · {c.category ?? "CONFERENCE"}
                    {c.status === "LIVE" && <span className="text-emerald-600">● LIVE</span>}
                  </div>
                  <div className="mt-1 font-bold text-zinc-100">{c.name}</div>
                  <div className="mt-1 text-sm text-zinc-500">{dateRange(c.startAt, c.endAt)} · {c.city ?? "Online"}</div>
                  <div className="mt-3 flex gap-3 text-xs font-medium text-zinc-500">
                    <span>{c._count.sessions} sessions</span>
                    <span>{c._count.speakers} speakers</span>
                    <span>{c._count.registrations} registered</span>
                  </div>
                  <div className="mt-3 border-t border-zinc-800/70 pt-3 text-xs text-zinc-500">
                    {c.regClosesAt ? `Registration closes ${fmtDate(c.regClosesAt)}` : "Registration open"} · by {c.org.name}
                  </div>
                </div>
              </Card>
            </Link>
          ))}
        </div>
      </section>

      {/* CTA */}
      <section className="mx-auto max-w-6xl px-4 pb-20">
        <div className="fx-reveal overflow-hidden rounded-3xl bg-gradient-to-r from-indigo-500 via-violet-500 to-fuchsia-500 p-10 text-center shadow-[0_20px_60px_rgba(120,80,220,0.35)] sm:p-14">
          <h2 className="text-3xl font-extrabold text-white">Ready to host your next conference?</h2>
          <p className="mx-auto mt-2 max-w-xl text-white/85">
            Spin up a branded website, open registration, and manage everything from one workspace — in minutes.
            {user && !organizer && " Sign up for an organizer account to get started."}
          </p>
          <Link href={organizer ? "/dashboard/conferences/new" : "/signup"} className="fx-shine mt-6 inline-block rounded-xl bg-white px-7 py-3 text-sm font-bold text-indigo-600 shadow-lg transition hover:scale-[1.02]">
            Create your conference
          </Link>
        </div>
      </section>

      <footer className="border-t border-white/60 bg-white/40 py-8 text-center text-xs text-zinc-500 backdrop-blur">
        Confexe — the unified conference lifecycle platform. Registration → Ticket → Check-in → Certificate, all connected.
      </footer>
    </main>
  );
}
