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

import FooterEN from '@/components/en/FooterEN';
import NavbarEN from '@/components/en/NavbarEN';
import ScrollReveal from '@/components/ScrollReveal';
import StickyMobileCTAEN from '@/components/en/StickyMobileCTAEN';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { useJsonLd, usePageMeta } from '@/hooks/usePageMeta';
import { type RoofPageData, type 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 RoofPageTemplateENProps {
  page: RoofPageData;
}

const SITE_URL = 'https://www.covalba.fr';

// Internal route for all CTAs on the EN site. There is no dedicated EN
// diagnostic/contact route yet, so every conversion CTA points to the EN home.
const CTA_HREF = '/en';

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('en-US', { 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('membrane-bitumineuse') ||
    text.includes('toiture-plate') ||
    text.includes('aging') ||
    text.includes('leak')
  ) {
    return { min: 28, max: 38, label: 'CovaSeal 20 estimate' };
  }

  if (
    text.includes('covametal') ||
    text.includes('bac-acier') ||
    text.includes('corrosion') ||
    text.includes('steel')
  ) {
    return { min: 24, max: 32, label: 'CovaMetal 20 estimate' };
  }

  if (text.includes('fibrociment') || text.includes('fiber') || text.includes('sheets')) {
    return { min: 22, max: 28, label: 'CovaTherm sensitive substrate' };
  }

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

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

  if (optionIndex === 0) return treatmentMidpoint;
  if (lower.includes('anticorrosion') || lower.includes('repaint')) return 16;
  if (lower.includes('replacement') || lower.includes('replace')) return 120;
  if (lower.includes('new membrane') || lower.includes('membrane')) return 90;
  if (lower.includes('insulation')) 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('steel') || text.includes('corrosion') || text.includes('rust'))) {
    return '/images/toitures/support-bac-acier-cool.webp';
  }

  if (text.includes('bill') || text.includes('cooling') || text.includes('air conditioning') || text.includes('cold')) {
    return '/images/toitures/benefit-clim.webp';
  }

  if (
    text.includes('project') ||
    text.includes('refurbishment') ||
    text.includes('replacement') ||
    text.includes('removal') ||
    text.includes('strip')
  ) {
    return '/images/toitures/benefit-chantier-evite.webp';
  }

  if (
    text.includes('protect') ||
    text.includes('waterproof') ||
    text.includes('corrosion') ||
    text.includes('lifespan') ||
    text.includes('durab')
  ) {
    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: 'Without cool roof: bitumen membrane absorbing heat',
    coolLabel: 'With cool roof: reflective membrane',
  },
  'bac-acier': {
    hot: '/images/toitures/support-bac-acier-chaud.webp',
    cool: '/images/toitures/support-bac-acier-cool.webp',
    hotLabel: 'Without cool roof: overheating metal',
    coolLabel: 'With cool roof: reflective, protected steel deck',
  },
  'toiture-plate': {
    hot: '/images/toitures/support-toiture-plate-chaud.webp',
    cool: '/images/toitures/feedback-economie-clim-2.png',
    hotLabel: 'Without cool roof: roof terrace absorbing heat',
    coolLabel: 'With cool roof: reflective roof terrace',
  },
  fibrociment: {
    hot: '/images/toitures/support-fibrociment-chaud.webp',
    cool: '/images/toitures/support-fibrociment-cool.webp',
    hotLabel: 'Without cool roof: fiber cement absorbing heat',
    coolLabel: 'With cool roof: protected sheets',
  },
  'tuiles-ciment': {
    hot: '/images/toitures/support-tuiles-ciment-chaud.webp',
    cool: '/images/toitures/support-tuiles-ciment-cool.webp',
    hotLabel: 'Without cool roof: tiles storing heat',
    coolLabel: 'With cool roof: reflective tiles',
  },
};

const layerTitles = ['Bonding primer', 'Reflective resin', 'Protective top coat'];

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 }> = {
    'A black bitumen roof is a radiator sitting on top of your building.': {
      strong: 'Your roof heats up.',
      muted: 'Your building takes the hit.',
    },
    'Steel decking heats up fast, rusts fast, and wears out fast.': {
      strong: 'The metal heats up fast.',
      muted: 'The roof wears out too.',
    },
    'Flat, your roof takes the sun all day long.': {
      strong: 'Your roof terrace takes it all.',
      muted: 'Heat, UV, waterproofing.',
    },
    'Fiber cement heats up, ages, and is expensive to remove.': {
      strong: 'Fiber cement heats up.',
      muted: 'Removing it is expensive.',
    },
    'Dark cement tiles, overheating attic space.': {
      strong: 'The tiles store the heat.',
      muted: 'The attic space takes it.',
    },
  };

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

