import React, { useRef, useState, useEffect, useCallback } from "react";
import { motion, useInView, AnimatePresence } from "motion/react";
import {
  ArrowRight,
  Star,
  Mail,
  Linkedin,
  Paperclip,
  ChevronLeft,
  ChevronRight,
  Play,
} from "lucide-react";
import {
  colors,
  typography,
  spacing,
  layout,
} from "@/app/utils/design-tokens";
import { easing, duration } from "@/app/utils/animations";
import { Button } from "../components/ui/shared/Buttons";
import { ImageWithFallback } from "../components/figma/ImageWithFallback";
import { optimizeUnsplashUrl, optimizeForSize } from "../utils/image-utils";
import { useDocumentMeta } from "../hooks/useDocumentMeta";
import { externalUrls, socialLinks } from "../config/site";
import { SectionHeader, GradientText } from "../components/shared/SectionHeader";
import { FinalCTASection } from "../components/shared/FinalCTASection";
import { AnimatedSection } from "../components/shared/AnimatedSection";
import {
  specialistStats,
  industries,
  clientBreakdown,
  whyWorkWithUs,
  testimonials,
  heroReviews,
  aboutWhatHappensNext,
} from "../data/about";

// Data arrays imported from @/app/data/about.ts
// Tech stack imported from @/app/data/tech-stack.tsx








// ============================================================================
// MAIN COMPONENT
// ============================================================================

export function About() {
  useDocumentMeta({
    title: "About",
    description: "Meet the Finjineers team — a 100% in-house team of mobile app developers, designers, and strategists building world-class apps for startups and enterprises.",
  });

  return (
    <div className="relative min-h-screen" style={{ backgroundColor: colors.dark.deep }}>
      <HeroSection />
      <SpecialistsSection />
      <IndustriesSection />
      <WhyWorkWithUsSection />
      <TestimonialsSection />
      <JoinTeamSection />
      <SendCVSection />
      <FinalCTASection formId="about-final-cta" steps={aboutWhatHappensNext} />
    </div>
  );
}

// ============================================================================
// 1. HERO SECTION — About Us
// ============================================================================

