"use client";

import { useEffect, useRef, useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import AnimatedButton from "@/components/ui/AnimatedButton";
import { ArrowRight } from "@/components/ui/icons";

/**
 * Testimonials — immersive stage. One cinematic full-width panel: the active
 * client's video fills the stage, their quote overlays it bottom-left,
 * playback + navigation live on the frame, and circular avatar tabs (top
 * right) switch clients. Auto-advances; pauses while a video plays.
 * Placeholder videos/quotes — swap with real client clips.
 */
const TESTIMONIALS = [
  {
    src: "/videos/Technology.mp4",
    poster: "/images/opt/HeroBanner1.webp",
    name: "Priya Sharma",
    role: "Founder, Fintech startup",
    quote:
      "Cerkel took us from a whiteboard sketch to a live product in fourteen weeks — and it hasn't missed a beat since.",
    metric: { value: "14 wks", label: "idea to launch" },
  },
  {
    src: "/videos/Technology1.mp4",
    poster: "/images/opt/HeroBanner2.webp",
    name: "Daniel Reyes",
    role: "Product Lead, SaaS",
    quote:
      "The team thinks like owners. They challenged our roadmap where it mattered and shipped exactly what our users needed.",
    metric: { value: "2.4×", label: "user activation" },
  },
  {
    src: "/videos/Technology.mp4",
    poster: "/images/opt/HeroBanner3.png",
    name: "Aisha Khan",
    role: "COO, Logistics platform",
    quote:
      "Our AI assistant now handles half of our support volume. Cerkel made the complex feel simple.",
    metric: { value: "−50%", label: "support tickets" },
  },
];

const EASE = [0.21, 0.47, 0.32, 0.98];

const rise = {
  hidden: { opacity: 0, y: 36 },
  show: { opacity: 1, y: 0, transition: { duration: 0.6, ease: EASE } },
};

const quoteStagger = { hidden: {}, show: { transition: { staggerChildren: 0.09, delayChildren: 0.2 } } };
const lineUp = {
  hidden: { opacity: 0, y: 24 },
  show: { opacity: 1, y: 0, transition: { duration: 0.5, ease: EASE } },
};

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

function PlayIcon({ className = "h-5 w-5" }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M8 5.14v13.72c0 .8.87 1.3 1.56.88l11.2-6.86a1.03 1.03 0 0 0 0-1.76L9.56 4.26A1.03 1.03 0 0 0 8 5.14z" />
    </svg>
  );
}

function PauseIcon({ className = "h-5 w-5" }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M7 4h3.5v16H7zM13.5 4H17v16h-3.5z" />
    </svg>
  );
}

