"use client";

import { useState } from 'react';
import {
  ArrowRight,
  BadgeCheck,
  CalendarClock,
  CalendarCheck,
  Check,
  CheckCircle2,
  ChevronDown,
  ClipboardCheck,
  Factory,
  HelpCircle,
  Play,
  ShieldCheck,
  ShieldAlert,
  Sparkles,
  SunMedium,
  Thermometer,
  TrendingDown,
  Users,
  Wrench,
  type LucideIcon,
} from 'lucide-react';

import Footer from '@/components/Footer';
import Navbar from '@/components/Navbar';
import ScrollReveal from '@/components/ScrollReveal';
import StickyMobileCTA from '@/components/StickyMobileCTA';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import WpImage from '@/components/ui/WpImage';
import type { RoofPageData, TextCard } from '@/data/roofPages';
import coolRoofLayers from '@/assets/cool-roof-layers.webp';
import covaMetalProduct from '@/assets/produits/Covalba-CovaMetal20-Duo-Produit.webp';
import covaSealProduct from '@/assets/produits/Covalba-CovaSeal20-Duo-Produit.webp';
import covaTherm8Product from '@/assets/produits/Covalba-CovaTherm8-Produit.webp';
import covaTherm20Product from '@/assets/produits/Covalba-CovaTherm20-Produit.webp';

interface RoofPageTemplateProps {
  page: RoofPageData;
}

const cardIcons: LucideIcon[] = [SunMedium, Wrench, Factory, ShieldCheck];
const methodIcons: LucideIcon[] = [ClipboardCheck, CalendarClock, ShieldCheck, TrendingDown];
const proofIcons: LucideIcon[] = [Thermometer, ShieldCheck, BadgeCheck];
const problemIcons: LucideIcon[] = [Users, SunMedium, ShieldAlert];

const logos = [
  { name: 'Continental', url: '/logos/logo-continental.svg' },
  { name: 'Thales', url: '/logos/logo-thales.svg' },
  { name: 'Nestlé', url: '/logos/logo-nestle.svg' },
  { name: 'SNCF', url: '/logos/logo-sncf.svg' },
  { name: 'Leclerc', url: '/logos/logo-leclerc.svg' },
  { name: 'Super U', url: '/logos/logo-super-u.svg' },
];

const displayCell = (value: string) => value.replace(/EUR/g, '€').replace(/m2/g, 'm²');

const formatCurrency = (value: number) =>
  `${new Intl.NumberFormat('fr-FR', { maximumFractionDigits: 0 }).format(Math.round(value))} €`;

const parsePricePerM2 = (value: string) => {
  const match = displayCell(value).match(/\(([\d,.]+)\s*€\/m²\)/);
  if (!match) return null;

  return Number.parseFloat(match[1].replace(',', '.'));
};

const getTreatmentRange = (page: RoofPageData, situation: string) => {
  const text = `${page.slug} ${situation}`.toLowerCase();

  if (text.includes('covaseal') || text.includes('vieillissante') || text.includes('fuite')) {
    return { min: 28, max: 38, label: 'CovaSeal 20 estimatif' };
  }

  if (text.includes('covametal') || text.includes('corrosion') || text.includes('tôle')) {
    return { min: 24, max: 32, label: 'CovaMetal 20 estimatif' };
  }

  if (text.includes('fibrociment') || text.includes('plaques')) {
    return { min: 22, max: 28, label: 'CovaTherm support sensible' };
  }

  return { min: 20, max: 25, label: 'CovaTherm estimatif' };
};

const getFallbackPricePerM2 = (option: string, optionIndex: number, treatmentMidpoint: number) => {
  const lower = option.toLowerCase();

  if (optionIndex === 0) return treatmentMidpoint;
  if (lower.includes('anticorrosion simple')) return 16;
  if (lower.includes('remplacement')) return 120;
  if (lower.includes('membrane neuve')) return 90;
  if (lower.includes('isolation')) return 150;

  return null;
};

const benefitImages = [
  '/images/toitures/benefit-confort.webp',
  '/images/toitures/benefit-protection-toiture.webp',
  '/images/toitures/benefit-clim.webp',
  '/images/toitures/benefit-chantier-evite.webp',
];

const feedbackRoofBenefitImages = [
  '/images/toitures/feedback-batiment-tempere.png',
  '/images/toitures/feedback-etancheite.png',
  '/images/toitures/feedback-economie-clim-1.png',
  '/images/toitures/feedback-economie-clim-3.png',
];

const getBenefitImage = (page: RoofPageData, benefit: TextCard, index: number) => {
  if (['membrane-bitumineuse', 'toiture-plate'].includes(page.slug)) {
    return feedbackRoofBenefitImages[index] ?? feedbackRoofBenefitImages[0];
  }

  const text = `${benefit.title} ${benefit.text}`.toLowerCase();

  if (page.slug === 'bac-acier' && (text.includes('tôle') || text.includes('corrosion'))) {
    return '/images/toitures/support-bac-acier-cool.webp';
  }

  if (text.includes('facture') || text.includes('clim') || text.includes('froid')) {
    return '/images/toitures/benefit-clim.webp';
  }

  if (text.includes('chantier') || text.includes('réfection') || text.includes('remplacement') || text.includes('dépose')) {
    return '/images/toitures/benefit-chantier-evite.webp';
  }

  if (text.includes('protég') || text.includes('étanchéité') || text.includes('corrosion') || text.includes('durée')) {
    return '/images/toitures/benefit-protection-toiture.webp';
  }

  return benefitImages[index] ?? benefitImages[0];
};

const supportVisuals: Record<string, { hot: string; cool: string; hotLabel: string; coolLabel: string }> = {
  'membrane-bitumineuse': {
    hot: '/images/toitures/support-bitume-chaud.webp',
    cool: '/images/toitures/feedback-economie-clim-2.png',
    hotLabel: 'Sans cool roof : membrane bitume en absorption',
    coolLabel: 'Avec cool roof : membrane réfléchissante',
  },
  'bac-acier': {
    hot: '/images/toitures/support-bac-acier-chaud.webp',
    cool: '/images/toitures/support-bac-acier-cool.webp',
    hotLabel: 'Sans cool roof : métal en surchauffe',
    coolLabel: 'Avec cool roof : bac acier réfléchi et protégé',
  },
  'toiture-plate': {
    hot: '/images/toitures/support-toiture-plate-chaud.webp',
    cool: '/images/toitures/feedback-economie-clim-2.png',
    hotLabel: 'Sans cool roof : terrasse en absorption',
    coolLabel: 'Avec cool roof : terrasse réfléchissante',
  },
  fibrociment: {
    hot: '/images/toitures/support-fibrociment-chaud.webp',
    cool: '/images/toitures/support-fibrociment-cool.webp',
    hotLabel: 'Sans cool roof : fibrociment en absorption',
    coolLabel: 'Avec cool roof : plaques protégées',
  },
  'tuiles-ciment': {
    hot: '/images/toitures/support-tuiles-ciment-chaud.webp',
    cool: '/images/toitures/support-tuiles-ciment-cool.webp',
    hotLabel: 'Sans cool roof : tuiles qui stockent la chaleur',
    coolLabel: 'Avec cool roof : tuiles réfléchissantes',
  },
};

const layerTitles = ["Primaire d'accroche", 'Résine réfléchissante', 'Vernis de protection'];

