"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { AnimatePresence, motion, useScroll, useTransform } from "framer-motion";
import {
  ArrowRight,
  Book,
  Briefcase,
  Cart,
  ChevronDown,
  Code,
  DollarSign,
  Gamepad,
  Heart,
  Home,
  Refresh,
  Sparkles,
  Truck,
  Users,
  categoryIcons,
} from "@/components/ui/icons";
import AnimatedButton from "@/components/ui/AnimatedButton";
import { Aurora, BrowserFrame, Counter, DotWave, TechBelt } from "./fx";
import Faq from "../home/Faq";

/**
 * Service-detail layout (client) — immersive, motion-rich and full-width.
 * Hero (parallax + particles + glass panels) → overview + animated results →
 * product lifecycle path → featured work mockup → capabilities (tilt cards) →
 * technology ecosystem (marquee) → industries → why Cerkel → testimonials →
 * FAQ → related → CTA. Brand-strict: dark tokens, Google Sans, orange/gold.
 *
 * Props: service, category ({ title, slug } | null), related ([...]).
 */
const EASE = [0.21, 0.47, 0.32, 0.98];
const container = { hidden: {}, show: { transition: { staggerChildren: 0.08 } } };
const rise = {
  hidden: { opacity: 0, y: 28 },
  show: { opacity: 1, y: 0, transition: { duration: 0.6, ease: EASE } },
};

const CATEGORY_IMAGE = {
  "game-development": "/images/opt/HeroBanner1.webp",
  "data-analytics-ai": "/images/opt/HeroBanner3.png",
  "web-software-development": "/images/opt/Pillar2.webp",
  "media-creative": "/images/opt/Pillar1.webp",
};

/** Success-story slides for the testimonial carousel (two-panel: results +
   quote). Mirrors the catalog stories so proof stays consistent site-wide. */
const STORIES = [
  {
    image: "/images/opt/HeroBanner1.webp",
    result: "Shipped a production fintech platform in 14 weeks.",
    summary: "Designed, built and launched the full web and mobile product end to end.",
    metrics: [
      { value: "14 wks", label: "idea to launch" },
      { value: "2M+", label: "users" },
      { value: "99.9%", label: "uptime" },
    ],
    quote: "From a whiteboard sketch to a live product in fourteen weeks — and it hasn't missed a beat since.",
    name: "Priya Sharma",
    role: "Founder · Fintech startup",
  },
  {
    image: "/images/opt/HeroBanner2.webp",
    result: "Cut operating costs 40% modernizing a 12-year-old system.",
    summary: "Re-platformed a legacy monolith to cloud-native with a zero-downtime migration.",
    metrics: [
      { value: "−40%", label: "ops cost" },
      { value: "0", label: "downtime" },
      { value: "3.2×", label: "faster releases" },
    ],
    quote: "They re-platformed our core system with zero downtime. Releases that took weeks now ship in a day.",
    name: "Marcus Hale",
    role: "CTO · Logistics platform",
  },
  {
    image: "/images/opt/HeroBanner3.png",
    result: "Turned scattered data into decisions leadership trusts.",
    summary: "Unified pipelines and analytics into a single source of truth across channels.",
    metrics: [
      { value: "2.4×", label: "activation" },
      { value: "−35%", label: "churn" },
      { value: "1", label: "source of truth" },
    ],
    quote: "For the first time, the whole leadership team is looking at the same numbers — and trusting them.",
    name: "Sara Whitman",
    role: "CMO · Retail group",
  },
];

/** Featured case study per capability area. */
const FEATURED_WORK = {
  "game-development": {
    title: "Cross-platform multiplayer arena", image: "/images/opt/HeroBanner1.webp",
    challenge: "A studio needed a real-time multiplayer game that ran flawlessly across mobile and PC — with netcode that scaled to launch-day spikes.",
    solution: "We built the game in Unity with low-latency netcode, dedicated servers and live ops, shipping to iOS, Android and Steam from one codebase.",
    results: [{ end: 1, suffix: "M+", label: "Players" }, { end: 60, label: "FPS on mobile" }, { end: 4.7, decimals: 1, suffix: "★", label: "Store rating" }],
    tech: ["Unity", "C#", "Photon", "AWS GameLift"],
  },
  "data-analytics-ai": {
    title: "AI-powered analytics suite", image: "/images/opt/HeroBanner3.png",
    challenge: "Scattered data across channels meant leadership couldn't trust a single number — or predict what came next.",
    solution: "We unified pipelines into one source of truth and layered ML forecasting on top, surfacing insight that lifted conversion.",
    results: [{ end: 2.4, decimals: 1, suffix: "×", label: "Activation" }, { end: 35, suffix: "%", label: "Less churn" }, { end: 1, label: "Source of truth" }],
    tech: ["Snowflake", "dbt", "Python", "PyTorch"],
  },
  "web-software-development": {
    title: "Fintech super-app", image: "/images/opt/HeroBanner1.webp",
    challenge: "A high-growth startup needed to launch a regulated fintech product fast — without compromising security or stability.",
    solution: "We designed and engineered the full web and mobile platform end to end, with weekly demos and a hardened, audited architecture.",
    results: [{ end: 14, suffix: " wks", label: "Idea to launch" }, { end: 2, suffix: "M+", label: "Users" }, { end: 99.9, decimals: 1, suffix: "%", label: "Uptime" }],
    tech: ["React Native", "Node.js", "PostgreSQL", "AWS"],
  },
  "media-creative": {
    title: "Brand & launch campaign", image: "/images/opt/Pillar1.webp",
    challenge: "A scaling company had outgrown its identity and needed a cohesive brand and launch content that performed across every channel.",
    solution: "We delivered a full rebrand — identity, motion system and social creatives — rolled out consistently from web to paid ads.",
    results: [{ end: 3.1, decimals: 1, suffix: "×", label: "Engagement" }, { end: 48, suffix: "%", label: "More reach" }, { end: 12, label: "Channels unified" }],
    tech: ["Figma", "After Effects", "Illustrator", "Premiere Pro"],
  },
};

