import React, { useState, useEffect } from 'react';
import { Badge } from './ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from './ui/dialog';
import { Gift, Star, Snowflake, Heart, Cookie, TreePine, Bell, Candy, Sparkles } from 'lucide-react';

interface AdventDay {
  day: number;
  opened: boolean;
  cracking: boolean;
  texture: number;
  content: {
    icon: React.ReactNode;
    message: string;
    color: string;
  };
}

const adventContents = [
  { icon: , message: "Желаем вам волшебного декабря!", color: "bg-red-500" },
  { icon: , message: "Пусть каждый день приносит радость!", color: "bg-yellow-500" },
  { icon: , message: "Снежинки танцуют за окном...", color: "bg-blue-500" },
  { icon: , message: "Любовь согревает сердца зимой", color: "bg-pink-500" },
  { icon: , message: "Время печь праздничное печенье!", color: "bg-orange-500" },
  { icon: , message: "Елочка, зажгись огнями!", color: "bg-green-500" },
  { icon: , message: "Лучший подарок - это время с близкими", color: "bg-purple-500" },
  { icon: , message: "Звездочка на верхушке елки", color: "bg-indigo-500" },
  { icon: , message: "Каждая снежинка уникальна", color: "bg-cyan-500" },
  { icon: , message: "Дарите объятия чаще", color: "bg-rose-500" },
  { icon: , message: "Горячий какао и зефир", color: "bg-amber-500" },
  { icon: , message: "Запах еловых веток", color: "bg-emerald-500" },
  { icon: , message: "Упаковка подарков - это искусство", color: "bg-violet-500" },
  { icon: , message: "Загадайте желание!", color: "bg-yellow-400" },
  { icon: , message: "Зимняя сказка начинается", color: "bg-blue-400" },
  { icon: , message: "Семейные традиции дороже золота", color: "bg-pink-400" },
  { icon: , message: "Имбирные человечки приветствуют вас!", color: "bg-orange-400" },
  { icon: , message: "Лесная прогулка в снегу", color: "bg-green-400" },
  { icon: , message: "Неожиданные сюрпризы", color: "bg-purple-400" },
  { icon: , message: "Ночное небо полно чудес", color: "bg-indigo-400" },
  { icon: , message: "Санки, лыжи и веселье", color: "bg-cyan-400" },
  { icon: , message: "Письма Деду Морозу", color: "bg-rose-400" },
  { icon: , message: "Праздничный торт ждет!", color: "bg-amber-400" },
  { icon: , message: "Рождественские украшения", color: "bg-emerald-400" },
  { icon: , message: "Звон колокольчиков", color: "bg-red-400" },
  { icon: , message: "Сладкие леденцы", color: "bg-pink-300" },
  { icon: , message: "Блеск праздника", color: "bg-yellow-300" },
  { icon: , message: "Подарки под елкой", color: "bg-green-300" },
  { icon: , message: "Яркие огни", color: "bg-blue-300" },
  { icon: , message: "Морозные узоры", color: "bg-cyan-300" },
  { icon: , message: "С наступающим Новым Годом! 🎉", color: "bg-emerald-600" }
];

// Различные текстуры плиток
const tileTextures = [
  'linear-gradient(135deg, #1e3a8a, #3730a3)',
  'linear-gradient(135deg, #1e40af, #3b82f6)',
  'linear-gradient(135deg, #1e3a8a 0%, #2563eb 50%, #3730a3 100%)',
  'linear-gradient(45deg, #1e3a8a, #312e81)',
  'linear-gradient(135deg, #1e40af, #1d4ed8, #3730a3)',
  'radial-gradient(circle at center, #3730a3, #1e3a8a)',
];

