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 FooterES from '@/components/es/FooterES';
import NavbarES from '@/components/es/NavbarES';
import ScrollReveal from '@/components/ScrollReveal';
import StickyMobileCTAES from '@/components/es/StickyMobileCTAES';
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 RoofPageTemplateESProps {
  page: RoofPageData;
}

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

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

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('es-ES', { 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(',', '.'));
};

// Keyword-matching anchored on FR slugs (page.slug values are shared across all
// locales) plus a few Spanish copy keywords. Slug matching keeps the pricing
// helpers stable regardless of the translated situation labels.
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('envejec') ||
    text.includes('fuga')
  ) {
    return { min: 28, max: 38, label: 'CovaSeal 20 estimado' };
  }

  if (
    text.includes('covametal') ||
    text.includes('bac-acier') ||
    text.includes('corrosión') ||
    text.includes('corrosion') ||
    text.includes('acero')
  ) {
    return { min: 24, max: 32, label: 'CovaMetal 20 estimado' };
  }

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

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

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

  if (optionIndex === 0) return treatmentMidpoint;
  if (lower.includes('anticorrosión') || lower.includes('anticorrosion') || lower.includes('repintado')) return 16;
  if (lower.includes('sustitución') || lower.includes('reemplazo') || lower.includes('cambio')) return 120;
  if (lower.includes('membrana nueva') || lower.includes('membrana')) return 90;
  if (lower.includes('aislamiento')) 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('acero') || text.includes('corrosión') || text.includes('óxido') || text.includes('oxidación'))) {
    return '/images/toitures/support-bac-acier-cool.webp';
  }

  if (text.includes('factura') || text.includes('refrigeración') || text.includes('climatización') || text.includes('aire acondicionado') || text.includes('frío')) {
    return '/images/toitures/benefit-clim.webp';
  }

  if (
    text.includes('obra') ||
    text.includes('reforma') ||
    text.includes('rehabilitación') ||
    text.includes('sustitución') ||
    text.includes('retirada') ||
    text.includes('desmontaje')
  ) {
    return '/images/toitures/benefit-chantier-evite.webp';
  }

  if (
    text.includes('proteg') ||
    text.includes('impermeab') ||
    text.includes('estanqueidad') ||
    text.includes('corrosión') ||
    text.includes('vida útil') ||
    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: 'Sin cool roof: membrana bituminosa que absorbe el calor',
    coolLabel: 'Con cool roof: membrana reflectante',
  },
  'bac-acier': {
    hot: '/images/toitures/support-bac-acier-chaud.webp',
    cool: '/images/toitures/support-bac-acier-cool.webp',
    hotLabel: 'Sin cool roof: metal sobrecalentado',
    coolLabel: 'Con cool roof: chapa de acero reflectante y protegida',
  },
  'toiture-plate': {
    hot: '/images/toitures/support-toiture-plate-chaud.webp',
    cool: '/images/toitures/feedback-economie-clim-2.png',
    hotLabel: 'Sin cool roof: cubierta plana que absorbe el calor',
    coolLabel: 'Con cool roof: cubierta plana reflectante',
  },
  fibrociment: {
    hot: '/images/toitures/support-fibrociment-chaud.webp',
    cool: '/images/toitures/support-fibrociment-cool.webp',
    hotLabel: 'Sin cool roof: fibrocemento que absorbe el calor',
    coolLabel: 'Con cool roof: placas protegidas',
  },
  'tuiles-ciment': {
    hot: '/images/toitures/support-tuiles-ciment-chaud.webp',
    cool: '/images/toitures/support-tuiles-ciment-cool.webp',
    hotLabel: 'Sin cool roof: tejas que acumulan calor',
    coolLabel: 'Con cool roof: tejas reflectantes',
  },
};

