import Link from "next/link";
import Image from "next/image";
import { db } from "@/lib/db";
import type { RenderSection } from "@/lib/homepage";
import { productCardInclude, batchCapacityInfo, productAvailability, priceRange } from "@/lib/catalog";
import { batchState, STATE_LABEL, depositLabel } from "@/lib/preorder";
import { fmtDate, fmtWindow } from "@/lib/dates";
import { taka } from "@/lib/money";
import CategoryIndex from "./CategoryIndex";
import NewsletterForm from "./NewsletterForm";

type D = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
const s = (v: unknown) => (typeof v === "string" ? v : "");
const arr = (v: unknown): D[] => (Array.isArray(v) ? (v as D[]) : []);

function Cta({ label, href, className = "link-line" }: { label?: string; href?: string; className?: string }) {
  if (!label || !href) return null;
  return <Link href={href} className={className}>{label}</Link>;
}

export default async function Sections({ sections }: { sections: RenderSection[] }) {
  const ids = new Set<string>();
  for (const sec of sections) {
    const d = sec.data as D;
    if (sec.type === "PRODUCT_STORIES") arr(d.stories).forEach((x) => x.productId && ids.add(x.productId));
    if (sec.type === "LIMITED_DROP") (Array.isArray(d.productIds) ? d.productIds : []).forEach((x: string) => ids.add(x));
  }
  const products = ids.size ? await db.product.findMany({ where: { id: { in: [...ids] }, status: "PUBLISHED" }, include: { ...productCardInclude, batches: true } }) : [];
  const byId = new Map(products.map((p) => [p.id, p]));
  let firstFeature = true;

  return (
    <>
      {sections.map((sec) => {
        const d = sec.data as D;
        switch (sec.type) {
          case "CATEGORY_FEATURE": {
            const hero = firstFeature; firstFeature = false;
            const panels = arr(d.panels);
            return (
              <section key={sec.id} aria-label={s(d.title)}>
                <div className={`grid grid-cols-2 md:grid-cols-${Math.min(4, Math.max(2, panels.length))} ${hero ? "rise" : ""}`}>
                  {panels.map((p, i) => (
                    <Link key={i} href={s(p.href) || s(d.href)} className={`swap block bg-linen ${hero ? "aspect-portrait md:aspect-auto md:h-[calc(100svh-var(--header-h)-36px)]" : "aspect-portrait md:aspect-[2000/2386]"}`} aria-label={s(p.alt) || s(d.title)}>
                      {p.image && <Image src={s(p.image)} alt={s(p.alt)} fill priority={hero} sizes="(min-width:768px) 25vw, 50vw" className="object-cover" />}
                      {p.hoverImage && <div className="swap-b"><Image src={s(p.hoverImage)} alt="" fill sizes="(min-width:768px) 25vw, 50vw" className="object-cover" /></div>}
                    </Link>
                  ))}
                </div>
                <Link href={s(d.href)} className="wrap flex items-baseline justify-between py-6 md:py-9 group">
                  <h2 className="font-display text-[48px] md:text-[96px] leading-none">{s(d.title)}</h2>
                  <span className="nav-type group-hover:text-gilt transition-colors">Explore</span>
                </Link>
              </section>
            );
          }
          case "EDITORIAL_TRIPTYCH":
            return (
              <section key={sec.id} className="wrap py-16 md:py-28">
                <div className="grid md:grid-cols-12 gap-4 md:gap-6 items-end">
                  <div className="md:col-span-6 relative aspect-[4/5] bg-linen">{d.large && <Image src={s(d.large)} alt="" fill sizes="(min-width:768px) 50vw, 100vw" className="object-cover" />}</div>
                  <div className="md:col-span-3 relative aspect-[2/3] bg-linen">{d.smallA && <Image src={s(d.smallA)} alt="" fill sizes="25vw" className="object-cover" />}</div>
                  <div className="md:col-span-3 relative aspect-[2/3] bg-linen md:translate-y-16">{d.smallB && <Image src={s(d.smallB)} alt="" fill sizes="25vw" className="object-cover" />}</div>
                </div>
                <div className="grid md:grid-cols-12 gap-6 mt-14 md:mt-32">
                  <h2 className="md:col-span-5 font-display text-[40px] md:text-[64px] leading-[1.05]">{s(d.title)}</h2>
                  <div className="md:col-span-5 md:col-start-7">
                    <p className="font-display text-[20px] md:text-[24px] leading-[1.5]">{s(d.body)}</p>
                    <div className="mt-8"><Cta label={s(d.ctaLabel)} href={s(d.ctaHref)} className="btn-line" /></div>
                  </div>
                </div>
              </section>
            );
          case "PRODUCT_STORIES":
            return (
              <section key={sec.id} className="wrap py-12 md:py-24">
                {d.title && <h2 className="font-display text-[34px] md:text-[56px] mb-12 md:mb-20">{s(d.title)}</h2>}
                <div className="space-y-20 md:space-y-36">
                  {arr(d.stories).map((st, i) => {
                    const p = byId.get(s(st.productId));
                    if (!p) return null;
                    const batch = p.batches[0];
                    const av = productAvailability(p);
                    const { min } = priceRange(p);
                    const cap = batch ? batchCapacityInfo(batch) : null;
                    return (
                      <article key={i} className={`grid md:grid-cols-12 gap-6 md:gap-10 items-center`}>
                        <Link href={`/products/${p.slug}`} className={`md:col-span-5 ${i % 2 ? "md:order-2 md:col-start-8" : ""} swap block aspect-portrait bg-linen`}>
                          {p.images[0] && <Image src={p.images[0].url} alt={p.images[0].alt} fill sizes="(min-width:768px) 40vw, 100vw" className="object-cover" />}
                          {p.images[1] && <div className="swap-b"><Image src={p.images[1].url} alt="" fill sizes="40vw" className="object-cover" /></div>}
                        </Link>
                        <div className={`md:col-span-5 ${i % 2 ? "md:order-1 md:col-start-2" : "md:col-start-7"}`}>
                          <h3 className="font-display text-[34px] md:text-[48px] leading-tight"><Link href={`/products/${p.slug}`} className="hover:text-gilt transition-colors">{p.name}</Link></h3>
                          <p className="text-stone mt-1">{s(st.caption)}{s(st.caption) ? " · " : ""}{taka(min)}</p>
                          {av.mode === "PRE_ORDER" && batch && (
                            <p className="eyebrow-status mt-2">{STATE_LABEL[batchState(batch)]}{cap && batchState(batch) === "OPEN" ? `, ${cap.remaining} of ${cap.capacity} places left` : ""}. Estimated dispatch {fmtWindow(batch.dispatchFrom, batch.dispatchTo)}.</p>
                          )}
                          <p className="font-display text-[20px] md:text-[22px] leading-[1.55] mt-6 max-w-[48ch]">{s(st.body)}</p>
                          <div className="mt-8"><Cta label={s(st.ctaLabel)} href={s(st.ctaHref)} /></div>
                        </div>
                      </article>
                    );
                  })}
                </div>
              </section>
            );
          case "CATEGORY_INDEX":
            return <section key={sec.id} aria-label="Shop by category"><CategoryIndex items={arr(d.items).map((i) => ({ label: s(i.label), href: s(i.href), image: s(i.image) }))} /></section>;
          case "LIMITED_DROP": {
            const list = (Array.isArray(d.productIds) ? d.productIds : []).map((id: string) => byId.get(id)).filter(Boolean) as typeof products;
            return (
              <section key={sec.id} className="bg-linen py-16 md:py-28">
                <div className="wrap grid md:grid-cols-12 gap-8">
                  <h2 className="md:col-span-6 font-display text-[44px] md:text-[88px] leading-[1]">{s(d.title)}</h2>
                  <div className="md:col-span-5 md:col-start-8">
                    <p className="font-display text-[22px] md:text-[26px] leading-[1.45]">{s(d.lead)}</p>
                    <p className="mt-5 max-w-[52ch]">{s(d.body)}</p>
                    <div className="mt-7"><Cta label={s(d.ctaLabel)} href={s(d.ctaHref)} /></div>
                  </div>
                </div>
                <div className="wrap mt-14">
                  <ul className="flex gap-4 md:gap-6 overflow-x-auto no-scrollbar snap-x pb-2">
                    {list.map((p) => {
                      const b = p.batches[0]; const st = b ? batchState(b) : null; const cap = b ? batchCapacityInfo(b) : null;
                      return (
                        <li key={p.id} className="snap-start shrink-0 w-[62vw] sm:w-[36vw] md:w-[22vw]">
                          <Link href={`/products/${p.slug}`} className="block group">
                            <div className="swap aspect-portrait bg-paper">{p.images[0] && <Image src={p.images[0].url} alt={p.images[0].alt} fill sizes="25vw" className="object-cover" />}{p.images[1] && <div className="swap-b"><Image src={p.images[1].url} alt="" fill sizes="25vw" className="object-cover" /></div>}</div>
                            <div className="mt-3 flex justify-between gap-2 text-[14px]"><span>{p.name}</span><span>{taka(priceRange(p).min)}</span></div>
                            {b && st && <p className={`text-[12px] mt-0.5 ${st === "OPEN" ? "text-gilt" : "text-stone"}`}>{STATE_LABEL[st]}{st === "OPEN" && cap ? ` · ${cap.remaining} left · closes ${fmtDate(b.closesAt, { year: undefined })}` : ""}</p>}
                            {b && st === "OPEN" && <p className="text-[12px] text-stone">{depositLabel(b)}</p>}
                          </Link>
                        </li>
                      );
                    })}
                  </ul>
                  {d.footnote && <p className="text-stone mt-10 max-w-[60ch]">{s(d.footnote)}</p>}
                </div>
              </section>
            );
          }
          case "ENQUIRY_MARQUEE": {
            const imgs = arr(d.images);
            return (
              <section key={sec.id} className="py-16 md:py-28">
                <div className="marquee overflow-hidden" aria-hidden="true">
                  <div className="marquee-track flex gap-4">
                    {[...imgs, ...imgs].map((im, i) => (
                      <div key={i} className="relative w-[48vw] md:w-[20vw] aspect-portrait shrink-0 bg-linen">{im.image && <Image src={s(im.image)} alt="" fill sizes="20vw" className="object-cover" />}</div>
                    ))}
                  </div>
                </div>
                <div className="wrap grid md:grid-cols-12 gap-6 mt-14">
                  <h2 className="md:col-span-5 font-display text-[40px] md:text-[64px] leading-[1.05]">{s(d.title)}</h2>
                  <div className="md:col-span-5 md:col-start-7"><p className="font-display text-[20px] md:text-[24px] leading-[1.5]">{s(d.body)}</p><div className="mt-8"><Cta label={s(d.ctaLabel)} href={s(d.ctaHref)} className="btn-line" /></div></div>
                </div>
              </section>
            );
          }
          case "BRAND_STORY":
            return (
              <section key={sec.id} className="wrap py-16 md:py-28 grid md:grid-cols-12 gap-8 md:gap-14 items-center">
                <div className="md:col-span-6 relative aspect-[5/4] bg-linen">{d.image && <Image src={s(d.image)} alt="" fill sizes="(min-width:768px) 50vw, 100vw" className="object-cover" />}</div>
                <div className="md:col-span-5">
                  <h2 className="font-display text-[40px] md:text-[64px] leading-[1.05]">{s(d.title)}</h2>
                  <p className="font-display text-[22px] md:text-[26px] leading-[1.4] mt-6">{s(d.lead)}</p>
                  <p className="mt-5 max-w-[52ch]">{s(d.body)}</p>
                  <div className="mt-8"><Cta label={s(d.ctaLabel)} href={s(d.ctaHref)} /></div>
                </div>
              </section>
            );
          case "GIFTING":
            return (
              <section key={sec.id} className="py-16 md:py-28">
                <div className="wrap text-center max-w-3xl mx-auto">
                  <h2 className="font-display text-[34px] md:text-[56px] leading-[1.05]">{s(d.title)}</h2>
                  <p className="font-display text-[20px] md:text-[22px] leading-[1.55] mt-6">{s(d.body)}</p>
                  <div className="mt-8"><Cta label={s(d.ctaLabel)} href={s(d.ctaHref)} className="btn-line" /></div>
                </div>
                {d.image && <div className="relative mt-14 aspect-[16/8] bg-linen"><Image src={s(d.image)} alt="" fill sizes="100vw" className="object-cover" /></div>}
              </section>
            );
          case "FOOTER_GALLERY":
            return (
              <section key={sec.id} aria-hidden="true" className="overflow-x-auto no-scrollbar">
                <div className="flex">{arr(d.images).map((im, i) => <div key={i} className="relative shrink-0 w-[40vw] md:w-[22vw] aspect-portrait bg-linen">{im.image && <Image src={s(im.image)} alt="" fill sizes="25vw" className="object-cover" />}</div>)}</div>
              </section>
            );
          case "NEWSLETTER":
            return (
              <section key={sec.id} className="wrap py-20 md:py-32">
                <h2 className="font-display text-[34px] md:text-[64px] leading-[1.05] max-w-[20ch]">{s(d.title)}</h2>
                <div className="mt-8 max-w-xl"><NewsletterForm source="homepage" label={s(d.buttonLabel) || "Get notified"} /></div>
              </section>
            );
          default:
            return null;
        }
      })}
    </>
  );
}
