"use client";

import { motion, useMotionValue, useSpring, useTransform } from "motion/react";
import { useRef } from "react";
import Image from "next/image";
import { Link } from "@/i18n/routing";
import { DirectionalChevron } from "@/components/ui/directional-chevron";
import { cn } from "@/lib/utils";
import type { WebsiteServiceListItem } from "@/lib/api/website/services-api";

const ease = [0.22, 1, 0.36, 1] as const;

type Props = {
  services: WebsiteServiceListItem[];
  direction: "ltr" | "rtl";
  browseLabel: string;
  contactLabel: string;
};

function ServicePanel({
  service,
  index,
  direction,
  browseLabel,
  contactLabel,
}: {
  service: WebsiteServiceListItem;
  index: number;
  direction: "ltr" | "rtl";
  browseLabel: string;
  contactLabel: string;
}) {
  const isRtl = direction === "rtl";
  // In LTR: even = image-left, odd = image-right. In RTL: mirror.
  const imageOnStart = isRtl ? index % 2 === 1 : index % 2 === 0;
  const num = String(index + 1).padStart(2, "0");
  const linkHref = `/our-services/${service.slug}`;

  // Magnetic tilt on image
  const cardRef = useRef<HTMLDivElement>(null);
  const mouseX = useMotionValue(0);
  const mouseY = useMotionValue(0);
  const rotateX = useSpring(useTransform(mouseY, [-1, 1], [3, -3]), { stiffness: 200, damping: 30 });
  const rotateY = useSpring(useTransform(mouseX, [-1, 1], [-4, 4]), { stiffness: 200, damping: 30 });

  function onMouseMove(e: React.MouseEvent<HTMLDivElement>) {
    const r = cardRef.current?.getBoundingClientRect();
    if (!r) return;
    mouseX.set(((e.clientX - r.left) / r.width) * 2 - 1);
    mouseY.set(((e.clientY - r.top) / r.height) * 2 - 1);
  }
  function onMouseLeave() {
    mouseX.set(0);
    mouseY.set(0);
  }

  // Entrance: slide from the image side
  const enterX = imageOnStart ? -60 : 60;

  return (
    <motion.article
      initial={{ opacity: 0, y: 48 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true, margin: "-80px" }}
      transition={{ duration: 0.8, ease, delay: 0.05 }}
      className="relative"
    >
      {/* Animated hairline separator (skipped for first) */}
      {index > 0 && (
        <motion.div
          className="mb-16 h-px w-full bg-gradient-to-r from-transparent via-primary/25 to-transparent"
          initial={{ scaleX: 0 }}
          whileInView={{ scaleX: 1 }}
          viewport={{ once: true }}
          transition={{ duration: 1.0, ease, delay: 0 }}
        />
      )}

      <div
        className={cn(
          "flex flex-col gap-8 lg:items-center lg:gap-0",
          imageOnStart ? "lg:flex-row" : "lg:flex-row-reverse"
        )}
      >
        {/* ── Image column ── */}
        <motion.div
          className="relative w-full shrink-0 lg:w-[48%]"
          initial={{ opacity: 0, x: enterX, filter: "blur(8px)" }}
          whileInView={{ opacity: 1, x: 0, filter: "blur(0px)" }}
          viewport={{ once: true, margin: "-60px" }}
          transition={{ duration: 0.9, ease, delay: 0.1 }}
        >
          <div
            ref={cardRef}
            onMouseMove={onMouseMove}
            onMouseLeave={onMouseLeave}
            className="relative overflow-hidden rounded-[24px] shadow-[0_24px_64px_rgba(13,52,48,0.12)]"
            style={{ perspective: 800 }}
          >
            <motion.div
              style={{ rotateX, rotateY }}
              className="relative h-[280px] sm:h-[360px] lg:h-[440px]"
            >
              {/* Clip-path reveal */}
              <motion.div
                className="absolute inset-0"
                initial={{ clipPath: "inset(0 100% 0 0 round 24px)" }}
                whileInView={{ clipPath: "inset(0 0% 0 0 round 24px)" }}
                viewport={{ once: true, margin: "-60px" }}
                transition={{ duration: 0.95, ease, delay: 0.2 }}
              >
                {service.imageSrc ? (
                  <motion.div
                    className="absolute inset-0"
                    initial={{ scale: 1.12 }}
                    whileInView={{ scale: 1 }}
                    viewport={{ once: true }}
                    transition={{ duration: 1.2, ease: "easeOut", delay: 0.2 }}
                    whileHover={{ scale: 1.04 }}
                  >
                    <Image
                      src={service.imageSrc}
                      alt={service.imageAlt ?? service.title}
                      fill
                      className="object-cover"
                      sizes="(max-width: 1024px) 100vw, 48vw"
                    />
                  </motion.div>
                ) : (
                  <div className="absolute inset-0 bg-gradient-to-br from-primary/20 to-primary/5" />
                )}
                {/* Gradient wash */}
                <div className="absolute inset-x-0 bottom-0 h-2/5 bg-gradient-to-t from-[rgba(13,52,48,0.35)] to-transparent" />
              </motion.div>

              {/* Index number on image */}
              <motion.span
                aria-hidden
                className="absolute bottom-4 end-5 font-bold text-white/20 leading-none select-none"
                style={{ fontSize: "clamp(56px, 8vw, 100px)" }}
                initial={{ opacity: 0, scale: 0.7 }}
                whileInView={{ opacity: 1, scale: 1 }}
                viewport={{ once: true }}
                transition={{ duration: 0.7, ease, delay: 0.55 }}
              >
                {num}
              </motion.span>
            </motion.div>
          </div>

          {/* Decorative teal ring accent */}
          {/* <motion.div
            aria-hidden
            className={cn(
              "pointer-events-none absolute -z-10 rounded-full border border-primary/20",
              imageOnStart ? "-bottom-6 -end-6" : "-bottom-6 -start-6"
            )}
            style={{ width: 160, height: 160 }}
            initial={{ opacity: 0, scale: 0.5 }}
            whileInView={{ opacity: 1, scale: 1 }}
            viewport={{ once: true }}
            transition={{ type: "spring", stiffness: 160, damping: 18, delay: 0.6 }}
          /> */}
          {/* <motion.div
            aria-hidden
            className={cn(
              "pointer-events-none absolute -z-10 rounded-full border border-primary/10",
              imageOnStart ? "-bottom-10 -end-10" : "-bottom-10 -start-10"
            )}
            style={{ width: 240, height: 240 }}
            initial={{ opacity: 0, scale: 0.5 }}
            whileInView={{ opacity: 1, scale: 1 }}
            viewport={{ once: true }}
            transition={{ type: "spring", stiffness: 130, damping: 20, delay: 0.72 }}
          /> */}
        </motion.div>

        {/* ── Content column ── */}
        <div
          className={cn(
            "relative flex w-full flex-col gap-5 lg:w-[52%] lg:px-12 xl:px-16",
            imageOnStart ? "items-start text-start" : "items-end text-end"
          )}
          dir={direction}
        >
          {/* Giant editorial number — background */}
          <motion.span
            aria-hidden
            className={cn(
              "pointer-events-none absolute -top-6 select-none font-bold leading-none text-primary/[0.06]",
              imageOnStart ? "-start-4 lg:start-8" : "-end-4 lg:end-8"
            )}
            style={{ fontSize: "clamp(100px, 14vw, 180px)" }}
            initial={{ opacity: 0, scale: 0.8, filter: "blur(12px)" }}
            whileInView={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
            viewport={{ once: true }}
            transition={{ duration: 0.9, ease, delay: 0.3 }}
          >
            {num}
          </motion.span>

          {/* Teal accent bar */}
          <motion.div
            className={cn("h-[3px] w-10 rounded-full bg-primary")}
            initial={{ scaleX: 0 }}
            whileInView={{ scaleX: 1 }}
            viewport={{ once: true }}
            style={{ originX: imageOnStart ? 0 : 1 }}
            transition={{ duration: 0.5, ease, delay: 0.25 }}
          />

          {/* Title */}
          <motion.h2
            className="relative text-[28px] font-bold leading-[1.25] text-foreground sm:text-[34px] lg:text-[40px]"
            initial={{ opacity: 0, y: 24, filter: "blur(8px)" }}
            whileInView={{ opacity: 1, y: 0, filter: "blur(0px)" }}
            viewport={{ once: true }}
            transition={{ duration: 0.7, ease, delay: 0.3 }}
          >
            {service.title}
          </motion.h2>

          {/* Description */}
          <motion.p
            className="max-w-[520px] text-[16px] leading-[1.9] text-muted-foreground"
            initial={{ opacity: 0, y: 16 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.65, ease, delay: 0.42 }}
          >
            {service.description}
          </motion.p>

          {/* CTAs */}
          <motion.div
            className={cn(
              "flex flex-wrap items-center gap-3 pt-2",
              imageOnStart ? "justify-start" : "justify-end"
            )}
            initial={{ opacity: 0, y: 12 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.55, ease, delay: 0.55 }}
          >
            <Link href={linkHref}>
              <motion.div
                whileHover={{ scale: 1.04, y: -2, boxShadow: "0 8px 24px -4px rgba(30,124,115,0.38)" }}
                whileTap={{ scale: 0.97 }}
                transition={{ duration: 0.2, ease: "easeOut" }}
                className="flex h-11 items-center gap-2 rounded-full bg-primary px-6 text-sm font-semibold text-white"
              >
                <DirectionalChevron direction={direction} className="h-4 w-4" />
                {browseLabel}
              </motion.div>
            </Link>

            <Link href="/contact-us">
              <motion.div
                whileHover={{ scale: 1.04, y: -2 }}
                whileTap={{ scale: 0.97 }}
                transition={{ duration: 0.2, ease: "easeOut" }}
                className="flex h-11 items-center gap-2 rounded-full border border-primary px-6 text-sm font-semibold text-primary"
              >
                {contactLabel}
              </motion.div>
            </Link>
          </motion.div>
        </div>
      </div>
    </motion.article>
  );
}

export function ServicesListClient({ services, direction, browseLabel, contactLabel }: Props) {
  return (
    <section className="relative overflow-hidden bg-[#FAFAF9] px-4 py-16 sm:px-8 lg:px-[80px] lg:py-24">
      {/* Ambient background orbs */}
      <div aria-hidden className="pointer-events-none absolute inset-0">
        <motion.div
          className="absolute rounded-full"
          style={{
            width: 600,
            height: 600,
            right: -200,
            top: "10%",
            background: "radial-gradient(ellipse, rgba(30,124,115,0.05) 0%, transparent 70%)",
            filter: "blur(80px)",
          }}
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 2, ease: "easeOut" }}
        />
        <motion.div
          className="absolute rounded-full"
          style={{
            width: 500,
            height: 500,
            left: -150,
            bottom: "15%",
            background: "radial-gradient(ellipse, rgba(0,174,157,0.06) 0%, transparent 70%)",
            filter: "blur(72px)",
          }}
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 2.4, ease: "easeOut", delay: 0.3 }}
        />
      </div>

      <div className="relative mx-auto flex max-w-[1300px] flex-col gap-16 lg:gap-24">
        {services.map((service, index) => (
          <ServicePanel
            key={service.slug}
            service={service}
            index={index}
            direction={direction}
            browseLabel={browseLabel}
            contactLabel={contactLabel}
          />
        ))}
      </div>
    </section>
  );
}