const BENEFITS = [
  { Icon: Users, title: "Senior engineers only", desc: "No juniors learning on your budget. Proven specialists who've shipped this before." },
  { Icon: Refresh, title: "Weekly demos, zero surprises", desc: "You see working software every week and steer as you go — never a black box." },
  { Icon: Sparkles, title: "Built to scale", desc: "Clean architecture and automated testing, so what we ship keeps growing with you." },
];

const LIFECYCLE = [
  { t: "Idea", d: "We pressure-test the concept against real users and business goals before anything is built." },
  { t: "Research", d: "Market, technical and UX research that de-risks the build and sharpens the direction." },
  { t: "Wireframe", d: "Low-fidelity structure and flows agreed up front — before a single pixel is polished." },
  { t: "Prototype", d: "Interactive prototypes we put in front of real users to validate the experience early." },
  { t: "Development", d: "Senior engineers ship tested increments with weekly demos and zero surprises." },
  { t: "Launch", d: "A confident, fully monitored release — no fire drills, no guesswork." },
  { t: "Scale", d: "We measure, harden and keep evolving the product with you long after go-live." },
];

const RESULTS = [
  { end: 250, suffix: "+", label: "Products shipped" },
  { end: 98, suffix: "%", label: "Client retention" },
  { end: 40, suffix: "+", label: "Industries served" },
  { end: 4.9, decimals: 1, label: "Avg client rating" },
];

const INDUSTRIES = [
  { name: "Healthcare", Icon: Heart },
  { name: "FinTech", Icon: DollarSign },
  { name: "Banking", Icon: Briefcase },
  { name: "eCommerce", Icon: Cart },
  { name: "Gaming", Icon: Gamepad },
  { name: "Education", Icon: Book },
  { name: "Logistics", Icon: Truck },
  { name: "Real Estate", Icon: Home },
];

const ECOSYSTEM_A = ["React", "Next.js", "Node.js", "TypeScript", "Python", "Go", "PostgreSQL", "MongoDB", "Redis", "GraphQL", "Kafka"];
const ECOSYSTEM_B = ["Docker", "Kubernetes", "Terraform", "AWS", "Azure", "GCP", "OpenAI", "TensorFlow", "React Native", "Flutter", "Unity"];

/** Signature "system flow" per capability area — the section that varies most
   from one service to the next, so no two pages feel identical. */
const SIGNATURE = {
  "game-development": {
    label: "Production pipeline",
    heading: "From concept to launch — playable at every step.",
    blurb: "A proven game pipeline: prototype the fun first, build the systems and art, then optimize and ship to every platform with live ops ready.",
    stages: ["Concept", "Prototype", "Production", "Optimize", "Launch"],
  },
  "data-analytics-ai": {
    label: "Data & AI pipeline",
    heading: "Raw data to intelligence — in one flow.",
    blurb: "Ingest from everywhere, process and model into a single source of truth, then train, deploy and act on AI your team can trust.",
    stages: ["Ingest", "Process", "Model", "Train AI", "Decide"],
  },
  "web-software-development": {
    label: "Delivery pipeline",
    heading: "From commit to production — instrumented.",
    blurb: "One connected pipeline: every change is built, tested, scanned and shipped automatically — with full visibility end to end.",
    stages: ["Code", "CI/CD", "Automated tests", "Security scan", "Production"],
  },
  "media-creative": {
    label: "Creative process",
    heading: "From brief to brand — crafted to convert.",
    blurb: "A structured creative process: understand the brand, explore directions, design and animate, then deliver assets ready for every channel.",
    stages: ["Discover", "Concept", "Design", "Produce", "Deliver"],
  },
};

/** Punchy, service-specific closing CTA headline. */
const CTA_TAGLINE = {
  "game-development": "Build a game players can't put down.",
  "data-analytics-ai": "Turn data into a competitive advantage.",
  "web-software-development": "Ship faster. Build to last.",
  "media-creative": "Make a brand impossible to ignore.",
};

function buildFaqs(title) {
  const t = title.toLowerCase();
  return [
    { q: `How do you approach a ${t} project?`, a: `We start with discovery to understand your goals and constraints, agree on scope and architecture, then build in tested increments with weekly demos so you can steer throughout.` },
    { q: `How long does a ${t} engagement take?`, a: `It depends on scope, but most engagements move from kickoff to a first usable release in a matter of weeks. We share a realistic timeline in the proposal and keep it visible as we go.` },
    { q: `What does it cost?`, a: `We scope each engagement individually — fixed-scope for well-defined work, or a flexible monthly team for evolving products. You get a clear proposal before anything starts.` },
    { q: `Do you support the product after launch?`, a: `Yes. We offer ongoing support and maintenance — monitoring, fixes, updates and enhancements — backed by clear SLAs, so your product stays healthy long after launch.` },
  ];
}

