// Drawing Lessons Website - Version 3 (HTML/CSS/JS) - Creative Design

const styles = {
  watercolor: {
    id: 'watercolor',
    name: 'Акварель',
    icon: 'paintbrush.svg',
    color: '#4A90E2',
    gradient: 'linear-gradient(135deg, #4A90E2 0%, #357ABD 100%)',
    description: 'Легкость и прозрачность красок. Идеально для пейзажей и портретов.',
    duration: '2 часа',
    price: 'от 1200₽',
    features: ['Техника мокрым по мокрому', 'Работа с цветом', 'Создание атмосферы']
  },
  graphics: {
    id: 'graphics',
    name: 'Графика',
    icon: 'pen-tool.svg',
    color: '#2C3E50',
    gradient: 'linear-gradient(135deg, #2C3E50 0%, #1A252F 100%)',
    description: 'Точность линий и штриховка. Классическая техника рисунка.',
    duration: '2.5 часа',
    price: 'от 1000₽',
    features: ['Работа с карандашом', 'Штриховка и тонировка', 'Композиция']
  },
  oil: {
    id: 'oil',
    name: 'Масло',
    icon: 'layers.svg',
    color: '#E74C3C',
    gradient: 'linear-gradient(135deg, #E74C3C 0%, #C0392B 100%)',
    description: 'Богатство цвета и фактуры. Профессиональная живопись.',
    duration: '3 часа',
    price: 'от 1500₽',
    features: ['Техника мазка', 'Работа с палитрой', 'Создание объема']
  },
  digital: {
    id: 'digital',
    name: 'Цифровое',
    icon: 'monitor.svg',
    color: '#9B59B6',
    gradient: 'linear-gradient(135deg, #9B59B6 0%, #8E44AD 100%)',
    description: 'Современные технологии в искусстве. Графические планшеты и программы.',
    duration: '2.5 часа',
    price: 'от 1300₽',
    features: ['Работа в Photoshop', 'Графические планшеты', 'Цифровая живопись']
  }
}

let currentSlide = 0
let slides = []
let dots = []
let slideInterval
let selectedStyle = ''
let selectedDate = ''

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

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

function loadLessons() {
  const saved = localStorage.getItem('drawingLessons')
  let lessons = []
  
  if (saved) {
    try {
      lessons = JSON.parse(saved)
    } catch (e) {
      lessons = []
    }
  } else {
    lessons = [
      {
        id: 1,
        technique: 'Акварельная живопись',
        instructor: 'Мария Иванова',
        date: '2025-04-15',
        rating: 5,
        workTitle: 'Пейзаж с озером'
      },
      {
        id: 2,
        technique: 'Графический рисунок',
        instructor: 'Алексей Петров',
        date: '2025-04-12',
        rating: 4,
        workTitle: 'Портрет в карандаше'
      },
      {
        id: 3,
        technique: 'Масляная живопись',
        instructor: 'Елена Соколова',
        date: '2025-04-10',
        rating: 5,
        workTitle: 'Натюрморт с фруктами'
      }
    ]
    localStorage.setItem('drawingLessons', JSON.stringify(lessons))
  }
  
  renderLessons(lessons)
}

function renderLessons(lessons) {
  const container = document.getElementById('lessons-container')
  if (!container) return
  
  if (lessons.length === 0) {
    container.innerHTML = `
      <div class="empty-creative">
        <div class="empty-palette">
          <img src="icons/palette.svg" alt="Palette" width="64" height="64">
        </div>
        <h3 class="empty-title-creative">Начните свой творческий путь</h3>
        <p class="empty-text-creative">Запишитесь на первое занятие и откройте для себя мир искусства</p>
      </div>
    `
    return
  }
  
  container.innerHTML = lessons.map(lesson => {
    const date = new Date(lesson.date)
    const formattedDate = date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' })
    const progress = lesson.rating > 0 ? 100 : 0
    
    const stars = Array.from({ length: 5 }, (_, i) => {
      const filled = i < lesson.rating
      return `<img src="icons/${filled ? 'star-filled.svg' : 'star.svg'}" alt="Star" width="18" height="18">`
    }).join('')
    
    const gradientMap = {
      'Акварельная живопись': 'var(--gradient-1)',
      'Графический рисунок': 'var(--gradient-2)',
      'Масляная живопись': 'var(--gradient-3)',
      'Цифровое рисование': 'var(--gradient-4)'
    }
    
    const badgeGradient = gradientMap[lesson.technique] || 'var(--gradient-1)'
    
    return `
      <div class="lesson-card-creative">
        <div class="lesson-card-main">
          <div class="lesson-card-header">
            <div class="lesson-technique-badge" style="background: ${badgeGradient}">
              ${lesson.technique}
            </div>
            <div class="lesson-rating">
              ${stars}
            </div>
          </div>
          <h3 class="lesson-work-title">${lesson.workTitle}</h3>
          <div class="lesson-info-grid">
            <div class="lesson-info-item">
              <img src="icons/user.svg" alt="User" width="18" height="18">
              <span>${lesson.instructor}</span>
            </div>
            <div class="lesson-info-item">
              <img src="icons/calendar.svg" alt="Calendar" width="18" height="18">
              <span>${formattedDate}</span>
            </div>
          </div>
        </div>
        <div class="lesson-card-footer">
          <div class="lesson-progress-bar">
            <div class="lesson-progress-fill" style="width: ${progress}%"></div>
          </div>
          <div class="lesson-progress-text">${progress}% завершено</div>
        </div>
      </div>
    `
  }).join('')
}

