/**
 * SERVICES PAGE — FULL REDESIGN
 * 
 * Matches the reference design layout while strictly following
 * Finjineers' locked design system (tokens, fonts, colors, animations).
 * 
 * Sections:
 * 1.  Hero — "OUR SERVICES"
 * 2.  Services Grid — Tabbed bento grid
 * 3.  Case Studies — Portfolio showcase (3 projects)
 * 4.  Mid-Page CTA — "Have a Great Idea?" (imported from Homepage)
 * 5.  Our Expertise — Auto-cycling domain chips + phone mockup
 * 6.  Why Finjineers + Testimonials
 * 7.  How We Work — 6-step process
 * 8.  Consultation CTA Banner
 * 9.  Tech Stack (bento layout)
 * 10. Final CTA — "Got a Project in Mind?" + "What Happens Next?"
 */

import { useRef, useState, useEffect } from "react";
import { motion, AnimatePresence, useInView } from "motion/react";
import { Link } from "react-router";
import teamImage from "figma:asset/22939b40b7751694b6fa87efec01230693a8f8ec.webp";
import whyImage from "figma:asset/ca905b480448e1b9c983f73e7a177d02d9eeffd4.webp";
import founderImage from "figma:asset/founder_haseeb.webp";
import founderTransparentImage from "figma:asset/founder_transparent.webp";
import serviceHeroImage from "figma:asset/service_feature_graphic.webp";
import {
  ArrowRight,
  ArrowUpRight,
  Calendar,
  Star,
  Linkedin,
  Mail,
} from "lucide-react";
import {
  typography,
  spacing,
  layout,
  backgrounds,
  borders,
  transitions,
  colors,
} from "@/app/utils/design-tokens";
import { easing, duration } from "@/app/utils/animations";
import { Button } from "@/app/components/ui/shared/Buttons";
import { ImageWithFallback } from "@/app/components/figma/ImageWithFallback";
import { optimizeUnsplashUrl, optimizeForSize } from "@/app/utils/image-utils";
import { useDocumentMeta } from "@/app/hooks/useDocumentMeta";
import { MidPageCTA } from "@/app/components/shared/MidPageCTA";
import { SectionHeader, GradientText } from "@/app/components/shared/SectionHeader";
import { TechStackSection } from "@/app/components/shared/TechStackSection";
import { externalUrls, contact, socialLinks } from "@/app/config/site";
import {
  startupsData,
  businessData,
  caseStudies,
  expertiseDomains,
  servicesTestimonials as testimonials,
  whyStatRows,
  workModels,
  whatHappensNext,
} from "@/app/data/services";
import { FinalCTASection } from "@/app/components/shared/FinalCTASection";

// ============================================================================
// SECTION: HERO
// ============================================================================

function ServicesHero() {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true });

  return (
    <section
      ref={ref}
      className="relative overflow-hidden"
      style={{ backgroundColor: colors.dark.warmDeep }}
    >
      {/* Background glow */}
      <div className="absolute inset-0 pointer-events-none">
        <div className="absolute top-1/4 right-1/4 w-[800px] h-[800px] blur-3xl bg-[radial-gradient(circle,rgba(241,95,61,0.06),transparent_60%)]" />
        <div className="absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-[#0d0b0a] to-transparent" />
      </div>

      <div className={`relative z-10 ${layout.section.standard} pt-32 pb-16 md:pt-40 md:pb-20 lg:pt-44 lg:pb-24`}>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={isInView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: duration.slower, ease: easing.smooth }}
            className="max-w-3xl"
          >
            <p className={`${typography.scale.small.size} uppercase tracking-wider text-gray-400 mb-4`}>
              What We Offer
            </p>
            <h1
              className="text-5xl md:text-6xl lg:text-7xl font-bold text-white uppercase leading-[1.05] tracking-tight mb-6"
              style={{ fontFamily: typography.fonts.heading }}
            >
              Our{" "}
              <span className="text-transparent bg-clip-text bg-gradient-to-r from-[#f15f3d] to-[#ff9575]">
                Services
              </span>
            </h1>
            <p className={`${typography.scale.subheadline.size} ${typography.scale.subheadline.color} max-w-xl mb-8`}>
              We craft enterprise-grade mobile and web applications that drive growth, 
              delight users, and scale with your ambition. From concept to launch and beyond.
            </p>

            <div className="flex items-center gap-4 flex-wrap">
              <Button variant="primary" size="large" href={externalUrls.calendly} magnetic>
                Book Free Call
                <Calendar className="w-4 h-4" />
              </Button>
              <Button variant="secondary" size="large" to="/work">
                View Portfolio
                <ArrowRight className="w-4 h-4" />
              </Button>
            </div>
          </motion.div>

          <motion.div
            initial={{ opacity: 0, scale: 0.9, x: 20 }}
            animate={isInView ? { opacity: 1, scale: 1, x: 0 } : {}}
            transition={{ duration: duration.slower, ease: easing.smooth, delay: 0.2 }}
            className="relative"
          >
            <ImageWithFallback
              src={serviceHeroImage}
              alt="Finjineers Services"
              className="w-full h-auto"
            />
          </motion.div>
        </div>
      </div>
    </section>
  );
}

// ============================================================================
// SECTION: SERVICES GRID
// ============================================================================

