"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { AnimatePresence, motion } from "framer-motion";
import { useInView } from "react-intersection-observer";
import { ArrowRight, Code, Sparkles, categoryIcons } from "@/components/ui/icons";
import { serviceCategories } from "@/data/services";

/**
 * Services catalog — a sticky scroll-spy index (left) paired with rich,
 * elevated service cards (right). The index highlights the category currently
 * in view and smooth-scrolls to any category on click; on mobile it collapses
 * to a horizontal quick-jump pill row. Brand-strict: dark surfaces, orange/gold
 * accents, Google Sans, scroll-reveal matching the home sections.
 */
const EASE = [0.21, 0.47, 0.32, 0.98];

const container = { hidden: {}, show: { transition: { staggerChildren: 0.07 } } };
const rise = {
  hidden: { opacity: 0, y: 28 },
  show: { opacity: 1, y: 0, transition: { duration: 0.55, ease: EASE } },
};

/* Short social-proof blurbs for the sticky rail. Swap with real client
   quotes; the full video testimonials live on the home page. */
const REVIEWS = [
  {
    quote: "From whiteboard sketch to a live product in fourteen weeks — and it hasn't missed a beat since.",
    name: "Priya Sharma",
    role: "Founder, Fintech startup",
    metric: "14 wks to launch",
  },
  {
    quote: "They think like owners — challenged our roadmap where it mattered and shipped exactly what users needed.",
    name: "Daniel Reyes",
    role: "Product Lead, SaaS",
    metric: "2.4× activation",
  },
  {
    quote: "Our AI assistant now handles half our support volume. Cerkel made the complex feel simple.",
    name: "Aisha Khan",
    role: "COO, Logistics platform",
    metric: "−50% tickets",
  },
];

/* One success story per capability area, keyed by category slug. Swap the
   copy/metrics/images with real case studies; link points to the portfolio
   for now. Images are existing optimized assets in /public/images/opt. */
const SUCCESS_STORIES = {
  "game-development": {
    image: "/images/opt/HeroBanner1.webp",
    client: "Game studio",
    industry: "Gaming · Multiplayer Development",
    result: "Launched a cross-platform multiplayer game to 1M+ players.",
    summary: "Built in Unity with low-latency netcode and live ops, shipping to mobile and PC from one codebase.",
    metrics: [
      { value: "1M+", label: "players" },
      { value: "60 FPS", label: "on mobile" },
      { value: "4.7★", label: "store rating" },
    ],
    quote:
      "They nailed the feel of the game and the netcode held up on launch day. Players noticed — and stayed.",
    person: { name: "Marcus Hale", role: "Studio Lead · Gaming" },
  },
  "data-analytics-ai": {
    image: "/images/opt/HeroBanner3.png",
    client: "Retail group",
    industry: "Retail · Data Analytics & AI",
    result: "Turned scattered data into AI-driven decisions leadership trusts.",
    summary: "Unified pipelines into a single source of truth, then layered ML forecasting that lifted conversion.",
    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 the forecasts are right.",
    person: { name: "Sara Whitman", role: "CMO · Retail group" },
  },
  "web-software-development": {
    image: "/images/opt/HeroBanner1.webp",
    client: "Fintech startup",
    industry: "Finance · Web & Software Development",
    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: "99.9%", label: "uptime" },
      { value: "4.8★", label: "app rating" },
    ],
    quote:
      "Cerkel took us from a whiteboard sketch to a live product in fourteen weeks — and it hasn't missed a beat since.",
    person: { name: "Priya Sharma", role: "Founder · Fintech startup" },
  },
  "media-creative": {
    image: "/images/opt/Pillar1.webp",
    client: "Consumer brand",
    industry: "Brand · Media & Creative",
    result: "Tripled engagement with a full rebrand and launch content.",
    summary: "Delivered identity, motion system and social creatives, rolled out consistently across every channel.",
    metrics: [
      { value: "3.1×", label: "engagement" },
      { value: "+48%", label: "reach" },
      { value: "12", label: "channels unified" },
    ],
    quote:
      "Our brand finally looks the way it should — and the launch content performed better than anything we'd run.",
    person: { name: "Sara Whitman", role: "CMO · Consumer brand" },
  },
};

function Stars({ className = "h-3.5 w-3.5" }) {
  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>
  );
}

