import { headers } from "next/headers";
import { storefrontApi } from "@/lib/api";
import { getLocaleFromCookie, getTranslations } from "@/lib/i18n";
import { getLocalizedText } from "@/lib/utils";
import Link from "next/link";
import { notFound } from "next/navigation";

export const revalidate = 300;

interface PageProps {
  params: Promise<{ slug: string }>;
}

export default async function StaticPage({ params }: PageProps) {
  const { slug } = await params;
  const headersList = await headers();
  const tenantSlug = headersList.get("x-tenant-slug") || "";
  const cookieHeader = headersList.get("cookie") ?? "";
  const locale = getLocaleFromCookie(cookieHeader);
  const t = getTranslations(locale);

  if (!tenantSlug || tenantSlug === "default") {
    notFound();
  }

  const res = await storefrontApi.getPage(tenantSlug, slug).catch(() => null);
  const page = res?.page;
  if (!page) notFound();
  const title = getLocalizedText(page.title, page.title_ar, locale);
  const content = getLocalizedText(page.content, page.content_ar, locale);

  return (
    <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <nav className="text-xs text-gray-400 mb-8 flex items-center gap-1.5">
        <Link href="/" className="hover:text-gray-600 transition-colors">
          {t.page.home}
        </Link>
        <svg
          className="w-3 h-3 text-gray-300"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={2}
        >
          <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
        </svg>
        <span className="text-gray-600">{title}</span>
      </nav>

      <article>
        <h1 className="text-3xl font-bold text-gray-900 mb-3 tracking-tight leading-tight">
          {title}
        </h1>
        <div className="divider-primary mb-8" />
        <div
          className="prose max-w-none"
          dangerouslySetInnerHTML={{ __html: content }}
        />
      </article>

      {page.updated_at && (
        <p
          className="mt-14 text-xs text-gray-400 border-t border-gray-100 pt-5"
          suppressHydrationWarning
        >
          {t.page.lastUpdated}{" "}
          <span suppressHydrationWarning>
            {new Date(page.updated_at).toLocaleDateString()}
          </span>
        </p>
      )}
    </div>
  );
}
