"use client";

import FlexBox from "@component/FlexBox";
import Typography from "@component/Typography";
import { useHome } from "context/helpers/Home";
import { useParams } from "next/navigation";
import { useMemo } from "react";

interface CmsPage {
	id?: string | number;
	slug?: string;
	title?: string;
	content?: string;
	description?: string;
	body?: string;
}

export default function CmsPage() {
	const raw = useParams()?.slug;
	const slugParam = typeof raw === "string" ? raw : Array.isArray(raw) ? raw[0] : "";
	const { cmsPages = [] } = useHome();

	const page = useMemo(() => {
		const slug = decodeURIComponent(slugParam || "");
		return (cmsPages as CmsPage[]).find((p) => p?.slug === slug) || null;
	}, [cmsPages, slugParam]);

	if (!page) {
		return (
			<FlexBox flexDirection="column" alignItems="center" justifyContent="center" minHeight="50vh" px="1rem">
				<Typography fontSize={22} fontWeight="700" mb="0.5rem">
					Page not found
				</Typography>
				<Typography color="gray.600">This page isn’t available for the selected store.</Typography>
			</FlexBox>
		);
	}

	const html = page.content || page.description || page.body || "";

	return (
		<FlexBox flexDirection="column" maxWidth="900px" mx="auto" px="1rem" py="2rem">
			<Typography fontSize={28} fontWeight="800" mb="1rem">
				{page.title || page.slug}
			</Typography>
			{/* API provides HTML content */}
			<div dangerouslySetInnerHTML={{ __html: html }} />
		</FlexBox>
	);
}
