'use client';

/**
 * Categories Section — ShineCode
 * 
 * Premium, visual "Category Discovery" section immediately below Hero:
 * - Loaded dynamically from the live API categories
 * - 5 cards visible per view on desktop in a fluid horizontal track
 * - Explicit dimensions (w-[260px] md:w-[calc((100%-64px)/5)] h-[340px] md:h-[380px]) preventing 0px collapse on web
 * - Two small circular navigation arrows (Left / Right) positioned BEFORE "View All"
 * - Instagram Story / Reel style portrait cards with smooth hover zoom & glassmorphic price pills
 * - Full dark mode and RTL support
 */

import React, { useRef } from 'react';
import Link from 'next/link';
import { ChevronLeft, ChevronRight, ArrowRight } from 'lucide-react';
import { PriceDisplay } from '../PriceDisplay';
import { ImageWithFallback } from '@/components/ui/ImageWithFallback';
import type { Category } from '@shinecode/api-client/types';

interface CategoriesProps {
  categories?: Category[];
  /** Map of category_id → minimum service price, derived from getServices() in parent RSC */
  minPriceByCategory?: Record<number, number>;
  locale: string;
}

const CATEGORY_IMAGE_MAPPING: Record<string, { image: string; alt: string }> = {
  nails: {
    image: 'https://images.unsplash.com/photo-1632345031435-8727f6897d53?w=800&auto=format&fit=crop&q=85',
    alt: 'Luxury nails and manicure service',
  },
  hair: {
    image: 'https://images.unsplash.com/photo-1562322140-8baeececf3df?w=800&auto=format&fit=crop&q=85',
    alt: 'Professional hair styling and blowdry',
  },
  massage: {
    image: 'https://images.unsplash.com/photo-1544161515-4ab6ce6db874?w=800&auto=format&fit=crop&q=85',
    alt: 'Relaxing spa and therapeutic massage',
  },
  spa: {
    image: 'https://images.unsplash.com/photo-1544161515-4ab6ce6db874?w=800&auto=format&fit=crop&q=85',
    alt: 'Relaxing spa and therapeutic massage',
  },
  facials: {
    image: 'https://images.unsplash.com/photo-1570172619644-dfd03ed5d881?w=800&auto=format&fit=crop&q=85',
    alt: 'Aesthetic facial treatments and skincare',
  },
  skin: {
    image: 'https://images.unsplash.com/photo-1570172619644-dfd03ed5d881?w=800&auto=format&fit=crop&q=85',
    alt: 'Aesthetic facial treatments and skincare',
  },
  treatment: {
    image: 'https://images.unsplash.com/photo-1570172619644-dfd03ed5d881?w=800&auto=format&fit=crop&q=85',
    alt: 'Aesthetic facial treatments and skincare',
  },
  lashes: {
    image: 'https://images.unsplash.com/photo-1583001931096-959e9a1a6223?w=800&auto=format&fit=crop&q=85',
    alt: 'Lash lift and extensions',
  },
  'mens-grooming': {
    image: 'https://images.unsplash.com/photo-1622286342621-4bd786c2447c?w=800&auto=format&fit=crop&q=85',
    alt: "Premium men's grooming and haircut",
  },
};

