import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import StorePage from '@/components/store/StorePage';
import StoreClosedPage from '@/components/store/StoreClosedPage';
import { loadStoreConfig } from '@/lib/storeConfig';
import { loadStoreCatalog } from '@/lib/storeCatalog';
import { loadStoreProduct } from '@/lib/storeProduct';
import { getStoreBaseUrl, isIndexable } from '@/lib/storeSeo';

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

/**
 * Ficha de producto con URL propia. La tienda navega por hash (#/producto/…), que
 * los buscadores no indexan y que al compartirse no trae vista previa: todas las
 * fichas tenían el título «Comercial Kety» y ninguna imagen. Esta ruta se renderiza
 * en el servidor con la metadata del producto y abre su ficha al cargar.
 */
// eslint-disable-next-line react-refresh/only-export-components
export async function generateMetadata({ params }: Params): Promise<Metadata> {
	const { slug } = await params;
	const [config, product] = await Promise.all([loadStoreConfig(), loadStoreProduct(slug)]);

	if (!product) return { title: 'Producto no encontrado', robots: { index: false, follow: false } };

	const base = await getStoreBaseUrl();
	const url = `${base}/producto/${product.slug || product.id}`;
	const descripcion =
		(product.description && product.description !== product.name ? product.description : '') ||
		`${product.name}${product.brand ? ` · ${product.brand}` : ''} en ${config.identity?.name ?? 'la tienda'}.`;
	const imagen = product.image?.trim() || undefined;

	return {
		title: product.name,
		description: descripcion.slice(0, 300),
		alternates: { canonical: url },
		robots: isIndexable(config) ? { index: true, follow: true } : { index: false, follow: false },
		openGraph: {
			type: 'website',
			title: product.name,
			description: descripcion.slice(0, 300),
			url,
			siteName: config.identity?.name,
			locale: 'es_PY',
			...(imagen ? { images: [{ url: imagen, alt: product.name }] } : {})
		},
		twitter: {
			card: imagen ? 'summary_large_image' : 'summary',
			title: product.name,
			description: descripcion.slice(0, 200)
		}
	};
}

export default async function ProductoPage({ params }: Params) {
	const { slug } = await params;
	const [config, catalog, product] = await Promise.all([
		loadStoreConfig(),
		loadStoreCatalog(),
		loadStoreProduct(slug)
	]);

	if (config.status === 'closed') return <StoreClosedPage config={config} />;
	if (!product) notFound();

	return (
		<StorePage
			config={config}
			catalog={catalog}
			initialProductId={product.id}
		/>
	);
}
