"use client";

import { SafeImage } from "@/components/ui/SafeImage";
import Link from "next/link";
import {
  useCallback,
  useEffect,
  useRef,
  useState,
  type MouseEvent,
  type ReactNode,
} from "react";
import { AnimatePresence, motion, type PanInfo } from "framer-motion";
import {
  ArrowRight,
  ChevronLeft,
  ChevronRight,
  Cpu,
  Sparkles,
} from "lucide-react";
import type { Product } from "@/data/types";
import { formatPrice } from "@/lib/format";
import { easeOut } from "@/lib/motion";
import { cn } from "@/lib/cn";

const AUTO_MS = 4000;
const RESUME_MS = 10000;

/** Marketplace hero: dark showcase + sliding product card + department promos. */
export function HeroMarketplace({ products = [] }: { products?: Product[] }) {
  const slides = (() => {
    const featured = products.filter((p) => p.featured);
    const flash = products.filter((p) => p.flashSale);
    const merged = [...featured, ...flash, ...products];
    const unique = merged.filter(
      (item, index, list) => list.findIndex((p) => p.id === item.id) === index,
    );
    return unique.slice(0, 8);
  })();

  const [index, setIndex] = useState(0);
  const [direction, setDirection] = useState(0);
  const [paused, setPaused] = useState(false);
  const indexRef = useRef(0);
  const busyRef = useRef(false);
  const dragXRef = useRef(0);
  const resumeTimer = useRef<number | null>(null);
  const active = slides[index] ?? slides[0];

  useEffect(() => {
    indexRef.current = index;
  }, [index]);

  const clearResume = () => {
    if (resumeTimer.current != null) {
      window.clearTimeout(resumeTimer.current);
      resumeTimer.current = null;
    }
  };

  const pauseAutoplay = useCallback((resumeAfter = true) => {
    setPaused(true);
    clearResume();
    if (resumeAfter) {
      resumeTimer.current = window.setTimeout(() => {
        setPaused(false);
        resumeTimer.current = null;
      }, RESUME_MS);
    }
  }, []);

  const goTo = useCallback(
    (nextIndex: number, dir: number) => {
      if (!slides.length || busyRef.current) return;
      busyRef.current = true;
      setDirection(dir);
      setIndex((nextIndex + slides.length) % slides.length);
      window.setTimeout(() => {
        busyRef.current = false;
      }, 650);
    },
    [slides.length],
  );

  const next = useCallback(() => {
    goTo(indexRef.current + 1, 1);
  }, [goTo]);

  const prev = useCallback(() => {
    goTo(indexRef.current - 1, -1);
  }, [goTo]);

  useEffect(() => {
    if (slides.length < 2 || paused) return;
    const id = window.setInterval(() => {
      if (busyRef.current) return;
      goTo(indexRef.current + 1, 1);
    }, AUTO_MS);
    return () => window.clearInterval(id);
  }, [slides.length, paused, goTo]);

  useEffect(() => () => clearResume(), []);

  const onDragStart = () => {
    dragXRef.current = 0;
    pauseAutoplay(false);
  };

  const onDrag = (_: unknown, info: PanInfo) => {
    dragXRef.current = info.offset.x;
  };

  const onDragEnd = (_: unknown, info: PanInfo) => {
    const offset = info.offset.x;
    const velocity = info.velocity.x;
    dragXRef.current = offset;

    if (offset < -36 || velocity < -250) {
      next();
    } else if (offset > 36 || velocity > 250) {
      prev();
    }

    // Reset after click handlers can inspect drag distance.
    window.setTimeout(() => {
      dragXRef.current = 0;
    }, 80);
  };

  const guardLinkClick = (event: MouseEvent) => {
    if (Math.abs(dragXRef.current) > 12) {
      event.preventDefault();
      event.stopPropagation();
    }
  };

  const slideTransition = {
    duration: 0.62,
    ease: easeOut,
  };

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

  return (
    <section className="border-b border-border bg-background">
      <div className="mx-auto grid w-full max-w-7xl gap-4 px-4 py-6 sm:gap-5 sm:px-6 lg:grid-cols-[minmax(0,1.55fr)_minmax(260px,0.72fr)] lg:items-stretch lg:px-8 lg:py-8">
        <motion.div
          initial={{ opacity: 0, y: 18 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.55, ease: easeOut }}
          className="relative overflow-hidden rounded-[1.75rem] bg-[#0b0b0f] text-white shadow-[0_24px_60px_rgba(0,0,0,0.18)]"
        >
          <div
            className="pointer-events-none absolute inset-0"
            style={{
              background:
                "radial-gradient(circle at 78% 45%, rgba(180,30,40,0.38), transparent 42%)",
            }}
          />

          <div className="relative grid min-h-[360px] items-center gap-5 px-4 py-7 sm:min-h-[480px] sm:gap-6 sm:px-8 sm:py-10 lg:grid-cols-[1.05fr_0.95fr] lg:gap-4 lg:px-10">
            <div className="max-w-xl">
              <motion.span
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.1, duration: 0.45, ease: easeOut }}
                className="inline-flex rounded-full bg-[#e11d2e] px-3 py-1 text-[10px] font-bold uppercase tracking-[0.14em] text-white"
              >
                SiloMart grocery
              </motion.span>

              <motion.h1
                initial={{ opacity: 0, y: 14 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.16, duration: 0.5, ease: easeOut }}
                className="mt-4 text-[1.85rem] font-bold leading-[1.12] tracking-tight sm:text-4xl lg:text-[2.55rem]"
              >
                Quality essentials, radical prices
              </motion.h1>

              <motion.p
                initial={{ opacity: 0, y: 14 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.22, duration: 0.5, ease: easeOut }}
                className="mt-3 text-sm text-zinc-300 sm:text-base"
              >
                Shop electronics, home, kitchen, beauty, sports, and more.
              </motion.p>

              <motion.ul
                initial={{ opacity: 0, y: 14 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.28, duration: 0.5, ease: easeOut }}
                className="mt-5 space-y-2 text-[12px] font-semibold uppercase tracking-[0.06em] text-white sm:text-[13px]"
              >
                <li className="flex items-center gap-2">
                  <span className="h-1.5 w-1.5 rounded-full bg-[#e11d2e]" />
                  100+ unique products
                </li>
                <li className="flex items-center gap-2">
                  <span className="h-1.5 w-1.5 rounded-full bg-[#e11d2e]" />
                  Electronics · Home · Beauty · Sports
                </li>
                <li className="flex items-center gap-2">
                  <span className="h-1.5 w-1.5 rounded-full bg-[#e11d2e]" />
                  Free shipping over $75
                </li>
              </motion.ul>

              <motion.div
                initial={{ opacity: 0, y: 14 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.34, duration: 0.5, ease: easeOut }}
                className="mt-7 flex flex-wrap gap-3"
              >
                <Link
                  href="/shop"
                  className="inline-flex h-11 items-center gap-2 rounded-full bg-white pl-5 pr-2 text-sm font-semibold text-zinc-950 transition hover:bg-zinc-100"
                >
                  Shop collection
                  <span className="inline-flex h-8 w-8 items-center justify-center rounded-full bg-[#e11d2e] text-white">
                    <ArrowRight className="h-4 w-4" />
                  </span>
                </Link>
                <Link
                  href="/categories"
                  className="inline-flex h-11 items-center rounded-full border border-white/35 px-5 text-sm font-semibold text-white transition hover:bg-white/10"
                >
                  Browse categories
                </Link>
              </motion.div>
            </div>

            <div
              className="relative mx-auto w-full max-w-[300px] sm:max-w-[340px]"
              onMouseEnter={() => pauseAutoplay(false)}
              onMouseLeave={() => {
                clearResume();
                setPaused(false);
              }}
              onFocusCapture={() => pauseAutoplay(false)}
              onBlurCapture={(event) => {
                if (!event.currentTarget.contains(event.relatedTarget as Node)) {
                  clearResume();
                  setPaused(false);
                }
              }}
            >
              <button
                type="button"
                onClick={() => {
                  pauseAutoplay();
                  prev();
                }}
                aria-label="Previous product"
                className="absolute left-1 top-1/2 z-20 flex h-9 w-9 -translate-y-1/2 items-center justify-center rounded-full border border-white/15 bg-zinc-950/80 text-white shadow-lg backdrop-blur-md transition hover:scale-105 hover:bg-zinc-900 sm:left-0 sm:h-10 sm:w-10 sm:-translate-x-1/2"
              >
                <ChevronLeft className="h-5 w-5" />
              </button>
              <button
                type="button"
                onClick={() => {
                  pauseAutoplay();
                  next();
                }}
                aria-label="Next product"
                className="absolute right-1 top-1/2 z-20 flex h-9 w-9 -translate-y-1/2 items-center justify-center rounded-full border border-white/15 bg-zinc-950/80 text-white shadow-lg backdrop-blur-md transition hover:scale-105 hover:bg-zinc-900 sm:right-0 sm:h-10 sm:w-10 sm:translate-x-1/2"
              >
                <ChevronRight className="h-5 w-5" />
              </button>

              <div className="relative overflow-hidden rounded-[1.35rem] border border-white/10 bg-zinc-900/70 shadow-[0_28px_60px_rgba(0,0,0,0.45)] backdrop-blur-md">
                <AnimatePresence custom={direction} mode="wait" initial={false}>
                  {active ? (
                    <motion.div
                      key={active.id}
                      custom={direction}
                      variants={variants}
                      initial="enter"
                      animate="center"
                      exit="exit"
                      transition={slideTransition}
                      drag="x"
                      dragConstraints={{ left: 0, right: 0 }}
                      dragElastic={0.35}
                      dragMomentum={false}
                      onDragStart={onDragStart}
                      onDrag={onDrag}
                      onDragEnd={onDragEnd}
                      className="cursor-grab touch-pan-y active:cursor-grabbing"
                    >
                      <div className="px-4 pt-4">
                        <span className="inline-flex items-center gap-1 rounded-full border border-white/10 bg-white/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-wide text-zinc-200">
                          {active.category}
                        </span>
                      </div>

                      <Link
                        href={`/product/${active.id}`}
                        prefetch
                        onClick={guardLinkClick}
                        draggable={false}
                        className="relative mx-auto mt-2 block aspect-square w-[86%] overflow-hidden rounded-2xl"
                      >
                        <SafeImage
                          src={active.images[0]}
                          alt={active.name}
                          fill
                          priority
                          sizes="280px"
                          className="pointer-events-none object-cover"
                          draggable={false}
                        />
                      </Link>

                      <div className="mt-1 flex justify-center gap-1.5 pb-3">
                        {slides.map((slide, dotIndex) => (
                          <button
                            key={slide.id}
                            type="button"
                            aria-label={`Go to slide ${dotIndex + 1}`}
                            onClick={() => {
                              pauseAutoplay();
                              goTo(
                                dotIndex,
                                dotIndex > indexRef.current ? 1 : -1,
                              );
                            }}
                            className={cn(
                              "h-1.5 rounded-full transition-all duration-500 ease-out",
                              dotIndex === index
                                ? "w-5 bg-[#e11d2e]"
                                : "w-1.5 bg-white/30 hover:bg-white/50",
                            )}
                          />
                        ))}
                      </div>

                      <Link
                        href={`/product/${active.id}`}
                        onClick={guardLinkClick}
                        draggable={false}
                        className="flex items-center justify-between gap-3 border-t border-white/10 bg-black/45 px-4 py-3.5 text-white backdrop-blur-sm"
                      >
                        <div className="min-w-0">
                          <p className="truncate text-sm font-medium">
                            {active.name}
                          </p>
                          <p className="mt-0.5 text-base font-bold tabular-nums">
                            {formatPrice(active.price)}
                          </p>
                        </div>
                        <span className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[#e11d2e]">
                          <ArrowRight className="h-4 w-4" />
                        </span>
                      </Link>
                    </motion.div>
                  ) : null}
                </AnimatePresence>
              </div>
            </div>
          </div>
        </motion.div>

        <div className="grid min-h-[220px] gap-4 sm:grid-cols-2 lg:grid-cols-1 lg:gap-5">
          <PromoCard
            href="/categories/electronics"
            title="Electronics"
            text="Smart displays, audio, charging & everyday tech"
            delay={0.12}
            icon={<Cpu className="h-6 w-6 text-white" />}
            gradient="linear-gradient(135deg, #dbeafe 0%, #60a5fa 48%, #2563eb 100%)"
            glow="rgba(37, 99, 235, 0.55)"
            iconBg="#1d4ed8"
          />
          <PromoCard
            href="/categories/home-living"
            title="Home & Living"
            text="Furniture, lighting, and comfort for every room"
            delay={0.2}
            icon={<Sparkles className="h-6 w-6 text-white" />}
            gradient="linear-gradient(135deg, #ecfccb 0%, #a3e635 45%, #65a30d 100%)"
            glow="rgba(101, 163, 13, 0.5)"
            iconBg="#4d7c0f"
          />
        </div>
      </div>
    </section>
  );
}