export function AdventCalendar() {
  const [days, setDays] = useState([]);
  const [selectedDay, setSelectedDay] = useState(null);
  const [currentDate, setCurrentDate] = useState(new Date());

  // Функция для создания звуковых эффектов
  const playSound = (type: 'click' | 'crack' | 'open') => {
    const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
    const oscillator = audioContext.createOscillator();
    const gainNode = audioContext.createGain();

    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);

    switch (type) {
      case 'click':
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
        oscillator.frequency.exponentialRampToValueAtTime(400, audioContext.currentTime + 0.1);
        gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.1);
        break;
      case 'crack':
        oscillator.frequency.setValueAtTime(200, audioContext.currentTime);
        oscillator.frequency.linearRampToValueAtTime(150, audioContext.currentTime + 0.3);
        gainNode.gain.setValueAtTime(0.2, audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
        break;
      case 'open':
        oscillator.frequency.setValueAtTime(600, audioContext.currentTime);
        oscillator.frequency.exponentialRampToValueAtTime(1200, audioContext.currentTime + 0.2);
        gainNode.gain.setValueAtTime(0.4, audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
        break;
    }

    oscillator.type = 'sine';
    oscillator.start(audioContext.currentTime);
    oscillator.stop(audioContext.currentTime + (type === 'crack' ? 0.3 : 0.2));
  };

  useEffect(() => {
    // Инициализация дней календаря
    const savedProgress = localStorage.getItem('advent-calendar-2024');
    const openedDays = savedProgress ? JSON.parse(savedProgress) : [];

    const initialDays = Array.from({ length: 31 }, (_, i) => ({
      day: i + 1,
      opened: openedDays.includes(i + 1),
      cracking: false,
      texture: i % tileTextures.length,
      content: adventContents[i]
    }));

    setDays(initialDays);
  }, []);

  const isDateAvailable = (day: number): boolean => {
    const december = new Date(currentDate.getFullYear(), 11, day); // 11 = декабрь
    return december  {
    if (!isDateAvailable(day.day) || day.opened || day.cracking) return;

    // Звук клика
    playSound('click');

    // Начинаем анимацию трещины
    setDays(prevDays => 
      prevDays.map(d => 
        d.day === day.day ? { ...d, cracking: true } : d
      )
    );

    // Звук трещины
    setTimeout(() => playSound('crack'), 100);

    // Завершаем открытие через 800мс
    setTimeout(() => {
      const updatedDays = days.map(d => 
        d.day === day.day ? { ...d, opened: true, cracking: false } : d
      );
      
      setDays(updatedDays);
      setSelectedDay(day);
      playSound('open');

      // Сохранение прогресса
      const openedDays = updatedDays.filter(d => d.opened).map(d => d.day);
      localStorage.setItem('advent-calendar-2024', JSON.stringify(openedDays));
    }, 800);
  };

  // Для демонстрации - позволяем открывать любой день
  const isDemo = true;

  return (
    
      
        {`
          @keyframes advent-crack {
            0% { 
              transform: scale(1);
              box-shadow: inset 0 2px 4px rgba(255,255,255,0.1), 0 2px 4px rgba(0,0,0,0.3);
            }
            25% {
              transform: scale(1.02);
              box-shadow: inset 0 2px 8px rgba(0,0,0,0.3), 0 4px 8px rgba(0,0,0,0.4);
            }
            50% {
              transform: scale(0.98);
              box-shadow: inset 0 4px 12px rgba(0,0,0,0.4), 0 2px 4px rgba(0,0,0,0.3);
            }
            75% {
              transform: scale(1.01);
              box-shadow: inset 0 6px 16px rgba(0,0,0,0.5), 0 6px 12px rgba(0,0,0,0.4);
            }
            100% {
              transform: scale(1);
              box-shadow: inset 0 8px 20px rgba(0,0,0,0.6), 0 8px 16px rgba(0,0,0,0.5);
            }
          }
          
          .advent-cracking {
            animation: advent-crack 0.8s ease-in-out;
          }
          
          .advent-cracking::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: 
              linear-gradient(45deg, transparent 40%, rgba(0,0,0,0.8) 41%, rgba(0,0,0,0.8) 43%, transparent 44%),
              linear-gradient(-45deg, transparent 40%, rgba(0,0,0,0.8) 41%, rgba(0,0,0,0.8) 43%, transparent 44%),
              linear-gradient(135deg, transparent 60%, rgba(0,0,0,0.6) 61%, rgba(0,0,0,0.6) 62%, transparent 63%);
            opacity: 0;
            animation: advent-show-cracks 0.8s ease-in-out;
          }
          
          @keyframes advent-show-cracks {
            0% { opacity: 0; }
            30% { opacity: 0.3; }
            60% { opacity: 0.7; }
            100% { opacity: 1; }
          }

          .grout-lines {
            position: relative;
          }

          .grout-lines::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: 
              repeating-linear-gradient(
                0deg,
                transparent 0px,
                rgba(139, 139, 150, 0.3) 1px,
                rgba(139, 139, 150, 0.4) 2px,
                rgba(139, 139, 150, 0.3) 3px,
                transparent 4px,
                transparent 12px
              ),
              repeating-linear-gradient(
                90deg,
                transparent 0px,
                rgba(139, 139, 150, 0.3) 1px,
                rgba(139, 139, 150, 0.4) 2px,
                rgba(139, 139, 150, 0.3) 3px,
                transparent 4px,
                transparent 12px
              );
            opacity: 0.6;
            pointer-events: none;
          }

          .grout-lines::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: 
              repeating-linear-gradient(
                45deg,
                transparent 0px,
                rgba(107, 114, 128, 0.2) 1px,
                rgba(107, 114, 128, 0.3) 2px,
                transparent 3px,
                transparent 8px
              ),
              repeating-linear-gradient(
                -45deg,
                transparent 0px,
                rgba(107, 114, 128, 0.1) 1px,
                rgba(107, 114, 128, 0.2) 2px,
                transparent 3px,
                transparent 10px
              );
            opacity: 0.4;
            pointer-events: none;
          }
        `}
      

      
        🎄 Адвент Календарь 2024 🎄
        
          Открывайте по одной плитке каждый день декабря!
        
      

      {/* Стена с плиткой */}
      
        
          {/* Дополнительные полоски клея в зазорах */}
          
            {/* Горизонтальные полоски */}
            {Array.from({ length: 5 }, (_, i) => (
              
            ))}
            
            {/* Вертикальные полоски */}
            {Array.from({ length: 6 }, (_, i) => (
              
            ))}

            {/* Следы шпателя в случайных местах */}
            {Array.from({ length: 8 }, (_, i) => (
              
            ))}
          

          {days.map((day) => {
            const available = isDemo || isDateAvailable(day.day);
            const canOpen = available && !day.opened && !day.cracking;

            return (
               canOpen && openDay(day)}
              >
                {/* Эффект керамической поверхности */}
                
                
                {/* Дополнительная текстура */}
                {day.texture % 3 === 0 && !day.opened && (
                  
                )}
                
                
                  {day.opened ? (
                    
                      {day.content.icon}
                      
                        {day.day}
                      
                    
                  ) : (
                    
                      🎁
                      
                        {day.day}
                      
                    
                  )}

                  {!available && (
                    
                      🔒
                    
                  )}
                

                {/* Блики на плитке */}
                {!day.opened && (
                  
                    
                    {day.texture % 4 === 0 && (
                      
                    )}
                  
                )}
              
            );
          })}
        
      

       setSelectedDay(null)}>
        
          
            
              🎄 День {selectedDay?.day}
            
            
              
                
                  {selectedDay?.content.icon}
                
                {selectedDay?.content.message}
              
            
          
        
      
    
  );
}