function updateStats() {
  const saved = localStorage.getItem('drawingLessons')
  let lessons = []
  
  if (saved) {
    try {
      lessons = JSON.parse(saved)
    } catch (e) {
      lessons = []
    }
  }
  
  const totalLessons = lessons.length
  const averageRating = lessons.length > 0
    ? (lessons.reduce((sum, l) => sum + l.rating, 0) / lessons.length).toFixed(1)
    : 0
  const upcomingLessons = lessons.filter(l => new Date(l.date) >= new Date()).length
  const completedLessons = lessons.filter(l => new Date(l.date) < new Date() || l.rating > 0).length
  
  const totalEl = document.getElementById('total-lessons')
  const avgEl = document.getElementById('average-rating')
  const upcomingEl = document.getElementById('upcoming-lessons')
  const completedEl = document.getElementById('completed-lessons')
  
  if (totalEl) totalEl.textContent = totalLessons
  if (avgEl) avgEl.textContent = averageRating
  if (upcomingEl) upcomingEl.textContent = upcomingLessons
  if (completedEl) completedEl.textContent = completedLessons
}

function initSlider() {
  slides = document.querySelectorAll('.slide-creative')
  dots = document.querySelectorAll('.dot-creative')
  
  if (slides.length === 0) return
  
  updateSlider()
  
  slideInterval = setInterval(() => {
    currentSlide = (currentSlide + 1) % slides.length
    updateSlider()
  }, 3000)
}

function updateSlider() {
  slides.forEach((slide, index) => {
    if (index === currentSlide) {
      slide.classList.add('active')
    } else {
      slide.classList.remove('active')
    }
  })
  
  dots.forEach((dot, index) => {
    if (index === currentSlide) {
      dot.classList.add('active')
    } else {
      dot.classList.remove('active')
    }
  })
}

function goToPrevious() {
  if (slides.length === 0) return
  currentSlide = (currentSlide - 1 + slides.length) % slides.length
  updateSlider()
  if (slideInterval) clearInterval(slideInterval)
  slideInterval = setInterval(() => {
    currentSlide = (currentSlide + 1) % slides.length
    updateSlider()
  }, 3000)
}

function goToNext() {
  if (slides.length === 0) return
  currentSlide = (currentSlide + 1) % slides.length
  updateSlider()
  if (slideInterval) clearInterval(slideInterval)
  slideInterval = setInterval(() => {
    currentSlide = (currentSlide + 1) % slides.length
    updateSlider()
  }, 3000)
}

function goToSlide(index) {
  if (slides.length === 0) return
  currentSlide = index
  updateSlider()
  if (slideInterval) clearInterval(slideInterval)
  slideInterval = setInterval(() => {
    currentSlide = (currentSlide + 1) % slides.length
    updateSlider()
  }, 3000)
}

function initEnrollPage() {
  renderStyles()
  
  const dateInput = document.getElementById('date-input')
  if (dateInput) {
    const today = new Date()
    const maxDate = new Date(today.getTime() + 90 * 24 * 60 * 60 * 1000)
    dateInput.min = today.toISOString().split('T')[0]
    dateInput.max = maxDate.toISOString().split('T')[0]
  }
  
  const form = document.getElementById('enroll-form')
  if (form) {
    form.addEventListener('submit', handleSubmit)
  }
}

