jQuery(document).ready(function($){
    const sliderContainer = $('#zs_webp_test_slider_container');
    const beforeImg = $('#before_img');
    const afterImg = $('#after_img');
    const sliderHandle = $('.slider-handle');
    const overlay = $('.img-comp-overlay');
    const sourceInfo = $('#zs_webp_source_info');
    const labelWebP = $('#webp-label');
    const labelPNG = $('#png-label');
    let dragging = false;

    function waitForImagesToLoad(callback) {
        let loadedCount = 0;

        function checkLoaded() {
            loadedCount++;
            if (loadedCount === 2) {
                callback();
            }
        }

        // If already loaded (from cache)
        if (beforeImg[0].complete) checkLoaded();
        else beforeImg.on('load', checkLoaded).on('error', function () {
            console.error("Before image failed to load.");
        });

        if (afterImg[0].complete) checkLoaded();
        else afterImg.on('load', checkLoaded).on('error', function () {
            console.error("After image failed to load.");
        });
    }

    //function setOverlayWidth(percent) {
    //    overlay.width(percent + '%');
    //    sliderHandle.css('left', percent + '%');
    //}
    function setOverlayWidth(percent) {
        $('.img-comp-overlay').css('width', percent + '%');
        $('.slider-handle').css('left', percent + '%');
    }

    // Then call this function
    waitForImagesToLoad(function () {
        $('.img-comp-container').fadeIn();
        //initializeSlider(); // Your custom slider logic

        // Initialize slider position to 50%
        setOverlayWidth(50);

        // Draggable handle
        sliderHandle.on('mousedown touchstart', function(e) {
            e.preventDefault();
            dragging = true;
        });
        $(document).on('mouseup touchend', function() {
            dragging = false;
        });
        $(document).on('mousemove touchmove', function(e) {
            if (!dragging) return;
            let containerOffset = sliderContainer.offset().left;
            let pageX = e.pageX || e.originalEvent.touches[0].pageX;
            let pos = pageX - containerOffset;
            let width = sliderContainer.width();
            let percent = Math.min(Math.max(pos / width * 100, 0), 100);
            setOverlayWidth(percent);
        });

        // Click on any webp sample to load before/after
        $('#zs_webp_test_images img').click(function(){
            let basename = $(this).data('basename');
            $.post(zsWebpTest.ajax_url, {
                action: 'zs_convert_png_to_webp',
                nonce: zsWebpTest.nonce,
                basename: basename,
                quality: $('#zs_webp_quality_slider').val()
            }, function(response){
                if (response.success) {
                    let originalPNG = zsWebpTest.plugin_url + 'samples/' + basename + '.png';
                    let convertedWebP = response.data.webp_url;
                    beforeImg.attr('src', originalPNG);
                    afterImg.attr('src', convertedWebP);
                    labelWebP.html('WebP [' + response.data.webp_size + ' KBytes]');
                    labelPNG.html('PNG [' + response.data.png_size + ' KBytes]');
                    sourceInfo.html('Source: <a href="' + response.data.source_info + '" target="_blank">' + response.data.source_info + '</a>');
                    sliderContainer.show();
                    setOverlayWidth(50);
                } else {
                    alert(response.data || 'Error loading images');
                }
            });
        });
    });
});
