// Costume Rental Website - Version 4 (HTML/CSS/JS) - Minimalist Design

const categories = {
  era: {
    name: 'Эпоха',
    color: '#6366F1',
    themes: [
      { id: 'medieval', name: 'Средневековье', icon: 'icons/icon-crown.svg' },
      { id: 'renaissance', name: 'Ренессанс', icon: 'icons/icon-check-circle.svg' },
      { id: 'victorian', name: 'Викторианская', icon: 'icons/icon-star.svg' }
    ]
  },
  theme: {
    name: 'Тематика',
    color: '#8B5CF6',
    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: '#A78BFA',
    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 statsGeometric = document.getElementById('statsGeometric')
  if (statsGeometric) {
    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
    
    statsGeometric.innerHTML = `
      <div class="stat-geometric-square">
        <div class="stat-geometric-icon">
          <img src="icons/icon-package.svg" alt="Package" width="36" height="36">
        </div>
        <div class="stat-geometric-value">${totalRentals}</div>
        <div class="stat-geometric-label">Аренд</div>
        <div class="stat-geometric-corner"></div>
      </div>
      <div class="stat-geometric-circle">
        <div class="stat-geometric-icon">
          <img src="icons/icon-star.svg" alt="Star" width="36" height="36">
        </div>
        <div class="stat-geometric-value">${avgRating}</div>
        <div class="stat-geometric-label">Оценка</div>
      </div>
      <div class="stat-geometric-diamond">
        <div class="stat-geometric-icon">
          <img src="icons/icon-calendar.svg" alt="Calendar" width="36" height="36">
        </div>
        <div class="stat-geometric-value">${totalDays}</div>
        <div class="stat-geometric-label">Дней</div>
      </div>
      <div class="stat-geometric-hexagon">
        <div class="stat-geometric-icon">
          <img src="icons/icon-shirt.svg" alt="Shirt" width="36" height="36">
        </div>
        <div class="stat-geometric-value">${uniqueCategories}</div>
        <div class="stat-geometric-label">Категорий</div>
      </div>
    `
  }
  
  const rentalsList = document.getElementById('rentalsList')
  if (rentalsList) {
    if (rentals.length === 0) {
      rentalsList.innerHTML = `
        <div class="empty-modular">
          <div class="empty-modular-icon">
            <img src="icons/icon-shirt.svg" alt="Shirt" width="56" height="56">
          </div>
          <h3 class="empty-modular-title">Нет аренд</h3>
          <p class="empty-modular-text">Арендуйте первый костюм и увидите его здесь</p>
        </div>
      `
    } else {
      rentalsList.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">`
        ).join('')
        
        const date = new Date(rental.date).toLocaleDateString('ru-RU', { 
          day: 'numeric', 
          month: 'long', 
          year: 'numeric' 
        })
        
        return `
          <div class="rental-modular-item">
            <div class="rental-modular-indicator"></div>
            <div class="rental-modular-content">
              <div class="rental-modular-header">
                <div class="rental-modular-category">${rental.category}</div>
                <div class="rental-modular-rating">${stars}</div>
              </div>
              <h3 class="rental-modular-costume">${rental.costume}</h3>
              <div class="rental-modular-details">
                <div class="rental-modular-detail">
                  <img src="icons/icon-calendar.svg" alt="Calendar" width="16" height="16">
                  <span>${date}</span>
                </div>
                <div class="rental-modular-detail">
                  <img src="icons/icon-clock.svg" alt="Clock" width="16" height="16">
                  <span>Срок: ${rental.duration}</span>
                </div>
              </div>
              ${rental.review ? `
                <div class="rental-modular-review">
                  <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-modular-item')
  categoryCards.forEach(card => {
    card.addEventListener('click', () => {
      const category = card.dataset.category
      selectCategory(category)
    })
  })
  
  const sizeCards = document.querySelectorAll('.size-modular-item')
  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]
    returnDateInput.addEventListener('change', updateSubmitButton)
  }
}

function selectCategory(categoryId) {
  selectedCategory = categoryId
  selectedTheme = ''
  selectedSize = ''
  
  const categoryCards = document.querySelectorAll('.category-modular-item')
  categoryCards.forEach(card => {
    if (card.dataset.category === categoryId) {
      card.classList.add('selected')
      const category = categories[categoryId]
      const icon = card.querySelector('.category-modular-icon')
      if (icon) {
        icon.style.background = `${category.color}15`
        icon.style.borderColor = category.color
      }
    } else {
      card.classList.remove('selected')
      const category = categories[card.dataset.category]
      const icon = card.querySelector('.category-modular-icon')
      if (icon) {
        icon.style.background = 'rgba(99, 102, 241, 0.05)'
        icon.style.borderColor = 'rgba(99, 102, 241, 0.2)'
      }
    }
  })
  
  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-modular-item" data-theme="${theme.id}" style="border-color: rgba(99, 102, 241, 0.2); background: white;">
          <div class="theme-modular-icon" style="background: rgba(99, 102, 241, 0.05);">
            <img src="${theme.icon}" alt="${theme.name}" width="28" height="28">
          </div>
          <span class="theme-modular-name">${theme.name}</span>
        </button>
      `
    }).join('')
    
    const themeCards = themesList.querySelectorAll('.theme-modular-item')
    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-modular-item')
  themeCards.forEach(card => {
    if (card.dataset.theme === themeId) {
      card.classList.add('selected')
      const category = categories[selectedCategory]
      card.style.borderColor = category.color
      card.style.background = `${category.color}10`
      const icon = card.querySelector('.theme-modular-icon')
      if (icon) {
        icon.style.background = `${category.color}15`
      }
    } else {
      card.classList.remove('selected')
      const category = categories[selectedCategory]
      card.style.borderColor = 'rgba(99, 102, 241, 0.2)'
      card.style.background = 'white'
      const icon = card.querySelector('.theme-modular-icon')
      if (icon) {
        icon.style.background = 'rgba(99, 102, 241, 0.05)'
      }
    }
  })
  
  const sizesSection = document.getElementById('sizesSection')
  if (sizesSection) {
    sizesSection.style.display = 'block'
  }
  
  updateSubmitButton()
}

function selectSize(size) {
  selectedSize = size
  
  const sizeCards = document.querySelectorAll('.size-modular-item')
  sizeCards.forEach(card => {
    if (card.dataset.size === size) {
      card.classList.add('selected')
      const category = categories[selectedCategory]
      card.style.borderColor = category.color
      card.style.background = `${category.color}10`
      card.style.color = category.color
    } else {
      card.classList.remove('selected')
      const category = categories[selectedCategory]
      card.style.borderColor = 'rgba(99, 102, 241, 0.2)'
      card.style.background = 'white'
      card.style.color = '#6366F1'
    }
  })
  
  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)

