import Link from "next/link";
import { format } from "date-fns";
import Marquee from "@/components/marquee";
import { getUpcomingEvents, getFeaturedEvents, priceFromCents, isSoldOut } from "@db/queries/events";
import { getHomeSlides, getHomeVideo } from "@db/queries/settings";
import Hero from "@/components/hero";
import SiteFooter from "@/components/site-footer";
import ContactSection from "@/components/contact-section";
import {
  PLATFORM,
  HOME_INTRO,
  HOME_WAYS,
  HOME_WHY,
  HOME_FEE_STAT,
  HOME_COMPARISON,
  HOME_WHY_CTA,
  FEATURED_EVENTS,
} from "@/lib/platform-content";
import { ArrowRightIcon } from "@/components/icons";
import { eventPath } from "@/lib/event-url";

// Queries live event/stat data — must render per-request, not bake a
// build-time snapshot into a static page (a stale/wrong DB at build time
// would ship as the permanent homepage until the next deploy).
export const dynamic = "force-dynamic";

// The full range of events VibePass produces and promotes across East
// Africa — mirroring the breadth of a marketplace like HustleSasa, framed
// around the audiences and pricing models we build for each.
// Shared "touch of gold" hover treatment: card lifts to a warm gold edge + glow
// on hover, keeping green as the primary/action colour and gold as the accent.
const GOLD_HOVER =
  "transition-all duration-200 hover:-translate-y-0.5 hover:border-brand-gold hover:shadow-[0_14px_34px_-18px_rgba(231,184,75,0.55)] motion-reduce:hover:translate-y-0";

// Each card opens with a photo header (optimized 16:9 crops in
// public/events/types/) that sets the mood for the event type.
const EVENT_TYPES = [
  {
    title: "Concerts & Live Shows",
    category: "Music & Entertainment",
    blurb: "Headline nights, artist showcases and cultural fusion for music lovers and the nightlife crowd.",
    audience: "Music lovers · Nightlife crowd",
    pricing: "VIP / VVIP & general admission",
    photo: "/events/types/concerts.jpg",
  },
  {
    title: "Festivals",
    category: "Culture & Lifestyle",
    blurb: "Immersive, multi-tier celebrations of heritage and community pride — colour fests to homecomings.",
    audience: "Families · Cultural-pride crowds",
    pricing: "Regular · VIP · VVIP tiers",
    photo: "/events/types/festivals.jpg",
  },
  {
    title: "Community & Cultural Gatherings",
    category: "Heritage & Creativity",
    blurb: "Storytelling, artisan showcases and pride-driven nights that put local creativity centre stage.",
    audience: "Artisans · Cultural enthusiasts",
    pricing: "Flexible community pricing",
    photo: "/events/types/community.jpg",
  },
  {
    title: "Game Launches & Tournaments",
    category: "Gaming & Esports",
    blurb: "Competitive, digital-first launch events and tournaments built for youth, gamers and tech fans.",
    audience: "Youth · Gamers · Tech fans",
    pricing: "Early bird & tiered entry",
    photo: "/events/types/gaming.jpg",
  },
  {
    title: "Webinars & Workshops",
    category: "Education & Pro Development",
    blurb: "Interactive learning on funding, proposals and creative strategy for professionals and NGOs.",
    audience: "Creatives · Professionals · NGOs",
    pricing: "Free or paid access",
    photo: "/events/types/workshops.jpg",
  },
  {
    title: "Health & Wellness Sessions",
    category: "Wellness & Community",
    blurb: "Awareness and resilience-building conversations — from mental health to men's groups.",
    audience: "Advocates · Wellness groups",
    pricing: "Free or donation-based",
    photo: "/events/types/wellness.jpg",
  },
  {
    title: "Nightlife & Social Events",
    category: "Lifestyle & Entertainment",
    blurb: "Club nights, lifestyle activations and social hangouts branded for urban youth and party-goers.",
    audience: "Urban youth · Party-goers",
    pricing: "Cover charge & packages",
    photo: "/events/types/nightlife.jpg",
  },
];

