/**
 * ============================================
 * CATEGORY PRODUCT LISTING PAGE
 * ============================================
 * Equivalent to: category/index.html.twig in Shopware
 * Route: /category/[id]
 *
 * Server component — data is fetched on the server for fast LCP.
 * Sort, pagination and filters are driven by URL search params.
 */

import { Suspense } from 'react';
import Link from 'next/link';
import { redirect } from 'next/navigation';
import ProductCard from '@/components/product/ProductCard';
import CategoryControls from '@/components/category/CategoryControls';
import CategoryFilters from '@/components/category/CategoryFilters';
import CmsPage from '@/components/cms/CmsPage';
import {
  getProducts,
  getCategoryWithCmsPage,
  getNavigation,
  getCategoryUrl,
  getActiveLocalePrefix,
  ShopwareCategory,
} from '@/lib/shopware-api';

const LIMIT = 12;

interface PageProps {
  params: Promise<{ id: string }>;
  searchParams: Promise<{
    sort?: string;
    page?: string;
    manufacturer?: string;
    properties?: string;
    'min-price'?: string;
    'max-price'?: string;
    _fromSeo?: string;
  }>;
}

export default async function CategoryPage({ params, searchParams }: PageProps) {
  const [{ id: categoryId }, sp] = await Promise.all([params, searchParams]);

  const sort = sp.sort ?? '';
  const page = Math.max(1, parseInt(sp.page ?? '1', 10) || 1);
  const manufacturer = sp.manufacturer?.split(',').filter(Boolean) ?? [];
  const properties = sp.properties?.split(',').filter(Boolean) ?? [];
  const minPrice = sp['min-price'] ? parseFloat(sp['min-price']) : undefined;
  const maxPrice = sp['max-price'] ? parseFloat(sp['max-price']) : undefined;

  // Fetch category (with CMS page if assigned)
  const category = await getCategoryWithCmsPage(categoryId).catch(() => null);

  // Force the slug URL in the browser. When reached via the catch-all,
  // _fromSeo is set so we don't redirect away from the URL the user is on.
  if (!sp._fromSeo && category) {
    const categoryForUrl: Partial<ShopwareCategory> & { id: string } =
      category.category ?? category;
    const target = getCategoryUrl(categoryForUrl as ShopwareCategory);
    if (!target.startsWith('/category/')) {
      const params = new URLSearchParams();
      if (sp.sort) params.set('sort', sp.sort);
      if (sp.page) params.set('page', sp.page);
      if (sp.manufacturer) params.set('manufacturer', sp.manufacturer);
      if (sp.properties) params.set('properties', sp.properties);
      if (sp['min-price']) params.set('min-price', sp['min-price']);
      if (sp['max-price']) params.set('max-price', sp['max-price']);
      const qs = params.toString();
      redirect(`${getActiveLocalePrefix()}${target}${qs ? `?${qs}` : ''}`);
    }
  }

  // If a CMS listing layout is assigned (contains 'sidebar-filter' or 'listing' or 'product-listing' slots),
  // render the entire CMS page which includes the product listing.
  const cmsPageSections =
    category?.cmsPage?.sections ??
    category?.category?.cmsPage?.sections ??
    null;

  const isListingLayout = cmsPageSections?.some((section: any) =>
    section.blocks?.some((block: any) =>
      block.slots?.some((slot: any) =>
        ['sidebar-filter', 'listing', 'product-listing'].includes(slot.type)
      )
    )
  ) ?? false;

  // If there's a CMS listing layout, render it (it contains product listing + filters)
  if (isListingLayout && cmsPageSections) {
    const categoryName =
      category?.translated?.name ?? category?.category?.translated?.name ?? category?.name ?? '';
    return (
      <div>
        <div className="max-w-7xl mx-auto px-6 py-6">
          <nav aria-label="Breadcrumb" className="flex items-center gap-2 text-sm text-surface-400 mb-4">
            <Link href={getActiveLocalePrefix() || '/'} className="hover:text-surface-600 transition-colors">Home</Link>
            {categoryName && (
              <>
                <span aria-hidden="true">/</span>
                <span className="text-surface-700 font-medium" aria-current="page">{categoryName}</span>
              </>
            )}
          </nav>
        </div>
        <CmsPage sections={cmsPageSections} />
      </div>
    );
  }

  // Fetch products with all active filters
  const productsResponse = await getProducts({
    categoryId,
    limit: LIMIT,
    page,
    sort: sort || undefined,
    manufacturer: manufacturer.length ? manufacturer : undefined,
    properties: properties.length ? properties : undefined,
    minPrice,
    maxPrice,
  }).catch(() => ({ elements: [], total: 0, aggregations: undefined }));

  // Child categories for subcategory chips
  let childCategories: Array<{ id: string; name: string; translated?: { name: string } }> = [];
  try {
    childCategories = (await getNavigation(categoryId, 1)) || [];
  } catch {
    // non-fatal
  }

  const products = productsResponse.elements || [];
  const total = productsResponse.total || 0;
  const totalPages = Math.ceil(total / LIMIT);
  const aggregations = productsResponse.aggregations ?? {};

  return (
    <div className="max-w-7xl mx-auto px-6 py-10">
      {/* Breadcrumb */}
      <nav aria-label="Breadcrumb" className="flex items-center gap-2 text-sm text-surface-400 mb-6">
        <Link href={getActiveLocalePrefix() || '/'} className="hover:text-surface-600 transition-colors">Home</Link>
        {category && (
          <>
            <span aria-hidden="true">/</span>
            <span className="text-surface-700 font-medium" aria-current="page">
              {category.translated?.name || category.name}
            </span>
          </>
        )}
      </nav>

      {/* Category Header */}
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-surface-900">
          {category ? category.translated?.name || category.name : 'Category'}
        </h1>
        {category?.description && (
          <p
            className="text-surface-500 mt-2 max-w-2xl"
            dangerouslySetInnerHTML={{ __html: category.description }}
          />
        )}
      </div>

      {/* Subcategory Chips */}
      {childCategories.length > 0 && (
        <div className="flex flex-wrap gap-2 mb-6" role="list" aria-label="Subcategories">
          {childCategories.map((child) => (
            <Link
              key={child.id}
              href={`${getActiveLocalePrefix()}${getCategoryUrl(child)}`}
              role="listitem"
              className="inline-flex items-center px-4 py-2 text-sm font-medium rounded-full border border-surface-200 text-surface-600 hover:text-brand-600 hover:border-brand-300 hover:bg-brand-50 transition-all"
            >
              {child.translated?.name || child.name}
            </Link>
          ))}
        </div>
      )}

      {/* Sort bar */}
      <Suspense fallback={null}>
        <CategoryControls
          categoryId={categoryId}
          sort={sort}
          page={page}
          totalPages={totalPages}
          total={total}
        />
      </Suspense>

      {/* Sidebar + product grid */}
      <div className="flex flex-col lg:flex-row gap-8 mt-2">
        {/* Filter sidebar */}
        <Suspense fallback={null}>
          <CategoryFilters aggregations={aggregations} />
        </Suspense>

        {/* Products */}
        <div className="flex-1 min-w-0">
          {products.length > 0 ? (
            <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">
              {products.map((product, index) => (
                <div
                  key={product.id}
                  className="animate-slide-up"
                  style={{ animationDelay: `${index * 30}ms` }}
                >
                  <ProductCard product={product} categoryId={categoryId} />
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-20">
              <span className="text-5xl mb-4 block" role="img" aria-label="magnifying glass">🔍</span>
              <p className="text-surface-500 text-lg mb-2">No products found</p>
              <Link href={`/category/${categoryId}`} className="text-brand-600 hover:text-brand-700 font-medium text-sm">
                Clear filters
              </Link>
            </div>
          )}

          {/* Bottom pagination */}
          {totalPages > 1 && (
            <Suspense fallback={null}>
              <CategoryControls
                categoryId={categoryId}
                sort={sort}
                page={page}
                totalPages={totalPages}
                total={total}
              />
            </Suspense>
          )}
        </div>
      </div>
    </div>
  );
}
