"use client";

import { useEffect, useRef } from "react";
import { Layers, Maximize2, ShieldCheck, Sun, Volume2 } from "lucide-react";
import { cn } from "@/lib/utils";
import layerImages from "@/lib/layer-images.json";

// Four-layer breakdown of the iRoof sheet: scroll, hover or tap a layer to inspect it.
// The sheet stack and cards are driven imperatively (one rAF loop, class toggles) so
// scrolling never re-renders React.

const LAYERS = [
    {
        src: layerImages[0],
        num: "01",
        short: "ASA Layer",
        kicker: "Top Layer | Acrylonitrile Styrene Acrylate",
        title: "LG ASA Weather-Shield",
        body: "The outer protective layer, made using high-quality LG ASA raw materials and advanced polymer technology, helps protect the roofing sheet against Sri Lanka's intense sunlight and harsh weather conditions.",
        Icon: Sun,
        advantages: ["Helps reduce solar heat absorption."],
        tone: "accent",
    },
    {
        src: layerImages[1],
        num: "02",
        short: "UPVC Layer",
        kicker: "Second Layer | UPVC Structural Layer",
        title: "Structural Strength Layer",
        body: "This layer provides structural strength and helps the roofing sheet maintain its shape.",
        Icon: ShieldCheck,
        advantages: ["Provides strength and rigidity."],
        tone: "light",
    },
    {
        src: layerImages[2],
        num: "03",
        short: "Insulation",
        kicker: "Third Layer | Thermal & Acoustic Layer",
        title: "Heat & Sound Insulation Layer",
        body: "This layer helps create a more comfortable indoor environment.",
        Icon: Volume2,
        advantages: ["Contributes to thermal and acoustic comfort."],
        tone: "dark",
    },
    {
        src: layerImages[3],
        num: "04",
        short: "UPVC Base",
        kicker: "Bottom Layer | UPVC Structural Base",
        title: "Bottom Protective Layer",
        body: "The bottom layer provides additional support and a clean underside finish.",
        Icon: Layers,
        advantages: ["Adds structural stability.", "Supports overall sheet rigidity."],
        tone: "accent",
    },
] as const;

const N = LAYERS.length;
const IMG_W = 1103; // layer image size (all four share one frame)
const IMG_H = 415;
const MASK_W = 240;
const MASK_H = Math.round((MASK_W * IMG_H) / IMG_W);
const STEPS = [0.125, 0.375, 0.625, 0.875]; // scroll progress that centres each layer

