import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import { ArrowRight, Hammer, Leaf, PackageCheck, ShieldCheck, Sparkles, Truck } from "lucide-react";
import { isLocale, type Locale } from "@/lib/i18n/config";
import { getDictionary } from "@/lib/i18n";
import { categoryTitle, getBestSellers, getCategories, getFeaturedProducts } from "@/lib/catalog";
import { getSettings, setting } from "@/lib/settings";
import { formatPrice } from "@/lib/money";
import { buildMetadata, jsonLd } from "@/lib/seo";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { ProductCard } from "@/components/store/product-card";
import { NewsletterForm } from "@/components/store/newsletter-form";
import { Reveal } from "@/components/store/reveal";

const fallbackCategoryImages: Record<string, string> = {
  tapis: "/images/cat-rugs.jpg",
  ceramiques: "/images/cat-ceramics.jpg",
  luminaires: "/images/cat-lighting.jpg",
  mobilier: "/images/cat-furniture.jpg",
  cuir: "/images/cat-leather.jpg",
  textiles: "/images/cat-textiles.jpg",
  objets: "/images/cat-objects.jpg",
  cadeaux: "/images/cat-gifts.jpg",
};

export async function generateMetadata({ params }: { params: Promise<{ locale: string }> }) {
  const { locale: raw } = await params;
  if (!isLocale(raw)) return {};
  const locale = raw as Locale;
  const settings = await getSettings();
  const dict = getDictionary(locale);
  return buildMetadata({
    locale,
    title: setting(settings, "seo.title", locale) || dict.meta.defaultTitle,
    description: setting(settings, "seo.description", locale) || dict.meta.defaultDescription,
    image: "/images/hero-main.jpg",
  });
}

