import FacilitySearch from "@/app/FacilitySearch";
import { API_URL } from "@/config/constants";
import {
  createBreadcrumbJsonLd,
  createCollectionPageJsonLd,
  createItemListJsonLd,
  createPageMetadata,
} from "@/app/seo";

export const dynamic = "force-dynamic";

const pageTitle = "Golfbaner i Norge";
const pageDescription =
  "Finn golfbaner i Norge og filtrer på område, banestatus, antall hull og fasiliteter i TeeOffs samlede oversikt.";

export const metadata = createPageMetadata({
  title: pageTitle,
  description: pageDescription,
  path: "/golfbaner",
});

export default async function GolfCoursesIndexPage() {
  let facilities = [];

  try {
    const res = await fetch(`${API_URL}/facilities`, {
      next: { revalidate: 0 },
      cache: "no-store",
    });

    if (!res.ok) {
      throw new Error(`API returnerte status ${res.status}`);
    }

    facilities = await res.json();
  } catch (error) {
    console.error("Kritisk feil ved henting av golfbaner:", error);
    facilities = [];
  }

  const safeData = Array.isArray(facilities) ? facilities : [];
  const collectionJsonLd = createCollectionPageJsonLd({
    name: pageTitle,
    description: pageDescription,
    path: "/golfbaner",
  });
  const itemListJsonLd = createItemListJsonLd({
    name: pageTitle,
    path: "/golfbaner",
    items: safeData
      .filter((facility) => facility?.slug && facility?.name)
      .map((facility) => ({
        name: facility.name,
        path: `/golfbaner/${facility.slug}`,
        description: facility.description,
      })),
  });
  const breadcrumbJsonLd = createBreadcrumbJsonLd([
    { name: "Hjem", path: "/" },
    { name: "Golfbaner", path: "/golfbaner" },
  ]);

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(collectionJsonLd) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(itemListJsonLd) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbJsonLd) }}
      />
      <main className="site-shell min-h-screen">
        <section className="mx-auto max-w-[1400px] px-4 pt-6 sm:px-6 sm:pt-8 lg:px-8 lg:pt-10">
          <div className="mb-2 max-w-4xl">
            <p className="mb-3 text-[11px] font-extrabold uppercase tracking-[0.3em] text-[#6FA786]">Golfbaner</p>
            <h1 className="section-title text-4xl text-[#112015] sm:text-5xl lg:text-6xl">Golfbaner i Norge</h1>
            <p className="mt-4 max-w-3xl text-base leading-8 text-[#617063]">
              Filtrer norske golfbaner etter område, banestatus, antall hull og fasiliteter, og gå videre til hver baneprofil.
            </p>
          </div>
        </section>
        <FacilitySearch
          initialFacilities={safeData}
          variant="home"
          hideTitleBlock
          filterHeading="Filtrer golfbaner"
        />
      </main>
    </>
  );
}
