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: true,
    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);
        }
      }
    });
    if (!$('.view-content').hasClass('filtered')) {
      $('.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: 1,
            dots: false,
            arrows: true,
            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" });
      }
    }


  }
});

/////////////////start diaporama ressource //////////
document.addEventListener('DOMContentLoaded', function () {
  // Vérifie que le body a la classe souhaitée
  if (!document.body.classList.contains('type-media-images---photos')) return;

  // 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.length > 0) {
      clearInterval(interval); // Tous les éléments sont là, on lance le carrousel
      initCarousel({ mainImage, prevArrow, nextArrow, caption, thumbsContainer });
    }
  }, 100);
});

function initCarousel({ mainImage, prevArrow, nextArrow, caption, thumbsContainer }) {
  const images = [];
  // Adapter l'orientation des vignettes si écran < 810px
function applyResponsiveThumbnailsLayout() {
  if (window.innerWidth < 810) {
    thumbsContainer.style.flexDirection = 'row';
    thumbsContainer.style.flexWrap = 'nowrap';
    thumbsContainer.style.overflowX = 'auto';
    thumbsContainer.style.overflowY = 'hidden';
    thumbsContainer.style.display = 'flex';
    thumbsContainer.style.justifyContent = 'center';
  } else {
    thumbsContainer.style.flexDirection = 'column';
    thumbsContainer.style.overflowY = 'auto';
    thumbsContainer.style.overflowX = 'hidden';
  }
}
applyResponsiveThumbnailsLayout();
window.addEventListener('resize', applyResponsiveThumbnailsLayout);

  document.querySelectorAll('.carousel-items .carousel-item img').forEach((img) => {
    images.push({
      src: img.getAttribute('src'),
      caption: img.getAttribute('alt') || ''
    });
  });

  if (!images.length) return;

  let currentIndex = 0;

  // function scrollThumbnailToCenter(index) {
  //   const thumbnails = document.querySelectorAll('.thumbnails img');
  //   const activeThumb = thumbnails[index];
  //   if (activeThumb && thumbsContainer) {
  //     const containerHeight = thumbsContainer.clientHeight;
  //     const thumbOffsetTop = activeThumb.offsetTop;
  //     const thumbHeight = activeThumb.offsetHeight;
  //     const scrollTarget = thumbOffsetTop - (containerHeight / 2) + (thumbHeight / 2);
  //     thumbsContainer.scrollTo({ top: scrollTarget, behavior: 'smooth' });
  //   }
  // }
  function scrollThumbnailToCenter(index) {
    const thumbnails = document.querySelectorAll('.thumbnails img');
    const activeThumb = thumbnails[index];
    if (activeThumb && thumbsContainer) {
      const isMobile = window.innerWidth < 810;
  
      if (isMobile) {
        // Scroll horizontal
        const containerWidth = thumbsContainer.clientWidth;
        const thumbOffsetLeft = activeThumb.offsetLeft;
        const thumbWidth = activeThumb.offsetWidth;
        const scrollTarget = thumbOffsetLeft - (containerWidth / 2) + (thumbWidth / 2);
        thumbsContainer.scrollTo({ left: scrollTarget, behavior: 'smooth' });
      } else {
        // Scroll vertical
        const containerHeight = thumbsContainer.clientHeight;
        const thumbOffsetTop = activeThumb.offsetTop;
        const thumbHeight = activeThumb.offsetHeight;
        const scrollTarget = thumbOffsetTop - (containerHeight / 2) + (thumbHeight / 2);
        thumbsContainer.scrollTo({ top: scrollTarget, behavior: 'smooth' });
      }
    }
  }
  

  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');
      scrollThumbnailToCenter(index);
    }
  }

  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.addEventListener('click', () => {
      currentIndex = index;
      showImage(index);
    });
    thumbsContainer.appendChild(thumb);
  });

  showImage(currentIndex);

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

  // ✅ Masquer les flèches de thumbnails si pas assez d’images pour scroller
  const thumbHeight = 70; // approx : image + gap
  const visibleCount = Math.floor(thumbsContainer.clientHeight / thumbHeight);
  if (images.length <= visibleCount) {
    if (thumbPrev) thumbPrev.style.display = 'none';
    if (thumbNext) thumbNext.style.display = 'none';
  }

  // Boucle haut/bas avec scroll
  thumbPrev.addEventListener('click', () => {
    if (thumbsContainer.scrollTop <= 0) {
      thumbsContainer.scrollTo({ top: thumbsContainer.scrollHeight, behavior: 'smooth' });
    } else {
      thumbsContainer.scrollBy({ top: -150, behavior: 'smooth' });
    }
  });

  thumbNext.addEventListener('click', () => {
    const maxScrollTop = thumbsContainer.scrollHeight - thumbsContainer.clientHeight;
    if (thumbsContainer.scrollTop >= maxScrollTop - 1) {
      thumbsContainer.scrollTo({ top: 0, behavior: 'smooth' });
    } else {
      thumbsContainer.scrollBy({ top: 150, behavior: 'smooth' });
    }
  });
}

    
/////////////////end diaporama ressource //////////


