/* ============================================
   CLARTÉ COMPÉTENCE — Main JavaScript
   ============================================ */

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

  /* ---------- Enable animations (content visible by default until JS loads) ---------- */
  document.body.classList.add('js-ready');

  /* ---------- Header Scroll Effect ---------- */
  const header = document.querySelector('.header');
  if (header) {
    const onScroll = () => {
      header.classList.toggle('scrolled', window.scrollY > 20);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
  }

  /* ---------- Mobile Menu ---------- */
  const burger = document.querySelector('.burger');
  const mobileMenu = document.querySelector('.mobile-menu');
  const overlay = document.querySelector('.overlay');

  function toggleMenu() {
    const isOpen = mobileMenu && mobileMenu.classList.contains('active');
    burger && burger.classList.toggle('active', !isOpen);
    mobileMenu && mobileMenu.classList.toggle('active', !isOpen);
    overlay && overlay.classList.toggle('active', !isOpen);
    document.body.style.overflow = isOpen ? '' : 'hidden';
  }

  function closeMenu() {
    burger && burger.classList.remove('active');
    mobileMenu && mobileMenu.classList.remove('active');
    overlay && overlay.classList.remove('active');
    document.body.style.overflow = '';
  }

  burger && burger.addEventListener('click', toggleMenu);
  overlay && overlay.addEventListener('click', closeMenu);

  // Close on link click
  if (mobileMenu) {
    mobileMenu.querySelectorAll('a').forEach(link => {
      link.addEventListener('click', closeMenu);
    });
  }

  /* ---------- Scroll Reveal Animations ---------- */
  const revealElements = document.querySelectorAll('.reveal');
  if (revealElements.length > 0) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add('visible');
          observer.unobserve(entry.target);
        }
      });
    }, { threshold: 0.1, rootMargin: '0px 0px -50px 0px' });

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

  /* ---------- Hero Text Animation ---------- */
  const heroTitle = document.querySelector('.hero-animated-title');
  if (heroTitle) {
    const lines = heroTitle.querySelectorAll('.hero-line');
    lines.forEach((line, i) => {
      line.style.opacity = '0';
      line.style.transform = 'translateY(20px)';
      line.style.transition = `opacity 0.6s ease ${i * 0.25 + 0.3}s, transform 0.6s ease ${i * 0.25 + 0.3}s`;
      setTimeout(() => {
        line.style.opacity = '1';
        line.style.transform = 'translateY(0)';
      }, 50);
    });
  }

  /* ---------- Animated Counters ---------- */
  const counters = document.querySelectorAll('[data-count]');
  if (counters.length > 0) {
    const counterObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const el = entry.target;
          const target = parseInt(el.dataset.count, 10);
          const suffix = el.dataset.suffix || '';
          const prefix = el.dataset.prefix || '';
          const duration = 1500;
          const start = Date.now();

          function animate() {
            const elapsed = Date.now() - start;
            const progress = Math.min(elapsed / duration, 1);
            const eased = 1 - Math.pow(1 - progress, 3);
            const current = Math.round(target * eased);
            el.textContent = prefix + current + suffix;
            if (progress < 1) requestAnimationFrame(animate);
          }

          animate();
          counterObserver.unobserve(el);
        }
      });
    }, { threshold: 0.5 });

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

  /* ---------- Catalogue: Filtering & Search ---------- */
  const catalogueGrid = document.getElementById('catalogue-grid');
  const searchInput = document.getElementById('catalogue-search');
  const filterPills = document.querySelectorAll('.filter-pill');
  const noResults = document.querySelector('.no-results');

  let activeFilter = 'all';

  function filterFormations() {
    if (!catalogueGrid) return;
    const cards = catalogueGrid.querySelectorAll('.formation-card');
    const query = searchInput ? searchInput.value.toLowerCase().trim() : '';
    let visibleCount = 0;

    cards.forEach(card => {
      const category = card.dataset.category || '';
      const title = (card.dataset.title || '').toLowerCase();
      const matchesFilter = activeFilter === 'all' || category === activeFilter;
      const matchesSearch = !query || title.includes(query);
      const show = matchesFilter && matchesSearch;

      card.style.display = show ? '' : 'none';
      if (show) visibleCount++;
    });

    if (noResults) {
      noResults.style.display = visibleCount === 0 ? 'block' : 'none';
    }
  }

  filterPills.forEach(pill => {
    pill.addEventListener('click', () => {
      filterPills.forEach(p => p.classList.remove('active'));
      pill.classList.add('active');
      activeFilter = pill.dataset.filter || 'all';
      filterFormations();
    });
  });

  if (searchInput) {
    searchInput.addEventListener('input', filterFormations);
  }

  /* ---------- Catalogue: Modal ---------- */
  const modalOverlay = document.getElementById('formation-modal');

  if (catalogueGrid && modalOverlay) {
    catalogueGrid.addEventListener('click', (e) => {
      const card = e.target.closest('.formation-card');
      if (!card || e.target.closest('.btn')) return;

      const data = card.dataset;
      const modal = modalOverlay.querySelector('.modal');

      modal.querySelector('.modal-title').textContent = data.title || '';
      modal.querySelector('.modal-category').textContent = data.categoryLabel || '';
      modal.querySelector('.modal-category').className = 'formation-category ' + (data.categoryClass || '');
      modal.querySelector('.modal-duration').textContent = data.duration || '';
      modal.querySelector('.modal-modality').textContent = data.modality || '';
      modal.querySelector('.modal-description').textContent = data.description || '';
      modal.querySelector('.modal-objectives').innerHTML = data.objectives
        ? data.objectives.split('|').map(o => `<li>${o.trim()}</li>`).join('')
        : '';
      modal.querySelector('.modal-public').textContent = data.public || '';
      modal.querySelector('.modal-prerequis').textContent = data.prerequis || '';

      modalOverlay.classList.add('active');
      document.body.style.overflow = 'hidden';
    });

    // Close modal
    modalOverlay.addEventListener('click', (e) => {
      if (e.target === modalOverlay || e.target.closest('.modal-close')) {
        modalOverlay.classList.remove('active');
        document.body.style.overflow = '';
      }
    });

    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && modalOverlay.classList.contains('active')) {
        modalOverlay.classList.remove('active');
        document.body.style.overflow = '';
      }
    });
  }

  /* ---------- Contact & Réseau Forms ---------- */
  document.querySelectorAll('form[data-validate]').forEach(form => {
    form.addEventListener('submit', (e) => {
      e.preventDefault();

      // Basic validation
      const requiredFields = form.querySelectorAll('[required]');
      let valid = true;

      requiredFields.forEach(field => {
        if (!field.value.trim()) {
          valid = false;
          field.style.borderColor = '#EF4444';
          field.addEventListener('input', () => {
            field.style.borderColor = '';
          }, { once: true });
        }
      });

      if (!valid) return;

      // Show success message
      const successEl = form.parentElement.querySelector('.form-success');
      if (successEl) {
        form.style.display = 'none';
        successEl.classList.add('show');
      }
    });
  });

  /* ---------- Smooth scroll for anchor links ---------- */
  document.querySelectorAll('a[href^="#"]').forEach(link => {
    link.addEventListener('click', (e) => {
      const target = document.querySelector(link.getAttribute('href'));
      if (target) {
        e.preventDefault();
        target.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    });
  });

});
