import { useState, useEffect, useRef, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import ScrollAnimation from './ScrollAnimation';
import { useLanguage } from '../contexts/LanguageContext';
import { HERO_PROJECTS } from '../constants/common';
import { batchDOMUpdates } from '../utils/performance';
import { preloadHeroImages, preloadHeroImagesOnDemand } from '../utils/imagePreloader';
import { scrollToContact, scrollToPortfolio } from '../utils/scrollOptimization';

const Hero = () => {
  const [currentImage, setCurrentImage] = useState(0);
  const [imagesLoaded, setImagesLoaded] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  
  // Hook de idioma
  const { t } = useLanguage();

  // Project information for hero images
  const heroProjects = HERO_PROJECTS;
  
  // Estilos de blur consistentes con el navbar
  // const buttonBackdropStyles = useBackdropFilter(24); // Removed - not used
  // const heroBgUrl = ['/optimized/hero/1.webp','/optimized/hero/2.webp','/optimized/hero/3.webp'][currentImage]; // Removed - not used
  
  // Función para obtener el label traducido del proyecto - OPTIMIZADA PARA LCP
  const getProjectLabel = (project: typeof HERO_PROJECTS[0]) => {
    const projectKey = project.title.toLowerCase().replace(/\s+/g, '').replace(/'/g, '');
    return t(`hero.project.${projectKey}`);
  };

  // LCP OPTIMIZATION - Pre-calculate project labels to avoid translation delays
  const projectLabels = HERO_PROJECTS.map(project => ({
    ...project,
    label: getProjectLabel(project)
  }));



  // Preload images for smooth transitions - OPTIMIZADO PARA LCP
  const preloadImages = useCallback(async () => {
    try {
      // Preload solo la primera imagen para LCP
      const results = await preloadHeroImages();
      const successCount = results.filter(r => r.success).length;
      console.log(`Hero images preloaded: ${successCount}/${results.length}`);
      
      // Usar batchDOMUpdates para evitar reflows
      batchDOMUpdates([() => setImagesLoaded(true)]);
      
      // Preload imágenes adicionales en background después de LCP
      setTimeout(async () => {
        try {
          await preloadHeroImagesOnDemand();
          console.log('Additional hero images preloaded in background');
        } catch (error) {
          console.warn('Failed to preload additional hero images:', error);
        }
      }, 2000); // Delay para no interferir con LCP
    } catch (error) {
      console.warn('Some hero images failed to preload:', error);
      batchDOMUpdates([() => setImagesLoaded(true)]); // Continue anyway
    }
  }, []);

  useEffect(() => {
    preloadImages();
  }, [preloadImages]);

  // Simplified image transition
  useEffect(() => {
    if (!imagesLoaded) {return;}
    
    const interval = setInterval(() => {
      setCurrentImage((prev) => (prev === 2 ? 0 : prev + 1));
    }, 6000);

    return () => clearInterval(interval);
  }, [imagesLoaded]);


  return (
    <>
    <section
      id='home'
      ref={containerRef}
      className='relative min-h-[100vh] sm:min-h-screen flex items-center justify-center py-6 sm:py-8 md:py-10 lg:py-12'
    >
      {/* Background Images with Zoom Animation and Crossfade */}
      <div className='absolute inset-0 z-0 overflow-hidden'>
        {/* First image with zoom animation */}
        {/* Background Images - Optimized responsive images with transitions */}
        <motion.picture
          key={currentImage}
          className='absolute inset-0 w-full h-full'
        >
          <source
            media='(max-width: 480px)'
            srcSet={`/optimized/hero/${currentImage + 1}-small.webp`}
          />
          <source
            media='(max-width: 768px)'
            srcSet={`/optimized/hero/${currentImage + 1}-medium.webp`}
          />
          <source
            media='(max-width: 1024px)'
            srcSet={`/optimized/hero/${currentImage + 1}-large.webp`}
          />
          <source
            media='(min-width: 1025px)'
            srcSet={`/optimized/hero/${currentImage + 1}-xl.webp`}
          />
          <motion.img
            src={`/optimized/hero/${currentImage + 1}.webp`}
            alt={`Hero background ${currentImage + 1}`}
            className='absolute inset-0 w-full h-full object-cover object-center'
            initial={{ scale: 1.15, opacity: 0 }}
            animate={{ 
              scale: 1.1,
              opacity: 1,
            }}
            transition={{
              scale: { duration: 8, ease: [0.25, 0.46, 0.45, 0.94] },
              opacity: { duration: 1.5, ease: [0.25, 0.46, 0.45, 0.94] },
            }}
            loading='eager'
          />
        </motion.picture>

        {/* Project Info Card - Bottom Left (OPTIMIZADO PARA LCP) */}
        <div
          className='absolute bottom-4 left-4 z-30 hero-glass rounded-3xl overflow-hidden w-auto inline-block'
          style={{ maxWidth: 'calc(100vw - 2rem)' }}
        >
          {/* Elemento LCP optimizado - sin animaciones que causen delay */}
          <div className='px-6 py-3 lg:px-8 lg:py-4 rounded-3xl inline-flex items-center'>
            <div className='flex items-center gap-2 pr-3 lg:pr-5'>
              <div className='w-5 h-5 lg:w-6 lg:h-6 flex items-center justify-center flex-shrink-0'>
                <div 
                  className='w-4 h-4 lg:w-5 lg:h-5 text-white'
                  style={{
                    textShadow: '0 0 30px rgba(0, 241, 140, 0.3), 0 0 60px rgba(0, 241, 140, 0.1)',
                    filter: 'drop-shadow(0 4px 8px rgba(0, 0, 0, 0.5))',
                    background: 'currentColor',
                    mask: 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'currentColor\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\'%3E%3Crect x=\'3\' y=\'3\' width=\'18\' height=\'18\' rx=\'2\' ry=\'2\'/%3E%3Ccircle cx=\'8.5\' cy=\'8.5\' r=\'1.5\'/%3E%3Cpolyline points=\'21,15 16,10 5,21\'/%3E%3C/svg%3E") no-repeat center',
                    WebkitMask: 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'currentColor\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\'%3E%3Crect x=\'3\' y=\'3\' width=\'18\' height=\'18\' rx=\'2\' ry=\'2\'/%3E%3Ccircle cx=\'8.5\' cy=\'8.5\' r=\'1.5\'/%3E%3Cpolyline points=\'21,15 16,10 5,21\'/%3E%3C/svg%3E") no-repeat center',
                  }}
                />
              </div>
              <div className='flex-1 min-w-0'>
                <p className='text-xs lg:text-sm leading-snug m-0 p-0 drop-shadow-lg whitespace-nowrap overflow-hidden text-ellipsis md:overflow-visible md:[text-overflow:clip]'>
                  <span
                    className='text-white font-semibold hero-project-text'
                    style={{
                      textShadow: '0 0 30px rgba(0, 241, 140, 0.3), 0 0 60px rgba(0, 241, 140, 0.1)',
                      filter: 'drop-shadow(0 4px 8px rgba(0, 0, 0, 0.5))',
                    }}
                  >
                    {/* LCP OPTIMIZATION - Hardcoded text for immediate rendering */}
                    {currentImage === 0 ? "Don't Kill the Rumble - Música del Trailer" : 
                     currentImage === 1 ? "Master of Earth - Diseño de Sonido" :
                     currentImage === 2 ? "Play 2 Chipeada - Banda Sonora Original" :
                     'Proyecto HanjoAudio'}
                  </span>
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Subtle overlay for better element separation */}
      <div className='absolute inset-0 z-10 bg-transparent pointer-events-none hero-overlay' />
      
      {/* iOS 26 Main Content */}
      <div className='relative z-20 w-full max-w-none mx-auto px-6'>
        <div className='flex flex-col items-center justify-center text-center space-y-6 sm:space-y-8 md:space-y-10 lg:pt-24'>
          {/* Enhanced Typography Design */}
          <ScrollAnimation
            className='relative w-full max-w-none mx-auto text-center space-y-6'
            delay={0.2}
            duration={0.6}
            direction='up'
            distance={30}
          >
            {/* Main descriptive text - Mobile: 3 lines, Desktop: 2 lines */}
            <div className='space-y-2 sm:space-y-3 md:space-y-4 lg:space-y-6'>

              {/* First line */}
              <motion.h1
                className='text-xl sm:text-2xl md:text-3xl lg:text-3xl xl:text-4xl 2xl:text-5xl font-black text-white uppercase tracking-wide leading-tight px-2 sm:px-4 text-center break-words lg:whitespace-nowrap'
                style={{
                  fontStyle: 'italic',
                  transform: 'skew(-2deg)',
                  textShadow: '0 0 30px rgba(0, 241, 140, 0.3), 0 0 60px rgba(0, 241, 140, 0.1)',
                  filter: 'drop-shadow(0 4px 8px rgba(0, 0, 0, 0.5))',
                  display: 'block',
                  margin: '0 auto',
                }}
                whileHover={{
                  textShadow: '0 0 40px rgba(0, 241, 140, 0.5), 0 0 80px rgba(0, 241, 140, 0.2)',
                  transition: { duration: 0.3 },
                }}
              >
                {t('hero.line1')}
              </motion.h1>

              {/* Second line (colored) */}
              <motion.h2
                className='text-xl sm:text-2xl md:text-3xl lg:text-3xl xl:text-4xl 2xl:text-5xl font-black text-brandeis-400 uppercase tracking-wide leading-tight px-2 sm:px-4 text-center break-words lg:whitespace-nowrap'
                style={{
                  fontStyle: 'italic',
                  transform: 'skew(-2deg)',
                  textShadow: '0 0 30px rgba(0, 241, 140, 0.4), 0 0 60px rgba(0, 241, 140, 0.2)',
                  display: 'block',
                  margin: '0 auto',
                }}
                whileHover={{
                  textShadow: '0 0 40px rgba(0, 241, 140, 0.6), 0 0 80px rgba(0, 241, 140, 0.3)',
                  transition: { duration: 0.3 },
                }}
              >
                {t('hero.line2')}
              </motion.h2>
            </div>
          </ScrollAnimation>

          {/* Action Buttons */}
          <div
            className='relative z-40 flex flex-col sm:flex-row gap-4 sm:gap-6 items-center justify-center mt-8 sm:mt-12'
          >
            {/* Contact Button */}
            <button
              onClick={() => scrollToContact()}
            className='group relative z-40 w-full max-w-[320px] sm:w-auto sm:max-w-none px-6 py-3 sm:px-8 sm:py-4 bg-white/10 rounded-3xl text-white font-semibold text-base sm:text-lg transition-all duration-500 ease-out hover:scale-105 focus:outline-none focus:ring-2 focus:ring-white/30 focus:ring-offset-2 focus:ring-offset-transparent'
            style={{
              backdropFilter: 'blur(24px)',
              WebkitBackdropFilter: 'blur(24px)',
              border: '1px solid rgba(255,255,255,0.2)',
              boxShadow:
                '0 20px 40px -12px rgba(0,0,0,0.3), 0 0 0 1px rgba(255,255,255,0.15)'
            }}
            >
              <span className='text-shadow-lg'>{t('hero.cta.contact')}</span>
            </button>

            {/* Portfolio Button */}
            <button
              onClick={() => scrollToPortfolio()}
            className='group relative z-40 w-full max-w-[320px] sm:w-auto sm:max-w-none px-6 py-3 sm:px-8 sm:py-4 bg-white/10 rounded-3xl text-white font-medium text-base sm:text-lg transition-all duration-500 ease-out hover:scale-105 focus:outline-none focus:ring-2 focus:ring-white/30 focus:ring-offset-2 focus:ring-offset-transparent'
            style={{
              backdropFilter: 'blur(24px)',
              WebkitBackdropFilter: 'blur(24px)',
              border: '1px solid rgba(255,255,255,0.2)',
              boxShadow:
                '0 20px 40px -12px rgba(0,0,0,0.3), 0 0 0 1px rgba(255,255,255,0.15)'
            }}
            >
              <span className='text-shadow-lg'>{t('hero.cta.portfolio')}</span>
            </button>
          </div>

        </div>
      </div>
    </section>
    </>
  );
};

export default Hero;