//////////////////////////start classe en JS si des filtres sont présents///////////
document.addEventListener('DOMContentLoaded', () => {
  if (window.location.search.length > 0) {
    document.querySelector('.view-content')?.classList.add('filtered');
    document.querySelectorAll('.tout-voir').forEach(btn => btn.remove());

  }
});
//////////////////////////end classe en JS si des filtres sont présents///////////

// ////////////////// start tronquage sous titre  //////////////////
  document.addEventListener("DOMContentLoaded", function () {
    const maxLength = 80;

    document.querySelectorAll('.view-base-de-donnees .wrapper-ressource .field--name-field-sous-titre a').forEach(function (element) {
      const fullText = element.textContent.trim();

      if (fullText.length > maxLength) {
        const truncated = fullText.slice(0, maxLength).trim() + '...';
        element.textContent = truncated;
      }
    });
  });
  // //////////////////end tronquage sous titre  //////////////////

////////////////// start boutons media ////////////////

document.addEventListener("DOMContentLoaded", function () {
  const mediaButtons = document.querySelectorAll('.buttons-filtres-ressources a');

  mediaButtons.forEach(button => {
    button.addEventListener('click', function (e) {
      e.preventDefault();

      // Récupérer l’ID media depuis l’URL du bouton
      const url = new URL(button.href);
      const mediaID = url.searchParams.get('field_type_de_media_target_id');

      // Appliquer la valeur dans le <select>
      const select = document.getElementById('edit-field-type-de-media-target-id');
      if (select) {
        select.value = mediaID;
        // Simuler le clic sur le bouton "Appliquer"
        const submit = document.querySelector('input#edit-submit-base-de-donnees');
        if (submit) {
          submit.click();
        }
      }
    });
  });
});
////////////////// end boutons media ////////////////

////////////////// start bouton "Tout voir" ////////////////
document.addEventListener("DOMContentLoaded", function () {
  const toutVoirButtons = document.querySelectorAll('.tout-voir');

  toutVoirButtons.forEach(button => {
    button.addEventListener('click', function () {
      const tid = this.dataset.tid;
      const select = document.getElementById('edit-field-type-de-ressource-target-id');

      if (!select) return;

      const optionExists = Array.from(select.options).some(o => o.value === tid);
      if (!optionExists) {
        alert("Le type de ressource sélectionné n’est pas disponible.");
        return;
      }

      select.value = tid;
      select.dispatchEvent(new Event('change'));

      const form = select.closest('form');
      if (form) {
        const submitButton = form.querySelector('input[type="submit"]');
        if (submitButton) {
          submitButton.click();
        } else {
          form.submit();
        }
      }
    });
  });
});


////////////////// end bouton "Tout voir" ////////////////



////////////// start croix clear input recherche ////////////
document.addEventListener("DOMContentLoaded", function () {
  const input = document.getElementById("edit-combine");
  const clearBtn = document.querySelector('.form-item-combine .clear-input');
  const form = document.querySelector("form.views-exposed-form");

  if (input && clearBtn && form) {
    // Affiche la croix si contenu présent
    input.addEventListener('input', () => {
      clearBtn.style.display = input.value ? 'block' : 'none';
    });

    // Efface et soumet le formulaire
    clearBtn.addEventListener('click', () => {
      input.value = '';
      clearBtn.style.display = 'none';
      input.focus();
      form.submit(); // déclenche la recherche sans rechargement manuel
    });

    // Affiche la croix au chargement si une valeur est déjà présente
    if (input.value) {
      clearBtn.style.display = 'block';
    }
  }
});


////////////// end croix clear input recherche ////////////

