import { useState, useEffect } from 'react';
import { useFocusableAutoScroll } from '../hooks/useFocusableAutoScroll';
import { Game } from '../api/client';

const FocusablePoster = ({ coverUrl }: { coverUrl: string }) => {
  const { ref, focused } = useFocusableAutoScroll();
  return (
    <div ref={ref} className={`w-[25rem] aspect-[3/4] shrink-0 bg-white/5 overflow-hidden rounded-[1.5rem] shadow-[0_20px_50px_rgba(0,0,0,0.3)] transition-all duration-500 ease-out ${focused ? 'scale-105 ring-4 ring-[#2563eb] shadow-2xl z-20' : ''}`}>
      <img alt="Hero Poster" className="w-full h-full object-cover" src={coverUrl} />
    </div>
  );
};

const FocusableButton = ({ children, onClick, className }: { children: React.ReactNode, onClick?: () => void, className?: string }) => {
  const { ref, focused } = useFocusableAutoScroll({ onEnterPress: () => onClick?.() });
  return (
    <button ref={ref} onClick={onClick} className={`${className} transition-all duration-300 ${focused ? 'scale-105 ring-2 ring-[#2563eb] shadow-xl z-10' : ''}`}>
      {children}
    </button>
  );
};

const FocusableThumb = ({ g, isActive, onClick }: { g: Game, isActive: boolean, onClick: () => void }) => {
  const { ref, focused } = useFocusableAutoScroll({ onEnterPress: onClick });
  return (
    <div 
      ref={ref}
      onClick={onClick}
      className={`carousel-thumb w-[5.625rem] shrink-0 aspect-[2/3] overflow-hidden cursor-pointer transition-all duration-300 ring-1 ring-white/10 bg-white/5 rounded-md ${
        isActive ? 'opacity-100 ring-2 ring-[#2563eb]' : 'opacity-60 hover:opacity-100'
      } ${focused ? 'scale-110 ring-2 ring-white z-10 shadow-2xl' : ''}`}
    >
      <img className="w-full h-full object-cover" src={g.coverUrl} alt="Thumbnail poster" />
    </div>
  );
};

export const FeaturedHero = ({ games, isFallback }: { games: Game[], isFallback?: boolean }) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isPaused, setIsPaused] = useState(false);

  useEffect(() => {
    if (isPaused || !games?.length) return;
    const interval = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % games.length);
    }, 5000);
    return () => clearInterval(interval);
  }, [games, isPaused]);

  if (!games?.length) return null;
  const game = games[currentIndex];

  const formattedSize = ((Number(game.size) || 0) / (1024 * 1024)).toFixed(2) + " MB";

  return (
    <section 
      className="bg-[#10131f] border-b border-white/5" 
      id="featured-section"
      onMouseEnter={() => setIsPaused(true)}
      onMouseLeave={() => setIsPaused(false)}
    >
      <div className="px-12 py-12">
        <div className="flex gap-12 items-stretch max-w-full">
          {/* Large Hero Poster */}
          <FocusablePoster coverUrl={game.coverUrl} />

          {/* Content Area */}
          <div className="flex-1 flex flex-col justify-between min-w-0">
            <div className="flex flex-col min-w-0">
              <div className="inline-flex items-center gap-2 px-3 py-1 bg-[#2563eb]/20 text-[#b4c5ff] mb-4 w-fit border border-[#2563eb]/30 rounded-md">
                <span className="material-symbols-outlined text-[0.625rem]" style={{ fontVariationSettings: "'FILL' 1" }}>
                  {isFallback ? 'history' : 'star'}
                </span>
                <span className="text-[0.625rem] font-black uppercase tracking-widest geist-mono">
                  {isFallback ? 'Recently Added' : 'Featured'}
                </span>
              </div>
              
              <h2 
                className="text-[4.5rem] font-black text-white tracking-tighter mb-4 leading-[0.9] uppercase geist-mono truncate" 
                title={game.title}
              >
                {game.title}
              </h2>
              
              <div className="flex gap-10 mb-8 geist-mono">
                <div className="flex flex-col">
                  <span className="text-[0.625rem] text-[#c3c6d7] uppercase tracking-[0.2em] font-bold mb-1 opacity-60">Platform</span>
                  <span className="text-xs font-black text-white">{game.system}</span>
                </div>
                <div className="flex flex-col">
                  <span className="text-[0.625rem] text-[#c3c6d7] uppercase tracking-[0.2em] font-bold mb-1 opacity-60">Size</span>
                  <span className="text-xs font-black text-white">{formattedSize}</span>
                </div>
              </div>

              <p className="text-sm text-[#c3c6d7] leading-relaxed max-w-2xl mb-8 geist-mono">
                Experience the magic of {game.title} perfectly emulated and synced natively by the Digital Atelier architecture.
              </p>

              <div className="flex items-center gap-3 mb-8">
                <FocusableButton className="bg-gradient-to-br from-[#2563eb] to-[#6001d1] hover:opacity-90 text-white h-11 px-8 font-black flex items-center gap-2 active:scale-95 text-[0.6875rem] uppercase geist-mono rounded-xl shadow-[0_10px_30px_rgba(37,99,235,0.1)]">
                  <span className="material-symbols-outlined text-base" style={{ fontVariationSettings: "'FILL' 1" }}>play_arrow</span>
                  Play Now
                </FocusableButton>
                <FocusableButton className="bg-transparent hover:bg-white/10 text-[#2563eb] border border-white/5 h-11 px-8 font-black flex items-center gap-2 text-[0.6875rem] uppercase geist-mono rounded-xl">
                  <span className="material-symbols-outlined text-base">download</span>
                  Download
                </FocusableButton>
              </div>
            </div>

            {/* Thumbnail Carousel */}
            <div className="relative w-full overflow-hidden mt-4">
              <div className="flex gap-3 overflow-x-auto no-scrollbar scroll-smooth py-2 px-1 -mx-1 -my-2">
                {games.map((g, i) => (
                  <FocusableThumb 
                    key={g.id} 
                    g={g} 
                    isActive={i === currentIndex} 
                    onClick={() => setCurrentIndex(i)} 
                  />
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};
