"use client";

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

// Girişimci arketip türleri
type ArchetypeType = 'visionary' | 'architect' | 'executor';

// Soru yanıtları için puan sistemi
type AnswerScores = {
  visionary: number;
  architect: number;
  executor: number;
};

// Bileşen için prop tipleri
interface CharacterAnalysisProps {
  manualShow?: boolean;
  onClose?: () => void;
}

export default function CharacterAnalysis({ manualShow, onClose }: CharacterAnalysisProps = {}) {
  const locale = useLocale();
  const t = useTranslations('characterAnalysis');
  
  const [showPopup, setShowPopup] = useState(false);
  const [stage, setStage] = useState<'intro' | 'questions' | 'results'>('intro');
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [scores, setScores] = useState<AnswerScores>({
    visionary: 0,
    architect: 0,
    executor: 0
  });
  const [finalArchetype, setFinalArchetype] = useState<ArchetypeType | null>(null);
  
  // Manual show prop kullanılırsa, showPopup durumunu güncelle
  useEffect(() => {
    if (manualShow !== undefined) {
      setShowPopup(manualShow);
    }
  }, [manualShow]);
  
  // Sayfaya giriş yapıldığında popup'ı görüntüle (sadece manual show ayarlanmamışsa)
  useEffect(() => {
    // Eğer manuel gösterme seçeneği belirtilmemişse otomatik gösterme davranışını uygula
    if (manualShow === undefined) {
      // Kullanıcının bu popup'ı daha önce görmediğinden emin olmak için
      // localStorage'a bakıyoruz
      const hasSeenPopup = localStorage.getItem('hasSeenCharacterAnalysis');
      
      if (!hasSeenPopup) {
        // Sayfanın yüklenmesini bekle
        const timer = setTimeout(() => {
          setShowPopup(true);
        }, 1500); // 1,5 saniye bekletiyoruz
        
        return () => clearTimeout(timer);
      }
    }
  }, [manualShow]);

  // Sayfanın üstüne kaydırma fonksiyonu
  const scrollToTop = () => {
    // Hero bölümüne yumuşak kaydırma yap (id="hero")
    const heroSection = document.getElementById('hero');
    if (heroSection) {
      heroSection.scrollIntoView({ behavior: 'smooth' });
    } else {
      // Hero bölümü bulunamazsa sayfanın en üstüne kaydır
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    }
  };

  // Popup'ı tamamen kapatma
  const closePopup = () => {
    setShowPopup(false);
    
    // Eğer dışarıdan bir onClose fonksiyonu iletildiyse, onu da çağır
    if (onClose) {
      onClose();
    } else {
      // Yoksa varsayılan davranışı uygula (localStorage'a kaydedildi olarak işaretle)
      localStorage.setItem('hasSeenCharacterAnalysis', 'true');
    }
  };
  
  // Test sorularını görüntülemeyi başlatma
  const startTest = () => {
    setStage('questions');
  };
  
  // Bir soruya cevap verme
  const answerQuestion = (answerScores: AnswerScores) => {
    setScores(prevScores => ({
      visionary: prevScores.visionary + answerScores.visionary,
      architect: prevScores.architect + answerScores.architect,
      executor: prevScores.executor + answerScores.executor
    }));
    
    if (currentQuestion < questions.length - 1) {
      setCurrentQuestion(currentQuestion + 1);
    } else {
      // Son sorudan sonra sonuçları göster
      calculateResults();
    }
  };
  
  // Sonuçları hesapla
  const calculateResults = () => {
    // En yüksek puanı alan arketipi bul
    const archetypeScores = [
      { type: 'visionary', score: scores.visionary },
      { type: 'architect', score: scores.architect },
      { type: 'executor', score: scores.executor }
    ];
    
    const highestScore = archetypeScores.reduce((prev, current) => 
      (prev.score > current.score) ? prev : current
    );
    
    setFinalArchetype(highestScore.type as ArchetypeType);
    setStage('results');
  };
  
  // Testi sıfırlama
  const resetTest = () => {
    setCurrentQuestion(0);
    setScores({ visionary: 0, architect: 0, executor: 0 });
    setFinalArchetype(null);
    setStage('intro');
  };

  // Animasyon varyantları
  const popupVariants = {
    hidden: { opacity: 0, scale: 0.8, y: 20 },
    visible: {
      opacity: 1,
      scale: 1,
      y: 0,
      transition: {
        type: "spring",
        damping: 25,
        stiffness: 300
      }
    },
    exit: {
      opacity: 0,
      scale: 0.8,
      y: 20,
      transition: { duration: 0.2 }
    }
  };

  // Tüm sorular
  const questions = [
    {
      id: 1,
      answers: [
        {
          id: "1a",
          scores: { visionary: 3, architect: 1, executor: 0 }
        },
        {
          id: "1b",
          scores: { visionary: 0, architect: 3, executor: 1 }
        },
        {
          id: "1c",
          scores: { visionary: 1, architect: 0, executor: 3 }
        }
      ]
    },
    {
      id: 2,
      answers: [
        {
          id: "2a",
          scores: { visionary: 3, architect: 1, executor: 0 }
        },
        {
          id: "2b",
          scores: { visionary: 0, architect: 3, executor: 1 }
        },
        {
          id: "2c",
          scores: { visionary: 1, architect: 0, executor: 3 }
        }
      ]
    },
    {
      id: 3,
      answers: [
        {
          id: "3a",
          scores: { visionary: 3, architect: 0, executor: 1 }
        },
        {
          id: "3b",
          scores: { visionary: 0, architect: 3, executor: 0 }
        },
        {
          id: "3c",
          scores: { visionary: 1, architect: 0, executor: 3 }
        }
      ]
    },
    {
      id: 4,
      answers: [
        {
          id: "4a",
          scores: { visionary: 3, architect: 0, executor: 1 }
        },
        {
          id: "4b",
          scores: { visionary: 1, architect: 3, executor: 0 }
        },
        {
          id: "4c",
          scores: { visionary: 0, architect: 1, executor: 3 }
        }
      ]
    }
  ];

  // Popup'ı tamamen gösterip göstermiyoruz
  if (!showPopup) return null;

  return (
    <AnimatePresence>
      <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-900/80 backdrop-blur-sm">
        <motion.div 
          className="relative bg-gradient-to-br from-slate-800 to-slate-900 rounded-xl max-w-lg w-full shadow-2xl border border-slate-700/50 overflow-hidden"
          variants={popupVariants}
          initial="hidden"
          animate="visible"
          exit="exit"
        >
          {/* Üst çubuk ve kapat butonu */}
          <div className="h-2 w-full bg-gradient-to-r from-blue-600 to-indigo-600" />
          
          <button
            className="absolute top-4 right-4 w-8 h-8 rounded-full bg-white/10 flex items-center justify-center text-white/70 hover:text-white hover:bg-white/20 transition-colors z-10"
            onClick={closePopup}
            aria-label={locale === 'tr' ? 'Kapat' : 'Close'}
          >
            <svg className="w-5 h-5 pointer-events-none" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>

          {/* İçerik Alanı */}
          <div className="p-6 md:p-8">
            {/* Giriş Ekranı */}
            {stage === 'intro' && (
              <div className="text-center">
                <div className="flex justify-center mb-6">
                  <div className="w-20 h-20 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center">
                    <svg className="w-10 h-10 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                    </svg>
                  </div>
                </div>
                <h2 className="text-2xl md:text-3xl font-bold text-white mb-3">
                  {t('title')}
                </h2>
                <p className="text-blue-100 mb-6">
                  {t('subtitle')}
                </p>
                <div className="flex flex-col sm:flex-row gap-4 mt-6">
                  <button 
                    className="w-full py-3 rounded-full bg-gradient-to-r from-blue-600 to-indigo-600 text-white font-medium hover:shadow-lg hover:shadow-blue-500/20 transition-all hover:-translate-y-0.5"
                    onClick={startTest}
                  >
                    {t('startButton')}
                  </button>
                  <button 
                    className="w-full py-3 rounded-full bg-white/10 text-white font-medium hover:bg-white/20 transition-colors"
                    onClick={closePopup}
                  >
                    {t('laterButton')}
                  </button>
                </div>
              </div>
            )}

            {/* Soru Ekranı */}
            {stage === 'questions' && (
              <div>
                <div className="mb-6">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm text-blue-300">
                      {t('question')} {currentQuestion + 1}/{questions.length}
                    </span>
                    <span className="text-sm text-blue-300">
                      {Math.round((currentQuestion / questions.length) * 100)}%
                    </span>
                  </div>
                  <div className="w-full h-2 bg-slate-700 rounded-full overflow-hidden">
                    <motion.div 
                      className="h-full bg-gradient-to-r from-blue-500 to-indigo-600"
                      initial={{ width: 0 }}
                      animate={{ width: `${((currentQuestion) / questions.length) * 100}%` }}
                      transition={{ duration: 0.5 }}
                    />
                  </div>
                </div>

                <h2 className="text-xl md:text-2xl font-semibold text-white mb-6">
                  {t(`questions.q${currentQuestion + 1}.question`)}
                </h2>

                <div className="space-y-4">
                  {questions[currentQuestion].answers.map((answer, index) => (
                    <motion.button
                      key={answer.id}
                      className="w-full text-left p-4 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 text-blue-50 transition-colors"
                      whileHover={{ scale: 1.02 }}
                      whileTap={{ scale: 0.98 }}
                      onClick={() => answerQuestion(answer.scores)}
                    >
                      {t(`questions.q${currentQuestion + 1}.a${index + 1}`)}
                    </motion.button>
                  ))}
                </div>
              </div>
            )}

            {/* Sonuç Ekranı */}
            {stage === 'results' && finalArchetype && (
              <div className="text-center">
                <div className="flex justify-center mb-6">
                  <div className="w-24 h-24 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center">
                    <img 
                      src={`/icons/${finalArchetype}.svg`}
                      alt={t(`archetypes.${finalArchetype}.title`)}
                      className="w-12 h-12 text-white"
                    />
                  </div>
                </div>
                <h2 className="text-2xl md:text-3xl font-bold text-white mb-3">
                  {t(`archetypes.${finalArchetype}.title`)}
                </h2>
                <p className="text-blue-100 mb-6">
                  {t(`archetypes.${finalArchetype}.description`)}
                </p>
                <div className="p-4 rounded-lg bg-blue-600/20 border border-blue-500/30 text-blue-100 mb-6">
                  <h3 className="font-semibold mb-2">
                    {t('recommendation')}
                  </h3>
                  <p>
                    {t(`archetypes.${finalArchetype}.recommendation`)}
                  </p>
                </div>
                <div className="flex flex-col sm:flex-row gap-4 mt-6">
                  <button 
                    className="w-full py-3 rounded-full bg-gradient-to-r from-blue-600 to-indigo-600 text-white font-medium hover:shadow-lg hover:shadow-blue-500/20 transition-all hover:-translate-y-0.5"
                    onClick={() => {
                      closePopup();
                      scrollToTop();
                    }}
                  >
                    {t('exploreButton')}
                  </button>
                  <button 
                    className="w-full py-3 rounded-full bg-white/10 text-white font-medium hover:bg-white/20 transition-colors"
                    onClick={resetTest}
                  >
                    {t('retakeButton')}
                  </button>
                </div>
              </div>
            )}
          </div>
          
          {/* Dekoratif elementler */}
          <div className="absolute top-0 right-0 w-40 h-40 bg-blue-600/10 rounded-full blur-[80px] -z-10" />
          <div className="absolute bottom-0 left-0 w-40 h-40 bg-indigo-600/10 rounded-full blur-[80px] -z-10" />
        </motion.div>
      </div>
    </AnimatePresence>
  );
} 