import { cache } from "react";
import { Metadata } from "next";
import dynamic from "next/dynamic";

import Hero from "@/routes/Scilly/hero";
import SnippetsInjector from "@/component/snippetsInjector";

import {
  WhyChooseSection,
  SpecialSection,
  WeekendEscapeSection,
  TestimonialsSection,
  AwardsRecognition,
  ReadyToExperienceParadise,
  ScillyImageGallery,
  RequestForm,
  Footer,
  FloatingBookButton,
  CookieConsent,
} from "./LazySections.client";

const ScillySmoothScroll = dynamic(() => import("@/routes/Scilly/SmoothScroll"));

const CMS_BASE = process.env.NEXT_PUBLIC_CMS_BASE_URL?.replace(/\/$/, "") ?? "";

function toCmsAbsoluteUrl(url?: string | null): string | null {
  if (!url) return null;
  if (url.startsWith("http://") || url.startsWith("https://")) return url;
  if (CMS_BASE && url.startsWith("/")) return `${CMS_BASE}${url}`;
  return null;
}

const getScillyPageData = cache(async () => {
  const baseUrl = process.env.NEXT_PUBLIC_CMS_BASE_URL;

  if (!baseUrl) {
    throw new Error("NEXT_PUBLIC_CMS_BASE_URL is not defined");
  }

  const res = await fetch(
    `${baseUrl}/api/pages/render/scilly-days-2?include=media,forms,globals,snippets&mediaSizes=small,medium,large,og&compact=true&includeMeta=true`,
    {
      next: { revalidate: 60 },
    }
  );

  if (!res.ok) {
    throw new Error(`Failed to fetch Scilly page data: ${res.status}`);
  }

  const result = await res.json();
  if (!result?.layout) {
    throw new Error("No page layout found for slug: scilly-days-2");
  }

  return result;
});

export async function generateMetadata(): Promise<Metadata> {
  try {
    const data = await getScillyPageData();
    const pageMeta = data?.page?.meta;
    const title = pageMeta?.title || data?.page?.title || "Scilly Days";
    const description = pageMeta?.description || "Experience paradise at Scilly Days. Exclusive offers, luxury stays, and unforgettable island escapes.";

    const metaImageId = pageMeta?.metaImageId;
    const mediaEntry = metaImageId ? data?.included?.media?.[String(metaImageId)] : null;
    const ogImageUrl =
      mediaEntry?.sizes?.og?.url || mediaEntry?.url || "/scilly/hero-desktop.jpg";

    const pageUrl = `${process.env.NEXT_PUBLIC_SITE_URL || "https://dev.ads.karmagroup.com"}/scilly-days`;

    return {
      title,
      description,
      alternates: {
        canonical: pageUrl,
      },
      openGraph: {
        title,
        description,
        url: pageUrl,
        type: "website",
        ...(ogImageUrl && {
          images: [{ url: ogImageUrl, alt: title }],
        }),
      },
      twitter: {
        card: "summary_large_image",
        title,
        description,
        ...(ogImageUrl && { images: [ogImageUrl] }),
      },
    };
  } catch {
    return {
      title: "Scilly Days",
    };
  }
}

export default async function ScillyPage() {
  const data = await getScillyPageData();

  // Extract mobile hero image URL to emit a server-side preload hint.
  // Browser starts fetching the image in parallel with HTML parsing,
  // cutting mobile LCP before React hydrates.
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const heroBlock = (data?.layout as any[])?.find(
    (b: any) => b?.type === "heroOfferV1" && b?.props?.variant === "hero"
  );
  const mediaMap: Record<string, any> = data?.included?.media ?? {};
  const mobileId = heroBlock?.props?.mobileImageId;
  const mobileMedia = mobileId != null ? mediaMap[String(mobileId)] : null;
  const rawMobileUrl = toCmsAbsoluteUrl(
    mobileMedia?.sizes?.medium?.url ?? mobileMedia?.sizes?.small?.url ?? mobileMedia?.url
  );
  // Moto G Power: 412px × 2.625 DPR ≈ 1082px → Next.js picks 1200w from deviceSizes.
  const enc = rawMobileUrl ? encodeURIComponent(rawMobileUrl) : null;

  return (
    <>
      {enc && (
        <link
          rel="preload"
          as="image"
          href={`/_next/image?url=${enc}&w=1200&q=75`}
          imageSrcSet={`/_next/image?url=${enc}&w=828&q=75 828w, /_next/image?url=${enc}&w=1080&q=75 1080w, /_next/image?url=${enc}&w=1200&q=75 1200w`}
          imageSizes="(max-width: 640px) 100vw, 1px"
          media="(max-width: 639px)"
          fetchPriority="high"
        />
      )}
      <link rel="dns-prefetch" href="https://www.google.com" />
      <link rel="dns-prefetch" href="https://www.gstatic.com" />

      <SnippetsInjector
        snippets={data?.snippets}
        pageSnippets={data?.page?.meta?.snippets}
        renderTop
        renderBottom
      />

      <ScillySmoothScroll />
      <main>
        <Hero data={data} />
        <WhyChooseSection data={data} />
        <SpecialSection data={data} />
        <WeekendEscapeSection data={data} />
        <TestimonialsSection data={data} />
        <AwardsRecognition data={data} />
        <ReadyToExperienceParadise data={data} />
        <ScillyImageGallery data={data} />
        <RequestForm data={data} />
        <Footer data={data} />
      </main>
      <FloatingBookButton cta={data?.layoutSettings?.floatingCTA} />
      <CookieConsent data={data} />
    </>
  );
}
