import { Metadata } from "next"
import Image from "next/image"

import Hero from "@modules/home/components/hero"
import { getRegion } from "@lib/data/regions"
import { listProductsWithSort } from "@lib/data/products"
import { getProductPrice } from "@lib/util/get-product-price"
import ProductPreview from "@modules/products/components/product-preview"
import LocalizedClientLink from "@modules/common/components/localized-client-link"
import { getHomepageContent } from "@lib/data/homepage"

export const metadata: Metadata = {
  title: "Totti – Educational Toys for Kids",
  description: "Curated educational toys for children. Construction, fine motor, movement, and sensory toys delivered to your door.",
}

const FALLBACK_HERO = {
  headline: "Play.\nLearn.\nGrow.",
  subtitle: "Curated toys that spark imagination and build skills — from construction to sensory play.",
  badge_1_text: "Educational Toys",
  badge_2_text: "🚚 Gratis ongkir 500k+",
  cta_1_label: "Shop All",
  cta_1_link: "/store",
  cta_2_label: "Rent a Toy",
  cta_2_link: "/categories/toys-for-rent",
  rent_banner_title: "🔄 Toys for Rent",
  rent_banner_text: "Try before you buy. Swap anytime.",
  rent_banner_cta: "Rent now",
  hero_photos: [
    { id: "1", image_url: "/images/product-jungle-gym.webp", label: "Movement", rotate: "-rotate-2", sort_order: 0 },
    { id: "2", image_url: "/images/categories/construction.webp", label: "Construction", rotate: "rotate-1", sort_order: 1 },
    { id: "3", image_url: "/images/product-little-chef.webp", label: "Fine Motor", rotate: "rotate-2", sort_order: 2 },
    { id: "4", image_url: "/images/categories/sensory.webp", label: "Sensory", rotate: "-rotate-1", sort_order: 3 },
  ],
  category_cards: [
    { id: "1", label: "Construction & Open-Ended", sub: "Build & create", image_url: "/images/categories/construction.webp", handle: "/categories/construction-and-open-ended", badge: "🧱", bg_color: "bg-orange-400", sort_order: 0 },
    { id: "2", label: "Fine Motor Toys", sub: "Strengthen skills", image_url: "/images/categories/fine-motor.webp", handle: "/categories/fine-motor-toys", badge: "✂️", bg_color: "bg-pink-400", sort_order: 1 },
    { id: "3", label: "Movement Toys", sub: "Jump & explore", image_url: "/images/categories/movement.webp", handle: "/categories/movement-toys", badge: "🏃", bg_color: "bg-sky-400", sort_order: 2 },
    { id: "4", label: "Sensory Toys", sub: "Touch & discover", image_url: "/images/categories/sensory.webp", handle: "/categories/sensory-toys", badge: "🌈", bg_color: "bg-green-400", sort_order: 3 },
  ],
}

const FALLBACK_PARTNERS = [
  { id: "1", name: "Kidzooona", image_url: "/images/partners/kidzooona.webp", link: "", sort_order: 0 },
  { id: "2", name: "Jumma", image_url: "/images/partners/jumma.webp", link: "", sort_order: 1 },
  { id: "3", name: "Kejora", image_url: "/images/partners/kejora.webp", link: "", sort_order: 2 },
  { id: "4", name: "Edokko", image_url: "/images/partners/edokko.webp", link: "", sort_order: 3 },
  { id: "5", name: "Group 152", image_url: "/images/partners/group-152.webp", link: "", sort_order: 4 },
  { id: "6", name: "Tentang Anak", image_url: "/images/partners/tentang-anak.webp", link: "", sort_order: 5 },
  { id: "7", name: "BCA", image_url: "/images/partners/bca.webp", link: "", sort_order: 6 },
  { id: "8", name: "Blibli", image_url: "/images/partners/blibli.webp", link: "", sort_order: 7 },
  { id: "9", name: "Tokopedia", image_url: "/images/partners/tokopedia.webp", link: "", sort_order: 8 },
  { id: "10", name: "Buumi", image_url: "/images/partners/buumi.webp", link: "", sort_order: 9 },
  { id: "11", name: "Dekoruma", image_url: "/images/partners/dekoruma.webp", link: "", sort_order: 10 },
  { id: "12", name: "Fanpekka", image_url: "/images/partners/fanpekka.webp", link: "", sort_order: 11 },
  { id: "13", name: "Juniordept", image_url: "/images/partners/jundept.webp", link: "", sort_order: 12 },
]