function scrollToId(e, id) {
  e.preventDefault();
  const el = document.getElementById(id);
  if (!el) return;
  if (window.lenis) window.lenis.scrollTo(el, { offset: -120 });
  else el.scrollIntoView({ behavior: "smooth" });
}

function Stars({ className = "h-4 w-4" }) {
  return (
    <span className="flex gap-0.5 text-primary" aria-label="5 out of 5 stars">
      {Array.from({ length: 5 }).map((_, i) => (
        <svg key={i} className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
          <path d="M12 2l2.92 6.26 6.58.62-4.97 4.73 1.44 6.68L12 16.9l-5.97 3.39 1.44-6.68L2.5 8.88l6.58-.62L12 2z" />
        </svg>
      ))}
    </span>
  );
}

const initials = (name) => name.split(" ").map((w) => w[0]).join("").slice(0, 2);

export default function ServiceDetailView({ service, category, related }) {
  const [activeCap, setActiveCap] = useState(0);
  const [storyIdx, setStoryIdx] = useState(0);
  const [storyPaused, setStoryPaused] = useState(false);

  // Scroll-driven glowing beam down the lifecycle timeline.
  const timelineRef = useRef(null);
  const { scrollYProgress } = useScroll({ target: timelineRef, offset: ["start 75%", "end 55%"] });
  const beamHeight = useTransform(scrollYProgress, [0, 1], ["0%", "100%"]);

  const Icon = (category && categoryIcons[category.slug]) || Code;
  const signature = (category && SIGNATURE[category.slug]) || SIGNATURE["web-software-development"];
  const ctaTagline = (category && CTA_TAGLINE[category.slug]) || "Ready to build your next digital product?";
  const capabilities = service.capabilities ?? (service.features ?? []).map((f) => ({ title: f }));
  const heroImage = (category && CATEGORY_IMAGE[category.slug]) || "/images/opt/HeroBanner1.webp";
  const work = (category && FEATURED_WORK[category.slug]) || FEATURED_WORK["web-software-development"];
  const story = STORIES[storyIdx];

  // Auto-advance the success-story carousel (pauses on hover).
  useEffect(() => {
    if (storyPaused) return;
    const id = setTimeout(() => setStoryIdx((s) => (s + 1) % STORIES.length), 6000);
    return () => clearTimeout(id);
  }, [storyIdx, storyPaused]);

  const nextStory = () => setStoryIdx((s) => (s + 1) % STORIES.length);
  const prevStory = () => setStoryIdx((s) => (s - 1 + STORIES.length) % STORIES.length);
  const faqs = buildFaqs(service.title);

  return (
    <>
      {/* ── Hero (image + dot-wave backdrop, full height) ─────────────── */}
      <section className="relative isolate flex min-h-[calc(100svh-5rem)] flex-col overflow-hidden bg-background">
        <Image src={heroImage} alt="" fill priority sizes="100vw" className="-z-20 object-cover opacity-50" />
        <span className="absolute inset-0 -z-10 bg-gradient-to-b from-background/40 via-background/70 to-background" />
        <Aurora className="opacity-50" />
        <DotWave />
        <div className="pointer-events-none absolute -top-40 left-[28%] h-96 w-40 -rotate-[18deg] rounded-[50%] bg-foreground/[0.06] blur-3xl" />
        <div className="pointer-events-none absolute -top-40 right-[30%] h-96 w-32 rotate-[18deg] rounded-[50%] bg-foreground/[0.05] blur-3xl" />

        {/* breadcrumb — pinned top */}
        <div className="container relative z-10 w-full pt-8">
          <nav aria-label="Breadcrumb" className="flex flex-wrap items-center justify-center gap-1.5 text-xs text-muted-foreground">
            <Link href="/" className="transition-colors hover:text-foreground">Home</Link>
            <span className="text-foreground/30">/</span>
            <Link href="/services" className="transition-colors hover:text-foreground">Services</Link>
            {category && (<><span className="text-foreground/30">/</span><span className="text-muted-foreground">{category.title}</span></>)}
            <span className="text-foreground/30">/</span>
            <span className="text-primary">{service.title}</span>
          </nav>
        </div>

        {/* content — centered in remaining height */}
        <div className="container relative z-10 flex w-full flex-1 items-center justify-center py-12">
          <motion.div variants={container} initial="hidden" animate="show" className="mx-auto max-w-3xl text-center">
            <motion.div variants={rise} className="flex items-center justify-center gap-3">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-primary to-accent text-primary-foreground shadow-lg shadow-primary/30">
                <Icon className="h-5 w-5" />
              </span>
              {category && <span className="font-heading text-xs font-semibold uppercase tracking-wider text-primary">{category.title}</span>}
            </motion.div>
            <motion.h1 variants={rise} className="mt-6 font-heading text-5xl font-bold leading-[1.04] tracking-tight drop-shadow-[0_2px_24px_rgba(0,0,0,0.55)] sm:text-6xl md:text-7xl">
              {service.title}
            </motion.h1>
            <motion.p variants={rise} className="mx-auto mt-6 max-w-2xl text-base leading-relaxed text-foreground/80 sm:text-lg">
              {service.excerpt}
            </motion.p>
            <motion.div variants={rise} className="mt-9 flex flex-wrap items-center justify-center gap-5">
              <AnimatedButton href="/contact">Start a project</AnimatedButton>
              <a href="#lifecycle" onClick={(e) => scrollToId(e, "lifecycle")} className="group inline-flex items-center gap-2 text-sm font-semibold text-foreground">
                See how we build
                <span className="flex h-7 w-7 items-center justify-center rounded-full border border-border transition-all duration-300 group-hover:border-primary group-hover:bg-primary group-hover:text-primary-foreground">
                  <ChevronDown className="h-4 w-4" />
                </span>
              </a>
            </motion.div>
          </motion.div>
        </div>
      </section>

      {/* ── Overview + animated results ───────────────────────────────── */}
      <section className="relative overflow-hidden bg-background py-14 text-foreground md:py-20">
        <div className="pointer-events-none absolute -left-32 top-0 h-[24rem] w-[34rem] rounded-full bg-primary/[0.06] blur-[150px]" />
        <div className="container relative">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.4 }} className="max-w-4xl">
            <span className="inline-flex items-center gap-2 rounded-full border border-border bg-surface/60 px-4 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground backdrop-blur">
              <span className="h-1.5 w-1.5 rounded-full bg-primary" /> Overview
            </span>
            <p className="mt-6 font-heading text-2xl font-medium leading-[1.4] tracking-tight text-foreground sm:text-3xl">{service.description}</p>
          </motion.div>

          <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.3 }} className="mt-12 grid grid-cols-2 gap-px overflow-hidden rounded-2xl border border-border bg-border lg:grid-cols-4">
            {RESULTS.map((r) => (
              <motion.div key={r.label} variants={rise} className="bg-surface/60 px-6 py-8 text-center backdrop-blur sm:text-left">
                <div className="font-heading text-4xl font-bold text-primary sm:text-5xl">
                  <Counter end={r.end} suffix={r.suffix || ""} decimals={r.decimals || 0} />
                </div>
                <div className="mt-1 text-xs uppercase tracking-wider text-muted-foreground">{r.label}</div>
              </motion.div>
            ))}
          </motion.div>
        </div>
      </section>

      {/* ── Product lifecycle (glowing path) ──────────────────────────── */}
      <section id="lifecycle" className="relative overflow-hidden scroll-mt-24 bg-background py-14 text-foreground md:py-20">
        <div className="pointer-events-none absolute right-0 top-1/4 h-[26rem] w-[32rem] rounded-full bg-accent/[0.06] blur-[150px]" />
        <div className="container relative">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="mx-auto max-w-2xl text-center">
            <span className="font-heading text-sm font-semibold text-primary">The journey</span>
            <h2 className="mt-2 font-heading text-3xl font-bold tracking-tight sm:text-4xl">From idea to scale — the full arc.</h2>
          </motion.div>

          <div ref={timelineRef} className="relative mt-14">
            {/* static track */}
            <div className="absolute bottom-0 left-[19px] top-0 w-px bg-border md:left-1/2 md:-translate-x-1/2" />
            {/* glowing beam — fills as you scroll the section */}
            <motion.div
              style={{ height: beamHeight }}
              className="absolute left-[19px] top-0 w-px bg-gradient-to-b from-primary via-primary to-accent shadow-[0_0_16px_3px_rgb(var(--primary)/0.5)] md:left-1/2 md:-translate-x-1/2"
            >
              <span className="absolute -bottom-1 left-1/2 h-2.5 w-2.5 -translate-x-1/2 rounded-full bg-accent shadow-[0_0_12px_3px_rgb(var(--accent)/0.7)]" />
            </motion.div>
            <div className="space-y-6 md:space-y-0">
              {LIFECYCLE.map((s, i) => {
                const isLeft = i % 2 === 0;
                return (
                  <div key={s.t} className="relative md:grid md:grid-cols-2 md:py-3">
                    {/* node on the path — outer span owns the centering
                        transform; inner motion span owns the scale-in (framer's
                        transform would otherwise clobber the centering) */}
                    <span className="absolute left-[19px] top-3 z-10 -translate-x-1/2 md:left-1/2 md:top-1/2 md:-translate-y-1/2">
                      <motion.span
                        initial={{ scale: 0, opacity: 0 }}
                        whileInView={{ scale: 1, opacity: 1 }}
                        viewport={{ once: true, amount: 0.6 }}
                        transition={{ duration: 0.4, ease: EASE }}
                        className="flex h-10 w-10 items-center justify-center rounded-full border border-primary/40 bg-background font-heading text-xs font-bold text-primary shadow-[0_0_18px_3px_rgb(var(--primary)/0.4)]"
                      >
                        {String(i + 1).padStart(2, "0")}
                      </motion.span>
                    </span>

                    {/* card — fills its half and slides in from its side */}
                    <motion.div
                      initial={{ opacity: 0, x: isLeft ? -48 : 48 }}
                      whileInView={{ opacity: 1, x: 0 }}
                      viewport={{ once: true, amount: 0.5 }}
                      transition={{ duration: 0.6, ease: EASE }}
                      className={
                        "ml-16 rounded-2xl border border-border bg-surface/60 p-6 transition-colors duration-300 hover:border-primary/40 md:ml-0 " +
                        (isLeft
                          ? "md:col-start-1 md:mr-12 md:text-right"
                          : "md:col-start-2 md:ml-12")
                      }
                    >
                      <span className="font-heading text-xs font-semibold uppercase tracking-wider text-primary">
                        Step {String(i + 1).padStart(2, "0")}
                      </span>
                      <h3 className="mt-1 font-heading text-lg font-semibold">{s.t}</h3>
                      <p className="mt-1 text-sm leading-relaxed text-muted-foreground">{s.d}</p>
                    </motion.div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </section>

      {/* ── Featured work (mockup) ────────────────────────────────────── */}
      <section className="relative bg-background py-14 text-foreground md:py-20">
        <div className="container">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.4 }} className="mb-10">
            <span className="font-heading text-sm font-semibold text-primary">Featured work</span>
            <h2 className="mt-2 font-heading text-3xl font-bold tracking-tight sm:text-4xl">A product we shipped.</h2>
          </motion.div>

          <div className="grid items-center gap-12 lg:grid-cols-2 lg:gap-16">
            <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.3 }}>
              <BrowserFrame>
                <div className="relative aspect-[16/10]">
                  <Image src={work.image} alt={work.title} fill sizes="(min-width:1024px) 40vw, 100vw" className="object-cover" />
                </div>
              </BrowserFrame>
            </motion.div>

            <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.3 }}>
              <motion.h3 variants={rise} className="font-heading text-2xl font-bold sm:text-3xl">{work.title}</motion.h3>
              <motion.div variants={rise} className="mt-5">
                <span className="text-xs font-semibold uppercase tracking-wider text-primary">Challenge</span>
                <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{work.challenge}</p>
              </motion.div>
              <motion.div variants={rise} className="mt-4">
                <span className="text-xs font-semibold uppercase tracking-wider text-primary">Solution</span>
                <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{work.solution}</p>
              </motion.div>
              <motion.div variants={rise} className="mt-6 grid grid-cols-3 gap-4 border-y border-border py-5">
                {work.results.map((r) => (
                  <div key={r.label}>
                    <div className="font-heading text-2xl font-bold text-primary">
                      <Counter end={r.end} prefix={r.prefix || ""} suffix={r.suffix || ""} decimals={r.decimals || 0} />
                    </div>
                    <div className="mt-0.5 text-[11px] leading-tight text-muted-foreground">{r.label}</div>
                  </div>
                ))}
              </motion.div>
              <motion.div variants={rise} className="mt-5 flex flex-wrap gap-2">
                {work.tech.map((t) => (
                  <span key={t} className="rounded-full border border-border bg-muted px-3 py-1 text-xs text-muted-foreground">{t}</span>
                ))}
              </motion.div>
              <motion.div variants={rise}>
                <Link href="/portfolio" className="group mt-6 inline-flex items-center gap-2 text-sm font-semibold text-primary">
                  View the full case study
                  <ArrowRight className="h-4 w-4 transition-transform duration-300 group-hover:translate-x-0.5" />
                </Link>
              </motion.div>
            </motion.div>
          </div>
        </div>
      </section>

      {/* ── Capabilities (interactive selector) ───────────────────────── */}
      <section className="relative overflow-hidden bg-background py-14 text-foreground md:py-20">
        <div className="pointer-events-none absolute -left-24 top-1/4 h-[24rem] w-[30rem] rounded-full bg-primary/[0.06] blur-[150px]" />
        <div className="container relative">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="max-w-2xl">
            <span className="font-heading text-sm font-semibold text-primary">Capabilities</span>
            <h2 className="mt-2 font-heading text-3xl font-bold tracking-tight sm:text-4xl">
              Everything {service.title.toLowerCase()} covers.
            </h2>
            <p className="mt-4 max-w-md text-base leading-relaxed text-muted-foreground">
              Hover a capability to explore what&apos;s included — each one delivered end to end
              by a senior team that owns the outcome.
            </p>
          </motion.div>

          <div className="mt-10 grid gap-6 lg:grid-cols-2 lg:gap-12">
            {/* Selectable list */}
            <motion.ul variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.2 }} className="space-y-2">
              {capabilities.map((c, i) => {
                const active = i === activeCap;
                return (
                  <motion.li key={c.title} variants={rise}>
                    <button
                      type="button"
                      onMouseEnter={() => setActiveCap(i)}
                      onFocus={() => setActiveCap(i)}
                      onClick={() => setActiveCap(i)}
                      className={
                        "flex w-full items-center gap-5 rounded-2xl border px-5 py-4 text-left transition-all duration-300 " +
                        (active ? "border-primary/40 bg-surface" : "border-border/60 bg-surface/30 hover:border-border")
                      }
                    >
                      <span
                        className={
                          "flex h-11 w-11 shrink-0 items-center justify-center rounded-xl font-heading text-sm font-bold transition-colors duration-300 " +
                          (active ? "bg-primary text-primary-foreground" : "bg-primary/10 text-primary")
                        }
                      >
                        {String(i + 1).padStart(2, "0")}
                      </span>
                      <span
                        className={
                          "flex-1 font-heading text-lg font-semibold leading-snug transition-colors duration-300 " +
                          (active ? "text-primary" : "text-foreground")
                        }
                      >
                        {c.title}
                      </span>
                      <ArrowRight
                        className={
                          "h-5 w-5 shrink-0 transition-all duration-300 " +
                          (active ? "-rotate-45 text-primary" : "text-muted-foreground")
                        }
                      />
                    </button>
                  </motion.li>
                );
              })}
            </motion.ul>

            {/* Detail panel */}
            <motion.div
              variants={rise}
              initial="hidden"
              whileInView="show"
              viewport={{ once: true, amount: 0.2 }}
              className="relative min-h-[22rem] overflow-hidden rounded-3xl border border-border lg:sticky lg:top-28"
            >
              <Image src={heroImage} alt={service.title} fill sizes="(min-width:1024px) 40vw, 100vw" className="object-cover" />
              <span className="absolute inset-0 bg-gradient-to-t from-background via-background/85 to-background/40" />
              <div className="relative flex h-full min-h-[22rem] flex-col justify-end p-8">
                <AnimatePresence mode="wait">
                  <motion.div
                    key={activeCap}
                    initial={{ opacity: 0, y: 16 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -16 }}
                    transition={{ duration: 0.35, ease: EASE }}
                  >
                    <span className="font-heading text-6xl font-bold text-primary/30">
                      {String(activeCap + 1).padStart(2, "0")}
                    </span>
                    <h3 className="mt-2 font-heading text-2xl font-semibold sm:text-3xl">
                      {capabilities[activeCap].title}
                    </h3>
                    <p className="mt-3 max-w-md text-sm leading-relaxed text-foreground/80">
                      {capabilities[activeCap].desc ||
                        "Delivered end to end by a senior team that owns the outcome — from first plan to ongoing care."}
                    </p>
                  </motion.div>
                </AnimatePresence>
              </div>
            </motion.div>
          </div>
        </div>
      </section>

      {/* ── Signature: system flow (varies per service) ──────────────── */}
      <section className="relative overflow-hidden bg-background py-16 text-foreground md:py-24">
        <div className="pointer-events-none absolute left-1/2 top-1/2 h-[26rem] w-[46rem] -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary/[0.08] blur-[150px]" />
        <div className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-border to-transparent" />
        <div className="container relative">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="mx-auto max-w-2xl text-center">
            <span className="inline-flex items-center gap-2 rounded-full border border-primary/30 bg-primary/10 px-4 py-1.5 text-xs font-semibold uppercase tracking-wider text-primary backdrop-blur">
              <Sparkles className="h-3.5 w-3.5" />
              {signature.label}
            </span>
            <h2 className="mt-5 font-heading text-3xl font-bold tracking-tight sm:text-4xl md:text-5xl">{signature.heading}</h2>
            <p className="mt-4 text-sm leading-relaxed text-muted-foreground sm:text-base">{signature.blurb}</p>
          </motion.div>

          <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.2 }} className="relative mt-16 grid gap-10 sm:grid-cols-2 md:grid-cols-5 md:gap-4">
            {/* connector line with a travelling light (desktop) */}
            <div className="absolute left-0 right-0 top-8 hidden h-px overflow-hidden bg-gradient-to-r from-primary/40 via-primary/20 to-accent/40 md:block">
              <span className="absolute inset-y-0 left-0 w-1/4 animate-beam bg-gradient-to-r from-transparent via-primary to-transparent" />
            </div>

            {signature.stages.map((stage, i) => (
              <motion.div key={stage} variants={rise} className="relative flex flex-col items-center text-center">
                <span className="relative z-10 flex h-16 w-16 items-center justify-center rounded-2xl border border-primary/30 bg-surface/70 shadow-[0_0_24px_-6px_rgb(var(--primary)/0.6)] backdrop-blur">
                  <span className="relative flex h-3.5 w-3.5">
                    <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary opacity-60" />
                    <span className="relative inline-flex h-3.5 w-3.5 rounded-full bg-gradient-to-br from-primary to-accent" />
                  </span>
                </span>
                <span className="mt-4 font-heading text-[11px] font-semibold uppercase tracking-wider text-primary">
                  {String(i + 1).padStart(2, "0")}
                </span>
                <h3 className="mt-1 font-heading text-sm font-semibold leading-snug">{stage}</h3>
              </motion.div>
            ))}
          </motion.div>
        </div>
      </section>

      {/* ── Technology ecosystem (marquee) ────────────────────────────── */}
      <section className="relative overflow-hidden bg-background py-14 text-foreground md:py-20">
        <div className="pointer-events-none absolute left-1/2 top-1/2 h-[22rem] w-[42rem] -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary/[0.05] blur-[150px]" />
        <div className="container relative">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="mx-auto max-w-2xl text-center">
            <span className="font-heading text-sm font-semibold text-primary">Technology ecosystem</span>
            <h2 className="mt-2 font-heading text-3xl font-bold tracking-tight sm:text-4xl">A modern stack, chosen to fit.</h2>
          </motion.div>
        </div>
        <div className="relative mt-12 space-y-4">
          <TechBelt items={service.technologies?.length ? [...service.technologies, ...ECOSYSTEM_A] : ECOSYSTEM_A} />
          <TechBelt items={ECOSYSTEM_B} reverse />
        </div>
      </section>

      {/* ── Industries (icon-card grid) ───────────────────────────────── */}
      <section className="relative bg-background py-14 text-foreground md:py-20">
        <div className="container">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
            <div>
              <span className="font-heading text-sm font-semibold text-primary">Industries</span>
              <h2 className="mt-2 font-heading text-3xl font-bold tracking-tight sm:text-4xl">Domain expertise that shows.</h2>
            </div>
            <p className="max-w-sm text-sm leading-relaxed text-muted-foreground">
              We&apos;ve shipped across regulated, high-stakes industries — so we arrive already
              fluent in your domain.
            </p>
          </motion.div>

          <motion.div
            variants={container}
            initial="hidden"
            whileInView="show"
            viewport={{ once: true, amount: 0.1 }}
            className="mt-10 grid grid-cols-2 gap-px overflow-hidden rounded-3xl border border-border bg-border sm:grid-cols-3 lg:grid-cols-4"
          >
            {INDUSTRIES.map(({ name, Icon: IIcon }) => (
              <motion.div
                key={name}
                variants={rise}
                className="group relative flex items-center gap-4 bg-background px-6 py-8 transition-colors duration-300 hover:bg-surface"
              >
                {/* top accent line on hover */}
                <span className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100" />
                <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary transition-all duration-300 group-hover:scale-105 group-hover:bg-primary group-hover:text-primary-foreground">
                  <IIcon className="h-5 w-5" />
                </span>
                <h3 className="font-heading text-base font-semibold leading-tight">{name}</h3>
              </motion.div>
            ))}
          </motion.div>
        </div>
      </section>

      {/* ── Why Cerkel ────────────────────────────────────────────────── */}
      <section className="relative bg-background py-14 text-foreground md:py-20">
        <div className="container">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="max-w-2xl">
            <span className="font-heading text-sm font-semibold text-primary">Why Cerkel</span>
            <h2 className="mt-2 font-heading text-3xl font-bold tracking-tight sm:text-4xl">A partner you can build on.</h2>
          </motion.div>
          <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.15 }} className="mt-10 grid gap-4 md:grid-cols-3">
            {BENEFITS.map(({ Icon: BIcon, title, desc }) => (
              <motion.div key={title} variants={rise} className="group rounded-2xl border border-border bg-surface/60 p-7 transition-colors duration-300 hover:border-primary/40">
                <span className="flex h-12 w-12 items-center justify-center rounded-xl border border-primary/25 bg-primary/10 text-primary transition-colors duration-300 group-hover:bg-primary group-hover:text-primary-foreground"><BIcon className="h-5 w-5" /></span>
                <h3 className="mt-5 font-heading text-lg font-semibold">{title}</h3>
                <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{desc}</p>
              </motion.div>
            ))}
          </motion.div>
        </div>
      </section>

      {/* ── Success stories (carousel) ────────────────────────────────── */}
      <section className="relative overflow-hidden bg-background py-14 text-foreground md:py-20">
        <div className="pointer-events-none absolute -left-24 top-1/3 h-[24rem] w-[30rem] rounded-full bg-primary/[0.06] blur-[150px]" />
        <div className="container relative">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="mx-auto max-w-2xl text-center">
            <span className="inline-flex items-center gap-2 rounded-full border border-border bg-surface/60 px-4 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground backdrop-blur">
              <span className="h-1.5 w-1.5 rounded-full bg-primary" /> Success stories
            </span>
            <h2 className="mt-5 font-heading text-3xl font-bold tracking-tight sm:text-4xl">Proof, not promises.</h2>
          </motion.div>

          <div
            className="relative mt-12"
            onMouseEnter={() => setStoryPaused(true)}
            onMouseLeave={() => setStoryPaused(false)}
          >
            <AnimatePresence mode="wait">
              <motion.div
                key={storyIdx}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                transition={{ duration: 0.4, ease: EASE }}
                className="grid gap-4 lg:grid-cols-2"
              >
                {/* Results card */}
                <div className="relative flex min-h-[24rem] flex-col justify-end overflow-hidden rounded-3xl border border-border p-8">
                  <Image src={story.image} alt="" fill sizes="(min-width:1024px) 45vw, 100vw" className="object-cover" />
                  <span className="absolute inset-0 bg-gradient-to-t from-background via-background/85 to-background/30" />
                  <span className="absolute left-6 top-6 inline-flex items-center gap-1.5 rounded-full border border-primary/40 bg-background/60 px-3 py-1 text-[11px] font-semibold uppercase tracking-wider text-primary backdrop-blur">
                    <Sparkles className="h-3.5 w-3.5" />
                    Success story
                  </span>
                  <div className="relative">
                    <h3 className="font-heading text-xl font-semibold leading-snug drop-shadow-[0_2px_16px_rgba(0,0,0,0.7)] sm:text-2xl">
                      {story.result}
                    </h3>
                    <p className="mt-2 max-w-md text-sm leading-relaxed text-foreground/80">{story.summary}</p>
                    <div className="mt-5 flex items-end gap-6 border-t border-white/15 pt-4">
                      {story.metrics.map((m) => (
                        <div key={m.label}>
                          <div className="font-heading text-xl font-bold text-primary sm:text-2xl">{m.value}</div>
                          <div className="mt-0.5 text-[11px] leading-tight text-foreground/70">{m.label}</div>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>

                {/* Quote card */}
                <div className="flex flex-col justify-between rounded-3xl border border-border bg-surface/60 p-8 sm:p-10">
                  <div>
                    <span className="font-heading text-5xl leading-none text-primary/40">“</span>
                    <blockquote className="-mt-3 font-heading text-lg font-medium leading-relaxed text-foreground sm:text-2xl">
                      {story.quote}
                    </blockquote>
                  </div>
                  <footer className="mt-8 flex items-center gap-3 border-t border-border/70 pt-5">
                    <span className="flex h-12 w-12 items-center justify-center rounded-full bg-gradient-to-br from-primary to-accent font-heading text-sm font-bold text-primary-foreground">
                      {initials(story.name)}
                    </span>
                    <span className="min-w-0">
                      <span className="block font-heading text-sm font-semibold">{story.name}</span>
                      <span className="block truncate text-xs text-muted-foreground">{story.role}</span>
                    </span>
                    <Stars className="ml-auto h-4 w-4" />
                  </footer>
                </div>
              </motion.div>
            </AnimatePresence>

            {/* Controls */}
            <div className="mt-8 flex items-center justify-center gap-6">
              <button
                onClick={prevStory}
                aria-label="Previous story"
                className="flex h-11 w-11 items-center justify-center rounded-full border border-border text-foreground transition-colors duration-300 hover:border-primary hover:text-primary"
              >
                <ArrowRight className="h-4 w-4 rotate-180" />
              </button>
              <div className="flex gap-2">
                {STORIES.map((_, i) => (
                  <button
                    key={i}
                    onClick={() => setStoryIdx(i)}
                    aria-label={`Go to story ${i + 1}`}
                    className={
                      "h-1.5 rounded-full transition-all duration-300 " +
                      (i === storyIdx ? "w-7 bg-primary" : "w-3 bg-foreground/25 hover:bg-foreground/50")
                    }
                  />
                ))}
              </div>
              <button
                onClick={nextStory}
                aria-label="Next story"
                className="flex h-11 w-11 items-center justify-center rounded-full border border-border text-foreground transition-colors duration-300 hover:border-primary hover:text-primary"
              >
                <ArrowRight className="h-4 w-4" />
              </button>
            </div>
          </div>
        </div>
      </section>

      {/* ── FAQ (shared home-page design) ─────────────────────────────── */}
      <Faq items={faqs} subtitle={`The things teams usually ask before a ${service.title.toLowerCase()} project.`} />

      {/* ── Related services ──────────────────────────────────────────── */}
      {related?.length > 0 && (
        <section className="relative bg-background py-14 text-foreground md:py-20">
          <div className="container">
            <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="flex items-end justify-between gap-4">
              <h2 className="font-heading text-3xl font-bold tracking-tight sm:text-4xl">Related services</h2>
              <Link href="/services" className="group hidden items-center gap-1.5 text-sm font-semibold text-primary sm:inline-flex">
                View all <ArrowRight className="h-4 w-4 transition-transform duration-300 group-hover:translate-x-0.5" />
              </Link>
            </motion.div>
            <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.15 }} className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {related.map((r) => (
                <motion.div key={r.slug} variants={rise} className="h-full">
                  <Link href={`/services/${r.slug}`} className="group flex h-full flex-col rounded-2xl border border-border bg-surface/60 p-6 transition-all duration-300 hover:-translate-y-1 hover:border-primary/50 hover:bg-surface">
                    <div className="flex items-start justify-between gap-3">
                      <h3 className="font-heading text-lg font-semibold text-foreground transition-colors duration-300 group-hover:text-primary">{r.name}</h3>
                      <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border text-muted-foreground transition-all duration-300 group-hover:-rotate-45 group-hover:border-primary group-hover:bg-primary group-hover:text-primary-foreground"><ArrowRight className="h-4 w-4" /></span>
                    </div>
                    {r.description && <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{r.description}</p>}
                  </Link>
                </motion.div>
              ))}
            </motion.div>
          </div>
        </section>
      )}

      {/* ── CTA ───────────────────────────────────────────────────────── */}
      <section className="relative overflow-hidden bg-background pb-16 md:pb-24">
        <div className="container">
          <div className="relative overflow-hidden rounded-3xl bg-gradient-to-br from-primary via-primary to-accent p-8 sm:p-14">
            <div className="pointer-events-none absolute -right-10 -top-10 h-56 w-56 rounded-full bg-white/10 blur-2xl" />
            <div className="relative max-w-2xl">
              <h2 className="font-heading text-3xl font-bold leading-tight tracking-tight text-background sm:text-5xl">{ctaTagline}</h2>
              <p className="mt-4 max-w-xl text-base leading-relaxed text-background/80">Tell us where you are and where you want to be. We&apos;ll map the fastest, safest path to get there.</p>
              <Link href="/contact" className="group mt-8 inline-flex items-center gap-2.5 rounded-full bg-background px-7 py-3.5 text-sm font-semibold text-foreground shadow-xl shadow-black/25 transition-all duration-300 hover:-translate-y-0.5">
                Start a project
                <span className="flex h-7 w-7 items-center justify-center rounded-full bg-primary text-primary-foreground transition-transform duration-300 group-hover:translate-x-0.5"><ArrowRight className="h-3.5 w-3.5" /></span>
              </Link>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}
