import { createFileRoute, Link, notFound } from '@tanstack/react-router';
import { ArrowLeft, Calendar } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import { useBlogPost } from '@/hooks/useWooCommerce';
import Breadcrumbs from '@/components/Breadcrumbs';
import { sanitizedHtml } from '@/lib/sanitize';
import { wp } from '@/lib/woocommerce';
import { articleSchema } from '@/lib/schemas';
import { useT, useLang, locale, headLang, localizePath, SITE_URL } from '@/lib/i18n';

function humanizeSlug(slug: string): string {
  return slug
    .split('-')
    .filter(Boolean)
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(' ');
}

function stripHtml(html?: string): string {
  return (html || '')
    .replace(/<[^>]*>/g, '')
    .replace(/&nbsp;/g, ' ')
    .replace(/&amp;/g, '&')
    .replace(/&#8217;/g, "'")
    .replace(/\s+/g, ' ')
    .trim();
}

export const Route = createFileRoute('/blog/$slug')({
  loader: async ({ params }) => {
    try {
      const { data } = await wp.getPost(params.slug);
      return {
        title: stripHtml(data.title?.rendered) || humanizeSlug(params.slug),
        excerpt: stripHtml(data.excerpt?.rendered).slice(0, 160),
        date: data.date as string,
        image: data._embedded?.['wp:featuredmedia']?.[0]?.source_url as string | undefined,
      };
    } catch {
      // Unknown post (e.g. a literal "/blog/$slug" a crawler picked up): real 404, not an indexable empty page.
      throw notFound();
    }
  },
  head: (ctx) => {
    const { params, loaderData } = ctx;
    const lang = headLang(ctx);
    const title = loaderData?.title || humanizeSlug(params.slug);
    const description =
      loaderData?.excerpt ||
      `${title} — artikel op de Peptidewinkel blog. Lees onze gids over peptides, dosering en research.`;
    const url = `${SITE_URL}${localizePath(`/blog/${params.slug}`, lang)}`;
    const image = loaderData?.image;
    return {
      meta: [
        { title: `${title} | Blog Peptidewinkel` },
        { name: 'description', content: description },
        { property: 'og:title', content: `${title} | Blog Peptidewinkel` },
        { property: 'og:description', content: description },
        { property: 'og:url', content: url },
        { property: 'og:type', content: 'article' },
        ...(image
          ? [
              { property: 'og:image', content: image },
              { name: 'twitter:image', content: image },
            ]
          : []),
      ],
      links: [{ rel: 'canonical', href: url }],
      scripts: [{
        type: 'application/ld+json',
        children: JSON.stringify(
          articleSchema({
            title,
            slug: params.slug,
            excerpt: description,
            date: loaderData?.date || new Date().toISOString(),
            image,
          }),
        ),
      }],
    };
  },
  component: BlogPostPage,
});

function BlogPostPage() {
  const t = useT();
  const lang = useLang();
  const { slug } = Route.useParams();
  // The loader already resolved the post title server-side, so the breadcrumb
  // bar can render immediately with the article name — before the client query
  // for the full body finishes. That keeps the bar in the same place as on
  // every other page instead of appearing only after hydration.
  const { title: loaderTitle } = Route.useLoaderData();
  const { data: wpPost, isLoading } = useBlogPost(slug);
  const post = wpPost?.data;

  const crumbs = (
    <Breadcrumbs
      items={[
        { label: t('Blog', 'Blog'), to: '/blog' },
        { label: loaderTitle || humanizeSlug(slug) },
      ]}
    />
  );

  if (isLoading) {
    return (
      <>
        {crumbs}
        <div className="container py-12 max-w-4xl">
          <Skeleton className="h-10 w-3/4 mb-4" />
          <Skeleton className="aspect-video rounded-2xl mb-8" />
          <Skeleton className="h-96 w-full" />
        </div>
      </>
    );
  }

  if (!post) {
    return (
      <>
        {crumbs}
        <div className="container py-16 text-center">
          <h1 className="text-2xl font-bold mb-2">{t('Artikel niet gevonden', 'Article not found')}</h1>
          <Link to="/blog" className="text-primary hover:underline">{t('Terug naar blog', 'Back to blog')}</Link>
        </div>
      </>
    );
  }

  const featuredImg = post._embedded?.['wp:featuredmedia']?.[0]?.source_url;
  const dateStr = new Date(post.date).toLocaleDateString(locale(lang), { day: 'numeric', month: 'long', year: 'numeric' });

  return (
    <>
      {/* The same bar as the rest of the site (see components/Breadcrumbs). */}
      {crumbs}
      <article className="container py-12 max-w-4xl">
      <Link to="/blog" className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-primary mb-6">
        <ArrowLeft className="w-4 h-4" /> {t('Terug naar blog', 'Back to blog')}
      </Link>
      {featuredImg && <img src={featuredImg} alt={post?.title?.rendered ? `${t('Uitgelichte afbeelding:', 'Featured image:')} ${post.title.rendered}` : t('Uitgelichte blog afbeelding — Peptidewinkel', 'Featured blog image — Peptidewinkel')} width={1200} height={675} loading="eager" decoding="async" className="aspect-video w-full object-cover rounded-2xl mb-8" />}
      <div className="flex items-center gap-3 mb-4 text-sm text-muted-foreground">
        <Calendar className="w-3.5 h-3.5" /> {dateStr}
      </div>
      <h1 className="text-2xl md:text-4xl font-extrabold leading-tight mb-8" dangerouslySetInnerHTML={sanitizedHtml(post.title.rendered)} />
      <div className="prose prose-lg max-w-none wc-content 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 prose-h4:text-base md:prose-h4:text-lg" dangerouslySetInnerHTML={sanitizedHtml(post.content.rendered)} />
      <nav aria-label={t('Verder op Peptidewinkel', 'More on Peptidewinkel')} className="mt-12 border-t border-border pt-8">
        <h2 className="text-xl font-bold mb-4">{t('Verder op Peptidewinkel', 'More on Peptidewinkel')}</h2>
        <ul className="grid sm:grid-cols-2 gap-3 text-sm">
          <li><Link to="/shop" className="block rounded-xl border border-border p-4 hover:border-primary transition-colors"><strong>{t('Alle peptiden', 'All peptides')}</strong><br /><span className="text-muted-foreground">{t('Bekijk het volledige assortiment.', 'Browse the full range.')}</span></Link></li>
          <li><Link to="/labtesten" className="block rounded-xl border border-border p-4 hover:border-primary transition-colors"><strong>{t('Labresultaten', 'Lab results')}</strong><br /><span className="text-muted-foreground">{t('Gemeten zuiverheid per batch.', 'Measured purity per batch.')}</span></Link></li>
          <li><Link to="/peptide-calculator" className="block rounded-xl border border-border p-4 hover:border-primary transition-colors"><strong>{t('Peptide calculator', 'Peptide calculator')}</strong><br /><span className="text-muted-foreground">{t('Reken reconstitutie en dosering uit.', 'Calculate reconstitution and dosage.')}</span></Link></li>
          <li><Link to="/blog" className="block rounded-xl border border-border p-4 hover:border-primary transition-colors"><strong>{t('Meer artikelen', 'More articles')}</strong><br /><span className="text-muted-foreground">{t('Alle blogs en kennisartikelen.', 'All blogs and knowledge articles.')}</span></Link></li>
        </ul>
      </nav>
    </article>
    </>
  );
}
