/* ================================================
   HOTEL NOESIS - MAIN JAVASCRIPT
   Vanilla JavaScript for interactions and animations
   ================================================ */

// ================================================
// NAVIGATION - Header scroll effects and mobile menu
// ================================================
document.addEventListener('DOMContentLoaded', function() {
  const header = document.querySelector('.header');
  const menuToggle = document.querySelector('.menu-toggle');
  const navLinks = document.querySelector('.nav-links');
  const navLinkItems = document.querySelectorAll('.nav-link');

  // Header scroll effect
  let lastScroll = 0;
  window.addEventListener('scroll', function() {
    const currentScroll = window.pageYOffset;

    if (currentScroll > 100) {
      header.classList.add('scrolled');
    } else {
      header.classList.remove('scrolled');
    }

    lastScroll = currentScroll;
  });

  // Mobile menu toggle
  if (menuToggle) {
    menuToggle.addEventListener('click', function() {
      this.classList.toggle('active');
      navLinks.classList.toggle('active');
      document.body.style.overflow = navLinks.classList.contains('active') ? 'hidden' : '';
    });
  }

  // Close mobile menu when clicking a link
  navLinkItems.forEach(link => {
    link.addEventListener('click', function() {
      if (window.innerWidth <= 768) {
        menuToggle.classList.remove('active');
        navLinks.classList.remove('active');
        document.body.style.overflow = '';
      }
    });
  });

  // Set active nav link based on current page
  const currentPage = window.location.pathname.split('/').pop() || 'index.html';
  navLinkItems.forEach(link => {
    const linkPage = link.getAttribute('href').split('/').pop();
    if (linkPage === currentPage) {
      link.classList.add('active');
    }
  });
});

// ================================================
// SCROLL ANIMATIONS - Intersection Observer
// ================================================
const observerOptions = {
  threshold: 0.15,
  rootMargin: '0px 0px -50px 0px'
};

const observer = new IntersectionObserver(function(entries) {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('visible');
      // Optionally unobserve after animation
      // observer.unobserve(entry.target);
    }
  });
}, observerOptions);

// Observe elements with animation classes
document.addEventListener('DOMContentLoaded', function() {
  const animatedElements = document.querySelectorAll('.fade-in, .slide-in-left, .slide-in-right');
  animatedElements.forEach(el => observer.observe(el));
});

// ================================================
// SMOOTH SCROLL - For anchor links
// ================================================
document.addEventListener('DOMContentLoaded', function() {
  const smoothScrollLinks = document.querySelectorAll('a[href^="#"]');

  smoothScrollLinks.forEach(link => {
    link.addEventListener('click', function(e) {
      const href = this.getAttribute('href');
      if (href === '#') return;

      e.preventDefault();
      const target = document.querySelector(href);

      if (target) {
        // Scroll to the very top of the target element (0 offset)
        const targetPosition = target.getBoundingClientRect().top + window.pageYOffset;

        window.scrollTo({
          top: targetPosition,
          behavior: 'smooth'
        });
      }
    });
  });
});

// ================================================
// FAQ ACCORDION - Travel Info Page
// ================================================
document.addEventListener('DOMContentLoaded', function() {
  const faqQuestions = document.querySelectorAll('.faq-question');

  faqQuestions.forEach(question => {
    question.addEventListener('click', function() {
      const faqItem = this.parentElement;
      const isActive = faqItem.classList.contains('active');

      // Close all other items
      document.querySelectorAll('.faq-item').forEach(item => {
        item.classList.remove('active');
      });

      // Toggle current item
      if (!isActive) {
        faqItem.classList.add('active');
      }
    });
  });
});

// ================================================
// LIGHTBOX - Image gallery functionality
// ================================================
class Lightbox {
  constructor() {
    this.createLightbox();
    this.bindEvents();
  }

  createLightbox() {
    const lightboxHTML = `
      <div class="lightbox" id="lightbox">
        <div class="lightbox-content">
          <span class="lightbox-close">&times;</span>
          <img src="" alt="" class="lightbox-image" id="lightbox-image">
        </div>
      </div>
    `;
    document.body.insertAdjacentHTML('beforeend', lightboxHTML);

    this.lightbox = document.getElementById('lightbox');
    this.lightboxImage = document.getElementById('lightbox-image');
    this.closeBtn = document.querySelector('.lightbox-close');
  }

  bindEvents() {
    // Open lightbox
    document.addEventListener('click', (e) => {
      if (e.target.classList.contains('lightbox-trigger')) {
        e.preventDefault();
        this.open(e.target.src, e.target.alt);
      }
    });

    // Close lightbox
    this.closeBtn.addEventListener('click', () => this.close());
    this.lightbox.addEventListener('click', (e) => {
      if (e.target === this.lightbox) {
        this.close();
      }
    });

    // Close on Escape key
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && this.lightbox.classList.contains('active')) {
        this.close();
      }
    });
  }

  open(src, alt) {
    this.lightboxImage.src = src;
    this.lightboxImage.alt = alt;
    this.lightbox.classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  close() {
    this.lightbox.classList.remove('active');
    document.body.style.overflow = '';
    setTimeout(() => {
      this.lightboxImage.src = '';
    }, 300);
  }
}

// Initialize lightbox
document.addEventListener('DOMContentLoaded', () => {
  new Lightbox();
});

