(function ($) {
        "use strict";
            var WidgetScrollSequenceHandler = function($scope, $) { 
                let is_editable = elementorFrontend?.isEditMode();
                let clickTmedia = $scope[0].querySelector('.wkit-click-to-media');

let allMedia = clickTmedia.querySelectorAll('.media-item');
let imageArr = [], videoArr = [], textArr = [], externalVideoArr = [];
let videoload = false;

allMedia.forEach((media) => {
    let imageWrap = media.querySelector('.image-url');
    let videoWrap = media.querySelector('.video-url');
    let textWrap = media.querySelector('.text');
    let externalWrap = media.querySelector('.external-url');

    if (media.classList.contains('type-image')) {
        let imageURL = imageWrap?.innerHTML;
        imageWrap?.remove();
        videoWrap?.remove();
        textWrap?.remove();
        externalWrap?.remove();
        if (imageURL) imageArr.push(imageURL);
    }

    if (media.classList.contains('type-video')) {
        let videoURL = videoWrap?.innerHTML;
        videoWrap?.remove();
        imageWrap?.remove();
        textWrap?.remove();
        externalWrap?.remove();
        if (videoURL) {
            videoArr.push(videoURL);
            videoload = true;
        }
    }

if (media.classList.contains('type-text')) {
    let text = textWrap?.innerHTML;
    let color = textWrap?.getAttribute('data-color') || '';
    let classList = Array.from(textWrap?.classList || []).join(' ');
    let typoClasses = textWrap?.getAttribute('data-typo') || '';

    let typo = {};

    // From data-typo class keywords
    if (typoClasses.includes('weight-bold')) typo.fontWeight = '700';
    if (typoClasses.includes('weight-light')) typo.fontWeight = '300';
    if (typoClasses.includes('italic')) typo.fontStyle = 'italic';
    if (typoClasses.includes('uppercase')) typo.textTransform = 'uppercase';
    if (typoClasses.includes('underline')) typo.textDecoration = 'underline';
    if (typoClasses.includes('size-xl')) typo.fontSize = '2rem';
    if (typoClasses.includes('size-md')) typo.fontSize = '1rem';
    if (typoClasses.includes('spacing-wide')) typo.letterSpacing = '0.05em';

    // ✅ Fallback from computed style (before removing element!)
// ✅ Fallback from computed style (before removing element!)
const computed = window.getComputedStyle(textWrap);
typo.fontSize = typo.fontSize || computed.getPropertyValue('font-size');
typo.fontWeight = typo.fontWeight || computed.getPropertyValue('font-weight');
typo.lineHeight = typo.lineHeight || computed.getPropertyValue('line-height');
typo.letterSpacing = typo.letterSpacing || computed.getPropertyValue('letter-spacing');
typo.textTransform = typo.textTransform || computed.getPropertyValue('text-transform');
typo.textDecoration = typo.textDecoration || computed.getPropertyValue('text-decoration');
typo.fontStyle = typo.fontStyle || computed.getPropertyValue('font-style');

    if (text) {
        textArr.push({
            content: text,
            color,
            className: classList,
            typo,
        });
    }

    // ✅ Only now remove
    textWrap?.remove();
    imageWrap?.remove();
    videoWrap?.remove();
    externalWrap?.remove();
}

    if (media.classList.contains('type-url')) {
        let externalURL = externalWrap?.innerHTML;
        externalWrap?.remove();
        textWrap?.remove();
        imageWrap?.remove();
        videoWrap?.remove();
        if (externalURL) {
            externalVideoArr.push(externalURL);
            videoload = true;
        }
    }
});

let getContainer = clickTmedia.closest('.e-con');
const itemsArray = [];

const mediaData = { imageArr, videoArr, textArr, externalVideoArr };

getContainer.addEventListener("click", function (event) {
    const availableTypes = [];
    if (videoArr.length || externalVideoArr.length) availableTypes.push('video');
    if (imageArr.length) availableTypes.push('image');
    if (textArr.length) availableTypes.push('text');

    if (!availableTypes.length) return;

    const itemType = availableTypes[Math.floor(Math.random() * availableTypes.length)];
    let container = document.createElement("div");
    let elementWidth = 0;

    if (itemType === "video") {
        const isExternal = Math.random() < 0.5 && externalVideoArr.length;
        if (isExternal) {
            const extURL = externalVideoArr[Math.floor(Math.random() * externalVideoArr.length)];
// Add autoplay=1 and mute=1 to avoid browser blocking
const autoplayURL = extURL.includes('?') ? `${extURL}&autoplay=1&mute=1` : `${extURL}?autoplay=1&mute=1`;

container.innerHTML = `<div class="video-container external">
    <iframe src="${autoplayURL}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>`;

        } else {
            const videoSrc = videoArr[Math.floor(Math.random() * videoArr.length)];
            container.innerHTML = `<div class="video-container">
                                     <video autoplay loop muted>
                                       <source src="${videoSrc}" type="video/mp4"/>
                                     </video>
                                   </div>`;
        }
    } 
 else if (itemType === "text") {
    const textItem = textArr[Math.floor(Math.random() * textArr.length)];
    const typo = textItem.typo || {};

    const span = document.createElement("span");
    span.className = `text-inner ${textItem.className}`.trim();
    span.textContent = textItem.content;

    // ✅ Apply all typography via JS
    if (textItem.color) span.style.color = textItem.color;
    if (typo.fontFamily) span.style.fontFamily = typo.fontFamily;
    if (typo.fontSize) span.style.fontSize = typo.fontSize;
    if (typo.fontWeight) span.style.fontWeight = typo.fontWeight;
    if (typo.lineHeight) span.style.lineHeight = typo.lineHeight;
    if (typo.letterSpacing) span.style.letterSpacing = typo.letterSpacing;
    if (typo.textTransform) span.style.textTransform = typo.textTransform;
    if (typo.textDecoration) span.style.textDecoration = typo.textDecoration;
    if (typo.fontStyle) span.style.fontStyle = typo.fontStyle;

    const wrapper = document.createElement("div");
    wrapper.className = "text-container";
    wrapper.appendChild(span);

    container.appendChild(wrapper);
}

else {
        const imgSrc = imageArr[Math.floor(Math.random() * imageArr.length)];
        container.innerHTML = `<div class="img-container">
                                 <img src="${imgSrc}" alt="Random Image" />
                               </div>`;
    }
const animatedEl = container.querySelector('.text-container') || container.firstChild;
appendAndAnimateElement(animatedEl, event.clientX, event.clientY, elementWidth);



});
function appendAndAnimateElement(element, clientX, clientY, elementWidth) {
    if (!element) return;

    getContainer.appendChild(element);

    // Positioning logic
    element.style.position = 'absolute';
    element.style.left = `${clientX - elementWidth / 1}px`;
    element.style.top = `${clientY}px`;

    const randomRotation = Math.random() * 10 - 5;

    // Animation init
    gsap.set(element, {
        scale: 0,
        rotation: randomRotation,
        transformOrigin: "center",
        opacity: 0,
    });

    const tl = gsap.timeline();
    const randomScale = Math.random() * 0.4 + 0.3;

    // Scale in
    tl.to(element, {
        scale: randomScale,
        opacity: 1,
        duration: 0.5,
    });

    // Float up
    tl.to(
        element,
        {
            y: `-=${500}`,
            duration: 4,
            ease: "none",
        },
        "<"
    ).to(
        element,
        {
            opacity: 0,
            duration: 1,
            onComplete: () => {
                element.remove();
                const index = itemsArray.indexOf(element);
                if (index > -1) itemsArray.splice(index, 1);
            },
        },
        "-=0.5"
    );
}
  
            };	
        $(window).on('elementor/frontend/init', function () {
          elementorFrontend.hooks.addAction('frontend/element_ready/wb-adnz4f24.default', WidgetScrollSequenceHandler);
        });
    })(jQuery);