/* ============================================================
   TAHWISSA v2 — Enhanced JavaScript
   ============================================================ */
(function () {
  'use strict';

  /* --- Nav scroll --- */
  const nav = document.getElementById('mainNav');
  if (nav) {
    function updateNav() { nav.classList.toggle('scrolled', window.scrollY > 40); }
    window.addEventListener('scroll', updateNav, { passive: true });
    updateNav();
  }

  /* --- Mobile menu --- */
  const hamburger  = document.getElementById('hamburger');
  const mobileMenu = document.getElementById('mobileMenu');
  if (hamburger && mobileMenu) {
    hamburger.addEventListener('click', () => {
      const isOpen = hamburger.classList.toggle('open');
      mobileMenu.classList.toggle('open', isOpen);
      document.body.style.overflow = isOpen ? 'hidden' : '';
      hamburger.setAttribute('aria-expanded', isOpen);
    });
    mobileMenu.addEventListener('click', e => {
      if (e.target === mobileMenu) {
        hamburger.classList.remove('open');
        mobileMenu.classList.remove('open');
        document.body.style.overflow = '';
      }
    });
    mobileMenu.querySelectorAll('a[href^="#"]').forEach(a => {
      a.addEventListener('click', () => {
        hamburger.classList.remove('open');
        mobileMenu.classList.remove('open');
        document.body.style.overflow = '';
      });
    });
  }

  /* --- Smooth scroll --- */
  document.querySelectorAll('a[href^="#"]').forEach(a => {
    a.addEventListener('click', e => {
      const id = a.getAttribute('href').slice(1);
      const el = document.getElementById(id);
      if (el) {
        e.preventDefault();
        const top = el.getBoundingClientRect().top + window.scrollY - 70;
        window.scrollTo({ top, behavior: 'smooth' });
      }
    });
  });

  /* --- Reveal on scroll (enhanced with stagger) --- */
  const reveals = document.querySelectorAll('.reveal, .stagger-children');
  if ('IntersectionObserver' in window && reveals.length) {
    const obs = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('visible');
          obs.unobserve(e.target);
        }
      });
    }, { threshold: 0.08, rootMargin: '0px 0px -30px 0px' });
    reveals.forEach(el => obs.observe(el));
  } else {
    reveals.forEach(el => el.classList.add('visible'));
  }

  /* --- Contact form --- */
  const form    = document.getElementById('contactForm');
  const success = document.getElementById('formSuccess');
  if (form) {
    form.addEventListener('submit', e => {
      e.preventDefault();
      const btn = form.querySelector('.form-submit');
      btn.disabled = true;
      btn.innerHTML = '<span style="display:inline-block;animation:rotate-slow 1s linear infinite">⏳</span> جاري الإرسال...';
      fetch('contact.php', { method: 'POST', body: new FormData(form) })
        .then(r => r.json())
        .then(res => {
          btn.disabled = false;
          btn.innerHTML = 'إرسال الرسالة';
          if (res.ok) {
            form.reset();
            if (success) { success.classList.add('show'); setTimeout(() => success.classList.remove('show'), 6000); }
          } else {
            alert('يرجى ملء جميع الحقول بشكل صحيح.');
          }
        })
        .catch(() => {
          btn.disabled = false;
          btn.innerHTML = 'إرسال الرسالة';
          alert('خطأ في الاتصال، حاول مجدداً.');
        });
    });
  }

  /* --- Cursor glow (desktop) --- */
  if (window.matchMedia('(hover: hover)').matches) {
    const glow = document.createElement('div');
    glow.className = 'cursor-glow';
    document.body.appendChild(glow);
    let mx = 0, my = 0, cx = 0, cy = 0;
    document.addEventListener('mousemove', e => { mx = e.clientX; my = e.clientY; }, { passive: true });
    (function animateGlow() {
      cx += (mx - cx) * 0.08;
      cy += (my - cy) * 0.08;
      glow.style.left = cx + 'px';
      glow.style.top  = cy + 'px';
      requestAnimationFrame(animateGlow);
    })();
  }

  /* --- Animated counters in hero stats --- */
  function animateCounter(el, target, suffix) {
    let start = 0;
    const duration = 1800;
    const step = timestamp => {
      if (!start) start = timestamp;
      const progress = Math.min((timestamp - start) / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      el.textContent = Math.floor(eased * target) + suffix;
      if (progress < 1) requestAnimationFrame(step);
    };
    requestAnimationFrame(step);
  }

  const statsObs = new IntersectionObserver(entries => {
    entries.forEach(e => {
      if (e.isIntersecting) {
        const nums = e.target.querySelectorAll('.hero-stat-num');
        nums.forEach(num => {
          const text = num.textContent.trim();
          const match = text.match(/^(\d+)(.*)$/);
          if (match) animateCounter(num, parseInt(match[1]), match[2]);
        });
        statsObs.unobserve(e.target);
      }
    });
  }, { threshold: 0.5 });
  const heroStats = document.querySelector('.hero-stats');
  if (heroStats) statsObs.observe(heroStats);

  /* --- Scroll progress bar --- */
  const progressBar = document.createElement('div');
  progressBar.style.cssText = `
    position: fixed; top: 0; left: 0; height: 3px; z-index: 2000;
    background: linear-gradient(90deg, #52B788, #C9A84C);
    width: 0%; transition: width .1s; pointer-events: none;
    box-shadow: 0 0 8px rgba(201,168,76,.5);
  `;
  document.body.appendChild(progressBar);
  window.addEventListener('scroll', () => {
    const total = document.documentElement.scrollHeight - window.innerHeight;
    progressBar.style.width = (window.scrollY / total * 100) + '%';
  }, { passive: true });

  /* --- Parallax on hero blobs --- */
  const blobs = document.querySelectorAll('.hero-blob');
  if (blobs.length) {
    window.addEventListener('mousemove', e => {
      const x = (e.clientX / window.innerWidth  - 0.5) * 30;
      const y = (e.clientY / window.innerHeight - 0.5) * 30;
      blobs[0] && (blobs[0].style.transform = `translate(${x}px, ${y}px)`);
      blobs[1] && (blobs[1].style.transform = `translate(${-x}px, ${-y}px)`);
    }, { passive: true });
  }

  /* --- Ripple effect on buttons --- */
  document.querySelectorAll('.btn, .hero-btn-primary, .form-submit, .place-map-btn').forEach(btn => {
    btn.addEventListener('click', function(e) {
      const rect = this.getBoundingClientRect();
      const ripple = document.createElement('span');
      const size = Math.max(rect.width, rect.height);
      ripple.style.cssText = `
        position:absolute; width:${size}px; height:${size}px;
        border-radius:50%; background:rgba(255,255,255,.3);
        top:${e.clientY - rect.top - size/2}px;
        left:${e.clientX - rect.left - size/2}px;
        transform:scale(0); animation:ripple .6s linear;
        pointer-events:none;
      `;
      if (!document.getElementById('ripple-style')) {
        const s = document.createElement('style');
        s.id = 'ripple-style';
        s.textContent = '@keyframes ripple{to{transform:scale(4);opacity:0}}';
        document.head.appendChild(s);
      }
      const pos = getComputedStyle(this).position;
      if (pos === 'static') this.style.position = 'relative';
      this.style.overflow = 'hidden';
      this.appendChild(ripple);
      ripple.addEventListener('animationend', () => ripple.remove());
    });
  });

  /* --- Tilt effect on place cards --- */
  if (window.matchMedia('(hover: hover)').matches) {
    document.querySelectorAll('.place-card, .act-card').forEach(card => {
      card.addEventListener('mousemove', e => {
        const rect = card.getBoundingClientRect();
        const x = ((e.clientX - rect.left) / rect.width  - 0.5) * 10;
        const y = ((e.clientY - rect.top)  / rect.height - 0.5) * 10;
        card.style.transform = `translateY(-8px) rotateY(${x}deg) rotateX(${-y}deg) scale(1.01)`;
      });
      card.addEventListener('mouseleave', () => {
        card.style.transform = '';
        card.style.transition = 'transform .5s cubic-bezier(.34,1.56,.64,1)';
      });
      card.addEventListener('mouseenter', () => {
        card.style.transition = 'transform .1s ease';
      });
    });
  }

  /* --- Scroll to top button --- */
  const scrollTop = document.createElement('button');
  scrollTop.innerHTML = '↑';
  scrollTop.setAttribute('aria-label', 'العودة للأعلى');
  scrollTop.style.cssText = `
    position:fixed; bottom:24px; inset-inline-end:24px; z-index:999;
    width:44px; height:44px; border-radius:50%;
    background:var(--g-main); color:#fff;
    font-size:1.2rem; font-weight:900;
    box-shadow:0 4px 16px rgba(45,106,79,.35);
    border:none; cursor:pointer;
    opacity:0; transform:translateY(16px);
    transition:.3s cubic-bezier(.4,0,.2,1);
    font-family:var(--font);
  `;
  document.body.appendChild(scrollTop);
  window.addEventListener('scroll', () => {
    const show = window.scrollY > 400;
    scrollTop.style.opacity  = show ? '1'  : '0';
    scrollTop.style.transform = show ? 'translateY(0)' : 'translateY(16px)';
    scrollTop.style.pointerEvents = show ? 'auto' : 'none';
  }, { passive: true });
  scrollTop.addEventListener('click', () => window.scrollTo({ top: 0, behavior: 'smooth' }));
  scrollTop.addEventListener('mouseenter', () => scrollTop.style.background = 'var(--g-deep)');
  scrollTop.addEventListener('mouseleave', () => scrollTop.style.background = 'var(--g-main)');

})();