export default async function HomePage() {
  const [events, featuredEvents, heroSlides, heroVideo] = await Promise.all([
    getUpcomingEvents(6),
    getFeaturedEvents(4),
    getHomeSlides(),
    getHomeVideo(),
  ]);
  const featured = events[0];

  return (
    <div className="flex-1 bg-bg">
      {/* Hero */}
      <Hero
        slides={heroSlides}
        video={heroVideo}
        featuredHref={featured ? eventPath(featured) : "#tickets"}
      />

      {/* What is VibePass Tickets — brand intro band */}
      <section className="bg-bg border-b border-line">
        <div className="max-w-6xl mx-auto px-4 py-16 grid lg:grid-cols-[1.1fr_1fr] gap-10 items-center">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.3em] text-brand-green-h">
              What is VibePass Tickets?
            </p>
            <h2 className="mt-3 text-3xl sm:text-4xl font-black tracking-tight text-white">
              {PLATFORM.tagline}
            </h2>
            <p className="mt-5 text-lg text-muted leading-relaxed">
              VibePass Tickets is Kenya&apos;s event operating system — a storefront where
              fans discover and buy tickets in seconds, and a dashboard where organizers
              launch an event, price it, and get paid without chasing a till number.
              One platform, built for every kind of gathering East Africa puts on.
            </p>
            <div className="mt-8 flex flex-wrap gap-3">
              <Link
                href="#tickets"
                className="rounded-full bg-brand-green px-6 py-3 text-sm font-bold text-white transition-colors hover:bg-brand-green-deep"
              >
                Find an event
              </Link>
              <Link
                href="/dashboard/events/new"
                className="rounded-full border border-line px-6 py-3 text-sm font-bold text-white transition-colors hover:border-brand-gold"
              >
                Launch an event
              </Link>
            </div>
          </div>
          <dl className="grid grid-cols-2 gap-4">
            {[
              { label: "M-Pesa checkout", body: "STK push at checkout, ticket arrives instantly by SMS & email." },
              { label: "Same-day payouts", body: "Money settles to your bank or M-Pesa — no weeks-long wait." },
              { label: "Your own brand", body: "Every event page, receipt and ticket carries your name, not a marketplace's." },
              { label: "Built for Kenya", body: "KES pricing, local fees, and support that understands the market." },
            ].map((item) => (
              <div key={item.label} className="rounded-2xl border border-line bg-panel p-5">
                <dt className="font-bold text-white">{item.label}</dt>
                <dd className="mt-2 text-sm text-muted leading-relaxed">{item.body}</dd>
              </div>
            ))}
          </dl>
        </div>
      </section>

      <Marquee />

      {/* What's on — featured events (§5) */}
      <section id="featured" className="bg-panel border-y border-line">
        <div className="max-w-6xl mx-auto px-4 py-20">
          <div className="flex items-end justify-between gap-4">
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.3em] text-brand-green-h">
                What&apos;s on
              </p>
              <h2 className="mt-3 text-3xl sm:text-4xl font-black tracking-tight text-white">
                Featured events
              </h2>
            </div>
            <Link
              href="/events"
              className="shrink-0 text-sm font-semibold text-brand-green-h transition-colors hover:text-brand-gold-h"
            >
              All events →
            </Link>
          </div>

          {/* Admin-curated featured events (0011 `events.featured`); falls back to
              the static highlights until staff curate from /admin/events. */}
          {featuredEvents.length > 0 ? (
            <div className="mt-10 grid sm:grid-cols-2 lg:grid-cols-4 gap-5">
              {featuredEvents.map((ev) => {
                const priceCents = priceFromCents(ev.ticket_types);
                return (
                  <Link
                    key={ev.id}
                    href={eventPath(ev)}
                    className={`group flex flex-col rounded-2xl border border-line bg-panel-soft overflow-hidden ${GOLD_HOVER}`}
                  >
                    <div className="aspect-[16/10] relative overflow-hidden bg-brand-green-panel">
                      {ev.cover_image_url ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img
                          src={ev.cover_image_url}
                          alt={ev.title}
                          className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                        />
                      ) : (
                        <div
                          aria-hidden="true"
                          className="absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,var(--brand-green-wash),transparent_60%)]"
                        />
                      )}
                      <span className="absolute left-3 top-3 rounded-full bg-brand-green px-2.5 py-1 text-[11px] font-bold uppercase tracking-wide text-white">
                        {ev.categories?.name ?? "Featured"}
                      </span>
                    </div>
                    <div className="flex flex-1 flex-col p-5">
                      <h3 className="font-bold text-lg text-white group-hover:text-brand-gold-h transition-colors line-clamp-2">
                        {ev.title}
                      </h3>
                      <p className="mt-2 text-sm text-muted leading-relaxed flex-1">
                        {format(new Date(ev.starts_at), "PPP")} · {ev.venue}
                      </p>
                      <span className="mt-4 inline-flex items-center gap-1.5 text-sm font-semibold text-brand-green-h">
                        {priceCents === null
                          ? "View event"
                          : priceCents === 0
                            ? "FREE · View event"
                            : `From KES ${(priceCents / 100).toLocaleString()}`}
                        <ArrowRightIcon className="w-4 h-4" />
                      </span>
                    </div>
                  </Link>
                );
              })}
            </div>
          ) : (
            <div className="mt-10 grid sm:grid-cols-2 lg:grid-cols-4 gap-5">
              {FEATURED_EVENTS.map((ev) => (
                <Link
                  key={ev.title}
                  href={ev.href}
                  className={`group flex flex-col rounded-2xl border border-line bg-panel-soft overflow-hidden ${GOLD_HOVER}`}
                >
                  <div className="aspect-[16/10] relative overflow-hidden bg-brand-green-panel">
                    {ev.image ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={ev.image}
                        alt={ev.title}
                        className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                      />
                    ) : (
                      <div
                        aria-hidden="true"
                        className="absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,var(--brand-green-wash),transparent_60%)]"
                      />
                    )}
                    <span
                      className={`absolute left-3 top-3 rounded-full px-2.5 py-1 text-[11px] font-bold uppercase tracking-wide ${
                        ev.comingSoon
                          ? "bg-black/60 text-white/90"
                          : "bg-brand-green text-white"
                      }`}
                    >
                      {ev.comingSoon ? "Coming soon" : ev.tag}
                    </span>
                  </div>
                  <div className="flex flex-1 flex-col p-5">
                    <h3 className="font-bold text-lg text-white group-hover:text-brand-gold-h transition-colors">
                      {ev.title}
                    </h3>
                    <p className="mt-2 text-sm text-muted leading-relaxed flex-1">{ev.caption}</p>
                    <span className="mt-4 inline-flex items-center gap-1.5 text-sm font-semibold text-brand-green-h">
                      {ev.comingSoon ? "Get notified" : "View event"}
                      <ArrowRightIcon className="w-4 h-4" />
                    </span>
                  </div>
                </Link>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* Upcoming events carousel */}
      <section id="tickets" className="bg-bg">
        <div className="max-w-6xl mx-auto px-4 py-20">
          <div className="flex items-end justify-between gap-4">
            <div>
              <h2 className="text-3xl sm:text-4xl font-black tracking-tight text-white">
                Upcoming events
              </h2>
              <p className="mt-2 text-muted">
                Prices in KES · M-Pesa STK push at checkout, no till numbers.
              </p>
            </div>
            <Link
              href="/events"
              className="shrink-0 text-sm font-semibold text-brand-green-h transition-colors hover:text-brand-gold-h"
            >
              All events →
            </Link>
          </div>

          {!events.length && (
            <p className="mt-8 text-muted">No dates are live right now. Check back soon.</p>
          )}

          <div className="mt-8 -mx-4 px-4 flex gap-5 overflow-x-auto pb-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden snap-x snap-mandatory">
            {events.map((ev) => {
              const priceCents = priceFromCents(ev.ticket_types);
              const soldOut = isSoldOut(ev.ticket_types);
              return (
                <Link
                  key={ev.id}
                  href={eventPath(ev)}
                  className={`group shrink-0 snap-start w-72 sm:w-80 rounded-2xl border border-line bg-panel overflow-hidden ${GOLD_HOVER}`}
                >
                  <div className="aspect-[16/10] bg-panel-soft relative overflow-hidden">
                    {ev.cover_image_url && (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={ev.cover_image_url}
                        alt={ev.title}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                      />
                    )}
                    {soldOut && (
                      <span className="absolute left-3 top-3 rounded-full bg-brand-gold px-2.5 py-1 text-[11px] font-bold uppercase tracking-wider text-[#1a1206]">
                        Sold out
                      </span>
                    )}
                  </div>
                  <div className="p-5">
                    {ev.categories && (
                      <p className="text-xs font-semibold uppercase tracking-wide text-brand-green-h">
                        {ev.categories.name}
                      </p>
                    )}
                    <h3 className="mt-1 font-bold text-lg text-white line-clamp-2">{ev.title}</h3>
                    <p className="mt-1 text-sm text-muted">
                      {format(new Date(ev.starts_at), "PPP")} · {ev.venue}
                    </p>
                    <p className="mt-3 text-sm font-semibold text-brand-green-h">
                      {priceCents === null
                        ? "Tickets coming soon"
                        : priceCents === 0
                          ? "FREE"
                          : `From KES ${(priceCents / 100).toLocaleString()}`}
                    </p>
                  </div>
                </Link>
              );
            })}
          </div>
        </div>
      </section>

      {/* What we produce — full event range */}
      <section id="what-we-do" className="bg-bg">
        <div className="max-w-6xl mx-auto px-4 py-20">
          <div className="max-w-3xl">
            <p className="text-xs font-semibold uppercase tracking-[0.3em] text-brand-green-h">
              Every kind of event
            </p>
            <h2 className="mt-3 text-3xl sm:text-4xl font-black tracking-tight text-white">
              If people gather for it, VibePass sells the ticket.
            </h2>
            <p className="mt-5 text-lg text-muted">
              Concerts, culture festivals, gaming nights, workshops, wellness, nightlife —
              every scene has its own crowd, its own format and its own way to sell.
              VibePass powers all of them on one set of rails, with instant M-Pesa checkout
              and the lowest fees in Kenya.
            </p>
          </div>

          <div className="mt-10 grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
            {EVENT_TYPES.map((e) => (
              <Link
                key={e.title}
                href="/events"
                className={`group flex flex-col rounded-2xl border border-line bg-panel overflow-hidden ${GOLD_HOVER}`}
              >
                <div className="aspect-[16/9] overflow-hidden bg-brand-green-panel">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={e.photo}
                    alt=""
                    aria-hidden="true"
                    loading="lazy"
                    className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                  />
                </div>
                <div className="flex flex-1 flex-col p-6">
                  <p className="text-xs font-semibold uppercase tracking-widest text-brand-green-h">
                    {e.category}
                  </p>
                  <h3 className="mt-1 font-bold text-lg text-white group-hover:text-brand-gold-h transition-colors">
                    {e.title}
                  </h3>
                  <p className="mt-2 text-sm text-muted leading-relaxed flex-1">{e.blurb}</p>
                  <dl className="mt-5 space-y-2 border-t border-line pt-4 text-xs">
                    <div className="flex gap-2">
                      <dt className="shrink-0 font-semibold uppercase tracking-wide text-ink/60">
                        Audience
                      </dt>
                      <dd className="text-muted">{e.audience}</dd>
                    </div>
                    <div className="flex gap-2">
                      <dt className="shrink-0 font-semibold uppercase tracking-wide text-ink/60">
                        Pricing
                      </dt>
                      <dd className="text-muted">{e.pricing}</dd>
                    </div>
                  </dl>
                  <span className="mt-4 inline-flex items-center gap-1.5 text-sm font-semibold text-brand-green-h transition-colors group-hover:text-brand-gold-h">
                    Browse events
                    <ArrowRightIcon className="w-4 h-4" />
                  </span>
                </div>
              </Link>
            ))}
          </div>
        </div>
      </section>

      {/* Story — how the platform works (§2 / §3 / §4) */}
      <section className="bg-bg">
        <div className="max-w-6xl mx-auto px-4 py-20">
          <div className="max-w-3xl">
            <p className="text-xs font-semibold uppercase tracking-[0.3em] text-brand-green-h">
              {HOME_INTRO.eyebrow}
            </p>
            <h2 className="mt-3 text-3xl sm:text-5xl font-black tracking-tight text-white">
              {HOME_INTRO.heading}
            </h2>
            <p className="mt-5 text-lg text-muted">{HOME_INTRO.body}</p>
          </div>

          {/* The three ways: Sell · Stage · Scale */}
          <div className="mt-12 grid sm:grid-cols-3 gap-6">
            {HOME_WAYS.map((w) => {
              const card = (
                <>
                  <p className="text-sm font-bold uppercase tracking-widest text-brand-green-h">
                    {w.label}
                  </p>
                  <p className="mt-3 text-sm text-ink/80 leading-relaxed">{w.body}</p>
                  {w.href && (
                    <span className="mt-4 inline-flex items-center gap-1.5 text-sm font-semibold text-brand-green-h transition-colors group-hover:text-brand-gold-h">
                      Explore Bash
                      <ArrowRightIcon className="w-4 h-4" />
                    </span>
                  )}
                </>
              );
              return w.href ? (
                <Link
                  key={w.label}
                  href={w.href}
                  className={`group flex flex-col rounded-2xl border border-line bg-panel p-6 ${GOLD_HOVER}`}
                >
                  {card}
                </Link>
              ) : (
                <div key={w.label} className="rounded-2xl border border-line bg-panel p-6">
                  {card}
                </div>
              );
            })}
          </div>

          {/* Why VibePass — the "why us over them" block */}
          <div className="mt-12">
            <p className="text-xs font-semibold uppercase tracking-[0.3em] text-brand-green-h">
              {HOME_WHY.eyebrow}
            </p>
            <h3 className="mt-2 text-2xl sm:text-3xl font-black tracking-tight text-white">
              {HOME_WHY.heading}
            </h3>
            <p className="mt-4 max-w-3xl text-muted leading-relaxed">{HOME_WHY.body}</p>
            <div className="mt-8 grid sm:grid-cols-2 gap-x-8 gap-y-5">
              {HOME_WHY.items.map((item) => (
                <div key={item.label} className="flex gap-3 border-l-2 border-brand-green pl-4">
                  <div>
                    <p className="font-bold text-white">{item.label}</p>
                    <p className="mt-1 text-sm text-muted leading-relaxed">{item.body}</p>
                  </div>
                </div>
              ))}
            </div>

            {/* Fee-gap stat strip */}
            <div className="mt-10 rounded-2xl border border-line bg-panel p-6 sm:p-8">
              <p className="text-3xl sm:text-4xl font-black tracking-tight text-brand-green-h">
                {HOME_FEE_STAT.figure}
              </p>
              <p className="mt-2 text-sm text-muted leading-relaxed">{HOME_FEE_STAT.caption}</p>
            </div>

            {/* See the difference — comparison table */}
            <div className="mt-10">
              <h4 className="text-xl font-black tracking-tight text-white">
                {HOME_COMPARISON.heading}
              </h4>
              <div className="mt-4 overflow-x-auto">
                <table className="w-full min-w-[560px] border-separate border-spacing-0 overflow-hidden rounded-2xl border border-line text-sm">
                  <thead>
                    <tr className="bg-panel">
                      <th className="p-4 text-left font-semibold text-ink/60" scope="col">
                        <span className="sr-only">Feature</span>
                      </th>
                      {HOME_COMPARISON.columns.map((col, i) => (
                        <th
                          key={col}
                          scope="col"
                          className={`p-4 text-left font-bold ${i === 0 ? "text-brand-green-h" : "text-muted"}`}
                        >
                          {col}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {HOME_COMPARISON.rows.map((row) => (
                      <tr key={row.label}>
                        <th
                          scope="row"
                          className="border-t border-line p-4 text-left font-semibold text-white"
                        >
                          {row.label}
                        </th>
                        <td className="border-t border-line p-4 font-semibold text-white">
                          {row.vibepass}
                        </td>
                        <td className="border-t border-line p-4 text-muted">{row.others}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* CTAs */}
            <div className="mt-8 flex flex-wrap gap-3">
              <Link
                href={HOME_WHY_CTA.primary.href}
                className="rounded-full bg-brand-green px-6 py-3 text-sm font-bold text-white transition-colors hover:bg-brand-green-deep"
              >
                {HOME_WHY_CTA.primary.label}
              </Link>
              <Link
                href={HOME_WHY_CTA.secondary.href}
                className="rounded-full border border-line px-6 py-3 text-sm font-bold text-white transition-colors hover:border-brand-gold"
              >
                {HOME_WHY_CTA.secondary.label}
              </Link>
            </div>
          </div>
        </div>
      </section>

      <ContactSection />
      <SiteFooter />
    </div>
  );
}
