import { createFileRoute, Link } from '@tanstack/react-router';
import Breadcrumbs from "@/components/Breadcrumbs";
import RelatedLinks from '@/components/RelatedLinks';
import { getRelatedLinks } from '@/lib/relatedLinks';
import { HelpCircle, ArrowRight, Search } from 'lucide-react';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { motion } from 'framer-motion';
import { useState } from 'react';
import heroFaq from '@/assets/hero-faq.jpg';
import { useT, useLang, headLang, localizePath, SITE_URL, type T } from '@/lib/i18n';

export const Route = createFileRoute('/veelgestelde-vragen')({
  head: (ctx) => {
    const lang = headLang(ctx);
    const path = localizePath('/veelgestelde-vragen', lang);
    const title = lang === 'en' ? 'FAQ — Peptidewinkel | Answers about peptides, ordering & shipping' : 'FAQ — Peptidewinkel | Antwoorden over peptides, bestellen & verzending';
    const description = lang === 'en'
      ? 'Frequently asked questions about Peptidewinkel: ordering, payment, shipping, reconstitution, storage, lab reports and research-only policy.'
      : 'Veelgestelde vragen over Peptidewinkel: bestellen, betaling, verzending, reconstitutie, opslag, labrapporten en research-only beleid.';
    const ogTitle = lang === 'en' ? 'FAQ — Peptidewinkel' : 'FAQ — Peptidewinkel';
    const ogDescription = lang === 'en' ? 'Answers to the most common questions about our peptides and service.' : 'Antwoorden op de meest gestelde vragen over onze peptides en service.';
    return {
      meta: [
        { title },
        { name: 'description', content: description },
        { property: 'og:title', content: ogTitle },
        { property: 'og:description', content: ogDescription },
        { property: 'og:url', content: `${SITE_URL}${path}` },
      ],
      links: [{ rel: 'canonical', href: `${SITE_URL}${path}` }],
    };
  },
  component: FAQPage,
});

const fadeUp = {
  initial: { opacity: 0, y: 30 },
  whileInView: { opacity: 1, y: 0 },
  viewport: { once: true, margin: '-50px' },
};

