"use client";

import React, { useRef, useState, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import { m } from "framer-motion";
import { ArrowRight, ChevronLeft, ChevronRight, Flame, Sparkles, Layers, Image as ImageIcon } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { getProductFormatLabels, localizeProductDescription, localizeProductName, localizeSeriesName } from "@/lib/product-i18n";

interface ProductImage {
  id: string;
  url: string;
  alt: string | null;
  order: number;
}

interface Series {
  id: string;
  name: string;
}

interface Category {
  id: string;
  name: string;
}

interface Product {
  id: string;
  slug: string;
  sku: string | null;
  name: string;
  nameTr: string | null;
  nameEn: string | null;
  nameRu: string | null;
  widthCm: number | null;
  surface: string | null;
  burnerCount: number | null;
  description: string | null;
  descriptionTr: string | null;
  descriptionEn: string | null;
  descriptionRu: string | null;
  images: ProductImage[];
  series: Series | null;
  category: Category;
}

interface FeaturedProductsProps {
  products: Product[];
}

export default function FeaturedProducts({ products }: FeaturedProductsProps) {
  const t = useTranslations();
  const locale = useLocale();
  const scrollRef = useRef<HTMLDivElement>(null);
  const [isMobile, setIsMobile] = useState(false);

  // Check screen size to optimize marquee / swipe experience on mobile devices
  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < 768);
    };
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const scrollLeft = () => {
    if (scrollRef.current) {
      scrollRef.current.scrollBy({ left: -380, behavior: "smooth" });
    }
  };

  const scrollRight = () => {
    if (scrollRef.current) {
      scrollRef.current.scrollBy({ left: 380, behavior: "smooth" });
    }
  };

  // Duplicate list items to create a seamless slow auto-scroll marquee loop on desktop
  const marqueeItems = [...products, ...products, ...products];

  return (
    <section
      className="py-20 md:py-32 flex flex-col justify-center snap-start w-full overflow-hidden"
      style={{ background: "var(--surface-1)" }}
    >
      {/* Header — title from left, controls from right */}
      <div className="w-full max-w-7xl mx-auto px-6 md:px-12 mb-12 flex flex-col sm:flex-row sm:items-end justify-between gap-6">
        <m.div
          initial={{ opacity: 0, x: -50 }}
          whileInView={{ opacity: 1, x: 0 }}
          viewport={{ once: true, margin: "-60px" }}
          transition={{ duration: 0.8, ease: [0.16, 1, 0.3, 1] }}
        >
          <span className="eyebrow">{t("featured.eyebrow")}</span>
          <h2 className="section-title">{t("featured.title")}</h2>
        </m.div>

        <m.div
          initial={{ opacity: 0, x: 50 }}
          whileInView={{ opacity: 1, x: 0 }}
          viewport={{ once: true, margin: "-60px" }}
          transition={{ duration: 0.8, ease: [0.16, 1, 0.3, 1] }}
          className="flex items-center gap-4"
        >
          <Link
            href={`/${locale}/products`}
            className="font-sans text-xs uppercase tracking-widest flex items-center gap-2 group transition-colors duration-300 mr-2"
            style={{ color: "var(--fg-secondary)" }}
            onMouseEnter={(e) => (e.currentTarget.style.color = "var(--ember)")}
            onMouseLeave={(e) => (e.currentTarget.style.color = "var(--fg-secondary)")}
          >
            {t("featured.view_all")}
            <ArrowRight size={14} className="transform group-hover:translate-x-1 transition-transform" />
          </Link>

          {/* Slider Navigation Buttons */}
          <div className="hidden md:flex items-center gap-2">
            <button
              onClick={scrollLeft}
              className="w-10 h-10 rounded-full flex items-center justify-center transition-all duration-200 cursor-pointer hover:scale-105 active:scale-95"
              style={{ border: "1px solid var(--border)", background: "transparent", color: "var(--fg-secondary)" }}
              aria-label={t("catalog.previous")}
            >
              <ChevronLeft size={16} />
            </button>
            <button
              onClick={scrollRight}
              className="w-10 h-10 rounded-full flex items-center justify-center transition-all duration-200 cursor-pointer hover:scale-105 active:scale-95"
              style={{ border: "1px solid var(--border)", background: "transparent", color: "var(--fg-secondary)" }}
              aria-label={t("catalog.next")}
            >
              <ChevronRight size={16} />
            </button>
          </div>
        </m.div>
      </div>

      {/* Scroll Area */}
      <div className="relative w-full overflow-hidden">
        <div className="absolute inset-y-0 left-0 w-12 md:w-28 z-10 pointer-events-none" style={{ background: "linear-gradient(to right, var(--surface-1), transparent)" }} />
        <div className="absolute inset-y-0 right-0 w-12 md:w-28 z-10 pointer-events-none" style={{ background: "linear-gradient(to left, var(--surface-1), transparent)" }} />

        {/* Scrollable Track container */}
        <div
          ref={scrollRef}
          className="overflow-x-auto snap-x snap-mandatory scrollbar-none pb-6 scroll-smooth select-none w-full flex"
          style={{ 
            scrollbarWidth: "none",
          }}
        >
          {/* Inner track that auto-scrolls dynamically via CSS marquee-slow, aligns with container margins */}
          <div 
            className={`flex gap-6 px-6 md:px-12 xl:px-[calc((100vw-1280px)/2+3rem)] scroll-pl-6 md:scroll-pl-12 xl:scroll-pl-[calc((100vw-1280px)/2+3rem)] ${
              isMobile ? "" : "animate-marquee-slow"
            }`}
          >
            {marqueeItems.map((product, index) => (
              <div 
                key={`${product.id}-${index}`} 
                className="snap-start flex-shrink-0 w-[290px] sm:w-[330px] md:w-[360px]"
              >
                <ProductCard product={product} index={index % products.length} locale={locale} />
              </div>
            ))}
          </div>
        </div>
      </div>

    </section>
  );
}

