// Costume Rental Website - Version 3 (HTML/CSS/JS)

const categories = {
  era: {
    name: 'Эпоха',
    color: '#C41E3A',
    gradient: 'linear-gradient(135deg, #C41E3A 0%, #E63946 100%)',
    themes: [
      { id: 'medieval', name: 'Средневековье', icon: 'icons/icon-crown.svg' },
      { id: 'renaissance', name: 'Ренессанс', icon: 'icons/icon-award.svg' },
      { id: 'victorian', name: 'Викторианская', icon: 'icons/icon-heart.svg' }
    ]
  },
  theme: {
    name: 'Тематика',
    color: '#FF6B35',
    gradient: 'linear-gradient(135deg, #FF6B35 0%, #FFB627 100%)',
    themes: [
      { id: 'fantasy', name: 'Фэнтези', icon: 'icons/icon-sparkles.svg' },
      { id: 'pirate', name: 'Пираты', icon: 'icons/icon-package.svg' },
      { id: 'superhero', name: 'Супергерои', icon: 'icons/icon-zap.svg' }
    ]
  },
  size: {
    name: 'Размер',
    color: '#FFB627',
    gradient: 'linear-gradient(135deg, #FFB627 0%, #FFD93D 100%)',
    themes: [
      { id: 'xs-xl', name: 'XS-XXL', icon: 'icons/icon-ruler.svg' },
      { id: 'kids', name: 'Детские', icon: 'icons/icon-users.svg' },
      { id: 'plus', name: 'Большие размеры', icon: 'icons/icon-trending.svg' }
    ]
  }
}

const sizes = ['XS', 'S', 'M', 'L', 'XL', 'XXL']

let currentSlide = 0
let slides = []
let dots = []
let slideInterval
let selectedCategory = ''
let selectedTheme = ''
let selectedSize = ''

function initPage() {
  const currentPage = window.location.pathname.includes('rent.html') ? 'rent' : 'index'
  
  if (currentPage === 'rent') {
    initRentPage()
  } else {
    initIndexPage()
  }
  
  initSlider()
}

function initIndexPage() {
  loadRentals()
  updateStats()
  
  setInterval(() => {
    loadRentals()
    updateStats()
  }, 500)
}

