// EGE Preparation Website - Version 4 (HTML/CSS/JS) - Academic Design

const subjects = {
  math: {
    id: 'math',
    name: 'Математика',
    icon: 'calculator.svg',
    description: 'Профильная математика с углубленным изучением всех разделов',
    duration: '120 часов',
    price: 'от 15000₽'
  },
  russian: {
    id: 'russian',
    name: 'Русский язык',
    icon: 'book-open.svg',
    description: 'Подготовка к сочинению и тестовой части',
    duration: '100 часов',
    price: 'от 12000₽'
  },
  physics: {
    id: 'physics',
    name: 'Физика',
    icon: 'zap.svg',
    description: 'Механика, термодинамика, оптика и квантовая физика',
    duration: '140 часов',
    price: 'от 18000₽'
  },
  informatics: {
    id: 'informatics',
    name: 'Информатика',
    icon: 'code.svg',
    description: 'Программирование, алгоритмы и структуры данных',
    duration: '130 часов',
    price: 'от 16000₽'
  }
}

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

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

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

function loadCourses() {
  const saved = localStorage.getItem('egeCourses')
  let courses = []
  
  if (saved) {
    try {
      courses = JSON.parse(saved)
    } catch (e) {
      courses = []
    }
  } else {
    courses = [
      {
        id: 1,
        subject: 'Математика',
        instructor: 'Александр Петров',
        progress: 75,
        testResults: [
          { name: 'Пробный ЕГЭ №1', score: 82, maxScore: 100, date: '2025-04-10' },
          { name: 'Пробный ЕГЭ №2', score: 88, maxScore: 100, date: '2025-04-17' }
        ]
      },
      {
        id: 2,
        subject: 'Русский язык',
        instructor: 'Елена Соколова',
        progress: 60,
        testResults: [
          { name: 'Пробный ЕГЭ №1', score: 90, maxScore: 100, date: '2025-04-12' }
        ]
      },
      {
        id: 3,
        subject: 'Физика',
        instructor: 'Дмитрий Новиков',
        progress: 45,
        testResults: []
      }
    ]
    localStorage.setItem('egeCourses', JSON.stringify(courses))
  }
  
  renderCourses(courses)
}

function renderCourses(courses) {
  const container = document.getElementById('courses-container')
  if (!container) return
  
  if (courses.length === 0) {
    container.innerHTML = `
      <div class="empty-panel-classic">
        <div class="empty-icon-classic">
          <img src="icons/book-open.svg" alt="BookOpen" width="40" height="40">
        </div>
        <h3 class="empty-title-classic">Начните обучение</h3>
        <p class="empty-text-classic">Запишитесь на первый курс и начните подготовку к ЕГЭ</p>
      </div>
    `
    return
  }
  
  container.innerHTML = courses.map(course => {
    const date = new Date()
    const formattedDate = date.toLocaleDateString('ru-RU', { 
      day: 'numeric', 
      month: 'long',
      year: 'numeric'
    })
    
    return `
      <div class="course-panel-classic">
        <div class="panel-header-classic">
          <div class="panel-subject-classic">${course.subject}</div>
          <div class="panel-progress-classic">${course.progress}%</div>
        </div>
        <div class="panel-body-classic">
          <div class="panel-instructor-classic">
            <img src="icons/user.svg" alt="User" width="14" height="14">
            <span>${course.instructor}</span>
          </div>
          <div class="panel-progress-track-classic">
            <div class="panel-progress-fill-classic" style="width: ${course.progress}%"></div>
          </div>
        </div>
        ${course.testResults.length > 0 ? `
          <div class="panel-tests-classic">
            <div class="tests-label-classic">
              <img src="icons/file-text.svg" alt="FileText" width="14" height="14">
              <span>Результаты тестов</span>
            </div>
            <div class="tests-stack-classic">
              ${course.testResults.map(test => {
                const testDate = new Date(test.date)
                const formattedTestDate = testDate.toLocaleDateString('ru-RU', { 
                  day: 'numeric', 
                  month: 'short'
                })
                
                return `
                  <div class="test-panel-classic">
                    <div class="test-info-classic">
                      <div class="test-name-classic">${test.name}</div>
                      <div class="test-date-classic">
                        <img src="icons/calendar.svg" alt="Calendar" width="12" height="12">
                        ${formattedTestDate}
                      </div>
                    </div>
                    <div class="test-score-classic">
                      <span class="score-main-classic">${test.score}</span>
                      <span class="score-separator-classic">/</span>
                      <span class="score-max-classic">${test.maxScore}</span>
                    </div>
                  </div>
                `
              }).join('')}
            </div>
          </div>
        ` : ''}
        <div class="panel-footer-classic">
          <span class="panel-action-classic">
            Подробнее
            <img src="icons/chevron-right.svg" alt="Chevron" width="14" height="14">
          </span>
        </div>
      </div>
    `
  }).join('')
}