const layerColors = [
  {
    pill: 'bg-terracotta text-white',
    dot: 'bg-terracotta',
    chevron: 'text-terracotta',
  },
  {
    pill: 'bg-foreground text-white',
    dot: 'bg-foreground',
    chevron: 'text-foreground',
  },
  {
    pill: 'bg-primary text-white',
    dot: 'bg-primary',
    chevron: 'text-primary',
  },
];

const layerPositions = [
  { top: '56.7%', left: '36.5%' },
  { top: '48.2%', left: '36.5%' },
  { top: '36.3%', left: '35.6%' },
];

const getProblemTitle = (title: string) => {
  const map: Record<string, { strong: string; muted: string }> = {
    "Une toiture bitume noire, c'est un radiateur posé sur votre bâtiment.": {
      strong: 'Votre toiture chauffe.',
      muted: 'Votre bâtiment encaisse.',
    },
    'Le bac acier chauffe vite, rouille vite, et fatigue vite.': {
      strong: 'Le métal chauffe vite.',
      muted: 'La toiture fatigue aussi.',
    },
    'À plat, votre toiture prend le soleil toute la journée.': {
      strong: 'Votre terrasse prend tout.',
      muted: "Chaleur, UV, étanchéité.",
    },
    'Le fibrociment chauffe, vieillit, et coûte cher à déposer.': {
      strong: 'Le fibrociment chauffe.',
      muted: 'Le déposer coûte cher.',
    },
    'Des tuiles ciment foncées, des combles en surchauffe.': {
      strong: 'Les tuiles stockent la chaleur.',
      muted: 'Les combles la subissent.',
    },
  };

  return map[title] ?? { strong: title, muted: '' };
};

const getLayerDescription = (index: number) => {
  if (index === 0) {
    return "S'adapte au support existant. Chaque toiture a sa chimie, chaque chimie demande une préparation et une accroche adaptées.";
  }

  if (index === 1) {
    return "C'est le coeur du système. La surface réfléchit le rayonnement solaire au lieu de l'absorber, donc la chaleur rentre moins dans le bâtiment.";
  }

  return "Un top coat protège la résine des UV, de la pollution et du vieillissement prématuré pour conserver la performance dans le temps.";
};

const getLayerExpert = (index: number) => {
  const notes = [
    "Un primaire inadapté, c'est un système qui cloque et se décolle. Le support décide de tout.",
    "Le cool roof traite la cause : la toiture chauffe moins, donc le bâtiment reçoit moins de calories.",
    "La différence entre une peinture et un investissement, c'est la tenue dans le temps. La finition est là pour protéger la performance.",
  ];

  return notes[index] ?? notes[0];
};

const Label = ({ children, light = false }: { children: string; light?: boolean }) => (
  <div className="mb-5 flex items-center gap-3">
    <span className={`h-px w-9 ${light ? 'bg-teal-vivid/70' : 'bg-primary/65'}`} aria-hidden="true" />
    <span
      className={`font-body text-[11px] font-bold uppercase tracking-[0.22em] ${
        light ? 'text-teal-vivid' : 'text-primary'
      }`}
    >
      {children}
    </span>
  </div>
);

const PrimaryCTA = ({ label, href }: { label: string; href: string }) => (
  <a
    href={href}
    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">{label}</span>
    <span className="flex h-8 w-8 items-center justify-center rounded-full bg-white/20 transition-transform duration-500 group-hover:translate-x-0.5">
      <ArrowRight className="h-3.5 w-3.5" />
    </span>
  </a>
);

