import { createFileRoute } from '@tanstack/react-router';
import ProductsListing from '@/components/ProductsListing';
import {
  categoriesQueryOptions,
  productsQueryOptions,
  SHOP_DEFAULT_PRODUCTS_PARAMS,
} from '@/hooks/useWooCommerce';
import { breadcrumbSchema, collectionSchema } from '@/lib/schemas';
import { categories as mockCategories } from '@/data/mockProducts';
import { assertCached } from '@/lib/assertCached';
import { getCategorySeo } from '@/data/categorySeo';
import { headLang, makeT, localizePath, SITE_URL } from '@/lib/i18n';

export const Route = createFileRoute('/product-category/$slug')({
  loader: async ({ params, context }) => {
    const catsOpts = categoriesQueryOptions();
    await context.queryClient.ensureQueryData(catsOpts);
    const all = assertCached<Awaited<ReturnType<typeof catsOpts.queryFn>>>(
      context.queryClient,
      catsOpts.queryKey,
      'categories',
    );
    const match =
      all?.find((c) => c.slug === params.slug || c.slugEn === params.slug) ||
      mockCategories.find((c) => c.slug === params.slug);

    // Prime the default product grid for this category. Must be awaited so
    // the resolved data is included in the dehydrated cache shipped to the
    // client — otherwise SSR renders with data but hydration falls back to
    // mock data, causing a hydration mismatch.
    let products: Awaited<ReturnType<ReturnType<typeof productsQueryOptions>['queryFn']>>['products'] = [];
    if (match?.id) {
      const prodOpts = productsQueryOptions({
        ...SHOP_DEFAULT_PRODUCTS_PARAMS,
        category: match.id,
      });
      const res = await context.queryClient.ensureQueryData(prodOpts);
      assertCached(context.queryClient, prodOpts.queryKey, `products[cat=${match.id}]`);
      products = res?.products ?? [];
    }

    return { categoryName: match?.name ?? params.slug, categorySlug: match?.slug ?? params.slug, products };
  },
  head: (ctx) => {
    const { params, loaderData } = ctx;
    const lang = headLang(ctx);
    const t = makeT(lang);
    const nlSlug = loaderData?.categorySlug ?? params.slug;
    const seo = getCategorySeo(nlSlug, lang);
    const name = seo?.heading ?? loaderData?.categoryName ?? params.slug;
    const title = seo?.metaTitle ?? t(`${name} Kopen | Peptidewinkel`, `Buy ${name} | Peptidewinkel`);
    const description =
      seo?.metaDescription ??
      t(
        `Bekijk onze catalogus — research-grade peptiden, lab-getest en discreet verzonden door Peptidewinkel.`,
        `Browse our catalog — research-grade peptides, lab-tested and shipped discreetly by Peptidewinkel.`,
      );
    const path = `/product-category/${nlSlug}`;
    const url = `${SITE_URL}${localizePath(path, lang)}`;
    return {
      meta: [
        { title },
        { name: 'description', content: description },
        ...(seo?.keywords?.length ? [{ name: 'keywords', content: seo.keywords.join(', ') }] : []),
        { property: 'og:title', content: title },
        { property: 'og:description', content: description },
        { property: 'og:type', content: 'website' },
        { property: 'og:url', content: url },
        { property: 'og:site_name', content: 'Peptidewinkel' },
        { property: 'og:locale', content: lang === 'en' ? 'en_US' : 'nl_NL' },
        { name: 'twitter:card', content: 'summary_large_image' },
        { name: 'twitter:title', content: title },
        { name: 'twitter:description', content: description },
      ],
      links: [
        { rel: 'canonical', href: url },
        { rel: 'alternate', hrefLang: 'nl-NL', href: `${SITE_URL}${path}` },
        { rel: 'alternate', hrefLang: 'en', href: `${SITE_URL}${localizePath(path, 'en')}` },
        { rel: 'alternate', hrefLang: 'x-default', href: `${SITE_URL}${path}` },
      ],
      scripts: [
        ...collectionSchema(name, path, loaderData?.products ?? [], description, lang).map((s) => ({
          type: 'application/ld+json',
          children: JSON.stringify(s),
        })),
        {
          type: 'application/ld+json',
          children: JSON.stringify(
            breadcrumbSchema([
              { name: t('Home', 'Home'), url: '/' },
              { name: t('Webshop', 'Shop'), url: '/shop' },
              { name, url: path },
            ]),
          ),
        },
      ],
    };
  },
  component: CategoryPage,
});

function CategoryPage() {
  const { slug } = Route.useParams();
  return <ProductsListing categorySlugFromRoute={slug} />;
}
