// Slider functionality
let currentSlide = 0
const slides = document.querySelectorAll('.slide-academy')
const dots = document.querySelectorAll('.dot-academy')
const totalSlides = slides.length

function goToSlide(index) {
  if (slides.length === 0) return
  
  slides[currentSlide]?.classList.remove('active')
  dots[currentSlide]?.classList.remove('active')
  
  currentSlide = index
  if (currentSlide >= totalSlides) currentSlide = 0
  if (currentSlide < 0) currentSlide = totalSlides - 1
  
  slides[currentSlide]?.classList.add('active')
  dots[currentSlide]?.classList.add('active')
}

function goToNext() {
  goToSlide(currentSlide + 1)
}

function goToPrevious() {
  goToSlide(currentSlide - 1)
}

// Auto-slide
if (slides.length > 0) {
  setInterval(() => {
    goToNext()
  }, 3000)
  
  goToSlide(0)
}

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

// Index page functions
function initIndexPage() {
  loadCourses()
  updateStats()
}

function loadCourses() {
  const saved = localStorage.getItem('marketingCourses')
  let courses = []
  
  if (saved) {
    try {
      courses = JSON.parse(saved)
    } catch (e) {
      courses = []
    }
  } else {
    courses = [
      {
        id: 1,
        module: 'SMM для бизнеса',
        mentor: 'Анна Петрова',
        certificate: true,
        grade: 4.8
      },
      {
        id: 2,
        module: 'Email-маркетинг',
        mentor: 'Иван Сидоров',
        certificate: false,
        grade: null
      },
      {
        id: 3,
        module: 'Аналитика данных',
        mentor: 'Мария Козлова',
        certificate: true,
        grade: 5.0
      }
    ]
    localStorage.setItem('marketingCourses', JSON.stringify(courses))
  }
  
  renderCourses(courses)
}

function renderCourses(courses) {
  const container = document.getElementById('courses-section')
  if (!container) return
  
  if (courses.length === 0) {
    container.innerHTML = `
      <div class="empty-editorial">
        <div class="empty-icon-editorial">
          <img src="icons/book-open.svg" alt="Empty" style="width: 48px; height: 48px; opacity: 0.5;">
        </div>
        <h2 class="empty-title-editorial">Нет курсов</h2>
        <p class="empty-text-editorial">Начните обучение с выбора программы</p>
        <button class="empty-button-editorial" onclick="window.location.href='enroll.html'">Записаться</button>
      </div>
    `
    return
  }
  
  container.innerHTML = courses.map(course => {
    return `
      <article class="course-article-editorial" onclick="window.location.href='#'">
        <div class="article-header-editorial">
          <div class="article-number-editorial">0${course.id}</div>
          <div class="article-meta-editorial">
            <span class="meta-tag-editorial">
              <img src="icons/user.svg" alt="User" style="width: 14px; height: 14px;">
              ${course.mentor}
            </span>
            ${course.certificate ? `
              <span class="meta-tag-editorial tag-cert-editorial">
                <img src="icons/award.svg" alt="Award" style="width: 14px; height: 14px;">
                Сертификат
              </span>
            ` : ''}
            ${course.grade ? `
              <span class="meta-tag-editorial tag-rating-editorial">
                <img src="icons/star.svg" alt="Star" style="width: 14px; height: 14px;">
                ${course.grade}
              </span>
            ` : ''}
          </div>
        </div>
        <h2 class="article-title-editorial">${course.module}</h2>
        <div class="article-divider-editorial"></div>
      </article>
    `
  }).join('')
}

function updateStats() {
  const saved = localStorage.getItem('marketingCourses')
  let courses = []
  
  if (saved) {
    try {
      courses = JSON.parse(saved)
    } catch (e) {
      courses = []
    }
  }
  
  const stats = {
    total: courses.length,
    certificates: courses.filter(c => c.certificate).length,
    mentors: new Set(courses.map(c => c.mentor)).size,
    avgGrade: courses.filter(c => c.grade).length > 0 
      ? (courses.filter(c => c.grade).reduce((sum, c) => sum + c.grade, 0) / courses.filter(c => c.grade).length).toFixed(1)
      : '0.0'
  }
  
  const container = document.getElementById('stats-list')
  if (!container) return
  
  container.innerHTML = `
    <div class="stat-item-editorial">
      <div class="stat-number-editorial">${stats.total}</div>
      <div class="stat-label-editorial">Курсов</div>
    </div>
    <div class="stat-item-editorial">
      <div class="stat-number-editorial">${stats.certificates}</div>
      <div class="stat-label-editorial">Сертификатов</div>
    </div>
    <div class="stat-item-editorial">
      <div class="stat-number-editorial">${stats.mentors}</div>
      <div class="stat-label-editorial">Наставников</div>
    </div>
    <div class="stat-item-editorial">
      <div class="stat-number-editorial">${stats.avgGrade}</div>
      <div class="stat-label-editorial">Средний балл</div>
    </div>
  `
}

