jQuery(function ($) {
  console.log('salut');

  // MENU BURGER
  const burger = document.getElementById("block-burger");
  const burgertitle = document.getElementById("block-burger-menu");
  if (burger && burgertitle) {
    burgertitle.addEventListener("click", function () {
      burger.classList.toggle('opened');
    });
  }

  // FAQ — réponses
  const answers = document.getElementsByClassName("field--name-field-reponse");
  const fichiers = document.getElementsByClassName("field--name-field-fichiers");
  const liens = document.getElementsByClassName("field--name-field-liens");
  const ressources = document.getElementsByClassName("field--name-field-ress");
  const questions = document.getElementsByClassName("field--name-field-question");

  for (let i = 0; i < questions.length; i++) {
    const q = questions[i];
    q.addEventListener("click", function () {
      // Réponses
      Array.from(answers).forEach(a => a.classList.remove("opened"));
      const r = this.parentNode.querySelector(".field--name-field-reponse");
      if (r) r.classList.add("opened");

      // Fichiers
      Array.from(fichiers).forEach(f => f.classList.remove("opened"));
      const f = this.parentNode.querySelector(".field--name-field-fichiers");
      if (f) f.classList.add("opened");

      // Liens
      Array.from(liens).forEach(l => l.classList.remove("opened"));
      const l = this.parentNode.querySelector(".field--name-field-liens");
      if (l) l.classList.add("opened");

      // Ressources
      Array.from(ressources).forEach(r => r.classList.remove("opened"));
      const res = this.parentNode.querySelector(".field--name-field-ress");
      if (res) res.classList.add("opened");
    });
  }

  // SLIDESHOW INIT
  $('.path-frontpage .view-actus-blocks-pages .view-content .view-type-slide .views-row-wrapper').slick({
    slidesToShow: 1,
    dots: true,
    arrows: true,
    centerMode: true,
    responsive: [{
      breakpoint: 810,
      settings: {
        slidesToShow: 1,
        adaptiveHeight: true,
        arrows: false,
        draggable: true,
        centerMode: true,
      }
    }]
  });

  $('.page-node-type-actualite .block-entity-fieldnodefield-images .field--type-image').slick({
    dots: true,
    arrows: true,
    adaptiveHeight: true,
    responsive: [{
      breakpoint: 800,
      settings: { adaptiveHeight: true }
    }]
  });

  $('.page-node-type-projet .block-entity-fieldnodefield-photo .field--type-image').slick({
    slidesToShow: 1,
    dots: true,
    arrows: false,
    draggable: true,
    adaptiveHeight: true,
    responsive: [{
      breakpoint: 800,
      settings: { adaptiveHeight: true }
    }]
  });
 


  
  
  ///// fusion views-type-slide de class identique ////////////

    const seen = new Set();
  
    $('.view-type-slide').each(function () {
      const $slide = $(this);
      const classes = $slide.attr('class').split(/\s+/);
      const typeClass = classes.find(cls => cls.startsWith('type-'));
  
      if (typeClass) {
        if (seen.has(typeClass)) {
          // Trouver le premier slide avec cette classe
          const $target = $('.view-type-slide.' + typeClass).first();
  
          // Déplacer les rows de la slide actuelle vers la première
          $slide.find('.views-row').appendTo($target.find('.views-row-wrapper'));
  
          // Supprimer la slide en double
          $slide.remove();
        } else {
          seen.add(typeClass);
        }
      }
    });

    $('.path-ressources .view:not(.view-partenaires) .view-content .view-type-slide .views-row-wrapper').slick({
      slidesToShow: 3,
      dots: false,
      arrows: true,
      infinite: false,
      centerMode: false,
      draggable: true,

      responsive: [{
        breakpoint: 810,
        settings: {
          slidesToShow: 3,
          arrows: false,
          draggable: true,
          centerMode: true,
        }
      }]
    });

  // Classes media → .wrapper-ressource
  $(".wrapper-ressource").each(function () {
    const media = $(this).find(".field--name-field-type-de-media").text().trim();
    const className = media
      .toLowerCase()
      .normalize("NFD").replace(/[\u0300-\u036f]/g, "")
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)/g, '');
    $(this).addClass('type-media-' + className);
  });
  console.log("classses media");

    // MASQUER TYPE DE RESSOURCE DOUBLON
  if (document.body.classList.contains("path-ressources")) {
    $(".view-type-slide").each(function () {
      const h3Content = $(this).find("h3").text().trim();
      console.log(h3Content);
      $(this).find(".field--name-field-type-de-ressource .field__item a").each(function () {
        if ($(this).text().trim() === h3Content) {
          $(this).hide();
        }
      });
    });

  }

  // Ouvrir les liens externes dans un nouvel onglet
  document.querySelectorAll('a[href^="http"]').forEach(link => {
    if (!link.href.includes(location.hostname)) {
      link.setAttribute('target', '_blank');
      link.setAttribute('rel', 'noopener noreferrer');
    }
  });

  // Scroll automatique au filtre
  if (document.body.classList.contains("path-projets")) {
    const form = document.querySelector(".views-exposed-form");
    if (form) form.setAttribute("action", form.action.split("#")[0] + "#filtres");

    if (window.location.hash === "#filtres") {
      const target = document.getElementById("filtres");
      if (target) {
        const offset = 300;
        const top = target.getBoundingClientRect().top + window.pageYOffset - offset;
        window.scrollTo({ top: top, behavior: "smooth" });
      }
    }


  }
});
/////////////////diaporama ressource //////////
document.addEventListener('DOMContentLoaded', function () {
  // Attendre que les éléments HTML soient bien présents
  const interval = setInterval(() => {
    const mainImage = document.getElementById('mainImage');
    const prevArrow = document.getElementById('prevArrow');
    const nextArrow = document.getElementById('nextArrow');
    const caption = document.getElementById('caption');
    const thumbsContainer = document.getElementById('thumbnails');
    const imagesInDom = document.querySelectorAll('.carousel-items .carousel-item img');

    if (mainImage && prevArrow && nextArrow && caption && thumbsContainer && imagesInDom) {
      clearInterval(interval); // Tous les éléments sont là, on lance le carrousel
      initCarousel({ mainImage, prevArrow, nextArrow, caption, thumbsContainer });
    }
  }, 100); // vérifie toutes les 100ms
});
function initCarousel({ mainImage, prevArrow, nextArrow, caption, thumbsContainer }) {
  const images = [];
  document.querySelectorAll('.carousel-items .carousel-item img').forEach((img) => {
    images.push({
      src: img.getAttribute('src'),
      caption: img.getAttribute('alt') || 'Image sans légende'
    });
  });
  console.log('Images chargées pour le carrousel :', images);

  if (!images.length) return;

  let currentIndex = 0;

  function showImage(index) {
    mainImage.src = images[index].src;
    caption.textContent = images[index].caption;

    const thumbnails = document.querySelectorAll('.thumbnails img');
    thumbnails.forEach(img => img.classList.remove('active'));
    if (thumbnails[index]) {
      thumbnails[index].classList.add('active');
    }
  }

  prevArrow.addEventListener('click', () => {
    currentIndex = (currentIndex - 1 + images.length) % images.length;
    showImage(currentIndex);
  });

  nextArrow.addEventListener('click', () => {
    currentIndex = (currentIndex + 1) % images.length;
    showImage(currentIndex);
  });

  images.forEach((img, index) => {
    const thumb = document.createElement('img');
    thumb.src = img.src;
    thumb.alt = img.caption;
    thumb.onclick = () => {
      currentIndex = index;
      showImage(index);
    };
    thumbsContainer.appendChild(thumb);
  });

  showImage(currentIndex);
  const thumbPrev = document.getElementById('thumbPrev');
  const thumbNext = document.getElementById('thumbNext');

  thumbPrev.addEventListener('click', () => {
    thumbsContainer.scrollBy({ left: -150, behavior: 'smooth' });
  });

  thumbNext.addEventListener('click', () => {
    thumbsContainer.scrollBy({ left: 150, behavior: 'smooth' });
  });

}