const layerTitles = ['Imprimación de adherencia', 'Resina reflectante', 'Barniz de protección'];

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 }> = {
    'Una cubierta bituminosa negra es un radiador colocado sobre su edificio.': {
      strong: 'Su cubierta se calienta.',
      muted: 'Su edificio lo sufre.',
    },
    'La chapa de acero se calienta rápido, se oxida rápido y se desgasta rápido.': {
      strong: 'El metal se calienta rápido.',
      muted: 'La cubierta también se desgasta.',
    },
    'En plano, su cubierta recibe el sol todo el día.': {
      strong: 'Su cubierta lo recibe todo.',
      muted: 'Calor, UV, estanqueidad.',
    },
    'El fibrocemento se calienta, envejece y es caro de retirar.': {
      strong: 'El fibrocemento se calienta.',
      muted: 'Retirarlo cuesta caro.',
    },
    'Tejas de cemento oscuras, desvanes sobrecalentados.': {
      strong: 'Las tejas acumulan calor.',
      muted: 'Los desvanes lo sufren.',
    },
  };

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

const getLayerDescription = (index: number) => {
  if (index === 0) {
    return 'Se adapta al soporte existente. Cada cubierta tiene su química, y cada química requiere una preparación y una adherencia adaptadas.';
  }

  if (index === 1) {
    return 'Es el corazón del sistema. La superficie refleja la radiación solar en lugar de absorberla, de modo que entra menos calor en el edificio.';
  }

  return 'Un barniz de acabado protege la resina de los UV, la contaminación y el envejecimiento prematuro para conservar el rendimiento en el tiempo.';
};

