// Slider functionality
let currentSlide = 0
const slides = document.querySelectorAll('.slide-hub')
const dots = document.querySelectorAll('.dot-hub')
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()
  renderActivity()
}

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-list')
  if (!container) return
  
  if (courses.length === 0) {
    container.innerHTML = `
      <div class="empty-dashboard">
        <img src="icons/book-open.svg" alt="Empty" style="width: 64px; height: 64px; opacity: 0.5; margin-bottom: 1.5rem;">
        <h2 class="empty-title-dashboard">Нет курсов</h2>
        <p class="empty-text-dashboard">Начните обучение с выбора курса</p>
        <button class="empty-button-dashboard" onclick="window.location.href='enroll.html'">Записаться</button>
      </div>
    `
    return
  }
  
  const getModuleColor = (module) => {
    if (module.includes('SMM')) return 'var(--accent-pink)'
    if (module.includes('Email')) return 'var(--accent-cyan)'
    if (module.includes('Аналитика')) return 'var(--accent-green)'
    return 'var(--accent-purple)'
  }
  
  container.innerHTML = courses.map(course => {
    const color = getModuleColor(course.module)
    
    return `
      <div class="course-widget-dashboard" style="border-left-color: ${color};" onclick="window.location.href='#'">
        <div class="course-header-widget-dashboard">
          <div class="course-icon-widget-dashboard" style="background: ${color}20; color: ${color};">
            <img src="icons/book-open.svg" alt="Course" style="width: 24px; height: 24px; filter: brightness(0) saturate(100%) invert(1);">
          </div>
          <div class="course-info-widget-dashboard">
            <h4 class="course-name-widget-dashboard">${course.module}</h4>
            <div class="course-meta-widget-dashboard">
              <span class="meta-badge-dashboard">
                <img src="icons/user.svg" alt="User" style="width: 14px; height: 14px;">
                ${course.mentor}
              </span>
              ${course.certificate ? `
                <span class="meta-badge-dashboard badge-cert-dashboard">
                  <img src="icons/award.svg" alt="Award" style="width: 14px; height: 14px;">
                  Сертификат
                </span>
              ` : ''}
              ${course.grade ? `
                <span class="meta-badge-dashboard badge-rating-dashboard">
                  <img src="icons/star.svg" alt="Star" style="width: 14px; height: 14px;">
                  ${course.grade}
                </span>
              ` : ''}
            </div>
          </div>
          <div class="course-id-dashboard">#${course.id}</div>
        </div>
      </div>
    `
  }).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-grid')
  if (!container) return
  
  container.innerHTML = `
    <div class="stat-widget-dashboard">
      <div class="stat-value-dashboard">${stats.total}</div>
      <div class="stat-label-dashboard">Курсов</div>
      <div class="stat-trend-dashboard trend-up">
        <img src="icons/trending-up.svg" alt="Trend" style="width: 16px; height: 16px;">
        <span>+2</span>
      </div>
    </div>
    <div class="stat-widget-dashboard">
      <div class="stat-value-dashboard">${stats.certificates}</div>
      <div class="stat-label-dashboard">Сертификатов</div>
      <div class="stat-trend-dashboard trend-up">
        <img src="icons/trending-up.svg" alt="Trend" style="width: 16px; height: 16px;">
        <span>+1</span>
      </div>
    </div>
    <div class="stat-widget-dashboard">
      <div class="stat-value-dashboard">${stats.mentors}</div>
      <div class="stat-label-dashboard">Наставников</div>
    </div>
    <div class="stat-widget-dashboard">
      <div class="stat-value-dashboard">${stats.avgGrade}</div>
      <div class="stat-label-dashboard">Средний балл</div>
      <div class="stat-trend-dashboard trend-up">
        <img src="icons/trending-up.svg" alt="Trend" style="width: 16px; height: 16px;">
        <span>+0.3</span>
      </div>
    </div>
  `
}