const getLayerDescription = (index: number) => {
  if (index === 0) {
    return 'Adapts to the existing substrate. Every roof has its own chemistry, and every chemistry calls for tailored preparation and bonding.';
  }

  if (index === 1) {
    return 'This is the heart of the system. The surface reflects solar radiation instead of absorbing it, so less heat enters the building.';
  }

  return 'A top coat protects the resin from UV, pollution and premature aging to preserve performance over time.';
};

const getLayerExpert = (index: number) => {
  const notes = [
    'An unsuitable primer means a system that blisters and peels off. The substrate decides everything.',
    'Cool roof treats the cause: the roof heats up less, so the building takes on less heat.',
    'The difference between a paint job and an investment is how it holds up over time. The finish is there to protect 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>
);

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('en-US').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"
    >
      <img
        src={page.heroImage}
        alt={page.heroImageAlt}
        className="absolute inset-0 -z-10 size-full scale-[1.02] object-cover"
        style={page.slug === 'membrane-bitumineuse' ? { objectPosition: 'center 28%' } : undefined}
        loading="eager"
        decoding="async"
      />
      <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="/en" className="transition-colors hover:text-cream/75">Home</a>
                <span className="text-cream/28">/</span>
                <span>Roofs</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="Key benefits">
                {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">
                      Estimate your potential savings
                    </h2>
                    <p className="mb-4 text-center font-body text-[12px] text-white/50">
                      Tailored reply within 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">Is the building air-conditioned?</option>
                        {['Yes', 'No', 'Partially', 'To confirm'].map((option) => (
                          <option key={option} value={option} className="bg-card text-foreground">{option}</option>
                        ))}
                      </select>
                      <input
                        type="number"
                        placeholder="Roof surface (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="Work email"
                        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]">See my potential</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">
                      No commitment · Study tailored to your substrate
                    </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">Indicative basis for {new Intl.NumberFormat('en-US').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">
                      An advisor refines the estimate based on the actual condition of the roof.
                    </p>
                    <button onClick={() => setSubmitted(false)} className="font-body text-sm font-semibold text-primary hover:underline">
                      Edit my request
                    </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">
            They trust us
          </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)]">
                  <img
                    src={visual.hot}
                    alt=""
                    className="h-full w-full object-contain p-4"
                    loading="lazy"
                    decoding="async"
                  />
                </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)]">
                  <img
                    src={visual.cool}
                    alt=""
                    className="h-full w-full object-contain p-4"
                    loading="lazy"
                    decoding="async"
                  />
                </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 }}
              >
                Cool roof: a concrete answer
                <span className="text-foreground/30"> to the heat problem.</span>
              </h3>
              <p className="mb-8 max-w-lg font-body text-base leading-relaxed text-foreground/50">
                A light-colored surface sends solar radiation back before it penetrates the building. The roof heats up less, the top floors can breathe, and the substrate is subjected to less UV and thermal shock.
              </p>
              <PrimaryCTA label="Request a quote" href={CTA_HREF} />
            </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">A system designed to </span>
                reflect, protect and last.
              </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">
                A primer, a resin and a top coat that guarantee your roof's performance over time.
              </p>
              <div className="mt-5 flex lg:justify-end">
                <PrimaryCTA label="Request a quote" href={CTA_HREF} />
              </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">
            <img src={coolRoofLayers.src} alt="Cross-section of the Covalba cool roof system" className="w-full" loading="lazy" />
          </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">
                          <img
                            src="/maxime-bourassin.jpg"
                            alt="Maxime Bourassin, founder of Covalba"
                            className="mt-0.5 h-9 w-9 shrink-0 rounded-full object-cover"
                          />
                          <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, founder
                            </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)]">
              <img src={coolRoofLayers.src} alt="Cross-section of the Covalba cool roof system" className="w-full" loading="lazy" />
              {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]">
                  <img
                    src={getBenefitImage(page, benefit, index)}
                    alt=""
                    className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-[1.035]"
                    loading="lazy"
                    decoding="async"
                  />
                  <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('investment'));
  const duration = rows.find((row) => {
    const key = row[0].toLowerCase();
    return key.includes('life') || key.includes('durat') || key.includes('lifespan');
  });
  const activity = rows.find((row) => {
    const key = row[0].toLowerCase();
    return key.includes('activity') || key.includes('operation');
  });
  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'}`}>
                basis {new Intl.NumberFormat('en-US').format(surface)} m² · {pricePerM2.toLocaleString('en-US')} €/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('insulation') ? 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">
            Indicative calculator
          </p>
          <h3 className="mt-4 max-w-lg font-satoshi text-2xl font-black leading-tight lg:text-3xl">
            Adjust the surface and the condition of the roof.
          </h3>
          <p className="mt-3 max-w-lg font-body text-sm leading-relaxed text-white/52">
            Default: 5,000 m², a typical surface for a warehouse or industrial building to treat.
          </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 to treat in square meters"
            />
          </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="Roof situation"
            >
              {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² depending on preparation`,
            valueClass: 'text-teal-vivid',
          },
          {
            label: 'Reference refurbishment',
            value: `~${formatCurrency(referenceCost)}`,
            detail: `${referencePrice} €/m², order of magnitude for comparison`,
            valueClass: 'text-terracotta',
          },
          {
            label: 'Potential gap',
            value: `up to ${formatCurrency(potentialGap)}`,
            detail: 'Heavy investment avoided or deferred if the substrate is 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">
        Indicative estimate: the study adjusts the price based on access, preparation, detailing points and the actual condition of the substrate.
      </p>
    </div>
  );
};

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

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">
          <img src={getSituationImage(row[1])} alt="" className="max-h-full max-w-full object-contain" loading="lazy" decoding="async" />
        </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²', 'to treat and cool down'],
            ['8-10 years', 'of refurbishment deferred'],
            ['0 downtime', 'during the works'],
          ].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">
              Compare the options
            </p>
            <h3 className="mt-4 font-satoshi text-2xl font-black leading-tight text-foreground lg:text-3xl">
              A quick read on the 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">
                Decide on the actual condition
              </p>
              <h3 className="mt-4 max-w-xl font-satoshi text-2xl font-black leading-tight text-foreground lg:text-3xl">
                Which solution for your roof?
              </h3>
            </div>
            <PrimaryCTA label={page.roi.cta} href={CTA_HREF} />
          </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="Request a quote" href={CTA_HREF} />
          </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">
                The 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 steps. Zero interruption.
                <span className="text-foreground/30"> Zero risk.</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">Watch a project in 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">
                          Step 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">
                  Average duration: 3 days · No interruption of activity
                </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, a project in 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">
            Field figures to be confirmed project by project, used here as performance benchmarks.
          </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">
            Client references
          </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">
              Your questions,
              <br />
              <span className="text-foreground/40">our answers.</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">
              Another question? Let's talk
              <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="Request a quote" href={CTA_HREF} />
          </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">
            Substrate guide
          </p>
          <h2 className="font-satoshi text-3xl font-black leading-tight text-foreground lg:text-4xl">
            Everything you need to know about {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 buildFaqSchema = (page: RoofPageData) => ({
  '@context': 'https://schema.org',
  '@type': 'FAQPage',
  mainEntity: page.faq.map((item) => ({
    '@type': 'Question',
    name: item.q,
    acceptedAnswer: {
      '@type': 'Answer',
      text: item.a,
    },
  })),
});

const buildBreadcrumbSchema = (page: RoofPageData) => ({
  '@context': 'https://schema.org',
  '@type': 'BreadcrumbList',
  itemListElement: [
    { '@type': 'ListItem', position: 1, name: 'Home', item: `${SITE_URL}/en` },
    { '@type': 'ListItem', position: 2, name: 'Roofs', item: `${SITE_URL}/en` },
    { '@type': 'ListItem', position: 3, name: page.breadcrumb, item: page.canonical },
  ],
});

const RoofPageTemplateEN = ({ page }: RoofPageTemplateENProps) => {
  usePageMeta({
    title: page.title,
    description: page.description,
    canonical: page.canonical,
  });
  useJsonLd(`roof-en-${page.slug}-faq`, buildFaqSchema(page));
  useJsonLd(`roof-en-${page.slug}-breadcrumb`, buildBreadcrumbSchema(page));

  return (
    <>
      <NavbarEN />
      <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>
      <FooterEN />
      <StickyMobileCTAEN />
    </>
  );
};

export default RoofPageTemplateEN;