// Enroll page functions
function initEnrollPage() {
  renderDirections()
  setupForm()
}

const directions = [
  { 
    id: 'smm', 
    name: 'SMM', 
    icon: 'share-2',
    description: 'Социальные сети и контент-маркетинг. Профессиональное продвижение брендов в цифровой среде.',
    features: ['Instagram', 'TikTok', 'Facebook', 'YouTube']
  },
  { 
    id: 'email', 
    name: 'Email-маркетинг', 
    icon: 'mail',
    description: 'Эффективные email-кампании и автоматизация. Повышение конверсии через персонализированные рассылки.',
    features: ['Автоматизация', 'A/B тестирование', 'Сегментация', 'Аналитика']
  },
  { 
    id: 'analytics', 
    name: 'Аналитика', 
    icon: 'bar-chart-3',
    description: 'Работа с данными и метриками. Принятие решений на основе глубокой аналитики и отчетов.',
    features: ['Google Analytics', 'Яндекс.Метрика', 'Дашборды', 'Отчеты']
  },
  { 
    id: 'context', 
    name: 'Контекстная реклама', 
    icon: 'megaphone',
    description: 'Яндекс.Директ и Google Ads. Настройка и оптимизация рекламных кампаний для максимальной эффективности.',
    features: ['Яндекс.Директ', 'Google Ads', 'Ретаргетинг', 'Оптимизация']
  }
]

function renderDirections() {
  const container = document.getElementById('directions-container')
  if (!container) return
  
  container.innerHTML = directions.map((direction, index) => {
    return `
      <button 
        type="button" 
        class="direction-item-editorial" 
        data-direction="${direction.id}"
        onclick="selectDirection('${direction.id}')"
      >
        <div class="direction-icon-wrapper-editorial">
          <img src="icons/${direction.icon}.svg" alt="${direction.name}" style="width: 24px; height: 24px;">
        </div>
        <div class="direction-content-editorial">
          <h3 class="direction-name-editorial">${direction.name}</h3>
          <p class="direction-desc-editorial">${direction.description}</p>
          <div class="direction-features-editorial">
            ${direction.features.map(feature => `
              <span class="feature-tag-editorial">${feature}</span>
            `).join('')}
          </div>
        </div>
      </button>
    `
  }).join('')
}

let selectedDirection = ''
let selectedDate = ''

function selectDirection(id) {
  selectedDirection = id
  
  // Update UI
  document.querySelectorAll('.direction-item-editorial').forEach(item => {
    const directionId = item.getAttribute('data-direction')
    
    if (directionId === id) {
      item.classList.add('selected')
      
      // Add check mark
      if (!item.querySelector('.check-mark-editorial')) {
        const check = document.createElement('div')
        check.className = 'check-mark-editorial'
        check.innerHTML = `<img src="icons/check-circle.svg" alt="Check" style="width: 24px; height: 24px;">`
        item.appendChild(check)
      }
    } else {
      item.classList.remove('selected')
      const check = item.querySelector('.check-mark-editorial')
      if (check) check.remove()
    }
  })
  
  // Show date section
  const dateSection = document.getElementById('date-section')
  if (dateSection) {
    dateSection.style.display = 'flex'
    dateSection.style.opacity = '1'
    dateSection.style.height = 'auto'
  }
  
  updateSubmitButton()
}

function setupForm() {
  const dateInput = document.getElementById('date-input')
  if (dateInput) {
    const today = new Date()
    const maxDate = new Date(today.getTime() + 180 * 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
      updateSubmitButton()
    })
  }
}

function updateSubmitButton() {
  const button = document.getElementById('submit-btn')
  if (button) {
    button.disabled = !selectedDirection || !selectedDate
  }
}

function handleSubmit(e) {
  if (e) e.preventDefault()
  
  if (!selectedDirection || !selectedDate) return
  
  const saved = localStorage.getItem('marketingCourses')
  const courses = saved ? JSON.parse(saved) : []
  
  const directionData = directions.find(d => d.id === selectedDirection)
  
  const newCourse = {
    id: Date.now(),
    module: directionData.name,
    mentor: 'Преподаватель будет назначен',
    certificate: false,
    grade: null
  }
  
  courses.push(newCourse)
  localStorage.setItem('marketingCourses', JSON.stringify(courses))
  
  // Show success
  const form = document.getElementById('enroll-form')
  if (form) {
    form.innerHTML = `
      <div class="success-editorial">
        <img src="icons/check-circle.svg" alt="Success" style="width: 32px; height: 32px;">
        <span>Запись успешно оформлена!</span>
      </div>
    `
    
    setTimeout(() => {
      window.location.href = 'index.html'
    }, 2000)
  }
}

// Initialize on load
document.addEventListener('DOMContentLoaded', initPage)

