/* ============================================
   AJOUAMAI IMMO-BUSINESS — Luxury Editorial JS Engine
   Animations, Smooth Scroll, Magnetic Hover, Split Text
   ============================================ */

document.addEventListener('DOMContentLoaded', () => {

  // ============================================
  // 1. Loading Screen Controller
  // ============================================
  const loadingScreen = document.getElementById('loading-screen');
  if (loadingScreen) {
    const hideLoading = () => {
      loadingScreen.style.opacity = '0';
      loadingScreen.style.visibility = 'hidden';
      setTimeout(() => loadingScreen.remove(), 800);
    };
    window.addEventListener('load', () => setTimeout(hideLoading, 400));
    setTimeout(hideLoading, 2500); // Fallback
  }

  // ============================================
  // 2. Header Scroll Controller & Logo Color Inversion
  // ============================================
  const header = document.getElementById('site-header');
  const logo = document.getElementById('header-logo');
  
  if (header) {
    const isHeaderTransparent = header.dataset.headerStyle === 'transparent' || header.classList.contains('header-transparent');
    
    const updateHeader = () => {
      if (window.scrollY > 40) {
        header.classList.add('scrolled');
        header.classList.remove('header-transparent');
        if (logo) {
          logo.style.filter = 'brightness(0)'; // Invert to crisp black on white background
        }
      } else {
        header.classList.remove('scrolled');
        if (isHeaderTransparent) {
          header.classList.add('header-transparent');
          if (logo) {
            logo.style.filter = 'brightness(0) invert(1)'; // Invert to crisp white on dark hero
          }
        } else {
          if (logo) {
            logo.style.filter = 'brightness(0)';
          }
        }
      }
    };

    window.addEventListener('scroll', updateHeader, { passive: true });
    updateHeader(); // Run immediately on DOM ready
  }

  // ============================================
  // 3. Mobile Navigation Drawer
  // ============================================
  const sidebarToggle = document.getElementById('sidebar-toggle');
  const sidebarClose = document.getElementById('sidebar-close');
  const sidebarNav = document.getElementById('sidebar-nav');
  const sidebarOverlay = document.getElementById('sidebar-overlay');

  function openSidebar() {
    if (!sidebarNav || !sidebarOverlay) return;
    sidebarNav.classList.remove('translate-x-full', '-translate-x-full');
    sidebarNav.classList.add('translate-x-0');
    sidebarOverlay.classList.remove('opacity-0', 'invisible');
    sidebarOverlay.classList.add('opacity-100', 'visible');
    document.body.style.overflow = 'hidden';
  }

  function closeSidebar() {
    if (!sidebarNav || !sidebarOverlay) return;
    sidebarNav.classList.add('-translate-x-full');
    sidebarNav.classList.remove('translate-x-0', 'translate-x-full');
    sidebarOverlay.classList.add('opacity-0', 'invisible');
    sidebarOverlay.classList.remove('opacity-100', 'visible');
    document.body.style.overflow = '';
  }

  if (sidebarToggle) sidebarToggle.addEventListener('click', openSidebar);
  if (sidebarClose) sidebarClose.addEventListener('click', closeSidebar);
  if (sidebarOverlay) sidebarOverlay.addEventListener('click', closeSidebar);
  document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeSidebar(); });

  // ============================================
  // 4. Scroll Reveal Intersection Observer
  // ============================================
  const revealElements = document.querySelectorAll('.reveal, .reveal-left, .reveal-right, .reveal-scale, .clip-up');
  
  if (revealElements.length > 0) {
    const revealObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add('active');
          revealObserver.unobserve(entry.target);
        }
      });
    }, {
      threshold: 0.12,
      rootMargin: '0px 0px -50px 0px'
    });

    revealElements.forEach(el => revealObserver.observe(el));
  }

  // ============================================
  // 5. Magnetic Hover Effect for Luxury Buttons
  // ============================================
  const magneticButtons = document.querySelectorAll('.btn-lemonde-consultation, .btn-magnetic');
  
  magneticButtons.forEach(btn => {
    btn.addEventListener('mousemove', (e) => {
      const rect = btn.getBoundingClientRect();
      const x = e.clientX - rect.left - rect.width / 2;
      const y = e.clientY - rect.top - rect.height / 2;
      btn.style.transform = `translate3d(${x * 0.25}px, ${y * 0.25}px, 0)`;
    });

    btn.addEventListener('mouseleave', () => {
      btn.style.transform = 'translate3d(0, 0, 0)';
    });
  });

  // ============================================
  // 6. Split Text Animation
  // ============================================
  const splitTextElements = document.querySelectorAll('.split-text');
  
  splitTextElements.forEach(el => {
    const text = el.textContent.trim();
    const words = text.split(' ');
    el.innerHTML = '';
    
    words.forEach((word, wordIndex) => {
      const wordSpan = document.createElement('span');
      wordSpan.style.display = 'inline-block';
      wordSpan.style.overflow = 'hidden';
      wordSpan.style.marginRight = '0.3em';
      wordSpan.style.verticalAlign = 'top';
      
      const innerSpan = document.createElement('span');
      innerSpan.textContent = word;
      innerSpan.style.display = 'inline-block';
      innerSpan.style.transform = 'translateY(110%)';
      innerSpan.style.transition = `transform 0.8s cubic-bezier(0.16, 1, 0.3, 1) ${wordIndex * 0.05}s`;
      innerSpan.className = 'split-word-inner';
      
      wordSpan.appendChild(innerSpan);
      el.appendChild(wordSpan);
    });

    const splitObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.querySelectorAll('.split-word-inner').forEach(span => {
            span.style.transform = 'translateY(0%)';
          });
          splitObserver.unobserve(entry.target);
        }
      });
    }, { threshold: 0.2 });

    splitObserver.observe(el);
  });

  // ============================================
  // 7. Parallax Scroll Effect
  // ============================================
  const parallaxElements = document.querySelectorAll('.parallax-bg, [data-parallax]');
  if (parallaxElements.length > 0) {
    window.addEventListener('scroll', () => {
      const scrolled = window.scrollY;
      parallaxElements.forEach(el => {
        const speed = parseFloat(el.dataset.parallaxSpeed || '0.2');
        el.style.transform = `translate3d(0, ${scrolled * speed}px, 0)`;
      });
    }, { passive: true });
  }

  // ============================================
  // 8. Number Counter Animation
  // ============================================
  const counters = document.querySelectorAll('.counter');
  if (counters.length > 0) {
    const counterObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const counter = entry.target;
          const target = parseInt(counter.getAttribute('data-target') || '0', 10);
          const suffix = counter.getAttribute('data-suffix') || '';
          const duration = 2000;
          const startTime = performance.now();

          const updateCounter = (currentTime) => {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);
            const eased = 1 - Math.pow(1 - progress, 3);
            counter.textContent = Math.round(target * eased) + suffix;
            
            if (progress < 1) {
              requestAnimationFrame(updateCounter);
            } else {
              counter.textContent = target + suffix;
            }
          };

          requestAnimationFrame(updateCounter);
          counterObserver.unobserve(counter);
        }
      });
    }, { threshold: 0.3 });

    counters.forEach(c => counterObserver.observe(c));
  }

  // ============================================
  // 9. Multi-step Form (Estimation Page Breteuil Style)
  // ============================================
  const estimationForm = document.getElementById('estimation-form');
  if (estimationForm) {
    const steps = estimationForm.querySelectorAll('.estimation-step');
    const dots = document.querySelectorAll('.step-indicator-dot');
    const fill = document.getElementById('step-progress-fill');
    let currentStep = 0;

    const updateStep = (n) => {
      steps.forEach((step, i) => {
        step.classList.toggle('hidden', i !== n);
      });
      dots.forEach((dot, i) => {
        dot.classList.toggle('bg-gold', i <= n);
        dot.classList.toggle('bg-gray-300', i > n);
      });
      if (fill) {
        fill.style.width = `${((n + 1) / steps.length) * 100}%`;
      }
      currentStep = n;
      estimationForm.scrollIntoView({ behavior: 'smooth', block: 'start' });
    };

    document.querySelectorAll('.btn-next-step').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.preventDefault();
        if (currentStep < steps.length - 1) {
          updateStep(currentStep + 1);
        }
      });
    });

    document.querySelectorAll('.btn-prev-step').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.preventDefault();
        if (currentStep > 0) {
          updateStep(currentStep - 1);
        }
      });
    });
  }

  // ============================================
  // 10. Swiper Initialization Helper
  // ============================================
  if (typeof Swiper !== 'undefined') {
    const featuredSwiper = document.querySelector('.swiper-featured-properties');
    if (featuredSwiper) {
      new Swiper('.swiper-featured-properties', {
        slidesPerView: 1,
        spaceBetween: 0,
        loop: true,
        effect: 'fade',
        fadeEffect: { crossFade: true },
        speed: 900,
        autoplay: {
          delay: 5000,
          disableOnInteraction: false,
        },
        pagination: {
          el: '.swiper-pagination',
          clickable: true,
          bulletClass: 'swiper-pagination-bullet-custom',
          bulletActiveClass: 'swiper-pagination-bullet-custom-active',
        },
        navigation: {
          nextEl: '.swiper-button-next-custom',
          prevEl: '.swiper-button-prev-custom',
        },
      });
    }
  }

  // ============================================
  // 11. Property Gallery Interactive Slider
  // ============================================
  const galleryMain = document.getElementById('gallery-main');
  const galleryThumbs = document.querySelectorAll('.gallery-thumb');
  const galleryPrev = document.getElementById('gallery-prev');
  const galleryNext = document.getElementById('gallery-next');
  const galleryCounter = document.getElementById('gallery-counter');

  if (galleryMain && galleryThumbs.length > 0) {
    let currentIndex = 0;
    const imagesList = Array.from(galleryThumbs).map(t => t.dataset.src || t.src);

    const updateGallery = (index) => {
      currentIndex = (index + imagesList.length) % imagesList.length;
      galleryMain.style.opacity = '0.3';
      setTimeout(() => {
        galleryMain.src = imagesList[currentIndex];
        galleryMain.style.opacity = '1';
      }, 150);

      galleryThumbs.forEach((thumb, i) => {
        if (i === currentIndex) {
          thumb.classList.add('border-black', 'scale-95');
          thumb.classList.remove('border-transparent', 'opacity-70');
        } else {
          thumb.classList.remove('border-black', 'scale-95');
          thumb.classList.add('border-transparent', 'opacity-70');
        }
      });

      if (galleryCounter) {
        galleryCounter.textContent = `${currentIndex + 1} / ${imagesList.length}`;
      }
    };

    let autoSlideTimer = null;
    const startAutoSlide = () => {
      if (imagesList.length > 1) {
        autoSlideTimer = setInterval(() => {
          updateGallery(currentIndex + 1);
        }, 3500);
      }
    };

    const resetAutoSlide = () => {
      if (autoSlideTimer) clearInterval(autoSlideTimer);
      startAutoSlide();
    };

    galleryThumbs.forEach((thumb, i) => {
      thumb.addEventListener('click', () => {
        updateGallery(i);
        resetAutoSlide();
      });
    });

    if (galleryPrev) galleryPrev.addEventListener('click', () => {
      updateGallery(currentIndex - 1);
      resetAutoSlide();
    });
    if (galleryNext) galleryNext.addEventListener('click', () => {
      updateGallery(currentIndex + 1);
      resetAutoSlide();
    });

    document.addEventListener('keydown', (e) => {
      if (e.key === 'ArrowLeft') { updateGallery(currentIndex - 1); resetAutoSlide(); }
      if (e.key === 'ArrowRight') { updateGallery(currentIndex + 1); resetAutoSlide(); }
    });

    // Start auto slide on init
    startAutoSlide();
  }

  // ============================================
  // 12. Horizontal Auto-Scroll & Drag Scroll for Featured Properties
  // ============================================
  const dragScrollContainers = document.querySelectorAll('.drag-scroll');

  dragScrollContainers.forEach(container => {
    let isDown = false;
    let startX;
    let scrollLeft;
    let autoScrollSpeed = 0.8;
    let isHovered = false;

    container.addEventListener('mousedown', (e) => {
      isDown = true;
      container.classList.add('cursor-grabbing');
      startX = e.pageX - container.offsetLeft;
      scrollLeft = container.scrollLeft;
    });

    container.addEventListener('mouseleave', () => {
      isDown = false;
      isHovered = false;
      container.classList.remove('cursor-grabbing');
    });

    container.addEventListener('mouseenter', () => {
      isHovered = true;
    });

    container.addEventListener('mouseup', () => {
      isDown = false;
      container.classList.remove('cursor-grabbing');
    });

    container.addEventListener('mousemove', (e) => {
      if (!isDown) return;
      e.preventDefault();
      const x = e.pageX - container.offsetLeft;
      const walk = (x - startX) * 1.5;
      container.scrollLeft = scrollLeft - walk;
    });

    container.addEventListener('touchstart', () => { isHovered = true; }, { passive: true });
    container.addEventListener('touchend', () => { isHovered = false; }, { passive: true });

    const stepAutoScroll = () => {
      if (!isHovered && !isDown) {
        container.scrollLeft += autoScrollSpeed;
        if (container.scrollLeft + container.clientWidth >= container.scrollWidth - 2) {
          container.scrollLeft = 0;
        }
      }
      requestAnimationFrame(stepAutoScroll);
    };

    requestAnimationFrame(stepAutoScroll);
  });

});

