"use client";

import Link from "next/link";
import { BadgeCheck, RefreshCw, ShieldCheck, Truck } from "lucide-react";
import { FaqAccordion } from "@/components/home/FaqAccordion";
import { HeroMarketplace } from "@/components/home/HeroMarketplace";
import { ProductSlider } from "@/components/home/ProductSlider";
import { PageTransition } from "@/components/motion/PageTransition";
import { ProductCard } from "@/components/product/ProductCard";
import { SafeImage } from "@/components/ui/SafeImage";
import type { Category, Product } from "@/data/types";
import { formatPrice } from "@/lib/format";
import { cn } from "@/lib/cn";
import { isYouthProduct } from "@/lib/products";

const promoBadges = [
  { label: "New", href: "/shop?sort=newest" },
  { label: "Sale", href: "/shop?sort=price-asc" },
];

export type HomeCatalogProps = {
  categories: Category[];
  products: Product[];
  flash: Product[];
  recent: Product[];
  best: Product[];
  arrivals: Product[];
  men: Product[];
  women: Product[];
  kids: Product[];
  baby: Product[];
};

function SectionRule({
  kicker,
  title,
  href,
  action,
}: {
  kicker: string;
  title: string;
  href: string;
  action: string;
}) {
  return (
    <div className="mb-4 flex items-end justify-between gap-3 border-b border-border pb-2.5">
      <div>
        <p className="text-[10px] font-medium uppercase tracking-[0.2em] text-[var(--accent)]">
          {kicker}
        </p>
        <h2 className="font-display text-[1.65rem] leading-none text-foreground sm:text-[1.85rem]">
          {title}
        </h2>
      </div>
      <Link
        href={href}
        className="mb-0.5 shrink-0 text-[11px] font-medium uppercase tracking-[0.14em] text-muted transition hover:text-foreground"
      >
        {action}
      </Link>
    </div>
  );
}

