import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { getPayload } from 'payload'
import config from '@payload-config'
import { normalizeCar, normalizeLocation, type PayloadCar, type PayloadLocation } from "@/lib/payload-helpers";
import { SITE } from "@/lib/seo";
import { getSiteStats } from "@/lib/stats";
import { getSiteSettings } from "@/lib/site-settings";

interface Props { params: Promise<{ slug: string }> }

export const revalidate = 86400

export async function generateStaticParams() {
  const payload = await getPayload({ config })
  const { docs } = await payload.find({ collection: 'locations', limit: 50, pagination: false })
  return (docs as unknown as PayloadLocation[]).map(l => ({ slug: l.slug }))
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const payload = await getPayload({ config })
  const { docs } = await payload.find({
    collection: 'locations', where: { slug: { equals: slug } }, limit: 1,
  })
  const locDoc = docs[0] as unknown as PayloadLocation | undefined
  if (!locDoc) return { title: "Location not found" };
  const loc = normalizeLocation(locDoc)

  const ogTitle = loc.seoTitle || `Car Rental ${loc.name} | Free Delivery | NCK`
  const ogDesc  = loc.seoDesc || loc.desc || `Rent a car in ${loc.name}, Dubai. Free delivery, no deposit, 24/7 support. NCK Car Rental.`
  return {
    title:       ogTitle,
    description: ogDesc,
    alternates:  { canonical: `${SITE.domain}/locations/${slug}/` },
    robots:      { index: true, follow: true },
    openGraph: {
      title:       ogTitle,
      description: ogDesc,
      url:         `${SITE.domain}/locations/${slug}/`,
      siteName:    "NCK Car Rental",
      locale:      "en_AE",
      images:      [{ url: "/media/ferrari-f8-tributo-rental-dubai-02.webp", width: 1200, height: 630, alt: `Car Rental ${loc.name} Dubai - NCK Car Rental` }],
    },
    twitter: {
      card:        "summary_large_image",
      title:       ogTitle,
      description: ogDesc,
      images:      ["/media/ferrari-f8-tributo-rental-dubai-02.webp"],
    },
  };
}

