// Cooking Masterclass Booking Website - Version 4 (HTML/CSS/JS)

// Topics data
const topics = [
  { 
    id: 'baking', 
    name: 'Выпечка', 
    icon: 'icons/topic-baking.svg', 
    color: '#D2691E'
  },
  { 
    id: 'desserts', 
    name: 'Десерты', 
    icon: 'icons/topic-desserts.svg', 
    color: '#CD853F'
  },
  { 
    id: 'asian', 
    name: 'Азиатская кухня', 
    icon: 'icons/topic-asian.svg', 
    color: '#F4A460'
  },
  { 
    id: 'vegan', 
    name: 'Веганство', 
    icon: 'icons/topic-vegan.svg', 
    color: '#654321'
  }
]

// Initialize page
function initPage() {
  const currentPage = window.location.pathname.includes('book.html') ? 'book' : 'participations'
  
  if (currentPage === 'participations') {
    initParticipationsPage()
  } else {
    initBookPage()
  }
  
  initSlider()
}

// Initialize participations page
function initParticipationsPage() {
  loadParticipations()
  updateStats()
  
  // Poll for storage changes
  setInterval(() => {
    loadParticipations()
    updateStats()
  }, 500)
}

// Load participations from localStorage
function loadParticipations() {
  const saved = localStorage.getItem('cookingParticipations')
  let participations = []
  
  if (saved) {
    const data = JSON.parse(saved)
    participations = data.past || []
  } else {
    // Default participations
    participations = [
      {
        id: 1,
        title: 'Искусство выпечки хлеба',
        date: '2025-03-15',
        rating: 5
      },
      {
        id: 2,
        title: 'Десерты без сахара',
        date: '2025-03-10',
        rating: 4
      },
      {
        id: 3,
        title: 'Секреты азиатской кухни',
        date: '2025-03-05',
        rating: 5
      }
    ]
    localStorage.setItem('cookingParticipations', JSON.stringify({ past: participations }))
  }
  
  renderParticipations(participations)
}

// Render participations
function renderParticipations(participations) {
  const container = document.getElementById('participationsContainer')
  if (!container) return
  
  if (participations.length === 0) {
    container.innerHTML = `
      <div class="empty-state">
        <img src="icons/empty-participations.svg" alt="" class="empty-icon" width="72" height="72" />
        <p>Вы еще не участвовали в мастер-классах</p>
      </div>
    `
    return
  }
  
  container.innerHTML = participations.map(participation => {
    const ratingSection = !participation.rating ? `
      <div class="rating-section">
        <div class="rating-label">Оцените мастер-класс:</div>
        <div class="stars-container">
          ${[1, 2, 3, 4, 5].map(star => `
            <button class="star-btn" onclick="handleRating(${participation.id}, ${star})">
              <img src="icons/star.svg" alt="Оценка ${star}" class="star-icon" width="28" height="28" />
            </button>
          `).join('')}
        </div>
      </div>
    ` : `
      <div class="rating-display">
        <div class="rating-label">Ваша оценка:</div>
        <div class="stars-container">
          ${[1, 2, 3, 4, 5].map(star => `
            <img 
              src="icons/star.svg" 
              alt="Звезда ${star}" 
              class="star-icon ${star <= participation.rating ? 'filled' : ''}" 
              width="28" 
              height="28" 
            />
          `).join('')}
        </div>
      </div>
    `
    
    return `
      <div class="participation-card">
        <div class="participation-header">
          <div class="participation-title-wrapper">
            <img src="icons/participation-chef.svg" alt="" class="participation-icon" width="40" height="40" />
            <h3 class="participation-title">${participation.title}</h3>
          </div>
        </div>
        <div class="participation-date">
          <img src="icons/detail-calendar.svg" alt="" class="detail-icon" width="20" height="20" />
          <span>${new Date(participation.date).toLocaleDateString('ru-RU', { 
            day: 'numeric', 
            month: 'long', 
            year: 'numeric' 
          })}</span>
        </div>
        ${ratingSection}
      </div>
    `
  }).join('')
}

// Update stats
function updateStats() {
  const saved = localStorage.getItem('cookingParticipations')
  if (!saved) {
    document.getElementById('statPassed').textContent = '0'
    document.getElementById('statExcellent').textContent = '0'
    document.getElementById('statRating').textContent = '0'
    return
  }
  
  const data = JSON.parse(saved)
  const participations = data.past || []
  const passed = participations.length
  const excellent = participations.filter(p => p.rating === 5).length
  const avgRating = participations.length > 0 
    ? (participations.reduce((sum, p) => sum + (p.rating || 0), 0) / participations.length).toFixed(1)
    : '0'
  
  document.getElementById('statPassed').textContent = passed
  document.getElementById('statExcellent').textContent = excellent
  document.getElementById('statRating').textContent = avgRating
}

// Handle rating
function handleRating(id, rating) {
  const saved = localStorage.getItem('cookingParticipations')
  if (!saved) return
  
  const data = JSON.parse(saved)
  data.past = data.past.map(p => 
    p.id === id ? { ...p, rating } : p
  )
  
  localStorage.setItem('cookingParticipations', JSON.stringify(data))
  loadParticipations()
  updateStats()
}

