// Drawing Lessons Website - Version 4 (HTML/CSS/JS) - Elegant Design

const styles = {
  watercolor: {
    id: 'watercolor',
    name: 'Акварель',
    icon: 'paintbrush.svg',
    color: '#2C3E50',
    description: 'Легкость и прозрачность красок. Идеально для пейзажей и портретов.',
    duration: '2 часа',
    price: 'от 1200₽',
    quote: 'Акварель учит нас видеть красоту в простоте и прозрачности.',
    features: ['Техника мокрым по мокрому', 'Работа с цветом', 'Создание атмосферы']
  },
  graphics: {
    id: 'graphics',
    name: 'Графика',
    icon: 'pen-tool.svg',
    color: '#2C3E50',
    description: 'Точность линий и штриховка. Классическая техника рисунка.',
    duration: '2.5 часа',
    price: 'от 1000₽',
    quote: 'В графике каждая линия имеет значение, каждый штрих — характер.',
    features: ['Работа с карандашом', 'Штриховка и тонировка', 'Композиция']
  },
  oil: {
    id: 'oil',
    name: 'Масло',
    icon: 'layers.svg',
    color: '#2C3E50',
    description: 'Богатство цвета и фактуры. Профессиональная живопись.',
    duration: '3 часа',
    price: 'от 1500₽',
    quote: 'Масляная живопись — это диалог между художником и холстом.',
    features: ['Техника мазка', 'Работа с палитрой', 'Создание объема']
  },
  digital: {
    id: 'digital',
    name: 'Цифровое',
    icon: 'monitor.svg',
    color: '#2C3E50',
    description: 'Современные технологии в искусстве. Графические планшеты и программы.',
    duration: '2.5 часа',
    price: 'от 1300₽',
    quote: 'Цифровое искусство открывает безграничные возможности творчества.',
    features: ['Работа в Photoshop', 'Графические планшеты', 'Цифровая живопись']
  }
}

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

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-elegant">
        <div class="empty-icon-elegant">
          <img src="icons/pen-tool.svg" alt="PenTool" width="48" height="48">
        </div>
        <h3 class="empty-title-elegant">Начните свой творческий путь</h3>
        <p class="empty-text-elegant">
          Запишитесь на первое занятие и откройте для себя мир искусства
        </p>
      </div>
    `
    return
  }
  
  container.innerHTML = lessons.map((lesson, index) => {
    const date = new Date(lesson.date)
    const formattedDate = date.toLocaleDateString('ru-RU', { 
      day: 'numeric', 
      month: 'long',
      year: 'numeric'
    })
    const ratingPercent = (lesson.rating / 5) * 100
    
    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="14" height="14">`
    }).join('')
    
    return `
      <div class="lesson-timeline-item">
        <div class="timeline-marker">
          <div class="marker-dot"></div>
          ${index < lessons.length - 1 ? '<div class="marker-line"></div>' : ''}
        </div>
        <div class="lesson-timeline-content">
          <div class="lesson-timeline-header">
            <div class="lesson-technique-elegant">${lesson.technique}</div>
            <div class="lesson-rating-elegant">
              ${stars}
            </div>
          </div>
          <h3 class="lesson-work-title-elegant">${lesson.workTitle}</h3>
          <div class="lesson-details-elegant">
            <div class="lesson-detail-elegant">
              <img src="icons/user.svg" alt="User" width="14" height="14">
              <span>${lesson.instructor}</span>
            </div>
            <div class="lesson-detail-elegant">
              <img src="icons/calendar.svg" alt="Calendar" width="14" height="14">
              <span>${formattedDate}</span>
            </div>
          </div>
          <div class="lesson-rating-bar">
            <div class="rating-bar-fill" style="width: ${ratingPercent}%"></div>
            <span class="rating-text">Оценка: ${lesson.rating}/5</span>
          </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-elegant')
  dots = document.querySelectorAll('.dot-elegant')
  
  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]
    
    dateInput.addEventListener('change', (e) => {
      selectedDate = e.target.value
      formProgress = 100
      updateProgress()
      const submitBtn = document.getElementById('submit-btn')
      if (submitBtn) submitBtn.disabled = !selectedDate
    })
  }
  
  const form = document.getElementById('enroll-form')
  if (form) {
    form.addEventListener('submit', handleSubmit)
  }
  
  initSlider()
}

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-elegant" 
        data-style="${style.id}"
      >
        <div class="style-icon-wrapper-elegant">
          <div class="style-icon-elegant">
            <img src="icons/${style.icon}" alt="${style.name}" width="40" height="40">
          </div>
        </div>
        <div class="style-content-elegant">
          <h3 class="style-name-elegant">${style.name}</h3>
          <p class="style-description-elegant">${style.description}</p>
          <div class="style-quote-elegant">
            <img src="icons/quote.svg" alt="Quote" width="16" height="16">
            <span>${style.quote}</span>
          </div>
          <div class="style-features-elegant">
            ${style.features.map(feature => `
              <span class="feature-tag-elegant">
                ${feature}
              </span>
            `).join('')}
          </div>
          <div class="style-meta-elegant">
            <div class="meta-item-elegant">
              <img src="icons/clock.svg" alt="Clock" width="14" height="14">
              <span>${style.duration}</span>
            </div>
            <div class="meta-item-elegant">
              <span>${style.price}</span>
            </div>
          </div>
        </div>
      </button>
    `
  }).join('')
  
  const styleCards = document.querySelectorAll('.style-card-elegant')
  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-elegant')
        const check = c.querySelector('.style-check-elegant')
        
        if (c === card) {
          c.classList.add('selected')
          if (check) check.remove()
          c.innerHTML += `
            <div class="style-check-elegant">
              <img src="icons/check-circle.svg" alt="Check" width="28" height="28">
            </div>
          `
        } else {
          if (check) check.remove()
        }
      })
      
      formProgress = 50
      updateProgress()
      showDateSection()
    })
  })
}

function updateProgress() {
  const progressFill = document.getElementById('progress-fill')
  const progressText = document.getElementById('progress-text')
  
  if (progressFill) progressFill.style.width = `${formProgress}%`
  if (progressText) progressText.textContent = `${formProgress}%`
}

function showDateSection() {
  const dateSection = document.getElementById('date-section')
  const submitBtn = document.getElementById('submit-btn')
  
  if (selectedStyle) {
    dateSection.style.display = 'block'
  }
}

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)

