import { notFound } from 'next/navigation';
import pool from '@/lib/db';
import { RowDataPacket } from 'mysql2';
import ProductCatalog from '@/components/products/ProductCatalog';
import { Suspense } from 'react';
import { Loader2 } from 'lucide-react';

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

export default async function CategoryPage({ params }: PageProps) {
    const { slug } = await params;

    // Simple logic: Take the last segment as the category name
    const categorySlug = slug[slug.length - 1];

    // Convert "office-chairs" -> "Office Chairs"
    // Heuristic: matching case-insensitive
    const categoryNameCandidate = categorySlug.replace(/-/g, ' ');

    try {
        const [rows] = await pool.query<RowDataPacket[]>(
            'SELECT id, name FROM categories WHERE name = ? OR name LIKE ? LIMIT 1',
            [categoryNameCandidate, categoryNameCandidate]
        );

        if (rows.length === 0) {
            return notFound();
        }

        const category = rows[0];

        return (
            <Suspense fallback={<div className="p-10 text-center"><Loader2 className="animate-spin mx-auto" /></div>}>
                <ProductCatalog
                    initialCategoryId={category.id.toString()}
                    initialCategoryName={category.name}
                />
            </Suspense>
        );

    } catch (error) {
        console.error('Category Page Error:', error);
        return <div>Error loading category</div>;
    }
}
