import { createFileRoute, Link } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery } from "@tanstack/react-query";
import { ArrowRight, BookOpen, Megaphone, Music, Users } from "lucide-react";
import {
  listBooks,
  listTestimonials,
  listUpcomingEvents,
  listVideos,
  type BookDto,
  type EventDto,
  type VideoDto,
} from "@/lib/public-data.functions";
import { imgs } from "@/lib/assets";
import { site } from "@/lib/site";
import { Reveal } from "@/components/brand/Reveal";
import { ArchImage, CircleBadge, GoldRule, LeafShadow, MonogramWatermark } from "@/components/brand/decor";
import { TestimonialCarousel } from "@/components/brand/TestimonialCarousel";
import { NewsletterForm } from "@/components/brand/NewsletterForm";
import { DailyEncouragement } from "@/components/brand/DailyEncouragement";
import { FloatingPill } from "@/components/brand/FloatingPill";
import { Button } from "@/components/ui/button";
import { formatPublicEventDate } from "@/lib/event-date";

const booksQ = queryOptions({ queryKey: ["books"], queryFn: () => listBooks() });
const eventsQ = queryOptions({ queryKey: ["events"], queryFn: () => listUpcomingEvents() });
const testimonialsQ = queryOptions({ queryKey: ["testimonials"], queryFn: () => listTestimonials() });
const videosQ = queryOptions({ queryKey: ["videos"], queryFn: () => listVideos() });

export const Route = createFileRoute("/")({
  loader: ({ context }) =>
    Promise.all([
      context.queryClient.ensureQueryData(booksQ),
      context.queryClient.ensureQueryData(eventsQ),
      context.queryClient.ensureQueryData(testimonialsQ),
      context.queryClient.ensureQueryData(videosQ),
    ]),
  head: () => ({
    meta: [
      { title: "Eva Shii Jason — Lives of Purpose, A Greater Tomorrow" },
      {
        name: "description",
        content:
          "Author, worship minister, gospel recording artist, vocal coach, speaker and mentor in Nairobi, Kenya. Books, mentorship and speaking that lead, empower and transform — for a brighter tomorrow.",
      },
      { property: "og:title", content: "Eva Shii Jason — Lives of Purpose, A Greater Tomorrow" },
      {
        property: "og:description",
        content:
          "Books, worship, mentorship and speaking that awaken lives of purpose. People. Purpose. Possibilities.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
    scripts: [
      {
        type: "application/ld+json",
        children: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "Person",
          name: site.name,
          alternateName: site.legalName,
          jobTitle: "Author, Worship Minister, Speaker & Mentor",
          address: { "@type": "PostalAddress", addressLocality: "Nairobi", addressCountry: "KE" },
          sameAs: site.socials.map((s) => s.href),
          knowsAbout: ["Purpose", "Worship", "Leadership", "Mentorship", "Vocal Coaching"],
        }),
      },
    ],
  }),
  component: HomePage,
});

function Hero({ latest }: { latest?: BookDto | null }) {
  return (
    <section className="relative overflow-hidden bg-jungle pb-20 pt-32 text-ivory sm:pt-36">
      <LeafShadow className="opacity-[0.07]" />
      <MonogramWatermark className="absolute -left-10 top-24 text-[18rem] sm:-left-16" />
      <div className="relative mx-auto grid max-w-6xl items-center gap-12 px-4 sm:px-6 lg:grid-cols-2">
        <Reveal>
          <div>
            <p className="eyebrow text-[0.65rem] text-gold-light">
              {site.name} · {site.location}
            </p>
            <h1 className="mt-6 font-display text-5xl leading-[1.05] sm:text-6xl lg:text-7xl">
              Lives awakened for a Greater{" "}
              <span className="gold-text">Tomorrow.</span>
            </h1>
            <p className="mt-7 max-w-md text-base leading-relaxed text-ivory/80">
              Eva Shii Jason is a Christian author, worship minister, gospel recording artist, vocal
              coach, speaker, mentor and marketplace leader — walking with people as they discover
              their God-given identity, embrace their purpose, and steward every assignment.
            </p>
            <div className="mt-9 flex flex-wrap gap-3">
              <Button asChild variant="gold" size="xl" className="rounded-full">
                <Link to="/books">
                  <BookOpen className="h-4 w-4" /> Explore the books
                </Link>
              </Button>
              <Button asChild variant="outline-ivory" size="xl" className="rounded-full">
                <Link to="/contact">
                  Book Eva <ArrowRight className="h-4 w-4" />
                </Link>
              </Button>
            </div>
            {latest ? (
              <p className="mt-8 text-sm text-ivory/60">
                New book to look out for:{" "}
                <Link to="/books" className="link-gold font-semibold text-gold-light">
                  {latest.title}
                </Link>
              </p>
            ) : null}
          </div>
        </Reveal>
        <Reveal delayMs={150} className="relative mx-auto w-full max-w-sm">
          <div className="arch aspect-[4/5] outline outline-gold/40 outline-offset-[10px]">
          <img
            src={imgs.homePortrait}
            alt={`${site.name} smiling in a gold blouse`}
            className="block h-full w-full object-cover object-[55%_center]"
            fetchPriority="high"
          />
          </div>
        </Reveal>
      </div>
      <div className="relative mx-auto mt-14 max-w-6xl px-4 sm:px-6">
        <p className="eyebrow text-center text-[0.6rem] text-gold-light">
          {site.roles.join("  ·  ")}
        </p>
      </div>
    </section>
  );
}

