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

// Categories data
const categories = [
  { 
    id: 'sound', 
    name: 'Звуковое оборудование', 
    icon: 'icons/category-sound.svg', 
    color: '#4f46e5',
    items: ['Микрофоны', 'Колонки', 'Микшерный пульт', 'Усилители']
  },
  { 
    id: 'lighting', 
    name: 'Освещение', 
    icon: 'icons/category-light.svg', 
    color: '#f59e0b',
    items: ['Прожекторы', 'Светодиодные панели', 'Световые эффекты', 'Сценическое освещение']
  },
  { 
    id: 'furniture', 
    name: 'Мебель', 
    icon: 'icons/category-furniture.svg', 
    color: '#10b981',
    items: ['Столы', 'Стулья', 'Диваны', 'Стеллажи']
  }
]

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

// Initialize rentals page
function initRentalsPage() {
  loadRentals()
  updateStats()
  
  // Poll for storage changes
  setInterval(() => {
    loadRentals()
    updateStats()
  }, 500)
}

// Load rentals from localStorage
function loadRentals() {
  const savedRentals = localStorage.getItem('equipmentRentals')
  let rentals = { active: [], past: [] }
  
  if (savedRentals) {
    rentals = JSON.parse(savedRentals)
  } else {
    // Default rentals
    rentals = {
      active: [
        {
          id: 1,
          category: 'Звуковое оборудование',
          items: ['Микрофоны', 'Колонки', 'Микшерный пульт'],
          startDate: '2025-12-25',
          endDate: '2025-12-28',
          status: 'Активна',
          total: 15000
        },
        {
          id: 2,
          category: 'Освещение',
          items: ['Прожекторы', 'Светодиодные панели'],
          startDate: '2025-12-26',
          endDate: '2025-12-29',
          status: 'Активна',
          total: 12000
        },
        {
          id: 3,
          category: 'Мебель',
          items: ['Столы', 'Стулья', 'Диваны'],
          startDate: '2025-12-27',
          endDate: '2025-12-30',
          status: 'Активна',
          total: 8000
        }
      ],
      past: [
        {
          id: 4,
          category: 'Звуковое оборудование',
          items: ['Микрофоны', 'Колонки'],
          startDate: '2025-12-15',
          endDate: '2025-12-18',
          status: 'Завершена',
          total: 10000,
          rating: 5,
          review: 'Отличное оборудование, все работало идеально!'
        },
        {
          id: 5,
          category: 'Освещение',
          items: ['Прожекторы', 'Светодиодные панели'],
          startDate: '2025-12-10',
          endDate: '2025-12-12',
          status: 'Завершена',
          total: 12000,
          rating: 4
        },
        {
          id: 6,
          category: 'Мебель',
          items: ['Столы', 'Стулья'],
          startDate: '2025-12-05',
          endDate: '2025-12-08',
          status: 'Завершена',
          total: 8000,
          rating: 5
        }
      ]
    }
    localStorage.setItem('equipmentRentals', JSON.stringify(rentals))
  }
  
  renderRentals(rentals.active, 'activeRentals')
  renderRentals(rentals.past, 'pastRentals', true)
  updateStats()
}

