function reloadScript(scriptUrl) {
  // Remove the existing script tag if it exists
  $(`script[src*="${scriptUrl}"]`).remove();

  // Create a new script tag with a cache-busting query parameter
  const timestamp = new Date().getTime();
  const newScript = document.createElement('script');
  newScript.src = `${scriptUrl}?t=${timestamp}`;
  newScript.type = 'text/javascript';

  // Append the script tag to the <body> instead of <head>
  document.body.appendChild(newScript);
}

function reloadCss(cssUrl) {
  // Get the existing <link> tag
  const linkElement = $(`link[href*="${cssUrl}"]`);
  if (linkElement.length === 0) return;

  // Create a new <link> tag for preloading the CSS
  const timestamp = new Date().getTime();
  const newHref = `${cssUrl.split('?')[0]}?t=${timestamp}`;

  const preloadLink = document.createElement('link');
  preloadLink.rel = 'preload';
  preloadLink.as = 'style';
  preloadLink.href = newHref;

  // When preload is complete, update the existing <link> tag
  preloadLink.onload = () => {
    preloadLink.rel = 'stylesheet';
    linkElement.attr('href', newHref);
    document.head.removeChild(preloadLink);
  };

  // Append the preload link to the <head>
  document.head.appendChild(preloadLink);
}