const MOBILE_CATEGORIES_FALLBACK = [
  { label: "Construction", handle: "/categories/construction-and-open-ended", bg: "bg-orange-400", badge: "🧱" },
  { label: "Fine Motor", handle: "/categories/fine-motor-toys", bg: "bg-pink-400", badge: "✂️" },
  { label: "Movement", handle: "/categories/movement-toys", bg: "bg-sky-400", badge: "🏃" },
  { label: "Sensory", handle: "/categories/sensory-toys", bg: "bg-green-400", badge: "🌈" },
  { label: "Rent a Toy", handle: "/categories/toys-for-rent", bg: "bg-violet-500", badge: "🔄" },
]

export default async function Home(props: {
  params: Promise<{ countryCode: string }>
}) {
  const params = await props.params
  const { countryCode } = params
  const region = await getRegion(countryCode)

  if (!region) return null

  const {
    response: { products },
  } = await listProductsWithSort({
    page: 1,
    queryParams: { limit: 20, order: "-created_at" },
    sortBy: "created_at",
    countryCode,
  })

  const latestProducts = products.slice(0, 8)

  const discountedProducts = products
    .filter((p) => {
      const { cheapestPrice } = getProductPrice({ product: p })
      return cheapestPrice?.price_type === "sale"
    })
    .slice(0, 8)

  const cmsData = await getHomepageContent()
  const h = cmsData.homepage

  const heroProps = h
    ? {
        headline: h.headline,
        subtitle: h.subtitle,
        badge_1_text: h.badge_1_text,
        badge_2_text: h.badge_2_text,
        cta_1_label: h.cta_1_label,
        cta_1_link: h.cta_1_link,
        cta_2_label: h.cta_2_label,
        cta_2_link: h.cta_2_link,
        rent_banner_title: h.rent_banner_title,
        rent_banner_text: h.rent_banner_text,
        rent_banner_cta: h.rent_banner_cta,
        hero_photos: h.hero_photos,
        category_cards: h.category_cards,
      }
    : FALLBACK_HERO

  const partners = h?.partners ?? FALLBACK_PARTNERS
  const bestDealsHeading = h?.section_best_deals_heading ?? "Best Deals"
  const newArrivalsHeading = h?.section_new_arrivals_heading ?? "New Arrivals"
  const partnersHeading = h?.section_partners_heading ?? "Partners & Friends"

  const mobileCategories = h?.category_cards
    ? h.category_cards.map((c) => ({ label: c.label.split(" ")[0], handle: c.handle, bg: c.bg_color, badge: c.badge }))
    : MOBILE_CATEGORIES_FALLBACK

  return (
    <>
      <Hero {...heroProps} />

      {/* ── MOBILE CATEGORY STRIP (shown only on mobile, since hero hides them) ── */}
      <div className="md:hidden bg-[#111] py-3">
        <div className="overflow-x-auto no-scrollbar">
          <div className="flex gap-2 px-4 w-max">
            {mobileCategories.map((cat) => (
              <LocalizedClientLink
                key={cat.handle}
                href={cat.handle}
                className={`flex items-center gap-1.5 ${cat.bg} text-white text-xs font-black px-3 py-2 rounded-full whitespace-nowrap shadow-[2px_2px_0px_rgba(0,0,0,0.3)] hover:opacity-90 transition-opacity`}
              >
                <span>{cat.badge}</span>
                <span>{cat.label}</span>
              </LocalizedClientLink>
            ))}
          </div>
        </div>
      </div>

      {/* ── BEST DEALS ── */}
      <section className="bg-yellow-50 py-8 sm:py-10 border-y-2 border-yellow-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6">
          <div className="flex items-center justify-between mb-5">
            <div className="flex items-center gap-3">
              <span className="bg-red-500 text-white text-xs font-black px-3 py-1 rounded-full animate-pulse">
                SALE
              </span>
              <h2 className="text-2xl font-black text-black">{bestDealsHeading}</h2>
            </div>
            <LocalizedClientLink
              href="/store"
              className="text-sm font-bold text-black hover:underline"
            >
              View all →
            </LocalizedClientLink>
          </div>

          {discountedProducts.length > 0 ? (
            <>
              <div className="md:hidden -mx-4 overflow-x-auto no-scrollbar snap-x snap-mandatory">
                <div className="flex">
                  {Array.from({ length: Math.ceil(discountedProducts.length / 4) }).map((_, si) => (
                    <ul key={si} className="flex-shrink-0 w-screen px-4 snap-start grid grid-cols-2 gap-3">
                      {discountedProducts.slice(si * 4, si * 4 + 4).map((p) => (
                        <li key={p.id}>
                          <ProductPreview product={p} region={region} />
                        </li>
                      ))}
                    </ul>
                  ))}
                </div>
              </div>
              {discountedProducts.length > 4 && (
                <div className="flex justify-center gap-1.5 mt-3 md:hidden">
                  {Array.from({ length: Math.ceil(discountedProducts.length / 4) }).map((_, i) => (
                    <div key={i} className={`h-1 rounded-full bg-black/20 ${i === 0 ? "w-4 bg-black/60" : "w-1.5"}`} />
                  ))}
                </div>
              )}
              <ul className="hidden md:grid grid-cols-4 gap-4">
                {discountedProducts.slice(0, 4).map((p) => (
                  <li key={p.id}>
                    <ProductPreview product={p} region={region} />
                  </li>
                ))}
              </ul>
            </>
          ) : (
            <div className="text-center py-10">
              <p className="text-4xl mb-3">🏷️</p>
              <p className="text-gray-500 font-semibold text-sm">Special deals coming soon!</p>
              <LocalizedClientLink
                href="/store"
                className="inline-block mt-4 bg-black text-yellow-400 font-black text-sm px-5 py-2.5 rounded-full hover:bg-gray-900 transition-colors"
              >
                Browse all products →
              </LocalizedClientLink>
            </div>
          )}
        </div>
      </section>

      {/* ── NEW ARRIVALS ── */}
      <section className="bg-white py-8 sm:py-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6">
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center gap-4">
              <h2 className="text-2xl font-black text-black">{newArrivalsHeading}</h2>
              <div className="h-1 w-20 bg-yellow-400 rounded-full hidden sm:block" />
            </div>
            <LocalizedClientLink
              href="/store"
              className="text-sm font-bold text-black hover:underline"
            >
              View all →
            </LocalizedClientLink>
          </div>

          {latestProducts.length > 0 ? (
            <>
              <div className="md:hidden -mx-4 overflow-x-auto no-scrollbar snap-x snap-mandatory">
                <div className="flex">
                  {Array.from({ length: Math.ceil(latestProducts.length / 4) }).map((_, si) => (
                    <ul key={si} className="flex-shrink-0 w-screen px-4 snap-start grid grid-cols-2 gap-3">
                      {latestProducts.slice(si * 4, si * 4 + 4).map((p) => (
                        <li key={p.id}>
                          <ProductPreview product={p} region={region} />
                        </li>
                      ))}
                    </ul>
                  ))}
                </div>
              </div>
              {latestProducts.length > 4 && (
                <div className="flex justify-center gap-1.5 mt-3 md:hidden">
                  {Array.from({ length: Math.ceil(latestProducts.length / 4) }).map((_, i) => (
                    <div key={i} className={`h-1 rounded-full bg-black/20 ${i === 0 ? "w-4 bg-black/60" : "w-1.5"}`} />
                  ))}
                </div>
              )}
              <ul className="hidden md:grid grid-cols-4 gap-4">
                {latestProducts.slice(0, 4).map((p) => (
                  <li key={p.id}>
                    <ProductPreview product={p} region={region} />
                  </li>
                ))}
              </ul>
            </>
          ) : (
            <p className="text-gray-400 text-sm py-8 text-center">Products coming soon!</p>
          )}
        </div>
      </section>

      {/* ── PARTNERS & FRIENDS ── */}
      <section className="bg-gray-50 border-t-2 border-gray-100 py-6 sm:py-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6">
          <div className="flex items-center gap-3 mb-5 sm:mb-8 justify-center">
            <div className="h-px flex-1 bg-gray-200 hidden sm:block" />
            <h2 className="text-gray-400 font-black text-[10px] sm:text-sm uppercase tracking-widest whitespace-nowrap">
              {partnersHeading}
            </h2>
            <div className="h-px flex-1 bg-gray-200 hidden sm:block" />
          </div>
          <div className="flex flex-wrap justify-center items-center gap-4 sm:gap-8">
            {partners.map((p) => (
              <div
                key={p.id}
                className="relative h-6 w-16 sm:h-10 sm:w-28 grayscale opacity-40 hover:grayscale-0 hover:opacity-100 transition-all duration-300"
              >
                <Image
                  src={p.image_url}
                  alt={p.name}
                  fill
                  className="object-contain"
                  sizes="(max-width: 640px) 64px, 112px"
                />
              </div>
            ))}
          </div>
        </div>
      </section>
    </>
  )
}
