// Formats mapping
const formats = {
  'in-person': { name: 'Лично' },
  'video': { name: 'Видео' }
};

// Topics mapping
const topics = {
  'stress': { name: 'Стресс', color: '#ef4444' },
  'relationships': { name: 'Отношения', color: '#ec4899' },
  'career': { name: 'Карьера', color: '#f59e0b' }
};

// Initialize default sessions if not exists
function initDefaultSessions() {
  const saved = localStorage.getItem('psychologistSessions');
  if (!saved) {
    const defaultSessions = {
      past: [
        {
          id: 1,
          date: '2025-03-15',
          type: 'Лично',
          topic: 'Стресс',
          rating: 5
        },
        {
          id: 2,
          date: '2025-03-10',
          type: 'Видео',
          topic: 'Отношения',
          rating: 4
        },
        {
          id: 3,
          date: '2025-03-05',
          type: 'Лично',
          topic: 'Карьера',
          rating: 5
        }
      ]
    };
    localStorage.setItem('psychologistSessions', JSON.stringify(defaultSessions));
  }
}

// Get sessions from localStorage
function getSessions() {
  const saved = localStorage.getItem('psychologistSessions');
  return saved ? JSON.parse(saved) : { past: [] };
}

// Save sessions to localStorage
function saveSessions(sessions) {
  localStorage.setItem('psychologistSessions', JSON.stringify(sessions));
}

// Format date
function formatDate(dateString) {
  const date = new Date(dateString);
  return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' });
}

// Initialize page based on current page
function initPage() {
  const currentPage = window.location.pathname.split('/').pop();
  
  if (currentPage === 'index.html' || currentPage === '' || currentPage.includes('index')) {
    initSessionsPage();
  } else if (currentPage === 'book.html' || currentPage.includes('book')) {
    initBookingForm();
  }
}

// Initialize sessions page
function initSessionsPage() {
  initDefaultSessions();
  const sessions = getSessions();
  
  // Update stats
  updateStats(sessions);
  
  // Update banner stats
  updateBannerStats(sessions);
  
  // Display sessions
  displaySessions(sessions);
  
  // Update sessions periodically
  setInterval(() => {
    const updatedSessions = getSessions();
    updateStats(updatedSessions);
    updateBannerStats(updatedSessions);
    displaySessions(updatedSessions);
  }, 500);
}

// Update statistics
function updateStats(sessions) {
  const sessionsCount = document.getElementById('sessionsCount');
  const avgRating = document.getElementById('avgRating');
  const progress = document.getElementById('progress');
  
  if (sessionsCount) {
    sessionsCount.textContent = sessions.past.length;
  }
  
  if (avgRating) {
    const ratings = sessions.past.filter(s => s.rating).map(s => s.rating);
    const avg = ratings.length > 0 
      ? (ratings.reduce((a, b) => a + b, 0) / ratings.length).toFixed(1)
      : '0';
    avgRating.textContent = avg;
  }
  
  if (progress) {
    progress.textContent = '85%';
  }
}

// Update banner stats
function updateBannerStats(sessions) {
  const bannerSessionsCount = document.getElementById('bannerSessionsCount');
  const bannerAvgRating = document.getElementById('bannerAvgRating');
  
  if (bannerSessionsCount) {
    bannerSessionsCount.textContent = sessions.past.length;
  }
  
  if (bannerAvgRating) {
    const ratings = sessions.past.filter(s => s.rating).map(s => s.rating);
    const avg = ratings.length > 0 
      ? (ratings.reduce((a, b) => a + b, 0) / ratings.length).toFixed(1)
      : '0';
    bannerAvgRating.textContent = avg;
  }
}

// Display sessions
function displaySessions(sessions) {
  const container = document.getElementById('sessionsContainer');
  if (!container) return;
  
  if (sessions.past.length === 0) {
    container.innerHTML = `
      <div class="empty-state">
        <img src="icons/empty-sessions.svg" alt="" class="empty-icon" width="64" height="64" />
        <p>У вас пока нет завершенных сеансов</p>
      </div>
    `;
    return;
  }
  
  container.innerHTML = sessions.past.map(session => {
    const typeLower = session.type.toLowerCase();
    return `
      <div class="session-card">
        <div class="session-header">
          <div class="session-type-badge" data-type="${typeLower}">${session.type}</div>
          <div class="session-topic-badge">${session.topic}</div>
        </div>
        <div class="session-body">
          <div class="session-detail">
            <img src="icons/detail-calendar.svg" alt="" class="detail-icon" width="20" height="20" />
            <span>${formatDate(session.date)}</span>
          </div>
          <div class="session-detail">
            <img src="icons/detail-type.svg" alt="" class="detail-icon" width="20" height="20" />
            <span>${session.type === 'Лично' ? 'Очная консультация' : 'Онлайн-консультация'}</span>
          </div>
        </div>
        <div class="rating-section">
          <p class="rating-label">Оценка сеанса</p>
          <div class="stars-container">
            ${[1, 2, 3, 4, 5].map(star => `
              <button 
                class="star-btn ${session.rating >= star ? 'filled' : ''}"
                onclick="rateSession(${session.id}, ${star})"
              >
                <img src="icons/star.svg" alt="Оценка ${star}" class="star-icon" width="24" height="24" />
              </button>
            `).join('')}
          </div>
        </div>
      </div>
    `;
  }).join('');
}