/** Auto-rotating client review card — fills the sticky rail beneath the index. */
function CatalogReview() {
  const [i, setI] = useState(0);
  const r = REVIEWS[i];

  useEffect(() => {
    const id = setTimeout(() => setI((p) => (p + 1) % REVIEWS.length), 6000);
    return () => clearTimeout(id);
  }, [i]);

  return (
    <div className="mt-8 rounded-2xl border border-border bg-surface/60 p-5 backdrop-blur">
      <div className="flex items-center justify-between">
        <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
          What clients say
        </span>
        <Stars />
      </div>

      <div className="relative mt-4 min-h-[8.5rem]">
        <AnimatePresence mode="wait">
          <motion.blockquote
            key={i}
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            transition={{ duration: 0.4, ease: EASE }}
          >
            <span className="inline-block rounded-full border border-primary/30 bg-primary/10 px-2.5 py-0.5 text-[11px] font-semibold text-primary">
              {r.metric}
            </span>
            <p className="mt-3 text-sm leading-relaxed text-foreground/90">“{r.quote}”</p>
            <footer className="mt-4 flex items-center gap-3">
              <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-primary to-accent font-heading text-[11px] font-bold text-primary-foreground">
                {r.name.split(" ").map((n) => n[0]).join("")}
              </span>
              <span className="min-w-0">
                <span className="block truncate font-heading text-sm font-semibold text-foreground">
                  {r.name}
                </span>
                <span className="block truncate text-xs text-muted-foreground">{r.role}</span>
              </span>
            </footer>
          </motion.blockquote>
        </AnimatePresence>
      </div>

      <div className="mt-4 flex gap-1.5">
        {REVIEWS.map((_, idx) => (
          <button
            key={idx}
            onClick={() => setI(idx)}
            aria-label={`Show review ${idx + 1}`}
            className={
              "h-1.5 rounded-full transition-all duration-300 " +
              (idx === i ? "w-6 bg-primary" : "w-1.5 bg-foreground/25 hover:bg-foreground/50")
            }
          />
        ))}
      </div>
    </div>
  );
}

/** Smooth, header-offset-aware jump (falls back to native if Lenis is absent). */
function scrollToCategory(e, slug) {
  e.preventDefault();
  const el = document.getElementById(slug);
  if (!el) return;
  if (window.lenis) window.lenis.scrollTo(el, { offset: -104 });
  else el.scrollIntoView({ behavior: "smooth" });
}

