// Carousel Functionality
class Carousel {
  constructor() {
    this.slides = document.querySelectorAll('.carousel-slide');
    this.currentSlide = 0;
    this.slideCount = this.slides.length;
    this.autoPlayInterval = null;
    this.init();
  }

  init() {
    this.createDots();
    this.setupEventListeners();
    this.startAutoPlay();
  }

  createDots() {
    const dotsContainer = document.getElementById('carouselDots');
    for (let i = 0; i < this.slideCount; i++) {
      const dot = document.createElement('div');
      dot.className = `carousel-dot ${i === 0 ? 'active' : ''}`;
      dot.addEventListener('click', () => this.goToSlide(i));
      dotsContainer.appendChild(dot);
    }
  }

  setupEventListeners() {
    document.getElementById('prevBtn').addEventListener('click', () => this.prevSlide());
    document.getElementById('nextBtn').addEventListener('click', () => this.nextSlide());
  }

  showSlide(index) {
    // Remove active class from all slides and dots
    this.slides.forEach(slide => slide.classList.remove('active'));
    document.querySelectorAll('.carousel-dot').forEach(dot => dot.classList.remove('active'));

    // Add active class to current slide and dot
    this.slides[index].classList.add('active');
    document.querySelectorAll('.carousel-dot')[index].classList.add('active');
  }

  nextSlide() {
    this.currentSlide = (this.currentSlide + 1) % this.slideCount;
    this.showSlide(this.currentSlide);
    this.resetAutoPlay();
  }

  prevSlide() {
    this.currentSlide = (this.currentSlide - 1 + this.slideCount) % this.slideCount;
    this.showSlide(this.currentSlide);
    this.resetAutoPlay();
  }

  goToSlide(index) {
    this.currentSlide = index;
    this.showSlide(this.currentSlide);
    this.resetAutoPlay();
  }

  startAutoPlay() {
    this.autoPlayInterval = setInterval(() => this.nextSlide(), 5000);
  }

  resetAutoPlay() {
    clearInterval(this.autoPlayInterval);
    this.startAutoPlay();
  }
}

// Navigation Hamburger Menu
class Navigation {
  constructor() {
    this.hamburger = document.getElementById('hamburger');
    this.navLinks = document.getElementById('navLinks');
    this.navButtons = document.getElementById('navButtons');
    this.init();
  }

  init() {
    this.hamburger.addEventListener('click', (e) => {
      e.stopPropagation();
      this.toggleMenu();
    });

    const navItems = this.navLinks.querySelectorAll('a');
    navItems.forEach(item => {
      item.addEventListener('click', () => this.closeMenu());
    });

    document.addEventListener('click', (e) => this.handleClickOutside(e));
  }

  toggleMenu() {
    this.hamburger.classList.toggle('active');
    this.navLinks.classList.toggle('active');
    this.navButtons.classList.toggle('active');
  }

  closeMenu() {
    this.hamburger.classList.remove('active');
    this.navLinks.classList.remove('active');
    this.navButtons.classList.remove('active');
  }

  handleClickOutside(e) {
    const isClickInsideNav = e.target.closest('.nav-container');
    const isClickInsideModal = e.target.closest('.modal');
    
    if (!isClickInsideNav && !isClickInsideModal) {
      this.closeMenu();
    }
  }
}

// Modal Management
class ModalManager {
  constructor() {
    this.loginModal = document.getElementById('loginModal');
    this.registerModal = document.getElementById('registerModal');
    this.init();
  }