function updateStats() {
  const saved = localStorage.getItem('egeCourses')
  let courses = []
  
  if (saved) {
    try {
      courses = JSON.parse(saved)
    } catch (e) {
      courses = []
    }
  }
  
  const totalCourses = courses.length
  const totalProgress = courses.length > 0
    ? Math.round(courses.reduce((sum, c) => sum + c.progress, 0) / courses.length)
    : 0
  
  const allTests = courses.flatMap(c => c.testResults)
  const averageScore = allTests.length > 0
    ? Math.round(allTests.reduce((sum, t) => sum + (t.score / t.maxScore) * 100, 0) / allTests.length)
    : 0
  
  const totalCoursesEl = document.getElementById('total-courses')
  const totalProgressEl = document.getElementById('total-progress')
  const averageScoreEl = document.getElementById('average-score')
  const totalTestsEl = document.getElementById('total-tests')
  const totalCoursesCountEl = document.getElementById('total-courses-count')
  const totalProgressTextEl = document.getElementById('total-progress-text')
  
  if (totalCoursesEl) totalCoursesEl.textContent = totalCourses
  if (totalProgressEl) totalProgressEl.textContent = totalProgress + '%'
  if (averageScoreEl) averageScoreEl.textContent = averageScore || 0
  if (totalTestsEl) totalTestsEl.textContent = allTests.length
  if (totalCoursesCountEl) totalCoursesCountEl.textContent = totalCourses
  if (totalProgressTextEl) totalProgressTextEl.textContent = totalProgress
}

function initSlider() {
  slides = document.querySelectorAll('.slide')
  dots = document.querySelectorAll('.dot')
  
  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() {
  renderSubjects()
  
  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
      const submitBtn = document.getElementById('submit-btn')
      if (submitBtn) submitBtn.disabled = !selectedSubject || !selectedDate
    })
  }
  
  const form = document.getElementById('enroll-form')
  if (form) {
    form.addEventListener('submit', handleSubmit)
  }
}

function renderSubjects() {
  const container = document.getElementById('subjects-container')
  if (!container) return
  
  container.innerHTML = Object.values(subjects).map(subject => {
    return `
      <button 
        type="button" 
        class="subject-item-classic" 
        data-subject="${subject.id}"
      >
        <div class="subject-icon-classic">
          <img src="icons/${subject.icon}" alt="${subject.name}" width="20" height="20">
        </div>
        <div class="subject-info-classic">
          <h3 class="subject-name-classic">${subject.name}</h3>
          <p class="subject-description-classic">${subject.description}</p>
          <div class="subject-details-classic">
            <span class="detail-item-classic">
              <img src="icons/clock.svg" alt="Clock" width="12" height="12">
              ${subject.duration}
            </span>
            <span class="detail-item-classic price-classic">${subject.price}</span>
          </div>
        </div>
      </button>
    `
  }).join('')
  
  const subjectCards = document.querySelectorAll('.subject-item-classic')
  subjectCards.forEach(card => {
    card.addEventListener('click', () => {
      const subjectId = card.dataset.subject
      selectedSubject = subjectId
      
      subjectCards.forEach(c => {
        c.classList.remove('selected')
        if (c === card) {
          c.classList.add('selected')
          c.innerHTML += `
            <div class="subject-check-classic">
              <img src="icons/check-circle.svg" alt="Check" width="20" height="20">
            </div>
          `
        } else {
          const check = c.querySelector('.subject-check-classic')
          if (check) check.remove()
        }
      })
      
      const dateStep = document.getElementById('date-step')
      const submitBtn = document.getElementById('submit-btn')
      
      if (dateStep) dateStep.style.display = 'flex'
      if (submitBtn) submitBtn.disabled = !selectedDate
    })
  })
}

function handleSubmit(e) {
  e.preventDefault()
  if (!selectedSubject || !selectedDate) return
  
  const saved = localStorage.getItem('egeCourses')
  const courses = saved ? JSON.parse(saved) : []
  
  const subjectData = subjects[selectedSubject]
  
  const newCourse = {
    id: Date.now(),
    subject: subjectData.name,
    instructor: 'Преподаватель',
    progress: 0,
    testResults: []
  }
  
  courses.push(newCourse)
  localStorage.setItem('egeCourses', JSON.stringify(courses))
  
  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)