// Render rentals
function renderRentals(rentals, containerId, isPast = false) {
  const container = document.getElementById(containerId)
  if (!container) return
  
  if (rentals.length === 0) {
    container.innerHTML = `
      <div class="empty-state">
        <img src="icons/empty-rentals.svg" alt="" class="empty-icon" width="64" height="64" />
        <p>${isPast ? 'Нет завершенных аренд' : 'Нет активных аренд'}</p>
      </div>
    `
    return
  }
  
  container.innerHTML = rentals.map(rental => {
    const categoryIcon = getCategoryIcon(rental.category)
    const statusColor = getStatusColor(rental.status)
    
    let ratingSection = ''
    if (isPast) {
      if (!rental.rating) {
        ratingSection = `
          <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(${rental.id}, ${star})">
                  <img src="icons/star.svg" alt="Оценка ${star}" class="star-icon" width="24" height="24" />
                </button>
              `).join('')}
            </div>
          </div>
        `
      } else {
        ratingSection = `
          <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 <= rental.rating ? 'filled' : ''}" width="24" height="24" />
              `).join('')}
            </div>
          </div>
        `
      }
      
      let reviewSection = ''
      if (rental.rating && !rental.review) {
        reviewSection = `
          <div class="review-section">
            <textarea class="review-input" placeholder="Оставьте отзыв о вашей аренде..." rows="3" onblur="handleReview(${rental.id}, this.value)"></textarea>
          </div>
        `
      } else if (rental.review) {
        reviewSection = `
          <div class="review-display">
            <div class="review-label">Ваш отзыв:</div>
            <p class="review-text">${rental.review}</p>
          </div>
        `
      }
      
      return `
        <div class="rental-card past">
          <div class="rental-header">
            <div class="rental-category">
              <img src="${categoryIcon}" alt="${rental.category}" class="category-icon" width="32" height="32" />
              <span class="category-name">${rental.category}</span>
            </div>
            <span class="rental-status" style="background-color: ${statusColor}20; color: ${statusColor}">
              ${rental.status}
            </span>
          </div>
          <div class="rental-items">
            ${rental.items.map(item => `<span class="rental-item-tag">${item}</span>`).join('')}
          </div>
          <div class="rental-bottom-section">
            <div class="rental-dates">
              <div class="rental-date">
                <img src="icons/detail-calendar.svg" alt="" class="detail-icon" width="18" height="18" />
                <span>С ${new Date(rental.startDate).toLocaleDateString('ru-RU')}</span>
              </div>
              <div class="rental-date">
                <img src="icons/detail-calendar.svg" alt="" class="detail-icon" width="18" height="18" />
                <span>По ${new Date(rental.endDate).toLocaleDateString('ru-RU')}</span>
              </div>
            </div>
            <div class="rental-total">
              <span class="total-label">Сумма:</span>
              <span class="total-value">${rental.total.toLocaleString('ru-RU')} ₽</span>
            </div>
          </div>
          ${ratingSection}
          ${reviewSection}
        </div>
      `
    } else {
      return `
        <div class="rental-card">
          <div class="rental-header">
            <div class="rental-category">
              <img src="${categoryIcon}" alt="${rental.category}" class="category-icon" width="32" height="32" />
              <span class="category-name">${rental.category}</span>
            </div>
            <span class="rental-status" style="background-color: ${statusColor}20; color: ${statusColor}">
              ${rental.status}
            </span>
          </div>
          <div class="rental-items">
            ${rental.items.map(item => `<span class="rental-item-tag">${item}</span>`).join('')}
          </div>
          <div class="rental-bottom-section">
            <div class="rental-dates">
              <div class="rental-date">
                <img src="icons/detail-calendar.svg" alt="" class="detail-icon" width="18" height="18" />
                <span>С ${new Date(rental.startDate).toLocaleDateString('ru-RU')}</span>
              </div>
              <div class="rental-date">
                <img src="icons/detail-calendar.svg" alt="" class="detail-icon" width="18" height="18" />
                <span>По ${new Date(rental.endDate).toLocaleDateString('ru-RU')}</span>
              </div>
            </div>
            <div class="rental-total">
              <span class="total-label">Сумма:</span>
              <span class="total-value">${rental.total.toLocaleString('ru-RU')} ₽</span>
            </div>
          </div>
        </div>
      `
    }
  }).join('')
}

// Update stats
function updateStats() {
  const savedRentals = localStorage.getItem('equipmentRentals')
  if (!savedRentals) return
  
  const rentals = JSON.parse(savedRentals)
  const activeCount = rentals.active?.length || 0
  const pastCount = rentals.past?.length || 0
  const totalCount = activeCount + pastCount
  
  const statActive = document.getElementById('statActive')
  const statCompleted = document.getElementById('statCompleted')
  const statTotal = document.getElementById('statTotal')
  
  if (statActive) statActive.textContent = activeCount
  if (statCompleted) statCompleted.textContent = pastCount
  if (statTotal) statTotal.textContent = totalCount
}

// Handle rating
function handleRating(rentalId, rating) {
  const savedRentals = localStorage.getItem('equipmentRentals')
  if (!savedRentals) return
  
  const rentals = JSON.parse(savedRentals)
  rentals.past = rentals.past.map(rental => 
    rental.id === rentalId ? { ...rental, rating } : rental
  )
  
  localStorage.setItem('equipmentRentals', JSON.stringify(rentals))
  loadRentals()
}

// Handle review
function handleReview(rentalId, review) {
  const savedRentals = localStorage.getItem('equipmentRentals')
  if (!savedRentals) return
  
  const rentals = JSON.parse(savedRentals)
  rentals.past = rentals.past.map(rental => 
    rental.id === rentalId ? { ...rental, review } : rental
  )
  
  localStorage.setItem('equipmentRentals', JSON.stringify(rentals))
  loadRentals()
}

// Get category icon
function getCategoryIcon(category) {
  if (category.includes('Звук')) return 'icons/category-sound.svg'
  if (category.includes('Освещение')) return 'icons/category-light.svg'
  if (category.includes('Мебель')) return 'icons/category-furniture.svg'
  return 'icons/category-default.svg'
}

// Get status color
function getStatusColor(status) {
  if (status === 'Активна') return '#10b981'
  if (status === 'Завершена') return '#64748b'
  return '#f59e0b'
}

