/* ==================================================== */
/* PAGE CONFIGURATEUR PC SUR MESURE - INFOMAX - JS       */
/* À coller dans Creative Elements > JS personnalisé     */
/* OU dans un widget HTML en bas de page entouré de       */
/* balises <script>...</script>                           */
/* ==================================================== */

(function () {
  'use strict';

  function init() {
    initFAQ();
    initSmoothScroll();
  }

  // ============ FAQ ACCORDÉON ============
  function initFAQ() {
    var faqContainers = document.querySelectorAll('[data-ifx-cpc-faq]');
    if (!faqContainers.length) return;

    faqContainers.forEach(function (container) {
      var items = container.querySelectorAll('.ifx-cpc-faq-item');

      items.forEach(function (item) {
        var btn = item.querySelector('.ifx-cpc-faq-q');
        if (!btn) return;

        btn.setAttribute('aria-expanded', 'false');

        btn.addEventListener('click', function () {
          var isOpen = item.classList.contains('is-open');

          // Comportement accordéon : ferme les autres items du même groupe
          items.forEach(function (other) {
            if (other !== item) {
              other.classList.remove('is-open');
              var otherBtn = other.querySelector('.ifx-cpc-faq-q');
              if (otherBtn) otherBtn.setAttribute('aria-expanded', 'false');
            }
          });

          if (isOpen) {
            item.classList.remove('is-open');
            btn.setAttribute('aria-expanded', 'false');
          } else {
            item.classList.add('is-open');
            btn.setAttribute('aria-expanded', 'true');
          }
        });
      });
    });
  }

  // ============ SMOOTH SCROLL POUR ANCRES INTERNES ============
  function initSmoothScroll() {
    var links = document.querySelectorAll('.ifx-configurateur-pc a[href^="#"]');
    links.forEach(function (link) {
      link.addEventListener('click', function (e) {
        var href = link.getAttribute('href');
        if (href.length <= 1) return;
        var target = document.querySelector(href);
        if (!target) return;
        e.preventDefault();
        var offset = 80;
        var top = target.getBoundingClientRect().top + window.pageYOffset - offset;
        window.scrollTo({ top: top, behavior: 'smooth' });
      });
    });
  }

  // ============ DÉMARRAGE ============
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();