// — Detail card component (title + arrow + description)
function DetailCard({
  title,
  description,
  delay: delayMs,
  isInView,
}: {
  title: string;
  description: string;
  delay: number;
  isInView: boolean;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={isInView ? { opacity: 1, y: 0 } : {}}
      transition={{ delay: delayMs, duration: duration.slow, ease: easing.smooth }}
      className="group relative rounded-[20px] bg-white/[0.03] border border-white/[0.06] p-6 lg:p-7 hover:border-white/[0.12] hover:bg-white/[0.04] transition-all duration-300 cursor-pointer h-full flex flex-col"
    >
      <div className="flex items-start justify-between gap-4 mb-4">
        <h3
          className="text-xl lg:text-2xl font-bold text-white"
          style={{ fontFamily: typography.fonts.heading }}
        >
          {title}
        </h3>
        <div className="w-8 h-8 rounded-full border border-white/[0.1] flex items-center justify-center shrink-0 group-hover:border-[#f15f3d]/40 group-hover:bg-[#f15f3d]/10 transition-all duration-300">
          <ArrowUpRight className="w-4 h-4 text-gray-400 group-hover:text-[#f15f3d] transition-colors duration-300" aria-hidden="true" />
        </div>
      </div>
      <p className="text-gray-400 text-sm leading-relaxed">
        {description}
      </p>
    </motion.div>
  );
}

// — Link-list card component (stacked items with arrows)
function LinkListCard({
  items,
  delay: delayMs,
  isInView,
}: {
  items: string[];
  delay: number;
  isInView: boolean;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={isInView ? { opacity: 1, y: 0 } : {}}
      transition={{ delay: delayMs, duration: duration.slow, ease: easing.smooth }}
      className="rounded-[20px] bg-white/[0.03] border border-white/[0.06] overflow-hidden h-full flex flex-col"
    >
      {items.map((item, i) => (
        <div
          key={item}
          className={`group/link flex items-center justify-between px-6 lg:px-7 py-4 lg:py-5 cursor-pointer hover:bg-white/[0.03] transition-all duration-300 ${
            i < items.length - 1 ? "border-b border-white/[0.06]" : ""
          }`}
        >
          <span
            className="text-white font-bold group-hover/link:text-[#f15f3d] transition-colors duration-300"
            style={{ fontFamily: typography.fonts.heading }}
          >
            {item}
          </span>
          <ArrowUpRight className="w-4 h-4 text-gray-600 group-hover/link:text-[#f15f3d] transition-colors duration-300" />
        </div>
      ))}
    </motion.div>
  );
}

// Tab data imported from @/app/data/services