export default function Testimonials() {
  const [active, setActive] = useState(0);
  const [playing, setPlaying] = useState(false);
  const videoRef = useRef(null);
  const len = TESTIMONIALS.length;
  const t = TESTIMONIALS[active];

  const go = (i) => {
    setPlaying(false);
    setActive((i + len) % len);
  };

  // Auto-advance unless a video is playing.
  useEffect(() => {
    if (playing) return;
    const id = setTimeout(() => go(active + 1), 7000);
    return () => clearTimeout(id);
  }, [active, playing]);

  const togglePlay = () => {
    const vid = videoRef.current;
    if (!vid) return;
    if (playing) {
      vid.pause();
      setPlaying(false);
    } else {
      vid.muted = false;
      vid.play();
      setPlaying(true);
    }
  };

  return (
    <section className="relative overflow-hidden bg-background py-14 text-foreground md:py-16">
      <div className="pointer-events-none absolute -left-40 top-1/4 h-[30rem] w-[30rem] rounded-full bg-primary/10 blur-[150px]" />

      <div className="container relative">
        {/* Header */}
        <motion.div
          variants={rise}
          initial="hidden"
          whileInView="show"
          viewport={{ once: true, amount: 0.5 }}
          className="mx-auto max-w-3xl text-center"
        >
          <span className="inline-flex items-center gap-2 rounded-full border border-border bg-surface/60 px-4 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground backdrop-blur">
            <span className="h-1.5 w-1.5 rounded-full bg-primary" />
            Testimonials
          </span>
          <h2 className="mt-5 font-heading text-3xl font-bold leading-[1.12] tracking-tight sm:text-4xl md:text-5xl">
            Hear it from{" "}
            <span className="animate-text-shimmer bg-gradient-to-r from-primary via-accent to-primary bg-clip-text text-transparent">
              the teams themselves.
            </span>
          </h2>
        </motion.div>

        {/* Immersive stage */}
        <motion.div
          variants={rise}
          initial="hidden"
          whileInView="show"
          viewport={{ once: true, amount: 0.2 }}
          className="relative mt-12 overflow-hidden rounded-3xl border border-border"
        >
          {/* Media layers — poster crossfade; video element for the active one */}
          <div className="relative h-[34rem] sm:h-[36rem]">
            {TESTIMONIALS.map((item, i) => (
              <motion.div
                key={item.name}
                initial={false}
                animate={{ opacity: i === active ? 1 : 0, scale: i === active ? 1 : 1.06 }}
                transition={{ duration: 0.7, ease: EASE }}
                className="absolute inset-0"
              >
                {i === active ? (
                  <video
                    ref={videoRef}
                    src={item.src}
                    poster={item.poster}
                    preload="none"
                    playsInline
                    loop
                    onClick={togglePlay}
                    className="h-full w-full cursor-pointer object-cover"
                  />
                ) : (
                  <span
                    className="block h-full w-full bg-cover bg-center"
                    style={{ backgroundImage: `url(${item.poster})` }}
                  />
                )}
              </motion.div>
            ))}

            {/* washes for legibility */}
            <span className="pointer-events-none absolute inset-0 bg-gradient-to-r from-background/90 via-background/40 to-background/20" />
            <span className="pointer-events-none absolute inset-0 bg-gradient-to-t from-background/85 via-transparent to-background/30" />

            {/* Avatar tabs — top right */}
            <div className="absolute right-5 top-5 flex items-center gap-2.5">
              {TESTIMONIALS.map((item, i) => (
                <button
                  key={item.name}
                  onClick={() => go(i)}
                  aria-label={`Show ${item.name}'s testimonial`}
                  className={
                    "relative h-12 w-12 overflow-hidden rounded-full border-2 transition-all duration-300 " +
                    (i === active
                      ? "scale-110 border-primary shadow-lg shadow-primary/40"
                      : "border-white/30 opacity-60 hover:opacity-100")
                  }
                >
                  <span
                    className="block h-full w-full bg-cover bg-center"
                    style={{ backgroundImage: `url(${item.poster})` }}
                  />
                </button>
              ))}
            </div>

            {/* Quote overlay — bottom left */}
            <div className="absolute inset-x-0 bottom-0 p-6 sm:p-10">
              <AnimatePresence mode="wait">
                <motion.div
                  key={active}
                  variants={quoteStagger}
                  initial="hidden"
                  animate="show"
                  exit={{ opacity: 0, transition: { duration: 0.2 } }}
                  className="max-w-2xl"
                >
                  <motion.div variants={lineUp} className="flex items-center gap-3">
                    <Stars />
                    <span className="rounded-full border border-primary/40 bg-background/60 px-3 py-1 text-xs font-semibold text-primary backdrop-blur">
                      {t.metric.value} {t.metric.label}
                    </span>
                  </motion.div>

                  <motion.blockquote
                    variants={lineUp}
                    className="mt-4 font-heading text-2xl font-semibold leading-snug drop-shadow-[0_2px_20px_rgba(0,0,0,0.6)] sm:text-3xl"
                  >
                    “{t.quote}”
                  </motion.blockquote>

                  <motion.div variants={lineUp} className="mt-5 flex items-center gap-3">
                    <span className="flex h-11 w-11 items-center justify-center rounded-full bg-gradient-to-br from-primary to-accent font-heading text-xs font-bold text-white">
                      {t.name
                        .split(" ")
                        .map((n) => n[0])
                        .join("")}
                    </span>
                    <span>
                      <span className="block font-heading text-sm font-semibold">{t.name}</span>
                      <span className="block text-xs text-muted-foreground">{t.role}</span>
                    </span>
                  </motion.div>
                </motion.div>
              </AnimatePresence>
            </div>

            {/* Controls — bottom right */}
            <div className="absolute bottom-6 right-5 flex items-center gap-2 sm:bottom-10 sm:right-10">
              <button
                onClick={togglePlay}
                aria-label={playing ? "Pause testimonial" : "Play testimonial"}
                className={
                  "flex h-12 w-12 items-center justify-center rounded-full border text-white shadow-xl shadow-black/40 backdrop-blur transition-all duration-300 " +
                  (playing
                    ? "border-border bg-background/50 hover:border-primary"
                    : "border-primary/50 bg-primary/90 hover:scale-110")
                }
              >
                {playing ? <PauseIcon /> : <PlayIcon className="ml-0.5 h-5 w-5" />}
              </button>
              <button
                onClick={() => go(active - 1)}
                aria-label="Previous testimonial"
                className="flex h-12 w-12 items-center justify-center rounded-full border border-border bg-background/50 text-foreground backdrop-blur transition-colors hover:border-primary hover:text-primary"
              >
                <ArrowRight className="h-4 w-4 rotate-180" />
              </button>
              <button
                onClick={() => go(active + 1)}
                aria-label="Next testimonial"
                className="flex h-12 w-12 items-center justify-center rounded-full border border-border bg-background/50 text-foreground backdrop-blur transition-colors hover:border-primary hover:text-primary"
              >
                <ArrowRight className="h-4 w-4" />
              </button>
            </div>

            {/* progress — thin bar along the very bottom */}
            <div className="absolute inset-x-0 bottom-0 h-1 bg-border/40">
              {!playing && (
                <div
                  key={`p-${active}`}
                  className="h-full origin-left bg-gradient-to-r from-primary to-accent"
                  style={{ animation: "slide-progress 7000ms linear forwards" }}
                />
              )}
            </div>
          </div>
        </motion.div>

        {/* CTA */}
        <motion.div
          variants={rise}
          initial="hidden"
          whileInView="show"
          viewport={{ once: true }}
          className="mt-12 flex justify-center"
        >
          <AnimatedButton href="/contact" size="sm">
            Become our next story
          </AnimatedButton>
        </motion.div>
      </div>
    </section>
  );
}