  init() {
    // Login button
    document.getElementById('loginBtn').addEventListener('click', () => this.openLogin());
    document.getElementById('registerBtn').addEventListener('click', () => this.openRegister());

    // Close buttons
    document.getElementById('loginClose').addEventListener('click', () => this.closeLogin());
    document.getElementById('registerClose').addEventListener('click', () => this.closeRegister());

    // Switch between forms
    document.getElementById('switchToRegister').addEventListener('click', (e) => {
      e.preventDefault();
      this.closeLogin();
      this.openRegister();
    });

    document.getElementById('switchToLogin').addEventListener('click', (e) => {
      e.preventDefault();
      this.closeRegister();
      this.openLogin();
    });

    // Close on outside click
    window.addEventListener('click', (e) => {
      if (e.target === this.loginModal) this.closeLogin();
      if (e.target === this.registerModal) this.closeRegister();
    });

    // Form submissions
    document.getElementById('loginForm').addEventListener('submit', (e) => this.handleLogin(e));
    document.getElementById('registerForm').addEventListener('submit', (e) => this.handleRegister(e));
  }

  openLogin() {
    this.loginModal.classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  closeLogin() {
    this.loginModal.classList.remove('active');
    document.body.style.overflow = 'auto';
    document.getElementById('loginForm').reset();
    this.clearErrors('login');
  }

  openRegister() {
    this.registerModal.classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  closeRegister() {
    this.registerModal.classList.remove('active');
    document.body.style.overflow = 'auto';
    document.getElementById('registerForm').reset();
    this.clearErrors('register');
  }

  clearErrors(formType) {
    const errorElements = document.querySelectorAll(`#${formType}Modal .form-error`);
    errorElements.forEach(el => el.textContent = '');
  }

  handleLogin(e) {
    e.preventDefault();
    this.clearErrors('login');

    const email = document.getElementById('loginEmail').value.trim();
    const password = document.getElementById('loginPassword').value;

    // Validation
    let isValid = true;

    if (!this.validateEmail(email)) {
      document.getElementById('loginEmailError').textContent = 'Please enter a valid email address';
      isValid = false;
    }

    if (password.length < 6) {
      document.getElementById('loginPasswordError').textContent = 'Password must be at least 6 characters';
      isValid = false;
    }

    if (isValid) {
      // Here you would send the login data to your backend
      console.log('Login data:', { email, password });
      alert('Login successful! (Demo - no backend connected)');
      this.closeLogin();
    }
  }

  handleRegister(e) {
    e.preventDefault();
    this.clearErrors('register');

    const fullName = document.getElementById('fullName').value.trim();
    const email = document.getElementById('registerEmail').value.trim();
    const country = document.getElementById('country').value;
    const phone = document.getElementById('phone').value.trim();
    const password = document.getElementById('registerPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;

    // Validation
    let isValid = true;

    if (fullName.length < 2) {
      document.getElementById('fullNameError').textContent = 'Please enter your full name';
      isValid = false;
    }

    if (!this.validateEmail(email)) {
      document.getElementById('registerEmailError').textContent = 'Please enter a valid email address';
      isValid = false;
    }

    if (!country) {
      document.getElementById('countryError').textContent = 'Please select your country';
      isValid = false;
    }

    if (!this.validatePhone(phone)) {
      document.getElementById('phoneError').textContent = 'Please enter a valid phone number';
      isValid = false;
    }

    if (!this.validatePassword(password)) {
      document.getElementById('registerPasswordError').textContent = 'Password must be at least 8 characters with uppercase, lowercase, and numbers';
      isValid = false;
    }

    if (password !== confirmPassword) {
      document.getElementById('confirmPasswordError').textContent = 'Passwords do not match';
      isValid = false;
    }

    if (isValid) {
      // Here you would send the registration data to your backend
      console.log('Registration data:', {
        fullName,
        email,
        country,
        phone,
        password
      });
      alert('Registration successful! (Demo - no backend connected)');
      this.closeRegister();
    }
  }

  validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  }

  validatePhone(phone) {
    // Basic phone validation - allows various formats
    const phoneRegex = /^[\d\s\-\+\(\)]{10,}$/;
    return phoneRegex.test(phone.replace(/\s/g, ''));
  }

  validatePassword(password) {
    // At least 8 characters, one uppercase, one lowercase, one number
    const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
    return passwordRegex.test(password);
  }
}

// Initialize everything when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  new Carousel();
  new Navigation();
  new ModalManager();
});
