import type { Metadata } from "next";
import { API_URL } from "@/config/constants";
import {
  createBreadcrumbJsonLd,
  createFacilityJsonLd,
  createPageMetadata,
  trimDescription,
} from "@/app/seo";
import FacilityDetailView from "./FacilityDetailView";

type GolfCoursePageProps = {
  params: Promise<{ slug: string }>;
};

async function getFacility(slug: string) {
  const res = await fetch(`${API_URL}/facilities/${slug}`, { cache: "no-store" });
  return res.json();
}

export async function generateMetadata({ params }: GolfCoursePageProps): Promise<Metadata> {
  const { slug } = await params;

  try {
    const facility = await getFacility(slug);
    if (!facility || facility.error) {
      return createPageMetadata({
        title: "Golfbane ikke funnet",
        description: "Golfanlegget du prøvde å åpne finnes ikke på TeeOff.",
        path: `/golfbaner/${slug}`,
      });
    }

    const title = `${facility.name}${facility.city ? ` i ${facility.city}` : ""}`;
    const fallbackDescription = `${facility.name} på TeeOff med banestatus, priser, kontaktinfo og lenker til nyttige ressurser.`;

    return createPageMetadata({
      title,
      description: trimDescription(facility.description) || fallbackDescription,
      path: `/golfbaner/${slug}`,
      image: facility.image_url,
    });
  } catch {
    return createPageMetadata({
      title: "Golfbane",
      description: "Golfanlegg på TeeOff med status, priser og klubbinfo.",
      path: `/golfbaner/${slug}`,
    });
  }
}

export default async function GolfCoursePage({ params }: GolfCoursePageProps) {
  const { slug } = await params;
  const facility = await getFacility(slug);

  if (!facility || facility.error) {
    return <div className="p-20 text-center font-bold text-2xl">Fant ikke golfbanen...</div>;
  }

  const facilityJsonLd = createFacilityJsonLd(facility);
  const breadcrumbJsonLd = createBreadcrumbJsonLd([
    { name: "Hjem", path: "/" },
    { name: "Golfbaner", path: "/golfbaner" },
    { name: facility.name, path: `/golfbaner/${facility.slug}` },
  ]);

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(facilityJsonLd) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbJsonLd) }}
      />
      <FacilityDetailView facility={facility} />
    </>
  );
}