// ================================================
// FORM VALIDATION - Contact form
// ================================================
class FormValidator {
  constructor(formId) {
    this.form = document.getElementById(formId);
    if (!this.form) return;

    this.bindEvents();
  }

  bindEvents() {
    this.form.addEventListener('submit', (e) => {
      e.preventDefault();
      if (this.validateForm()) {
        this.submitForm();
      }
    });

    // Real-time validation on blur
    const inputs = this.form.querySelectorAll('.form-input, .form-textarea');
    inputs.forEach(input => {
      input.addEventListener('blur', () => this.validateField(input));
      input.addEventListener('input', () => {
        if (input.classList.contains('error')) {
          this.validateField(input);
        }
      });
    });
  }

  validateField(field) {
    const value = field.value.trim();
    const fieldName = field.name;
    let isValid = true;
    let errorMessage = '';

    // Required field check
    if (field.hasAttribute('required') && !value) {
      isValid = false;
      errorMessage = 'This field is required';
    }

    // Email validation
    if (fieldName === 'email' && value) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(value)) {
        isValid = false;
        errorMessage = 'Please enter a valid email address';
      }
    }

    // Phone validation (optional but if filled, must be valid)
    if (fieldName === 'phone' && value) {
      const phoneRegex = /^[\d\s\-\+\(\)]+$/;
      if (!phoneRegex.test(value) || value.length < 10) {
        isValid = false;
        errorMessage = 'Please enter a valid phone number';
      }
    }

    // Min length check
    const minLength = field.getAttribute('minlength');
    if (minLength && value.length < minLength && value.length > 0) {
      isValid = false;
      errorMessage = `Minimum ${minLength} characters required`;
    }

    this.showFieldError(field, isValid, errorMessage);
    return isValid;
  }

  validateForm() {
    const inputs = this.form.querySelectorAll('.form-input, .form-textarea');
    let isFormValid = true;

    inputs.forEach(input => {
      if (!this.validateField(input)) {
        isFormValid = false;
      }
    });

    return isFormValid;
  }

  showFieldError(field, isValid, message) {
    const formGroup = field.closest('.form-group');
    let errorElement = formGroup.querySelector('.form-error');

    if (!errorElement) {
      errorElement = document.createElement('div');
      errorElement.className = 'form-error';
      formGroup.appendChild(errorElement);
    }

    if (isValid) {
      field.classList.remove('error');
      errorElement.classList.remove('visible');
      errorElement.textContent = '';
    } else {
      field.classList.add('error');
      errorElement.classList.add('visible');
      errorElement.textContent = message;
    }
  }

  submitForm() {
    // Get form data
    const formData = new FormData(this.form);
    const data = Object.fromEntries(formData);

    // Show success message
    this.showSuccessMessage();

    // Reset form
    this.form.reset();

    // Remove error states
    const inputs = this.form.querySelectorAll('.form-input, .form-textarea');
    inputs.forEach(input => {
      input.classList.remove('error');
      const errorElement = input.closest('.form-group').querySelector('.form-error');
      if (errorElement) {
        errorElement.classList.remove('visible');
      }
    });

    // In production, you would send data to a server
    console.log('Form submitted:', data);
  }

  showSuccessMessage() {
    const message = document.createElement('div');
    message.className = 'form-success';
    message.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: var(--charcoal);
      color: var(--ivory);
      padding: 2rem 3rem;
      border: 2px solid var(--gold-primary);
      z-index: 3000;
      text-align: center;
      box-shadow: var(--shadow-lg);
    `;
    message.innerHTML = `
      <h3 style="color: var(--gold-primary); margin-bottom: 1rem;">Thank You!</h3>
      <p>Your message has been sent successfully. We will get back to you soon.</p>
    `;

    document.body.appendChild(message);

    setTimeout(() => {
      message.style.opacity = '0';
      message.style.transition = 'opacity 0.3s ease';
      setTimeout(() => message.remove(), 300);
    }, 3000);
  }
}

// Initialize form validation
document.addEventListener('DOMContentLoaded', () => {
  new FormValidator('contact-form');
});

// ================================================
// LAZY LOADING - Images
// ================================================
document.addEventListener('DOMContentLoaded', function() {
  const lazyImages = document.querySelectorAll('img[data-src]');

  const imageObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;
        img.removeAttribute('data-src');
        observer.unobserve(img);
      }
    });
  });

  lazyImages.forEach(img => imageObserver.observe(img));
});

// ================================================
// PARALLAX EFFECT - Hero sections
// ================================================
document.addEventListener('DOMContentLoaded', function() {
  const parallaxElements = document.querySelectorAll('.hero-bg');

  window.addEventListener('scroll', function() {
    const scrolled = window.pageYOffset;

    parallaxElements.forEach(element => {
      const rect = element.getBoundingClientRect();
      if (rect.top < window.innerHeight && rect.bottom > 0) {
        const speed = 0.5;
        element.style.transform = `translateY(${scrolled * speed}px)`;
      }
    });
  });
});

// ================================================
// UTILITY FUNCTIONS
// ================================================

// Debounce function for performance
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// Get element offset from top
Element.prototype.getBoundingClientOffset = function() {
  const rect = this.getBoundingClientRect();
  return {
    top: rect.top,
    left: rect.left,
    right: rect.right,
    bottom: rect.bottom
  };
};

// ================================================
// PAGE LOADER (Optional)
// ================================================
window.addEventListener('load', function() {
  document.body.classList.add('loaded');
});
