"use client";

import { useRef } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { Poster, type PosterItem } from "./poster";

interface ContentRowProps {
  title: string;
  items: PosterItem[];
  showReason?: boolean;
  onMore?: () => void;
  moreLabel?: string;
}

export function ContentRow({ title, items, showReason, onMore, moreLabel = "همه" }: ContentRowProps) {
  const scrollRef = useRef<HTMLDivElement>(null);

  const scroll = (dir: 1 | -1) => {
    const el = scrollRef.current;
    if (!el) return;
    const amount = el.clientWidth * 0.8;
    el.scrollBy({ left: dir * amount, behavior: "smooth" });
  };

  if (!items?.length) return null;

  return (
    <section className="mb-8">
      <div className="flex items-center justify-between px-4 md:px-8 mb-3">
        <h2 className="flex items-center gap-2 text-lg md:text-xl font-bold text-foreground">
          <span className="h-5 w-1 rounded-full bg-gradient-brand" />
          {title}
        </h2>
        <div className="flex items-center gap-2">
          {onMore && (
            <button onClick={onMore} className="text-xs text-muted-foreground hover:text-accent transition">
              {moreLabel} ←
            </button>
          )}
          <div className="hidden md:flex gap-1">
            <button
              onClick={() => scroll(-1)}
              className="flex h-8 w-8 items-center justify-center rounded-full glass hover:bg-primary/20 transition"
              aria-label="قبلی"
            >
              <ChevronRight className="h-4 w-4" />
            </button>
            <button
              onClick={() => scroll(1)}
              className="flex h-8 w-8 items-center justify-center rounded-full glass hover:bg-primary/20 transition"
              aria-label="بعدی"
            >
              <ChevronLeft className="h-4 w-4" />
            </button>
          </div>
        </div>
      </div>
      <div
        ref={scrollRef}
        className="flex gap-3 md:gap-4 overflow-x-auto hide-scrollbar px-4 md:px-8 pb-2 scroll-snap-x"
        style={{ scrollbarWidth: "none" }}
      >
        {items.map((item, i) => (
          <div
            key={`${item.slug}-${i}`}
            className="snap-start shrink-0 w-[140px] sm:w-[160px] md:w-[180px] lg:w-[200px]"
          >
            <Poster item={item} showReason={showReason} className="w-full" />
          </div>
        ))}
      </div>
    </section>
  );
}

interface PosterGridProps {
  items: PosterItem[];
  className?: string;
}

export function PosterGrid({ items, className }: PosterGridProps) {
  return (
    <div className={cn("grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-3 md:gap-4", className)}>
      {items.map((item, i) => (
        <Poster key={`${item.slug}-${i}`} item={item} className="w-full" />
      ))}
    </div>
  );
}