function renderActivity() {
  const saved = localStorage.getItem('marketingCourses')
  let courses = []
  
  if (saved) {
    try {
      courses = JSON.parse(saved)
    } catch (e) {
      courses = []
    }
  }
  
  const container = document.getElementById('activity-list')
  if (!container) return
  
  const getModuleColor = (module) => {
    if (module.includes('SMM')) return 'var(--accent-pink)'
    if (module.includes('Email')) return 'var(--accent-cyan)'
    if (module.includes('Аналитика')) return 'var(--accent-green)'
    return 'var(--accent-purple)'
  }
  
  container.innerHTML = courses.slice(0, 3).map((course, index) => {
    const color = getModuleColor(course.module)
    const timeLabels = ['Сегодня', 'Вчера', '2 дня назад']
    
    return `
      <div class="activity-item-dashboard" style="border-left-color: ${color};">
        <div class="activity-dot-dashboard" style="background: ${color};"></div>
        <div class="activity-content-dashboard">
          <p class="activity-text-dashboard">${course.module}</p>
          <span class="activity-time-dashboard">${timeLabels[index] || 'Недавно'}</span>
        </div>
      </div>
    `
  }).join('')
}

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

const directions = [
  { 
    id: 'smm', 
    name: 'SMM', 
    icon: 'share-2',
    color: 'var(--accent-pink)',
    description: 'Социальные сети и контент-маркетинг. Научитесь создавать вирусный контент и управлять сообществами.',
    features: ['Instagram', 'TikTok', 'Facebook', 'YouTube']
  },
  { 
    id: 'email', 
    name: 'Email-маркетинг', 
    icon: 'mail',
    color: 'var(--accent-cyan)',
    description: 'Эффективные email-кампании и автоматизация. Повышайте конверсию через email-рассылки.',
    features: ['Автоматизация', 'A/B тестирование', 'Сегментация', 'Аналитика']
  },
  { 
    id: 'analytics', 
    name: 'Аналитика', 
    icon: 'bar-chart-3',
    color: 'var(--accent-green)',
    description: 'Работа с данными и метриками. Принимайте решения на основе аналитики и отчетов.',
    features: ['Google Analytics', 'Яндекс.Метрика', 'Дашборды', 'Отчеты']
  },
  { 
    id: 'context', 
    name: 'Контекстная реклама', 
    icon: 'megaphone',
    color: 'var(--accent-purple)',
    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-card-dashboard" 
        data-direction="${direction.id}"
        style="border-color: var(--border); background: var(--bg-card);"
        onclick="selectDirection('${direction.id}')"
      >
        <div class="direction-icon-dashboard" style="background: ${direction.color}20; color: ${direction.color};">
          <img src="icons/${direction.icon}.svg" alt="${direction.name}" style="width: 28px; height: 28px;">
        </div>
        <h3 class="direction-name-dashboard" style="color: ${direction.color};">${direction.name}</h3>
        <p class="direction-desc-dashboard">${direction.description}</p>
        <div class="direction-features-dashboard">
          ${direction.features.map(feature => `
            <span class="feature-badge-dashboard" style="background: ${direction.color}20; color: ${direction.color}; border-color: ${direction.color}40;">
              ${feature}
            </span>
          `).join('')}
        </div>
      </button>
    `
  }).join('')
}

let selectedDirection = ''
let selectedDate = ''

function selectDirection(id) {
  selectedDirection = id
  
  // Update UI
  document.querySelectorAll('.direction-card-dashboard').forEach(card => {
    const directionId = card.getAttribute('data-direction')
    const direction = directions.find(d => d.id === directionId)
    
    if (directionId === id) {
      card.classList.add('selected')
      card.style.borderColor = direction.color
      card.style.backgroundColor = `${direction.color}15`
      
      // Add check indicator
      if (!card.querySelector('.check-indicator-dashboard')) {
        const check = document.createElement('div')
        check.className = 'check-indicator-dashboard'
        check.style.color = direction.color
        check.innerHTML = `<img src="icons/check-circle.svg" alt="Check" style="width: 28px; height: 28px; filter: brightness(0) saturate(100%) invert(1);">`
        card.appendChild(check)
      }
    } else {
      card.classList.remove('selected')
      card.style.borderColor = 'var(--border)'
      card.style.backgroundColor = 'var(--bg-card)'
      
      const check = card.querySelector('.check-indicator-dashboard')
      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'
  }
}

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-dashboard">
        <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)