// Rate session
function rateSession(sessionId, rating) {
  const sessions = getSessions();
  const session = sessions.past.find(s => s.id === sessionId);
  if (session) {
    session.rating = rating;
    saveSessions(sessions);
    displaySessions(sessions);
    updateStats(sessions);
    updateBannerStats(sessions);
  }
}

// Initialize booking form
function initBookingForm() {
  initDefaultSessions();
  
  let selectedFormat = null;
  let selectedTopic = null;
  let selectedDate = null;
  
  // Initialize formats
  const formatsGrid = document.getElementById('formatsGrid');
  if (formatsGrid) {
    formatsGrid.querySelectorAll('.format-card').forEach(card => {
      card.addEventListener('click', () => {
        formatsGrid.querySelectorAll('.format-card').forEach(c => c.classList.remove('selected'));
        card.classList.add('selected');
        selectedFormat = card.dataset.format;
        updateSubmitButton();
      });
    });
  }
  
  // Initialize topics
  const topicsGrid = document.getElementById('topicsGrid');
  if (topicsGrid) {
    topicsGrid.querySelectorAll('.topic-card').forEach(card => {
      card.addEventListener('click', () => {
        topicsGrid.querySelectorAll('.topic-card').forEach(c => c.classList.remove('selected'));
        card.classList.add('selected');
        selectedTopic = card.dataset.topic;
        updateSubmitButton();
      });
    });
  }
  
  // Initialize dates
  const datesScroll = document.getElementById('datesScroll');
  if (datesScroll) {
    const dates = [];
    for (let i = 0; i < 14; i++) {
      const date = new Date();
      date.setDate(date.getDate() + i);
      dates.push(date.toISOString().split('T')[0]);
    }
    
    datesScroll.innerHTML = dates.map(date => {
      const dateObj = new Date(date);
      const isToday = date === new Date().toISOString().split('T')[0];
      return `
        <button type="button" class="date-button ${isToday ? 'today' : ''}" data-date="${date}">
          <div class="date-day">${dateObj.getDate()}</div>
          <div class="date-weekday">${dateObj.toLocaleDateString('ru-RU', { weekday: 'short' })}</div>
        </button>
      `;
    }).join('');
    
    datesScroll.querySelectorAll('.date-button').forEach(button => {
      button.addEventListener('click', () => {
        datesScroll.querySelectorAll('.date-button').forEach(b => b.classList.remove('selected'));
        button.classList.add('selected');
        selectedDate = button.dataset.date;
        updateSubmitButton();
      });
    });
  }
  
  // Update submit button state
  function updateSubmitButton() {
    const submitBtn = document.getElementById('submitBtn');
    if (submitBtn) {
      submitBtn.disabled = !(selectedFormat && selectedTopic && selectedDate);
    }
  }
  
  // Handle form submission
  const form = document.getElementById('bookingForm');
  if (form) {
    form.addEventListener('submit', (e) => {
      e.preventDefault();
      
      if (selectedFormat && selectedTopic && selectedDate) {
        const sessions = getSessions();
        const formatName = formats[selectedFormat]?.name || selectedFormat;
        const topicName = topics[selectedTopic]?.name || selectedTopic;
        
        const newSession = {
          id: Date.now(),
          date: selectedDate,
          type: formatName,
          topic: topicName,
          rating: null
        };
        
        sessions.past.push(newSession);
        saveSessions(sessions);
        
        // Reset form
        selectedFormat = null;
        selectedTopic = null;
        selectedDate = null;
        
        formatsGrid.querySelectorAll('.format-card').forEach(c => c.classList.remove('selected'));
        topicsGrid.querySelectorAll('.topic-card').forEach(c => c.classList.remove('selected'));
        datesScroll.querySelectorAll('.date-button').forEach(b => b.classList.remove('selected'));
        updateSubmitButton();
        
        // Redirect to sessions page
        window.location.href = 'index.html';
      }
    });
  }
}

// Initialize slider
function initSlider() {
  const slider = document.getElementById('slider');
  if (!slider) return;
  
  const slides = slider.querySelectorAll('.slide');
  const prevBtn = document.getElementById('prevBtn');
  const nextBtn = document.getElementById('nextBtn');
  const dots = document.getElementById('dots');
  
  let currentIndex = 0;
  
  // Create dots
  if (dots) {
    slides.forEach((_, index) => {
      const dot = document.createElement('button');
      dot.className = `dot ${index === 0 ? 'active' : ''}`;
      dot.addEventListener('click', () => goToSlide(index));
      dots.appendChild(dot);
    });
  }
  
  function goToSlide(index) {
    slides.forEach((slide, i) => {
      slide.classList.toggle('active', i === index);
    });
    
    if (dots) {
      dots.querySelectorAll('.dot').forEach((dot, i) => {
        dot.classList.toggle('active', i === index);
      });
    }
    
    currentIndex = index;
  }
  
  function nextSlide() {
    const next = (currentIndex + 1) % slides.length;
    goToSlide(next);
  }
  
  function prevSlide() {
    const prev = (currentIndex - 1 + slides.length) % slides.length;
    goToSlide(prev);
  }
  
  if (prevBtn) {
    prevBtn.addEventListener('click', prevSlide);
  }
  
  if (nextBtn) {
    nextBtn.addEventListener('click', nextSlide);
  }
  
  // Auto-advance slider
  setInterval(nextSlide, 3000);
}

// Initialize when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    initPage();
    initSlider();
  });
} else {
  initPage();
  initSlider();
}

