import Link from "next/link";
import { JsonLd } from "@/components/JsonLd";
import { SafeImage } from "@/components/SafeImage";
import { HomepageHeroMedia } from "@/components/HomepageHeroMedia";
import { Icon } from "@/components/kidz/Icon";
import { bundleItems } from "@/data/kidz";
import { FreeGuideGate } from "@/components/FreeGuideGate";
import { MarlotiiPricingBlock } from "@/components/MarlotiiPricing";
import { featuredStay } from "@/data/stays";
import { breadcrumbSchema, collectionPageSchema, createPageMetadata } from "@/lib/seo";
import { getAdminState } from "@/lib/admin-store";
import { whatsappHref } from "@/lib/public-url";
import {
  selectedListingPath,
  selectedListingTypeLabels,
  selectedListingsFromState,
  type SelectedListing,
  type SelectedListingType,
} from "@/lib/selected-listings";

export const dynamic = "force-dynamic";
export const metadata = createPageMetadata({
  title: "Marloth Park Central | Marlotii Safari House, Busy Bee Shuttle, Restaurants & Free Guides",
  description:
    "Marloth Park Central connects visitors to Marlotii Safari House, Busy Bee Shuttle, two featured restaurant partners, local services, local options and free visitor guides.",
  path: "/",
  image: "/images/heroes/homepage-hero.webp",
  keywords: [
    "Marlotii Safari House",
    "Marloth Park accommodation",
    "Marloth Park services",
    "Marloth Park visitor help",
    "Marloth Park Route Atlas",
  ],
});

const marlothiHomepagePath = "/stay";

const premiumAmenityIcons = [
  ["🏡", "Private self-catering home"],
  ["❄️", "2 air-conditioned bedrooms"],
  ["📶", "Uncapped WiFi"],
  ["⚡", "Generator backup"],
  ["🔥", "Patio, deck and braai"],
  ["🏊", "Pool and outdoor space"],
  ["📺", "55-inch TV with HDMI"],
  ["🦓", "Wildlife close to the home"],
];

type HomepageCard = {
  key: string;
  label: string;
  title: string;
  description: string;
  href: string;
  image: string;
  cta?: string;
};

type DepartmentSection = {
  id: string;
  eyebrow: string;
  title: string;
  text: string;
  hubHref: string;
  hubLabel: string;
  cards: HomepageCard[];
};

function cleanHomepageText(value: string, max = 146) {
  let text = String(value || "")
    .replace(/\s+/g, " ")
    .replace(/\bshops?\b/gi, "local stops")
    .replace(/\border(?:s|ing)?\b/gi, "request")
    .replace(/\bbuy(?:ing)?\b/gi, "view")
    .replace(/\bpurchase(?:s|d)?\b/gi, "view")
    .replace(/\bpaid\b/gi, "free-view")
    .replace(/\bpayments?\b/gi, "enquiry")
    .replace(/\bcheckout\b/gi, "guide page")
    .replace(/\bcart\b/gi, "guide page")
    .replace(/\bdownloads?\b/gi, "on-site pages")
    .replace(/\bdownloadable\b/gi, "on-site")
    .replace(/\bprintable\b/gi, "on-site")
    .replace(/\boffline\b/gi, "on-site")
    .replace(/\bbundle(?:s)?\b/gi, "guide")
    .trim();
  if (text.length <= max) return text;
  return `${text.slice(0, max - 1).trim()}…`;
}

