let spDeleteStory, spUpdateStoryPrivacy;


document.addEventListener("DOMContentLoaded", function () {
    "use strict";

    class StorySlider {
        constructor(wrapper) {
            this.wrapper = wrapper;
            this.slider = wrapper.querySelector(".sp-story-slider");
            this.swiperWrapper = wrapper.querySelector(".swiper-wrapper");
            
            this.mode = wrapper.dataset.mode || 'users';
            this.context = wrapper.dataset.context || '';
            this.ajaxAction = wrapper.dataset.ajaxAction || 'storyposts_get_user_stories';
            this.source = wrapper.dataset.source || '';
            this.productFilter = wrapper.dataset.productFilter || '';
            this.limit = parseInt(wrapper.dataset.limit || storypostsStory.settings.stories_per_load || 12, 10);
            
            this.id = 'sp-slider-' + Math.random().toString(36).substr(2, 9);
            this.stories = [];
            this.loadedIds = new Set();
            this.offset = 0;
            this.loading = false;
            this.hasMore = true;
            this.isInitialLoad = true;
            
            this.init();
        }

        init() {
            this.initializeSwiper();
            this.fetchStories();
        }

        initializeSwiper() {
            // Detect layout type from data attribute
            const layout = this.wrapper.dataset.layout || 'card';
            const isAvatarLayout = layout === 'avatar';
            
            // Adjust configuration based on data attributes or defaults
            const slidesPerView = parseInt(this.wrapper.dataset.slidesPerView) || (isAvatarLayout ? 12 : 5);
            const spaceBetween  = parseInt(this.wrapper.dataset.spaceBetween) || (isAvatarLayout ? 12 : 15);
            
            // Store layout type for later use
            this.layout = layout;

            // Cap each breakpoint's fixed default at the admin-configured desktop value.
            const cap = (value) => Math.min(value, slidesPerView);

            this.swiper = new Swiper(this.slider, {
                slidesPerView: slidesPerView,
                spaceBetween: spaceBetween,
                grabCursor: true,
                watchSlidesProgress: true,
                mousewheel: {
                    forceToAxis: true,
                    releaseOnEdges: true,
                    enabled: true,
                    sensitivity: 1,
                },
                breakpoints: {
                    // Mobile (up to 480px)
                    0: {
                        slidesPerView: cap(isAvatarLayout ? 4 : 3),
                        spaceBetween: Math.max(4, spaceBetween * 0.5)
                    },
                    // Small Tablet (480px+)
                    480: {
                        slidesPerView: cap(isAvatarLayout ? 5 : 4),
                        spaceBetween: Math.max(8, spaceBetween * 0.75)
                    },
                    // Tablet Landscape (768px+)
                    768: {
                        slidesPerView: cap(isAvatarLayout ? 7 : 5),
                        spaceBetween: spaceBetween
                    },
                    // Desktop (1024px+)
                    1024: {
                        slidesPerView: slidesPerView,
                        spaceBetween: spaceBetween
                    },
                },
                navigation: {
                    nextEl: this.wrapper.querySelector(".swiper-button-next"),
                    prevEl: this.wrapper.querySelector(".swiper-button-prev")
                },
                on: {
                    init: (swiper) => {
                        const shouldAddClass = swiper.slides.length < slidesPerView;
                        swiper.el.classList.toggle('sp-slider-partial', shouldAddClass);
                    },
                    slidesLengthChange: function() {
                        const shouldAddClass = this.slides.length < slidesPerView;
                        this.el.classList.toggle('sp-slider-partial', shouldAddClass);
                    },
                    reachEnd: () => {
                        if (this.isInitialLoad) {
                            this.isInitialLoad = false;
                            return;
                        }
                        if (this.hasMore) {
                            this.showSkeletonLoading();
                        }
                        this.fetchStories();
                    }
                }
            });
        }

        showSkeletonLoading() {
            this.swiperWrapper.querySelectorAll('.sp-story-skeleton.loading, .sp-story-skeleton-avatar.loading').forEach(s => s.remove());
            
            // Generate skeleton based on layout type
            if (this.layout === 'avatar') {
                this.swiperWrapper.insertAdjacentHTML('beforeend', `
                    <div class="swiper-slide sp-story-skeleton-avatar loading">
                        <div class="sp-story-avatar-ring-skeleton">
                            <div class="sp-story-avatar-circle-skeleton"></div>
                        </div>
                        <div class="sp-story-avatar-name-skeleton"></div>
                    </div>
                `);
            } else {
                this.swiperWrapper.insertAdjacentHTML('beforeend', `
                    <div class="swiper-slide sp-story-skeleton loading">
                        <div class="sp-story-avatar-skeleton"></div>
                        <div class="sp-story-content-skeleton">
                            <div class="sp-story-title-skeleton"></div>
                            <div class="sp-story-meta-skeleton"></div>
                        </div>
                    </div>
                `);
            }
            
            this.swiper.update();
        }

        fetchStories() {
            if (this.loading || !this.hasMore) return;
            this.loading = true;

            fetch(storypostsStory.ajax_url, {
                method: "POST",
                headers: { "Content-Type": "application/x-www-form-urlencoded" },
                body: new URLSearchParams({
                    action: this.ajaxAction,
                    nonce: storypostsStory.nonce,
                    context: this.context,
                    offset: this.offset,
                    limit: this.limit,
                    source: this.source,
                    product_filter: this.productFilter
                })
            })
            .then(res => res.json())
            .then(json => {
                this.loading = false;
                if (json.success && Array.isArray(json.data)) {
                    if (json.data.length < this.limit) {
                        this.hasMore = false;
                    }
                    this.replaceSkeletonsWithRealCards(json.data);
                    this.offset += this.limit;

                    const totalSlides = this.slider.querySelectorAll(".swiper-slide").length;
                    const visibleSlides = this.swiper.params.slidesPerView;
                    if (totalSlides <= visibleSlides + 1 && this.hasMore) {
                        this.fetchStories();
                    }
                } else {
                    this.hasMore = false;
                }
            })
            .catch(err => {
                this.loading = false;
                console.error("Error fetching stories:", err);
                this.swiperWrapper.querySelectorAll('.sp-story-skeleton, .sp-story-skeleton-avatar').forEach(el => el.remove());
                this.swiper.update();
            });
        }

        replaceSkeletonsWithRealCards(items) {

            if (this.offset === 0) {
                // Remove all skeletons (initial from PHP)
                this.swiperWrapper.querySelectorAll('.sp-story-skeleton, .sp-story-skeleton-avatar, .sp-story-avatar-skeleton').forEach(el => el.remove());
                this.slider.classList.remove("skeletons");
                
                // If completely empty (no create button and no stories)
                if (items.length === 0 && this.swiperWrapper.querySelectorAll('.swiper-slide').length === 0) {
                    this.wrapper.innerHTML = `<div class="sp-message warn">${storypostsStory.i18n.no_stories_found || 'No stories found.'}</div>`;
                    return;
                }
            }
            this.appendStoryCards(items);
        }

        appendStoryCards(items) {
            const slides = [];
            items.forEach(item => {
                const globalId = `${this.mode}-${item.id}`;
                if (this.loadedIds.has(globalId)) return;

                const index = this.stories.length;
                this.stories.push(item);
                this.loadedIds.add(globalId);
                slides.push(this.renderStoryCard(item, index));
            });

            if (slides.length) {
                // Remove all loading skeletons (dynamic from JS)
                this.swiperWrapper.querySelectorAll('.sp-story-skeleton.loading, .sp-story-skeleton-avatar.loading').forEach(s => s.remove());
                this.swiperWrapper.insertAdjacentHTML("beforeend", slides.join(""));
                this.attachCardEvents();
            }
            this.swiper.update();
        }

        renderStoryCard(item, index) {
            const isSelf = this.mode === 'users' && item.user_id == storypostsStory.current_user_id;
            const hasUnseen = item.stories.some(s => !s.seen);
            const storyType = isSelf ? 'self' : (hasUnseen ? 'new' : 'viewed');
            
            const poster = item.stories.find(s => !s.seen)?.poster || item.stories[0]?.poster || '';
            const avatar = item.avatar || '';
            const name = item.name || '';
            
            // Render based on layout type
            if (this.layout === 'avatar') {
                return `
                    <div class="swiper-slide sp-story-avatar-item sp-type-${storyType}" 
                        data-instance-id="${this.id}" 
                        data-story-index="${index}">
                        <div class="sp-story-avatar-ring">
                            <div class="sp-story-avatar-circle" style="${avatar ? `background-image: url(${avatar});` : ''}">
                            </div>
                        </div>
                        <div class="sp-story-avatar-name"><span>${name}</span></div>
                    </div>
                `;
            }
            
            // Default card layout
            return `
                <div class="swiper-slide sp-story-card sp-type-${storyType}" 
                    style="${poster ? `background-image: url(${poster});` : ''}" 
                    data-instance-id="${this.id}" 
                    data-story-index="${index}">
                    <div class="sp-story-avatar">
                        <img src="${avatar}" alt="${name}">
                    </div>
                    <div class="sp-story-name"><span>${name}</span></div>
                </div>
            `;
        }

        attachCardEvents() {
            // Using a more robust event delegation or explicit check
            this.swiperWrapper.onclick = (e) => {
                const card = e.target.closest(this.layout === "avatar" ? ".sp-story-avatar-item" : ".sp-story-card");
                
                if (!card || card.classList.contains('sp-type-create')) return;

                const idxAttr = card.getAttribute("data-story-index");
                if (idxAttr === null) return;

                const idx = parseInt(idxAttr, 10);
                const item = this.stories[idx];
                if (item) {
                    const unseenIdx = item.stories.findIndex(story => !story.seen);
                    const startIdx = unseenIdx >= 0 ? unseenIdx : 0;
                    window.spPlayer.showStory(this, idx, startIdx);
                }
            };
        }
    }

    const spPlayer = {
        activeSlider: null,
        currentUserIndex: 0,
        currentStoryIndex: 0,
        currentStorySessionId: 0,
        isPaused: false,
        isMuted: storypostsStory.settings.mute_by_default || false,
        isModalClosed: true,
        autoplayTimer: null,
        startTime: null,
        timeDuration: null,
        timeLeft: 0,
        storyBackdrop: null,

        // Elements
        modal: document.getElementById("sp-story-modal"),
        modalAvatar: null,
        modalName: null,
        modalTime: null,
        modalMedia: null,
        modalInfo: null,
        modalProgress: null,
        controlsBar: null,
        indicator: null,
        footerAvatars: null,

        init() {
            if (!this.modal) return;
            
            this.modalAvatar = this.modal.querySelector(".sp-modal-avatar");
            this.modalName = this.modal.querySelector(".sp-modal-name");
            this.modalTime = this.modal.querySelector(".sp-modal-time");
            this.modalMedia = this.modal.querySelector(".sp-modal-media");
            this.modalInfo = this.modal.querySelector(".sp-modal-info");
            this.modalProgress = this.modal.querySelector(".sp-modal-progress");
            this.controlsBar = this.modal.querySelector(".sp-story-controls");
            this.indicator = this.modal.querySelector(".sp-story-indicators");
            this.footerAvatars = this.modal.querySelector(".sp-footer-avatars");
            this.modalBody = this.modal.querySelector(".sp-modal-body");

            const nextBtn = this.modal.querySelector(".sp-modal-next");
            if (nextBtn) nextBtn.addEventListener("click", () => this.goToNextStory());
            
            const prevBtn = this.modal.querySelector(".sp-modal-prev");
            if (prevBtn) prevBtn.addEventListener("click", () => this.goToPrevStory());
            
            const closeBtn = this.modal.querySelector(".sp-modal-close");
            if (closeBtn) closeBtn.addEventListener("click", () => this.closeModal());
        },

        showStory(slider, userIndex, storyIndex, direction = null) {
            this.isModalClosed = false;
            this.activeSlider = slider;
            this.activeUserIndex = userIndex;
            this.activeStoryIndex = storyIndex;

            if (this.modalBody && direction) {
                this.modalBody.classList.remove('sp-anim-next', 'sp-anim-prev');
                void this.modalBody.offsetWidth; // Force reflow
                this.modalBody.classList.add('sp-anim-' + direction);
            }

            // Update modal context class for styling
            if (this.modal) {
                this.modal.classList.remove('sp-story-users', 'sp-story-collections', 'sp-story-blog', 'sp-story-products');
                this.modal.classList.add('sp-story-' + slider.mode);
            }

            this.modal.classList.remove("hidden");
            this.currentStorySessionId++;

            const thisSession = this.currentStorySessionId;
            const item = this.activeSlider.stories[userIndex];
            const story = item.stories[storyIndex];

            this.clearStory();
            this.isPaused = false;

            if (this.modalMedia && story.type) {
                this.modalMedia.setAttribute("story-type", story.type);
                this.modalMedia.classList.add("loading");
            }

            if (this.modalAvatar) this.modalAvatar.src = item.avatar;
            if (this.modalName) this.modalName.textContent = item.name;
            if (this.modalTime) this.modalTime.textContent = story.timestamp || "";

            if (this.modalInfo) {
                this.modalInfo.innerHTML = "";
                const titleEl = document.createElement("h4");
                titleEl.className = "sp-story-title";
                if (story.link?.trim()) {
                    const linkEl = document.createElement("a");
                    linkEl.href = story.link.trim();
                    linkEl.target = "_blank";
                    linkEl.textContent = story.title || "";
                    const iconEl = document.createElement("i");
                    iconEl.className = "sp-icon--link";
                    linkEl.appendChild(iconEl);
                    titleEl.appendChild(linkEl);
                } else {
                    titleEl.textContent = story.title || "";
                }
                this.modalInfo.appendChild(titleEl);

                const captionEl = document.createElement("p");
                captionEl.className = "sp-story-caption";
                captionEl.innerHTML = story.caption || "";
                this.modalInfo.appendChild(captionEl);

                // 1. Prepend product image if context is products
                if (this.activeSlider.mode === 'products' && story.poster) {
                    const prodImg = document.createElement("img");
                    prodImg.className = "sp-story-product-preview";
                    prodImg.src = story.poster;
                    this.modalInfo.prepend(prodImg);
                }

                // 2. Add CTA Button only for blog/collections
                const allowedCtaModes = ['blog', 'collections'];
                if (story.link?.trim() && allowedCtaModes.includes(this.activeSlider.mode)) {
                    const ctaEl = document.createElement("a");
                    ctaEl.className = "sp-story-cta-btn";
                    ctaEl.href = story.link.trim();
                    ctaEl.target = "_blank";
                    ctaEl.textContent = storypostsStory.i18n?.read_more || "Read More";
                    this.modalInfo.appendChild(ctaEl);
                }
            }

            const progressSpan = document.createElement("span");
            progressSpan.className = "story-progress";
            this.modalProgress.appendChild(progressSpan);

            item.stories.forEach((s, i) => {
                const segment = document.createElement("div");
                segment.classList.add("sp-segment");
                if (i < storyIndex) segment.classList.add("seen");
                else if (i === storyIndex) segment.classList.add("active");
                this.indicator.appendChild(segment);
            });

            this.initFooterSwiper(userIndex);
            this.storyBackdrop = new StoryBackdrop();
            this.storyBackdrop.init();

            const duration = storypostsStory.settings.duration || 5000;

            if (story.type === "image") {
                const img = document.createElement("img");
                img.src = story.src;
                this.modalMedia.appendChild(img);
                this.addStoryControls(story, img);
                img.onload = () => {
                    if (thisSession !== this.currentStorySessionId) return;
                    this.modalMedia.classList.remove('loading');
                    this.playCurrentStory(duration);
                    this.progressControl = this.animateProgressBar(progressSpan, duration);
                    this.storyBackdrop.setSource(img);
                };
            } else if (story.type === "video") {
                const video = document.createElement("video");
                video.src = story.src;
                video.controls = false;
                video.muted = this.isMuted;
                this.modalMedia.appendChild(video);
                this.addStoryControls(story, video);

                video.onloadeddata = () => {
                    if (thisSession !== this.currentStorySessionId) return;
                    this.modalMedia.classList.remove('loading');
                    video.play().then(() => {
                        this.playCurrentStory(video);
                        this.progressControl = this.syncProgressToVideo(video, progressSpan);
                        this.storyBackdrop.setSource(video);
                    }).catch(() => {
                        this.playCurrentStory(duration);
                    });
                };
            } else if (story.type === "text") {
                this.modalMedia.style.backgroundColor = story.color;
                this.modalMedia.classList.remove('loading');
                this.addStoryControls(story, null);
                this.playCurrentStory(duration);
                this.progressControl = this.animateProgressBar(progressSpan, duration);
                this.storyBackdrop.setSource(story.color);
            }

            this.modal.classList.remove("hidden");
            this.markStoryAsSeen(story.id);

            const isLastUser = userIndex === this.activeSlider.stories.length - 1;
            const isLastStory = storyIndex === item.stories.length - 1;
            if (isLastUser && isLastStory && this.activeSlider.hasMore && !this.activeSlider.loading) {
                this.activeSlider.fetchStories();
            }
        },

        initFooterSwiper(activeIdx) {
            this.footerAvatars.innerHTML = `
                <div class="sp-avatar-list">
                    <div class="swiper-wrapper"></div>
                    <div class="swiper-button-prev"></div>
                    <div class="swiper-button-next"></div>
                </div>
            `;
            const container = this.footerAvatars.querySelector('.sp-avatar-list');
            const wrapper = container.querySelector('.swiper-wrapper');

            wrapper.innerHTML = this.activeSlider.stories.map((item, index) => {
                const avatar = item.avatar || '';
                const name = item.name || '';
                return `
                <div class="swiper-slide" data-index="${index}">
                    <div class="sp-footer-avatar ${index === activeIdx ? 'active' : ''}" data-tooltip="${name}">
                        <img src="${avatar}" alt="${name}">
                    </div>
                </div>
            `;}).join('');

            const swiper = new Swiper(container, {
                slidesPerView: 10,
                spaceBetween: 8,
                initialSlide: activeIdx,
                watchSlidesProgress: true,
                observer: true,
                observeSlideChildren: true,
                mousewheel: {
                    forceToAxis: true,
                    releaseOnEdges: false,
                    enabled: true,
                    sensitivity: 4,
                },
                navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
                breakpoints: { 0: { slidesPerView: 4 }, 500: { slidesPerView: 6 }, 800: { slidesPerView: 10 } },
                on: {
                    init(swiper) {
                        requestAnimationFrame(() => {
                            const shouldCenter = swiper.slides.length <= 10;
                            swiper.el.classList.toggle('centered-mode', shouldCenter);
                            swiper.navigation.update();
                        });
                    },
                    slidesLengthChange: function () {
                        const shouldCenter = this.slides.length <= 10;
                        this.el.classList.toggle('centered-mode', shouldCenter);
                    }
                }
            });

            container.onclick = (e) => {
                const slide = e.target.closest('.swiper-slide');
                if (slide) {
                    const idx = parseInt(slide.dataset.index);
                    if (idx !== this.activeUserIndex) this.showStory(this.activeSlider, idx, 0);
                }
            };
        },

        playCurrentStory(input) {
            if (this.isModalClosed) return;
            clearTimeout(this.autoplayTimer);

            if (input instanceof HTMLVideoElement) {
                const video = input;
                video.onended = () => this.goToNextStory();
            } else {
                this.timeDuration = input;
                this.startTime = Date.now();
                this.autoplayTimer = setTimeout(() => this.goToNextStory(), input);
            }
        },

        syncProgressToVideo(video, progressSpan) {
            let frameId = null;
            const update = () => {
                if (video.readyState >= 1 && video.duration) {
                    const pct = (video.currentTime / video.duration) * 100;
                    progressSpan.style.width = Math.min(pct, 100) + '%';
                }
                if (!video.ended && !video.paused && !this.isModalClosed) {
                    frameId = requestAnimationFrame(update);
                }
            };
            
            frameId = requestAnimationFrame(update);

            return {
                pause: () => {
                    if (frameId) cancelAnimationFrame(frameId);
                },
                resume: () => {
                    frameId = requestAnimationFrame(update);
                }
            };
        },

        togglePlayback() {
            this.isPaused = !this.isPaused;
            const playBtn = this.controlsBar.querySelector('.play-control i');
            if (playBtn) playBtn.className = `sp-icon--arrow-${this.isPaused ? 'play' : 'pause'}`;

            if (this.isPaused) {
                // Pause everything
                clearTimeout(this.autoplayTimer);
                if (this.modalMedia && this.modalMedia.querySelector('video')) {
                    this.modalMedia.querySelector('video').pause();
                    if (this.storyBackdrop) this.storyBackdrop.pauseVideo();
                } else {
                    // Calculate remaining time for timer-based stories
                    this.timeLeft = this.timeDuration - (Date.now() - this.startTime);
                }
                // Pause progress bar if control exists
                if (this.progressControl) this.progressControl.pause();
            } else {
                // Resume everything
                if (this.modalMedia && this.modalMedia.querySelector('video')) {
                    this.modalMedia.querySelector('video').play();
                    if (this.storyBackdrop) this.storyBackdrop.playVideo();
                } else {
                    this.playCurrentStory(this.timeLeft);
                }
                // Resume progress bar if control exists
                if (this.progressControl) this.progressControl.resume();
            }
        },

        animateProgressBar(elem, duration) {
            let start = null, elapsed = 0, isPlaying = true, frameId = null;
            let pauseTime = null;

            // Initial reset
            elem.style.width = '0%';

            const step = (timestamp) => {
                if (!isPlaying) return;

                if (!start) start = timestamp;
                
                // Adjust start time if we were paused
                if (pauseTime) {
                    start += (timestamp - pauseTime);
                    pauseTime = null;
                }

                elapsed = timestamp - start;
                const pct = Math.min((elapsed / duration) * 100, 100);
                elem.style.width = pct + '%';

                if (elapsed < duration && !this.isModalClosed) {
                    frameId = requestAnimationFrame(step);
                }
            };

            const pause = () => {
                isPlaying = false;
                pauseTime = performance.now();
                if (frameId) cancelAnimationFrame(frameId);
            };

            const resume = () => {
                if (!isPlaying && elapsed < duration) {
                    isPlaying = true;
                    frameId = requestAnimationFrame(step);
                }
            };

            frameId = requestAnimationFrame(step);
            return { pause, resume };
        },

        addStoryControls(story, media) {
            this.controlsBar.innerHTML = "";

            // 1. Mute Control (Videos only)
            if (story.type === "video") {
                const muteControl = document.createElement("span");
                muteControl.className = "item mute-control";
                const muteBtn = document.createElement("i");
                muteBtn.className = `sp-icon--arrow-${this.isMuted ? 'mute' : 'unmute'}`;
                muteControl.appendChild(muteBtn);
                this.controlsBar.appendChild(muteControl);

                muteBtn.onclick = (e) => {
                    e.stopPropagation();
                    this.isMuted = !this.isMuted;
                    muteBtn.className = `sp-icon--arrow-${this.isMuted ? 'mute' : 'unmute'}`;
                    if (media) media.muted = this.isMuted;
                };
            }

            // 2. Play/Pause Control
            const playControl = document.createElement("span");
            playControl.className = "item play-control";
            const playBtn = document.createElement("i");
            playBtn.className = `sp-icon--arrow-${this.isPaused ? 'play' : 'pause'}`;
            playControl.appendChild(playBtn);
            this.controlsBar.appendChild(playControl);
            
            playBtn.onclick = (e) => {
                e.stopPropagation();
                this.togglePlayback();
            };

            // 3. Actions Dropdown (Privacy, Delete, etc.)
            if (story.cans && (story.cans.can_edit || story.cans.can_delete)) {
                this.renderOptionsDropdown(story);
            }
        },

        renderOptionsDropdown(story) {
            const storyOptions = document.createElement("span");
            storyOptions.className = "item story-options";
            const optBtn = document.createElement("i");
            optBtn.className = "sp-icon--more";
            storyOptions.appendChild(optBtn);
            this.controlsBar.appendChild(storyOptions);

            const dropdown = document.createElement("div");
            dropdown.className = "story-options-dropdown";
            const ul = document.createElement("ul");

            // Privacy switcher (if user can edit and privacy is enabled)
            if (story.cans?.can_edit && storypostsStory.settings?.enable_privacy === 'on') {
                const privacyLevels = storypostsStory.settings?.privacy_levels || [];

                if (privacyLevels.length > 0) {
                    const liPrivacy = document.createElement("li");
                    liPrivacy.className = "dropdown-item privacy-option";

                    const privacySelect = document.createElement("select");
                    privacySelect.id = "sp-story-privacy-" + story.id;
                    privacySelect.className = "sp-story-privacy-toggle";
                    privacySelect.dataset.storyId = story.id;

                    // Privacy options mapping
                    const privacyLabels = {
                        'public': storypostsStory.i18n?.privacy_public || 'Public',
                        'friends': storypostsStory.i18n?.privacy_friends || 'Friends Only',
                        'private': storypostsStory.i18n?.privacy_private || 'Only Me'
                    };

                    // Add options
                    privacyLevels.forEach(level => {
                        const option = document.createElement("option");
                        option.value = level;
                        option.textContent = privacyLabels[level] || level;
                        if (level === story.privacy) {
                            option.selected = true;
                        }
                        privacySelect.appendChild(option);
                    });

                    // Handle privacy change
                    privacySelect.addEventListener("change", async (e) => {
                        e.stopPropagation();
                        const newPrivacy = e.target.value;

                        try {
                            const data = await spUpdateStoryPrivacy(story.id, newPrivacy);
                            story.privacy = newPrivacy;
                            if (storypostsStory.i18n?.privacy_updated) {
                                alert(data.data?.message || storypostsStory.i18n.privacy_updated);
                            }
                        } catch (err) {
                            console.error('Privacy update error:', err);
                            if (storypostsStory.i18n?.privacy_error) {
                                alert(err.message || storypostsStory.i18n.privacy_error);
                            }
                            e.target.value = story.privacy; // Revert
                        }
                    });

                    liPrivacy.appendChild(privacySelect);
                    ul.appendChild(liPrivacy);
                }
            }

            // Delete option
            if (story.cans?.can_delete) {
                const liDelete = document.createElement("li");
                liDelete.className = "dropdown-item delete-option";
                liDelete.textContent = storypostsStory.i18n?.delete || "Delete";
                ul.appendChild(liDelete);

                liDelete.addEventListener("click", (e) => {
                    e.stopPropagation();
                    e.preventDefault();

                    // Hide the dropdown before calling confirm() to avoid
                    // DOM changes that dismiss the native browser dialog.
                    dropdown.style.display = "none";

                    if (!confirm(storypostsStory.i18n?.confirm_delete || "Are you sure you want to delete this story?")) return;

                    spDeleteStory(story.id)
                        .then(success => {
                            if (success && success.success) {
                                this.handleStoryDeletion(this.activeUserIndex, this.activeStoryIndex);
                            } else {
                                alert(storypostsStory.i18n?.delete_failed || "Story deletion failed.");
                            }
                        })
                        .catch(err => {
                            console.error("Error deleting story:", err);
                            alert(storypostsStory.i18n?.delete_error || "Something went wrong while deleting the story.");
                        });
                });
            }

            dropdown.appendChild(ul);
            dropdown.style.display = 'none';
            storyOptions.appendChild(dropdown);
            optBtn.onclick = (e) => {
                e.stopPropagation();
                dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
            };
        },

        goToNextStory() {
            if (this.isModalClosed) return;
            const item = this.activeSlider.stories[this.activeUserIndex];
            if (this.activeStoryIndex + 1 < item.stories.length) {
                this.showStory(this.activeSlider, this.activeUserIndex, this.activeStoryIndex + 1);
            } else if (this.activeUserIndex + 1 < this.activeSlider.stories.length) {
                this.showStory(this.activeSlider, this.activeUserIndex + 1, 0, 'next');
            } else {
                if (!this.activeSlider.loading) {
                    this.closeModal();
                }
            }
        },

        goToPrevStory() {
            if (this.activeStoryIndex > 0) {
                this.showStory(this.activeSlider, this.activeUserIndex, this.activeStoryIndex - 1);
            } else if (this.activeUserIndex > 0) {
                const pIdx = this.activeUserIndex - 1;
                this.showStory(this.activeSlider, pIdx, this.activeSlider.stories[pIdx].stories.length - 1, 'prev');
            }
        },

        clearStory() {
            [this.indicator, this.modalMedia, this.controlsBar, this.modalProgress, this.footerAvatars].forEach(el => { if (el) el.innerHTML = ""; });
            this.modalMedia?.removeAttribute("style");
            if (this.storyBackdrop) { this.storyBackdrop.destroy(); this.storyBackdrop = null; }
        },

        closeModal() {
            this.isModalClosed = true;
            clearTimeout(this.autoplayTimer);
            const video = this.modalMedia?.querySelector("video");
            if (video) { video.pause(); video.src = ""; }
            this.clearStory();
            this.modal?.classList.add("hidden");
        },

        markStoryAsSeen(storyId) {
            if (this.activeSlider.mode !== 'users') return;
            if (!storyId || storypostsStory.seenStories?.includes(storyId)) return;
            fetch(storypostsStory.ajax_url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ action: 'storyposts_mark_story_seen', nonce: storypostsStory.nonce, story_id: storyId })
            }).then(res => res.json()).then(json => {
                if (json.success) { storypostsStory.seenStories = storypostsStory.seenStories || []; storypostsStory.seenStories.push(storyId); }
            });
        },

        handleStoryDeletion(uIdx, sIdx) {
            const item = this.activeSlider.stories[uIdx];
            item.stories.splice(sIdx, 1);
            if (item.stories.length === 0) {
                this.activeSlider.stories.splice(uIdx, 1);
                if (this.activeSlider.stories.length > 0) this.showStory(this.activeSlider, Math.min(uIdx, this.activeSlider.stories.length - 1), 0);
                else this.closeModal();
            } else this.showStory(this.activeSlider, uIdx, Math.min(sIdx, item.stories.length - 1));
        }
    };

    class StoryBackdrop {
        constructor() {
            this.canvas = document.querySelector('.sp-modal-backdrop');
            this.ctx = this.canvas?.getContext('2d');
            this.video = document.createElement('video');
            this.animationFrame = null;
            this.resizeObserver = new ResizeObserver(this.resizeCanvas.bind(this));
            this.currentSource = null;
            this.currentType = null;
            this.isRendering = false;
        }
        init() {
            if (!this.canvas) return;
            this.resizeObserver.observe(this.canvas.parentElement);
            this.resizeCanvas();
        }
        resizeCanvas() {
            const parent = this.canvas.parentElement;
            if (!parent) return;
            const { width, height } = parent.getBoundingClientRect();
            this.canvas.width = Math.max(1, width);
            this.canvas.height = Math.max(1, height);
            this.redrawContent();
        }
        redrawContent() {
            if (!this.currentSource) return;
            if (this.currentType === 'image') this.drawBlurredImage(this.currentSource);
            else if (this.currentType === 'video') this.drawBlurredImage(this.video);
            else if (this.currentType === 'color') { this.ctx.fillStyle = this.currentSource; this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); }
        }
        async setSource(src) {
            if (typeof src === 'string') { this.currentSource = src; this.currentType = 'color'; }
            else if (src?.tagName === 'IMG') { this.currentSource = src; this.currentType = 'image'; }
            else if (src?.tagName === 'VIDEO') { this.currentSource = src; this.currentType = 'video'; }

            cancelAnimationFrame(this.animationFrame);
            this.canvas?.classList.remove('active');

            if (typeof src === 'string' && src.startsWith('#')) this.drawSolidColor(src);
            else if (src?.tagName === 'IMG') await this.processImage(src);
            else if (src?.tagName === 'VIDEO') await this.processVideo(src);
            else this.drawFallbackColor();

            this.canvas?.classList.add('active');
        }
        processImage(img) {
            return new Promise((resolve) => {
                const temp = new Image(); temp.crossOrigin = 'Anonymous'; temp.src = img.src;
                temp.onload = () => { this.drawBlurredImage(temp); resolve(); };
                temp.onerror = () => { this.drawFallbackColor(); resolve(); };
            });
        }
        processVideo(video) {
            return new Promise((resolve) => { this.video = video; this.startVideoRendering(); resolve(); });
        }
        startVideoRendering() {
            if (this.isRendering) return;
            cancelAnimationFrame(this.animationFrame);
            this.isRendering = true;
            const render = () => {
                if (this.video.readyState >= 2 && this.canvas.width > 0) this.drawBlurredImage(this.video);
                this.animationFrame = requestAnimationFrame(render);
            };
            render();
        }
        playVideo() { if (this.currentType === 'video') this.startVideoRendering(); }
        pauseVideo() { if (this.currentType === 'video') { this.video.pause(); cancelAnimationFrame(this.animationFrame); this.isRendering = false; } }
        drawBlurredImage(source) {
            const { width, height } = this.canvas;
            const dw = Math.floor(width / 4), dh = Math.floor(height / 4);
            this.ctx.clearRect(0, 0, width, height);
            this.ctx.drawImage(source, 0, 0, dw, dh);
            this.ctx.imageSmoothingEnabled = true;
            this.ctx.globalAlpha = 0.9;
            this.ctx.drawImage(this.canvas, 0, 0, dw, dh, 0, 0, width, height);
        }
        drawFallbackColor() { if (this.ctx) { this.ctx.fillStyle = '#1a1a1a'; this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); } }
        drawSolidColor(hex) { if (this.ctx) { this.ctx.fillStyle = hex; this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); } }
        destroy() {
            cancelAnimationFrame(this.animationFrame);
            this.video.pause(); this.video.src = "";
            this.resizeObserver.disconnect();
            this.canvas.width = 1; this.canvas.height = 1;
        }
    }

    window.spPlayer = spPlayer;
    spPlayer.init();

    document.querySelectorAll(".sp-stories-container").forEach(wrapper => {
        new StorySlider(wrapper);
    });
});