function getFaqSections(t: T) {
  return [
    {
      title: t('Over Peptidewinkel', 'About Peptidewinkel'),
      items: [
        { q: t('Wat is Peptidewinkel?', 'What is Peptidewinkel?'), a: t('Peptidewinkel is een Europese leverancier van research-grade peptides. Wij leveren peptiden van fabrikant Alpha BioPharma, getest door het externe lab Janoshik, voor onderzoeksdoeleinden, verzonden vanuit en binnen de EU via peptidewinkel.com.', 'Peptidewinkel is a European supplier of research-grade peptides. We supply peptides from manufacturer Alpha BioPharma, tested by the independent lab Janoshik, for research purposes, shipped from and within the EU via peptidewinkel.com.') },
        { q: t('Zijn jullie peptides bedoeld voor menselijke consumptie?', 'Are your peptides intended for human consumption?'), a: t('Nee. Onze peptides worden uitsluitend geleverd voor onderzoeksdoeleinden (research only) en zijn niet bestemd voor menselijke of dierlijke consumptie. Lees altijd de bijbehorende documentatie.', 'No. Our peptides are supplied exclusively for research purposes (research only) and are not intended for human or animal consumption. Always read the accompanying documentation.') },
        { q: t('Welke peptides voeren jullie?', 'Which peptides do you carry?'), a: t('Onze focus ligt op healing & recovery (BPC-157, TB-500, GHK-Cu), growth peptides (CJC-1295, Ipamorelin, MK-677, Tesamorelin), fat loss (Semaglutide, Tirzepatide, Retatrutide, AOD-9604), cognitive (Selank, Semax, Cerebrolysin), sexual health (PT-141) en research supplies.', 'Our focus is on healing & recovery (BPC-157, TB-500, GHK-Cu), growth peptides (CJC-1295, Ipamorelin, MK-677, Tesamorelin), fat loss (Semaglutide, Tirzepatide, Retatrutide, AOD-9604), cognitive (Selank, Semax, Cerebrolysin), sexual health (PT-141) and research supplies.') },
      ],
    },
    {
      title: t('Kwaliteit & labtesten', 'Quality & lab tests'),
      items: [
        { q: t('Hoe weet ik dat een peptide zuiver is?', 'How do I know a peptide is pure?'), a: t('Al onze producten komen van fabrikant Alpha BioPharma. Batches worden getest door het externe lab Janoshik Analytical (in opdracht van de fabrikant). Op onze pagina Labtesten staat per rapport het product, de testdatum, het resultaat en een link naar het originele rapport op janoshik.com.', 'All our products come from manufacturer Alpha BioPharma. Batches are tested by the independent lab Janoshik Analytical (commissioned by the manufacturer). Our Lab Tests page shows the product, test date, result and a link to the original report on janoshik.com for every report.') },
        { q: t('Welke zuiverheid hanteren jullie?', 'What purity do you maintain?'), a: t('Wij streven naar een zuiverheid van ≥ 99%. De meeste geteste batches halen dat; enkele liggen iets lager (bijvoorbeeld rond 96–98%). We zijn daar open over: de exacte waarde die Janoshik heeft gemeten staat per rapport op onze pagina Labtesten.', 'We aim for a purity of ≥ 99%. Most tested batches achieve this; a few are slightly lower (for example around 96–98%). We are transparent about this: the exact value measured by Janoshik is shown per report on our Lab Tests page.') },
        { q: t('Hoe worden de vials verpakt?', 'How are the vials packaged?'), a: t('Gelyofiliseerde peptiden worden afgevuld in farmaceutisch glaswerk onder argon en met butyl rubber stoppers, om degradatie te voorkomen.', 'Lyophilised peptides are filled into pharmaceutical glassware under argon and sealed with butyl rubber stoppers to prevent degradation.') },
      ],
    },
    {
      title: t('Bestellen & betalen', 'Ordering & payment'),
      items: [
        { q: t('Hoe kan ik betalen?', 'How can I pay?'), a: t('iDEAL, Bancontact, creditcard via een beveiligd betaalplatform, en cryptocurrency (USDT, USDC, BTC, ETH). Bankoverschrijving is op aanvraag mogelijk.', 'iDEAL, Bancontact, credit card via a secure payment platform, and cryptocurrency (USDT, USDC, BTC, ETH). Bank transfer is possible on request.') },
        { q: t('Heb ik een account nodig?', 'Do I need an account?'), a: t('Nee, je kunt als gast bestellen. Een account geeft toegang tot bestelhistorie, sneller afrekenen en het loyaltyprogramma.', 'No, you can order as a guest. An account gives access to order history, faster checkout and the loyalty programme.') },
        { q: t('Verschijnt mijn bestelling herkenbaar op mijn afschrift?', 'Will my order appear recognisably on my statement?'), a: t('Nee. Betalingen verschijnen onder een neutrale, niet-herkenbare omschrijving.', 'No. Payments appear under a neutral, unrecognisable description.') },
        { q: t('Is er een minimale bestelwaarde?', 'Is there a minimum order value?'), a: t('Nee. Bestellingen vanaf €150 worden gratis verzonden binnen de EU.', 'No. Orders from €150 are shipped free of charge within the EU.') },
      ],
    },
    {
      title: t('Verzending & levertijd', 'Shipping & delivery time'),
      items: [
        { q: t('Vanuit waar verzenden jullie?', 'Where do you ship from?'), a: t('Uitsluitend vanuit de Europese Unie naar EU-landen. Geen douane, geen import-loterij.', 'Exclusively from the European Union to EU countries. No customs, no import lottery.') },
        { q: t('Wat zijn de levertijden?', 'What are the delivery times?'), a: t('Nederland 1-2 werkdagen, België/Duitsland 2-3 werkdagen, overige EU 3-5 werkdagen. Bestellingen vóór 12:00 op werkdagen worden dezelfde dag verzonden.', 'Netherlands 1-2 business days, Belgium/Germany 2-3 business days, rest of EU 3-5 business days. Orders placed before 12:00 on business days are shipped the same day.') },
        { q: t('Is de verpakking discreet?', 'Is the packaging discreet?'), a: t("Ja, 100%. Neutrale buitenverpakking zonder productnamen, logo's of verwijzingen naar de inhoud.", "Yes, 100%. Neutral outer packaging without product names, logos or references to the contents.") },
        { q: t('Verzenden jullie gekoeld?', 'Do you ship refrigerated?'), a: t('Voor temperatuurgevoelige peptiden (bijv. GLP-1 analogen) bieden wij een gekoelde transit-optie tijdens checkout.', 'For temperature-sensitive peptides (e.g. GLP-1 analogues) we offer a refrigerated transit option during checkout.') },
        { q: t('Krijg ik een track & trace?', 'Do I get a track & trace code?'), a: t('Ja, na verzending ontvang je per e-mail een track & trace-code.', 'Yes, after shipping you will receive a track & trace code by email.') },
      ],
    },
    {
      title: t('Reconstitutie & opslag', 'Reconstitution & storage'),
      items: [
        { q: t('Hoe reconstitueer ik een peptide?', 'How do I reconstitute a peptide?'), a: t('Gebruik bacteriostatisch water (BAC water) of steriel water. Per product geven wij de aanbevolen oplosverhouding mee. Gebruik onze Peptide Calculator om eenheden per insuline-spuit te berekenen.', 'Use bacteriostatic water (BAC water) or sterile water. We provide the recommended dilution ratio per product. Use our Peptide Calculator to calculate units per insulin syringe.') },
        { q: t('Hoe bewaar ik gelyofiliseerde peptiden?', 'How do I store lyophilised peptides?'), a: t('Onaangebroken (gevriesdroogd) kun je peptiden bewaren op kamertemperatuur in een afgesloten kast, uit direct licht en zonder grote temperatuurschommelingen. Onder die condities is de houdbaarheid 24+ maanden. Koeling is pas nodig na reconstitutie.', 'Unopened (freeze-dried), peptides can be stored at room temperature in a closed cabinet, away from direct light and without large temperature fluctuations. Under these conditions the shelf life is 24+ months. Refrigeration is only needed after reconstitution.') },
        { q: t('Hoe lang blijft een gereconstitueerde peptide bruikbaar?', 'How long does a reconstituted peptide remain usable?'), a: t('Na reconstitutie met bacteriostatisch water bewaar je het flesje in de koelkast (2–8 °C) en gebruik je het bij voorkeur binnen 30 dagen. Per peptide kunnen wij dit nader specificeren — neem contact op voor exacte richtlijnen.', 'After reconstitution with bacteriostatic water, store the vial in the refrigerator (2–8 °C) and preferably use it within 30 days. We can specify this further per peptide — contact us for exact guidelines.') },
      ],
    },
    {
      title: t('Retour & garantie', 'Returns & guarantee'),
      items: [
        { q: t('Kan ik een peptide retourneren?', 'Can I return a peptide?'), a: t('Wegens de aard van het product (research-grade, koudegevoelig) is retourneren in principe niet mogelijk. Ongeopende en ongekoelde producten kunnen binnen 14 dagen na overleg geretourneerd worden.', 'Due to the nature of the product (research-grade, cold-sensitive) returns are in principle not possible. Unopened and unrefrigerated products can be returned within 14 days after consultation.') },
        { q: t('Wat als mijn pakket beschadigd aankomt?', 'What if my package arrives damaged?'), a: t("Maak foto's van de verpakking en inhoud en stuur deze binnen 48 uur naar info@peptidewinkel.com. Wij regelen vervanging of terugbetaling.", 'Take photos of the packaging and contents and send them to info@peptidewinkel.com within 48 hours. We will arrange a replacement or refund.') },
        { q: t('Wat als mijn bestelling niet aankomt?', 'What if my order does not arrive?'), a: t('Neem contact op met info@peptidewinkel.com. Na onderzoek doen wij kosteloze nazending of terugbetaling.', 'Contact info@peptidewinkel.com. After investigation we will arrange free re-shipment or a refund.') },
      ],
    },
    {
      title: t('Klantenservice', 'Customer service'),
      items: [
        { q: t('Hoe bereik ik jullie?', 'How can I reach you?'), a: t('Het snelst via WhatsApp: +31 970 102 838 89. E-mail (ook voor orders en aftersales): info@peptidewinkel.com, reactie binnen 1–3 werkdagen. Ons Telegram-kanaal is alleen voor updates, niet voor persoonlijke berichten.', 'Fastest via WhatsApp: +31 970 102 838 89. Email (also for orders and after-sales): info@peptidewinkel.com, response within 1–3 business days. Our Telegram channel is for updates only, not for personal messages.') },
        { q: t('Wat is de reactietijd?', 'What is the response time?'), a: t('Telegram: meestal binnen enkele uren. E-mail: binnen 1 werkdag.', 'Telegram: usually within a few hours. Email: within 1 business day.') },
      ],
    },
  ];
}

