import { NextResponse } from "next/server";
import { getCollection } from "@/lib/mongodb";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";

interface PageProps {
  params: Promise<{ slug: string }>;
}

const policySlugMap: { [key: string]: string } = {
  terms: "terms_and_conditions",
  privacy: "privacy_policy",
  cookie: "cookie_policy",
  shipping: "shipping_policy",
  returns: "returns_refunds_policy",
  cancellation: "cancellation_policy",
  tax: "tax_vat_policy",
  warranty: "warranty_policy",
  payment: "payment_security_policy",
  "product-data": "product_data_policy",
  accessibility: "accessibility_statement",
  about: "about_us",
  contact: "contact_us",
};

export default async function PolicyPage({ params }: PageProps) {
  const { slug } = await params;
  const policyKey = policySlugMap[slug] || slug;

  try {
    const collection = await getCollection("settings");
    const settings = await collection.findOne({});

    const policyContent =
      settings?.policy_pages?.[policyKey] ||
      `Policy page "${slug}" not found.`;

    const pageTitle = slug
      .split("-")
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
      .join(" ");

    return (
      <div className="min-h-screen flex flex-col">
        <Navbar />
        <main className="flex-grow container mx-auto px-4 py-8">
          <div className="max-w-4xl mx-auto bg-white rounded-lg shadow p-8">
            <h1 className="text-3xl font-bold text-gray-900 mb-6">{pageTitle}</h1>
            <div
              className="prose max-w-none"
              dangerouslySetInnerHTML={{ __html: policyContent }}
            />
          </div>
        </main>
        <Footer />
      </div>
    );
  } catch (error) {
    console.error("Error fetching policy page:", error);
    return (
      <div className="min-h-screen flex flex-col">
        <Navbar />
        <main className="flex-grow container mx-auto px-4 py-8">
          <div className="max-w-4xl mx-auto bg-white rounded-lg shadow p-8">
            <h1 className="text-3xl font-bold text-gray-900 mb-6">Policy Page</h1>
            <p className="text-gray-600">Error loading policy page content.</p>
          </div>
        </main>
        <Footer />
      </div>
    );
  }
}

