import Link from "next/link";
import { getDictionary } from "@/i18n";
import { sanityFetch } from "@/sanity/client";
import {
  SITE_SETTINGS_QUERY,
  EVENTS_QUERY,
  POSTS_QUERY,
  SERMONS_QUERY,
  LEADERS_QUERY,
  MINISTRIES_QUERY,
  TESTIMONIES_QUERY,
} from "@/sanity/queries";
import { Hero } from "@/components/hero";
import { Reveal } from "@/components/reveal";
import { Button } from "@/components/ui/button";
import { Container, Eyebrow } from "@/components/ui";
import {
  PostCard,
  EventCard,
  SermonCard,
  LeaderCard,
  MinistryCard,
  TestimonyCard,
} from "@/components/cards";

/* eslint-disable @typescript-eslint/no-explicit-any */

export default async function Home({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  const dict = getDictionary(locale);

  const [settings, events, posts, sermons, leaders, ministries, testimonies] =
    await Promise.all([
      sanityFetch<any>(SITE_SETTINGS_QUERY, {}, null),
      sanityFetch<any[]>(EVENTS_QUERY, {}, []),
      sanityFetch<any[]>(POSTS_QUERY, {}, []),
      sanityFetch<any[]>(SERMONS_QUERY, {}, []),
      sanityFetch<any[]>(LEADERS_QUERY, {}, []),
      sanityFetch<any[]>(MINISTRIES_QUERY, {}, []),
      sanityFetch<any[]>(TESTIMONIES_QUERY, {}, []),
    ]);

  const now = Date.now();
  const cmsUpcoming = (events || [])
    .filter(
      (e) => e.startDateTime && new Date(e.startDateTime).getTime() >= now,
    )
    .slice(0, 3);
  const cmsEvents = cmsUpcoming.length ? cmsUpcoming : (events || []).slice(0, 3);

  // Events foretaste: real CMS events when available, otherwise the church's
  // weekly gatherings from the dictionary — each given its next real date so
  // the preview never goes stale. Fallback cards link to the events page.
  const nextOccurrence = (weekday: number, hour: number) => {
    const d = new Date(now);
    d.setHours(hour, 0, 0, 0);
    let add = (weekday - d.getDay() + 7) % 7;
    if (add === 0 && d.getTime() < now) add = 7;
    d.setDate(d.getDate() + add);
    return d.toISOString();
  };
  const weeklyEvents = dict.home.eventsFallback
    .map((e, i) => ({
      _id: `fallback-event-${i}`,
      title: e.title,
      location: e.location,
      startDateTime: nextOccurrence(e.weekday, e.startHour),
      endDateTime: nextOccurrence(e.weekday, e.endHour),
    }))
    .sort((a, b) => a.startDateTime.localeCompare(b.startDateTime));

  // Blog foretaste: latest CMS posts, else evergreen teasers from the
  // dictionary. Fallback cards link to the blog page.
  const cmsPosts = (posts || []).slice(0, 3);
  const fallbackPosts = dict.home.postsFallback.map((p, i) => ({
    _id: `fallback-post-${i}`,
    title: p.title,
    excerpt: p.excerpt,
    author: { name: p.author },
    publishedAt: new Date(now - (i + 1) * 7 * 86400000).toISOString(),
  }));
  const postsAreFallback = cmsPosts.length === 0;
  const shownPosts = postsAreFallback ? fallbackPosts : cmsPosts;

  // Ministries foretaste: CMS content when available, else the bilingual
  // defaults from the dictionary, capped at a six-card preview.
  const shownMinistries = (
    ministries?.length ? ministries : dict.ministries.items
  ).slice(0, 6);
  const gallery =
    settings?.galleryUrl || "https://photos.cityoftestimonies.com";
  const base = `/${locale}`;

  return (
    <>
      <Hero
        locale={locale}
        dict={dict}
        latestSermonSlug={sermons?.[0]?.slug?.current}
      />

      {weeklyEvents.length > 0 && (
        <section className="py-16 sm:py-20">
          <Container>
            <Reveal>
              <div className="flex items-end justify-between gap-6">
                <div>
                  <Eyebrow>{dict.home.weeklyEvents}</Eyebrow>
                  <h2 className="mt-3 text-3xl tracking-tight sm:text-4xl">
                    {dict.home.weeklyEventsLead}
                  </h2>
                </div>
                <Link
                  href={`${base}/events/`}
                  className="hidden shrink-0 text-sm font-semibold text-brand-bright hover:underline sm:inline"
                >
                  {dict.cta.viewAll} →
                </Link>
              </div>
            </Reveal>
            <div className="mt-8 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
              {weeklyEvents.map((e, i) => (
                <Reveal key={e._id} delay={i * 0.06}>
                  <EventCard
                    event={e}
                    locale={locale}
                    dict={dict}
                    href={undefined}
                  />
                </Reveal>
              ))}
            </div>
            <div className="mt-8 sm:hidden">
              <Link
                href={`${base}/events/`}
                className="text-sm font-semibold text-brand-bright hover:underline"
              >
                {dict.cta.seeEvents} →
              </Link>
            </div>
          </Container>
        </section>
      )}

      {shownMinistries.length > 0 && (
        <section className="bg-surface py-16 sm:py-20">
          <Container>
            <Reveal>
              <div className="flex items-end justify-between gap-6">
                <div>
                  <Eyebrow>{dict.home.ministriesEyebrow}</Eyebrow>
                  <h2 className="mt-3 text-3xl tracking-tight sm:text-4xl">
                    {dict.home.ministriesTitle}
                  </h2>
                  <p className="mt-3 max-w-xl text-lg text-ink-soft">
                    {dict.home.ministriesLead}
                  </p>
                </div>
                <Link
                  href={`${base}/ministries/`}
                  className="hidden shrink-0 text-sm font-semibold text-brand-bright hover:underline sm:inline"
                >
                  {dict.cta.allMinistries} →
                </Link>
              </div>
            </Reveal>
            <div className="mt-8 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
              {shownMinistries.map((m: any, i: number) => (
                <Reveal key={m._id || m.name} delay={(i % 3) * 0.06}>
                  <MinistryCard ministry={m} locale={locale} dict={dict} />
                </Reveal>
              ))}
            </div>
            <div className="mt-8 sm:hidden">
              <Link
                href={`${base}/ministries/`}
                className="text-sm font-semibold text-brand-bright hover:underline"
              >
                {dict.cta.allMinistries} →
              </Link>
            </div>
          </Container>
        </section>
      )}

      {cmsEvents.length > 0 && (
        <section className="py-16 sm:py-20 bg-brand-deep ">
          <Container>
            <Reveal>
              <div className="flex items-end justify-between gap-6">
                <div>
                  <Eyebrow className="text-white/80">
                    {dict.home.upcoming}
                  </Eyebrow>
                  <h2 className="mt-3 text-3xl tracking-tight text-white sm:text-4xl">
                    {dict.home.upcomingLead}
                  </h2>
                </div>
                <Link
                  href={`${base}/events/`}
                  className="hidden shrink-0 text-sm font-semibold text-white hover:underline sm:inline"
                >
                  {dict.cta.viewAll} →
                </Link>
              </div>
            </Reveal>
            <div className="mt-8 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
              {cmsEvents.map((e, i) => (
                <Reveal key={e._id} delay={i * 0.06}>
                  <EventCard
                    event={e}
                    locale={locale}
                    dict={dict}
                    href={cmsEvents?.length ? `${base}/events/` : undefined}
                  />
                </Reveal>
              ))}
            </div>
            <div className="mt-8 sm:hidden">
              <Link
                href={`${base}/events/`}
                className="text-sm font-semibold text-white hover:underline"
              >
                {dict.cta.seeEvents} →
              </Link>
            </div>
          </Container>
        </section>
      )}

      {sermons?.length > 0 && (
        <section className="py-16 sm:py-20">
          <Container>
            <Reveal>
              <Eyebrow>{dict.home.latestSermons}</Eyebrow>
              <h2 className="mt-3 text-3xl tracking-tight sm:text-4xl">
                {dict.home.latestSermonsLead}
              </h2>
            </Reveal>
            <div className="mt-8 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
              {sermons.slice(0, 3).map((s, i) => (
                <Reveal key={s._id} delay={i * 0.06}>
                  <SermonCard sermon={s} locale={locale} dict={dict} />
                </Reveal>
              ))}
            </div>
            <div className="mt-8">
              <Link
                href={`${base}/sermons/`}
                className="text-sm font-semibold text-brand-bright hover:underline"
              >
                {dict.cta.viewAll} →
              </Link>
            </div>
          </Container>
        </section>
      )}

      {shownPosts.length > 0 && (
        <section className="bg-surface py-16 sm:py-20">
          <Container>
            <Reveal>
              <div className="flex items-end justify-between gap-6">
                <div>
                  <Eyebrow>{dict.home.latestPosts}</Eyebrow>
                  <h2 className="mt-3 text-3xl tracking-tight sm:text-4xl">
                    {dict.home.latestPostsLead}
                  </h2>
                </div>
                <Link
                  href={`${base}/blog/`}
                  className="hidden shrink-0 text-sm font-semibold text-brand-bright hover:underline sm:inline"
                >
                  {dict.cta.readBlog} →
                </Link>
              </div>
            </Reveal>
            <div className="mt-8 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {shownPosts.map((p, i) => (
                <Reveal key={p._id} delay={i * 0.06}>
                  <PostCard
                    post={p}
                    locale={locale}
                    dict={dict}
                    href={postsAreFallback ? `${base}/blog/` : undefined}
                  />
                </Reveal>
              ))}
            </div>
            <div className="mt-8 sm:hidden">
              <Link
                href={`${base}/blog/`}
                className="text-sm font-semibold text-brand-bright hover:underline"
              >
                {dict.cta.readBlog} →
              </Link>
            </div>
          </Container>
        </section>
      )}

      {/* Signature band: testimonies marquee, or scripture when empty */}
      <section className="relative overflow-hidden bg-brand-deep py-20 text-bg">
        <div aria-hidden className="radiance absolute inset-0 opacity-30" />
        <Container>
          <div className="relative">
            <Eyebrow className="text-white/70">{dict.home.testimonies}</Eyebrow>
            {testimonies?.length > 0 ? (
              <div className="fade-x relative mt-8 overflow-hidden">
                <div className="flex w-max gap-5 animate-marquee">
                  {[...testimonies, ...testimonies].map((t, i) => (
                    <TestimonyCard key={i} testimony={t} locale={locale} />
                  ))}
                </div>
              </div>
            ) : (
              <blockquote className="mt-6 max-w-3xl font-display text-3xl font-bold leading-tight tracking-tight sm:text-4xl">
                {locale === "fr"
                  ? "« Ils l'ont vaincu par le sang de l'Agneau et par la parole de leur témoignage. »"
                  : "“They triumphed by the blood of the Lamb and by the word of their testimony.”"}
                <span className="mt-3 block text-base font-medium uppercase tracking-[0.16em] text-white/70">
                  {locale === "fr" ? "Apocalypse 12.11" : "Revelation 12:11"}
                </span>
              </blockquote>
            )}
          </div>
        </Container>
      </section>

      {leaders?.length > 0 && (
        <section className="py-16 sm:py-20">
          <Container>
            <Reveal>
              <div className="flex items-end justify-between gap-6">
                <div>
                  <Eyebrow>{dict.home.leaders}</Eyebrow>
                  <h2 className="mt-3 text-3xl tracking-tight sm:text-4xl">
                    {dict.home.leadersLead}
                  </h2>
                </div>
                <Link
                  href={`${base}/leadership/`}
                  className="hidden shrink-0 text-sm font-semibold text-brand-bright hover:underline sm:inline"
                >
                  {dict.cta.viewAll} →
                </Link>
              </div>
            </Reveal>
            <div className="mt-8 grid grid-cols-2 gap-5 sm:grid-cols-3 lg:grid-cols-4">
              {leaders.slice(0, 4).map((l, i) => (
                <Reveal key={l._id} delay={i * 0.06}>
                  <LeaderCard leader={l} locale={locale} dict={dict} />
                </Reveal>
              ))}
            </div>
          </Container>
        </section>
      )}

      <section className="pb-24">
        <Container>
          <Reveal>
            <div className="relative overflow-hidden rounded-[2rem] shadow-xl\ bg-ink px-8 py-14 text-bg sm:px-14">
              <div
                aria-hidden
                className="radiance absolute inset-0 opacity-25"
              />
              <div className="relative flex flex-col items-start justify-between gap-8 md:flex-row md:items-center">
                <div>
                  <Eyebrow className="text-white/70">
                    {dict.home.galleryTitle}
                  </Eyebrow>
                  <h2 className="mt-3 max-w-xl text-3xl tracking-tight sm:text-4xl">
                    {dict.home.galleryLead}
                  </h2>
                </div>
                <Button asChild variant="light" size="lg" className="shrink-0">
                  <a href={gallery} target="_blank" rel="noopener noreferrer">
                    {dict.cta.openGallery} →
                  </a>
                </Button>
              </div>
            </div>
          </Reveal>
        </Container>
      </section>
    </>
  );
}