export default async function HomePage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale: raw } = await params;
  if (!isLocale(raw)) notFound();
  const locale = raw as Locale;
  const dict = getDictionary(locale);

  const [settings, categories, bestsellers, featured] = await Promise.all([
    getSettings(),
    getCategories(),
    getBestSellers(4),
    getFeaturedProducts(3),
  ]);

  const heroImage = setting(settings, "hero.image") || "/images/hero-main.jpg";
  const collectionImage = setting(settings, "collection.image") || "/images/detail-courtyard.jpg";
  const artisans = setting(settings, "story.stat.artisans");
  const years = setting(settings, "story.stat.years");
  const pieces = setting(settings, "story.stat.pieces");

  const instagramImages = [
    "/images/p-cer-02.jpg",
    "/images/detail-rug-close.jpg",
    "/images/riad-courtyard.jpg",
    "/images/tea-set.jpg",
    "/images/journal-interior.jpg",
    "/images/p-lig-02.jpg",
  ];

  const jsonLdData = {
    "@context": "https://schema.org",
    "@type": "Organization",
    name: "DAR ZELLIGE",
    url: process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000",
    logo: `${process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000"}/favicon.svg`,
    description: setting(settings, "seo.description", locale),
    sameAs: [setting(settings, "social.instagram"), setting(settings, "social.facebook")].filter(Boolean),
    address: {
      "@type": "PostalAddress",
      streetAddress: "12, Derb El Ferrane",
      addressLocality: "Marrakech",
      postalCode: "40000",
      addressCountry: "MA",
    },
  };

  return (
    <>
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLd(jsonLdData) }} />

      <section className="relative grid min-h-[calc(100svh-108px)] grid-cols-1 lg:grid-cols-[0.92fr_1.08fr]">
        <div className="order-2 flex flex-col justify-center px-5 py-14 md:px-12 md:py-20 lg:order-1 lg:px-16 xl:px-20">
          <Reveal>
            <p className="eyebrow">{setting(settings, "hero.eyebrow", locale)}</p>
            <h1 className="mt-6 max-w-xl font-serif text-[2.7rem] font-light leading-[1.02] tracking-[-0.01em] text-charcoal sm:text-6xl lg:text-[4.4rem] xl:text-[5rem]">
              {setting(settings, "hero.title", locale)}
            </h1>
            <p className="mt-7 max-w-md text-[16px] leading-relaxed text-charcoal/65 md:text-[17px]">
              {setting(settings, "hero.description", locale)}
            </p>
            <div className="mt-9 flex flex-wrap items-center gap-3">
              <Button asChild size="lg">
                <Link href={`/${locale}/shop`}>
                  {dict.hero.explore}
                  <ArrowRight className="h-4 w-4 rtl:rotate-180" strokeWidth={1.4} />
                </Link>
              </Button>
              <Button asChild variant="outline" size="lg">
                <Link href={`/${locale}/story`}>{dict.hero.story}</Link>
              </Button>
            </div>
            <div className="mt-10 flex items-center gap-5 border-t border-border pt-5 text-[12px] uppercase tracking-[0.14em] text-charcoal/45">
              <span className="flex items-center gap-2">
                <Truck className="h-3.5 w-3.5" strokeWidth={1.3} />
                {dict.checkout.secure}
              </span>
              <span className="hidden h-3 w-px bg-border sm:block" />
              <span className="hidden sm:inline">{dict.common.madeInMorocco}</span>
            </div>
          </Reveal>
        </div>

        <div className="relative order-1 min-h-[58vh] overflow-hidden bg-sand/30 lg:order-2 lg:min-h-full">
          <Image
            src={heroImage}
            alt={setting(settings, "hero.caption", locale) || "DAR ZELLIGE"}
            fill
            priority
            sizes="(max-width: 1024px) 100vw, 54vw"
            className="object-cover"
          />
          <div className="absolute inset-0 bg-gradient-to-t from-charcoal/30 via-transparent to-transparent" />
          <div className="absolute bottom-5 left-5 right-5 flex items-end justify-between gap-4">
            <p className="max-w-[240px] text-[12px] uppercase tracking-[0.18em] text-ivory/75">
              {setting(settings, "hero.caption", locale)}
            </p>
            <span className="flex h-12 w-12 items-center justify-center border border-ivory/30 text-ivory/80 backdrop-blur-sm">
              <Sparkles className="h-4 w-4" strokeWidth={1.1} />
            </span>
          </div>
          <div className="absolute right-5 top-5 hidden items-center gap-3 bg-ivory/90 px-4 py-3 backdrop-blur md:flex">
            <span className="font-serif text-2xl leading-none text-charcoal">{years}</span>
            <span className="max-w-[90px] text-[11px] uppercase leading-tight tracking-[0.16em] text-charcoal/50">
              {dict.home.statsYears}
            </span>
          </div>
        </div>
      </section>

      <section className="border-y border-border bg-cream/50">
        <div className="shell grid grid-cols-2 divide-x divide-border/70 md:grid-cols-4">
          {[
            { icon: Truck, title: dict.cart.freeShipping, text: dict.home.badgeShipping },
            { icon: ShieldCheck, title: dict.common.securePayment, text: dict.home.badgePayment },
            { icon: PackageCheck, title: dict.footer.shipping, text: dict.home.badgeReturns },
            { icon: Hammer, title: dict.common.handmade, text: "Marrakech" },
          ].map((item) => (
            <div key={item.title} className="flex items-center gap-3 px-3 py-5 md:px-6">
              <item.icon className="h-4 w-4 shrink-0 text-gold" strokeWidth={1.3} />
              <div>
                <p className="text-[12px] uppercase tracking-[0.12em] text-charcoal">{item.title}</p>
                <p className="mt-0.5 text-[12px] text-charcoal/40">{item.text}</p>
              </div>
            </div>
          ))}
        </div>
      </section>

      <section className="shell py-20 md:py-28">
        <Reveal className="flex flex-col justify-between gap-6 md:flex-row md:items-end">
          <div>
            <p className="eyebrow">{dict.home.categoriesEyebrow}</p>
            <h2 className="mt-4 max-w-2xl font-serif text-4xl font-light leading-[1.08] tracking-tight md:text-5xl">
              {dict.home.categoriesTitle}
            </h2>
          </div>
          <p className="max-w-sm text-[15px] leading-relaxed text-charcoal/55">
            {dict.home.categoriesDescription}
          </p>
        </Reveal>

        <div className="mt-10 grid grid-cols-2 gap-3 md:mt-14 md:grid-cols-4 md:gap-5">
          {categories.slice(0, 4).map((category, index) => (
            <Reveal
              key={category.id}
              delay={index * 0.08}
              className={index === 0 ? "col-span-2 row-span-2 md:col-span-2" : ""}
            >
              <Link
                href={`/${locale}/shop?category=${category.slug}`}
                className="group relative block h-full overflow-hidden bg-sand/25"
              >
                <div className={index === 0 ? "relative aspect-[4/3] md:aspect-[4/3.5]" : "relative aspect-[4/3] md:aspect-[4/3]"}>
                  <Image
                    src={category.image || fallbackCategoryImages[category.slug] || "/images/cat-objects.jpg"}
                    alt={categoryTitle(category, locale)}
                    fill
                    sizes={index === 0 ? "(max-width: 768px) 100vw, 50vw" : "(max-width: 768px) 50vw, 25vw"}
                    className="object-cover transition-transform duration-[1100ms] group-hover:scale-[1.04]"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-charcoal/55 via-charcoal/5 to-transparent" />
                </div>
                <div className="absolute inset-x-0 bottom-0 flex items-end justify-between gap-4 p-4 md:p-6">
                  <div>
                    <h3 className={`font-serif font-light text-ivory ${index === 0 ? "text-2xl md:text-4xl" : "text-lg md:text-2xl"}`}>
                      {categoryTitle(category, locale)}
                    </h3>
                    <p className="mt-1 text-[12px] uppercase tracking-[0.18em] text-ivory/55">
                      {category._count.products} {dict.shop.productsCount}
                    </p>
                  </div>
                  <span className="flex h-8 w-8 shrink-0 items-center justify-center border border-ivory/30 text-ivory transition-colors group-hover:bg-ivory group-hover:text-charcoal">
                    <ArrowRight className="h-3.5 w-3.5 rtl:rotate-180" />
                  </span>
                </div>
              </Link>
            </Reveal>
          ))}
        </div>

        <div className="mt-8 flex justify-end">
          <Link
            href={`/${locale}/collections`}
            className="inline-flex items-center gap-2 text-[12px] uppercase tracking-[0.18em] text-charcoal/60 transition-colors hover:text-charcoal"
          >
            {dict.common.viewAll}
            <ArrowRight className="h-3.5 w-3.5 rtl:rotate-180" />
          </Link>
        </div>
      </section>

      <section className="border-t border-border bg-cream/40 py-20 md:py-28">
        <div className="shell">
          <Reveal className="flex flex-col justify-between gap-5 md:flex-row md:items-end">
            <div>
              <p className="eyebrow">{dict.home.bestsellersEyebrow}</p>
              <h2 className="mt-4 font-serif text-4xl font-light tracking-tight md:text-5xl">
                {dict.home.bestsellersTitle}
              </h2>
            </div>
            <Link
              href={`/${locale}/shop?sort=best-selling`}
              className="group inline-flex items-center gap-2 text-[12px] uppercase tracking-[0.18em] text-charcoal/60 hover:text-charcoal"
            >
              {dict.common.viewAll}
              <ArrowRight className="h-3.5 w-3.5 transition-transform group-hover:translate-x-1 rtl:rotate-180" />
            </Link>
          </Reveal>

          {bestsellers.length > 0 ? (
            <div className="mt-10 grid grid-cols-2 gap-x-4 gap-y-10 md:mt-14 md:grid-cols-4 md:gap-x-6">
              {bestsellers.map((product, index) => (
                <Reveal key={product.id} delay={index * 0.06}>
                  <ProductCard product={product} locale={locale} dict={dict} priority={index < 2} />
                </Reveal>
              ))}
            </div>
          ) : (
            <p className="mt-10 text-sm text-charcoal/50">{dict.shop.noResultsDesc}</p>
          )}
        </div>
      </section>

      <section className="shell grid items-center gap-10 py-20 md:py-28 lg:grid-cols-2 lg:gap-20">
        <Reveal className="relative">
          <div className="relative aspect-[4/5] overflow-hidden bg-sand/30">
            <Image
              src={setting(settings, "story.image") || "/images/story-pottery.jpg"}
              alt={setting(settings, "story.title", locale)}
              fill
              sizes="(max-width: 1024px) 100vw, 45vw"
              className="object-cover"
            />
          </div>
          <div className="absolute -bottom-5 end-5 border border-border bg-cream px-6 py-5 shadow-soft lg:-right-8">
            <p className="font-serif text-3xl leading-none text-charcoal">{pieces}+</p>
            <p className="mt-1 text-[11px] uppercase tracking-[0.18em] text-charcoal/45">{dict.home.statsPieces}</p>
          </div>
        </Reveal>

        <Reveal delay={0.1} className="lg:py-6">
          <p className="eyebrow">{setting(settings, "story.eyebrow", locale)}</p>
          <h2 className="mt-4 max-w-lg font-serif text-4xl font-light leading-[1.08] tracking-tight md:text-5xl">
            {setting(settings, "story.title", locale)}
          </h2>
          <p className="mt-6 max-w-lg text-[16px] leading-[1.85] text-charcoal/65">
            {setting(settings, "story.text1", locale)}
          </p>
          <p className="mt-4 max-w-lg text-[16px] leading-[1.85] text-charcoal/65">
            {setting(settings, "story.text2", locale)}
          </p>
          <div className="mt-8 flex flex-wrap items-center gap-x-10 gap-y-5 border-t border-border pt-7">
            {[
              { value: artisans, label: dict.home.statsArtisans },
              { value: years, label: dict.home.statsYears },
              { value: pieces, label: dict.home.statsPieces },
            ].map((stat) => (
              <div key={stat.label}>
                <p className="font-serif text-3xl leading-none text-charcoal">{stat.value}</p>
                <p className="mt-1.5 text-[11px] uppercase tracking-[0.18em] text-charcoal/40">{stat.label}</p>
              </div>
            ))}
          </div>
          <Button asChild variant="outline" className="mt-8">
            <Link href={`/${locale}/story`}>{dict.home.storyCta}</Link>
          </Button>
        </Reveal>
      </section>

      <section className="relative overflow-hidden bg-charcoal text-ivory">
        <div className="grid lg:grid-cols-2">
          <div className="relative order-2 min-h-[380px] lg:order-1 lg:min-h-[560px]">
            <Image
              src={collectionImage}
              alt={setting(settings, "collection.title", locale)}
              fill
              sizes="(max-width: 1024px) 100vw, 50vw"
              className="object-cover"
            />
            <div className="absolute inset-0 bg-gradient-to-r from-charcoal/20 to-transparent" />
          </div>
          <div className="order-1 flex flex-col justify-center px-5 py-16 md:px-14 lg:order-2 lg:px-20 lg:py-24">
            <Reveal>
              <p className="eyebrow">{setting(settings, "collection.eyebrow", locale)}</p>
              <h2 className="mt-4 max-w-md font-serif text-4xl font-light leading-[1.05] tracking-tight md:text-6xl">
                {setting(settings, "collection.title", locale)}
              </h2>
              <p className="mt-6 max-w-md text-[15px] leading-[1.9] text-ivory/55">
                {setting(settings, "collection.description", locale)}
              </p>
              <div className="mt-8 flex flex-wrap gap-6 border-y border-ivory/15 py-5">
                {featured.slice(0, 2).map((product) => (
                  <Link
                    key={product.id}
                    href={`/${locale}/product/${product.slug}`}
                    className="group flex items-center gap-3"
                  >
                    {product.images[0] && (
                      <span className="relative block h-12 w-10 overflow-hidden">
                        <Image src={product.images[0].url} alt="" fill sizes="40px" className="object-cover" />
                      </span>
                    )}
                    <span>
                      <span className="block max-w-[150px] truncate font-serif text-sm text-ivory/85 group-hover:text-ivory">
                        {product.translations.find((t) => t.locale === locale)?.name ??
                          product.translations[0]?.name}
                      </span>
                      <span className="mt-0.5 block text-[12px] text-ivory/40">
                        {formatPrice(product.price, locale)}
                      </span>
                    </span>
                  </Link>
                ))}
              </div>
              <Button asChild variant="gold" size="lg" className="mt-8">
                <Link href={setting(settings, "collection.href") || `/${locale}/shop?featured=1`}>
                  {dict.home.collectionCta}
                  <ArrowRight className="h-4 w-4 rtl:rotate-180" />
                </Link>
              </Button>
            </Reveal>
          </div>
        </div>
      </section>

      <section className="shell py-20 md:py-28">
        <Reveal className="mx-auto max-w-2xl text-center">
          <p className="eyebrow">{dict.home.craftEyebrow}</p>
          <h2 className="mt-4 font-serif text-4xl font-light tracking-tight md:text-5xl">{dict.home.craftTitle}</h2>
          <p className="mt-5 text-[15px] leading-relaxed text-charcoal/55">{dict.home.craftIntro}</p>
        </Reveal>

        <div className="mt-12 grid gap-10 md:mt-16 md:grid-cols-3 md:gap-6">
          {[
            {
              image: setting(settings, "craft.image1") || "/images/story-weaving.jpg",
              number: "01",
              title: dict.home.craft1Title,
              text: dict.home.craft1Text,
            },
            {
              image: setting(settings, "craft.image2") || "/images/p-rug-01.jpg",
              number: "02",
              title: dict.home.craft2Title,
              text: dict.home.craft2Text,
            },
            {
              image: setting(settings, "craft.image3") || "/images/detail-clay.jpg",
              number: "03",
              title: dict.home.craft3Title,
              text: dict.home.craft3Text,
            },
          ].map((step, index) => (
            <Reveal key={step.number} delay={index * 0.08} className="group">
              <div className="relative aspect-[4/5] overflow-hidden bg-sand/20">
                <Image
                  src={step.image}
                  alt={step.title}
                  fill
                  sizes="(max-width: 768px) 100vw, 33vw"
                  className="object-cover transition-transform duration-[1200ms] group-hover:scale-[1.04]"
                />
                <span className="absolute left-4 top-4 font-serif text-xs text-ivory/80">{step.number}</span>
              </div>
              <div className="mt-5 border-t border-border pt-4">
                <h3 className="font-serif text-2xl font-light">{step.title}</h3>
                <p className="mt-2.5 text-[14px] leading-relaxed text-charcoal/55">{step.text}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </section>

      <section className="border-y border-border bg-[#EFE8DA] py-20 md:py-24">
        <div className="shell">
          <Reveal className="flex flex-col justify-between gap-4 md:flex-row md:items-end">
            <div>
              <p className="eyebrow">{dict.home.testimonialsEyebrow}</p>
              <h2 className="mt-4 font-serif text-4xl font-light tracking-tight md:text-5xl">
                {dict.home.testimonialsTitle}
              </h2>
            </div>
            <Badge variant="outline" className="w-fit border-charcoal/20 text-charcoal/45">
              {dict.common.sample}
            </Badge>
          </Reveal>

          <div className="mt-10 grid gap-5 md:grid-cols-3">
            {dict.home.testimonials.map((testimonial, index) => (
              <Reveal key={testimonial.name} delay={index * 0.07} className="flex h-full flex-col justify-between border border-charcoal/10 bg-cream/70 p-6 md:p-8">
                <div>
                  <span className="font-serif text-4xl leading-none text-gold">“</span>
                  <p className="mt-3 text-[15px] leading-[1.85] text-charcoal/70">{testimonial.quote}</p>
                </div>
                <div className="mt-6 border-t border-border pt-4">
                  <p className="text-[13px] font-semibold uppercase tracking-[0.12em] text-charcoal">
                    {testimonial.name}
                  </p>
                  <p className="mt-1 text-[12px] text-charcoal/40">
                    {testimonial.role} · {testimonial.city}
                  </p>
                </div>
              </Reveal>
            ))}
          </div>
          <p className="mt-6 text-[12px] italic text-charcoal/40">{dict.home.testimonialsNote}</p>
        </div>
      </section>

      <section className="shell py-20 md:py-24">
        <Reveal className="flex flex-col justify-between gap-4 md:flex-row md:items-end">
          <div>
            <p className="eyebrow">{dict.home.instagramEyebrow}</p>
            <h2 className="mt-4 font-serif text-4xl font-light tracking-tight md:text-5xl">
              {dict.home.instagramTitle}
            </h2>
          </div>
          <a
            href={setting(settings, "social.instagram") || "https://instagram.com"}
            target="_blank"
            rel="noreferrer noopener"
            className="text-[12px] uppercase tracking-[0.18em] text-charcoal/55 hover:text-charcoal"
          >
            {dict.home.instagramCta}
          </a>
        </Reveal>

        <div className="mt-8 grid grid-cols-3 gap-2 md:grid-cols-6 md:gap-3">
          {instagramImages.map((image, index) => (
            <a
              key={image}
              href={setting(settings, "social.instagram") || "https://instagram.com"}
              target="_blank"
              rel="noreferrer noopener"
              className="group relative aspect-square overflow-hidden bg-sand/20"
            >
              <Image
                src={image}
                alt={`DAR ZELLIGE — Instagram ${index + 1}`}
                fill
                sizes="(max-width: 768px) 33vw, 16vw"
                className="object-cover transition-transform duration-700 group-hover:scale-105"
              />
              <div className="absolute inset-0 flex items-center justify-center bg-charcoal/25 opacity-0 transition-opacity group-hover:opacity-100">
                <Leaf className="h-4 w-4 text-ivory" strokeWidth={1.2} />
              </div>
            </a>
          ))}
        </div>
      </section>

      <section className="border-t border-border bg-secondary/50">
        <div className="shell grid items-center gap-8 py-16 md:grid-cols-2 md:py-20">
          <Reveal>
            <p className="eyebrow">{dict.newsletter.title}</p>
            <h2 className="mt-4 max-w-lg font-serif text-3xl font-light leading-[1.12] tracking-tight md:text-4xl">
              {dict.home.newsletterTitle}
            </h2>
            <p className="mt-4 max-w-md text-[15px] leading-relaxed text-charcoal/55">
              {dict.home.newsletterDescription}
            </p>
          </Reveal>
          <Reveal delay={0.08} className="w-full md:justify-self-end md:max-w-md">
            <NewsletterForm
              locale={locale}
              labels={{
                placeholder: dict.home.newsletterPlaceholder,
                cta: dict.home.newsletterCta,
                success: dict.home.newsletterSuccess,
                privacy: dict.newsletter.privacy,
              }}
            />
          </Reveal>
        </div>
      </section>
    </>
  );
}