"use client";

import { useEffect, useRef } from "react";

/**
 * Horizontal rail with continuous auto-slide (seamless marquee), hover-pause and
 * drag-to-swipe — mirrors the storefront's product/category rails. Children are
 * cloned in the DOM to loop; the rail is also natively scrollable/draggable.
 */
export default function AutoRail({
  children,
  railClassName = "",
  speed = 34,
}: {
  children: React.ReactNode;
  railClassName?: string;
  speed?: number;
}) {
  const railRef = useRef<HTMLDivElement>(null);
  const wrapRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const rail = railRef.current;
    const wrap = wrapRef.current;
    if (!rail || !wrap) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;

    let raf = 0;
    let paused = false;
    let down = false;
    let startX = 0;
    let startScroll = 0;
    let moved = false;
    let loopWidth = 0;

    // Clone children until the row overflows enough to loop seamlessly.
    const setup = () => {
      const kids = Array.prototype.slice.call(rail.children) as HTMLElement[];
      if (!kids.length) return;
      const base = rail.scrollWidth;
      const target = rail.clientWidth * 2 + base;
      let guard = 0;
      while (rail.scrollWidth < target && guard < 16) {
        kids.forEach((c) => {
          const cl = c.cloneNode(true) as HTMLElement;
          cl.setAttribute("aria-hidden", "true");
          cl.classList.add("pb-rail-clone");
          rail.appendChild(cl);
        });
        guard++;
      }
      const firstClone = rail.children[kids.length] as HTMLElement | undefined;
      loopWidth = firstClone ? firstClone.offsetLeft : base;
    };

    let last: number | null = null;
    const frame = (ts: number) => {
      if (last === null) last = ts;
      const dt = (ts - last) / 1000;
      last = ts;
      if (!paused && !down && !document.hidden && loopWidth) {
        rail.scrollLeft += speed * dt;
        if (rail.scrollLeft >= loopWidth) rail.scrollLeft -= loopWidth;
        else if (rail.scrollLeft < 0) rail.scrollLeft += loopWidth;
      }
      raf = requestAnimationFrame(frame);
    };

    const onEnter = () => { paused = true; };
    const onLeave = () => { if (!down) paused = false; };
    const onDown = (e: PointerEvent) => {
      paused = true;
      if (e.pointerType === "touch") return;
      down = true; moved = false; startX = e.clientX; startScroll = rail.scrollLeft;
      rail.classList.add("is-grabbing");
    };
    const onMove = (e: PointerEvent) => {
      if (!down) return;
      const dx = e.clientX - startX;
      if (Math.abs(dx) > 4) moved = true;
      rail.scrollLeft = startScroll - dx;
    };
    const endDrag = () => {
      if (!down) return;
      down = false;
      rail.classList.remove("is-grabbing");
      setTimeout(() => { paused = false; }, 1200);
    };
    const onClickCapture = (e: MouseEvent) => {
      if (moved) { e.preventDefault(); e.stopPropagation(); moved = false; return; }
      // Cloned cards are plain DOM (no React handlers), so delegate their
      // quick-add / wishlist clicks here using the buttons' data attributes.
      const target = e.target as HTMLElement;
      const clone = target.closest(".pb-rail-clone");
      if (!clone) return;
      const addBtn = target.closest<HTMLElement>(".pb-card-add");
      const wishBtn = target.closest<HTMLElement>(".pb-wish");
      if (addBtn) {
        e.preventDefault(); e.stopPropagation();
        import("@/lib/cart").then((m) => m.addToCart({
          id: addBtn.dataset.addId || "",
          name: addBtn.dataset.addName || "",
          brand: addBtn.dataset.addBrand || "",
          price: parseFloat(addBtn.dataset.addPrice || "0") || 0,
          image: addBtn.dataset.addImage || "",
          qty: 1,
        }));
      } else if (wishBtn) {
        e.preventDefault(); e.stopPropagation();
        import("@/lib/wishlist").then((m) => m.toggleWishlist({
          id: wishBtn.dataset.wishId || "",
          slug: wishBtn.dataset.wishSlug || "",
          name: wishBtn.dataset.wishName || "",
          brand: wishBtn.dataset.wishBrand || "",
          price: parseFloat(wishBtn.dataset.wishPrice || "0") || 0,
          oldPrice: wishBtn.dataset.wishOld ? parseFloat(wishBtn.dataset.wishOld) : null,
          image: wishBtn.dataset.wishImage || "",
        }));
      }
    };

    // Delay setup so layout/images settle, then start.
    const startTimer = setTimeout(() => {
      setup();
      raf = requestAnimationFrame(frame);
    }, 400);

    wrap.addEventListener("mouseenter", onEnter);
    wrap.addEventListener("mouseleave", onLeave);
    rail.addEventListener("pointerdown", onDown);
    window.addEventListener("pointermove", onMove);
    window.addEventListener("pointerup", endDrag);
    window.addEventListener("pointercancel", endDrag);
    rail.addEventListener("click", onClickCapture, true);

    return () => {
      clearTimeout(startTimer);
      cancelAnimationFrame(raf);
      wrap.removeEventListener("mouseenter", onEnter);
      wrap.removeEventListener("mouseleave", onLeave);
      rail.removeEventListener("pointerdown", onDown);
      window.removeEventListener("pointermove", onMove);
      window.removeEventListener("pointerup", endDrag);
      window.removeEventListener("pointercancel", endDrag);
      rail.removeEventListener("click", onClickCapture, true);
      rail.querySelectorAll(".pb-rail-clone").forEach((c) => c.remove());
    };
  }, [speed]);

  return (
    <div className="pb-rail-wrap" ref={wrapRef}>
      <div className={`pb-rail ${railClassName}`} data-rail ref={railRef}>
        {children}
      </div>
    </div>
  );
}