function FAQPage() {
  const t = useT();
  const lang = useLang();
  const [search, setSearch] = useState('');
  const faqSections = getFaqSections(t);
  const filteredSections = faqSections.map((section) => ({
    ...section,
    items: section.items.filter((item) => item.q.toLowerCase().includes(search.toLowerCase()) || item.a.toLowerCase().includes(search.toLowerCase())),
  })).filter((s) => s.items.length > 0);

  const faqJsonLd = {
    '@context': 'https://schema.org',
    '@type': 'FAQPage',
    mainEntity: faqSections.flatMap((s) => s.items).map((i) => ({
      '@type': 'Question',
      name: i.q,
      acceptedAnswer: { '@type': 'Answer', text: i.a },
    })),
  };

  return (
    <div className="overflow-hidden">
      <Breadcrumbs items={[{ label: t('Veelgestelde vragen', 'Frequently asked questions') }]} />
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(faqJsonLd) }} />
      <section className="relative min-h-[380px] md:min-h-[460px] overflow-hidden">
        <img src={heroFaq} alt={t('Veelgestelde vragen over Peptidewinkel — bestellen, verzending en research peptiden', 'Frequently asked questions about Peptidewinkel — ordering, shipping and research peptides')} width={1920} height={1080} loading="eager" decoding="async" className="absolute inset-0 w-full h-full object-cover" />
        <div className="absolute inset-0 bg-gradient-to-r from-black/85 via-black/70 to-black/40" />
        <div className="absolute inset-0 bg-molecule-grid opacity-40" />
        <div className="container relative z-10 text-center py-20 md:py-24">
          <motion.div {...fadeUp} transition={{ duration: 0.5 }}>
            <div className="w-16 h-16 mx-auto mb-5 rounded-xl bg-white/10 backdrop-blur-sm flex items-center justify-center border border-white/20">
              <HelpCircle className="w-8 h-8 text-primary" />
            </div>
          </motion.div>
          <motion.h1 {...fadeUp} transition={{ duration: 0.6, delay: 0.1 }} className="text-4xl md:text-6xl font-display font-extrabold text-white mb-5 tracking-tight">
            {t('Veelgestelde', 'Frequently asked')} <span className="text-gradient-primary">{t('vragen', 'questions')}</span>
          </motion.h1>
          <motion.p {...fadeUp} transition={{ duration: 0.6, delay: 0.2 }} className="text-white/75 max-w-xl mx-auto text-lg leading-relaxed mb-8">
            {t('Antwoorden op vragen over peptides, kwaliteit, bestellen en verzending. Staat je vraag er niet tussen? Neem contact op.', "Answers to questions about peptides, quality, ordering and shipping. Can't find your question? Get in touch.")}
          </motion.p>
          <motion.div {...fadeUp} transition={{ duration: 0.5, delay: 0.3 }} className="max-w-md mx-auto relative">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-white/60" />
            <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder={t('Zoek in FAQ...', 'Search FAQ...')} className="w-full pl-11 pr-4 py-3.5 rounded-md bg-white/10 text-white placeholder:text-white/60 border border-white/20 text-sm focus:ring-2 focus:ring-primary/40 outline-none backdrop-blur-sm" />
          </motion.div>
        </div>
      </section>

      <section className="container py-16 max-w-3xl">
        <div className="space-y-10">
          {filteredSections.map((section, si) => (
            <motion.div key={section.title} {...fadeUp} transition={{ duration: 0.5, delay: si * 0.05 }}>
              <h2 className="text-xl font-display font-bold mb-4 flex items-center gap-2 clinical-rule">
                <span className="w-8 h-8 rounded-md gradient-primary flex items-center justify-center text-white text-xs font-bold shadow-glow-soft">{si + 1}</span>
                {section.title}
              </h2>
              <Accordion type="single" collapsible className="space-y-2">
                {section.items.map((item, i) => (
                  <AccordionItem key={i} value={`${section.title}-${i}`} className="border border-border rounded-md px-5 bg-card hover:border-primary/40 transition-colors">
                    <AccordionTrigger className="text-sm font-medium text-left hover:no-underline">{item.q}</AccordionTrigger>
                    <AccordionContent className="text-sm text-muted-foreground leading-relaxed">{item.a}</AccordionContent>
                  </AccordionItem>
                ))}
              </Accordion>
            </motion.div>
          ))}
          {filteredSections.length === 0 && (
            <div className="text-center py-12">
              <p className="text-muted-foreground">{t('Geen resultaten gevonden voor', 'No results found for')} "{search}"</p>
            </div>
          )}
        </div>
      </section>

      <section className="container pb-20">
        <motion.div {...fadeUp} transition={{ duration: 0.6 }} className="gradient-clinical rounded-2xl p-10 md:p-16 text-center relative overflow-hidden border border-border">
          <div className="absolute inset-0 bg-molecule-grid opacity-30" />
          <div className="relative z-10">
            <h2 className="text-3xl md:text-4xl font-display font-extrabold text-white mb-4">{t('Nog vragen?', 'Still have questions?')}</h2>
            <p className="text-white/70 mb-8 max-w-md mx-auto text-lg">{t('Ons team staat klaar via e-mail of Telegram.', 'Our team is ready to help via email or Telegram.')}</p>
            <Link to="/contact-us" className="group inline-flex items-center gap-2.5 gradient-primary text-white font-bold px-8 py-4 rounded-md hover:shadow-gold transition-all duration-300 text-sm uppercase tracking-wide">
              {t('Neem contact op', 'Get in touch')} <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
            </Link>
          </div>
        </motion.div>
      </section>

      <RelatedLinks title={t("Gerelateerde pagina's", 'Related pages')} subtitle={t('Vind snel meer informatie over onze peptides, kwaliteit en service.', 'Quickly find more information about our peptides, quality and service.')} links={getRelatedLinks('faq', lang)} />
    </div>
  );
}