// Initialize book page
function initBookPage() {
  let selectedCategory = null
  let startDate = null
  let endDate = null
  
  const categoriesGrid = document.getElementById('categoriesGrid')
  const categoryPreview = document.getElementById('categoryPreview')
  const previewItems = document.getElementById('previewItems')
  const startDateInput = document.getElementById('startDate')
  const endDateInput = document.getElementById('endDate')
  const rentalSummary = document.getElementById('rentalSummary')
  const summaryDays = document.getElementById('summaryDays')
  const summaryTotal = document.getElementById('summaryTotal')
  const submitBtn = document.getElementById('submitBtn')
  const bookingForm = document.getElementById('bookingForm')
  
  // Set min date to today
  const today = new Date().toISOString().split('T')[0]
  if (startDateInput) startDateInput.min = today
  if (endDateInput) endDateInput.min = today
  
  // Category selection
  if (categoriesGrid) {
    categoriesGrid.querySelectorAll('.category-card').forEach(card => {
      card.addEventListener('click', function() {
        categoriesGrid.querySelectorAll('.category-card').forEach(c => c.classList.remove('selected'))
        this.classList.add('selected')
        selectedCategory = this.dataset.category
        
        const categoryData = categories.find(c => c.id === selectedCategory)
        if (categoryData && categoryPreview && previewItems) {
          previewItems.innerHTML = categoryData.items.map(item => 
            `<span class="preview-item">${item}</span>`
          ).join('')
          categoryPreview.style.display = 'block'
        }
        
        updateSubmitButton()
        updateSummary()
      })
    })
  }
  
  // Date inputs
  if (startDateInput) {
    startDateInput.addEventListener('change', function() {
      startDate = this.value
      if (endDateInput && endDateInput.value && endDateInput.value < startDate) {
        endDateInput.value = ''
        endDate = null
      }
      if (endDateInput) endDateInput.min = startDate
      updateSubmitButton()
      updateSummary()
    })
  }
  
  if (endDateInput) {
    endDateInput.addEventListener('change', function() {
      endDate = this.value
      updateSubmitButton()
      updateSummary()
    })
  }
  
  function updateSummary() {
    if (!selectedCategory || !startDate || !endDate) {
      if (rentalSummary) rentalSummary.style.display = 'none'
      return
    }
    
    const start = new Date(startDate)
    const end = new Date(endDate)
    const days = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1
    
    const basePrice = selectedCategory === 'sound' ? 5000 : selectedCategory === 'lighting' ? 4000 : 3000
    const total = days * basePrice
    
    if (summaryDays) summaryDays.textContent = `${days} дней`
    if (summaryTotal) summaryTotal.textContent = `${total.toLocaleString('ru-RU')} ₽`
    if (rentalSummary) rentalSummary.style.display = 'block'
  }
  
  function updateSubmitButton() {
    if (submitBtn) {
      submitBtn.disabled = !selectedCategory || !startDate || !endDate
    }
  }
  
  // Form submission
  if (bookingForm) {
    bookingForm.addEventListener('submit', function(e) {
      e.preventDefault()
      
      if (!selectedCategory || !startDate || !endDate) {
        alert('Пожалуйста, заполните все поля')
        return
      }
      
      const start = new Date(startDate)
      const end = new Date(endDate)
      
      if (end <= start) {
        alert('Дата окончания должна быть позже даты начала')
        return
      }
      
      const savedRentals = localStorage.getItem('equipmentRentals')
      const rentals = savedRentals ? JSON.parse(savedRentals) : { active: [], past: [] }
      const category = categories.find(c => c.id === selectedCategory)
      
      const newRental = {
        id: Date.now(),
        category: category.name,
        items: category.items,
        startDate: startDate,
        endDate: endDate,
        status: 'Активна',
        total: calculateTotal(selectedCategory, startDate, endDate)
      }
      
      rentals.active.push(newRental)
      localStorage.setItem('equipmentRentals', JSON.stringify(rentals))
      
      alert('Аренда успешно оформлена!')
      window.location.href = 'index.html'
    })
  }
  
  function calculateTotal(category, start, end) {
    const startDate = new Date(start)
    const endDate = new Date(end)
    const days = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1
    const basePrice = category === 'sound' ? 5000 : category === 'lighting' ? 4000 : 3000
    return days * basePrice
  }
}

// Initialize slider
function initSlider() {
  const slider = document.getElementById('slider')
  if (!slider) return
  
  const slides = slider.querySelectorAll('.slide')
  const prevBtn = document.getElementById('sliderPrev')
  const nextBtn = document.getElementById('sliderNext')
  const dots = slider.querySelectorAll('.dot')
  
  let currentIndex = 0
  
  function goToSlide(index) {
    slides.forEach((slide, i) => {
      slide.classList.toggle('active', i === index)
    })
    
    dots.forEach((dot, i) => {
      dot.classList.toggle('active', i === index)
    })
    
    currentIndex = index
  }
  
  function nextSlide() {
    const next = (currentIndex + 1) % slides.length
    goToSlide(next)
  }
  
  function prevSlide() {
    const prev = (currentIndex - 1 + slides.length) % slides.length
    goToSlide(prev)
  }
  
  if (prevBtn) {
    prevBtn.addEventListener('click', prevSlide)
  }
  
  if (nextBtn) {
    nextBtn.addEventListener('click', nextSlide)
  }
  
  dots.forEach((dot, index) => {
    dot.addEventListener('click', () => goToSlide(index))
  })
  
  // Auto-advance slider
  setInterval(nextSlide, 3000)
}

// Initialize when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initPage)
} else {
  initPage()
}

