"use client";

import { useTranslations, useLocale } from 'next-intl';
import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence, useAnimation } from 'framer-motion';

export default function BreakingPointSimulator() {
  const t = useTranslations('breakingPoint');
  const locale = useLocale();
  const [hoveredPiece, setHoveredPiece] = useState<number | null>(null);
  const [brokenPieces, setBrokenPieces] = useState<number[]>([]);
  const [isMobile, setIsMobile] = useState(false);
  const [activeSolution, setActiveSolution] = useState<number | null>(null);
  const [currentTarget, setCurrentTarget] = useState<number>(0);
  const containerRef = useRef<HTMLDivElement>(null);
  const hammerControls = useAnimation();

  // Mobil cihaz tespiti
  useEffect(() => {
    const checkScreenSize = () => {
      setIsMobile(window.innerWidth < 768);
    };
    
    checkScreenSize();
    window.addEventListener('resize', checkScreenSize);
    return () => window.removeEventListener('resize', checkScreenSize);
  }, []);

  // ESC tuşu ile popup'ı kapatma işlevselliği
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && activeSolution !== null) {
        closeSolution();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [activeSolution]);

  // Çekiç animasyonu
  useEffect(() => {
    // Sırayla hedef belirle (kırılmamış parçalara öncelik ver)
    const getNextTarget = () => {
      // Tüm camlara sırayla gitmesi için bir sonraki indeksi hesapla
      const nextTarget = (currentTarget + 1) % 6;
      setCurrentTarget(nextTarget);
      return nextTarget;
    };

    const animateHammer = async () => {
      const target = getNextTarget();

      // Hedef elemanın pozisyonunu al
      if (containerRef.current) {
        const container = containerRef.current;
        const targetEl = container.querySelector(`[data-piece="${target}"]`) as HTMLElement;
        
        if (targetEl) {
          const containerRect = container.getBoundingClientRect();
          const targetRect = targetEl.getBoundingClientRect();
          
          // Çekiç pozisyonunu güncelle (hedefin üzerinde)
          const x = targetRect.left + targetRect.width / 2 - containerRect.left;
          const y = targetRect.top - 40 - containerRect.top;
          
          // Çekici hareket ettir
          await hammerControls.start({
            x, 
            y,
            scale: 1,
            rotate: 0,
            transition: { duration: 1, ease: "easeInOut" }
          });
          
          // Çekiç vuruş animasyonu
          await hammerControls.start({
            rotate: [0, 20],
            scale: [1, 1.1],
            y: y + 20,
            transition: { duration: 0.2, ease: "easeIn" }
          });
          
          // Çekici geri çek
          await hammerControls.start({
            rotate: [20, 0],
            scale: [1.1, 1],
            y,
            transition: { duration: 0.3, ease: "easeOut" }
          });
        }
      }
    };

    // Periyodik çekiç animasyonu
    const interval = setInterval(animateHammer, 3000);
    return () => clearInterval(interval);
  }, [hammerControls, brokenPieces, currentTarget]);

  // Cam parçası kırma işlemi
  const breakGlass = (index: number) => {
    if (!brokenPieces.includes(index)) {
      // Cam kırıldığında o cam için açıklama gösteriliyor, diğer açıklamalar kalıyor
      setActiveSolution(index);
      setBrokenPieces([...brokenPieces, index]);
      
      // Haptic feedback (titreşim) mobil cihazlarda
      if (navigator.vibrate) {
        navigator.vibrate(50);
      }
    } else {
      // Zaten kırılmış bir parçaya tıklandığında sadece o parçanın açıklaması gösterilir/gizlenir (toggle)
      setActiveSolution(activeSolution === index ? null : index);
    }
  };

  // Solution popup'ını kapat
  const closeSolution = () => {
    setActiveSolution(null);
  };

  // Tüm kırıkları sıfırla
  const resetBrokenPieces = () => {
    setBrokenPieces([]);
    setActiveSolution(null);
  };

  // Kırık cam efekt varyantları
  const glassVariants = {
    normal: {
      background: "rgba(255, 255, 255, 0.1)",
      backdropFilter: "blur(10px)",
      scale: 1
    },
    hover: {
      background: "rgba(255, 255, 255, 0.2)",
      scale: 1.05,
      boxShadow: "0 0 15px 5px rgba(59, 130, 246, 0.3)"
    },
    broken: {
      background: "rgba(255, 255, 255, 0)"
    }
  };

  // Kırık parça varyantları
  const shardVariants = {
    hidden: { 
      opacity: 0, 
      scale: 0.5,
      rotate: 0
    },
    visible: (i: number) => ({ 
      opacity: 1, 
      scale: [0.5, 1.2, 1],
      rotate: (i % 2 === 0) ? [0, 15, 10] : [0, -15, -10],
      x: (i % 3 - 1) * 15,
      y: (i % 2 === 0) ? 10 : -10,
      transition: { 
        duration: 0.5, 
        type: "tween",
        damping: 10,
        stiffness: 100
      } 
    }),
    exit: (i: number) => ({ 
      opacity: 0, 
      scale: 0,
      x: (i % 3 - 1) * 100,
      y: (i % 2 === 0) ? 100 : -100,
      rotate: (i % 2 === 0) ? 45 : -45,
      transition: { 
        duration: 0.6,
        ease: "easeOut"
      } 
    })
  };

  // İçerik popup varyantları (Kırık cam üzerinde gösterilecek)
  const solutionCardVariants = {
    hidden: { 
      opacity: 0, 
      scale: 0.8,
      y: -5
    },
    visible: { 
      opacity: 1, 
      scale: 1,
      y: 0,
      transition: { 
        delay: 0.1, 
        duration: 0.3,
        type: "spring",
        damping: 20,
        stiffness: 300
      } 
    },
    exit: { 
      opacity: 0, 
      scale: 0.8,
      y: -5,
      transition: { 
        duration: 0.2 
      } 
    }
  };

  // Senaryolar
  const scenarios = Array.from({ length: 6 }, (_, i) => ({
    problem: t(`scenarios.${i}.problem`),
    solution: t(`scenarios.${i}.solution`)
  }));

  // Kart renkleri - her kart için farklı gradyen rengi
  const cardColors = [
    'from-blue-600 to-indigo-500',
    'from-violet-600 to-purple-500',
    'from-pink-600 to-rose-500',
    'from-amber-500 to-orange-500',
    'from-teal-500 to-cyan-600',
    'from-emerald-500 to-green-600'
  ];

  // İkonlar - her problem için uygun ikonlar
  const cardIcons = [
    // Yatırım
    <svg key="investment" className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M12 2v20M2 6h20M17 12H7M14 17H10" />
    </svg>,
    
    // Ekip
    <svg key="team" className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
      <circle cx="9" cy="7" r="4" />
      <path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75" />
    </svg>,
    
    // Pazar
    <svg key="market" className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="12" r="10" />
      <path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20" />
      <path d="M2 12h20" />
    </svg>,
    
    // Teknik altyapı
    <svg key="tech" className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
      <line x1="8" y1="21" x2="16" y2="21" />
      <line x1="12" y1="17" x2="12" y2="21" />
    </svg>,
    
    // Satış
    <svg key="sales" className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M3 3h18v18H3z" />
      <path d="m16 16-4-4 4-4" />
      <path d="M8 8v.01" />
      <path d="M8 12v.01" />
      <path d="M8 16v.01" />
    </svg>,
    
    // Nakit akışı
    <svg key="cash" className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <line x1="12" y1="1" x2="12" y2="23" />
      <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
    </svg>
  ];

  return (
    <section id="breaking-point" className="relative py-20 md:py-24 bg-gradient-to-b from-slate-800 to-slate-900 overflow-hidden">
      {/* Dekoratif arka plan öğeleri */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute inset-0 bg-grid-white/[0.03]"></div>
        
        {/* Işık efektleri */}
        <div className="absolute top-1/3 right-1/4 w-[300px] h-[300px] rounded-full bg-blue-600/10 blur-[100px]"></div>
        <div className="absolute bottom-1/3 left-1/4 w-[250px] h-[250px] rounded-full bg-indigo-600/10 blur-[100px]"></div>
      </div>
      
      <div className="container mx-auto px-4 sm:px-6 lg:px-8 relative" ref={containerRef}>
        {/* Başlık */}
        <div className="text-center mb-16">
          <motion.h2 
            className="text-3xl md:text-4xl font-bold mb-6 bg-clip-text text-transparent bg-gradient-to-r from-white to-blue-200"
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.7, delay: 0.1 }}
          >
            {t('title')}
          </motion.h2>
          
          <motion.div 
            className="w-24 h-1.5 bg-gradient-to-r from-blue-600 to-indigo-600 mx-auto rounded-full mb-8"
            initial={{ opacity: 0, width: 0 }}
            animate={{ opacity: 1, width: 96 }}
            transition={{ duration: 0.6, delay: 0.3 }}
          />
          
          <motion.p 
            className="max-w-3xl mx-auto text-gray-300 text-lg"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.7, delay: 0.4 }}
          >
            {t('subtitle')}
          </motion.p>
          
          {/* İpucu metni */}
          <motion.div
            className="flex items-center justify-center mt-6 text-sm text-blue-300 space-x-2"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 1 }}
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
            </svg>
            <span>{t('hint')}</span>
          </motion.div>
        </div>
        
        {/* Kırık Cam Alanı */}
        <div className="relative mt-10 md:mt-16 grid grid-cols-2 md:grid-cols-3 gap-4 md:gap-6 max-w-4xl mx-auto">
          {Array.from({ length: 6 }).map((_, index) => {
            const isBroken = brokenPieces.includes(index);
            // Burayı değiştiriyoruz - artık bir cam kırıldığında otomatik olarak açıklaması gösteriliyor
            const isActive = isBroken; // Tüm kırık camların açıklamaları görünür kalacak
            
            return (
              <div 
                key={index} 
                className="relative aspect-[4/3] md:aspect-[3/2]"
              >
                {/* Cam Parçası */}
                <motion.div
                  data-piece={index}
                  className={`absolute inset-0 backdrop-blur-[5px] rounded-lg border border-white/10 shadow-xl cursor-pointer overflow-hidden ${isBroken ? 'bg-transparent' : 'bg-white/5'}`}
                  variants={glassVariants}
                  initial="normal"
                  animate={isBroken ? "broken" : hoveredPiece === index ? "hover" : "normal"}
                  whileHover={!isBroken ? "hover" : undefined}
                  onClick={() => breakGlass(index)}
                  onMouseEnter={() => !isBroken && setHoveredPiece(index)}
                  onMouseLeave={() => setHoveredPiece(null)}
                >
                  {/* Cam İçeriği - Problem Adı */}
                  {!isBroken && (
                    <div className="absolute inset-0 flex items-center justify-center p-3 text-center">
                      <h3 className="text-sm md:text-base lg:text-lg font-medium text-white leading-tight">
                        {t(`scenarios.${index}.problem`)}
                      </h3>
                    </div>
                  )}
                  
                  {/* Kırık cam efekti */}
                  {isBroken && (
                    <div className="absolute inset-0">
                      {Array.from({ length: 7 }).map((_, i) => (
                        <motion.div
                          key={`shard-${index}-${i}`}
                          className="absolute bg-white/10 backdrop-blur-[5px] rounded-lg shadow-lg border border-white/20"
                          style={{
                            clipPath: `polygon(${50 + Math.random() * 50}% ${Math.random() * 100}%, ${Math.random() * 100}% ${Math.random() * 100}%, ${Math.random() * 100}% ${50 + Math.random() * 50}%)`,
                            width: `${30 + Math.random() * 70}%`,
                            height: `${30 + Math.random() * 70}%`,
                            left: `${Math.random() * 70}%`,
                            top: `${Math.random() * 70}%`,
                            zIndex: Math.floor(Math.random() * 10)
                          }}
                          custom={i}
                          variants={shardVariants}
                          initial="hidden"
                          animate="visible"
                        />
                      ))}
                    </div>
                  )}
                </motion.div>
                
                {/* Çözüm Kartı - Kırılmış cam üzerinde gösterilir */}
                <AnimatePresence>
                  {isBroken && isActive && (
                    <motion.div
                      className="absolute inset-0 flex items-center justify-center z-10"
                      initial="hidden"
                      animate="visible"
                      exit="exit"
                      variants={solutionCardVariants}
                    >
                      <div className="w-full h-full p-2 md:p-3 pointer-events-none">
                        <div className="relative w-full h-full bg-gradient-to-br from-blue-900/90 to-slate-900/95 backdrop-blur-sm rounded-lg p-3 sm:p-4 border border-blue-500/30 shadow-lg shadow-blue-500/20 overflow-hidden flex items-center justify-center">
                          {/* Çözüm metni */}
                          <p className="text-xs sm:text-sm md:text-base text-blue-50 text-center">
                            {t(`scenarios.${index}.solution`)}
                          </p>
                          
                          {/* Dekoratif ışık efekti */}
                          <div className="absolute top-0 right-0 w-16 h-16 bg-blue-500/20 rounded-full blur-xl"></div>
                          <div className="absolute bottom-0 left-0 w-12 h-12 bg-indigo-500/20 rounded-full blur-lg"></div>
                        </div>
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            );
          })}
        </div>
        
        {/* Mobil için ipucu */}
        <motion.div
          className="mt-6 text-center text-sm text-gray-400"
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 1, duration: 0.5 }}
        >
          {t('hint')}
        </motion.div>
        
        {/* Çekiç */}
        <motion.div
          className="absolute w-16 h-16 z-20 pointer-events-none"
          style={{ top: 0, left: 0 }}
          animate={hammerControls}
        >
          <img src="/icons/hammer.svg" alt="Hammer" className="w-full h-full" />
        </motion.div>
        
        {/* Mobil için sıfırlama düğmesi */}
        {brokenPieces.length > 0 && (
          <motion.button
            className="mt-8 mx-auto flex items-center justify-center px-4 py-2 bg-blue-700/30 hover:bg-blue-700/50 text-white text-sm rounded-full border border-blue-500/30 transition-colors"
            onClick={resetBrokenPieces}
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 10 }}
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
          >
            <svg className="w-4 h-4 mr-2" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            <span>{locale === 'tr' ? 'Yeniden Başlat' : 'Restart'}</span>
          </motion.button>
        )}
      </div>
      
      {/* CSS */}
      <style jsx global>{`
        .perspective-1000 {
          perspective: 1000px;
        }
        @keyframes shimmer {
          0%, 100% { opacity: 0.5; }
          50% { opacity: 1; }
        }
        .rotate-y-0 {
          transform: rotateY(0deg);
        }
        .group:hover .rotate-y-0 {
          transform: rotateY(15deg);
        }
      `}</style>
    </section>
  );
}