export default function LayerShowcase() {
    const trackRef = useRef<HTMLElement>(null);
    const stageRef = useRef<HTMLDivElement>(null);
    const cardsRef = useRef<HTMLDivElement>(null);
    const svgRef = useRef<SVGSVGElement>(null);
    const statusRef = useRef<HTMLSpanElement>(null);
    const explodeBtnRef = useRef<HTMLButtonElement>(null);
    const explodeLabelRef = useRef<HTMLSpanElement>(null);

    useEffect(() => {
        const track = trackRef.current;
        const stage = stageRef.current;
        const cardBox = cardsRef.current;
        const svg = svgRef.current;
        const status = statusRef.current;
        const explodeBtn = explodeBtnRef.current;
        const explodeLabel = explodeLabelRef.current;
        if (!track || !stage || !cardBox || !svg || !status || !explodeBtn || !explodeLabel) return;

        const plates = Array.from(stage.querySelectorAll<HTMLDivElement>("[data-plate]"));
        const cards = Array.from(cardBox.querySelectorAll<HTMLElement>("[data-card]"));
        const pills = Array.from(track.querySelectorAll<HTMLButtonElement>("[data-pill]"));
        const path = svg.querySelector<SVGPathElement>("[data-path]")!;
        const glow = svg.querySelector<SVGPathElement>("[data-glow]")!;
        const pulse = svg.querySelector<SVGCircleElement>("[data-pulse]")!;
        const dotStart = svg.querySelector<SVGCircleElement>("[data-dot-start]")!;
        const dotEnd = svg.querySelector<SVGCircleElement>("[data-dot-end]")!;

        const motionQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
        // Touch screens can't hover, so the prompts say "tap" there.
        const verb = window.matchMedia("(hover: none)").matches ? "Tap" : "Hover";
        let reduceMotion = motionQuery.matches;

        // ---- Alpha masks from the real images: precise hover hit-testing + connector anchors
        const masks: (Uint8Array | null)[] = new Array(N).fill(null);
        const anchors = Array.from({ length: N }, (_, i) => ({ x: 0.68, y: 0.48 + i * 0.02 }));
        const maskCanvas = document.createElement("canvas");
        maskCanvas.width = MASK_W;
        maskCanvas.height = MASK_H;
        const maskCtx = maskCanvas.getContext("2d", { willReadFrequently: true });

        const buildMask = (idx: number, img: HTMLImageElement) => {
            if (!maskCtx) return;
            maskCtx.clearRect(0, 0, MASK_W, MASK_H);
            maskCtx.drawImage(img, 0, 0, MASK_W, MASK_H);
            try {
                const d = maskCtx.getImageData(0, 0, MASK_W, MASK_H).data;
                const a = new Uint8Array(MASK_W * MASK_H);
                for (let i = 0, p = 0; p < a.length; i += 4, p++) a[p] = d[i + 3];
                masks[idx] = a;
                // Connector starts at the right-most opaque point in the middle band of the sheet.
                let bestX = -1;
                let bestY = MASK_H / 2;
                for (let y = Math.floor(MASK_H * 0.3); y < Math.floor(MASK_H * 0.72); y++) {
                    for (let x = MASK_W - 1; x > bestX; x--) {
                        if (a[y * MASK_W + x] > 40) {
                            bestX = x;
                            bestY = y;
                            break;
                        }
                    }
                }
                if (bestX > 0) anchors[idx] = { x: (bestX - 2) / MASK_W, y: bestY / MASK_H };
            } catch {
                masks[idx] = null;
            }
            wake();
        };

        // ---- Geometry
        const containBox = (sw: number, sh: number) => {
            const s = Math.min(sw / IMG_W, sh / IMG_H);
            const w = IMG_W * s;
            const h = IMG_H * s;
            return { x: (sw - w) / 2, y: (sh - h) / 2, w, h };
        };
        let rectsDirty = true;
        let rStage = stage.getBoundingClientRect();
        let rSvg = svg.getBoundingClientRect();
        let rCard = cardBox.getBoundingClientRect();
        const refreshRects = () => {
            rStage = stage.getBoundingClientRect();
            rSvg = svg.getBoundingClientRect();
            rCard = cardBox.getBoundingClientRect();
            rectsDirty = false;
        };

        // ---- State
        const anim = [-5, -1.7, 1.7, 5].map((y) => ({ y, scale: 1, opacity: 1 }));
        let targetP = 0;
        let smoothP = 0;
        let hovered: number | null = null;
        // null = follow the scroll position; true/false = the visitor forced exploded/assembled.
        let forced: boolean | null = null;
        let lastExploded: boolean | null = null;
        let activeIdx = 0;
        let lastAppliedIdx = -1;
        let lastLabel = "";
        const conn = { x1: 0, y1: 0, x2: 0, y2: 0, ready: false };

        const hitTest = (clientX: number, clientY: number): number | null => {
            if (rectsDirty) refreshRects();
            const r = rStage;
            if (clientX < r.left || clientX > r.right || clientY < r.top || clientY > r.bottom) return null;
            const relX = clientX - r.left;
            const relY = clientY - r.top;
            const cx = r.width / 2;
            const cy = r.height / 2;
            const box = containBox(r.width, r.height);

            let haveMask = false;
            for (let i = 0; i < N; i++) {
                const m = masks[i];
                if (!m) continue;
                haveMask = true;
                const st = anim[i];
                const u = ((relX - cx) / st.scale + cx - box.x) / box.w;
                const v = ((relY - st.y - cy) / st.scale + cy - box.y) / box.h;
                if (u < 0 || u >= 1 || v < 0 || v >= 1) continue;
                if (m[Math.floor(v * MASK_H) * MASK_W + Math.floor(u * MASK_W)] > 36) return i;
            }
            if (haveMask) return null;

            // Masks not ready yet: pick the nearest layer by height.
            let best = 0;
            let bestD = Infinity;
            for (let i = 0; i < N; i++) {
                const d = Math.abs(relY - (cy + anim[i].y));
                if (d < bestD) {
                    bestD = d;
                    best = i;
                }
            }
            return bestD < r.height * 0.32 ? best : null;
        };

        // Discrete UI state changes (only when the active layer changes).
        const applyActive = (idx: number) => {
            cards.forEach((c, i) => {
                c.classList.toggle("is-active", i === idx);
                c.classList.toggle("is-above", i < idx);
                c.setAttribute("aria-hidden", i === idx ? "false" : "true");
                c.inert = i !== idx;
            });
            pills.forEach((p, i) => {
                p.classList.toggle("is-active", i === idx);
                p.setAttribute("aria-pressed", i === idx ? "true" : "false");
            });
            plates.forEach((p, i) => p.classList.toggle("is-focus", i === idx));
        };

        const setLabel = (text: string) => {
            if (text === lastLabel) return;
            lastLabel = text;
            status.textContent = text;
        };

        // ---- Render loop (runs only while something is moving)
        let rafId: number | null = null;
        let inView = true;
        const wake = () => {
            if (inView && rafId === null) rafId = requestAnimationFrame(frame);
        };

        const updateProgress = () => {
            const rect = track.getBoundingClientRect();
            const maxScroll = rect.height - window.innerHeight;
            if (maxScroll <= 0) return;
            targetP = Math.max(0, Math.min(1, -rect.top / maxScroll));
        };

        const frame = () => {
            rafId = null;
            const k = reduceMotion ? 1 : 0.14;
            let moving = false;

            smoothP += (targetP - smoothP) * k;
            if (Math.abs(targetP - smoothP) < 0.0008) smoothP = targetP;
            else moving = true;

            const scrollIdx = Math.max(0, Math.min(N - 1, Math.floor(smoothP * N)));
            const isHovering = hovered !== null;
            activeIdx = isHovering ? hovered! : scrollIdx;

            if (activeIdx !== lastAppliedIdx) {
                lastAppliedIdx = activeIdx;
                applyActive(activeIdx);
            }

            setLabel(
                isHovering
                    ? `Inspecting layer 0${activeIdx + 1} of 04`
                    : (forced === false || (forced === null && smoothP < 0.04))
                        ? `Assembled 4-layer sheet. Scroll or ${verb.toLowerCase()}`
                        : `Layer 0${activeIdx + 1} of 04. ${verb} any layer`
            );

            const rawExplode = Math.min(1, smoothP / 0.14);
            const explode =
                forced === true ? 1 : forced === false ? 0 : isHovering ? Math.max(0.88, rawExplode) : rawExplode;

            // Keep the button label in step with what's on screen.
            const isExploded = explode > 0.5;
            if (isExploded !== lastExploded) {
                lastExploded = isExploded;
                explodeLabel.textContent = isExploded ? "Assemble layers" : "Explode layers";
                explodeBtn.setAttribute("aria-pressed", String(isExploded));
            }

            const spread = Math.min(1, (stage.clientHeight || 350) / 350);
            const stacked = [-5, -1.7, 1.7, 5];
            const exploded = [-78 * spread, -26 * spread, 26 * spread, 78 * spread];
            const ease = reduceMotion ? 1 : 0.18;

            for (let i = 0; i < N; i++) {
                let ty = stacked[i] + (exploded[i] - stacked[i]) * explode;
                const focused = i === activeIdx;
                if (explode > 0.2) {
                    if (i < activeIdx) ty -= 10 * spread;
                    if (i > activeIdx) ty += 9 * spread;
                    if (focused && isHovering) ty -= 3;
                }
                const flat = explode < 0.08 && !isHovering;
                const tScale = flat ? 1 : focused ? 1.035 : 0.955;
                const tOpacity = flat ? 1 : focused ? 1 : isHovering ? 0.46 : 0.4;

                const st = anim[i];
                st.y += (ty - st.y) * ease;
                st.scale += (tScale - st.scale) * ease;
                st.opacity += (tOpacity - st.opacity) * ease;
                if (Math.abs(ty - st.y) < 0.06) st.y = ty;
                else moving = true;
                if (Math.abs(tScale - st.scale) < 0.0008) st.scale = tScale;
                else moving = true;
                if (Math.abs(tOpacity - st.opacity) < 0.002) st.opacity = tOpacity;
                else moving = true;

                plates[i].style.transform = `translate3d(0,${st.y.toFixed(2)}px,0) scale(${st.scale.toFixed(3)})`;
                plates[i].style.opacity = st.opacity.toFixed(3);
            }

            // Connector line from the active sheet to its card (desktop only).
            if (window.innerWidth >= 1024) {
                if (rectsDirty) refreshRects();
                const box = containBox(rStage.width, rStage.height);
                const cx = rStage.width / 2;
                const cy = rStage.height / 2;
                const st = anim[activeIdx];
                const a = anchors[activeIdx];
                const ax = box.x + a.x * box.w;
                const ay = box.y + a.y * box.h;
                const tx1 = rStage.left - rSvg.left + cx + (ax - cx) * st.scale;
                const ty1 = rStage.top - rSvg.top + cy + (ay - cy) * st.scale + st.y;
                const tx2 = rCard.left - rSvg.left + 2;
                const ty2 = rCard.top - rSvg.top + 54;

                if (!conn.ready || reduceMotion) {
                    Object.assign(conn, { x1: tx1, y1: ty1, x2: tx2, y2: ty2, ready: true });
                } else {
                    conn.x1 += (tx1 - conn.x1) * 0.24;
                    conn.y1 += (ty1 - conn.y1) * 0.24;
                    conn.x2 += (tx2 - conn.x2) * 0.24;
                    conn.y2 += (ty2 - conn.y2) * 0.24;
                    if (
                        Math.abs(tx1 - conn.x1) > 0.4 || Math.abs(ty1 - conn.y1) > 0.4 ||
                        Math.abs(tx2 - conn.x2) > 0.4 || Math.abs(ty2 - conn.y2) > 0.4
                    ) moving = true;
                }

                const midX = conn.x1 + (conn.x2 - conn.x1) * 0.52;
                const d = `M ${conn.x1.toFixed(1)} ${conn.y1.toFixed(1)} C ${midX.toFixed(1)} ${conn.y1.toFixed(1)}, ${midX.toFixed(1)} ${conn.y2.toFixed(1)}, ${conn.x2.toFixed(1)} ${conn.y2.toFixed(1)}`;
                path.setAttribute("d", d);
                glow.setAttribute("d", d);
                for (const el of [pulse, dotStart]) {
                    el.setAttribute("cx", conn.x1.toFixed(1));
                    el.setAttribute("cy", conn.y1.toFixed(1));
                }
                dotEnd.setAttribute("cx", conn.x2.toFixed(1));
                dotEnd.setAttribute("cy", conn.y2.toFixed(1));
            }

            if (moving) rafId = requestAnimationFrame(frame);
        };

        // ---- Input
        const goToLayer = (idx: number) => {
            const rect = track.getBoundingClientRect();
            const maxScroll = rect.height - window.innerHeight;
            window.scrollTo({
                top: window.scrollY + rect.top + maxScroll * (STEPS[idx] ?? STEPS[0]),
                behavior: reduceMotion ? "auto" : "smooth",
            });
        };
        const setHover = (v: number | null) => {
            if (v !== hovered) {
                hovered = v;
                wake();
            }
        };

        const onPointerMove = (e: PointerEvent) => {
            if (e.pointerType !== "mouse") return;
            const hit = hitTest(e.clientX, e.clientY);
            setHover(hit);
            stage.style.cursor = hit !== null ? "pointer" : "default";
        };
        const onPointerLeave = () => setHover(null);
        const onStageClick = (e: MouseEvent) => {
            const hit = hitTest(e.clientX, e.clientY);
            if (hit !== null) goToLayer(hit);
        };
        const onArrowKeys = (e: KeyboardEvent) => {
            let next: number | null = null;
            if (e.key === "ArrowDown" || e.key === "ArrowRight") next = Math.min(N - 1, activeIdx + 1);
            else if (e.key === "ArrowUp" || e.key === "ArrowLeft") next = Math.max(0, activeIdx - 1);
            else if (e.key === "Home") next = 0;
            else if (e.key === "End") next = N - 1;
            if (next === null) return;
            e.preventDefault();
            goToLayer(next);
        };
        const onExplode = () => {
            forced = !lastExploded;
            wake();
        };

        stage.addEventListener("pointermove", onPointerMove);
        stage.addEventListener("pointerleave", onPointerLeave);
        stage.addEventListener("click", onStageClick);
        stage.addEventListener("keydown", onArrowKeys);
        explodeBtn.addEventListener("click", onExplode);

        const pillCleanups = pills.map((el) => {
            const idx = Number(el.dataset.pill);
            const enter = (e: PointerEvent) => e.pointerType === "mouse" && setHover(idx);
            const leave = (e: PointerEvent) => e.pointerType === "mouse" && setHover(null);
            const focus = () => setHover(idx);
            const blur = () => setHover(null);
            const click = (e: MouseEvent) => {
                e.stopPropagation();
                goToLayer(idx);
            };
            el.addEventListener("pointerenter", enter);
            el.addEventListener("pointerleave", leave);
            el.addEventListener("focus", focus);
            el.addEventListener("blur", blur);
            el.addEventListener("click", click);
            el.addEventListener("keydown", onArrowKeys);
            return () => {
                el.removeEventListener("pointerenter", enter);
                el.removeEventListener("pointerleave", leave);
                el.removeEventListener("focus", focus);
                el.removeEventListener("blur", blur);
                el.removeEventListener("click", click);
                el.removeEventListener("keydown", onArrowKeys);
            };
        });

        // ---- Lifecycle
        const onScroll = () => {
            rectsDirty = true;
            updateProgress();
            wake();
        };
        const onResize = () => {
            rectsDirty = true;
            conn.ready = false;
            updateProgress();
            wake();
        };
        window.addEventListener("scroll", onScroll, { passive: true });
        window.addEventListener("resize", onResize);

        const resizeObserver = new ResizeObserver(() => {
            rectsDirty = true;
            wake();
        });
        resizeObserver.observe(stage);

        const intersection = new IntersectionObserver(
            ([entry]) => {
                inView = entry.isIntersecting;
                if (inView) {
                    rectsDirty = true;
                    updateProgress();
                    wake();
                } else if (rafId !== null) {
                    cancelAnimationFrame(rafId);
                    rafId = null;
                }
            },
            { rootMargin: "150px" }
        );
        intersection.observe(track);

        const onMotionChange = (e: MediaQueryListEvent) => {
            reduceMotion = e.matches;
            conn.ready = false;
            wake();
        };
        motionQuery.addEventListener("change", onMotionChange);

        // Build hit-test masks once the images are decoded (cached images are ready immediately).
        // This must run after `wake` and the render loop are defined.
        plates.forEach((plate, i) => {
            const img = plate.querySelector("img");
            if (!img) return;
            if (img.complete && img.naturalWidth) buildMask(i, img);
            else img.addEventListener("load", () => buildMask(i, img), { once: true });
        });
        applyActive(0);
        updateProgress();
        wake();

        return () => {
            if (rafId !== null) cancelAnimationFrame(rafId);
            stage.removeEventListener("pointermove", onPointerMove);
            stage.removeEventListener("pointerleave", onPointerLeave);
            stage.removeEventListener("click", onStageClick);
            stage.removeEventListener("keydown", onArrowKeys);
            explodeBtn.removeEventListener("click", onExplode);
            pillCleanups.forEach((fn) => fn());
            window.removeEventListener("scroll", onScroll);
            window.removeEventListener("resize", onResize);
            resizeObserver.disconnect();
            intersection.disconnect();
            motionQuery.removeEventListener("change", onMotionChange);
        };
    }, []);

    return (
        <div className="iroof-layers bg-white">
            {/* Heading */}
            <section className="relative pt-10 pb-0 md:pt-14 px-6 max-w-4xl mx-auto text-center" aria-labelledby="iroof-edge-heading">
                <h2 id="iroof-edge-heading" className="text-3xl md:text-5xl font-bold tracking-tight text-brand-dark mb-5">
                    Why <span className="text-brand-accent">We Are</span> the Best Choice
                </h2>
                <p className="max-w-3xl mx-auto text-sm md:text-[15px] leading-relaxed text-brand-dark/60 mb-5">
                    i-Roof is a <strong className="text-brand-dark font-semibold">4-layer roofing sheet</strong> that brings a novel experience to anyone who
                    loves the traditional look of Spanish-style roofing tiles. It is a state-of-the-art polymer sheet built from{" "}
                    <strong className="text-brand-accent font-semibold">ASA material and PVC</strong>, produced with the latest technology for a sheet that
                    lasts longer, stays cooler and installs faster.
                </p>
                <p className="inline-flex flex-wrap items-center justify-center gap-x-3 gap-y-2 text-xs md:text-sm font-extrabold tracking-[0.2em] uppercase">
                    <span className="px-3 py-1.5 bg-brand-accent text-white rounded-md">ASA protected</span>
                    <span className="text-brand-dark/30" aria-hidden="true">+</span>
                    <span className="px-3 py-1.5 border-2 border-brand-accent text-brand-accent rounded-md">4 Layers</span>
                </p>
            </section>

            {/* Scroll-driven 4-layer breakdown */}
            <section ref={trackRef} className="relative w-full h-[420vh]" aria-label="Interactive breakdown of the four i-Roof sheet layers">
                <div className="layers-stage-viewport sticky top-0 w-full overflow-hidden flex flex-col justify-between pt-20 pb-5 md:pt-24 md:pb-8 px-4 sm:px-8 lg:px-12">
                    {/* Top status */}
                    <div className="max-w-7xl w-full mx-auto flex items-center z-30">
                        <div className="inline-flex items-center gap-2.5 px-3.5 py-1.5 bg-white/90 border border-brand-dark/10 shadow-sm">
                            <span className="w-2 h-2 rounded-full bg-brand-accent motion-safe:animate-pulse" aria-hidden="true" />
                            <span ref={statusRef} role="status" className="text-[10px] md:text-[11px] font-semibold tracking-wider uppercase text-brand-dark/60">
                                Scroll, hover or tap any layer to inspect
                            </span>
                        </div>
                    </div>

                    {/* Stage + cards */}
                    <div className="relative max-w-7xl w-full mx-auto grid grid-cols-1 lg:grid-cols-12 gap-4 lg:gap-8 items-center my-auto z-20">
                        <svg ref={svgRef} className="hidden lg:block pointer-events-none absolute inset-0 w-full h-full z-40 overflow-visible" aria-hidden="true">
                            <defs>
                                <linearGradient id="iroofLayerLine" x1="0%" y1="0%" x2="100%" y2="0%">
                                    <stop offset="0%" stopColor="#b12028" stopOpacity="0.95" />
                                    <stop offset="100%" stopColor="#b12028" stopOpacity="0.25" />
                                </linearGradient>
                            </defs>
                            <path data-glow d="" fill="none" stroke="rgba(177,32,40,0.16)" strokeWidth="6" strokeLinecap="round" />
                            <path data-path className="layers-connector-dash" d="" fill="none" stroke="url(#iroofLayerLine)" strokeWidth="2" strokeDasharray="6 6" strokeLinecap="round" />
                            <circle data-pulse className="layers-pulse-ring" cx="0" cy="0" r="8" fill="rgba(177,32,40,0.35)" />
                            <circle data-dot-start cx="0" cy="0" r="4.5" fill="#b12028" stroke="#fff" strokeWidth="2" />
                            <circle data-dot-end cx="0" cy="0" r="4" fill="#b12028" />
                        </svg>

                        {/* Sheet stack */}
                        <div className="lg:col-span-7 relative flex flex-col items-center justify-center">
                            <div
                                ref={stageRef}
                                tabIndex={0}
                                role="group"
                                aria-label="Exploded view of the four sheet layers. Use the arrow keys to step through each layer."
                                className="relative w-full max-w-[680px] h-[190px] sm:h-[290px] lg:h-[350px] flex items-center justify-center select-none outline-none focus-visible:ring-2 focus-visible:ring-brand-accent/40"
                            >
                                {LAYERS.map((layer, i) => (
                                    <div key={layer.num} data-plate className="layers-plate" style={{ zIndex: 40 - i * 10 }}>
                                        {/* eslint-disable-next-line @next/next/no-img-element -- pixel data is read for hit-testing; the files are already optimised */}
                                        <img src={layer.src} alt="" width={IMG_W} height={IMG_H} decoding="async" className="w-full h-full object-contain" draggable={false} />
                                    </div>
                                ))}
                            </div>
                        </div>

                        {/* Cards */}
                        <div className="lg:col-span-5">
                            <div ref={cardsRef} className="relative h-[350px] sm:h-[340px] w-full">
                                {LAYERS.map((layer, i) => (
                                    <article
                                        key={layer.num}
                                        data-card
                                        className={cn(
                                            "layers-card p-5 sm:p-8 flex flex-col justify-between border shadow-[0_18px_45px_rgba(18,18,18,0.07)]",
                                            i === 0 && "is-active",
                                            layer.num === "04" ? "bg-[#fff6f4] border-brand-accent/25" : "bg-white",
                                            layer.num === "01" ? "border-brand-accent/25" : layer.num !== "04" && "border-brand-dark/10"
                                        )}
                                    >
                                        <div>
                                            <div className="flex items-start justify-between gap-4 mb-3">
                                                <div>
                                                    <span
                                                        className={cn(
                                                            "inline-flex items-center justify-center px-3 py-1 text-white text-xs font-extrabold tracking-wider mb-2.5",
                                                            layer.tone === "accent" ? "bg-brand-accent" : layer.tone === "dark" ? "bg-brand-dark" : "bg-zinc-400"
                                                        )}
                                                    >
                                                        {layer.num}
                                                    </span>
                                                    <p className="text-[10px] sm:text-[11px] font-bold tracking-[0.12em] uppercase text-brand-dark/50">
                                                        {layer.kicker}
                                                    </p>
                                                </div>
                                                <div
                                                    className="w-20 h-16 sm:w-24 sm:h-[4.5rem] shrink-0 border border-brand-dark/10 bg-zinc-100 bg-no-repeat"
                                                    style={{ backgroundImage: `url(${layer.src})`, backgroundSize: "300%", backgroundPosition: "52% 55%" }}
                                                    aria-hidden="true"
                                                />
                                            </div>
                                            <h3 className="text-xl sm:text-2xl font-extrabold text-brand-accent mb-2 tracking-tight">{layer.title}</h3>
                                            <p className="text-sm text-brand-dark/60 leading-relaxed">{layer.body}</p>
                                        </div>
                                        <div className="pt-3 mt-3 border-t border-brand-dark/10">
                                            <p className="text-[10px] font-bold uppercase tracking-[0.2em] text-brand-dark/45 mb-2">Advantages</p>
                                            <ul className="space-y-1.5">
                                                {layer.advantages.map((adv) => (
                                                    <li key={adv} className="flex items-center gap-2.5 text-sm font-semibold text-brand-dark">
                                                        <span className={cn("flex items-center justify-center w-7 h-7 rounded-full shrink-0", layer.tone === "accent" ? "bg-brand-accent/10 text-brand-accent" : "bg-zinc-100 text-brand-dark")}>
                                                            <layer.Icon className="w-3.5 h-3.5" aria-hidden="true" />
                                                        </span>
                                                        {adv}
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>
                                    </article>
                                ))}
                            </div>
                        </div>
                    </div>

                    {/* Bottom dock */}
                    <div className="max-w-7xl w-full mx-auto flex flex-wrap items-center justify-between gap-3 z-30">
                        <div className="flex items-center gap-1 sm:gap-1.5 bg-white/90 p-1.5 shadow-[0_8px_25px_rgba(0,0,0,0.05)] border border-brand-dark/10 mx-auto sm:mx-0">
                            {LAYERS.map((layer, i) => (
                                <button key={layer.num} type="button" data-pill={i} aria-pressed={i === 0} className={cn("layers-pill", i === 0 && "is-active")}>
                                    <span aria-hidden="true">{layer.num}</span>
                                    <span className="hidden md:inline font-semibold">{layer.short}</span>
                                    <span className="md:hidden sr-only">{layer.short}</span>
                                </button>
                            ))}
                        </div>
                        <div className="flex items-center gap-3 mx-auto sm:mx-0">
                            <button
                                ref={explodeBtnRef}
                                type="button"
                                aria-pressed="false"
                                className="inline-flex items-center gap-2 px-4 py-2 bg-white/90 hover:bg-white text-xs font-bold text-brand-dark border border-brand-dark/10 shadow-sm transition-colors"
                            >
                                <Maximize2 className="w-4 h-4 text-brand-accent" aria-hidden="true" />
                                <span ref={explodeLabelRef}>Explode layers</span>
                            </button>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    );
}