interface ProductCardProps {
  product: Product;
  index: number;
  locale: string;
}

function ProductCard({ product, index, locale }: ProductCardProps) {
  const t = useTranslations();
  const [imageError, setImageError] = useState(false);
  const mainImage = product.images?.[0]?.url || "/brand/norden.png";
  const formatLabels = getProductFormatLabels(product, locale);

  const renderSurfaceIcon = () => {
    if (!product.surface) return null;
    const s = product.surface.toLowerCase();
    if (s.includes("cam")) {
      return <Sparkles size={12} className="text-ember" />;
    } else if (s.includes("inox") || s.includes("metal") || s.includes("çelik")) {
      return <Layers size={12} className="text-ember" />;
    }
    return <Flame size={12} className="text-ember" />;
  };

  return (
    <m.div
      initial={{ opacity: 0, y: 30 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true, margin: "-50px" }}
      transition={{ duration: 0.8, delay: index * 0.08, ease: [0.16, 1, 0.3, 1] }}
      className="w-full h-full"
    >
      {/* Redesigned card container: rounded-[32px] (rounded-3xl) & overflow-hidden */}
      <div className="group relative rounded-[32px] bg-bg-panel border border-white/5 overflow-hidden flex flex-col h-full hover:border-white/10 hover:-translate-y-1.5 hover:shadow-[0_20px_45px_rgba(0,0,0,0.65)] transition-all duration-500 hover-line-effect">
        
        {/* Upper Part: Product Image (aspect-square) */}
        <Link 
          href={`/${locale}/products/${product.slug}`} 
          className="relative aspect-square w-full bg-black/10 overflow-hidden flex items-center justify-center"
        >
          {!imageError ? (
            <Image
              src={mainImage}
              alt={localizeProductName(product, locale)}
              fill
              onError={() => setImageError(true)}
              className="object-cover scale-95 group-hover:scale-100 transition-transform duration-700 ease-out"
              sizes="(max-width: 768px) 100vw, 33vw"
            />
          ) : (
            <div className="flex flex-col items-center justify-center text-text-muted">
              <ImageIcon size={36} className="stroke-[1] mb-2" />
              <span className="font-sans text-xs tracking-wider">{t("catalog.image_unavailable")}</span>
            </div>
          )}

          {/* Surface badge left side */}
          {formatLabels.length > 0 && (
            <div className="absolute bottom-4 left-4 z-10">
              <span className="glass-pill px-2.5 py-1 rounded-full font-sans text-[10px] text-text-secondary flex items-center gap-1.5 backdrop-blur-md">
                {renderSurfaceIcon()}
                {formatLabels.join(" · ")}
              </span>
            </div>
          )}
        </Link>

        {/* Lower Part: Product name + series badge + width info */}
        <div className="p-6 flex flex-col flex-grow">
          <div className="flex items-center justify-between mb-3">
            {product.series ? (
              <span className="glass-pill px-3 py-1 rounded-full font-mono text-[9px] uppercase tracking-widest text-ember font-medium">
                {t("catalog.series_label", { name: localizeSeriesName(product.series.name) })}
              </span>
            ) : (
              <span className="glass-pill px-3 py-1 rounded-full font-mono text-[9px] uppercase tracking-widest text-text-secondary font-medium">
                NORDEN
              </span>
            )}
            
            {product.widthCm && (
              <span className="font-mono text-[10px] text-text-muted tracking-wider">
                {t("catalog.width_label", { width: product.widthCm })}
              </span>
            )}
          </div>

          {/* Product Name */}
          <h3 className="font-serif text-xl font-light text-text-primary group-hover:text-ember-bright transition-colors duration-300 mb-3">
            <Link href={`/${locale}/products/${product.slug}`}>
              {localizeProductName(product, locale)}
            </Link>
          </h3>

          {/* Description */}
          {product.description && (
            <p className="font-sans text-xs text-text-secondary leading-relaxed line-clamp-2 mb-6">
              {localizeProductDescription(product, locale)}
            </p>
          )}

          {/* Details CTA Link */}
          <div className="mt-auto pt-4 border-t border-white/5 flex items-center justify-between">
            <span className="font-mono text-[10px] text-text-muted uppercase tracking-wider">
              {product.sku || "NORDEN-APPLIANCE"}
            </span>
            
            <Link
              href={`/${locale}/products/${product.slug}`}
              className="font-sans text-xs uppercase tracking-widest text-ember font-medium hover:text-text-primary flex items-center gap-1 group transition-colors duration-200"
            >
              {t("featured.details")}
              <ArrowRight size={12} className="transform group-hover:translate-x-0.5 transition-transform" />
            </Link>
          </div>
        </div>

      </div>
    </m.div>
  );
}