function renderStyles() {
  const container = document.getElementById('styles-container')
  if (!container) return
  
  container.innerHTML = Object.values(styles).map(style => {
    return `
      <button 
        type="button" 
        class="style-card-creative" 
        data-style="${style.id}"
        style="border-color: ${style.color};"
      >
        <div class="style-icon-wrapper">
          <div 
            class="style-icon-creative"
            style="border-color: ${style.color}; background: rgba(255, 107, 157, 0.1);"
          >
            <img src="icons/${style.icon}" alt="${style.name}" width="48" height="48" style="filter: brightness(0) saturate(100%) invert(30%) sepia(100%) saturate(5000%) hue-rotate(320deg);">
          </div>
        </div>
        <div class="style-content-creative">
          <h3 class="style-name-creative" style="color: var(--text);">${style.name}</h3>
          <p class="style-description-creative" style="color: var(--text-light);">${style.description}</p>
          <div class="style-features-creative">
            ${style.features.map(feature => `
              <span class="feature-tag-creative" style="background: rgba(255, 107, 157, 0.1); color: var(--primary); border-color: ${style.color};">
                ${feature}
              </span>
            `).join('')}
          </div>
          <div class="style-meta-creative">
            <div class="meta-item-creative">
              <img src="icons/clock.svg" alt="Clock" width="16" height="16">
              <span>${style.duration}</span>
            </div>
            <div class="meta-item-creative">
              <span>${style.price}</span>
            </div>
          </div>
        </div>
      </button>
    `
  }).join('')
  
  const styleCards = document.querySelectorAll('.style-card-creative')
  styleCards.forEach(card => {
    card.addEventListener('click', () => {
      const styleId = card.dataset.style
      selectedStyle = styleId
      
      styleCards.forEach(c => {
        c.classList.remove('selected')
        const icon = c.querySelector('.style-icon-creative')
        const name = c.querySelector('.style-name-creative')
        const desc = c.querySelector('.style-description-creative')
        const features = c.querySelectorAll('.feature-tag-creative')
        
        if (c === card) {
          const style = styles[styleId]
          c.style.background = style.gradient
          c.style.borderColor = style.color
          c.style.color = 'white'
          icon.style.borderColor = 'rgba(255, 255, 255, 0.3)'
          icon.style.background = 'rgba(255, 255, 255, 0.2)'
          icon.querySelector('img').style.filter = 'brightness(0) invert(1)'
          name.style.color = 'white'
          desc.style.color = 'rgba(255, 255, 255, 0.9)'
          features.forEach(f => {
            f.style.background = 'rgba(255, 255, 255, 0.2)'
            f.style.color = 'white'
          })
          
          c.innerHTML += `
            <div class="style-check-creative">
              <img src="icons/check-circle.svg" alt="Check" width="32" height="32">
            </div>
          `
        } else {
          const style = styles[c.dataset.style]
          c.style.background = 'white'
          c.style.borderColor = style.color
          c.style.color = 'var(--text)'
          icon.style.borderColor = style.color
          icon.style.background = 'rgba(255, 107, 157, 0.1)'
          icon.querySelector('img').style.filter = 'brightness(0) saturate(100%) invert(30%) sepia(100%) saturate(5000%) hue-rotate(320deg)'
          name.style.color = 'var(--text)'
          desc.style.color = 'var(--text-light)'
          features.forEach(f => {
            f.style.background = 'rgba(255, 107, 157, 0.1)'
            f.style.color = 'var(--primary)'
          })
          
          const check = c.querySelector('.style-check-creative')
          if (check) check.remove()
        }
      })
      
      updateProgress()
      showDateSection()
    })
  })
}

function updateProgress() {
  const step1 = document.getElementById('step-1')
  const step2 = document.getElementById('step-2')
  const step3 = document.getElementById('step-3')
  const progress1 = document.getElementById('progress-1')
  const progress2 = document.getElementById('progress-2')
  
  if (selectedStyle) {
    step1.classList.add('active')
    if (progress1) progress1.style.width = '100%'
  } else {
    step1.classList.remove('active')
    if (progress1) progress1.style.width = '0%'
  }
  
  if (selectedDate) {
    step2.classList.add('active')
    if (progress2) progress2.style.width = '100%'
    step3.classList.add('active')
  } else {
    step2.classList.remove('active')
    if (progress2) progress2.style.width = '0%'
    step3.classList.remove('active')
  }
}

function showDateSection() {
  const dateSection = document.getElementById('date-section')
  const submitBtn = document.getElementById('submit-btn')
  
  if (selectedStyle) {
    dateSection.style.display = 'block'
    const dateInput = document.getElementById('date-input')
    if (dateInput) {
      dateInput.addEventListener('change', (e) => {
        selectedDate = e.target.value
        updateProgress()
        if (submitBtn) submitBtn.disabled = !selectedDate
      })
    }
  }
}

function handleSubmit(e) {
  e.preventDefault()
  if (!selectedStyle || !selectedDate) return
  
  const saved = localStorage.getItem('drawingLessons')
  const lessons = saved ? JSON.parse(saved) : []
  
  const styleData = styles[selectedStyle]
  
  const newLesson = {
    id: Date.now(),
    technique: styleData.name,
    instructor: 'Преподаватель',
    date: selectedDate,
    rating: 0,
    workTitle: `Работа в технике ${styleData.name.toLowerCase()}`
  }
  
  lessons.push(newLesson)
  localStorage.setItem('drawingLessons', JSON.stringify(lessons))
  
  const successMessage = document.getElementById('success-message')
  const submitBtn = document.getElementById('submit-btn')
  
  if (successMessage) successMessage.style.display = 'flex'
  if (submitBtn) submitBtn.style.display = 'none'
  
  setTimeout(() => {
    window.location.href = 'index.html'
  }, 2000)
}

document.addEventListener('DOMContentLoaded', initPage)

