'use client';

import { ArrowUpRight } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { useI18n } from '@/lib/i18n';
import { translateProduct } from '@/lib/i18n-content';
import type { Product } from '@/lib/types';

export function HeroShowcase({ products, initialProductId }: { products: Product[]; initialProductId?: string }) {
  const { language, t } = useI18n();
  const slides = useMemo(() => products.slice(0, 4).map((product) => translateProduct(product, language)), [language, products]);
  const initialIndex = Math.max(0, slides.findIndex((product) => product.id === initialProductId));
  const [activeIndex, setActiveIndex] = useState(initialIndex);

  useEffect(() => {
    if (slides.length < 2) return undefined;
    const timer = window.setInterval(() => setActiveIndex((current) => (current + 1) % slides.length), 4200);
    return () => window.clearInterval(timer);
  }, [slides.length]);

  if (slides.length === 0) return null;

  const currentProduct = slides[activeIndex] ?? slides[0];

  return (
    <div
      className="atelier-hero-stage"
      data-reveal
      aria-label={t('home.heroCarouselLabel')}
    >
      <span className="atelier-orbit atelier-orbit-one" aria-hidden="true" />
      <span className="atelier-orbit atelier-orbit-two" aria-hidden="true" />
      <div className="atelier-hero-image-shell">
        <img key={currentProduct.id} className="atelier-hero-slide-image" src={currentProduct.image} alt={currentProduct.alt} fetchPriority="high" />
        <div className="hero-tag">{t('home.heroTag')}</div>
      </div>
      <div className="atelier-project-card" aria-live="polite">
        <span className="project-card-label">{t('home.heroStageLabel')}</span>
        <strong>{currentProduct.name}</strong>
        <span>{currentProduct.level}{currentProduct.projects[0] ? ` · ${currentProduct.projects[0]}` : ''}</span>
        <a href={`/san-pham/${currentProduct.slug}`}>{t('home.startProject')} <ArrowUpRight size={15} aria-hidden="true" /></a>
      </div>
      <div className="atelier-stamp" aria-hidden="true"><span>MC</span><small>01 / MAKE</small></div>
      <div className="atelier-slide-controls" aria-label={t('home.heroCarouselLabel')}>
        {slides.map((slide, index) => (
          <button
            key={slide.id}
            className={`atelier-slide-dot${activeIndex === index ? ' is-active' : ''}`}
            type="button"
            aria-label={t('home.heroCarouselSlide', { name: slide.name })}
            aria-pressed={activeIndex === index}
            onClick={() => setActiveIndex(index)}
          >
            <span aria-hidden="true" />
          </button>
        ))}
      </div>
    </div>
  );
}