function BrandEssence() {
  const pillars = [
    { word: "People", verb: "Empower", icon: Users, tone: "jungle" as const, text: "Empower individuals to know who they are." },
    { word: "Purpose", verb: "Inspire", icon: Music, tone: "gold" as const, text: "Live with intention, on assignment." },
    { word: "Possibilities", verb: "Transform", icon: Megaphone, tone: "terra" as const, text: "Create a brighter tomorrow." },
  ];
  return (
    <section className="section-pad relative overflow-hidden">
      <div className="mx-auto max-w-6xl px-4 sm:px-6">
        <Reveal className="text-center">
          <p className="eyebrow text-[0.62rem] text-terra">Brand essence</p>
          <h2 className="mt-4 font-display text-4xl text-jungle sm:text-5xl">
            People. Purpose.{" "}
            <span className="gold-text">Possibilities.</span>
          </h2>
          <GoldRule className="mt-7" />
        </Reveal>
        <div className="mt-14 grid gap-6 md:grid-cols-3">
          {pillars.map((p, i) => (
            <Reveal key={p.word} delayMs={i * 120}>
              <div className="card-lift flex h-full flex-col items-center gap-4 rounded-2xl border border-gold/25 bg-card p-9 text-center">
                <CircleBadge tone={p.tone}>
                  <p.icon className="h-5 w-5" />
                </CircleBadge>
                <h3 className="font-display text-2xl text-jungle">{p.word}</h3>
                <p className="eyebrow text-[0.55rem] text-terra">{p.verb}</p>
                <p className="text-sm leading-relaxed text-muted-foreground">{p.text}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function LatestBooks({ books }: { books: BookDto[] }) {
  return (
    <section className="section-pad relative overflow-hidden bg-jungle-deep text-ivory">
      <LeafShadow className="opacity-[0.06]" />
      <MonogramWatermark className="absolute -right-8 bottom-0 text-[16rem]" />
      <div className="relative mx-auto max-w-6xl px-4 sm:px-6">
        <Reveal className="text-center">
          <p className="eyebrow text-[0.62rem] text-gold-light">Books for a brighter tomorrow</p>
          <h2 className="mt-4 font-display text-4xl sm:text-5xl">
            Real insights. Practical tools.{" "}
            <span className="gold-text">Lasting impact.</span>
          </h2>
        </Reveal>
        <div className="mt-14 grid items-center gap-10 md:grid-cols-2">
          <Reveal>
            <div className="relative mx-auto max-w-md">
              <img
                src={imgs.flyerGoodNeighbour}
                alt={`${books.find((b) => b.featured)?.title ?? "A Good Neighbour"} — new book promo artwork with the author and book cover`}
                loading="lazy"
                className="w-full rounded-2xl border border-gold/30 shadow-2xl"
              />
            </div>
          </Reveal>
          <Reveal delayMs={140}>
            <div>
              {books
                .filter((b) => b.featured)
                .slice(0, 2)
                .map((b) => (
                  <div key={b.id} className="mb-8 border-b border-ivory/10 pb-8 last:mb-0 last:border-0 last:pb-0">
                    <p className="eyebrow text-[0.55rem] text-gold-light">{b.category ?? "Book"}</p>
                    <h3 className="mt-2 font-display text-3xl">{b.title}</h3>
                    <p className="mt-1 font-script text-xl text-gold-light">{b.subtitle}</p>
                    {b.description ? (
                      <p className="mt-3 max-w-md text-sm leading-relaxed text-ivory/75">{b.description}</p>
                    ) : null}
                  </div>
                ))}
              <Button asChild variant="gold" size="xl" className="mt-8 rounded-full">
                <Link to="/books">
                  See all books <ArrowRight className="h-4 w-4" />
                </Link>
              </Button>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function AboutTeaser() {
  return (
    <section className="section-pad relative overflow-hidden">
      <div className="mx-auto grid max-w-6xl items-center gap-12 px-4 sm:px-6 lg:grid-cols-2">
        <Reveal className="order-2 h-[420px] max-w-sm sm:h-[520px] lg:order-1">
          <ArchImage src={imgs.blue} alt={`${site.name} in a royal-blue gown`} className="h-full" />
        </Reveal>
        <Reveal delayMs={120} className="order-1 lg:order-2">
          <p className="eyebrow text-[0.62rem] text-terra">About Eva</p>
          <h2 className="mt-4 font-display text-4xl text-jungle sm:text-5xl">
            Lead. Empower. <span className="gold-text">Transform.</span>
          </h2>
          <p className="mt-6 max-w-lg leading-relaxed text-muted-foreground">
            A purpose-driven leader devoted to empowering individuals and organizations to unlock
            their potential — through books, worship, mentorship and strategic engagement that
            inspire intentional choices and lasting growth.
          </p>
          <Button asChild variant="outline-gold" className="mt-8">
            <Link to="/about">
              Read her story <ArrowRight className="h-4 w-4" />
            </Link>
          </Button>
        </Reveal>
      </div>
    </section>
  );
}

function SpeakingTeaser() {
  const offers = [
    { icon: Megaphone, title: "Speaking", tone: "jungle" as const, text: "Keynotes and sessions on purpose, faith and leadership that move audiences to act." },
    { icon: Users, title: "Mentorship", tone: "gold" as const, text: "Structured journeys on identity, calling and stewarding every assignment." },
    { icon: Music, title: "Vocal Coaching", tone: "terra" as const, text: "Heart and skill — training worshippers and vocalists beyond the music." },
  ];
  return (
    <section className="section-pad bg-secondary">
      <div className="mx-auto max-w-6xl px-4 sm:px-6">
        <Reveal className="text-center">
          <p className="eyebrow text-[0.62rem] text-terra">Speaking & mentorship</p>
          <h2 className="mt-4 font-display text-4xl text-jungle sm:text-5xl">
            Walk with Eva <span className="gold-text">in person.</span>
          </h2>
        </Reveal>
        <div className="mt-14 grid gap-6 md:grid-cols-3">
          {offers.map((o, i) => (
            <Reveal key={o.title} delayMs={i * 120}>
              <div className="card-lift flex h-full flex-col gap-4 rounded-2xl border border-gold/25 bg-card p-9">
                <CircleBadge tone={o.tone}>
                  <o.icon className="h-5 w-5" />
                </CircleBadge>
                <h3 className="font-display text-2xl text-jungle">{o.title}</h3>
                <p className="text-sm leading-relaxed text-muted-foreground">{o.text}</p>
              </div>
            </Reveal>
          ))}
        </div>
        <Reveal className="mt-10 text-center">
          <Button asChild variant="green" size="xl" className="rounded-full">
            <Link to="/speaking">
              Explore speaking & mentorship <ArrowRight className="h-4 w-4" />
            </Link>
          </Button>
        </Reveal>
      </div>
    </section>
  );
}

function EventsBand({ events }: { events: EventDto[] }) {
  if (events.length === 0) return null;
  return (
    <section className="section-pad relative overflow-hidden">
      <MonogramWatermark className="absolute -left-6 bottom-0 text-[14rem]" />
      <div className="relative mx-auto max-w-6xl px-4 sm:px-6">
        <Reveal className="text-center">
          <p className="eyebrow text-[0.62rem] text-terra">Upcoming gatherings</p>
          <h2 className="mt-4 font-display text-4xl text-jungle sm:text-5xl">
            Where we'll <span className="gold-text">meet next.</span>
          </h2>
        </Reveal>
        <div className="mx-auto mt-12 max-w-3xl">
          {events.map((e, i) => (
            <Reveal key={e.id} delayMs={i * 100}>
              <div className="card-lift mb-5 flex flex-col gap-2 rounded-2xl border border-gold/25 bg-card p-6 sm:flex-row sm:items-center sm:justify-between sm:gap-6 sm:p-7">
                <div>
                  <h3 className="font-display text-xl text-jungle">{e.title}</h3>
                  <p className="mt-1 text-sm font-semibold tracking-wide text-terra">
                    {formatPublicEventDate(e)}
                    {e.location ? ` · ${e.location}` : ""}
                  </p>
                  {e.description ? (
                    <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{e.description}</p>
                  ) : null}
                </div>
                <Button asChild variant="outline-gold" size="sm" className="shrink-0 rounded-full">
                  <Link to="/contact">Enquire</Link>
                </Button>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function VideosBand({ videos }: { videos: VideoDto[] }) {
  if (videos.length === 0) return null;
  return (
    <section className="section-pad bg-secondary">
      <div className="mx-auto max-w-6xl px-4 sm:px-6">
        <Reveal className="text-center">
          <p className="eyebrow text-[0.62rem] text-terra">Watch & listen</p>
          <h2 className="mt-4 font-display text-4xl text-jungle sm:text-5xl">
            Latest from <span className="gold-text">Eva.</span>
          </h2>
        </Reveal>
        <div className="mt-12 flex flex-wrap justify-center gap-6">
          {videos.slice(0, 3).map((v, i) => (
            <Reveal key={v.id} delayMs={i * 110} className="w-full sm:w-[21rem]">
              <a
                href={v.video_url}
                target="_blank"
                rel="noreferrer"
                className="card-lift flex h-full flex-col overflow-hidden rounded-2xl border border-gold/25 bg-card"
              >
                {v.thumbnail_url ? (
                  <img
                    src={v.thumbnail_url}
                    alt={v.title}
                    loading="lazy"
                    className={`aspect-video w-full object-cover ${
                      v.video_url.includes("/post/") ? "object-top" : "object-center"
                    }`}
                  />
                ) : (
                  <div className="relative flex aspect-video items-center justify-center bg-jungle">
                    <MonogramWatermark className="absolute text-[7rem]" />
                    <span className="relative flex h-14 w-14 items-center justify-center rounded-full border border-gold/60 bg-gold/10">
                      <span className="ml-1 h-0 w-0 border-y-[9px] border-l-[14px] border-y-transparent border-l-gold" />
                    </span>
                  </div>
                )}
                <div className="flex flex-1 flex-col gap-2 p-6">
                  <h3 className="font-display text-xl text-jungle">{v.title}</h3>
                  {v.description ? (
                    <p className="text-sm leading-relaxed text-muted-foreground">{v.description}</p>
                  ) : null}
                </div>
              </a>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function TestimonialsBand({ items }: { items: Awaited<ReturnType<typeof listTestimonials>> }) {
  if (items.length === 0) return null;
  return (
    <section className="section-pad relative overflow-hidden bg-jungle text-ivory">
      <LeafShadow className="opacity-[0.06]" />
      <div className="relative mx-auto max-w-6xl px-4 sm:px-6">
        <Reveal className="mb-12 text-center">
          <p className="eyebrow text-[0.62rem] text-gold-light">Voices along the journey</p>
          <h2 className="mt-4 font-display text-4xl sm:text-5xl">
            What people <span className="gold-text">carry away.</span>
          </h2>
        </Reveal>
        <TestimonialCarousel items={items} />
      </div>
    </section>
  );
}

function NewsletterBand() {
  return (
    <section className="section-pad relative overflow-hidden bg-jungle-deep text-ivory">
      <MonogramWatermark className="absolute -right-6 top-6 text-[13rem]" />
      <div className="relative mx-auto grid max-w-6xl gap-10 px-4 sm:px-6 lg:grid-cols-2">
        <Reveal>
          <div>
            <p className="eyebrow text-[0.62rem] text-gold-light">Newsletter & community</p>
            <h2 className="mt-4 font-display text-4xl leading-tight sm:text-5xl">
              Join the journey to a{" "}
              <span className="gold-text">brighter tomorrow.</span>
            </h2>
            <p className="mt-5 max-w-md text-sm leading-relaxed text-ivory/75">
              New books, events and videos — straight to your inbox. Read. Grow. Make a difference.
            </p>
            <div className="mt-8 max-w-md">
              <DailyEncouragement />
            </div>
          </div>
        </Reveal>
        <Reveal delayMs={140} className="self-center">
          <div className="rounded-2xl border border-gold/30 bg-jungle/60 p-8 sm:p-10">
            <p className="eyebrow text-[0.6rem] text-gold-light">Stay connected</p>
            <div className="mt-6">
              <NewsletterForm />
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function HomePage() {
  const [books, events, testimonials, videos] = [
    useSuspenseQuery(booksQ).data,
    useSuspenseQuery(eventsQ).data,
    useSuspenseQuery(testimonialsQ).data,
    useSuspenseQuery(videosQ).data,
  ];
  const latest = books.find((b) => b.featured) ?? books[0] ?? null;

  return (
    <>
      <Hero latest={latest} />
      <BrandEssence />
      <LatestBooks books={books} />
      <AboutTeaser />
      <SpeakingTeaser />
      <EventsBand events={events} />
      <VideosBand videos={videos} />
      <TestimonialsBand items={testimonials} />
      <NewsletterBand />
      <FloatingPill latest={latest} />
    </>
  );
}