// Initialize book page
function initBookPage() {
  let selectedTopic = null
  
  const topicsGrid = document.getElementById('topicsGrid')
  const dateInput = document.getElementById('date')
  const submitBtn = document.getElementById('submitBtn')
  const bookingForm = document.getElementById('bookingForm')
  const successMessage = document.getElementById('successMessage')
  
  // Set date limits
  const today = new Date().toISOString().split('T')[0]
  const maxDate = new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
  if (dateInput) {
    dateInput.min = today
    dateInput.max = maxDate
  }
  
  // Render topics
  if (topicsGrid) {
    topicsGrid.innerHTML = topics.map(topic => `
      <button 
        type="button" 
        class="topic-card" 
        data-topic="${topic.id}"
        style="border-color: rgba(210, 105, 30, 0.2); background-color: rgba(255, 255, 255, 0.6);"
      >
        <img src="${topic.icon}" alt="${topic.name}" class="topic-icon" width="32" height="32" />
        <span class="topic-name">${topic.name}</span>
      </button>
    `).join('')
    
    // Topic selection
    topicsGrid.querySelectorAll('.topic-card').forEach(card => {
      card.addEventListener('click', function() {
        topicsGrid.querySelectorAll('.topic-card').forEach(c => {
          c.classList.remove('selected')
          c.style.borderColor = 'rgba(210, 105, 30, 0.2)'
          c.style.backgroundColor = 'rgba(255, 255, 255, 0.6)'
        })
        this.classList.add('selected')
        selectedTopic = this.dataset.topic
        const topic = topics.find(t => t.id === selectedTopic)
        if (topic) {
          this.style.borderColor = topic.color
          this.style.backgroundColor = `${topic.color}15`
        }
        updateSubmitButton()
      })
    })
  }
  
  // Date input
  if (dateInput) {
    dateInput.addEventListener('change', function() {
      updateSubmitButton()
    })
  }
  
  function updateSubmitButton() {
    if (submitBtn) {
      const hasDate = dateInput && dateInput.value
      submitBtn.disabled = !selectedTopic || !hasDate
    }
  }
  
  // Form submission
  if (bookingForm) {
    bookingForm.addEventListener('submit', function(e) {
      e.preventDefault()
      
      if (!selectedTopic || !dateInput.value) {
        alert('Пожалуйста, выберите тему и дату')
        return
      }
      
      const topic = topics.find(t => t.id === selectedTopic)
      const newParticipation = {
        id: Date.now(),
        title: topic.name,
        date: dateInput.value,
        rating: null
      }
      
      const saved = localStorage.getItem('cookingParticipations')
      const data = saved ? JSON.parse(saved) : { past: [] }
      data.past.unshift(newParticipation)
      localStorage.setItem('cookingParticipations', JSON.stringify(data))
      
      // Show success message
      if (successMessage) {
        successMessage.style.display = 'flex'
        setTimeout(() => {
          successMessage.style.display = 'none'
        }, 3000)
      }
      
      // Reset form
      topicsGrid.querySelectorAll('.topic-card').forEach(c => {
        c.classList.remove('selected')
        c.style.borderColor = 'rgba(210, 105, 30, 0.2)'
        c.style.backgroundColor = 'rgba(255, 255, 255, 0.6)'
      })
      selectedTopic = null
      if (dateInput) dateInput.value = ''
      updateSubmitButton()
    })
  }
}

// Initialize slider
function initSlider() {
  const slider = document.getElementById('slider')
  if (!slider) return
  
  const wrapper = slider.querySelector('.slider-wrapper')
  const slides = slider.querySelectorAll('.slide')
  const prevBtn = document.getElementById('sliderPrev')
  const nextBtn = document.getElementById('sliderNext')
  const indicators = slider.querySelectorAll('.indicator')
  
  let currentSlide = 0
  const totalSlides = slides.length
  
  function updateSlider() {
    slides.forEach((slide, index) => {
      slide.classList.toggle('active', index === currentSlide)
    })
    
    indicators.forEach((indicator, index) => {
      indicator.classList.toggle('active', index === currentSlide)
    })
  }
  
  function nextSlide() {
    currentSlide = (currentSlide + 1) % totalSlides
    updateSlider()
  }
  
  function prevSlide() {
    currentSlide = (currentSlide - 1 + totalSlides) % totalSlides
    updateSlider()
  }
  
  function goToSlide(index) {
    currentSlide = index
    updateSlider()
  }
  
  if (prevBtn) prevBtn.addEventListener('click', prevSlide)
  if (nextBtn) nextBtn.addEventListener('click', nextSlide)
  
  indicators.forEach((indicator, index) => {
    indicator.addEventListener('click', () => goToSlide(index))
  })
  
  // Auto-advance every 3 seconds
  setInterval(nextSlide, 3000)
  
  // Initialize
  updateSlider()
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', initPage)