const DEFAULT_CATEGORIES: Array<{ id: number; slug: string; name: string; startingPrice: number; image: string }> = [
  { id: 9, slug: 'spa', name: 'SPA & Massage', startingPrice: 199, image: 'https://images.unsplash.com/photo-1544161515-4ab6ce6db874?w=800&auto=format&fit=crop&q=85' },
  { id: 10, slug: 'skin-care', name: 'Skin Care & Facials', startingPrice: 250, image: 'https://images.unsplash.com/photo-1570172619644-dfd03ed5d881?w=800&auto=format&fit=crop&q=85' },
  { id: 11, slug: 'lashes-eyebrows', name: 'Lashes & Eyebrows', startingPrice: 149, image: 'https://images.unsplash.com/photo-1583001931096-959e9a1a6223?w=800&auto=format&fit=crop&q=85' },
  { id: 12, slug: 'nail-care', name: 'Nails & Pedicure', startingPrice: 120, image: 'https://images.unsplash.com/photo-1632345031435-8727f6897d53?w=800&auto=format&fit=crop&q=85' },
  { id: 13, slug: 'hair-care', name: 'Hair & Styling', startingPrice: 150, image: 'https://images.unsplash.com/photo-1562322140-8baeececf3df?w=800&auto=format&fit=crop&q=85' },
  { id: 14, slug: 'mens-grooming', name: "Men's Grooming", startingPrice: 140, image: 'https://images.unsplash.com/photo-1622286342621-4bd786c2447c?w=800&auto=format&fit=crop&q=85' },
];