function uniqueBySlug(listings: SelectedListing[]) {
  const seen = new Set<string>();
  return listings.filter((listing) => {
    const key = `${listing.listingType}:${listing.slug}`;
    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}

function listingCard(listing: SelectedListing, label?: string): HomepageCard {
  return {
    key: `${listing.listingType}-${listing.slug}`,
    label: label || selectedListingTypeLabels[listing.listingType],
    title: listing.name,
    description: cleanHomepageText(listing.shortDescription),
    href: selectedListingPath(listing),
    image: listing.images[0] || "/images/fallbacks/default-business-listing.webp",
    cta: "View listing",
  };
}

function bySlug(listings: SelectedListing[], slug: string) {
  return listings.find((listing) => listing.slug === slug);
}

function cardsBySlug(listings: SelectedListing[], slugs: string[], label: string) {
  return uniqueBySlug(slugs.map((slug) => bySlug(listings, slug)).filter(Boolean) as SelectedListing[]).map((listing) => listingCard(listing, label));
}

function cardsByType(listings: SelectedListing[], types: SelectedListingType[], label: string, limit = 8) {
  return uniqueBySlug(listings.filter((listing) => types.includes(listing.listingType))).slice(0, limit).map((listing) => listingCard(listing, label));
}

function SectionHeader({ eyebrow, title, text, hubHref, hubLabel }: { eyebrow: string; title: string; text: string; hubHref?: string; hubLabel?: string }) {
  return (
    <div className="homepage-editorial-header">
      <p className="eyebrow">{eyebrow}</p>
      <h2>{title}</h2>
      <p>{text}</p>
      {hubHref && hubLabel ? <Link className="btn btn-outline dark-text" href={hubHref}>{hubLabel}</Link> : null}
    </div>
  );
}

function HomepageCardTile({ card }: { card: HomepageCard }) {
  const featuredClass = card.key.includes("marloth-park-central-local-delivery") ? " is-main-featured-service" : "";
  return (
    <article className={`homepage-featured-partner-card homepage-department-listing-card${featuredClass}`}>
      <Link href={card.href} className="homepage-featured-partner-media" aria-label={`Open ${card.title}`}>
        <SafeImage src={card.image} alt={`${card.title} on Marloth Park Central`} />
        <span>{card.label}</span>
      </Link>
      <div className="homepage-featured-partner-body">
        <p className="eyebrow">{card.label}</p>
        <h3><Link href={card.href}>{card.title}</Link></h3>
        <p>{card.description}</p>
        <Link className="homepage-department-text-link" href={card.href}>{card.cta || "View listing"}</Link>
      </div>
    </article>
  );
}

function DepartmentListingSection({ section }: { section: DepartmentSection }) {
  if (!section.cards.length) return null;
  return (
    <section className="section homepage-featured-partners-section homepage-department-listing-section" id={section.id} aria-labelledby={`${section.id}-title`}>
      <div className="container">
        <SectionHeader eyebrow={section.eyebrow} title={section.title} text={section.text} hubHref={section.hubHref} hubLabel={section.hubLabel} />
        <div className="homepage-featured-partners-grid homepage-department-listing-grid">
          {section.cards.map((card) => <HomepageCardTile key={card.key} card={card} />)}
        </div>
      </div>
    </section>
  );
}

function stayWhatsAppHref() {
  const message = `Hi, I found ${featuredStay.name} on Marloth Park Central and would like to confirm availability, rates and booking details.`;
  return whatsappHref(featuredStay.whatsappNumber || "0723541091", message) || "/contact?topic=marlothi-safari-home-whatsapp";
}

function FeaturedStayLuxurySection() {
  const whatsappUrl = stayWhatsAppHref();
  const homepageGalleryTitles = [
    "Exterior / arrival view",
    "Main bedroom",
    "Second bedroom / visitor room",
    "Kitchen / dining",
  ];
  const gallery = homepageGalleryTitles
    .map((title) => featuredStay.gallery.find((item) => item.title === title))
    .filter(Boolean) as typeof featuredStay.gallery;
  return (
    <section className="section homepage-marlothi-luxury-section" id="featured-stay" aria-labelledby="homepage-marlothi-title">
      <div className="container homepage-marlothi-luxury-shell">
        <div className="homepage-marlothi-main-media">
          <SafeImage src={featuredStay.heroImage} alt="Marlotii Safari House featured Marloth Park holiday home" />
          <span>{featuredStay.badge}</span>
        </div>
        <div className="homepage-marlothi-luxury-copy">
          <p className="eyebrow">Featured accommodation</p>
          <h2 id="homepage-marlothi-title">Marlotii Safari House</h2>
          <p className="homepage-marlothi-lead">An image-led Marloth Park bush home showcase with direct enquiry routing, polished photography, practical stay details and Kruger planning links.</p>
          <div className="homepage-marlothi-icon-grid" aria-label="Marlotii Safari House key amenities">
            {premiumAmenityIcons.map(([icon, label]) => <span key={label}><b>{icon}</b>{label}</span>)}
          </div>
          <MarlotiiPricingBlock
            pricing={featuredStay.seasonalPricing}
            className="homepage-marlothi-rate-panel"
            compact
            heading="Private Safari Home"
            intro="Discover refined self-catering comfort in the heart of Marloth Park—an elegant private retreat for unhurried bushveld stays and effortless Kruger adventures."
          />
          <div className="hero-actions homepage-marlothi-actions">
            <Link className="btn btn-gold" href={marlothiHomepagePath}>View Home</Link>
            <Link className="btn btn-dark" href={whatsappUrl}>WhatsApp</Link>
            <Link className="btn btn-availability" href={`${marlothiHomepagePath}#stay-enquiry`}>Check Availability</Link>
          </div>
        </div>
        <div className="homepage-marlothi-gallery-strip" aria-label="Marlotii Safari House photo highlights">
          {gallery.map((item) => (
            <Link href={marlothiHomepagePath} key={item.image} aria-label={`View ${item.title}`}>
              <SafeImage src={item.image} alt={`${item.title} at Marlotii Safari House`} />
              <span>{item.title}</span>
            </Link>
          ))}
        </div>
      </div>
    </section>
  );
}



function BusyBeeShuttleSection({ listing }: { listing?: SelectedListing }) {
  if (!listing) return null;

  const listingHref = selectedListingPath(listing);
  const whatsappUrl = listing.whatsapp
    ? whatsappHref(listing.whatsapp, "Hi Busy Bee Shuttle, I found you on Marloth Park Central. Please help with transport for: [pickup], [destination], [date/time], [passengers].")
    : listingHref;
  const callUrl = listing.phone ? `tel:${listing.phone.replace(/[^\d+]/g, "")}` : listingHref;
  const serviceFacts = listing.sourceSupplier?.services?.slice(0, 6) || [];

  return (
    <section className="section homepage-busy-bee-feature" id="busy-bee-shuttle" aria-labelledby="homepage-busy-bee-title" data-homepage-block="busy-bee-shuttle">
      <div className="container homepage-busy-bee-shell">
        <Link href={listingHref} className="homepage-busy-bee-media" aria-label="Open Busy Bee Shuttle listing">
          <SafeImage src={listing.images[0] || "/images/local-options/busy-bee-shuttle.webp"} alt="Busy Bee Shuttle transport services for Marloth Park" />
          <span>Homepage shuttle partner</span>
        </Link>
        <div className="homepage-busy-bee-copy">
          <p className="eyebrow">Featured shuttle advertisement</p>
          <h2 id="homepage-busy-bee-title">Busy Bee Shuttle</h2>
          <p className="homepage-busy-bee-lead">Safe, comfortable guest transport for Marloth Park, restaurant trips, local shopping, airport transfers and Crocodile Bridge connections.</p>
          <div className="homepage-busy-bee-facts" aria-label="Busy Bee Shuttle service highlights">
            {serviceFacts.map((fact) => <span key={fact}>{fact}</span>)}
          </div>
          <p className="homepage-busy-bee-note">Confirm pickup point, route, passenger requirements, availability and rates directly with Busy Bee before travelling.</p>
          <div className="hero-actions homepage-busy-bee-actions">
            <Link className="btn btn-gold" href={whatsappUrl}>WhatsApp Busy Bee</Link>
            <Link className="btn btn-dark" href={callUrl}>Call Busy Bee</Link>
            <Link className="btn btn-outline dark-text" href={listingHref}>View shuttle listing</Link>
          </div>
        </div>
      </div>
    </section>
  );
}

function FeaturedRestaurantPairSection({ cards, shuttleListing }: { cards: HomepageCard[]; shuttleListing?: SelectedListing }) {
  if (!cards.length) return null;
  const shuttleHref = shuttleListing ? selectedListingPath(shuttleListing) : "/services";

  return (
    <section className="section homepage-restaurant-pair-section" id="homepage-featured-restaurants" aria-labelledby="homepage-featured-restaurants-title" data-homepage-block="featured-restaurants">
      <div className="container">
        <SectionHeader
          eyebrow="Featured restaurant partners"
          title="Choose where to eat, then arrange the ride separately."
          text="These two restaurant placements operate independently from Busy Bee Shuttle. Contact each restaurant directly for its menu or table, and contact Busy Bee separately for transport."
          hubHref="/restaurants"
          hubLabel="View all restaurants"
        />
        <div className="homepage-restaurant-pair-grid">
          {cards.slice(0, 2).map((card, index) => (
            <article className="homepage-restaurant-pair-card" key={card.key}>
              <Link href={card.href} className="homepage-restaurant-pair-media" aria-label={`Open ${card.title}`}>
                <SafeImage src={card.image || "/images/local-options/food-dining.webp"} alt={`${card.title} featured restaurant position`} />
                <span>Featured restaurant {index + 1}</span>
              </Link>
              <div className="homepage-restaurant-pair-body">
                <p className="eyebrow">Restaurant partner</p>
                <h3><Link href={card.href}>{card.title}</Link></h3>
                <p>{card.description}</p>
                <div className="homepage-restaurant-pair-actions">
                  <Link className="btn btn-gold" href={card.href}>{card.cta || "View restaurant"}</Link>
                  <Link className="btn btn-outline dark-text" href={`${shuttleHref}#listing-details`}>Arrange shuttle separately</Link>
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function FreeGuidesSection() {
  return (
    <section className="section homepage-guide-pack-section" id="free-guides-home" aria-labelledby="homepage-free-guides-title">
      <div className="container homepage-guide-pack-grid">
        <article className="homepage-guide-pack-panel homepage-guide-pack-free has-homepage-image-box">
          <Link href="/guides" className="homepage-section-image-box homepage-free-guide-set-image-box" aria-label="View free visitor guides">
            <SafeImage src="/images/homepage/free-guide-set.webp" alt="MPC free visitor guide homepage image" />
            <span>Free Guides</span>
          </Link>
          <p className="eyebrow">Free visitor guides</p>
          <h2 id="homepage-free-guides-title">Free visitor guides and on-site planning help.</h2>
          <p>Free Marloth Park visitor guides are available to view on Marloth Park Central. Read on site for arrival planning, local options, services and route context.</p>
          <div className="hero-actions">
            <Link className="btn btn-gold" href="/guides">View free guides</Link>
            <Link className="btn btn-outline dark-text" href="/visitor-help">Visitor planning help</Link>
          </div>
        </article>
        <article className="homepage-guide-pack-panel homepage-guide-pack-map has-homepage-image-box">
          <Link href="/free-guides/kruger-visitor-map" className="homepage-section-image-box homepage-kruger-map-image-box" aria-label="Preview and download the free Kruger Visitor Map">
            <SafeImage src="/images/free-guides/kruger-visitor-map/cover.webp" alt="MPC Premium Kruger Visitor Map free download" />
            <span>Free map download</span>
          </Link>
          <p className="eyebrow">Free 4-image ZIP</p>
          <h2>Download the MPC Premium Kruger Visitor Map.</h2>
          <p>Get the illustrated visitor overview, gate-exit quick reference, cover and print guide as four full-resolution PNG images in one free ZIP.</p>
          <div className="hero-actions">
            <a className="btn btn-gold" href="/free-guides/kruger-visitor-map#mpc-premium-kruger-visitor-map-free-email-gate">Get free map pack</a>
            <Link className="btn btn-outline dark-text" href="/free-guides/kruger-visitor-map">Preview all pages</Link>
          </div>
        </article>
        <article className="homepage-guide-pack-panel homepage-guide-pack-online">
          <p className="eyebrow">Free Route Atlas</p>
          <h2>Free Route Atlas, viewable on this site.</h2>
          <p>Use free Route Atlas pages on Marloth Park Central for gate context, route decisions, safer timing and visitor planning. The route pages are on-site resources.</p>
          <ul>
            <li>Free to view on Marloth Park Central</li>
            <li>Read on site for visitor route planning</li>
            <li>Browse route pages before your Kruger day</li>
          </ul>
          <div className="hero-actions">
            <Link className="btn btn-gold" href="/route-atlas">View Route Atlas</Link>
            <Link className="btn btn-outline dark-text" href="/guides">View all free guides</Link>
          </div>
        </article>
      </div>
    </section>
  );
}

function KidzBundleSection() {
  return (
    <section className="section homepage-kidz-bundle-section" id="marloth-kruger-kidz" aria-labelledby="homepage-kidz-title">
      <div className="container homepage-kidz-bundle-shell">
        <div className="homepage-kidz-bundle-copy">
          <p className="eyebrow">Free visitor resource</p>
          <h2 id="homepage-kidz-title">Marloth Kruger Kidz Adventure Bundle</h2>
          <p>Seven mobile-first and print-friendly family activities that keep children spotting, learning, creating and recording the holiday while wildlife safety stays central.</p>
          <div className="hero-actions">
            <Link className="btn btn-gold" href="/kidz">Open the Kidz bundle</Link>
            <Link className="btn btn-outline" href="/kidz/passport">Start the adventure passport</Link>
          </div>
        </div>
        <div className="homepage-kidz-bundle-grid">
          {bundleItems.map((item, index) => (
            <Link className="homepage-kidz-bundle-card" href={`/kidz/${item.slug}`} key={item.slug}>
              <span aria-hidden="true"><Icon name={item.icon} size={24}/></span>
              <span><strong>{item.shortTitle}</strong><small>{item.age} · {item.duration}</small></span>
            </Link>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomepageInternationalVisitorsSection() {
  return (
    <section className="section homepage-international-guide-section" id="international-visitors" aria-labelledby="homepage-international-guide-title">
      <div className="container homepage-international-guide-card has-homepage-image-box">
        <Link href="/international-visitors-guide" className="homepage-section-image-box homepage-international-visitors-image-box" aria-label="Open International Visitors Guide">
          <SafeImage src="/images/homepage/international-visitors.webp" alt="Marloth Park international visitor guide homepage image" />
          <span>International visitors</span>
        </Link>
        <div>
          <p className="eyebrow">International visitors</p>
          <h2 id="homepage-international-guide-title">Free Marloth Park guide for overseas visitors.</h2>
          <p>Open the visitor-facing international guide for arrival, driving, Kruger day-trip timing, safety, money, local orientation and useful MPC pages.</p>
          <div className="hero-actions">
            <Link className="btn btn-gold" href="/international-visitors-guide">Open International Visitors Guide</Link>
            <Link className="btn btn-outline dark-text" href="/contact?topic=international-visitors">Ask MPC</Link>
          </div>
        </div>
      </div>
    </section>
  );
}

function ContactHelpSection() {
  return (
    <section className="section homepage-contact-help-section" id="contact-help" aria-labelledby="homepage-contact-help-title">
      <div className="container homepage-guide-pack-grid">
        <article className="homepage-guide-pack-panel homepage-guide-pack-online">
          <p className="eyebrow">Contact / help</p>
          <h2 id="homepage-contact-help-title">Need a direct MPC pointer?</h2>
          <p>Use Contact MPC when you need help choosing the right listing, guide page, department or enquiry path.</p>
          <div className="hero-actions">
            <Link className="btn btn-gold" href="/contact">Contact MPC</Link>
            <Link className="btn btn-outline dark-text" href="/visitor-help">Visitor help</Link>
          </div>
        </article>
        <FreeGuideGate defaultBundle="mpc-free-explorer-pack" sourcePage="/" />
      </div>
    </section>
  );
}

function buildDepartmentSections(listings: SelectedListing[]): DepartmentSection[] {
  const serviceCards = cardsBySlug(listings, [
    "wild-wheels-workshop",
    "km-electrical",
    "mr-t-gas",
  ], "Featured service");

  const localOptions = cardsBySlug(listings, [
    "ingwe-supermarket-liquor-store",
    "nkosi-mobile-spa",
    "caroline-frozen-meals",
  ], "Local option");

  return [
    {
      id: "homepage-services",
      eyebrow: "Featured Services",
      title: "Trusted local help, when you need it.",
      text: "Find selected mobile mechanics, electrical and gas services in a dedicated block below the restaurant partners.",
      hubHref: "/services",
      hubLabel: "Explore services",
      cards: serviceCards,
    },
    {
      id: "homepage-local-options",
      eyebrow: "Local Options",
      title: "Food, shopping and useful local favourites.",
      text: "Browse selected essentials and useful local options for an easier Marloth Park stay.",
      hubHref: "/local-options",
      hubLabel: "View all local options",
      cards: localOptions,
    },
  ];
}

export default async function HomePage() {
  const state = await getAdminState();
  const selectedListings = selectedListingsFromState(state);
  const departmentSections = buildDepartmentSections(selectedListings);
  const busyBeeShuttle = bySlug(selectedListings, "busy-bee-shuttle");
  const restaurantListings = selectedListings
    .filter((listing) => listing.listingType === "restaurant" && listing.slug !== "caroline-frozen-meals")
    .slice(0, 2);
  const featuredRestaurantCards: HomepageCard[] = restaurantListings.map((listing) => ({
    ...listingCard(listing, "Restaurant partner"),
    cta: "View restaurant",
  }));
  while (featuredRestaurantCards.length < 2) {
    const position = featuredRestaurantCards.length + 1;
    featuredRestaurantCards.push({
      key: `featured-restaurant-position-${position}`,
      label: `Featured restaurant ${position}`,
      title: `Featured Restaurant Partner ${position}`,
      description: "Reserved for a verified Marloth Park restaurant partner. Menu, contact, booking and opening details will appear here when the restaurant listing is ready.",
      href: "/restaurants",
      image: "/images/local-options/food-dining.webp",
      cta: "View restaurants",
    });
  }
  const itemNames = [featuredStay.name, ...(busyBeeShuttle ? [busyBeeShuttle.name] : []), ...featuredRestaurantCards.map((card) => card.title), ...departmentSections.flatMap((section) => section.cards.map((card) => card.title)), "Free Route Atlas", "Free visitor guides", "Marloth Kruger Kidz Adventure Bundle"];

  return (
    <main className="home-page visitor-first-home mobile-local-platform-home homepage-fold-rebuild homepage-v137 homepage-v174">
      <JsonLd
        data={[
          breadcrumbSchema([{ name: "Home", path: "/" }]),
          collectionPageSchema({
            name: "Marloth Park Central",
            description: "Find Marlotii Safari House, Busy Bee Shuttle, two featured restaurants, selected services, local options, visitor help and free on-site guides near Kruger National Park.",
            path: "/",
            itemNames,
          }),
        ]}
      />

      <section className="homepage-fold-hero homepage-v112-hero" aria-labelledby="homepage-title">
        <div className="container homepage-fold-hero-grid">
          <div className="homepage-fold-hero-copy">
            <p className="eyebrow">Marloth Park Central</p>
            <h1 id="homepage-title">Your Marloth Park adventure starts before you arrive.</h1>
            <p>Find the stay, local services, route ideas, visitor tips and safari-ready planning tools that make Marloth Park easier to explore.</p>
            <div className="hero-actions homepage-hero-actions">
              <Link className="btn btn-gold" href="#featured-stay">View Featured Stay</Link>
              <Link className="btn btn-outline" href="/route-atlas">Explore Free Route Atlas</Link>
              <Link className="btn btn-outline" href="/shop">Shop Visitor Bundles</Link>
            </div>
            <div className="homepage-hero-proof" aria-label="Marloth Park Central visitor benefits">
              <span><strong>Local-first</strong> visitor planning</span>
              <span><strong>Direct</strong> listing enquiries</span>
              <span><strong>Free</strong> guides and route help</span>
            </div>
          </div>
          <HomepageHeroMedia config={state.homepageHeroMedia} />
        </div>
      </section>

      <FeaturedStayLuxurySection />
      <BusyBeeShuttleSection listing={busyBeeShuttle} />
      <FeaturedRestaurantPairSection cards={featuredRestaurantCards} shuttleListing={busyBeeShuttle} />
      {departmentSections.map((section) => <DepartmentListingSection key={section.id} section={section} />)}
      <FreeGuidesSection />
      <KidzBundleSection />
      <HomepageInternationalVisitorsSection />
      <ContactHelpSection />
    </main>
  );
}