// Function to update the progress bar
if (typeof runMode !== 'undefined' && runMode === true) {
  $('img').closest('figure, picture').addClass('loaded-image');
  $('[onclick="window.location.href=\'#\'"]').removeAttr('onclick').css('pointer-events', 'none');
} else {
  $(function () {
    $('.section-inspector').each(function (index) {
      const section = $(this);
      const sectionId = section.attr('id');

      if (sectionId) {
        const match = sectionId.match(/^([a-zA-Z0-9_-]+)-(\d+)$/);

        if (match === null) return;

        const sectionName = match[1];
        const objectId = match[2];

        const baseUrl = `${window.location.origin}${window.location.pathname.split('/').slice(0, -1).join('/')}/`;
        const sectionUrl = `${baseUrl}objet-${objectId}`;

        // Create the dropdown menu
        const dropdownMenu = $(`
          <div class="dropdown-menu-container dropdown-inspector" id="dropdown-menu-${sectionId}">
            <ul class="dropdown-menu list-style-none" style="display: block;">
              <li><a class="dropdown-item copy-id" href="javascript:void(0)" data-clipboard-text="${objectId}"><span><i class="icon icon--copy"></i> Copy ID</span></a></li>
              <li><a class="dropdown-item copy-name" href="javascript:void(0)" data-clipboard-text="${sectionName}"><span><i class="icon icon--copy"></i>  Copy Section Name</span></a></li>
              <li><a class="dropdown-item go-to-view" href="${sectionUrl}" target="_blank"><span><i class="icon icon--view"></i> Open in New Tab</span></a></li>
              <li><a class="dropdown-item refresh-section" href="javascript:void(0)"><span><i class="icon icon--refresh"></i> Reload Content</span></a></li>
            </ul>
          </div>
        `);


        // Show the dropdown on double-click
        section.on('dblclick', function (event) {
          $('.dropdown-menu-container').detach();
          $('body').append(dropdownMenu);
          const menu = $(`#dropdown-menu-${sectionId}`);
          menu.css({
            position: 'fixed',
            top: event.clientY,
            left: event.clientX,
            visibility: 'visible',
            zIndex: 9999
          });
        });

        // Hide the dropdown when clicking outside
        $(document).on('click', function (event) {
          if (!$(event.target).closest('.dropdown-menu-container').length) {
            $('.dropdown-menu-container').detach();
          }
        });

        // Refresh section functionality
        dropdownMenu.on('click', '.refresh-section', function () {
          $.ajax({
            url: sectionUrl,
            type: 'GET',
            cache: false, // Disable caching
            success: function (data) {
              try {
                const newContent = $(data).find(`#${sectionId}`).html();
                section.html(newContent);
                reloadCss($('link[href*="assets/css/addons.css"]').attr('href'));
                reloadCss($('link[href*="assets/css/objet.css"]').attr('href'));
                reloadScript($('script[src*="assets/js/_init/helpers.js"]').attr('src'));
                reloadScript($('script[src*="assets/js/objet.js"]').attr('src'));
                $('.dropdown-menu-container').detach();
              } catch (error) {
                alert('Failed to refresh the section. Please try again later.');
              }
            },
            error: function () {
              alert('Failed to refresh the section. Please try again later.');
            }
          });
        });
      }
    });

    $('[onclick="window.location.href=\'#\'"]').removeAttr('onclick').css('pointer-events', 'none');

    // Clipboard functionality
    const clipboard = new ClipboardJS('.copy-id, .copy-name');

    clipboard.on('success', function (e) {
      const target = $(e.trigger);
      const originalText = target.find('span').text(); // Store the original text (excluding the icon)

      // Update text inside <span> without removing the icon
      target.addClass('copied');
      target.find('span').contents().last().replaceWith(' Copied!');

      // Restore the original text after 2 seconds
      setTimeout(() => {
        target.find('span').contents().last().replaceWith(` ${originalText}`);
        target.removeClass('copied');
      }, 2000);

      e.clearSelection();
    });

    clipboard.on('error', function () {
      alert('Failed to copy text. Please try again.');
    });

    $(window).on('scroll', function () {
      $('.dropdown-menu-container').detach();
    });

  });

  $(function () {
    /**
     * Simple helper to check if a string ends with .svg
     */
    function isSVG(url) {
      return url.toLowerCase().endsWith('.svg');
    }

    /**
     * Attempt to compute rendered dimensions of the <img>.
     * If width/height are 0 (image not loaded), fall back to the parent container size
     * or a default.
     */
    function getRenderedDimensions($img) {
      let w = $img.width();
      let h = $img.height();

      // If the image has not actually rendered, we might get 0 × 0
      if (!w || !h) {
        const $parent = $img.parent();
        w = $parent.width() || 300;  // fallback width
        h = $parent.height() || 200; // fallback height
      }

      return { width: w, height: h };
    }

    /**
     * Generates a placeholder image URL (e.g. from picsum.photos) based on
     * the *rendered dimensions* of the <img>, with extra padding.
     */
    function generatePlaceholderUrl($img) {
      const { width, height } = getRenderedDimensions($img);
      // Add ~100px to each dimension, as in your original code
      const w = Math.floor(width) + 100;
      const h = Math.floor(height) + 100;
      // Generate a random query to avoid caching the same placeholder
      return `https://picsum.photos/${w}/${h}?random=${Math.floor(Math.random() * 1e7)}`;
    }

    /**
     * Applies a placeholder to the <img>:
     * 1. Removes srcset (and any <source> tags if inside <picture>)
     * 2. Sets the "broken-image" class on the <figure>, if present
     */
    function applyPlaceholder($img) {
      const placeholderUrl = generatePlaceholderUrl($img);
      console.debug('Applying placeholder:', placeholderUrl);

      // Remove srcset on the <img> so the browser won’t try to pick other sizes
      $img.removeAttr('srcset');

      // Remove all <source> children if inside a <picture>
      const $picture = $img.closest('picture');
      if ($picture.length) {
        $picture.find('source').remove();
      }

      // Replace with the placeholder
      $img.attr('src', placeholderUrl);

      // Mark the parent figure (optional, for CSS styling)
      $img.closest('figure, picture').removeClass('loaded-image').addClass('broken-image');
    }

    /**
     * Helper to check load success/failure using a Promise.
     * - We create a temporary <img> in memory to test the URL from currentSrc.
     */
    function testImageLoad(url) {
      return new Promise((resolve, reject) => {
        if (!url || !/^https?:\/\//i.test(url)) {
          return reject('Invalid image URL');
        }

        const testImg = new Image();
        // Attach events
        testImg.onload = () => {
          // For SVGs, naturalWidth can be 0, so we skip that check
          if (!isSVG(url) && testImg.naturalWidth === 0) {
            return reject('Image loaded but naturalWidth=0');
          }
          resolve('Image loaded successfully');
        };
        testImg.onerror = () => reject('Error loading image');
        // Start load
        testImg.src = url;
      });
    }

    /**
     * Main logic: for each <picture> or <img>, figure out which URL is actually
     * being used (via .currentSrc) and test-load it. If it fails, we apply a placeholder.
     */
    $('picture, img:not(.captcha-image)').each(function () {
      // If it's <picture>, find the fallback <img> inside
      let $img;
      if ($(this).is('picture')) {
        $img = $(this).find('img');
        if ($img.length === 0) return; // no fallback <img> = no check
      } else {
        // It's an <img>
        $img = $(this);
      }

      // Get the actual resource used (due to <picture> media matching) from .currentSrc
      // If the browser doesn’t support currentSrc, fallback to the img src attribute.
      const imgEl = $img[0];
      const chosenUrl = imgEl.currentSrc || $img.attr('src');

      // Now test-load that chosen URL
      testImageLoad(chosenUrl)
        .then((msg) => {
          console.debug(msg, chosenUrl);
          // Mark the <figure> as loaded
          $img.closest('figure, picture')
            .removeClass('broken-image')
            .addClass('loaded-image');
        })
        .catch((err) => {
          console.debug(err, chosenUrl);
          // If it fails, apply placeholder
          applyPlaceholder($img);
          $img.data('broken-src', chosenUrl);
        });
    });
  });

  $(function () {
    $('[onclick="window.location.href=\'#\'"]').removeAttr('onclick').css('pointer-events', 'none');
  });
}

function updateProgressBar() {
  const scrollTop = $(document).scrollTop();
  const scrollHeight = $(document).height();
  const windowHeight = $(window).height();
  const scrollPercent = (scrollTop / (scrollHeight - windowHeight)) * 100 + "%";
  $("#progress-bar").css("--progress", scrollPercent);
}

$.fn.isInViewport = function () {
  var elementTop = $(this).offset().top;
  var elementBottom = elementTop + $(this).outerHeight();

  var viewportTop = $(window).scrollTop();
  var viewportBottom = viewportTop + $(window).height();

  return elementBottom > viewportTop && elementTop < viewportBottom;
};