function loadRentals() {
  const saved = localStorage.getItem('costumeRentals')
  let rentals = []
  
  if (saved) {
    try {
      rentals = JSON.parse(saved)
    } catch (e) {
      rentals = []
    }
  } else {
    rentals = [
      {
        id: 1,
        costume: 'Рыцарский доспех',
        date: '2025-03-28',
        duration: '3 дня',
        review: 'Отличный костюм, все детали на месте, очень доволен!',
        rating: 5,
        category: 'Эпоха'
      },
      {
        id: 2,
        costume: 'Пиратский наряд',
        date: '2025-03-25',
        duration: '5 дней',
        review: 'Прекрасное качество, костюм выглядел очень реалистично',
        rating: 5,
        category: 'Тематика'
      },
      {
        id: 3,
        costume: 'Костюм эльфа',
        date: '2025-03-22',
        duration: '2 дня',
        review: 'Красивый костюм, отлично подошел по размеру',
        rating: 4,
        category: 'Тематика'
      }
    ]
    localStorage.setItem('costumeRentals', JSON.stringify(rentals))
  }
  
  const heroNumber = document.getElementById('heroNumber')
  if (heroNumber) {
    heroNumber.textContent = rentals.length
  }
  
  const heroStats = document.getElementById('heroStats')
  if (heroStats && rentals.length > 0) {
    const avgRating = (rentals.reduce((sum, r) => sum + r.rating, 0) / rentals.length).toFixed(1)
    const totalDays = rentals.reduce((sum, r) => sum + parseInt(r.duration), 0)
    heroStats.innerHTML = `
      <div class="hero-stat-inline">
        <img src="icons/icon-star.svg" alt="Star" width="20" height="20">
        <span>${avgRating}</span>
      </div>
      <div class="hero-stat-inline">
        <img src="icons/icon-calendar.svg" alt="Calendar" width="20" height="20">
        <span>${totalDays} дней</span>
      </div>
    `
  }
  
  const statsMasonry = document.getElementById('statsMasonry')
  if (statsMasonry) {
    const totalRentals = rentals.length
    const avgRating = rentals.length > 0 ? (rentals.reduce((sum, r) => sum + r.rating, 0) / rentals.length).toFixed(1) : 0
    const totalDays = rentals.reduce((sum, r) => sum + parseInt(r.duration), 0)
    const uniqueCategories = new Set(rentals.map(r => r.category)).size
    
    statsMasonry.innerHTML = `
      <div class="stat-masonry-large">
        <div class="stat-masonry-icon-large">
          <img src="icons/icon-package.svg" alt="Package" width="56" height="56">
        </div>
        <div class="stat-masonry-content">
          <div class="stat-masonry-value-large">${totalRentals}</div>
          <div class="stat-masonry-label-large">Всего аренд</div>
        </div>
        <div class="stat-masonry-decoration"></div>
      </div>
      <div class="stat-masonry-medium">
        <div class="stat-masonry-icon-medium">
          <img src="icons/icon-star.svg" alt="Star" width="44" height="44">
        </div>
        <div class="stat-masonry-content">
          <div class="stat-masonry-value-medium">${avgRating}</div>
          <div class="stat-masonry-label-medium">Средняя оценка</div>
        </div>
      </div>
      <div class="stat-masonry-small">
        <div class="stat-masonry-icon-small">
          <img src="icons/icon-calendar.svg" alt="Calendar" width="36" height="36">
        </div>
        <div class="stat-masonry-content">
          <div class="stat-masonry-value-small">${totalDays}</div>
          <div class="stat-masonry-label-small">Дней аренды</div>
        </div>
      </div>
      <div class="stat-masonry-wide">
        <div class="stat-masonry-icon-wide">
          <img src="icons/icon-heart.svg" alt="Heart" width="40" height="40">
        </div>
        <div class="stat-masonry-content">
          <div class="stat-masonry-value-wide">${uniqueCategories}</div>
          <div class="stat-masonry-label-wide">Категорий</div>
        </div>
      </div>
    `
  }
  
  const timelineContainer = document.getElementById('rentalsTimeline')
  if (timelineContainer) {
    if (rentals.length === 0) {
      timelineContainer.innerHTML = `
        <div class="empty-state-asymmetric">
          <div class="empty-icon-asymmetric">
            <img src="icons/icon-sparkles.svg" alt="Sparkles" width="80" height="80">
          </div>
          <h3 class="empty-title-asymmetric">Начните свое костюмное приключение</h3>
          <p class="empty-text-asymmetric">Арендуйте первый костюм и увидите его здесь</p>
        </div>
      `
    } else {
      timelineContainer.innerHTML = rentals.map((rental, index) => {
        const stars = Array.from({ length: 5 }, (_, i) => 
          `<img src="icons/icon-star${i < rental.rating ? '-fill' : ''}.svg" alt="Star" width="16" height="16" style="color: ${i < rental.rating ? '#FFB627' : '#E0E0E0'}">`
        ).join('')
        
        const date = new Date(rental.date).toLocaleDateString('ru-RU', { 
          day: 'numeric', 
          month: 'long', 
          year: 'numeric' 
        })
        
        const isLeft = index % 2 === 0
        const gradient = index % 3 === 0 ? 'linear-gradient(135deg, #C41E3A 0%, #E63946 100%)' :
          index % 3 === 1 ? 'linear-gradient(135deg, #FF6B35 0%, #FFB627 100%)' :
          'linear-gradient(135deg, #FFB627 0%, #FFD93D 100%)'
        
        return `
          <div class="rental-timeline-item ${isLeft ? 'left' : 'right'}">
            <div class="rental-timeline-marker">
              <div class="rental-marker-dot"></div>
              <div class="rental-marker-line"></div>
            </div>
            <div class="rental-timeline-card">
              <div class="rental-card-top">
                <div class="rental-category-tag" style="background: ${gradient}">
                  ${rental.category}
                </div>
                <div class="rental-rating-stars">${stars}</div>
              </div>
              <h3 class="rental-costume-title">${rental.costume}</h3>
              <div class="rental-details-grid">
                <div class="rental-detail-box">
                  <img src="icons/icon-calendar.svg" alt="Calendar" width="18" height="18">
                  <span>${date}</span>
                </div>
                <div class="rental-detail-box">
                  <img src="icons/icon-clock.svg" alt="Clock" width="18" height="18">
                  <span>Срок: ${rental.duration}</span>
                </div>
              </div>
              ${rental.review ? `
                <div class="rental-review-bubble">
                  <img src="icons/icon-star-fill.svg" alt="Star" width="14" height="14">
                  <span>${rental.review}</span>
                </div>
              ` : ''}
            </div>
          </div>
        `
      }).join('')
    }
  }
}