function HeroSection() {
  const ref = useRef<HTMLElement>(null);
  const isInView = useInView(ref, { once: true });

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

      <div className={`relative z-10 ${layout.section.standard}`}>
        <div className="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 lg:gap-16 items-center">
            {/* Left — Copy */}
            <motion.div
              initial={{ opacity: 0, y: 24 }}
              animate={isInView ? { opacity: 1, y: 0 } : {}}
              transition={{ duration: duration.slower, ease: easing.smooth }}
            >
              <span className="inline-flex items-center px-4 py-1.5 rounded-full bg-[#f15f3d]/10 border border-[#f15f3d]/20 text-[#f15f3d] text-[12px] font-medium uppercase tracking-wider mb-6">
                About us
              </span>

              <h1
                className="text-5xl md:text-6xl lg:text-7xl font-bold text-white uppercase leading-[1.05] tracking-tight mb-7"
                style={{ fontFamily: typography.fonts.heading }}
              >
                About <GradientText>Us</GradientText>
              </h1>

              <p
                className={`${typography.scale.subheadline.size} text-gray-400 leading-[1.7] mb-8 max-w-xl`}
                style={{ fontFamily: typography.fonts.body }}
              >
                We are a premium mobile app development agency founded by
                ex-Google and ex-Facebook engineers. We combine Silicon Valley
                engineering standards with world-class design to build apps that
                startups and SaaS founders love.
              </p>

              <Button
                variant="primary"
                size="large"
                href={externalUrls.calendly}
              >
                Book a free call
                <ArrowRight className="w-4 h-4" />
              </Button>
            </motion.div>

            {/* Right — Review Ticket Carousel */}
            <motion.div
              initial={{ opacity: 0, y: 24 }}
              animate={isInView ? { opacity: 1, y: 0 } : {}}
              transition={{ delay: 0.15, duration: duration.slower, ease: easing.smooth }}
              className=""
            >
              <ReviewTicketCarousel />
            </motion.div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============================================================================
// REVIEW TICKET CAROUSEL — used in Hero
// ============================================================================

function StarRating({ rating }: { rating: string }) {
  const numRating = parseFloat(rating);
  const fullStars = Math.floor(numRating);
  const hasHalf = numRating % 1 >= 0.5;
  return (
    <span className="inline-flex items-center gap-0.5">
      {Array.from({ length: 5 }).map((_, i) => (
        <Star
          key={i}
          className={`w-3 h-3 ${
            i < fullStars
              ? "text-[#f15f3d] fill-[#f15f3d]"
              : i === fullStars && hasHalf
              ? "text-[#f15f3d] fill-[#f15f3d]/50"
              : "text-gray-600"
          }`}
        />
      ))}
    </span>
  );
}

function ReviewTicketCarousel() {
  const [current, setCurrent] = useState(0);
  const [direction, setDirection] = useState(1);
  const total = heroReviews.length;
  const ticketRef = useRef<HTMLDivElement>(null);

  const goTo = useCallback(
    (next: number) => {
      setDirection(next > current ? 1 : -1);
      setCurrent(next);
    },
    [current]
  );

  const goNext = useCallback(() => {
    goTo((current + 1) % total);
  }, [current, total, goTo]);

  const goPrev = useCallback(() => {
    goTo((current - 1 + total) % total);
  }, [current, total, goTo]);

  // Auto-scroll every 4 seconds — pauses when off-screen
  useEffect(() => {
    const el = ticketRef.current;
    if (!el) return;

    let timer: ReturnType<typeof setInterval> | null = null;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          timer = setInterval(goNext, 4000);
        } else if (timer) {
          clearInterval(timer);
          timer = null;
        }
      },
      { threshold: 0.1 }
    );

    observer.observe(el);
    return () => {
      observer.disconnect();
      if (timer) clearInterval(timer);
    };
  }, [goNext]);

  const review = heroReviews[current];

  const variants = {
    enter: (dir: number) => ({ x: dir > 0 ? 80 : -80, opacity: 0 }),
    center: { x: 0, opacity: 1 },
    exit: (dir: number) => ({ x: dir > 0 ? -80 : 80, opacity: 0 }),
  };

  return (
    <div ref={ticketRef} className="flex flex-col gap-5">
      {/* Ticket Card */}
      <div className="relative overflow-hidden rounded-[20px] bg-white/[0.04] border border-white/[0.08] backdrop-blur-sm">
        {/* Top perforation dots */}
        <div className="flex items-center justify-between px-4 py-0">
          {Array.from({ length: 16 }).map((_, i) => (
            <div key={`top-${i}`} className="w-1.5 h-1.5 rounded-full bg-white/[0.08] -mt-0.5" />
          ))}
        </div>

        <AnimatePresence mode="wait" custom={direction}>
          <motion.div
            key={current}
            custom={direction}
            variants={variants}
            initial="enter"
            animate="center"
            exit="exit"
            transition={{ duration: duration.slow, ease: easing.smooth }}
          >
            <div className="flex flex-col md:flex-row">
              {/* Left — Quote & Date */}
              <div className="flex-1 p-6 md:p-7 border-b md:border-b-0 md:border-r border-dashed border-white/[0.1]">
                <div className="text-[11px] text-gray-400 uppercase tracking-[0.15em] mb-4" style={{ fontFamily: typography.fonts.body }}>
                  The Review
                </div>

                <p className="text-[14px] md:text-[15px] text-gray-300 leading-[1.7] mb-5 italic">
                  &ldquo;{review.quote}&rdquo;
                </p>

                <div className="text-[12px] text-gray-400" style={{ fontFamily: typography.fonts.body }}>
                  {review.date}
                </div>
              </div>

              {/* Right — Ratings */}
              <div className="w-full md:w-[200px] p-6 md:p-7 flex flex-col gap-3">
                {/* Overall */}
                <div className="flex items-center justify-between mb-1">
                  <span className="text-2xl font-bold text-white" style={{ fontFamily: typography.fonts.heading }}>
                    {review.overall}
                  </span>
                  <StarRating rating={review.overall} />
                </div>

                {/* Detail Scores */}
                <div className="space-y-2.5 pt-2 border-t border-white/[0.06]">
                  {[
                    { label: "Quality:", value: review.quality },
                    { label: "Schedule:", value: review.schedule },
                    { label: "Cost:", value: review.cost },
                    { label: "Willing to refer:", value: review.willingToRefer },
                  ].map((item) => (
                    <div key={item.label} className="flex items-center justify-between">
                      <span className="text-[12px] text-gray-400">{item.label}</span>
                      <span className="text-[13px] font-medium text-white">{item.value}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </motion.div>
        </AnimatePresence>

        {/* Bottom perforation dots */}
        <div className="flex items-center justify-between px-4 py-0" aria-hidden="true">
          {Array.from({ length: 16 }).map((_, i) => (
            <div key={`bot-${i}`} className="w-1.5 h-1.5 rounded-full bg-white/[0.08] -mb-0.5" />
          ))}
        </div>
      </div>

      {/* Navigation Arrows + Dots */}
      <div className="flex items-center justify-between">
        {/* Slide dots */}
        <div className="flex items-center gap-2">
          {heroReviews.map((_, i) => (
            <button
              key={i}
              onClick={() => goTo(i)}
              className={`w-2 h-2 rounded-full transition-all duration-300 ${
                i === current ? "bg-[#f15f3d] w-5" : "bg-white/[0.15] hover:bg-white/[0.25]"
              }`}
              aria-label={`Go to review ${i + 1}`}
            />
          ))}
        </div>

        {/* Arrows */}
        <div className="flex items-center gap-2">
          <button
            onClick={goPrev}
            className="w-10 h-10 rounded-full border border-white/[0.08] hover:border-white/[0.12] bg-white/[0.02] hover:bg-white/[0.04] flex items-center justify-center transition-all duration-300"
            aria-label="Previous review"
          >
            <ChevronLeft className="w-4 h-4 text-gray-400" />
          </button>
          <button
            onClick={goNext}
            className="w-10 h-10 rounded-full border border-white/[0.08] hover:border-white/[0.12] bg-white/[0.02] hover:bg-white/[0.04] flex items-center justify-center transition-all duration-300"
            aria-label="Next review"
          >
            <ChevronRight className="w-4 h-4 text-gray-400" />
          </button>
        </div>
      </div>
    </div>
  );
}



// 3. TECHNOLOGY STACK — Uses shared TechStackSection from @/app/components/shared/TechStackSection

// ============================================================================
// 4. 50+ IN-HOUSE SPECIALISTS
// ============================================================================

function SpecialistsSection() {
  return (
    <AnimatedSection bg={colors.dark.warmMedium}>
      {(isInView) => (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-10 lg:gap-16 items-center">
          {/* Left — Heading */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={isInView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: duration.slower, ease: easing.smooth }}
          >
            <h2
              className="text-4xl md:text-5xl lg:text-6xl font-bold text-white uppercase leading-[1.05] tracking-tight"
              style={{ fontFamily: typography.fonts.heading }}
            >
              50+ <GradientText>In-House</GradientText>
              <br />
              Specialists
            </h2>
          </motion.div>

          {/* Right — Stat Cards (2×2 grid, bounding-box style) */}
          <div className="grid grid-cols-2 gap-5">
            {specialistStats.map((stat, i) => (
              <motion.div
                key={stat.label}
                initial={{ opacity: 0, y: 16 }}
                animate={isInView ? { opacity: 1, y: 0 } : {}}
                transition={{
                  delay: 0.15 + i * 0.08,
                  duration: duration.slow,
                  ease: easing.smooth,
                }}
                className="relative"
              >
                {/* Bounding-box card */}
                <div className="relative border border-[#c8a96e]/30 bg-white/[0.02] p-6 md:p-7" style={{ borderRadius: "3px" }}>
                  {/* Corner & midpoint handles */}
                  {[
                    "top-0 left-0 -translate-x-1/2 -translate-y-1/2",
                    "top-0 right-0 translate-x-1/2 -translate-y-1/2",
                    "bottom-0 left-0 -translate-x-1/2 translate-y-1/2",
                    "bottom-0 right-0 translate-x-1/2 translate-y-1/2",
                    "top-0 left-1/2 -translate-x-1/2 -translate-y-1/2",
                    "bottom-0 left-1/2 -translate-x-1/2 translate-y-1/2",
                    "top-1/2 left-0 -translate-x-1/2 -translate-y-1/2",
                    "top-1/2 right-0 translate-x-1/2 -translate-y-1/2",
                  ].map((pos, hi) => (
                    <div
                      key={hi}
                      className={`absolute w-[6px] h-[6px] ${pos}`}
                      style={{ backgroundColor: "#c8a96e", border: "1px solid #a08040" }}
                    />
                  ))}

                  {/* Value */}
                  <div
                    className="text-3xl md:text-4xl font-bold mb-2 text-center"
                    style={{
                      fontFamily: typography.fonts.heading,
                      color: "#c8a96e",
                    }}
                  >
                    {stat.value}
                  </div>

                  {/* Label */}
                  <div className="text-[13px] text-gray-400 uppercase tracking-wide text-center">
                    {stat.label}
                  </div>
                </div>
              </motion.div>
            ))}
          </div>
        </div>
      )}
    </AnimatedSection>
  );
}

// ============================================================================
// ANIMATED BAR CHART — used in Industries section
// ============================================================================

const yAxisLabels = [0, 10, 20, 30, 40, 50];
const CHART_HEIGHT = 200;
const Y_LABEL_W = 36;

function AnimatedBarChart({
  data,
  maxPercentage,
  isInView,
}: {
  data: typeof clientBreakdown;
  maxPercentage: number;
  isInView: boolean;
}) {
  const [animKey, setAnimKey] = useState(0);
  const chartRef = useRef<HTMLDivElement>(null);

  // Use a local IntersectionObserver to pause/resume the replay interval
  // when the chart scrolls out of view (isInView from parent is once:true
  // and never resets, so the interval would run forever otherwise)
  useEffect(() => {
    if (!isInView) return;
    const el = chartRef.current;
    if (!el) return;

    let interval: ReturnType<typeof setInterval> | null = null;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          interval = setInterval(() => {
            setAnimKey((k) => k + 1);
          }, 5000);
        } else if (interval) {
          clearInterval(interval);
          interval = null;
        }
      },
      { threshold: 0.1 }
    );

    observer.observe(el);
    return () => {
      observer.disconnect();
      if (interval) clearInterval(interval);
    };
  }, [isInView]);

  return (
    <div ref={chartRef} className="relative rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 backdrop-blur-sm" role="img" aria-label={`Client breakdown chart: ${data.map(d => `${d.label.replace('\n', ' ')} ${d.percentage}%`).join(', ')}`}>
      {/* Chart area wrapper */}
      <div className="relative" style={{ paddingLeft: Y_LABEL_W }}>
        {/* Plot area — fixed height, all elements positioned relative to this */}
        <div className="relative" style={{ height: CHART_HEIGHT }}>
          {/* Grid lines — positioned absolutely within plot area */}
          {yAxisLabels.map((val) => {
            const bottomPx = (val / 50) * CHART_HEIGHT;
            return (
              <div
                key={val}
                className="absolute left-0 right-0"
                style={{ bottom: bottomPx, height: 1 }}
              >
                {/* Y-axis label — positioned to the left of the plot */}
                <span
                  className="absolute text-[10px] text-gray-600 tabular-nums leading-none"
                  style={{
                    fontFamily: typography.fonts.body,
                    width: Y_LABEL_W - 6,
                    textAlign: "right",
                    right: "100%",
                    top: "50%",
                    transform: "translateY(-50%)",
                    paddingRight: 6,
                  }}
                >
                  {val}%
                </span>
                {/* Horizontal grid line */}
                <div
                  className={`absolute inset-x-0 top-0 h-px ${
                    val === 0 ? "bg-white/[0.15]" : "bg-white/[0.04]"
                  }`}
                />
              </div>
            );
          })}

          {/* Bars — aligned exactly to the bottom edge (0-line) */}
          <div className="absolute inset-x-0 bottom-0 top-0 flex items-end justify-around px-2">
            {data.map((client, i) => {
              const barH = (client.percentage / 50) * CHART_HEIGHT;
              return (
                <div
                  key={client.label}
                  className="flex flex-col items-center"
                  style={{ width: `${100 / data.length - 2}%` }}
                >
                  {/* Percentage label above bar */}
                  <motion.span
                    key={`pct-${animKey}-${i}`}
                    className="text-[13px] font-bold text-white mb-1.5 tabular-nums"
                    style={{ fontFamily: typography.fonts.body }}
                    initial={{ opacity: 0, y: 8 }}
                    animate={isInView ? { opacity: 1, y: 0 } : {}}
                    transition={{
                      delay: 0.6 + i * 0.18,
                      duration: duration.slowest,
                      ease: easing.smooth,
                    }}
                  >
                    {client.percentage}%
                  </motion.span>

                  {/* Bar — grows upward from the 0-line */}
                  <div className="relative w-full max-w-[72px]">
                    <motion.div
                      key={`bar-${animKey}-${i}`}
                      className={`w-full rounded-t-lg bg-gradient-to-t ${client.gradient} relative overflow-hidden origin-bottom`}
                      initial={{ height: 0 }}
                      animate={isInView ? { height: barH } : {}}
                      transition={{
                        delay: 0.2 + i * 0.18,
                        duration: 1.6,
                        ease: easing.smooth,
                      }}
                    >
                      {/* Shimmer / glow effect */}
                      <motion.div
                        key={`shimmer-${animKey}-${i}`}
                        className="absolute inset-0 bg-gradient-to-t from-transparent via-white/[0.08] to-white/[0.15]"
                        initial={{ opacity: 0 }}
                        animate={isInView ? { opacity: [0, 1, 0.6] } : {}}
                        transition={{
                          delay: 1.2 + i * 0.18,
                          duration: 1.4,
                          ease: "easeOut",
                        }}
                      />
                    </motion.div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* X-axis labels — below chart, aligned with bars */}
      <div
        className="flex justify-around mt-4 px-2"
        style={{ marginLeft: Y_LABEL_W }}
      >
        {data.map((client) => (
          <p
            key={client.label}
            className="text-[11px] text-gray-400 text-center whitespace-pre-line leading-[1.4]"
            style={{
              fontFamily: typography.fonts.body,
              width: `${100 / data.length - 2}%`,
            }}
          >
            {client.label}
          </p>
        ))}
      </div>
    </div>
  );
}

// ============================================================================
// 5. INDUSTRIES
// ============================================================================

function IndustriesSection() {
  const maxPercentage = Math.max(...clientBreakdown.map((c) => c.percentage));

  return (
    <AnimatedSection bg={colors.dark.deep}>
      {(isInView) => (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-16 lg:gap-24 items-center">
          {/* Left — Title + Industry List */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={isInView ? { opacity: 1, y: 0 } : {}}
            transition={{ 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 lg:mb-14"
              style={{ fontFamily: typography.fonts.heading }}
            >
              <GradientText>Industries</GradientText>
            </h2>

            <div className="grid grid-cols-2 gap-x-10 gap-y-5">
              {industries.map((industry, i) => (
                <motion.div
                  key={industry}
                  initial={{ opacity: 0, x: -10 }}
                  animate={isInView ? { opacity: 1, x: 0 } : {}}
                  transition={{
                    delay: 0.15 + i * 0.06,
                    duration: duration.slow,
                    ease: easing.smooth,
                  }}
                  className="flex items-center gap-3"
                >
                  <span
                    className="text-[18px] font-bold select-none"
                    style={{ color: "#f15f3d" }}
                  >
                    /
                  </span>
                  <span
                    className="text-[15px] text-gray-300"
                    style={{ fontFamily: typography.fonts.body }}
                  >
                    {industry}
                  </span>
                </motion.div>
              ))}
            </div>
          </motion.div>

          {/* Right — Our Clients Bar Chart */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={isInView ? { opacity: 1, y: 0 } : {}}
            transition={{
              delay: 0.25,
              duration: duration.slower,
              ease: easing.smooth,
            }}
          >
            <h3
              className="text-[18px] font-semibold text-white mb-8"
              style={{ fontFamily: typography.fonts.heading }}
            >
              Our clients
            </h3>

            <AnimatedBarChart
              data={clientBreakdown}
              maxPercentage={maxPercentage}
              isInView={isInView}
            />
          </motion.div>
        </div>
      )}
    </AnimatedSection>
  );
}

// ============================================================================
// 6. WHY WORK WITH FINJINEERS
// ============================================================================

function WhyWorkWithUsSection() {
  return (
    <AnimatedSection bg={colors.dark.coolMedium}>
      {(isInView) => (
        <div className="grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-16">
          {/* Left — Heading (spans 2 cols) */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={isInView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: duration.slower, ease: easing.smooth }}
            className="lg:col-span-2"
          >
            <h2
              className="text-3xl md:text-4xl lg:text-5xl font-bold text-white uppercase leading-[1.05] tracking-tight lg:sticky lg:top-32"
              style={{ fontFamily: typography.fonts.heading }}
            >
              Why Work
              <br />
              With <GradientText>Finjineers</GradientText>
            </h2>
          </motion.div>

          {/* Right — Feature Cards (spans 3 cols) */}
          <div className="lg:col-span-3 flex flex-col gap-6">
            {whyWorkWithUs.map((item, i) => (
              <motion.div
                key={item.title}
                initial={{ opacity: 0, y: 16 }}
                animate={isInView ? { opacity: 1, y: 0 } : {}}
                transition={{
                  delay: 0.1 + i * 0.08,
                  duration: duration.slow,
                  ease: easing.smooth,
                }}
                className="p-7 rounded-[20px] bg-white/[0.02] border border-white/[0.06] hover:border-white/[0.12] transition-all duration-300"
              >
                <div className="flex items-start gap-5">
                  <span
                    className="text-[28px] font-bold text-transparent bg-clip-text bg-gradient-to-b from-[#f15f3d] to-[#ff9575] leading-none flex-shrink-0 mt-1"
                    style={{ fontFamily: typography.fonts.heading }}
                  >
                    {String(i + 1).padStart(2, "0")}
                  </span>
                  <div>
                    <h3
                      className="text-[17px] font-bold text-white mb-2"
                      style={{ fontFamily: typography.fonts.heading }}
                    >
                      {item.title}
                    </h3>
                    <p className="text-[14px] text-gray-400 leading-[1.7]">
                      {item.description}
                    </p>
                  </div>
                </div>
              </motion.div>
            ))}
          </div>
        </div>
      )}
    </AnimatedSection>
  );
}

// ============================================================================
// 7. TESTIMONIALS — Clients Are Saying
// ============================================================================

function TestimonialsSection() {
  const [current, setCurrent] = useState(0);
  const [direction, setDirection] = useState(1);
  const [isPlaying, setIsPlaying] = useState(false);



  const goTo = (index: number) => {
    setDirection(index > current ? 1 : -1);
    setCurrent(index);
    setIsPlaying(false);
  };

  const slideVariants = {
    enter: (d: number) => ({ opacity: 0, x: d > 0 ? 60 : -60 }),
    center: { opacity: 1, x: 0 },
    exit: (d: number) => ({ opacity: 0, x: d > 0 ? -60 : 60 }),
  };

  const t = testimonials[current];

  return (
    <AnimatedSection bg={colors.dark.deep}>
      {(isInView) => (
        <motion.div
          initial={{ opacity: 0, y: 24 }}
          animate={isInView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: duration.slower, ease: easing.smooth }}
        >
          {/* Ticket wrapper */}
          <div className="relative overflow-hidden rounded-[20px] bg-white/[0.04] border border-white/[0.08] backdrop-blur-sm">
            {/* Top perforation dots */}
            <div className="flex items-center justify-between px-4 py-0" aria-hidden="true">
              {Array.from({ length: 24 }).map((_, i) => (
                <div
                  key={`t-top-${i}`}
                  className="w-1.5 h-1.5 rounded-full bg-white/[0.08] -mt-0.5"
                />
              ))}
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2">
              {/* Left — Quote Panel (animated) */}
              <div className="relative border-b lg:border-b-0 lg:border-r border-dashed border-white/[0.1]" aria-live="polite" aria-atomic="true">
                <AnimatePresence mode="wait" custom={direction}>
                  <motion.div
                    key={current}
                    custom={direction}
                    variants={slideVariants}
                    initial="enter"
                    animate="center"
                    exit="exit"
                    transition={{ duration: duration.slow, ease: easing.smooth }}
                    className="p-8 md:p-10 lg:p-12 flex flex-col justify-between min-h-[380px]"
                  >
                    {/* Large faded slide number */}
                    <div
                      className="absolute top-4 left-8 md:left-10 lg:left-12 text-[120px] md:text-[150px] font-bold leading-none text-white/[0.03] select-none pointer-events-none"
                      style={{ fontFamily: typography.fonts.heading }}
                      aria-hidden="true"
                    >
                      {String(current + 1).padStart(2, "0")}
                    </div>

                    <div className="relative z-10">
                      {/* Section title */}
                      <h2
                        className="text-3xl md:text-4xl lg:text-[42px] font-bold text-white uppercase leading-[1.05] tracking-tight mb-8"
                        style={{ fontFamily: typography.fonts.heading }}
                      >
                        Clients
                        <br />
                        Are <GradientText>Saying</GradientText>
                      </h2>

                      {/* Quote */}
                      <p
                        className="text-[14px] md:text-[15px] text-gray-300 leading-[1.75] italic max-w-[480px]"
                        style={{ fontFamily: typography.fonts.body }}
                      >
                        &ldquo;{t.quote}&rdquo;
                      </p>
                    </div>

                    {/* Author */}
                    <div className="relative z-10 mt-8 pb-14">
                      <div className="w-12 h-[1px] bg-white/[0.15] mb-5" />
                      <div>
                        <div
                          className="text-[15px] font-bold text-white"
                          style={{ fontFamily: typography.fonts.heading }}
                        >
                          {t.author}
                        </div>
                        <div
                          className="text-[13px] text-gray-400 mt-0.5"
                          style={{ fontFamily: typography.fonts.body }}
                        >
                          {t.role}
                        </div>
                      </div>
                    </div>
                  </motion.div>
                </AnimatePresence>

                {/* Pagination — outside AnimatePresence so it stays fixed */}
                {testimonials.length > 1 && (
                  <div className="absolute bottom-8 md:bottom-10 lg:bottom-12 left-8 md:left-10 lg:left-12 z-20 flex items-center gap-2">
                    {testimonials.map((_, i) => (
                      <button
                        key={i}
                        onClick={() => goTo(i)}
                        aria-label={`Go to testimonial ${i + 1}`}
                        aria-current={i === current ? "true" : undefined}
                        className={`w-8 h-8 rounded-full text-[13px] font-medium transition-all duration-300 flex items-center justify-center ${
                          i === current
                            ? "bg-[#f15f3d] text-white"
                            : "bg-white/[0.06] text-gray-400 hover:bg-white/[0.1]"
                        }`}
                        style={{ fontFamily: typography.fonts.body }}
                      >
                        {i + 1}
                      </button>
                    ))}
                  </div>
                )}
              </div>

              {/* Right ��� Video Panel */}
              <div className="relative overflow-hidden min-h-[300px] lg:min-h-[380px]">
                {isPlaying ? (
                  <iframe
                    className="absolute inset-0 w-full h-full"
                    src={`https://www.youtube.com/embed/${t.videoId}?autoplay=1&rel=0&modestbranding=1&color=white`}
                    title="Client testimonial video"
                    frameBorder="0"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowFullScreen
                    sandbox="allow-scripts allow-same-origin allow-presentation"
                    loading="lazy"
                  />
                ) : (
                  <>
                    <ImageWithFallback
                      src={optimizeUnsplashUrl(t.videoThumb, 600)}
                      alt={`${t.author} testimonial video`}
                      width={600}
                      height={340}
                      loading="lazy"
                      decoding="async"
                      className="absolute inset-0 w-full h-full object-cover"
                    />

                    {/* Clickable overlay */}
                    <button
                      onClick={() => setIsPlaying(true)}
                      className="absolute inset-0 w-full h-full cursor-pointer z-10 group"
                      aria-label="Play testimonial video"
                    >
                      <div className="absolute inset-0 flex items-center justify-center">
                        <div className="relative w-16 h-16 md:w-20 md:h-20 flex items-center justify-center">
                          <div
                            className="absolute inset-0 rounded-full border-2 border-[#f15f3d]/40 animate-ping"
                            style={{ animationDuration: "2s" }}
                          />
                          <div className="absolute inset-0 rounded-full border-2 border-[#f15f3d]/60 group-hover:border-[#f15f3d] transition-colors duration-300" />
                          <div className="absolute inset-1.5 rounded-full bg-[#f15f3d]/10 group-hover:bg-[#f15f3d]/25 transition-all duration-300 backdrop-blur-sm" />
                          <Play className="relative z-10 w-6 h-6 md:w-7 md:h-7 text-[#f15f3d] fill-[#f15f3d] ml-1 group-hover:scale-110 transition-transform duration-300" />
                        </div>
                      </div>

                      <div className="absolute bottom-6 left-0 right-0 flex justify-center">
                        <span
                          className="text-[11px] uppercase tracking-[0.2em] text-white/50 group-hover:text-white/80 transition-colors duration-300"
                          style={{ fontFamily: typography.fonts.body }}
                        >
                          Watch Video
                        </span>
                      </div>
                    </button>

                    <div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-t from-black/50 to-transparent pointer-events-none" />
                    <div className="absolute top-0 left-0 right-0 h-16 bg-gradient-to-b from-black/20 to-transparent pointer-events-none" />
                  </>
                )}
              </div>
            </div>

            {/* Bottom perforation dots */}
            <div className="flex items-center justify-between px-4 py-0" aria-hidden="true">
              {Array.from({ length: 24 }).map((_, i) => (
                <div
                  key={`t-bot-${i}`}
                  className="w-1.5 h-1.5 rounded-full bg-white/[0.08] -mb-0.5"
                />
              ))}
            </div>
          </div>
        </motion.div>
      )}
    </AnimatedSection>
  );
}

// ============================================================================
// 8. AWARDS
// ============================================================================

/* Award badge SVG shapes */
function HexagonBadge({ children }: { children: React.ReactNode }) {
  return (
    <div className="relative w-[140px] h-[160px] flex-shrink-0 flex items-center justify-center">
      <svg viewBox="0 0 140 160" className="absolute inset-0 w-full h-full" fill="none">
        <path
          d="M70 4 L130 35 L130 125 L70 156 L10 125 L10 35 Z"
          stroke="rgba(255,255,255,0.15)"
          strokeWidth="1.5"
          fill="rgba(255,255,255,0.03)"
        />
        <path
          d="M70 14 L122 41 L122 119 L70 146 L18 119 L18 41 Z"
          stroke="rgba(255,255,255,0.08)"
          strokeWidth="0.75"
          fill="none"
        />
      </svg>
      <div className="relative z-10 flex flex-col items-center text-center px-3">
        {children}
      </div>
    </div>
  );
}

function ShieldBadge({ children }: { children: React.ReactNode }) {
  return (
    <div className="relative w-[140px] h-[160px] flex-shrink-0 flex items-center justify-center">
      <svg viewBox="0 0 140 160" className="absolute inset-0 w-full h-full" fill="none">
        <path
          d="M70 4 L130 25 L130 100 Q130 140 70 156 Q10 140 10 100 L10 25 Z"
          stroke="rgba(255,255,255,0.15)"
          strokeWidth="1.5"
          fill="rgba(255,255,255,0.03)"
        />
        <path
          d="M70 14 L122 32 L122 97 Q122 132 70 146 Q18 132 18 97 L18 32 Z"
          stroke="rgba(255,255,255,0.08)"
          strokeWidth="0.75"
          fill="none"
        />
      </svg>
      <div className="relative z-10 flex flex-col items-center text-center px-3">
        {children}
      </div>
    </div>
  );
}

function OvalBadge({ children }: { children: React.ReactNode }) {
  return (
    <div className="relative w-[140px] h-[160px] flex-shrink-0 flex items-center justify-center">
      <svg viewBox="0 0 140 160" className="absolute inset-0 w-full h-full" fill="none">
        <ellipse
          cx="70" cy="80" rx="62" ry="72"
          stroke="rgba(255,255,255,0.15)"
          strokeWidth="1.5"
          fill="rgba(255,255,255,0.03)"
        />
        <ellipse
          cx="70" cy="80" rx="54" ry="64"
          stroke="rgba(255,255,255,0.08)"
          strokeWidth="0.75"
          fill="none"
        />
      </svg>
      <div className="relative z-10 flex flex-col items-center text-center px-3">
        {children}
      </div>
    </div>
  );
}

function CircleBadge({ children }: { children: React.ReactNode }) {
  return (
    <div className="relative w-[140px] h-[160px] flex-shrink-0 flex items-center justify-center">
      <svg viewBox="0 0 140 160" className="absolute inset-0 w-full h-full" fill="none">
        <circle
          cx="70" cy="80" r="66"
          stroke="rgba(255,255,255,0.15)"
          strokeWidth="1.5"
          fill="rgba(255,255,255,0.03)"
        />
        <circle
          cx="70" cy="80" r="58"
          stroke="rgba(255,255,255,0.08)"
          strokeWidth="0.75"
          fill="none"
        />
      </svg>
      <div className="relative z-10 flex flex-col items-center text-center px-3">
        {children}
      </div>
    </div>
  );
}



// ============================================================================
// 9. JOIN OUR TEAM — Large Banner
// ============================================================================

function JoinTeamSection() {
  return (
    <AnimatedSection bg={colors.dark.deep}>
      {(isInView) => (
        <>
        <SectionHeader
          heading="Join Our"
          accentWord="Team"
          isInView={isInView}
          className="mb-10"
        />

        {/* Banner */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={isInView ? { opacity: 1, y: 0 } : {}}
          transition={{ delay: 0.1, duration: duration.slower, ease: easing.smooth }}
          className="relative rounded-[28px] overflow-hidden border border-white/[0.06] min-h-[340px] md:min-h-[420px]"
        >
          {/* Background Image */}
          <ImageWithFallback
            src={optimizeUnsplashUrl("https://images.unsplash.com/photo-1760611656007-f767a8082758?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHx0ZWNoJTIwc3RhcnR1cCUyMHRlYW0lMjBncm91cCUyMHBob3RvJTIwb2ZmaWNlJTIwbW9kZXJufGVufDF8fHx8MTc3MTk5MTI2Nnww&ixlib=rb-4.1.0&q=80&w=1080", 800)}
            alt="Finjineers team"
            loading="lazy"
            decoding="async"
            className="absolute inset-0 w-full h-full object-cover"
          />

          {/* Overlay */}
          <div className="absolute inset-0 bg-gradient-to-r from-black/80 via-black/50 to-transparent" />

          {/* Content */}
          <div className="relative z-10 flex flex-col justify-center p-10 md:p-14 h-full min-h-[340px] md:min-h-[420px] max-w-lg">
            {/* Badge */}
            <span className="inline-flex items-center self-start px-3 py-1 rounded-full bg-[#f15f3d] text-white text-[11px] font-bold uppercase tracking-wider mb-5">
              We&apos;re hiring
            </span>

            <h3
              className="text-3xl md:text-4xl font-bold text-white uppercase leading-[1.1] tracking-tight mb-4"
              style={{ fontFamily: typography.fonts.heading }}
            >
              Finjineers
            </h3>

            <p className="text-[15px] text-gray-300 leading-[1.7] mb-8">
              Join a team of world-class engineers, designers, and product
              thinkers building the next generation of mobile experiences.
            </p>

            <Button variant="primary" size="large" href={socialLinks.linkedin}>
              View open positions
              <ArrowRight className="w-4 h-4" />
            </Button>
          </div>
        </motion.div>
        </>
      )}
    </AnimatedSection>
  );
}

// ============================================================================
// 10. SEND YOUR CV CTA
// ============================================================================

/* Corner selection handle used in the Send CV section */
function CornerHandle({ className }: { className?: string }) {
  return (
    <div className={`absolute w-3 h-3 border-2 border-[#f15f3d] bg-[#f15f3d]/20 ${className ?? ""}`} />
  );
}

function SendCVSection() {
  const ref = useRef<HTMLElement>(null);
  const isInView = useInView(ref, { once: true, margin: "-80px" });
  const [formData, setFormData] = useState({ name: "", email: "", message: "" });
  const [fileName, setFileName] = useState("");
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setFormData((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleFileClick = () => fileInputRef.current?.click();

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    // Security: limit file size to 10MB
    if (file.size > 10 * 1024 * 1024) {
      e.target.value = "";
      return;
    }
    setFileName(file.name);
  };

  return (
    <section
      ref={ref}
      className={spacing.section.paddingStandard}
      style={{ backgroundColor: colors.dark.warmMedium }}
    >
      <div className={layout.section.standard}>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-16 items-start">
          {/* ── Left column: Banner + tagline ── */}
          <motion.div
            initial={{ opacity: 0, x: -30 }}
            animate={isInView ? { opacity: 1, x: 0 } : {}}
            transition={{ duration: duration.slower, ease: easing.smooth }}
            className="flex flex-col items-start"
          >
            {/* Banner flag */}
            <div className="relative mb-10">
              {/* Flag pole line */}
              <div className="absolute left-0 top-0 bottom-0 w-[3px] bg-gradient-to-b from-[#f15f3d] to-[#ff9575] rounded-full" />

              {/* Flag body */}
              <div className="relative ml-[3px]">
                {/* Orange banner shape */}
                <div className="relative bg-gradient-to-r from-[#f15f3d] to-[#e8532f] px-8 md:px-12 py-5 md:py-6"
                  style={{ clipPath: "polygon(0 0, 100% 0, 95% 50%, 100% 100%, 0 100%)" }}
                >
                  {/* Corner handles on the banner */}
                  <CornerHandle className="top-[-5px] left-[-5px] border-white/60 bg-white/20" />
                  <CornerHandle className="top-[-5px] right-[20px] border-white/60 bg-white/20" />
                  <CornerHandle className="bottom-[-5px] left-[-5px] border-white/60 bg-white/20" />
                  <CornerHandle className="bottom-[-5px] right-[20px] border-white/60 bg-white/20" />

                  {/* Inner border line */}
                  <div className="absolute inset-[6px] border border-white/25 pointer-events-none"
                    style={{ clipPath: "polygon(0 0, 100% 0, 96% 50%, 100% 100%, 0 100%)" }}
                  />

                  <h2
                    className="text-3xl md:text-4xl lg:text-[44px] font-bold text-white uppercase tracking-tight leading-[1.05] relative z-10"
                    style={{ fontFamily: typography.fonts.heading }}
                  >
                    Send Your CV
                  </h2>
                </div>
              </div>
            </div>

            {/* Tagline below banner */}
            <h3
              className="text-2xl md:text-3xl lg:text-[36px] font-bold uppercase leading-[1.15] tracking-tight"
              style={{ fontFamily: typography.fonts.heading }}
            >
              <GradientText>Become A Part Of</GradientText>
              <br />
              <GradientText>The Finjineers Team!</GradientText>
            </h3>
          </motion.div>

          {/* ── Right column: Form card ── */}
          <motion.div
            initial={{ opacity: 0, x: 30 }}
            animate={isInView ? { opacity: 1, x: 0 } : {}}
            transition={{ delay: 0.15, duration: duration.slower, ease: easing.smooth }}
            className="relative"
          >
            {/* Dashed border container with corner handles */}
            <div className="relative border-2 border-dashed border-white/[0.12] rounded-[4px] p-6 md:p-8 lg:p-10">
              {/* Corner handles */}
              <CornerHandle className="-top-[7px] -left-[7px]" />
              <CornerHandle className="-top-[7px] -right-[7px]" />
              <CornerHandle className="-bottom-[7px] -left-[7px]" />
              <CornerHandle className="-bottom-[7px] -right-[7px]" />

              {/* Form */}
              <form onSubmit={(e) => e.preventDefault()} className="space-y-6">
                {/* Name & Email row */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                  <div>
                    <label
                      className="block text-[13px] text-white/70 mb-2 tracking-wide"
                      style={{ fontFamily: typography.fonts.body }}
                    >
                      Name
                    </label>
                    <input
                      type="text"
                      name="name"
                      value={formData.name}
                      onChange={handleChange}
                      placeholder="Andrew Petrov"
                      className="w-full bg-transparent border-b border-white/[0.12] pb-2 text-[15px] text-white placeholder-white/25 outline-none focus:border-[#f15f3d]/60 transition-colors duration-300"
                      style={{ fontFamily: typography.fonts.body }}
                    />
                  </div>
                  <div>
                    <label
                      className="block text-[13px] text-white/70 mb-2 tracking-wide"
                      style={{ fontFamily: typography.fonts.body }}
                    >
                      E-mail
                    </label>
                    <input
                      type="email"
                      name="email"
                      value={formData.email}
                      onChange={handleChange}
                      placeholder="andrew@gmail.com"
                      className="w-full bg-transparent border-b border-white/[0.12] pb-2 text-[15px] text-white placeholder-white/25 outline-none focus:border-[#f15f3d]/60 transition-colors duration-300"
                      style={{ fontFamily: typography.fonts.body }}
                    />
                  </div>
                </div>

                {/* Message + Attach CV row */}
                <div>
                  <label
                    className="block text-[13px] text-white/70 mb-2 tracking-wide"
                    style={{ fontFamily: typography.fonts.body }}
                  >
                    Your message
                  </label>
                  <div className="flex items-end gap-4">
                    <textarea
                      name="message"
                      value={formData.message}
                      onChange={handleChange}
                      placeholder="Tell us about yourself"
                      rows={1}
                      className="flex-1 bg-transparent border-b border-white/[0.12] pb-2 text-[15px] text-white placeholder-white/25 outline-none focus:border-[#f15f3d]/60 transition-colors duration-300 resize-none"
                      style={{ fontFamily: typography.fonts.body }}
                    />

                    {/* Attach CV button */}
                    <button
                      type="button"
                      onClick={handleFileClick}
                      className="flex items-center gap-2 px-5 py-2 rounded-full border border-white/[0.15] text-white/80 hover:border-[#f15f3d]/50 hover:text-white transition-all duration-300 flex-shrink-0"
                    >
                      <Paperclip className="w-4 h-4" />
                      <span className="text-[13px] whitespace-nowrap" style={{ fontFamily: typography.fonts.body }}>
                        {fileName || "Attach CV"}
                      </span>
                    </button>
                    <input
                      ref={fileInputRef}
                      type="file"
                      accept=".pdf,.doc,.docx"
                      onChange={handleFileChange}
                      className="hidden"
                    />
                  </div>
                </div>

                {/* Privacy policy */}
                <p className="text-[12px] text-white/35 leading-[1.6]" style={{ fontFamily: typography.fonts.body }}>
                  By sending this form I confirm that I have read and accept the{" "}
                  <a href="/privacy" className="text-white/50 underline underline-offset-2 hover:text-[#f15f3d] transition-colors duration-200">
                    Privacy Policy
                  </a>.
                </p>

                {/* Send button */}
                <Button variant="primary" size="large" type="submit">
                  Send
                  <ArrowRight className="w-4 h-4" />
                </Button>
              </form>
            </div>
          </motion.div>
        </div>
      </div>
    </section>
  );
}

// 12. FINAL CTA — now uses shared FinalCTASection from @/app/components/shared/FinalCTASection