export const RoofHero = ({ page }: { page: RoofPageData }) => {
  const [form, setForm] = useState({ climate: '', surface: '', email: '' });
  const [submitted, setSubmitted] = useState(false);
  const surfaceNum = parseFloat(form.surface) || 0;
  const estimate = surfaceNum ? `${new Intl.NumberFormat('fr-FR').format(surfaceNum * 22.5)} €` : '20-25 €/m²';

  return (
    <section
      aria-labelledby={`${page.slug}-hero-title`}
      className="relative isolate flex min-h-[100svh] flex-col overflow-hidden bg-navy text-cream"
    >
      <WpImage
        image={{ sourceUrl: page.heroImage, altText: page.heroImageAlt, width: null, height: null }}
        alt={page.heroImageAlt}
        fill
        priority
        className={`-z-10 size-full scale-[1.02] object-cover${
          page.slug === 'membrane-bitumineuse' ? ' object-[center_28%]' : ''
        }`}
      />
      <div
        aria-hidden="true"
        className="absolute inset-0 -z-10 hidden bg-gradient-to-r from-navy/[0.94] via-navy/62 to-navy/25 lg:block"
      />
      <div
        aria-hidden="true"
        className={`absolute inset-0 -z-10 bg-gradient-to-b lg:hidden ${
          page.slug === 'membrane-bitumineuse'
            ? 'from-navy/92 via-navy/58 to-navy/96'
            : 'from-navy/84 via-navy/38 to-navy/96'
        }`}
      />
      <div aria-hidden="true" className="absolute inset-x-0 bottom-0 -z-10 h-[28%] bg-gradient-to-t from-navy via-navy/85 to-transparent" />

      <div className="container relative z-10 mx-auto flex flex-1 items-center px-6 pb-10 pt-24 lg:px-12 lg:pb-16 lg:pt-28">
        <div className="grid w-full grid-cols-1 items-center gap-10 lg:grid-cols-[55fr_45fr] lg:gap-12">
          <div className="max-w-2xl space-y-6 lg:space-y-8">
            <ScrollReveal>
              <nav className="flex items-center gap-2 font-body text-xs text-cream/50">
                <a href="/" className="transition-colors hover:text-cream/75">Accueil</a>
                <span className="text-cream/28">/</span>
                <span>Toitures</span>
                <span className="text-cream/28">/</span>
                <span className="text-cream/78">{page.breadcrumb}</span>
              </nav>
            </ScrollReveal>

            <ScrollReveal>
              <h1
                id={`${page.slug}-hero-title`}
                className="font-satoshi font-bold leading-[1.02] text-white"
                style={{ fontSize: 'clamp(2.25rem, 4.6vw, 4rem)', letterSpacing: '-0.03em' }}
              >
                {page.h1}
              </h1>
            </ScrollReveal>

            <ScrollReveal>
              <p
                className="max-w-xl font-satoshi font-medium leading-[1.3] text-cream/66"
                style={{ fontSize: 'clamp(1rem, 1.5vw, 1.375rem)', letterSpacing: '-0.005em' }}
              >
                {page.lead}
              </p>
            </ScrollReveal>

            <ScrollReveal>
              <ul className="hidden gap-4 pt-1 sm:flex sm:flex-wrap lg:gap-6" aria-label="Bénéfices clés">
                {page.heroStats.map((stat, index) => {
                  const Icon = [Thermometer, ShieldCheck, TrendingDown][index] ?? BadgeCheck;
                  return (
                    <li
                      key={stat.label}
                      className={`flex items-start gap-3 ${index !== 0 ? 'sm:border-l sm:border-white/10 sm:pl-6' : ''}`}
                    >
                      <Icon className="mt-0.5 h-[18px] w-[18px] shrink-0 text-teal-vivid" strokeWidth={1.5} />
                      <div className="leading-tight">
                        <p className="font-satoshi text-[15px] font-bold text-white lg:text-base">{stat.value}</p>
                        <p className="mt-1 font-body text-[12.5px] text-cream/55 lg:text-[13px]">{stat.label}</p>
                      </div>
                    </li>
                  );
                })}
              </ul>
            </ScrollReveal>
          </div>

          <ScrollReveal>
            <div className="rounded-[1.5rem] border border-white/[0.08] bg-white/[0.04] p-1.5 backdrop-blur-sm">
              <div className="rounded-[calc(1.5rem-6px)] border border-white/[0.06] bg-[#0b1a2b]/80 p-4 shadow-[inset_0_1px_1px_rgba(255,255,255,0.06)] backdrop-blur-xl lg:p-7">
                {!submitted ? (
                  <>
                    <h2 className="mb-1 text-center font-satoshi text-xl font-bold text-white lg:text-2xl">
                      Estimez le gain possible
                    </h2>
                    <p className="mb-4 text-center font-body text-[12px] text-white/50">
                      Réponse personnalisée sous 24h
                    </p>
                    <form
                      onSubmit={(event) => {
                        event.preventDefault();
                        setSubmitted(true);
                      }}
                      className="space-y-2.5 lg:space-y-3"
                    >
                      <input
                        value={page.breadcrumb}
                        readOnly
                        className="w-full rounded-xl border border-white/[0.12] bg-white/[0.07] px-4 py-3 font-body text-sm text-white outline-none"
                      />
                      <select
                        required
                        value={form.climate}
                        onChange={(e) => setForm({ ...form, climate: e.target.value })}
                        className="w-full appearance-none rounded-xl border border-white/[0.12] bg-white/[0.07] px-4 py-3 font-body text-sm text-white transition-all duration-300 focus:border-white/25 focus:outline-none focus:ring-2 focus:ring-primary/50"
                      >
                        <option value="" disabled className="bg-card text-foreground">Bâtiment climatisé ?</option>
                        {['Oui', 'Non', 'Partiellement', 'À confirmer'].map((option) => (
                          <option key={option} value={option} className="bg-card text-foreground">{option}</option>
                        ))}
                      </select>
                      <input
                        type="number"
                        placeholder="Surface toiture (m²)"
                        required
                        min="1"
                        value={form.surface}
                        onChange={(e) => setForm({ ...form, surface: e.target.value })}
                        className="w-full rounded-xl border border-white/[0.12] bg-white/[0.07] px-4 py-3 font-body text-sm text-white placeholder:text-white/40 transition-all duration-300 focus:border-white/25 focus:outline-none focus:ring-2 focus:ring-primary/50"
                      />
                      <input
                        type="email"
                        placeholder="Email professionnel"
                        required
                        value={form.email}
                        onChange={(e) => setForm({ ...form, email: e.target.value })}
                        className="w-full rounded-xl border border-white/[0.12] bg-white/[0.07] px-4 py-3 font-body text-sm text-white placeholder:text-white/40 transition-all duration-300 focus:border-white/25 focus:outline-none focus:ring-2 focus:ring-primary/50"
                      />

                      <button
                        type="submit"
                        className="group mt-1 flex w-full items-center justify-center gap-3 rounded-full cta-gradient py-3 font-semibold text-white active:scale-[0.98]"
                      >
                        <span className="text-[15px]">Voir mon potentiel</span>
                        <span className="flex h-8 w-8 items-center justify-center rounded-full bg-white/20 transition-transform duration-500 group-hover:translate-x-0.5">
                          <ArrowRight className="h-4 w-4" />
                        </span>
                      </button>
                    </form>

                    <p className="mt-3 text-center font-body text-[11px] text-white/35">
                      Sans engagement · Étude adaptée au support
                    </p>
                  </>
                ) : (
                  <div className="py-4 text-center">
                    <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/20">
                      <ShieldCheck className="h-6 w-6 text-primary" />
                    </div>
                    <p className="mb-1 font-body text-sm text-white/60">Base indicative pour {new Intl.NumberFormat('fr-FR').format(surfaceNum)} m²</p>
                    <p className="mb-4 font-satoshi text-2xl font-bold text-white">{estimate}</p>
                    <p className="mb-4 font-body text-[13px] text-white/50">
                      Un conseiller affine le chiffrage selon l'état réel de la toiture.
                    </p>
                    <button onClick={() => setSubmitted(false)} className="font-body text-sm font-semibold text-primary hover:underline">
                      Modifier ma demande
                    </button>
                  </div>
                )}
              </div>
            </div>
          </ScrollReveal>
        </div>
      </div>

      <div className="relative z-10 hidden border-t border-white/10 bg-navy/78 backdrop-blur-md lg:block">
        <div className="container mx-auto flex items-center gap-8 px-12 py-5">
          <p className="shrink-0 font-body text-[10px] font-semibold uppercase tracking-[0.24em] text-cream/45">
            Ils nous font confiance
          </p>
          <div className="flex flex-1 items-center justify-between gap-8">
            {logos.map((logo) => (
              <span key={logo.name} className="flex h-8 w-28 items-center justify-center">
                <img
                  src={logo.url}
                  alt={logo.name}
                  className="max-h-7 max-w-full object-contain opacity-65 brightness-0 invert transition-opacity duration-300 hover:opacity-95"
                  loading="eager"
                  decoding="async"
                />
              </span>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

const ProblemSection = ({ page }: { page: RoofPageData }) => {
  const title = getProblemTitle(page.problem.title);
  const visual = supportVisuals[page.slug] ?? supportVisuals['membrane-bitumineuse'];

  return (
    <section className="relative overflow-hidden bg-cream py-16 lg:py-36">
      <div className="container relative mx-auto px-4 lg:px-8">
        <ScrollReveal>
          <div className="mx-auto mb-14 max-w-3xl text-center lg:mb-20">
            <h2
              className="font-satoshi text-3xl font-black text-foreground sm:text-4xl lg:text-[3rem]"
              style={{ letterSpacing: '-0.03em', lineHeight: 1.05 }}
            >
              {title.strong}
              {title.muted && <span className="text-foreground/30"> {title.muted}</span>}
            </h2>
          </div>
        </ScrollReveal>

        <div className="grid grid-cols-1 items-center gap-12 lg:grid-cols-12 lg:gap-16">
          <div className="order-2 lg:order-1 lg:col-span-5">
            <ScrollReveal>
              <div className="relative">
                <div className="pointer-events-none absolute -inset-8 rounded-[3rem] bg-[radial-gradient(ellipse_at_50%_50%,_hsl(var(--terracotta)/0.18)_0%,_transparent_65%)] blur-2xl" />
                <div className="relative aspect-square overflow-hidden rounded-[2rem] bg-white shadow-[0_30px_80px_-15px_hsl(var(--terracotta-dark)/0.25),_0_10px_30px_-5px_hsl(var(--terracotta)/0.12)]">
                  <WpImage
                    image={{ sourceUrl: visual.hot, altText: '', width: null, height: null }}
                    alt=""
                    fill
                    className="h-full w-full object-contain p-4"
                  />
                </div>
              </div>
              <p className="mt-4 text-center font-body text-[11px] uppercase tracking-wide text-terracotta/60">
                {visual.hotLabel}
              </p>
            </ScrollReveal>
          </div>

          <div className="order-1 lg:order-2 lg:col-span-7 lg:pl-12">
            <ScrollReveal stagger>
              <div
                className="space-y-8 border-l-2 pl-8 lg:space-y-10 lg:pl-10"
                style={{ borderImage: 'linear-gradient(to bottom, hsl(var(--terracotta)), hsl(var(--terracotta-dark))) 1' }}
              >
                {page.problem.cards.map((card, index) => {
                  const Icon = problemIcons[index] ?? HelpCircle;
                  return (
                    <div key={card.title}>
                      <div className="mb-2 flex items-center gap-3">
                        <Icon className="h-5 w-5 text-terracotta" strokeWidth={1.8} />
                        <h3
                          className="font-satoshi text-xl font-bold text-foreground lg:text-2xl"
                          style={{ letterSpacing: '-0.02em', lineHeight: 1.2 }}
                        >
                          {card.title}
                        </h3>
                      </div>
                      <p className="font-body text-base leading-relaxed text-foreground/55">{card.text}</p>
                    </div>
                  );
                })}
              </div>
            </ScrollReveal>
          </div>
        </div>

        <div className="mt-20 grid grid-cols-1 items-center gap-12 lg:mt-28 lg:grid-cols-12 lg:gap-16">
          <div className="order-2 lg:order-2 lg:col-span-5">
            <ScrollReveal>
              <div className="relative">
                <div className="pointer-events-none absolute -inset-8 rounded-[3rem] bg-[radial-gradient(ellipse_at_50%_50%,_rgba(32,150,140,0.18)_0%,_transparent_65%)] blur-2xl" />
                <div className="relative aspect-square overflow-hidden rounded-[2rem] bg-white shadow-[0_30px_80px_-15px_rgba(20,120,110,0.20),_0_10px_30px_-5px_rgba(32,150,140,0.10)]">
                  <WpImage
                    image={{ sourceUrl: visual.cool, altText: '', width: null, height: null }}
                    alt=""
                    fill
                    className="h-full w-full object-contain p-4"
                  />
                </div>
              </div>
              <p className="mt-4 text-center font-body text-[11px] uppercase tracking-wide text-primary/60">
                {visual.coolLabel}
              </p>
            </ScrollReveal>
          </div>

          <div className="order-1 lg:order-1 lg:col-span-7 lg:pr-12">
            <ScrollReveal>
              <h3
                className="mb-8 max-w-xl font-satoshi text-3xl font-black text-foreground sm:text-4xl lg:text-[3rem]"
                style={{ letterSpacing: '-0.03em', lineHeight: 1.05 }}
              >
                Le cool roof : une réponse concrète
                <span className="text-foreground/30"> au problème de chaleur.</span>
              </h3>
              <p className="mb-8 max-w-lg font-body text-base leading-relaxed text-foreground/50">
                Une surface claire renvoie le rayonnement solaire avant qu'il ne pénètre dans le bâtiment. La toiture chauffe moins, les derniers niveaux respirent, et le support subit moins d'UV et de chocs thermiques.
              </p>
              <PrimaryCTA label="Demander un devis" href="/diagnostic" />
            </ScrollReveal>
          </div>
        </div>
      </div>
    </section>
  );
};

const SolutionSection = ({ page }: { page: RoofPageData }) => {
  const [active, setActive] = useState(0);

  return (
    <section className="relative bg-white">
      <div className="container mx-auto px-4 lg:px-8">
        <ScrollReveal>
          <div className="flex flex-col gap-8 pb-10 pt-16 lg:flex-row lg:items-end lg:gap-16 lg:pb-16 lg:pt-32">
            <div className="lg:w-2/3">
              <p className="mb-6 font-body text-[10px] font-semibold uppercase tracking-[0.25em] text-muted-foreground">
                {page.solution.badge}
              </p>
              <h2
                className="font-satoshi text-3xl font-black text-foreground sm:text-4xl lg:text-[3rem]"
                style={{ letterSpacing: '-0.03em', lineHeight: 1.05 }}
              >
                <span className="text-foreground/30">Un système conçu pour </span>
                réfléchir, protéger et durer.
              </h2>
            </div>
            <div className="lg:w-1/3 lg:pb-1">
              <p className="font-body text-base leading-relaxed text-foreground/52 lg:text-right lg:text-lg">
                Un primaire, une résine, un vernis qui garantissent la performance de votre toiture dans le temps.
              </p>
              <div className="mt-5 flex lg:justify-end">
                <PrimaryCTA label="Demander un devis" href="/diagnostic" />
              </div>
            </div>
          </div>
        </ScrollReveal>

        <div className="flex flex-col gap-12 pb-24 lg:flex-row lg:gap-16 lg:pb-32">
          <div className="overflow-hidden rounded-2xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.08)] lg:hidden">
            <WpImage
              image={{
                sourceUrl: coolRoofLayers.src,
                altText: 'Coupe du système cool roof Covalba',
                width: coolRoofLayers.width,
                height: coolRoofLayers.height,
              }}
              alt="Coupe du système cool roof Covalba"
              className="w-full"
            />
          </div>

          <div className="lg:w-1/2 lg:sticky lg:top-[20vh] lg:self-start">
            {layerTitles.map((item, index) => {
              const isOpen = active === index;
              const colors = layerColors[index] ?? layerColors[0];
              return (
                <div key={item} className="border-b border-border last:border-b-0">
                  <button
                    onClick={() => setActive(index)}
                    className="group flex w-full items-center gap-4 py-6 text-left"
                  >
                    <span
                      className={`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full font-body text-[11px] font-bold transition-all duration-300 ${
                        isOpen ? colors.pill : 'bg-muted text-muted-foreground'
                      }`}
                    >
                      0{index + 1}
                    </span>
                    <h3
                      className={`flex-1 font-satoshi text-xl font-bold transition-colors duration-300 lg:text-2xl ${
                        isOpen ? 'text-foreground' : 'text-foreground/50 group-hover:text-foreground/80'
                      }`}
                    >
                      {item}
                    </h3>
                    <ChevronDown
                      className={`h-5 w-5 shrink-0 transition-all duration-300 ${
                        isOpen ? `${colors.chevron} rotate-180` : 'text-foreground/25'
                      }`}
                      strokeWidth={2}
                    />
                  </button>

                  <div
                    className={`grid transition-all duration-500 ${
                      isOpen ? 'grid-rows-[1fr] opacity-100' : 'grid-rows-[0fr] opacity-0'
                    }`}
                  >
                    <div className="overflow-hidden">
                      <div className="pb-8 pl-6 lg:pl-12">
                        <p className="mb-6 font-body text-base leading-relaxed text-foreground/65 lg:text-lg">
                          {getLayerDescription(index)}
                        </p>
                        <div className="flex items-start gap-3 rounded-xl bg-foreground/[0.03] p-4">
                          <div className="relative mt-0.5 h-9 w-9 shrink-0 overflow-hidden rounded-full">
                            <WpImage
                              image={{
                                sourceUrl: '/maxime-bourassin.jpg',
                                altText: 'Maxime Bourassin, fondateur Covalba',
                                width: null,
                                height: null,
                              }}
                              alt="Maxime Bourassin, fondateur Covalba"
                              fill
                              className="object-cover"
                            />
                          </div>
                          <div>
                            <p className="font-body text-[15px] italic leading-relaxed text-foreground/65 lg:text-base">
                              "{getLayerExpert(index)}"
                            </p>
                            <p className="mt-2 font-body text-xs font-semibold text-foreground/50">
                              Maxime Bourassin, fondateur
                            </p>
                          </div>
                        </div>
                        {index === 0 && page.solution.note && (
                          <p className="mt-4 rounded-xl bg-primary/5 p-4 font-body text-sm leading-relaxed text-foreground/62">
                            {page.solution.note}
                          </p>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          <div className="hidden lg:block lg:w-1/2">
            <div className="relative overflow-hidden rounded-2xl shadow-[0_30px_80px_-15px_rgba(0,0,0,0.08)]">
              <WpImage
                image={{
                  sourceUrl: coolRoofLayers.src,
                  altText: 'Coupe du système cool roof Covalba',
                  width: coolRoofLayers.width,
                  height: coolRoofLayers.height,
                }}
                alt="Coupe du système cool roof Covalba"
                className="w-full"
              />
              {layerTitles.map((item, index) => {
                const pos = layerPositions[index];
                const colors = layerColors[index] ?? layerColors[0];
                const isActive = active === index;
                if (!pos) return null;

                return (
                  <div key={item} className="absolute" style={{ top: pos.top, left: pos.left }}>
                    <div
                      className={`absolute -translate-x-1/2 -translate-y-1/2 transition-all duration-500 ${
                        isActive ? 'scale-125' : 'scale-75 opacity-40'
                      }`}
                    >
                      <div
                        className={`h-3.5 w-3.5 rounded-full ${
                          isActive ? colors.dot : 'bg-foreground/20'
                        } shadow-lg ring-2 ring-white transition-colors duration-500`}
                      />
                      {isActive && (
                        <div className={`absolute inset-0 h-3.5 w-3.5 animate-ping rounded-full ${colors.dot} opacity-30`} />
                      )}
                    </div>
                    <div
                      className={`pointer-events-none absolute right-5 top-1/2 -translate-y-1/2 transition-all duration-500 ${
                        isActive ? 'translate-x-0 opacity-100' : 'translate-x-2 opacity-0'
                      }`}
                    >
                      <span className={`whitespace-nowrap rounded-full px-4 py-1.5 font-body text-[13px] font-bold shadow-lg ${colors.pill}`}>
                        {item}
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

const BenefitsSection = ({ page }: { page: RoofPageData }) => (
  <section className="bg-white py-20 lg:py-32">
    <div className="container mx-auto px-4 lg:px-8">
      <ScrollReveal>
        <div className="mb-10 grid gap-8 lg:grid-cols-[0.82fr_1.18fr] lg:items-end lg:gap-14">
          <div>
            <Label>{page.benefits.badge}</Label>
            <h2 className="font-satoshi text-3xl font-black leading-tight text-foreground sm:text-4xl lg:text-5xl">
              {page.benefits.title}
            </h2>
          </div>
          <p className="max-w-xl border-l border-primary/30 pl-6 font-body text-base leading-relaxed text-foreground/62 lg:text-lg">
            {page.benefits.featured}
          </p>
        </div>
      </ScrollReveal>

      <ScrollReveal stagger>
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {page.benefits.cards.map((benefit, index) => {
            const Icon = cardIcons[index] ?? Sparkles;
            return (
              <article
                key={benefit.title}
                className="group overflow-hidden rounded-2xl bg-cream ring-1 ring-foreground/[0.05] transition-all duration-500 hover:-translate-y-1 hover:shadow-[0_24px_70px_-48px_hsl(var(--navy)/0.45)]"
              >
                <div className="relative aspect-[4/3] overflow-hidden bg-foreground/[0.04]">
                  <WpImage
                    image={{ sourceUrl: getBenefitImage(page, benefit, index), altText: '', width: null, height: null }}
                    alt=""
                    fill
                    className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-[1.035]"
                  />
                  <div className="absolute inset-x-0 bottom-0 h-20 bg-gradient-to-t from-cream to-transparent" />
                </div>
                <div className="p-5 lg:p-6">
                  <div className="mb-4 flex h-10 w-10 items-center justify-center rounded-xl bg-white text-primary shadow-[0_12px_30px_-24px_hsl(var(--navy)/0.35)]">
                    <Icon className="h-5 w-5" strokeWidth={1.7} />
                  </div>
                  <h3 className="font-satoshi text-lg font-bold leading-tight text-foreground">{benefit.title}</h3>
                  <p className="mt-2 font-body text-sm leading-relaxed text-foreground/62">{benefit.text}</p>
                </div>
              </article>
            );
          })}
        </div>
      </ScrollReveal>
    </div>
  </section>
);

const RoiOptionCards = ({
  page,
  surface,
  treatmentRange,
}: {
  page: RoofPageData;
  surface: number;
  treatmentRange: ReturnType<typeof getTreatmentRange>;
}) => {
  if (!page.roi.comparison) {
    return page.roi.afterComparison ? (
      <article className="rounded-2xl bg-white p-6 ring-1 ring-foreground/[0.06] lg:p-8">
        <p className="font-body text-base leading-relaxed text-foreground/66 lg:text-lg">
          {page.roi.afterComparison}
        </p>
      </article>
    ) : null;
  }

  const options = page.roi.comparison.headers.slice(1);
  const rows = page.roi.comparison.rows;
  const investment = rows.find((row) => row[0].toLowerCase().includes('investissement'));
  const duration = rows.find((row) => row[0].toLowerCase().includes('dur'));
  const activity = rows.find((row) => row[0].toLowerCase().includes('activ'));
  const treatmentMidpoint = (treatmentRange.min + treatmentRange.max) / 2;

  return (
    <div className="grid gap-4 lg:grid-cols-3">
      {options.map((option, optionIndex) => {
        const isCovalba = optionIndex === 0;
        const rawInvestment = investment?.[optionIndex + 1] ?? '';
        const parsedPrice = parsePricePerM2(rawInvestment);
        const pricePerM2 = parsedPrice ?? getFallbackPricePerM2(option, optionIndex, treatmentMidpoint);
        const dynamicInvestment = pricePerM2 ? `~${formatCurrency(surface * pricePerM2)}` : displayCell(rawInvestment);

        return (
          <article
            key={option}
            className={`rounded-2xl p-6 ring-1 ${
              isCovalba
                ? 'bg-[#142333] text-white ring-transparent'
                : 'bg-white text-foreground ring-foreground/[0.06]'
            }`}
          >
            <div className="mb-6 flex items-start justify-between gap-4">
              <h3 className="font-satoshi text-xl font-black leading-tight">{option}</h3>
              {isCovalba && (
                <span className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-teal-vivid/15 text-teal-vivid">
                  <Check className="h-4 w-4" strokeWidth={2.4} />
                </span>
              )}
            </div>
            <p className={`font-satoshi text-3xl font-black leading-none ${isCovalba ? 'text-teal-vivid' : 'text-terracotta'}`}>
              {dynamicInvestment}
            </p>
            {pricePerM2 && (
              <p className={`mt-2 font-body text-xs font-semibold ${isCovalba ? 'text-white/45' : 'text-foreground/40'}`}>
                base {new Intl.NumberFormat('fr-FR').format(surface)} m² · {pricePerM2.toLocaleString('fr-FR')} €/m²
              </p>
            )}
            <dl className="mt-6 space-y-3 border-t border-current/10 pt-5">
              {[duration, activity].filter(Boolean).map((row) => (
                <div key={row![0]} className="grid grid-cols-[0.75fr_1fr] gap-4">
                  <dt className={`font-body text-xs font-bold uppercase tracking-[0.14em] ${isCovalba ? 'text-white/38' : 'text-foreground/35'}`}>
                    {displayCell(row![0])}
                  </dt>
                  <dd className={`font-body text-sm leading-relaxed ${isCovalba ? 'text-white/74' : 'text-foreground/62'}`}>
                    {displayCell(row![optionIndex + 1])}
                  </dd>
                </div>
              ))}
            </dl>
          </article>
        );
      })}
    </div>
  );
};

const ROICalculator = ({
  page,
  surface,
  selectedSituation,
  treatmentRange,
  onSurfaceChange,
  onSituationChange,
}: {
  page: RoofPageData;
  surface: number;
  selectedSituation: string;
  treatmentRange: ReturnType<typeof getTreatmentRange>;
  onSurfaceChange: (surface: number) => void;
  onSituationChange: (situation: string) => void;
}) => {
  const treatmentLow = surface * treatmentRange.min;
  const treatmentHigh = surface * treatmentRange.max;
  const referencePrice = selectedSituation.toLowerCase().includes('isolation') ? 150 : 90;
  const referenceCost = surface * referencePrice;
  const potentialGap = Math.max(referenceCost - treatmentHigh, 0);

  return (
    <div className="mb-10 rounded-[2rem] bg-[#142333] p-5 text-white shadow-[0_34px_90px_-64px_hsl(var(--navy)/0.65)] lg:p-8">
      <div className="grid gap-7 lg:grid-cols-[0.88fr_1.12fr] lg:items-end">
        <div>
          <p className="font-body text-[10px] font-semibold uppercase tracking-[0.25em] text-teal-vivid/70">
            Calculateur indicatif
          </p>
          <h3 className="mt-4 max-w-lg font-satoshi text-2xl font-black leading-tight lg:text-3xl">
            Ajustez la surface et l'état de la toiture.
          </h3>
          <p className="mt-3 max-w-lg font-body text-sm leading-relaxed text-white/52">
            Par défaut : 5 000 m², surface type d'un entrepôt ou bâtiment industriel à traiter.
          </p>
        </div>

        <div className="grid gap-3 sm:grid-cols-[0.72fr_1.28fr]">
          <label className="block">
            <span className="mb-2 block font-body text-[11px] font-bold uppercase tracking-[0.16em] text-white/40">
              Surface
            </span>
            <input
              type="number"
              min={100}
              step={100}
              value={surface}
              onChange={(event) => onSurfaceChange(Math.max(100, Number(event.target.value) || 100))}
              className="h-12 w-full rounded-xl border border-white/10 bg-white/[0.07] px-4 font-body text-sm font-semibold text-white outline-none transition focus:border-teal-vivid/50 focus:ring-2 focus:ring-teal-vivid/20"
              aria-label="Surface à traiter en mètres carrés"
            />
          </label>
          <label className="block">
            <span className="mb-2 block font-body text-[11px] font-bold uppercase tracking-[0.16em] text-white/40">
              Situation
            </span>
            <select
              value={selectedSituation}
              onChange={(event) => onSituationChange(event.target.value)}
              className="h-12 w-full rounded-xl border border-white/10 bg-white/[0.07] px-4 font-body text-sm font-semibold text-white outline-none transition focus:border-teal-vivid/50 focus:ring-2 focus:ring-teal-vivid/20"
              aria-label="Situation de la toiture"
            >
              {page.roi.situation.rows.map((row) => (
                <option key={row[0]} value={row[0]} className="bg-card text-foreground">
                  {row[0]}
                </option>
              ))}
            </select>
          </label>
        </div>
      </div>

      <div className="mt-7 grid gap-3 md:grid-cols-3">
        {[
          {
            label: treatmentRange.label,
            value: `${formatCurrency(treatmentLow)} - ${formatCurrency(treatmentHigh)}`,
            detail: `${treatmentRange.min}-${treatmentRange.max} €/m² selon préparation`,
            valueClass: 'text-teal-vivid',
          },
          {
            label: 'Réfection de référence',
            value: `~${formatCurrency(referenceCost)}`,
            detail: `${referencePrice} €/m², ordre de grandeur à comparer`,
            valueClass: 'text-terracotta',
          },
          {
            label: 'Écart potentiel',
            value: `jusqu'à ${formatCurrency(potentialGap)}`,
            detail: "Investissement lourd évité ou repoussé si le support est viable",
            valueClass: 'text-teal-vivid',
          },
        ].map((item) => (
          <article key={item.label} className="rounded-2xl bg-white/[0.07] p-5 ring-1 ring-white/10">
            <p className="font-body text-[11px] font-bold uppercase tracking-[0.16em] text-white/38">{item.label}</p>
            <p className={`mt-3 font-satoshi text-2xl font-black leading-tight ${item.valueClass}`}>{item.value}</p>
            <p className="mt-2 font-body text-xs leading-relaxed text-white/45">{item.detail}</p>
          </article>
        ))}
      </div>
      <p className="mt-4 font-body text-xs leading-relaxed text-white/38">
        Chiffrage indicatif : l'étude ajuste le prix selon l'accès, la préparation, les points singuliers et l'état réel du support.
      </p>
    </div>
  );
};

const getSituationImage = (recommendation: string) => {
  const lower = recommendation.toLowerCase();
  if (lower.includes('covametal')) return covaMetalProduct;
  if (lower.includes('covaseal')) return covaSealProduct;
  if (lower.includes('cova')) return covaTherm20Product;
  return covaTherm8Product;
};

const SituationCards = ({ rows }: { rows: string[][] }) => (
  <div className="grid gap-4 md:grid-cols-2">
    {rows.map((row) => (
      <article key={row[0]} className="grid gap-4 rounded-2xl bg-white p-4 ring-1 ring-foreground/[0.06] sm:grid-cols-[128px_1fr] lg:grid-cols-[190px_1fr] lg:gap-5 lg:p-5">
        <div className="flex aspect-[4/3] items-center justify-center rounded-xl bg-gradient-to-br from-cream to-white p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.75),_0_18px_44px_-34px_hsl(var(--navy)/0.45)] ring-1 ring-foreground/[0.04] sm:aspect-square lg:p-6">
          {(() => {
            const situationImg = getSituationImage(row[1]);
            return (
              <WpImage
                image={{
                  sourceUrl: situationImg.src,
                  altText: '',
                  width: situationImg.width,
                  height: situationImg.height,
                }}
                alt=""
                className="max-h-full max-w-full object-contain"
              />
            );
          })()}
        </div>
        <div className="self-center">
          <p className="font-satoshi text-lg font-bold leading-tight text-foreground">{row[0]}</p>
          <p className="mt-2 font-body text-sm font-bold text-primary">{row[1]}</p>
          <p className="mt-2 font-body text-sm leading-relaxed text-foreground/58">{row[2]}</p>
        </div>
      </article>
    ))}
  </div>
);

const ROISection = ({ page }: { page: RoofPageData }) => {
  const [surface, setSurface] = useState(5000);
  const [selectedSituation, setSelectedSituation] = useState(page.roi.situation.rows[0]?.[0] ?? '');
  const treatmentRange = getTreatmentRange(page, selectedSituation);

  return (
    <section className="bg-cream py-20 lg:py-32">
      <div className="container mx-auto px-4 lg:px-8">
      <ScrollReveal>
        <div className="mx-auto mb-12 max-w-3xl text-center lg:mb-16">
          <div className="flex justify-center">
            <Label>{page.roi.badge}</Label>
          </div>
          <h2 className="font-satoshi text-3xl font-black leading-tight text-foreground sm:text-4xl lg:text-[3rem]">
            {page.roi.title}
          </h2>
          <p className="mx-auto mt-5 max-w-2xl font-body text-base leading-relaxed text-foreground/58 lg:text-lg">
            {page.roi.intro}
          </p>
        </div>
      </ScrollReveal>

      <ScrollReveal>
        <div className="mb-12 grid gap-4 md:grid-cols-3">
          {[
            ['20-25 €/m²', 'pour traiter et rafraîchir'],
            ['8-10 ans', 'de réfection repoussée'],
            ['0 arrêt', "d'activité pendant le chantier"],
          ].map(([value, label]) => (
            <article key={value} className="rounded-2xl bg-white p-6 text-center ring-1 ring-foreground/[0.06]">
              <p className="font-satoshi text-4xl font-black leading-none text-primary">{value}</p>
              <p className="mt-3 font-body text-sm font-semibold text-foreground/52">{label}</p>
            </article>
          ))}
        </div>
      </ScrollReveal>

      <ScrollReveal>
        <div className="mb-8 max-w-2xl">
          <div>
            <p className="font-body text-[10px] font-semibold uppercase tracking-[0.25em] text-primary/55">
              Comparer les options
            </p>
            <h3 className="mt-4 font-satoshi text-2xl font-black leading-tight text-foreground lg:text-3xl">
              Une lecture rapide du budget.
            </h3>
          </div>
        </div>
      </ScrollReveal>

      <ScrollReveal>
        <ROICalculator
          page={page}
          surface={surface}
          selectedSituation={selectedSituation}
          treatmentRange={treatmentRange}
          onSurfaceChange={setSurface}
          onSituationChange={setSelectedSituation}
        />
      </ScrollReveal>

      <ScrollReveal>
        <RoiOptionCards page={page} surface={surface} treatmentRange={treatmentRange} />
        {page.roi.comparison && page.roi.afterComparison && (
          <p className="mt-5 max-w-3xl font-body text-sm leading-relaxed text-foreground/52 lg:text-base">
            {page.roi.afterComparison}
          </p>
        )}
      </ScrollReveal>

      <ScrollReveal>
        <div className="mt-16 rounded-[2rem] bg-white p-5 ring-1 ring-foreground/[0.06] lg:mt-20 lg:p-8">
          <div className="mb-6 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
            <div>
              <p className="font-body text-[10px] font-semibold uppercase tracking-[0.25em] text-primary/55">
                Décider selon l'état réel
              </p>
              <h3 className="mt-4 max-w-xl font-satoshi text-2xl font-black leading-tight text-foreground lg:text-3xl">
                Quelle solution pour votre toiture ?
              </h3>
            </div>
            <PrimaryCTA label={page.roi.cta} href="/diagnostic" />
          </div>
          <SituationCards rows={page.roi.situation.rows} />
        </div>
      </ScrollReveal>
    </div>
  </section>
  );
};

const DiagnosticCTA = ({ title, text }: { title: string; text: string }) => (
  <section className="relative overflow-hidden bg-[#182A3A] py-14 text-white lg:py-20">
    <div
      aria-hidden="true"
      className="absolute inset-0 opacity-35"
      style={{
        backgroundImage:
          'radial-gradient(circle at 16% 20%, rgba(83, 207, 166, 0.22), transparent 28%), linear-gradient(115deg, rgba(255,255,255,0.05) 0 1px, transparent 1px 120px)',
      }}
    />
    <div className="container relative mx-auto px-4 lg:px-8">
      <ScrollReveal>
        <div className="mx-auto grid max-w-5xl gap-7 lg:grid-cols-[1fr_auto] lg:items-center">
          <div>
            <h2 className="font-satoshi text-2xl font-black leading-tight lg:text-4xl">{title}</h2>
            <p className="mt-3 max-w-2xl font-body text-sm leading-relaxed text-white/68 lg:text-base">{text}</p>
          </div>
          <div className="flex flex-col gap-3 sm:flex-row lg:justify-end">
            <PrimaryCTA label="Demander un devis" href="/diagnostic" />
          </div>
        </div>
      </ScrollReveal>
    </div>
  </section>
);

const MethodSection = ({ page }: { page: RoofPageData }) => {
  const [videoOpen, setVideoOpen] = useState(false);

  return (
    <section className="bg-white py-16 lg:py-32">
      <div className="container mx-auto px-4 lg:px-8">
        <div className="flex flex-col items-start gap-12 lg:flex-row lg:gap-20">
          <div className="lg:sticky lg:top-[120px] lg:w-[40%]">
            <ScrollReveal>
              <p className="mb-6 font-body text-[10px] font-semibold uppercase tracking-[0.25em] text-primary/50">
                Le process
              </p>
              <h2
                className="mb-6 font-satoshi text-3xl font-black text-foreground sm:text-4xl lg:text-[3rem]"
                style={{ letterSpacing: '-0.03em', lineHeight: 1.05 }}
              >
                4 étapes. Zéro interruption.
                <span className="text-foreground/30"> Zéro risque.</span>
              </h2>
              <p className="mb-8 font-body text-base leading-relaxed text-muted-foreground lg:text-lg">
                {page.method.reassurance}
              </p>
              <button
                onClick={() => setVideoOpen(true)}
                className="group flex items-center gap-3 text-primary transition-colors hover:text-primary"
              >
                <span className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/10 transition-colors group-hover:bg-primary/20">
                  <Play className="h-5 w-5" />
                </span>
                <span className="font-body text-sm font-semibold">Voir un chantier en 2 minutes</span>
              </button>
            </ScrollReveal>
          </div>

          <div className="relative lg:w-[60%]">
            <div className="absolute bottom-4 left-5 top-4 w-px bg-gradient-to-b from-primary/25 via-primary/10 to-transparent lg:left-6" />
            <div className="flex flex-col">
              {page.method.steps.map((step, index) => {
                const Icon = methodIcons[index] ?? CheckCircle2;
                return (
                  <ScrollReveal key={step.title}>
                    <div className="group relative flex items-start gap-5 py-8 lg:gap-7 lg:py-10">
                      <span className="relative z-10 flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-primary/20 bg-primary/10 transition-colors duration-500 group-hover:bg-primary/15 lg:h-12 lg:w-12">
                        <Icon className="h-4 w-4 text-primary lg:h-5 lg:w-5" />
                      </span>
                      <div className="pt-1">
                        <span className="mb-2 block font-body text-xs font-bold uppercase tracking-widest text-primary/50">
                          Étape 0{index + 1}
                        </span>
                        <h3 className="mb-2 font-satoshi text-xl font-bold text-foreground lg:text-2xl">
                          {step.title}
                        </h3>
                        <p className="max-w-md font-body text-sm leading-relaxed text-muted-foreground lg:text-base">
                          {step.text}
                        </p>
                      </div>
                    </div>
                    {index < page.method.steps.length - 1 && <div className="ml-5 h-px bg-border lg:ml-6" />}
                  </ScrollReveal>
                );
              })}
            </div>

            <ScrollReveal>
              <div className="ml-16 mt-4 lg:ml-20">
                <p className="font-body text-xs font-medium text-muted-foreground/50">
                  Durée moyenne : 3 jours · Sans arrêt d'activité
                </p>
              </div>
            </ScrollReveal>
          </div>
        </div>
      </div>

      <Dialog open={videoOpen} onOpenChange={setVideoOpen}>
        <DialogContent className="max-w-4xl overflow-hidden border-none bg-black p-0">
          <div className="aspect-video">
            <iframe
              src="https://www.youtube.com/embed/9HOB5OVH0Ac?autoplay=1"
              className="h-full w-full"
              allow="autoplay; encrypted-media"
              allowFullScreen
              title="Covalba Cool Roof, un chantier en 2 minutes"
            />
          </div>
        </DialogContent>
      </Dialog>
    </section>
  );
};

const ProofSection = ({ page }: { page: RoofPageData }) => (
  <section className="bg-[#192A3A] py-20 text-white lg:py-32">
    <div className="container mx-auto px-4 lg:px-8">
      <ScrollReveal>
        <div className="mb-12 grid gap-8 lg:grid-cols-[0.9fr_1.1fr] lg:items-end">
          <div>
            <Label light>{page.proof.badge}</Label>
            <h2 className="font-satoshi text-3xl font-black leading-tight sm:text-4xl lg:text-5xl">{page.proof.title}</h2>
          </div>
          <p className="max-w-xl font-body text-base leading-relaxed text-white/62">
            Des chiffres de terrain à confirmer chantier par chantier, utilisés ici comme repères de performance.
          </p>
        </div>
      </ScrollReveal>

      <ScrollReveal stagger>
        <div className="grid gap-4 md:grid-cols-3">
          {page.proof.figures.map((figure, index) => {
            const Icon = proofIcons[index] ?? BadgeCheck;
            return (
              <article key={figure.value} className="rounded-2xl border border-white/10 bg-white/[0.045] p-7">
                <Icon className="mb-6 h-6 w-6 text-teal-vivid" strokeWidth={1.7} />
                <p className="font-satoshi text-3xl font-black leading-none text-white lg:text-4xl">{figure.value}</p>
                <p className="mt-3 font-body text-sm leading-relaxed text-white/60">{figure.label}</p>
              </article>
            );
          })}
        </div>
      </ScrollReveal>

      <ScrollReveal>
        <div className="mt-14 border-t border-white/10 pt-10">
          <p className="mb-8 text-center font-body text-[10px] font-bold uppercase tracking-[0.22em] text-white/42">
            Références clients
          </p>
          <div className="flex flex-wrap items-center justify-center gap-x-10 gap-y-7 lg:gap-x-14">
            {logos.map((logo) => (
              <span key={logo.name} className="flex h-8 w-28 items-center justify-center">
                <img
                  src={logo.url}
                  alt={logo.name}
                  className="max-h-7 max-w-full object-contain opacity-45 transition-opacity duration-300 hover:opacity-80"
                  style={{ filter: 'brightness(0) invert(1)' }}
                  loading="lazy"
                />
              </span>
            ))}
          </div>
        </div>
      </ScrollReveal>
    </div>
  </section>
);

const FAQSection = ({ faq }: { faq: RoofPageData['faq'] }) => (
  <section className="bg-cream py-20 lg:py-32">
    <div className="container mx-auto px-4 lg:px-8">
      <div className="grid gap-10 lg:grid-cols-[0.85fr_1.15fr] lg:gap-16">
        <ScrollReveal>
          <div className="lg:sticky lg:top-24">
            <Label>FAQ</Label>
            <h2 className="font-satoshi text-3xl font-black leading-tight text-foreground sm:text-4xl lg:text-5xl">
              Vos questions,
              <br />
              <span className="text-foreground/40">nos réponses.</span>
            </h2>
            <a href="#contact" className="group mt-8 inline-flex items-center gap-2 font-body text-sm font-semibold text-primary transition-all hover:gap-3">
              Une autre question ? Parlons-en
              <ArrowRight className="h-4 w-4" />
            </a>
          </div>
        </ScrollReveal>

        <ScrollReveal>
          <Accordion type="single" collapsible className="space-y-3">
            {faq.map((item, index) => (
              <AccordionItem
                key={item.q}
                value={`roof-faq-${index}`}
                className="rounded-xl border border-foreground/[0.06] bg-white px-5 shadow-[0_12px_34px_rgba(24,42,58,0.04)] data-[state=open]:border-primary/20 lg:px-6"
              >
                <AccordionTrigger className="py-5 text-left font-satoshi text-base font-bold text-foreground hover:no-underline lg:text-[17px]">
                  {item.q}
                </AccordionTrigger>
                <AccordionContent className="pb-5 font-body text-[14.5px] leading-relaxed text-foreground/67 lg:text-[15px]">
                  {item.a}
                </AccordionContent>
              </AccordionItem>
            ))}
          </Accordion>
        </ScrollReveal>
      </div>
    </div>
  </section>
);

const FinalCTA = ({ page }: { page: RoofPageData }) => (
  <section id="contact" className="overflow-hidden bg-[#182A3A] py-20 text-white lg:py-32">
    <div className="container mx-auto px-4 lg:px-8">
      <ScrollReveal>
        <div className="mx-auto max-w-4xl text-center">
          <h2 className="font-satoshi text-3xl font-black leading-tight text-white sm:text-4xl lg:text-5xl">
            {page.finalCta.title}
          </h2>
          <p className="mx-auto mt-5 max-w-2xl font-body text-base leading-relaxed text-white/72 lg:text-lg">
            {page.finalCta.text}
          </p>
          <div className="mt-9 flex flex-col gap-3 sm:flex-row sm:justify-center">
            <PrimaryCTA label="Demander un devis" href="/diagnostic" />
          </div>
        </div>
      </ScrollReveal>

      <ScrollReveal>
        <ul className="mx-auto mt-12 grid max-w-3xl gap-3 sm:grid-cols-3">
          {page.finalCta.reassurances.map((item) => (
            <li key={item} className="flex items-center justify-center gap-2.5 rounded-lg border border-white/[0.12] bg-white/[0.045] px-4 py-3">
              <CalendarCheck className="h-4 w-4 shrink-0 text-teal-vivid" strokeWidth={1.8} />
              <span className="font-body text-sm text-white/[0.76]">{item}</span>
            </li>
          ))}
        </ul>
      </ScrollReveal>
    </div>
  </section>
);

const SEOContent = ({ page }: { page: RoofPageData }) => (
  <section className="bg-white py-20 lg:py-28">
    <div className="container mx-auto px-4 lg:px-8">
      <ScrollReveal>
        <article className="mx-auto max-w-3xl">
          <p className="mb-5 font-body text-[10px] font-bold uppercase tracking-[0.25em] text-primary/55">
            Guide support
          </p>
          <h2 className="font-satoshi text-3xl font-black leading-tight text-foreground lg:text-4xl">
            Tout comprendre sur le {page.eyebrow.toLowerCase()}.
          </h2>
          <p className="mt-6 font-body text-base leading-relaxed text-foreground/68 lg:text-lg">
            {page.seo.intro}
          </p>

          <div className="mt-10 space-y-9">
            {page.seo.sections.map((section) => (
              <section key={section.title}>
                <h3 className="font-satoshi text-2xl font-bold leading-tight text-foreground">{section.title}</h3>
                <p className="mt-3 font-body text-base leading-relaxed text-foreground/66">{section.text}</p>
              </section>
            ))}
          </div>

          <div className="mt-12 rounded-2xl bg-cream p-6 ring-1 ring-foreground/[0.05]">
            <h3 className="font-satoshi text-lg font-bold text-foreground">Sources</h3>
            <ul className="mt-4 space-y-2">
              {page.seo.sources.map((source) => (
                <li key={source.href}>
                  <a href={source.href} className="font-body text-sm leading-relaxed text-primary underline-offset-4 hover:underline" target="_blank" rel="noreferrer">
                    {source.label}
                  </a>
                </li>
              ))}
            </ul>
          </div>
        </article>
      </ScrollReveal>
    </div>
  </section>
);

const RoofPageTemplate = ({ page }: RoofPageTemplateProps) => {
  return (
    <>
      <Navbar />
      <main>
        <RoofHero page={page} />
        <ProblemSection page={page} />
        <SolutionSection page={page} />
        <BenefitsSection page={page} />
        <ROISection page={page} />
        <DiagnosticCTA title={page.midCta.title} text={page.midCta.text} />
        <MethodSection page={page} />
        <ProofSection page={page} />
        <FAQSection faq={page.faq} />
        <FinalCTA page={page} />
        <SEOContent page={page} />
      </main>
      <Footer />
      <StickyMobileCTA />
    </>
  );
};

export default RoofPageTemplate;
