import { trainData } from "@/data";
import trainImages from "@/data/trainImages.json";
import { getArticleSchema } from "@/lib/schemas";
import { notFound } from "next/navigation";
import TrainDetailClient from "./TrainDetailClient";

export function generateStaticParams() {
  return trainData.map((train) => ({
    trainId: train.data.train_name
      .replace(/\s+/g, "-")
      .toLowerCase()
      .replace(/[()]/g, ""),
  }));
}

export function generateMetadata({ params }) {
  const train = trainData.find((t) => {
    const slug = t.data.train_name
      .replace(/\s+/g, "-")
      .toLowerCase()
      .replace(/[()]/g, "");
    return slug === params.trainId;
  });

  if (!train) return {};

  const trainName = train.data.train_name
    .split("(")[0]
    .trim()
    .toLowerCase()
    .replace(/\b\w/g, (c) => c.toUpperCase());
  const firstStation = train.data.routes[0]?.city?.replace(/_/g, " ") || "";
  const lastStation =
    train.data.routes[train.data.routes.length - 1]?.city?.replace(/_/g, " ") ||
    "";

  return {
    title: `${trainName} - Schedule, Route & Details`,
    description: `Complete details for ${trainName} train running from ${firstStation} to ${lastStation}. View schedule, stops, arrival/departure times.`,
    keywords: [
      trainName,
      `${trainName} schedule`,
      `${trainName} route`,
      "Bangladesh Railway",
      "train details",
    ],
    openGraph: {
      title: `${trainName} | Trains of Rajbari`,
      description: `Complete details for ${trainName} - ${firstStation} to ${lastStation}`,
      url: `https://trainsofrajbari.com/train/${params.trainId}`,
      images: [{ url: "/logo.png" }],
    },
    alternates: {
      canonical: `https://trainsofrajbari.com/train/${params.trainId}`,
    },
  };
}

export default function TrainDetailPage({ params }) {
  const train = trainData.find((t) => {
    const slug = t.data.train_name
      .replace(/\s+/g, "-")
      .toLowerCase()
      .replace(/[()]/g, "");
    return slug === params.trainId;
  });

  if (!train) notFound();

  const trainName = train.data.train_name
    .split("(")[0]
    .trim()
    .toLowerCase()
    .replace(/\b\w/g, (c) => c.toUpperCase());
  const trainNumberMatch = train.data.train_name.match(/\((\d+)\)/);
  const trainNumber = trainNumberMatch ? trainNumberMatch[1] : "";
  const firstStation = train.data.routes[0]?.city?.replace(/_/g, " ") || "";
  const lastStation =
    train.data.routes[train.data.routes.length - 1]?.city?.replace(/_/g, " ") ||
    "";

  // Find images for this train
  const baseName = train.data.train_name.split("(")[0].trim();
  const images = trainImages[baseName] || [];

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(
            getArticleSchema({
              title: `${trainName} - Schedule, Route & Details`,
              description: `Complete details for ${trainName} running from ${firstStation} to ${lastStation}`,
              author: "Trains of Rajbari",
              datePublished: new Date().toISOString().split("T")[0],
              image: images[0]
                ? `https://trainsofrajbari.com${images[0]}`
                : "https://trainsofrajbari.com/logo.png",
              url: `https://trainsofrajbari.com/train/${params.trainId}`,
            })
          ),
        }}
      />
      <TrainDetailClient
        train={train}
        trainName={trainName}
        trainNumber={trainNumber}
        firstStation={firstStation}
        lastStation={lastStation}
        images={images}
      />
    </>
  );
}