export default function HomeClient({
  categories,
  products,
  flash,
  recent,
  best,
  arrivals,
  men,
  women,
  kids = [],
  baby = [],
}: HomeCatalogProps) {
  const mini = products.find((p) => p.name.includes("Mini Cotton"));
  const culottes = products.find((p) => p.name.includes("Culottes"));
  const baggy = products.find((p) => p.name.includes("Baggy"));
  const easy = products.find((p) => p.name.includes("Easy Waist"));
  const jacket = products.find((p) => p.name.includes("Jacket"));

  const offers = (() => {
    const seen = new Set<string>();
    const list: Product[] = [];
    for (const product of [
      ...flash,
      ...products.filter((item) => Boolean(item.compareAt)),
      ...products,
    ]) {
      if (seen.has(product.id) || isYouthProduct(product)) continue;
      seen.add(product.id);
      list.push(product);
      if (list.length >= 12) break;
    }
    return list;
  })();

  const mosaic = [
    {
      href: jacket ? `/product/${jacket.id}` : "/categories/outerwear",
      title: "Fall layers",
      text: jacket?.name ?? "Packable jacket",
      image:
        jacket?.images[0] ??
        "https://images.unsplash.com/photo-1539533018447-63fcce2678e3?auto=format&fit=crop&w=900&q=80",
      className: "mosaic-tall min-h-[220px] md:min-h-0",
    },
    mini && {
      href: `/product/${mini.id}`,
      title: mini.name,
      text: formatPrice(mini.price),
      image: mini.images[0],
      className: "mosaic-a min-h-[140px] md:min-h-0",
    },
    baggy && {
      href: `/product/${baggy.id}`,
      title: "Now trending",
      text: baggy.name,
      image: baggy.images[0],
      className: "mosaic-b min-h-[140px] md:min-h-0",
    },
    {
      href: "/categories/dresses",
      title: "Summer edit",
      text: culottes ? `${culottes.name} · ${formatPrice(culottes.price)}` : "Dresses & culottes",
      image:
        culottes?.images[0] ??
        "https://images.unsplash.com/photo-1490481651871-ab68de25d43d?auto=format&fit=crop&w=1200&q=80",
      className: "mosaic-wide min-h-[140px] md:min-h-0",
    },
  ].filter(Boolean) as Array<{
    href: string;
    title: string;
    text: string;
    image: string;
    className: string;
  }>;

  return (
    <PageTransition>
      <div className="bg-background">
        <HeroMarketplace products={products} />

        <section className="border-b border-border">
          <div className="atelier py-5">
            <div className="mb-3 flex items-baseline justify-between">
              <h2 className="font-display text-xl">Departments</h2>
              <Link
                href="/categories"
                className="text-[11px] font-medium uppercase tracking-[0.14em] text-muted hover:text-foreground"
              >
                All
              </Link>
            </div>
            <div className="grid grid-cols-5 gap-2 sm:grid-cols-7 md:grid-cols-11">
              {categories.slice(0, 9).map((category) => (
                <Link
                  key={category.id}
                  href={`/categories/${category.slug}`}
                  className="group flex flex-col items-center gap-1.5"
                >
                  <span className="relative block aspect-square w-full overflow-hidden bg-surface">
                    <SafeImage
                      src={category.image}
                      alt={category.name}
                      fill
                      sizes="80px"
                      className="object-cover transition duration-500 group-hover:scale-105"
                    />
                  </span>
                  <span className="line-clamp-2 text-center text-[9px] font-medium uppercase tracking-[0.08em] text-muted group-hover:text-foreground">
                    {category.name}
                  </span>
                </Link>
              ))}
              {promoBadges.map((badge) => (
                <Link
                  key={badge.label}
                  href={badge.href}
                  className="flex flex-col items-center gap-1.5"
                >
                  <span className="flex aspect-square w-full items-center justify-center bg-[#1c1915] text-[10px] font-semibold uppercase tracking-[0.16em] text-[var(--on-ink)]">
                    {badge.label}
                  </span>
                  <span className="text-[9px] uppercase tracking-[0.08em] text-muted">
                    {badge.label}
                  </span>
                </Link>
              ))}
            </div>
          </div>
        </section>

        <section className="atelier py-6">
          <div className="mosaic">
            {mosaic.map((tile) => (
              <Link
                key={tile.title}
                href={tile.href}
                className={cn(
                  "relative overflow-hidden bg-surface",
                  tile.className,
                )}
              >
                <SafeImage
                  src={tile.image}
                  alt={tile.title}
                  fill
                  sizes="(max-width: 768px) 100vw, 50vw"
                  className="object-cover"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-[#1c1915]/70 to-transparent" />
                <div className="absolute inset-x-0 bottom-0 p-3 sm:p-4">
                  <h3 className="font-display text-xl leading-none text-white sm:text-2xl">
                    {tile.title}
                  </h3>
                  <p className="mt-1 text-[11px] text-white/80">{tile.text}</p>
                </div>
              </Link>
            ))}
          </div>
        </section>

        <section className="atelier py-7">
          <SectionRule
            kicker="Women"
            title="Now trending"
            href="/shop?category=women"
            action="Shop"
          />
          <div className="product-grid">
            {women.slice(0, 12).map((product, index) => (
              <ProductCard key={product.id} product={product} index={index} />
            ))}
          </div>
        </section>

        {offers.length > 0 ? (
          <section className="border-y border-border bg-[var(--paper)]">
            <div className="atelier py-7">
              <SectionRule
                kicker="Limited"
                title="Quiet offers"
                href="/shop?sort=price-asc"
                action="All offers"
              />
              <ProductSlider products={offers} autoPlay />
            </div>
          </section>
        ) : null}

        <section className="atelier py-7">
          <SectionRule
            kicker="Men"
            title="Daily cloth"
            href="/shop?category=men"
            action="Shop"
          />
          <div className="product-grid">
            {men.slice(0, 12).map((product, index) => (
              <ProductCard key={product.id} product={product} index={index} />
            ))}
          </div>
        </section>

        {kids.length > 0 ? (
          <section className="atelier py-7">
            <SectionRule
              kicker="Kids"
              title="Play-ready cloth"
              href="/categories/kids"
              action="Shop"
            />
            <div className="product-grid">
              {kids.slice(0, 12).map((product, index) => (
                <ProductCard key={product.id} product={product} index={index} />
              ))}
            </div>
          </section>
        ) : null}

        {baby.length > 0 ? (
          <section className="atelier py-7">
            <SectionRule
              kicker="Baby"
              title="Gentle layers"
              href="/categories/baby"
              action="Shop"
            />
            <div className="product-grid">
              {baby.slice(0, 12).map((product, index) => (
                <ProductCard key={product.id} product={product} index={index} />
              ))}
            </div>
          </section>
        ) : null}

        <section className="border-t border-border">
          <div className="atelier py-7">
            <SectionRule
              kicker="Just in"
              title="New arrivals"
              href="/shop?sort=newest"
              action="Shop"
            />
            <div className="product-grid">
              {arrivals.slice(0, 12).map((product, index) => (
                <ProductCard key={product.id} product={product} index={index} />
              ))}
            </div>
            <div className="mt-8">
              <SectionRule
                kicker="Loved"
                title="Bestsellers"
                href="/shop"
                action="Shop"
              />
              <div className="product-grid">
                {(best.length ? best : recent).slice(0, 12).map((product, index) => (
                  <ProductCard key={product.id} product={product} index={index} />
                ))}
              </div>
            </div>
          </div>
        </section>

        {easy ? (
          <section className="atelier pb-8">
            <Link
              href={`/product/${easy.id}`}
              className="relative flex min-h-[180px] items-end overflow-hidden bg-surface sm:min-h-[220px]"
            >
              <SafeImage
                src={easy.images[0]}
                alt={easy.name}
                fill
                sizes="1080px"
                className="object-cover object-center"
              />
              <div className="absolute inset-0 bg-[#121614]/45" />
              <div className="relative p-5 sm:p-7">
                <p className="text-[10px] uppercase tracking-[0.2em] text-white/70">
                  Easy dressing
                </p>
                <h2 className="font-display mt-1 text-3xl text-white">
                  {easy.name}
                </h2>
                <p className="mt-1 text-sm text-white/85">
                  {formatPrice(easy.price)}
                </p>
              </div>
            </Link>
          </section>
        ) : null}

        <section className="border-t border-border bg-[#121614] text-[var(--on-ink)]">
          <div className="atelier grid gap-6 py-9 sm:grid-cols-4">
            {[
              { icon: Truck, label: "Free over $99", note: "Standard $9" },
              { icon: RefreshCw, label: "30-day returns", note: "Unused, tagged" },
              { icon: ShieldCheck, label: "Secure pay", note: "Stripe checkout" },
              { icon: BadgeCheck, label: "BhoFit cut", note: "Fit notes on every SKU" },
            ].map((item) => (
              <div key={item.label} className="flex gap-3 border-l border-white/15 pl-3">
                <item.icon className="mt-0.5 h-3.5 w-3.5 shrink-0 opacity-80" />
                <div>
                  <p className="text-sm">{item.label}</p>
                  <p className="text-[11px] text-white/55">{item.note}</p>
                </div>
              </div>
            ))}
          </div>
        </section>

        <section className="atelier grid gap-8 py-10 lg:grid-cols-[0.9fr_1.1fr]">
          <div>
            <p className="text-[10px] uppercase tracking-[0.2em] text-[var(--accent)]">
              BhoFit
            </p>
            <h2 className="font-display mt-1 text-3xl leading-none">
              Cut for how you move.
            </h2>
            <p className="mt-3 max-w-sm text-sm leading-relaxed text-muted">
              Smaller edits. Honest cloth. Color and size on every core style —
              arranged like a gallery, never a warehouse.
            </p>
          </div>
          <FaqAccordion />
        </section>
      </div>
    </PageTransition>
  );
}