export default async function LocationPage({ params }: Readonly<Props>) {
  const { slug } = await params;
  const payload = await getPayload({ config })

  const [locResult, allLocsResult, featuredCarsResult, siteStats, s] = await Promise.all([
    payload.find({ collection: 'locations', where: { slug: { equals: slug } }, limit: 1 }),
    payload.find({ collection: 'locations', limit: 50, pagination: false }),
    payload.find({
      collection: 'cars',
      where: { carType: { not_equals: null } },
      depth: 1,
      limit: 6,
    }),
    getSiteStats(),
    getSiteSettings(),
  ])

  const locDoc = locResult.docs[0] as unknown as PayloadLocation | undefined
  if (!locDoc) notFound();
  const loc = normalizeLocation(locDoc)

  const allLocs = (allLocsResult.docs as unknown as PayloadLocation[]).map(d => normalizeLocation(d))
  const featuredCars = (featuredCarsResult.docs as unknown as PayloadCar[]).map(doc => normalizeCar(doc))

  // ── Structured data ───────────────────────────────────────────────────────

  const breadcrumbLd = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: "Home",      item: `${SITE.domain}/` },
      { "@type": "ListItem", position: 2, name: "Locations", item: `${SITE.domain}/locations/` },
      { "@type": "ListItem", position: 3, name: loc.name },
    ],
  };

  const localBusinessLd: Record<string, unknown> = {
    "@context": "https://schema.org",
    "@type": "AutoRental",
    "@id": `${SITE.domain}/locations/${slug}/`,
    name: `NCK Car Rental ${loc.name}`,
    description: loc.seoDesc || loc.desc,
    url: `${SITE.domain}/locations/${slug}/`,
    telephone: s.phone1,
    priceRange: "AED 150 - 6500/day",
    currenciesAccepted: "AED, USD",
    paymentAccepted: "Cash, Credit Card, Debit Card, Cryptocurrency",
    address: {
      "@type": "PostalAddress",
      addressLocality: loc.name,
      addressRegion: "Dubai",
      addressCountry: "AE",
    },
    openingHoursSpecification: {
      "@type": "OpeningHoursSpecification",
      dayOfWeek: ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],
      opens: "00:00",
      closes: "23:59",
    },
    areaServed: {
      "@type": "Place",
      name: loc.name,
      address: { "@type": "PostalAddress", addressLocality: loc.name, addressRegion: "Dubai", addressCountry: "AE" },
    },
    contactPoint: [
      {
        "@type": "ContactPoint",
        telephone: s.phone1,
        contactType: "customer service",
        availableLanguage: ["English", "Arabic"],
        contactOption: "TollFree",
        hoursAvailable: { "@type": "OpeningHoursSpecification", dayOfWeek: ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"], opens: "00:00", closes: "23:59" },
      },
      {
        "@type": "ContactPoint",
        url: `https://wa.me/${s.whatsapp1}`,
        contactType: "customer service",
        availableLanguage: ["English", "Arabic"],
      },
    ],
    hasMap: `https://www.google.com/maps/search/car+rental+${encodeURIComponent(loc.name)}+Dubai`,
    sameAs: [SITE.domain],
  }

  if (loc.lat && loc.lng) {
    localBusinessLd.geo = {
      "@type": "GeoCoordinates",
      latitude: loc.lat,
      longitude: loc.lng,
    }
  }

  if (siteStats.reviews > 0) {
    localBusinessLd.aggregateRating = {
      "@type": "AggregateRating",
      ratingValue: siteStats.rating,
      reviewCount: siteStats.reviews,
      bestRating: 5,
      worstRating: 1,
    }
  }

  if (featuredCars.length > 0) {
    localBusinessLd.makesOffer = featuredCars.slice(0, 5).map(car => ({
      "@type": "Offer",
      name: `Rent ${car.title} in ${loc.name}`,
      url: `${SITE.domain}/car/${car.slug}/`,
      priceCurrency: "AED",
      price: car.priceDay,
      eligibleDuration: { "@type": "QuantitativeValue", value: 1, unitCode: "DAY" },
    })).filter(o => o.price)
  }

  const faqLd = loc.faqs.length > 0 ? {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: loc.faqs.map(f => ({
      "@type": "Question",
      name: f.q,
      acceptedAnswer: { "@type": "Answer", text: f.a },
    })),
  } : null

  const introParagraphs = loc.intro ? loc.intro.split(/\n\n+/).filter(Boolean) : []

  return (
    <>
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbLd) }} />
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(localBusinessLd) }} />
      {faqLd && <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(faqLd) }} />}

      {/* ── Hero ─────────────────────────────────────────────────────────── */}
      <div className="bg-navy-900 text-white py-12">
        <div className="section-wrap">
          <nav className="flex items-center gap-1.5 text-xs text-navy-300 mb-3">
            <Link href="/" className="hover:text-white">Home</Link>
            <span>/</span>
            <Link href="/locations" className="hover:text-white">Locations</Link>
            <span>/</span>
            <span>{loc.name}</span>
          </nav>
          <div className="flex items-center gap-3 mb-3">
            {loc.icon && <span className="text-4xl">{loc.icon}</span>}
            <h1 className="text-3xl sm:text-4xl font-black">{loc.h1}</h1>
          </div>
          <p className="text-navy-300 text-sm max-w-2xl mb-6 leading-relaxed">{loc.desc}</p>

          {/* Stats row */}
          <div className="flex flex-wrap items-center gap-x-6 gap-y-2 mb-7">
            <div className="flex items-center gap-1.5">
              <span className="text-yellow-400 text-sm">★</span>
              <span className="font-bold text-sm">{siteStats.rating}</span>
              <span className="text-navy-300 text-xs">({siteStats.reviews.toLocaleString()} reviews)</span>
            </div>
            <div className="w-px h-4 bg-white/20 hidden sm:block" />
            <span className="text-navy-300 text-xs">Free delivery to {loc.name}</span>
            <div className="w-px h-4 bg-white/20 hidden sm:block" />
            <span className="text-navy-300 text-xs">24/7 support</span>
          </div>

          <div className="flex flex-wrap gap-3">
            <a
              href={`https://wa.me/${s.whatsapp1}`}
              target="_blank"
              rel="noopener noreferrer"
              className="btn-orange text-sm py-2.5 px-5 flex items-center gap-2"
            >
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/>
              </svg>
              Book via WhatsApp
            </a>
            <a href={s.callUrl1} className="btn-outline border-white/30 text-white hover:bg-white/10 text-sm py-2.5 px-5 flex items-center gap-2">
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.948V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"/>
              </svg>
              Call Us
            </a>
          </div>
        </div>
      </div>

      {/* ── Main layout ───────────────────────────────────────────────────── */}
      <div className="section-wrap py-10">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-10">

          {/* ── Main column ──────────────────────────────────────────────── */}
          <div className="lg:col-span-2 space-y-10">

            {/* Intro */}
            {introParagraphs.length > 0 ? (
              <div className="space-y-4 text-[#5c6472] text-sm leading-relaxed">
                {introParagraphs.map((p, i) => <p key={i}>{p}</p>)}
              </div>
            ) : loc.desc ? (
              <p className="text-[#5c6472] text-sm leading-relaxed">{loc.desc}</p>
            ) : null}

            {/* Highlights */}
            {loc.highlights.length > 0 ? (
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                {loc.highlights.map(h => (
                  <div key={h.title} className="bg-[#f8f9fb] rounded-xl p-4 border border-[#e2e6ed]">
                    {h.icon && <div className="text-2xl mb-2">{h.icon}</div>}
                    <p className="font-bold text-[#1a1f2e] text-xs mb-1">{h.title}</p>
                    <p className="text-[#5c6472] text-xs leading-relaxed">{h.body}</p>
                  </div>
                ))}
              </div>
            ) : (
              /* Fallback static highlights when no CMS data */
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                {[
                  ["🚚", "Free Delivery",  `To ${loc.name}`],
                  ["💳", "No Deposit",     "On selected cars"],
                  ["🕐", "24/7 Support",   "Always available"],
                  ["✅", "Fully Insured",  "All vehicles"],
                ].map(([icon, label, sub]) => (
                  <div key={label} className="bg-[#f8f9fb] rounded-xl p-3 border border-[#e2e6ed] text-center">
                    <div className="text-xl mb-1">{icon}</div>
                    <p className="font-bold text-[#1a1f2e] text-xs">{label}</p>
                    <p className="text-[#5c6472] text-xs">{sub}</p>
                  </div>
                ))}
              </div>
            )}

            {/* Popular cars */}
            {featuredCars.length > 0 && (
              <section>
                <div className="flex items-center justify-between mb-4">
                  <h2 className="section-title">Popular Cars in {loc.name}</h2>
                  <Link href="/all-cars" className="btn-ghost text-xs">View all →</Link>
                </div>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
                  {featuredCars.map(car => (
                    <Link key={car.slug} href={`/car/${car.slug}`} className="car-card flex flex-col group">
                      <div className="relative bg-[#f1f3f7] aspect-[4/3] overflow-hidden">
                        {car.image && (
                          <Image
                            src={car.image}
                            alt={`${car.title} rental ${loc.name}`}
                            fill
                            className="object-cover group-hover:scale-105 transition-transform duration-300"
                            sizes="(max-width: 640px) 50vw, 33vw"
                          />
                        )}
                        {car.noDeposit && (
                          <span className="absolute top-2 left-2 bg-emerald-500 text-white text-xs font-bold px-2 py-0.5 rounded-full">No Deposit</span>
                        )}
                      </div>
                      <div className="p-3">
                        <p className="text-xs text-[#5c6472] font-semibold">{car.brand}</p>
                        <p className="font-bold text-[#1a1f2e] text-xs leading-tight mb-1">{car.title}</p>
                        <p className="text-brand font-black text-sm">
                          AED {car.priceDay?.toLocaleString()}<span className="text-[#5c6472] font-normal text-xs">/day</span>
                        </p>
                      </div>
                    </Link>
                  ))}
                </div>
              </section>
            )}

            {/* Nearby attractions */}
            {loc.nearbyAttractions.length > 0 && (
              <section>
                <h2 className="section-title mb-4">Near {loc.name}</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  {loc.nearbyAttractions.map(a => (
                    <div key={a.name} className="flex items-start gap-3 bg-white border border-[#e2e6ed] rounded-xl px-4 py-3">
                      <div className="w-2 h-2 rounded-full bg-brand mt-1.5 flex-shrink-0" />
                      <div>
                        <p className="font-semibold text-[#1a1f2e] text-sm">{a.name}</p>
                        <div className="flex items-center gap-2 mt-0.5">
                          {a.type && <span className="text-xs bg-[#f0f4ff] text-brand px-2 py-0.5 rounded-full font-medium">{a.type}</span>}
                          {a.walkingTime && <span className="text-[#5c6472] text-xs">{a.walkingTime}</span>}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </section>
            )}

            {/* Delivery info */}
            {loc.deliveryInfo && (
              <section className="bg-[#f8f9fc] rounded-2xl p-6 border border-[#e2e6ed]">
                <div className="flex items-center gap-3 mb-3">
                  <div className="w-8 h-8 rounded-full bg-brand/10 flex items-center justify-center flex-shrink-0">
                    <svg className="w-4 h-4 text-brand" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/>
                    </svg>
                  </div>
                  <h2 className="font-black text-[#1a1f2e] text-base">Delivery to {loc.name}</h2>
                </div>
                <p className="text-[#5c6472] text-sm leading-relaxed">{loc.deliveryInfo}</p>
              </section>
            )}

            {/* FAQs */}
            {loc.faqs.length > 0 && (
              <section>
                <h2 className="section-title mb-4">Common Questions about {loc.name}</h2>
                <div className="space-y-2">
                  {loc.faqs.map((faq, i) => (
                    <details key={i} className="group bg-white border border-[#e2e6ed] rounded-xl overflow-hidden">
                      <summary className="flex items-center justify-between gap-3 px-5 py-4 cursor-pointer list-none font-semibold text-[#1a1f2e] text-sm hover:bg-[#f8f9fb] transition-colors">
                        <span>{faq.q}</span>
                        <span className="text-brand font-black flex-shrink-0 group-open:rotate-45 transition-transform">+</span>
                      </summary>
                      <div className="px-5 pb-4 text-[#5c6472] text-sm leading-relaxed border-t border-[#e2e6ed]">
                        <p className="pt-3">{faq.a}</p>
                      </div>
                    </details>
                  ))}
                </div>
              </section>
            )}

            {/* SEO text */}
            {loc.seoText && (
              <p className="text-[#5c6472] text-xs leading-relaxed border-t border-[#e2e6ed] pt-8">
                {loc.seoText}
              </p>
            )}
          </div>

          {/* ── Sidebar ───────────────────────────────────────────────────── */}
          <div className="space-y-4">

            {/* Booking card */}
            <div className="bg-white rounded-2xl border border-[#e2e6ed] p-5 shadow-card">
              <h3 className="font-black text-[#1a1f2e] mb-1">Book in {loc.name}</h3>
              <p className="text-[#5c6472] text-xs mb-4">Free delivery · No deposit · 24/7 support</p>
              <div className="space-y-2.5">
                <a
                  href={`https://wa.me/${s.whatsapp1}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="btn-orange w-full justify-center text-sm py-3 flex items-center gap-2"
                >
                  <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/>
                  </svg>
                  WhatsApp
                </a>
                <a href={s.callUrl1} className="btn-outline w-full justify-center text-sm py-3 flex items-center gap-2">
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.948V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"/>
                  </svg>
                  Call Us
                </a>
                <Link href="/all-cars" className="btn-ghost w-full justify-center text-sm py-2.5 flex items-center gap-2">
                  Browse all cars →
                </Link>
              </div>
            </div>

            {/* Quick facts */}
            <div className="bg-[#f8f9fb] rounded-2xl border border-[#e2e6ed] p-4">
              <p className="font-bold text-[#1a1f2e] text-xs mb-3">Quick Facts</p>
              <ul className="space-y-2 text-xs text-[#5c6472]">
                <li className="flex items-center gap-2"><span className="text-emerald-500">✓</span> Free delivery to {loc.name}</li>
                <li className="flex items-center gap-2"><span className="text-emerald-500">✓</span> No deposit on selected models</li>
                <li className="flex items-center gap-2"><span className="text-emerald-500">✓</span> 24/7 WhatsApp support</li>
                <li className="flex items-center gap-2"><span className="text-emerald-500">✓</span> Basic insurance included</li>
                <li className="flex items-center gap-2"><span className="text-emerald-500">✓</span> 1-day minimum rental</li>
                <li className="flex items-center gap-2"><span className="text-emerald-500">✓</span> Monthly rates available</li>
              </ul>
            </div>

            {/* Other locations */}
            <div className="bg-white rounded-2xl border border-[#e2e6ed] p-4">
              <h3 className="font-bold text-[#1a1f2e] text-sm mb-3">Other Locations</h3>
              <ul className="space-y-1.5 max-h-64 overflow-y-auto">
                {allLocs.filter(l => l.slug !== slug).map(l => (
                  <li key={l.slug}>
                    <Link href={`/locations/${l.slug}`} className="flex items-center gap-2 text-sm text-[#5c6472] hover:text-brand transition-colors py-0.5">
                      {l.icon && <span className="text-base">{l.icon}</span>}
                      <span>{l.name}</span>
                    </Link>
                  </li>
                ))}
              </ul>
            </div>
          </div>

        </div>
      </div>
    </>
  );
}