function updateStats() {
  // Stats are updated in loadRentals
}

function initRentPage() {
  const categoryCards = document.querySelectorAll('.category-staggered-card')
  categoryCards.forEach(card => {
    card.addEventListener('click', () => {
      const category = card.dataset.category
      selectCategory(category)
    })
  })
  
  const sizeCards = document.querySelectorAll('.size-staggered-card')
  sizeCards.forEach(card => {
    card.addEventListener('click', () => {
      const size = card.dataset.size
      selectSize(size)
    })
  })
  
  const form = document.getElementById('rentalForm')
  if (form) {
    form.addEventListener('submit', handleSubmit)
  }
  
  const returnDateInput = document.getElementById('returnDate')
  if (returnDateInput) {
    const today = new Date()
    const maxDate = new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000)
    returnDateInput.min = today.toISOString().split('T')[0]
    returnDateInput.max = maxDate.toISOString().split('T')[0]
  }
}

function selectCategory(categoryId) {
  selectedCategory = categoryId
  selectedTheme = ''
  selectedSize = ''
  
  const categoryCards = document.querySelectorAll('.category-staggered-card')
  categoryCards.forEach(card => {
    if (card.dataset.category === categoryId) {
      card.classList.add('selected')
      const category = categories[categoryId]
      card.style.background = category.gradient
      card.style.borderColor = 'transparent'
    } else {
      card.classList.remove('selected')
      card.style.background = 'white'
      card.style.borderColor = categories[card.dataset.category].color + '40'
    }
  })
  
  const themesSection = document.getElementById('themesSection')
  const themesList = document.getElementById('themesList')
  if (themesSection && themesList) {
    themesSection.style.display = 'block'
    const category = categories[categoryId]
    themesList.innerHTML = category.themes.map(theme => {
      return `
        <button type="button" class="theme-staggered-card" data-theme="${theme.id}" style="background: white; border-color: ${category.color}40;">
          <div class="theme-staggered-icon" style="background: ${category.color}15;">
            <img src="${theme.icon}" alt="${theme.name}" width="40" height="40">
          </div>
          <span class="theme-staggered-name" style="color: #1A1A1A;">${theme.name}</span>
        </button>
      `
    }).join('')
    
    const themeCards = themesList.querySelectorAll('.theme-staggered-card')
    themeCards.forEach(card => {
      card.addEventListener('click', () => {
        const themeId = card.dataset.theme
        selectTheme(themeId)
      })
    })
  }
  
  const sizesSection = document.getElementById('sizesSection')
  if (sizesSection) {
    sizesSection.style.display = 'none'
  }
  
  updateSubmitButton()
}