export function Categories({ categories = [], minPriceByCategory = {}, locale }: CategoriesProps) {
  const isAr = locale === 'ar';
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  const scroll = (direction: 'left' | 'right') => {
    if (!scrollContainerRef.current) return;
    const container = scrollContainerRef.current;
    // Scroll by roughly 1 page of cards (or container width)
    const scrollAmount = container.clientWidth * 0.75;
    const offset = direction === 'left' ? -scrollAmount : scrollAmount;
    const signedOffset = isAr ? -offset : offset;
    container.scrollBy({ left: signedOffset, behavior: 'smooth' });
  };

  const sourceList = categories.length > 0 ? categories : DEFAULT_CATEGORIES;

  // Connect live API categories directly with intelligent image fallback & live starting prices
  const displayCategories = sourceList.map((cat) => {
    let img =
      'category_image' in cat && cat.category_image && !cat.category_image.includes('default.png')
        ? cat.category_image
        : 'image' in cat && typeof cat.image === 'string'
        ? cat.image
        : null;

    let alt = cat.name;

    if (!img) {
      const slug = (cat.slug || cat.name || '').toLowerCase();
      const matchedKey = Object.keys(CATEGORY_IMAGE_MAPPING).find(
        (k) =>
          slug.includes(k) ||
          k.includes(slug) ||
          (k === 'lashes' && (slug.includes('lash') || slug.includes('brow') || slug.includes('eye'))) ||
          (k === 'facials' && slug.includes('skin')) ||
          (k === 'mens-grooming' && (slug.includes('men') || slug.includes('barber')))
      );
      if (matchedKey) {
        img = CATEGORY_IMAGE_MAPPING[matchedKey].image;
        alt = CATEGORY_IMAGE_MAPPING[matchedKey].alt;
      } else {
        img =
          'https://images.unsplash.com/photo-1632345031435-8727f6897d53?w=800&auto=format&fit=crop&q=85';
      }
    }

    const startingPrice =
      minPriceByCategory[cat.id] !== undefined
        ? minPriceByCategory[cat.id]
        : 'startingPrice' in cat && typeof cat.startingPrice === 'number'
        ? cat.startingPrice
        : 149;

    return {
      id: cat.id,
      slug: cat.slug || String(cat.id),
      name: cat.name,
      startingPrice,
      image: img,
      alt: alt,
    };
  });

  return (
    <section id="categories" className="py-16 md:py-24 bg-white dark:bg-zinc-950 border-b border-zinc-100 dark:border-zinc-900 transition-colors duration-200">
      <div className="container mx-auto px-4 lg:px-8">
        {/* ── 1. Section Header (Arrows BEFORE "View All") ── */}
        <div className="flex items-end justify-between mb-8 md:mb-10">
          <div>
            <h2 className="text-2xl sm:text-3xl md:text-4xl font-extrabold text-zinc-950 dark:text-white tracking-tight">
              {isAr ? 'استكشف تصنيفاتنا.' : 'Explore our categories.'}
            </h2>
          </div>

          <div className="flex items-center gap-3 sm:gap-4">
            {/* Small circular previous/next navigation arrows BEFORE View All (Hidden on mobile) */}
            <div className="hidden sm:flex items-center gap-1.5">
              <button
                type="button"
                onClick={() => scroll('left')}
                aria-label={isAr ? 'التصنيفات السابقة' : 'Previous categories'}
                className="w-8 h-8 rounded-full border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 flex items-center justify-center text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors shadow-2xs cursor-pointer active:scale-95"
              >
                {isAr ? <ChevronRight className="w-4 h-4" /> : <ChevronLeft className="w-4 h-4" />}
              </button>
              <button
                type="button"
                onClick={() => scroll('right')}
                aria-label={isAr ? 'التصنيفات التالية' : 'Next categories'}
                className="w-8 h-8 rounded-full border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 flex items-center justify-center text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors shadow-2xs cursor-pointer active:scale-95"
              >
                {isAr ? <ChevronLeft className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
              </button>
            </div>

            {/* View All Link */}
            <Link
              href={`/${locale}/services`}
              className="group inline-flex items-center gap-1.5 text-xs sm:text-sm font-semibold text-zinc-500 dark:text-zinc-400 hover:text-zinc-950 dark:hover:text-white transition-colors pb-0.5"
            >
              <span>{isAr ? 'عرض الكل' : 'View All'}</span>
              <ArrowRight className="w-3.5 h-3.5 sm:w-4 sm:h-4 transition-transform group-hover:translate-x-1 rtl:rotate-180 rtl:group-hover:-translate-x-1" />
            </Link>
          </div>
        </div>

        {/* ── 2. Category Cards Track (5 per view on desktop, explicit width & height to prevent collapse) ── */}
        <div
          ref={scrollContainerRef}
          className="flex overflow-x-auto scroll-smooth snap-x snap-mandatory gap-4 pb-4 -mx-4 px-4 hide-scrollbar md:mx-0 md:px-0 [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]"
        >
          {displayCategories.map((category) => (
            <Link
              key={category.id}
              href={`/${locale}/categories/${category.slug}`}
              className="group relative category-card-slide rounded-2xl overflow-hidden cursor-pointer border border-zinc-200/80 dark:border-zinc-800 shadow-xs hover:shadow-xl transition-all duration-500 bg-zinc-100 dark:bg-zinc-900 block snap-start"
            >
              {/* Background Image with Hover Zoom & Local Fallback */}
              <ImageWithFallback
                src={category.image}
                fallbackSrc="/images/fallback-placeholder.svg"
                alt={category.alt}
                fill
                sizes="(max-width: 640px) 260px, (max-width: 1024px) 280px, 20vw"
                className="object-cover w-full h-full transition-transform duration-700 ease-out group-hover:scale-105 pointer-events-none"
              />

              {/* Dark Gradient Overlay for Maximum Text Legibility */}
              <div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/30 to-transparent pointer-events-none transition-opacity duration-300 group-hover:from-black/90" />

              {/* Card Text & Glass Price Tag (Bottom-Left) */}
              <div className="absolute bottom-0 left-0 p-4 sm:p-5 w-full text-start z-10 pointer-events-none">
                <h3 className="text-lg sm:text-xl font-bold text-white tracking-tight leading-snug drop-shadow-xs mb-1.5 group-hover:text-brand-300 transition-colors line-clamp-1">
                  {category.name}
                </h3>

                {/* Glassmorphic Starting Price Tag */}
                <div className="inline-flex items-center gap-1 text-xs font-medium text-white/90 bg-white/15 backdrop-blur-md px-2.5 py-1 rounded-full border border-white/20 shadow-xs">
                  <span className="text-white/80">{isAr ? 'يبدأ من' : 'Starting at'}</span>
                  <PriceDisplay
                    amount={category.startingPrice}
                    className="text-white font-semibold"
                    iconClassName="w-[0.85em] h-[0.85em] mr-0.5 inline-block shrink-0 align-baseline text-white"
                  />
                </div>
              </div>
            </Link>
          ))}
        </div>
      </div>
    </section>
  );
}

export default Categories;
