import { createFileRoute, notFound, redirect, Link } from '@tanstack/react-router';
import { useT, headLang, langFromPath, localizePath, SITE_URL } from '@/lib/i18n';
import { sanitizedHtml } from '@/lib/sanitize';
import { getEditorialPage } from '@/lib/content.functions';
import PageBlocks from '@/components/blocks/PageBlocks';

/**
 * Catch-all for paths not matched by any other route.
 *
 * Three responsibilities:
 *  1. 301-redirect legacy WordPress blog posts that lived at the root path
 *     (e.g. `/testosterone-enanthate-...`) to the new `/blog/{slug}` URL.
 *     The slug list is the published-post inventory from the Yoast sitemap
 *     at migration time; new posts are added via the WP back office and
 *     served directly at `/blog/{slug}` from day one.
 *  2. Render an editorial page from the backend (content_pages, managed in
 *     /admin) when one exists for this slug, so pages published in the panel are
 *     reachable without a route of their own in this codebase.
 *  3. Render a proper 404 for anything else, instead of a soft 404.
 */

// Published post slugs that historically lived at root on peptidewinkel.com.
// Source: https://peptidewinkel.com/post-sitemap.xml (2026-05-22).
const LEGACY_BLOG_SLUGS = new Set<string>([
  'testosterone-enanthate-de-voordelen-voor-mannen',
  'ozempic-kopen-wat-je-moet-weten-over-dit-populaire-medicijn-tegen-diabetes-en-gewichtsbeheersing',
  'wat-is-genotropin-hgh-van-pfizer-en-waarom-wordt-het-gebruikt',
  'erectiemiddelen-kopen',
  'tren-kopen-de-ultieme-gids-voor-trenbolone-gebruik-dosering-en-bijwerkingen',
  'tb-500-kopen-een-complete-gids-over-dit-regeneratieve-peptide',
  'bpc-157-kopen-een-complete-gids-over-dit-krachtige-peptide',
  'pt141-kopen-het-complete-overzicht-van-dit-krachtige-libido-boostend-peptide',
  'peptidewinkel-stapt-over-naar-alpha-biopharma',
  'kristallisatie-testosteron-testosteron-enanthate-cypionate-uitgelegd',
  'ons-nieuwe-betaalsysteem-is-hier-exclusief-voor-premium-klanten',
]);

export const Route = createFileRoute('/$')({
  beforeLoad: ({ params }) => {
    const splat = (params as { _splat?: string })._splat ?? '';
    // Normalize: strip leading/trailing slashes, ignore deeper paths.
    const slug = splat.replace(/^\/+|\/+$/g, '').split('/')[0];
    if (slug && LEGACY_BLOG_SLUGS.has(slug)) {
      throw redirect({ to: '/blog/$slug', params: { slug } });
    }
  },
  loader: async ({ params, location }) => {
    const slug = requestedSlug(params);

    // Unknown or non editorial-looking paths skip the lookup entirely and become a
    // real 404 (not a soft one): that also means an endpoint or page that was
    // removed does not keep answering 200.
    if (slug === null) {
      throw notFound();
    }

    const lang = langFromPath(new URL(location.publicHref, SITE_URL).pathname);
    const page = await getEditorialPage({ data: { slug, lang } });

    if (! page) {
      throw notFound();
    }

    return { page };
  },
  head: (ctx) => {
    const lang = headLang(ctx);
    const page = ctx.loaderData?.page ?? null;

    if (page) {
      const title = page.metaTitle || page.title;
      const description = page.metaDescription ?? '';
      const url = `${SITE_URL}${localizePath(`/${page.slug}`, lang)}`;

      return {
        meta: [
          { title: `${title} | Peptidewinkel` },
          ...(description ? [{ name: 'description', content: description }] : []),
          { property: 'og:title', content: `${title} | Peptidewinkel` },
          ...(description ? [{ property: 'og:description', content: description }] : []),
          { property: 'og:url', content: url },
          { property: 'og:type', content: 'website' },
          ...(page.image ? [{ property: 'og:image', content: `${SITE_URL}${page.image.url}` }] : []),
        ],
        links: [
          { rel: 'canonical', href: url },
          { rel: 'alternate', hrefLang: 'nl', href: `${SITE_URL}/${page.slug}` },
          { rel: 'alternate', hrefLang: 'en', href: `${SITE_URL}/en/${page.slug}` },
        ],
      };
    }

    return { meta: [{ name: 'robots', content: 'noindex' }, { title: lang === 'en' ? 'Page not found | Peptidewinkel' : 'Pagina niet gevonden | Peptidewinkel' }] };
  },
  component: CatchAllPage,
});

/**
 * The slug from the URL, or null when this request is not a single clean
 * segment. Paths like `/wp-login.php` or `/en/shop/x` never get a lookup.
 */
function requestedSlug(params: unknown): string | null {
  const splat = (params as { _splat?: string })._splat ?? '';
  const path = splat.replace(/^\/+|\/+$/g, '');

  if (path === '' || path.includes('/')) return null;

  return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(path) ? path : null;
}

function CatchAllPage() {
  const { page } = Route.useLoaderData();

  if (!page) return <NotFoundPage />;

  // A page built in the panel brings its own sections; the rich-text body is the
  // fallback for pages that have no blocks.
  if (page.blocks.length > 0) {
    return <PageBlocks blocks={page.blocks} />;
  }

  return (
    <article className="container py-12 max-w-4xl">
      {page.image && (
        <img
          src={page.image.url}
          alt={page.image.alt || page.title}
          width={page.image.width ?? 1200}
          height={page.image.height ?? 630}
          loading="eager"
          decoding="async"
          className="aspect-video w-full object-cover rounded-2xl mb-8"
        />
      )}
      <h1 className="text-2xl md:text-4xl font-extrabold leading-tight mb-8">{page.title}</h1>
      <div
        className="prose prose-lg max-w-none prose-headings:font-bold prose-headings:leading-snug prose-h2:text-xl md:prose-h2:text-2xl prose-h2:mt-10 prose-h3:text-lg md:prose-h3:text-xl"
        dangerouslySetInnerHTML={sanitizedHtml(page.body)}
      />
    </article>
  );
}

function NotFoundPage() {
  const t = useT();
  return (
    <div className="container py-20 text-center">
      <h1 className="text-4xl font-black mb-4">{t('404 — Pagina niet gevonden', '404 — Page not found')}</h1>
      <p className="text-muted-foreground mb-8">{t('Deze pagina bestaat niet (meer).', 'This page does not (or no longer) exist.')}</p>
      <Link to="/" className="text-primary font-semibold hover:underline mr-6">{t('Naar homepage', 'Go to homepage')}</Link>
      <Link to="/shop" className="text-primary font-semibold hover:underline">{t('Naar shop', 'Go to shop')}</Link>
    </div>
  );
}