function selectTheme(themeId) {
  selectedTheme = themeId
  
  const themeCards = document.querySelectorAll('.theme-staggered-card')
  themeCards.forEach(card => {
    if (card.dataset.theme === themeId) {
      card.classList.add('selected')
      const category = categories[selectedCategory]
      card.style.background = category.gradient
      card.style.borderColor = 'transparent'
      card.querySelector('.theme-staggered-name').style.color = 'white'
    } else {
      card.classList.remove('selected')
      const category = categories[selectedCategory]
      card.style.background = 'white'
      card.style.borderColor = category.color + '40'
      card.querySelector('.theme-staggered-name').style.color = '#1A1A1A'
    }
  })
  
  const sizesSection = document.getElementById('sizesSection')
  if (sizesSection) {
    sizesSection.style.display = 'block'
  }
  
  updateSubmitButton()
}

function selectSize(size) {
  selectedSize = size
  
  const sizeCards = document.querySelectorAll('.size-staggered-card')
  sizeCards.forEach(card => {
    if (card.dataset.size === size) {
      card.classList.add('selected')
      const category = categories[selectedCategory]
      card.style.background = category.gradient
      card.style.borderColor = 'transparent'
      card.style.color = 'white'
    } else {
      card.classList.remove('selected')
      const category = categories[selectedCategory]
      card.style.background = 'white'
      card.style.borderColor = category.color + '40'
      card.style.color = '#1A1A1A'
    }
  })
  
  updateSubmitButton()
}

function updateSubmitButton() {
  const submitBtn = document.getElementById('submitBtn')
  const returnDate = document.getElementById('returnDate')
  if (submitBtn && returnDate) {
    if (selectedCategory && selectedTheme && selectedSize && returnDate.value) {
      submitBtn.disabled = false
    } else {
      submitBtn.disabled = true
    }
  }
}

function handleSubmit(e) {
  e.preventDefault()
  
  const returnDate = document.getElementById('returnDate')
  if (!returnDate || !returnDate.value) {
    return
  }
  
  const saved = localStorage.getItem('costumeRentals')
  const rentals = saved ? JSON.parse(saved) : []
  
  const category = categories[selectedCategory]
  const theme = category.themes.find(t => t.id === selectedTheme)
  
  const newRental = {
    id: Date.now(),
    costume: theme ? theme.name : 'Костюм',
    date: new Date().toISOString().split('T')[0],
    duration: '3 дня',
    review: '',
    rating: 0,
    category: category.name
  }
  
  rentals.push(newRental)
  localStorage.setItem('costumeRentals', JSON.stringify(rentals))
  
  const successMessage = document.getElementById('successMessage')
  if (successMessage) {
    successMessage.style.display = 'flex'
    setTimeout(() => {
      window.location.href = 'index.html'
    }, 2000)
  }
}

function initSlider() {
  slides = Array.from(document.querySelectorAll('.slide'))
  dots = Array.from(document.querySelectorAll('.dot'))
  
  if (slides.length === 0) return
  
  const sliderPrev = document.getElementById('sliderPrev')
  const sliderNext = document.getElementById('sliderNext')
  
  if (sliderPrev) {
    sliderPrev.addEventListener('click', () => {
      goToSlide((currentSlide - 1 + slides.length) % slides.length)
    })
  }
  
  if (sliderNext) {
    sliderNext.addEventListener('click', () => {
      goToSlide((currentSlide + 1) % slides.length)
    })
  }
  
  dots.forEach((dot, index) => {
    dot.addEventListener('click', () => {
      goToSlide(index)
    })
  })
  
  startSlider()
}

function goToSlide(index) {
  currentSlide = index
  
  slides.forEach((slide, i) => {
    slide.classList.toggle('active', i === index)
  })
  
  dots.forEach((dot, i) => {
    dot.classList.toggle('active', i === index)
  })
  
  clearInterval(slideInterval)
  startSlider()
}

function startSlider() {
  slideInterval = setInterval(() => {
    goToSlide((currentSlide + 1) % slides.length)
  }, 3000)
}

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