const getLayerExpert = (index: number) => {
  const notes = [
    'Una imprimación inadecuada es un sistema que se ampolla y se despega. El soporte lo decide todo.',
    'El cool roof trata la causa: la cubierta se calienta menos, así que el edificio recibe menos calor.',
    'La diferencia entre una pintura y una inversión es cómo aguanta en el tiempo. El acabado está para proteger el rendimiento.',
  ];

  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('es-ES').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="/es" className="transition-colors hover:text-cream/75">Inicio</a>
                <span className="text-cream/28">/</span>
                <span>Cubiertas</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="Beneficios clave">
                {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">
                      Estime el ahorro posible
                    </h2>
                    <p className="mb-4 text-center font-body text-[12px] text-white/50">
                      Respuesta personalizada en 24 h
                    </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">¿Edificio climatizado?</option>
                        {['Sí', 'No', 'Parcialmente', 'Por confirmar'].map((option) => (
                          <option key={option} value={option} className="bg-card text-foreground">{option}</option>
                        ))}
                      </select>
                      <input
                        type="number"
                        placeholder="Superficie de cubierta (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="Correo profesional"
                        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]">Ver mi potencial</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">
                      Sin compromiso · Estudio adaptado al soporte
                    </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 indicativa para {new Intl.NumberFormat('es-ES').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 asesor ajusta el presupuesto según el estado real de la cubierta.
                    </p>
                    <button onClick={() => setSubmitted(false)} className="font-body text-sm font-semibold text-primary hover:underline">
                      Modificar mi solicitud
                    </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">
            Confían en nosotros
          </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 }}
              >
                El cool roof: una respuesta concreta
                <span className="text-foreground/30"> al problema del calor.</span>
              </h3>
              <p className="mb-8 max-w-lg font-body text-base leading-relaxed text-foreground/50">
                Una superficie clara devuelve la radiación solar antes de que penetre en el edificio. La cubierta se calienta menos, las últimas plantas respiran y el soporte sufre menos UV y choques térmicos.
              </p>
              <PrimaryCTA label="Solicitar presupuesto" 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">Un sistema diseñado para </span>
                reflejar, proteger y durar.
              </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">
                Una imprimación, una resina y un barniz que garantizan el rendimiento de su cubierta en el tiempo.
              </p>
              <div className="mt-5 flex lg:justify-end">
                <PrimaryCTA label="Solicitar presupuesto" 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="Sección del sistema cool roof de Covalba" 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, fundador de 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, fundador
                            </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="Sección del sistema cool roof de Covalba" 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) => {
    const key = row[0].toLowerCase();
    return key.includes('inversión') || key.includes('inversion');
  });
  const duration = rows.find((row) => {
    const key = row[0].toLowerCase();
    return key.includes('durac') || key.includes('vida útil') || key.includes('vida');
  });
  const activity = rows.find((row) => {
    const key = row[0].toLowerCase();
    return key.includes('activ') || key.includes('operac');
  });
  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('es-ES').format(surface)} m² · {pricePerM2.toLocaleString('es-ES')} €/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('aislamiento') ? 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">
            Calculadora indicativa
          </p>
          <h3 className="mt-4 max-w-lg font-satoshi text-2xl font-black leading-tight lg:text-3xl">
            Ajuste la superficie y el estado de la cubierta.
          </h3>
          <p className="mt-3 max-w-lg font-body text-sm leading-relaxed text-white/52">
            Por defecto: 5.000 m², superficie típica de una nave o edificio industrial a tratar.
          </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">
              Superficie
            </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="Superficie a tratar en metros cuadrados"
            />
          </label>
          <label className="block">
            <span className="mb-2 block font-body text-[11px] font-bold uppercase tracking-[0.16em] text-white/40">
              Situación
            </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="Situación de la cubierta"
            >
              {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² según preparación`,
            valueClass: 'text-teal-vivid',
          },
          {
            label: 'Rehabilitación de referencia',
            value: `~${formatCurrency(referenceCost)}`,
            detail: `${referencePrice} €/m², orden de magnitud a comparar`,
            valueClass: 'text-terracotta',
          },
          {
            label: 'Diferencia potencial',
            value: `hasta ${formatCurrency(potentialGap)}`,
            detail: 'Inversión pesada evitada o aplazada si el soporte es 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">
        Presupuesto indicativo: el estudio ajusta el precio según el acceso, la preparación, los puntos singulares y el estado real del soporte.
      </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²', 'para tratar y refrescar'],
            ['8-10 años', 'de rehabilitación aplazada'],
            ['0 paradas', 'de actividad durante la obra'],
          ].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">
              Comparar las opciones
            </p>
            <h3 className="mt-4 font-satoshi text-2xl font-black leading-tight text-foreground lg:text-3xl">
              Una lectura rápida del presupuesto.
            </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">
                Decidir según el estado real
              </p>
              <h3 className="mt-4 max-w-xl font-satoshi text-2xl font-black leading-tight text-foreground lg:text-3xl">
                ¿Qué solución para su cubierta?
              </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="Solicitar presupuesto" 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">
                El proceso
              </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 etapas. Cero interrupción.
                <span className="text-foreground/30"> Cero riesgo.</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">Ver una obra en 2 minutos</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">
                          Etapa 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">
                  Duración media: 3 días · Sin parada de actividad
                </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, una obra en 2 minutos"
            />
          </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">
            Cifras de campo a confirmar obra por obra, utilizadas aquí como referencias de rendimiento.
          </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">
            Referencias de clientes
          </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">
              Sus preguntas,
              <br />
              <span className="text-foreground/40">nuestras respuestas.</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">
              ¿Otra pregunta? Hablemos
              <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="Solicitar presupuesto" 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">
            Guía de soporte
          </p>
          <h2 className="font-satoshi text-3xl font-black leading-tight text-foreground lg:text-4xl">
            Todo lo que hay que saber sobre {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">Fuentes</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: 'Inicio', item: `${SITE_URL}/es` },
    { '@type': 'ListItem', position: 2, name: 'Cubiertas', item: `${SITE_URL}/es` },
    { '@type': 'ListItem', position: 3, name: page.breadcrumb, item: page.canonical },
  ],
});

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

  return (
    <>
      <NavbarES />
      <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>
      <FooterES />
      <StickyMobileCTAES />
    </>
  );
};

export default RoofPageTemplateES;
