"use client";

import { useState } from 'react';
import { ArrowLeft, ArrowRight, CheckCircle2, ExternalLink, MapPin, ThermometerSun } from 'lucide-react';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import StickyMobileCTA from '@/components/StickyMobileCTA';
import { Badge } from '@/components/ui/badge';
import { getDetailedReferenceBySlug, type CustomerReference } from '@/data/references';

const getYoutubeId = (url: string) => {
  const match = url.match(/(?:watch\?v=|embed\/|youtu\.be\/)([^&?/]+)/);
  return match?.[1];
};

const getEmbedUrl = (url: string) => {
  const videoId = getYoutubeId(url);
  return videoId ? `https://www.youtube.com/embed/${videoId}` : url;
};

const ReferenceDetail = ({
  slug,
  reference: referenceProp,
}: {
  slug?: string;
  reference?: CustomerReference;
}) => {
  const reference = referenceProp ?? getDetailedReferenceBySlug(slug);
  const [imageFailed, setImageFailed] = useState(false);
  const hasImage = Boolean(reference?.image) && !imageFailed;
  const firstVideo = reference?.videoUrls?.[0];

  // Le 404 est géré en amont par app/references/[slug]/page.tsx via notFound().
  if (!reference) return null;

  const heroFallbackSubline = ['Cool roof', reference.sector, reference.location]
    .filter(Boolean)
    .join(' · ');

  const heroVisual = hasImage ? (
    <figure className="overflow-hidden rounded-lg border border-white/10 bg-white/[0.04] shadow-[0_24px_90px_rgba(0,0,0,0.24)]">
      <img
        src={reference.image}
        alt={reference.title}
        className="aspect-[16/11] w-full object-cover"
        loading="eager"
        decoding="async"
        onError={() => setImageFailed(true)}
      />
    </figure>
  ) : (
    <div className="flex aspect-[16/11] flex-col justify-between rounded-lg border border-white/10 bg-gradient-to-br from-navy-light to-navy p-8 shadow-[0_24px_90px_rgba(0,0,0,0.24)]">
      <ThermometerSun className="h-10 w-10 text-teal-vivid" aria-hidden="true" />
      <div>
        <p className="font-satoshi text-3xl font-black leading-tight tracking-tight text-white md:text-4xl">
          {reference.clientName}
        </p>
        <p className="mt-3 font-body text-sm font-semibold text-white/55">{heroFallbackSubline}</p>
      </div>
    </div>
  );

  const videoEmbed = firstVideo ? (
    <div className="overflow-hidden rounded-lg border border-border bg-navy shadow-[0_18px_70px_rgba(25,42,58,0.14)]">
      <div className="aspect-video">
        <iframe
          title={`Vidéo ${reference.title}`}
          src={getEmbedUrl(firstVideo)}
          className="h-full w-full"
          loading="lazy"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
          referrerPolicy="strict-origin-when-cross-origin"
          allowFullScreen
        />
      </div>
    </div>
  ) : null;

  return (
    <div className="min-h-screen bg-background">
      <Navbar />
      <main>
        <section className="bg-navy pb-14 pt-28 text-white lg:pb-20 lg:pt-32">
          <div className="container mx-auto px-4 lg:px-8">
            <a
              href="/references"
              className="mb-8 inline-flex items-center gap-2 font-body text-sm font-bold text-white/62 transition-colors hover:text-white"
            >
              <ArrowLeft className="h-4 w-4" />
              Retour aux références
            </a>
            <div className="grid gap-10 lg:grid-cols-[1fr_0.78fr] lg:items-center">
              <div>
                <Badge className="mb-5 border-white/12 bg-white/10 text-white">{reference.sector}</Badge>
                <h1 className="max-w-4xl font-satoshi text-4xl font-black leading-tight tracking-tight md:text-6xl">
                  {reference.title}
                </h1>
                <p className="mt-6 max-w-2xl font-body text-lg leading-relaxed text-white/68">
                  {reference.detailIntro ?? reference.description}
                </p>
                <div className="mt-7 flex flex-wrap gap-3 font-body text-sm text-white/58">
                  {reference.location ? (
                    <span className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.06] px-4 py-2">
                      <MapPin className="h-4 w-4 text-teal-vivid" />
                      {reference.location}
                    </span>
                  ) : null}
                  {reference.product ? (
                    <span className="rounded-full border border-white/10 bg-white/[0.06] px-4 py-2">
                      {reference.product}
                    </span>
                  ) : null}
                  {reference.support ? (
                    <span className="rounded-full border border-white/10 bg-white/[0.06] px-4 py-2">
                      {reference.support}
                    </span>
                  ) : null}
                </div>
              </div>
              {heroVisual}
            </div>
          </div>
        </section>

        {videoEmbed ? (
          <section className="bg-white py-14 lg:py-20">
            <div className="container mx-auto px-4 lg:px-8">
              <div className="mb-8 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
                <div>
                  <Badge className="mb-4 bg-teal-light text-primary">Vidéo</Badge>
                  <h2 className="font-satoshi text-3xl font-black tracking-tight text-foreground lg:text-5xl">
                    Le témoignage en images.
                  </h2>
                </div>
                <a
                  href={firstVideo}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-2 font-body text-sm font-bold text-primary"
                >
                  Ouvrir sur YouTube <ExternalLink className="h-4 w-4" />
                </a>
              </div>
              {videoEmbed}
            </div>
          </section>
        ) : null}

        <section className="bg-white py-14 lg:py-20">
          <div className="container mx-auto px-4 lg:px-8">
            <div className="grid gap-5 md:grid-cols-2 lg:grid-cols-4">
              {reference.metrics?.map((metric) => (
                <div key={`${metric.value}-${metric.label}`} className="rounded-lg border border-border bg-[#F6FAFB] p-6">
                  <p className="font-satoshi text-4xl font-black leading-none text-primary">{metric.value}</p>
                  <p className="mt-3 font-body text-sm font-semibold leading-snug text-foreground/62">{metric.label}</p>
                </div>
              ))}
            </div>
          </div>
        </section>

        <section className="bg-background py-16 lg:py-24">
          <div className="container mx-auto px-4 lg:px-8">
            <div className="grid gap-10 lg:grid-cols-[0.8fr_1fr] lg:items-start">
              <aside className="lg:sticky lg:top-28">
                <Badge className="mb-4 bg-teal-light text-primary">Cas client</Badge>
                <h2 className="font-satoshi text-3xl font-black tracking-tight text-foreground lg:text-4xl">
                  Ce que ce chantier démontre.
                </h2>
                {reference.quote ? (
                  <blockquote className="mt-8 rounded-lg border border-border bg-white p-6 shadow-sm">
                    <p className="font-satoshi text-xl font-bold leading-snug text-foreground">“{reference.quote.text}”</p>
                    {reference.quote.author ? (
                      <footer className="mt-4 font-body text-sm text-foreground/55">
                        {reference.quote.author}
                        {reference.quote.role ? ` · ${reference.quote.role}` : ''}
                      </footer>
                    ) : null}
                  </blockquote>
                ) : null}
              </aside>

              <div>
                <ol className="space-y-0">
                  {reference.detailSections?.map((section, index) => {
                    const isLast = index === (reference.detailSections?.length ?? 0) - 1;
                    return (
                      <li key={section.title} className="relative flex gap-5 pb-10 last:pb-0">
                        <div className="flex flex-col items-center">
                          <span className="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-full bg-teal-light font-satoshi text-base font-black text-teal">
                            {String(index + 1).padStart(2, '0')}
                          </span>
                          {!isLast ? <span className="mt-2 w-px flex-1 bg-border" aria-hidden="true" /> : null}
                        </div>
                        <div className="pt-1">
                          <h3 className="font-satoshi text-2xl font-black leading-tight text-foreground">{section.title}</h3>
                          <p className="mt-3 font-body text-base leading-relaxed text-foreground/64">{section.text}</p>
                        </div>
                      </li>
                    );
                  })}
                </ol>

                {reference.videoTakeaways?.length ? (
                  <article className="mt-8 rounded-lg border border-primary/10 bg-navy p-6 text-white shadow-sm lg:p-8">
                    <h3 className="font-satoshi text-2xl font-black leading-tight">
                      En magasin, des résultats mesurés.
                    </h3>
                    {reference.detailNarrative ? (
                      <p className="mt-5 font-body text-base leading-relaxed text-white/70">
                        {reference.detailNarrative}
                      </p>
                    ) : null}
                    <div className="mt-6 grid gap-4 sm:grid-cols-2">
                      {reference.videoTakeaways.map((takeaway) => (
                        <div key={takeaway.label} className="rounded-lg border border-white/10 bg-white/[0.06] p-4">
                          <div className="flex items-start gap-3">
                            <CheckCircle2 className="mt-0.5 h-5 w-5 flex-shrink-0 text-teal-vivid" />
                            <div>
                              <p className="font-body text-sm font-bold text-white">{takeaway.label}</p>
                              <p className="mt-2 font-body text-sm leading-relaxed text-white/66">{takeaway.text}</p>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </article>
                ) : null}
              </div>
            </div>
          </div>
        </section>

        <section className="bg-navy py-16 text-white">
          <div className="container mx-auto px-4 lg:px-8">
            <div className="flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">
              <div>
                <Badge className="mb-4 border-white/12 bg-white/10 text-white">Votre bâtiment</Badge>
                <h2 className="font-satoshi text-3xl font-black tracking-tight lg:text-5xl">
                  Identifiez le potentiel de votre toiture.
                </h2>
                <p className="mt-4 max-w-2xl font-body text-lg leading-relaxed text-white/62">
                  Même secteur, même support ou mêmes contraintes : l’étude permet de vérifier les gains possibles sur votre site.
                </p>
              </div>
              <a href="/diagnostic" className="group inline-flex items-center justify-center gap-2 rounded-full cta-gradient py-2.5 pl-6 pr-2 font-semibold text-white">
                <span className="text-sm">Demander un devis</span>
                <span className="flex h-8 w-8 items-center justify-center rounded-full bg-white/20 transition-transform group-hover:translate-x-0.5">
                  <ArrowRight className="h-4 w-4" />
                </span>
              </a>
            </div>
          </div>
        </section>
      </main>
      <Footer />
      <StickyMobileCTA label="Obtenir un devis" href="/diagnostic" phoneHref="tel:+33238775708" />
    </div>
  );
};

export default ReferenceDetail;