function PromoCard({
  href,
  title,
  text,
  icon,
  delay,
  gradient,
  glow,
  iconBg,
}: {
  href: string;
  title: string;
  text: string;
  icon: ReactNode;
  delay: number;
  gradient: string;
  glow: string;
  iconBg: string;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 18 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay, duration: 0.5, ease: easeOut }}
      whileHover={{ y: -4, scale: 1.012 }}
      className="h-full min-h-[180px]"
    >
      <Link
        href={href}
        className="group/promo relative flex h-full min-h-[180px] flex-col justify-between overflow-hidden rounded-[1.5rem] p-5 shadow-[0_16px_40px_rgba(15,23,42,0.18)] sm:p-6 lg:min-h-[210px]"
        style={{ backgroundImage: gradient }}
      >
        <div
          className="pointer-events-none absolute inset-0"
          style={{
            background: `radial-gradient(circle at 82% 18%, ${glow}, transparent 52%)`,
          }}
        />
        <div
          aria-hidden
          className="pointer-events-none absolute -right-8 -top-10 h-40 w-40 rounded-full opacity-40 blur-2xl"
          style={{ background: glow }}
        />
        <span aria-hidden className="promo-reflection" />
        <div className="relative z-[3]">
          <div
            className="mb-4 inline-flex h-12 w-12 items-center justify-center rounded-2xl shadow-lg ring-2 ring-white/50"
            style={{ backgroundColor: iconBg }}
          >
            {icon}
          </div>
          <h2 className="text-lg font-bold tracking-tight text-zinc-950 drop-shadow-sm">
            {title}
          </h2>
          <p className="mt-1 text-sm font-medium text-zinc-800/85">{text}</p>
        </div>
        <span className="relative z-[3] mt-5 inline-flex h-9 w-fit items-center gap-1 rounded-full bg-white px-3.5 text-xs font-semibold text-zinc-900 shadow-md">
          Shop now
          <ArrowRight className="h-3.5 w-3.5" />
        </span>
      </Link>
    </motion.div>
  );
}