// Attach the updateProgressBar function to the scroll event
$(document).scroll(updateProgressBar);

$(function () {
  var primaryColor = $(':root').css('--ev-primary');

  if (primaryColor) {
    primaryColor = primaryColor.trim();
    $('meta[name="theme-color"]').attr('content', primaryColor);
  }

  var currentPath = window.location.pathname; // Get the current path

  // Remove any trailing slashes for consistent comparison
  currentPath = currentPath.replace(/\/$/, "");

  // Loop through each nav-link and dropdown-item
  $('.navbar-nav :not(.nav-item--home) .nav-link, .navbar-nav .dropdown-item').each(function () {
    var linkPath = $(this).attr('href'); // Get the href attribute of the link

    // Remove trailing slashes for consistency in comparison
    linkPath = linkPath.replace(/\/$/, "");

    // If the current path starts with the link path, add 'active' class
    if (currentPath.startsWith(linkPath)) {
      $(this).addClass('active'); // Add 'active' class to the <a> element
      $(this).parent().addClass('active'); // Also add 'active' to the parent <li> element for nav items
    }
  });

  // Special case for the home link (assuming it's the root URL '/')
  if (!$('.nav-item.active').length) {
    if (currentPath.endsWith('') || currentPath.endsWith('/') || currentPath.endsWith('public/')) {
      $('.nav-item--home').addClass('active'); // Add 'active' class to the home link
    }
  }

  // Define the function normally (not as an IIFE)
  function setupCollapseToggler() {
    // Remove any existing handlers to avoid duplicating handlers
    $('#collapseToggler').off('click').on('click', function () {
      if ($(".collapse-body").hasClass('collapsed')) {
        $(this).find('.icon').removeClass('icon--plus').addClass('icon--minus');
        $(".collapse-body").removeClass('collapsed');
      } else {
        $(this).find('.icon').removeClass('icon--minus').addClass('icon--plus');
        $(".collapse-body").addClass('collapsed');
      }
    });
  }

  // Attach the event handler
  setupCollapseToggler();


  // Convert phone number in best format
  const formatPhoneNumber = (phoneNumber) => {
    const cleaned = phoneNumber.replace(/\D/g, '');
    if (cleaned.length === 10) {
      return `${cleaned.slice(0, 2)} ${cleaned.slice(2, 4)} ${cleaned.slice(4, 6)} ${cleaned.slice(6, 8)} ${cleaned.slice(8)}`;
    }
    return phoneNumber;
  };

  const $phoneNumber = $('#phoneNumber');
  $phoneNumber.text((index, currentText) => formatPhoneNumber(currentText));

  // Convert 'rel=preload' to 'rel=stylesheet' for link elements
  $('link[rel="preload"][as="style"]').each(function () {
    if ($(this).attr("rel") === "preload") {
      $(this).attr("rel", "stylesheet");
    }
  });

  // Strip HTML tags from 'alt' attributes of image elements
  $("img[alt]").each(function () {
    var stringWithTags = $(this).attr("alt");
    var strippedString = $("<div>").html(stringWithTags).text();
    $(this).attr("alt", strippedString);
  });

  // Set target attribute to "_blank" for external links
  $("a")
    .filter(function () {
      return this.hostname && this.hostname !== window.location.hostname;
    })
    .attr("target", "_blank");

  // Handle select change event to redirect based on selected value
  $("[rel='js-discover-select']").change(function () {
    window.location.replace($(this).val());
  });

  // Initialize the rotation degree for each Icon arrow
  $("[rel='js-btn-arrow'] .icon").each(function () {
    $(this).data("deg", -90).css({ transform: "rotate(0deg)" });
  });

  // Click event handler
  $("[rel='js-btn-arrow']").on("click", function (event) {
    event.preventDefault();
    var dropdown = $(this).closest(".dropdown").find(".dropdown-menu");
    var isOpen = dropdown.hasClass("show");

    // Determine the new rotation angle
    var rotation = isOpen ? 0 : 90;

    // Find the Icon within the clicked element
    var icon = $(this).find(".icon");
    var currentDeg = icon.data("deg");

    // Animate the rotation
    $({ deg: currentDeg }).animate(
      { deg: rotation },
      {
        duration: 150,
        step: function (now) {
          icon.css({ transform: "rotate(" + now + "deg)" });
        },
        complete: function () {
          // Update the dropdown visibility
          if (isOpen) {
            dropdown.removeClass("show");
          } else {
            dropdown.addClass("show");
          }
          // Update the stored rotation degree
          icon.data("deg", rotation);
        },
      }
    );
  });

  // Initialize clipboard functionality
  var clipboard = new ClipboardJS("#clipboardBtn");

  // Handle clipboard success
  $("#clipboardBtn").on("click", function () {
    clipboard.on('success', function () {
      $("#clipboardBtn").addClass('copied');
    });
  });

  $('.modal').each(function () {
    $(this).appendTo('body');
  });
});