/** One catalog block; reports itself active to the index when centered. */
function CategoryBlock({ category, index, onActive }) {
  const Icon = categoryIcons[category.slug] ?? Code;
  const no = String(index + 1).padStart(2, "0");
  const story = SUCCESS_STORIES[category.slug];
  const { ref } = useInView({
    rootMargin: "-45% 0px -50% 0px",
    onChange: (inView) => inView && onActive(index),
  });

  return (
    <section ref={ref} id={category.slug} className="scroll-mt-28">
      {/* Header */}
      <motion.div
        variants={rise}
        initial="hidden"
        whileInView="show"
        viewport={{ once: true, amount: 0.5 }}
        className="flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between"
      >
        <div className="flex items-center gap-4">
          <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>
          <div>
            <span className="font-heading text-xs font-semibold tracking-wider text-primary">
              {no} / {String(serviceCategories.length).padStart(2, "0")}
            </span>
            <h2 className="font-heading text-2xl font-semibold leading-snug sm:text-3xl">
              {category.title}
            </h2>
          </div>
        </div>
        <p className="max-w-md text-sm leading-relaxed text-muted-foreground">
          {category.description}
        </p>
      </motion.div>

      <div className="mt-5 h-px w-full bg-gradient-to-r from-border via-border to-transparent" />

      {/* Cards */}
      <motion.div
        variants={container}
        initial="hidden"
        whileInView="show"
        viewport={{ once: true, amount: 0.1 }}
        className="mt-6 grid gap-4 sm:grid-cols-2 xl:grid-cols-3"
      >
        {category.services.map((s) => (
          <motion.div key={s.slug} variants={rise} className="h-full">
            <Link
              href={`/services/${s.slug}`}
              className="group relative flex h-full flex-col overflow-hidden 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"
            >
              {/* top accent line + corner sheen on hover */}
              <span className="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
                aria-hidden="true"
                className="pointer-events-none absolute -right-12 -top-12 h-36 w-36 rounded-full bg-primary/15 opacity-0 blur-2xl transition-opacity duration-500 group-hover:opacity-100"
              />

              <div className="relative 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">
                  {s.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>

              {s.description && (
                <p className="relative mt-2 text-sm leading-relaxed text-muted-foreground">
                  {s.description}
                </p>
              )}

              {s.children?.length > 0 && (
                <ul className="relative mt-4 flex flex-wrap gap-2">
                  {s.children.map((c) => (
                    <li
                      key={c.slug}
                      className="rounded-full border border-border bg-muted px-2.5 py-1 text-xs text-muted-foreground transition-colors duration-300 group-hover:border-primary/30"
                    >
                      {c.name}
                    </li>
                  ))}
                </ul>
              )}
            </Link>
          </motion.div>
        ))}
      </motion.div>

      {/* Success story — image-backed results card + client quote card */}
      {story && (
        <motion.div
          variants={rise}
          initial="hidden"
          whileInView="show"
          viewport={{ once: true, amount: 0.25 }}
          className="mt-6 grid gap-4 lg:grid-cols-2"
        >
          {/* Results card (image background) */}
          <Link
            href="/portfolio"
            className="group/story relative flex min-h-[20rem] flex-col justify-end overflow-hidden rounded-2xl border border-border p-6 sm:p-8"
          >
            <Image
              src={story.image}
              alt=""
              fill
              sizes="(min-width: 1024px) 40vw, 100vw"
              className="object-cover transition-transform duration-700 group-hover/story:scale-105"
            />
            <span className="pointer-events-none absolute inset-0 bg-gradient-to-t from-background via-background/80 to-background/20" />
            <span className="pointer-events-none absolute inset-0 bg-gradient-to-r from-background/70 to-transparent" />

            <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 text-foreground 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>

              <span className="mt-5 inline-flex items-center gap-2 text-sm font-semibold text-primary">
                View success story
                <span className="flex h-7 w-7 items-center justify-center rounded-full border border-primary/40 transition-all duration-300 group-hover/story:-rotate-45 group-hover/story:bg-primary group-hover/story:text-primary-foreground">
                  <ArrowRight className="h-3.5 w-3.5" />
                </span>
              </span>
            </div>
          </Link>

          {/* Quote card */}
          <div className="flex flex-col justify-between rounded-2xl border border-border bg-surface/60 p-6 sm:p-8">
            <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-xl">
                {story.quote}
              </blockquote>
            </div>

            <footer className="mt-6 flex items-center gap-3 border-t border-border/70 pt-5">
              <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-primary to-accent font-heading text-sm font-bold text-primary-foreground">
                {story.person.name.split(" ").map((w) => w[0]).join("").slice(0, 2)}
              </span>
              <span className="min-w-0">
                <span className="block font-heading text-sm font-semibold text-foreground">
                  {story.person.name}
                </span>
                <span className="block truncate text-xs text-muted-foreground">
                  {story.person.role}
                </span>
              </span>
              <Stars className="ml-auto h-4 w-4" />
            </footer>
          </div>
        </motion.div>
      )}
    </section>
  );
}

export default function ServicesCatalog() {
  const [active, setActive] = useState(0);

  return (
    <section
      id="catalog"
      className="relative scroll-mt-24 overflow-x-clip bg-background py-16 text-foreground md:py-24"
    >
      <div className="pointer-events-none absolute left-1/2 top-1/4 h-[30rem] w-[46rem] -translate-x-1/2 rounded-full bg-primary/[0.06] blur-[160px]" />

      <div className="container relative">
        {/* Mobile quick-jump pills */}
        <div className="-mx-4 mb-10 flex gap-2 overflow-x-auto px-4 pb-2 lg:hidden [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
          {serviceCategories.map((c, i) => (
            <a
              key={c.slug}
              href={`#${c.slug}`}
              onClick={(e) => scrollToCategory(e, c.slug)}
              className={
                "shrink-0 rounded-full border px-4 py-2 text-xs font-medium transition-colors duration-300 " +
                (active === i
                  ? "border-primary/50 bg-primary/10 text-primary"
                  : "border-border bg-surface/60 text-muted-foreground")
              }
            >
              {c.title}
            </a>
          ))}
        </div>

        <div className="grid gap-10 lg:grid-cols-[16rem_1fr] lg:gap-16">
          {/* Sticky scroll-spy index (desktop) */}
          <aside className="hidden lg:block">
            <div className="sticky top-28">
              <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                Browse by capability
              </span>
              <nav className="mt-5 space-y-1">
                {serviceCategories.map((c, i) => {
                  const isActive = active === i;
                  return (
                    <a
                      key={c.slug}
                      href={`#${c.slug}`}
                      onClick={(e) => scrollToCategory(e, c.slug)}
                      className={
                        "group flex items-center gap-3 rounded-xl border px-3.5 py-3 transition-all duration-300 " +
                        (isActive
                          ? "border-primary/40 bg-surface"
                          : "border-transparent hover:bg-surface/50")
                      }
                    >
                      <span
                        className={
                          "flex h-7 w-7 shrink-0 items-center justify-center rounded-md font-heading text-[11px] font-semibold transition-colors duration-300 " +
                          (isActive
                            ? "bg-primary text-primary-foreground"
                            : "bg-muted text-muted-foreground group-hover:text-foreground")
                        }
                      >
                        {String(i + 1).padStart(2, "0")}
                      </span>
                      <span
                        className={
                          "flex-1 font-heading text-sm font-medium leading-tight transition-colors duration-300 " +
                          (isActive ? "text-foreground" : "text-muted-foreground group-hover:text-foreground")
                        }
                      >
                        {c.title}
                      </span>
                      <span className="text-xs tabular-nums text-muted-foreground">
                        {c.services.length}
                      </span>
                    </a>
                  );
                })}
              </nav>

              <CatalogReview />
            </div>
          </aside>

          {/* Catalog */}
          <div className="space-y-16 md:space-y-24">
            {serviceCategories.map((c, i) => (
              <CategoryBlock key={c.slug} category={c} index={i} onActive={setActive} />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}