function ServicesGrid() {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-100px" });
  const [activeTab, setActiveTab] = useState<"startups" | "business">("startups");

  const data = activeTab === "startups" ? startupsData : businessData;

  return (
    <section
      ref={ref}
      className={`relative ${spacing.section.paddingLarge} overflow-hidden`}
      style={{ backgroundColor: colors.dark.warmMedium }}
    >
      {/* Background */}
      <div className="absolute inset-0 pointer-events-none">
        <div className="absolute top-0 left-0 right-0 h-32 bg-gradient-to-b from-[#0a0908] to-transparent" />
        <div className="absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-[#0a0a0a] to-transparent" />
      </div>

      <div className={`relative z-10 ${layout.section.standard}`}>
        {/* Section Title */}
        <SectionHeader
          subtitle="What We Build"
          heading="End-to-End"
          accentWord="Development Excellence"
          isInView={isInView}
          className="mb-14 lg:mb-16"
        />

        {/* Bento Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-5">
          {/* ── Row 1: Tabs + Description | Featured Card ── */}

          {/* Tabs + Description (spans 2 cols) */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={isInView ? { opacity: 1, y: 0 } : {}}
            transition={{ delay: 0.1, duration: duration.slow, ease: easing.smooth }}
            className="md:col-span-2 lg:col-span-2 rounded-[20px] bg-white/[0.03] border border-white/[0.06] p-6 lg:p-8"
          >
            {/* Tab Buttons */}
            <div className="flex gap-3 mb-6">
              <button
                onClick={() => setActiveTab("startups")}
                className={`px-6 py-2.5 rounded-full text-sm font-medium transition-all duration-300 cursor-pointer ${
                  activeTab === "startups"
                    ? "bg-gradient-to-r from-[#f15f3d] to-[#ff7a59] text-white shadow-[0_4px_20px_rgba(241,95,61,0.3)]"
                    : "border border-white/[0.1] text-gray-400 hover:border-white/[0.2] hover:text-white"
                }`}
              >
                For Startups
              </button>
              <button
                onClick={() => setActiveTab("business")}
                className={`px-6 py-2.5 rounded-full text-sm font-medium transition-all duration-300 cursor-pointer ${
                  activeTab === "business"
                    ? "bg-gradient-to-r from-[#f15f3d] to-[#ff7a59] text-white shadow-[0_4px_20px_rgba(241,95,61,0.3)]"
                    : "border border-white/[0.1] text-gray-400 hover:border-white/[0.2] hover:text-white"
                }`}
              >
                For Business
              </button>
            </div>

            {/* Description */}
            <p className="text-gray-400 text-sm leading-relaxed max-w-2xl">
              {data.description}
            </p>
          </motion.div>

          {/* Featured Card (right column, row 1-2 on lg) */}
          <motion.div
            key={`featured-${activeTab}`}
            initial={{ opacity: 0, y: 20 }}
            animate={isInView ? { opacity: 1, y: 0 } : {}}
            transition={{ delay: 0.15, duration: duration.slow, ease: easing.smooth }}
            className="rounded-[20px] bg-white/[0.03] border border-white/[0.06] p-6 lg:p-7 lg:row-span-2 flex flex-col"
          >
            <h3
              className="text-2xl lg:text-3xl font-bold text-white mb-4"
              style={{ fontFamily: typography.fonts.heading }}
            >
              {data.featured.title}
            </h3>
            <p className="text-gray-400 text-sm leading-relaxed mb-6 lg:mb-auto">
              {data.featured.description}
            </p>

            {/* Featured Link Items */}
            <div className="mt-auto space-y-0 border-t border-white/[0.06] pt-4">
              {data.featuredLinks.map((link) => (
                <div
                  key={link}
                  className="group/flink flex items-center justify-between py-3 cursor-pointer"
                >
                  <span
                    className="text-white font-bold text-sm group-hover/flink:text-[#f15f3d] transition-colors duration-300"
                    style={{ fontFamily: typography.fonts.heading }}
                  >
                    {link}
                  </span>
                  <ArrowUpRight className="w-4 h-4 text-gray-600 group-hover/flink:text-[#f15f3d] transition-colors duration-300" />
                </div>
              ))}
            </div>
          </motion.div>

          {/* ── Row 2: First two detail cards ── */}
          {data.grid.slice(0, 2).map((item, i) =>
            item.type === "detail" ? (
              <DetailCard
                key={`${activeTab}-${item.title}`}
                title={item.title!}
                description={item.description!}
                delay={0.2 + i * 0.05}
                isInView={isInView}
              />
            ) : (
              <LinkListCard
                key={`${activeTab}-links-${i}`}
                items={item.items!}
                delay={0.2 + i * 0.05}
                isInView={isInView}
              />
            )
          )}

          {/* ── Row 3: Links + 2 detail cards ── */}
          {data.grid.slice(2, 5).map((item, i) =>
            item.type === "detail" ? (
              <DetailCard
                key={`${activeTab}-${item.title}`}
                title={item.title!}
                description={item.description!}
                delay={0.3 + i * 0.05}
                isInView={isInView}
              />
            ) : (
              <LinkListCard
                key={`${activeTab}-links-${i}`}
                items={item.items!}
                delay={0.3 + i * 0.05}
                isInView={isInView}
              />
            )
          )}

          {/* ── Row 4: Last 3 detail cards ── */}
          {data.grid.slice(5, 8).map((item, i) =>
            item.type === "detail" ? (
              <DetailCard
                key={`${activeTab}-${item.title}`}
                title={item.title!}
                description={item.description!}
                delay={0.4 + i * 0.05}
                isInView={isInView}
              />
            ) : (
              <LinkListCard
                key={`${activeTab}-links-${i}`}
                items={item.items!}
                delay={0.4 + i * 0.05}
                isInView={isInView}
              />
            )
          )}
        </div>
      </div>
    </section>
  );
}

// ============================================================================
// SECTION: CASE STUDIES
// ============================================================================

// Case studies imported from @/app/data/services

function CaseStudies() {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-100px" });

  return (
    <section
      ref={ref}
      className={`relative ${spacing.section.paddingLarge} overflow-hidden`}
      style={{ backgroundColor: colors.dark.coolMedium }}
    >
      <div className="absolute inset-0 pointer-events-none">
        <div className="absolute top-0 left-0 right-0 h-32 bg-gradient-to-b from-[#0a0a0a] to-transparent" />
      </div>

      <div className={`relative z-10 ${layout.section.standard}`}>
        {/* Header */}
        <SectionHeader
          subtitle="Featured Portfolio"
          heading="Case"
          accentWord="Studies"
          description="Real results from real projects. See how we've helped startups and enterprises build products that matter."
          isInView={isInView}
          className="mb-16 lg:mb-20"
        />

        {/* Case Study Cards */}
        <div className="space-y-8 lg:space-y-12">
          {caseStudies.map((study, i) => (
            <motion.div
              key={study.title}
              initial={{ opacity: 0, y: 30 }}
              animate={isInView ? { opacity: 1, y: 0 } : {}}
              transition={{ delay: 0.15 + i * 0.12, duration: duration.slower, ease: easing.smooth }}
            >
              <Link
                to="/work"
                className={`
                  block group relative overflow-hidden rounded-[28px] border border-white/[0.06]
                  bg-white/[0.02] hover:border-white/[0.12] ${transitions.standard}
                `}
              >
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-0">
                  {/* Image */}
                  <div className={`relative h-64 lg:h-auto overflow-hidden bg-gradient-to-br ${study.gradient}`}>
                    <ImageWithFallback
                      src={optimizeUnsplashUrl(study.image, 500)}
                      alt={study.title}
                      loading="lazy"
                      decoding="async"
                      className="w-full h-full object-cover opacity-80 group-hover:opacity-100 group-hover:scale-105 transition-all duration-700"
                    />
                    <div className="absolute inset-0 bg-gradient-to-r from-black/30 to-transparent" />
                  </div>

                  {/* Content */}
                  <div className="p-8 lg:p-12 flex flex-col justify-center">
                    <span className={`${typography.scale.small.size} text-[#f15f3d] uppercase tracking-wider mb-4`}>
                      {study.category}
                    </span>
                    <h3
                      className="text-2xl lg:text-3xl font-bold text-white mb-4"
                      style={{ fontFamily: typography.fonts.heading }}
                    >
                      {study.title}
                    </h3>
                    <p className={`${typography.scale.body.size} text-gray-400 leading-relaxed mb-6`}>
                      {study.description}
                    </p>

                    {/* Stats */}
                    <div className="flex items-center gap-8 mb-6">
                      {study.stats.map((stat) => (
                        <div key={stat.label}>
                          <div className="text-2xl font-bold text-white">{stat.value}</div>
                          <div className={`${typography.scale.small.size} text-gray-400`}>{stat.label}</div>
                        </div>
                      ))}
                    </div>

                    <div
                      className={`inline-flex items-center gap-2 text-[#f15f3d] group-hover:text-[#ff7a59] font-medium text-[15px] ${transitions.colors}`}
                    >
                      Explore Full Portfolio
                      <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
                    </div>
                  </div>
                </div>
              </Link>
            </motion.div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============================================================================
// SECTION: OUR EXPERTISE
// ============================================================================

// Expertise domains imported from @/app/data/services

function OurExpertise() {
  const ref = useRef(null);
  const chipsCardRef = useRef<HTMLDivElement>(null);
  const leftColumnRef = useRef<HTMLDivElement>(null);
  const isInView = useInView(ref, { once: true, margin: "-100px" });
  const [activeIndex, setActiveIndex] = useState(4); // Start on Social Media
  const [chipsCardHeight, setChipsCardHeight] = useState(0);
  const [leftColumnHeight, setLeftColumnHeight] = useState(0);

  // Measure chips card height and full left column height
  useEffect(() => {
    const measure = () => {
      if (chipsCardRef.current) {
        setChipsCardHeight(chipsCardRef.current.offsetHeight);
      }
      if (leftColumnRef.current) {
        setLeftColumnHeight(leftColumnRef.current.offsetHeight);
      }
    };
    measure();
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, []);

  // Auto-cycle through domains randomly
  useEffect(() => {
    const interval = setInterval(() => {
      setActiveIndex((prev) => {
        let next: number;
        do {
          next = Math.floor(Math.random() * expertiseDomains.length);
        } while (next === prev);
        return next;
      });
    }, 3000);
    return () => clearInterval(interval);
  }, []);

  const activeDomain = expertiseDomains[activeIndex];

  return (
    <section
      ref={ref}
      className={`relative ${spacing.section.paddingStandard} overflow-hidden`}
      style={{ backgroundColor: colors.dark.deep }}
    >
      {/* Subtle background glow */}
      <div className="absolute inset-0 pointer-events-none">
        <div className="absolute top-1/3 left-1/4 w-[600px] h-[600px] blur-3xl bg-[radial-gradient(circle,rgba(241,95,61,0.04),transparent_60%)]" />
      </div>

      <div className={`relative z-10 ${layout.section.standard}`}>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-10 items-end">
          {/* ── Left Column: Title + Chips ── */}
          <motion.div
            ref={leftColumnRef}
            initial={{ opacity: 0, y: 30 }}
            animate={isInView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: duration.slower, ease: easing.smooth }}
          >
            {/* Header */}
            <SectionHeader
              subtitle="Domains we have"
              heading="Great"
              accentWord="Expertise"
              isInView={isInView}
              animate={false}
              className="mb-6"
            />

            {/* Chips Card */}
            <div
              ref={chipsCardRef}
              className="rounded-[24px] p-6 sm:p-8"
              style={{
                backgroundColor: "rgba(255,255,255,0.03)",
                border: "1px solid rgba(255,255,255,0.06)",
              }}
            >
              <div className="flex flex-wrap gap-3">
                {expertiseDomains.map((domain, i) => {
                  const Icon = domain.icon;
                  const isActive = i === activeIndex;
                  return (
                    <motion.div
                      key={domain.name}
                      layout
                      className={`
                        inline-flex items-center gap-2.5 px-5 py-2.5 rounded-full cursor-default
                        transition-colors duration-500 select-none
                        ${
                          isActive
                            ? "bg-gradient-to-r from-[#f15f3d] to-[#ff9575] text-white shadow-lg shadow-[#f15f3d]/20"
                            : "bg-white/[0.04] border border-white/[0.08] text-gray-400"
                        }
                      `}
                    >
                      <Icon className={`w-4 h-4 ${isActive ? "text-white" : "text-gray-400"}`} />
                      <span className="text-[13px] whitespace-nowrap">{domain.name}</span>
                    </motion.div>
                  );
                })}
              </div>
            </div>
          </motion.div>

          {/* ── Right Column: Phone Mockup ── */}
          <motion.div
            initial={{ opacity: 0, x: 40 }}
            animate={isInView ? { opacity: 1, x: 0 } : {}}
            transition={{ duration: duration.slower, ease: easing.smooth, delay: 0.2 }}
            className="relative"
          >
            {/* Clipping container — height further refined for optimal visibility balance */}
            <div
              className="relative w-full mx-auto overflow-hidden"
              style={{ height: leftColumnHeight > 0 ? `${leftColumnHeight + 125}px` : "500px" }}
            >
              {/* Wide colored background card — matches chips card height exactly */}
              <motion.div
                className="absolute inset-x-0 bottom-0 rounded-[32px]"
                style={{ height: chipsCardHeight > 0 ? `${chipsCardHeight}px` : "60%" }}
                animate={{ backgroundColor: activeDomain.accent }}
                transition={{ duration: 0.5, ease: "easeInOut" }}
              />

              {/* Industry Shot — centered, original width but revealing much more height */}
              <div className="absolute left-1/2 -translate-x-1/2 top-0 z-10 w-[280px] sm:w-[310px]">
                <AnimatePresence mode="wait">
                  <motion.div
                    key={activeIndex}
                    initial={{ opacity: 0, scale: 0.95, y: 10 }}
                    animate={{ opacity: 1, scale: 1, y: 0 }}
                    exit={{ opacity: 0, scale: 1.05, y: -10 }}
                    transition={{ duration: duration.slower, ease: easing.smooth }}
                    className="w-full aspect-[9/19.5]"
                  >
                    <ImageWithFallback
                      src={activeDomain.image}
                      alt={`${activeDomain.name} app`}
                      loading="lazy"
                      decoding="async"
                      className="w-full h-full object-contain drop-shadow-2xl"
                    />
                  </motion.div>
                </AnimatePresence>
              </div>
            </div>
          </motion.div>
        </div>
      </div>
    </section>
  );
}

// ============================================================================
// SECTION: WHY FINJINEERS + TESTIMONIALS
// ============================================================================

// ── Large Circular Progress with text inside ──
function CircularStatCard({
  value,
  label,
  percentage,
  isInView,
  delay = 0,
}: {
  value: string;
  label: string;
  percentage: number;
  isInView: boolean;
  delay?: number;
}) {
  const size = 160;
  const strokeW = 6;
  const radius = (size - strokeW) / 2 - 8;
  const circumference = 2 * Math.PI * radius;
  const strokeDashoffset = circumference - (percentage / 100) * circumference;
  const gradId = `arcG-${percentage}-${delay}`;

  return (
    <div className="relative flex items-center justify-center">
      <svg
        width={size}
        height={size}
        viewBox={`0 0 ${size} ${size}`}
        className="w-[140px] h-[140px] lg:w-[160px] lg:h-[160px] flex-shrink-0"
      >
        <defs>
          <linearGradient id={gradId} x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#f15f3d" />
            <stop offset="100%" stopColor="#ff9575" />
          </linearGradient>
        </defs>
        {/* Track */}
        <circle
          cx={size / 2}
          cy={size / 2}
          r={radius}
          fill="none"
          stroke="rgba(255,255,255,0.06)"
          strokeWidth={strokeW}
        />
        {/* Animated arc */}
        <motion.circle
          cx={size / 2}
          cy={size / 2}
          r={radius}
          fill="none"
          stroke={`url(#${gradId})`}
          strokeWidth={strokeW}
          strokeLinecap="round"
          strokeDasharray={circumference}
          initial={{ strokeDashoffset: circumference }}
          animate={isInView ? { strokeDashoffset } : {}}
          transition={{ duration: 1.4, delay, ease: easing.smooth }}
          style={{ transformOrigin: "center", transform: "rotate(-90deg)" }}
        />
      </svg>
      {/* Text inside the circle */}
      <div className="absolute inset-0 flex flex-col items-center justify-center text-center px-4">
        <span
          className="text-2xl lg:text-3xl font-bold text-white"
          style={{ fontFamily: typography.fonts.heading }}
        >
          {value}
        </span>
        <span className={`${typography.scale.small.size} text-gray-400 leading-tight mt-1`}>
          {label}
        </span>
      </div>
    </div>
  );
}

// whyStatRows imported from @/app/data/services

// testimonials imported from @/app/data/services (as servicesTestimonials)

function WhyFinjineers() {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-100px" });

  return (
    <section
      ref={ref}
      className={`relative ${spacing.section.paddingLarge} overflow-hidden`}
      style={{ backgroundColor: colors.dark.warmMedium }}
    >
      <div className="absolute inset-0 pointer-events-none">
        <div className="absolute top-1/2 left-1/4 w-[600px] h-[600px] blur-3xl bg-[radial-gradient(circle,rgba(241,95,61,0.03),transparent_60%)]" />
      </div>

      <div className={`relative z-10 ${layout.section.standard}`}>
        {/* ── Section Title ── */}
        <SectionHeader
          subtitle="The Finjineers Difference"
          heading="Why Choose"
          accentWord="Finjineers"
          isInView={isInView}
          className="mb-12 lg:mb-16"
        />

        {/* ── 2-Column Stats Layout ── */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-12 items-stretch mb-24 lg:mb-32">
          {/* Left — Team Photo */}
          <motion.div
            initial={{ opacity: 0, x: -30 }}
            animate={isInView ? { opacity: 1, x: 0 } : {}}
            transition={{ duration: duration.slower, delay: 0.1, ease: easing.smooth }}
            className="relative rounded-[24px] overflow-hidden min-h-[400px] lg:min-h-0 border border-white/[0.06]"
          >
            <ImageWithFallback
              src={whyImage}
              alt="Finjineers team"
              loading="lazy"
              decoding="async"
              className="absolute inset-0 w-full h-full object-cover object-center"
            />
            <div className="absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent" />
          </motion.div>

          {/* Right — Paired Stats (circular left + rect right) with vertical connectors */}
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={isInView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: duration.slower, delay: 0.2, ease: easing.smooth }}
            className="flex flex-col items-center w-full relative"
          >
            {/* Vertical interlinking spine — runs behind all rows */}
            <div className="absolute left-1/2 top-8 bottom-8 w-[1px] -translate-x-1/2 bg-gradient-to-b from-transparent via-[#f15f3d]/20 to-transparent pointer-events-none hidden lg:block" />

            {whyStatRows.map((row, rowIdx) => (
              <div key={row.circular.value} className="relative w-full">
                {/* Row */}
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={isInView ? { opacity: 1, y: 0 } : {}}
                  transition={{
                    delay: 0.3 + rowIdx * 0.15,
                    duration: duration.slow,
                    ease: easing.smooth,
                  }}
                  className="grid grid-cols-2 gap-4 lg:gap-5"
                >
                  {/* Left — Circular card */}
                  <div
                    className={`
                      relative rounded-[20px] p-5 lg:p-6
                      ${backgrounds.card.standard} ${borders.width.standard} border-white/[0.06]
                      hover:border-white/[0.12] ${transitions.standard}
                      flex items-center justify-center
                      min-w-[150px] lg:min-w-[180px] min-h-[180px] lg:min-h-[200px]
                    `}
                  >
                    <CircularStatCard
                      value={row.circular.value}
                      label={row.circular.label}
                      percentage={row.circular.percentage}
                      isInView={isInView}
                      delay={0.4 + rowIdx * 0.2}
                    />
                  </div>

                  {/* Right — Rectangular card */}
                  <div
                    className={`
                      relative rounded-[20px] p-6 lg:p-8
                      ${backgrounds.card.standard} ${borders.width.standard} border-white/[0.06]
                      hover:border-white/[0.12] ${transitions.standard}
                      flex flex-col items-start justify-center
                      min-w-[150px] lg:min-w-[180px] min-h-[180px] lg:min-h-[200px]
                    `}
                  >
                    <span
                      className="text-3xl lg:text-4xl font-bold text-white mb-2"
                      style={{ fontFamily: typography.fonts.heading }}
                    >
                      {row.rect.value}
                    </span>
                    <span className={`${typography.scale.body.size} text-gray-400 leading-snug`}>
                      {row.rect.label}
                    </span>
                  </div>
                </motion.div>

                {/* Vertical connector bridge between rows */}
                {rowIdx < whyStatRows.length - 1 && (
                  <div className="relative flex justify-center py-2 lg:py-3">
                    {/* Connector node */}
                    <motion.div
                      initial={{ scale: 0, opacity: 0 }}
                      animate={isInView ? { scale: 1, opacity: 1 } : {}}
                      transition={{ delay: 0.6 + rowIdx * 0.15, duration: 0.4, ease: easing.smooth }}
                      className="relative z-10 flex items-center gap-2"
                    >
                      {/* Left arm */}
                      <div className="w-12 lg:w-16 h-[1px] bg-gradient-to-r from-transparent to-[#f15f3d]/30" />
                      {/* Center diamond */}
                      <div className="w-3 h-3 rotate-45 rounded-[2px] bg-gradient-to-br from-[#f15f3d]/40 to-[#ff9575]/20 border border-[#f15f3d]/20" />
                      {/* Right arm */}
                      <div className="w-12 lg:w-16 h-[1px] bg-gradient-to-l from-transparent to-[#f15f3d]/30" />
                    </motion.div>
                  </div>
                )}
              </div>
            ))}
          </motion.div>
        </div>

        {/* ── Testimonials — 2-col: title left, scrolling cards right ── */}
        <div className="grid grid-cols-1 lg:grid-cols-[1fr_1.2fr] gap-10 lg:gap-16 items-center">
          {/* Left — Title + Clutch CTA */}
          <motion.div
            initial={{ opacity: 0, x: -20 }}
            animate={isInView ? { opacity: 1, x: 0 } : {}}
            transition={{ delay: 0.3, duration: duration.slower, ease: easing.smooth }}
          >
            <h2
              className="text-3xl md:text-4xl lg:text-5xl font-bold text-white uppercase leading-[1.05] tracking-tight mb-10"
              style={{ fontFamily: typography.fonts.heading }}
            >
              Our Clients Are Our
              <br />
              Best <GradientText>Ambassadors</GradientText>
            </h2>

          </motion.div>

          {/* Right — Infinite scrolling testimonial cards */}
          <motion.div
            initial={{ opacity: 0, x: 20 }}
            animate={isInView ? { opacity: 1, x: 0 } : {}}
            transition={{ delay: 0.4, duration: duration.slower, ease: easing.smooth }}
            className="relative h-[480px] overflow-hidden"
          >
            {/* Fade masks top & bottom */}
            <div className="absolute top-0 left-0 right-0 h-20 z-10 pointer-events-none" style={{ background: `linear-gradient(to bottom, ${colors.dark.warmMedium}, transparent)` }} />
            <div className="absolute bottom-0 left-0 right-0 h-20 z-10 pointer-events-none" style={{ background: `linear-gradient(to top, ${colors.dark.warmMedium}, transparent)` }} />

            {/* Scrolling track */}
            <div
              className="flex flex-col gap-5 animate-[scrollTestimonials_25s_linear_infinite]"
              style={{ willChange: "transform" }}
            >
              {/* Duplicate list for seamless loop */}
              {[...testimonials, ...testimonials].map((t, i) => (
                <div
                  key={`${t.name}-${i}`}
                  className={`
                    rounded-[20px] p-6 lg:p-7
                    ${backgrounds.card.standard} ${borders.width.standard} border-white/[0.06]
                  `}
                >
                  {/* Author row */}
                  <div className="flex items-center gap-3 mb-4">
                    <ImageWithFallback
                      src={optimizeForSize(t.avatar, "avatar")}
                      alt={t.name}
                      width={40}
                      height={40}
                      loading="lazy"
                      decoding="async"
                      className="w-10 h-10 rounded-full object-cover flex-shrink-0"
                    />
                    <div className="min-w-0">
                      <div className="flex items-center gap-2">
                        <span
                          className="text-[15px] font-bold text-white truncate"
                          style={{ fontFamily: typography.fonts.heading }}
                        >
                          {t.role}
                        </span>
                        <span className="text-[16px]">{t.flag}</span>
                      </div>
                      <div className={`${typography.scale.small.size} text-gray-400`}>
                        {t.name}
                      </div>
                    </div>
                  </div>

                  {/* Quote */}
                  <p className={`${typography.scale.body.size} text-gray-300 leading-relaxed`}>
                    &ldquo;{t.quote}&rdquo;
                  </p>
                </div>
              ))}
            </div>
          </motion.div>
        </div>
      </div>
    </section>
  );
}

// ============================================================================
// SECTION: HOW DO WE WORK
// ============================================================================

// workModels imported from @/app/data/services

function HowWeWork() {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-100px" });

  return (
    <section
      ref={ref}
      className={`relative ${spacing.section.paddingLarge} overflow-hidden`}
      style={{ backgroundColor: colors.dark.deep }}
    >
      <div className={`relative z-10 ${layout.section.standard}`}>
        {/* Header */}
        <SectionHeader
          heading="How Do We"
          accentWord="Work"
          isInView={isInView}
          className="mb-14 lg:mb-20"
        />

        {/* Two model cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 lg:gap-8">
          {workModels.map((model, i) => (
            <motion.div
              key={model.title}
              initial={{ opacity: 0, y: 25 }}
              animate={isInView ? { opacity: 1, y: 0 } : {}}
              transition={{
                delay: 0.15 + i * 0.12,
                duration: duration.slow,
                ease: easing.smooth,
              }}
              className="relative"
            >
              {/* Badge */}
              {model.badge && (
                <div className="absolute -top-4 right-6 z-10">
                  <span
                    className="inline-flex items-center gap-1.5 rounded-full px-4 py-1.5 text-[13px] font-bold shadow-lg"
                    style={{
                      background: "linear-gradient(135deg, #7c5cfc, #9b7dfc)",
                      color: "#fff",
                    }}
                  >
                    {model.badge.emoji} {model.badge.text}
                  </span>
                </div>
              )}

              <div
                className={`
                  rounded-[24px] p-8 lg:p-10 h-full
                  ${backgrounds.card.standard} ${borders.width.standard} border-white/[0.06]
                  hover:border-white/[0.12] ${transitions.standard}
                `}
              >
                {/* Title */}
                <h3
                  className="text-2xl md:text-[26px] font-bold text-white mb-3"
                  style={{ fontFamily: typography.fonts.heading }}
                >
                  {model.title}
                </h3>

                {/* Description */}
                <p className={`${typography.scale.body.size} text-gray-400 leading-relaxed mb-7`}>
                  {model.description}
                </p>

                {/* Points heading */}
                <p className="text-[15px] font-bold text-white mb-4">{model.heading}</p>

                {/* Bullet list */}
                <ul className="space-y-3">
                  {model.points.map((pt) => (
                    <li
                      key={pt}
                      className="flex items-start gap-3 text-gray-400"
                    >
                      <span className="text-gray-400 mt-0.5 flex-shrink-0 text-[13px]" aria-hidden="true">/</span>
                      <span className={`${typography.scale.body.size} leading-relaxed`}>
                        {pt}
                      </span>
                    </li>
                  ))}
                </ul>
              </div>
            </motion.div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============================================================================
// SECTION: DON'T KNOW WHAT TO CHOOSE? CTA
// ============================================================================

function ConsultationCTA() {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-80px" });

  return (
    <section
      ref={ref}
      className="relative py-10 lg:py-16"
      style={{ backgroundColor: colors.dark.deep }}
    >
      <div className={`relative z-10 ${layout.section.standard}`}>
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={isInView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: duration.slower, ease: easing.smooth }}
          className="relative"
        >
          {/* Pill-shaped card — dark glassmorphic theme */}
          <div
            className="relative overflow-visible"
            style={{
              borderRadius: "80px",
              background:
                "linear-gradient(135deg, rgba(241,95,61,0.08) 0%, rgba(255,149,117,0.04) 40%, rgba(255,255,255,0.02) 100%)",
              border: "1px solid rgba(255,255,255,0.08)",
              backdropFilter: "blur(20px)",
            }}
          >
            {/* Subtle orange glow top-left */}
            <div
              className="absolute -top-24 -left-24 w-56 h-56 rounded-full pointer-events-none"
              style={{
                background:
                  "radial-gradient(circle, rgba(241,95,61,0.12) 0%, transparent 70%)",
              }}
            />

            <div className="flex flex-col lg:flex-row items-center lg:items-center px-10 md:px-14 lg:pl-16 lg:pr-[340px] py-9 md:py-11 lg:py-14 gap-8 lg:gap-0">
              {/* Left — Title + brand CTA */}
              <div className="flex-1 min-w-0 lg:pr-8 relative z-10">
                <h2
                  className="text-2xl md:text-3xl lg:text-[34px] font-bold text-white uppercase leading-[1.1] tracking-tight mb-6"
                  style={{ fontFamily: typography.fonts.heading }}
                >
                  Don&apos;t Know What
                  <br />
                  To <GradientText>Choose</GradientText>?
                </h2>
                <Button
                  variant="secondary"
                  size="large"
                  href={externalUrls.calendly}
                >
                  Book Free Call
                </Button>
              </div>

              {/* Center — Person info */}
              <div className="flex-shrink-0 relative z-10">
                <h3
                  className="text-xl md:text-[22px] font-bold text-white mb-0.5"
                  style={{ fontFamily: typography.fonts.heading }}
                >
                  Muhammad Haseeb
                </h3>
                <p className="text-[15px] text-gray-400 mb-3 leading-relaxed">
                  Founder & AI Consultant<br /><span className="text-[#f15f3d]">at Finjineers</span>
                </p>
                <div className="flex items-center gap-2.5">
                  <a
                    href="https://www.linkedin.com/in/haseeb-mobile/"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-9 h-9 rounded-lg bg-white/[0.06] border border-white/[0.08] flex items-center justify-center text-gray-400 hover:bg-[#f15f3d]/15 hover:border-[#f15f3d]/30 hover:text-[#f15f3d] transition-all"
                  >
                    <Linkedin className="w-4 h-4" />
                  </a>
                  <a
                    href="mailto:ceo@finjineers.com"
                    className="w-9 h-9 rounded-lg bg-white/[0.06] border border-white/[0.08] flex items-center justify-center text-gray-400 hover:bg-[#f15f3d]/15 hover:border-[#f15f3d]/30 hover:text-[#f15f3d] transition-all"
                  >
                    <Mail className="w-4 h-4" />
                  </a>
                </div>
              </div>
            </div>

            {/* Right — Floating character */}
            <div className="hidden lg:block absolute right-4 bottom-0 w-[320px] z-20 pointer-events-none">
              <div className="relative">
                {/* Glow behind character */}
                <div
                  className="absolute bottom-4 left-1/2 -translate-x-1/2 w-32 h-32 rounded-full"
                  style={{
                    background:
                      "radial-gradient(circle, rgba(241,95,61,0.15) 0%, transparent 70%)",
                  }}
                />
                <img
                  src={founderTransparentImage}
                  alt="Muhammad Haseeb — Founder & AI Consultant"
                  className="relative w-full h-auto object-contain scale-125 origin-bottom"
                  style={{
                    filter: "drop-shadow(0 10px 40px rgba(0,0,0,0.6))",
                    marginBottom: "-1px",
                  }}
                />
              </div>
            </div>
          </div>
        </motion.div>
      </div>
    </section>
  );
}

// TechStack — now uses shared TechStackSection component from @/app/components/shared/TechStackSection

// ============================================================================
// SECTION: FINAL CTA — GOT A PROJECT IN MIND? (Form + What Happens Next)
// ============================================================================

// whatHappensNext imported from @/app/data/services

// FinalCTA now uses shared FinalCTASection from @/app/components/shared/FinalCTASection

// ============================================================================
// PAGE EXPORT
// ============================================================================

export function Services() {
  useDocumentMeta({
    title: "Services",
    description: "Explore Finjineers' full-service mobile app development: strategy, UI/UX design, React Native, Flutter, iOS, Android, backend, DevOps, and post-launch support.",
  });

  return (
    <div className="relative min-h-screen" style={{ backgroundColor: colors.dark.deep }}>
      {/* 1. Hero */}
      <ServicesHero />

      {/* 2. Services Grid */}
      <ServicesGrid />

      {/* 4. Case Studies */}
      <CaseStudies />

      {/* 5. Mid-Page CTA */}
      <MidPageCTA />

      {/* 6. Our Expertise */}
      <OurExpertise />

      {/* 7. Why Finjineers + Testimonials */}
      <WhyFinjineers />

      {/* 8. How We Work */}
      <HowWeWork />

      {/* 9. Consultation CTA Banner */}
      <ConsultationCTA />

      {/* 10. Tech Stack */}
      <TechStackSection />

      {/* 12. Final CTA */}
      <FinalCTASection formId="services-final-cta" steps={whatHappensNext} />
    </div>
  );
}