class modernDesign extends elementorModules.frontend.handlers.Base {

    getDefaultSettings() {
        return {
            selectors: {
                mainwrapper: ".twae-modern-vertical-timeline",
                uibtn: ".twae-modern-vertical-timeline-tab-btn",
                uicontent: ".twae-modern-vertical-timeline-tab-content",
            },
        };
    }

    getDefaultElements() {
        const selectors = this.getSettings("selectors");
        return {
            $mainwrapper: this.$element.find(selectors.mainwrapper),
            $uibtn: this.$element.find(selectors.uibtn),
            $uicontent: this.$element.find(selectors.uicontent),
            $lineOuter: this.$element.find(`#timelineLine-${this.$element.data("id")}`),
            $lineInner: this.$element.find(`#timelineLine-${this.$element.data("id")} .twae-inner-line`),
            $tabBtnWrapper: this.$element.find(`#tabBtnWrapper-${this.$element.data("id")}`),
            $tabs: this.$element.find(".twae-modern-vertical-timeline-tab-btn"),
        };
    }


    bindEvents() {
        this.initTimelineWidget();


        elementorFrontend.on('change:deviceMode', () => {

            this.moveTabContentsBasedOnScreen();
        });
        // In editor mode, delay to ensure DOM is ready
        if (elementorFrontend.isEditMode()) {
            this.observeSidebarRepeaterClicks();
            this.observeDuplicateItemClicks();
            this.observeRepeaterFocusAndSync();
            this.observeAddItemClicks();
            // Retry once DOM is more stable
            requestAnimationFrame(() => {
                setTimeout(() => {
                    this.moveTabContentsBasedOnScreen();
                    this.updateScrollAndTimeline();
                    this.updateLineFillOnStoryChange();
                }, 300);
            });
        } else {
            this.moveTabContentsBasedOnScreen();
        }

        // Resize listener for both views
        window.addEventListener("resize", () => {
            this.moveTabContentsBasedOnScreen();

            if (typeof this.updateScrollAndTimeline === "function") {
                this.updateScrollAndTimeline();;
            }
            if (typeof this.updateLineFillOnStoryChange === "function") {
                this.updateLineFillOnStoryChange();
            }
        });



    }



    initTimelineWidget() {
        const wrapper = this.elements.$mainwrapper[0];
        if (!wrapper) return;
        this.moveTabContentsBasedOnScreen();
        const widgetId = this.$element.data("id");
        const tabs = wrapper.querySelectorAll(
            ".twae-modern-vertical-timeline-tab-btn"
        );
        const contents = wrapper.querySelectorAll(
            ".twae-modern-vertical-timeline-tab-content"
        );


        const dots = wrapper.querySelectorAll(
            ".twae-modern-vertical-timeline-tab-btn .dot"
        );
        const scrollUpButton = wrapper.querySelector("#twaescrollUp");
        const scrollDownButton = wrapper.querySelector("#twaescrollDown");

        const tabBtnWrapper = wrapper.querySelector(`#tabBtnWrapper-${widgetId}`);
        const btns = wrapper.querySelector(
            ".twae-modern-vertical-timeline-story-scroll-btns"
        );
        const TabMenu = wrapper.querySelector(
            ".twae-modern-vertical-timeline-tab-menu"
        );
        const yearSelect = wrapper.querySelector("#twaeyearSelect");
        const timelineLine = wrapper.querySelector(`#timelineLine-${widgetId}`);
        const lineFillAttr = wrapper.getAttribute("data-line-fill");
        this.isLineFillingEnabled =
            lineFillAttr === "yes" || lineFillAttr === "true" || lineFillAttr === "on";

        let lineInner = null;
        if (timelineLine) {
            lineInner = timelineLine.querySelector(".twae-inner-line");
        }

        const isLoopScrollEnabled =
            tabBtnWrapper && tabBtnWrapper.getAttribute("data-loop-scroll") === "true";


        const tabButtons = tabs;
        const lineOuter = timelineLine;
        const resizeObs = new ResizeObserver((entries) => {
            this.updateScrollAndTimeline();;
            this.updateLineFillOnStoryChange();
        });
        dots.forEach((dot) => resizeObs.observe(dot));

        if (timelineLine) {
            lineInner = timelineLine.querySelector(".twae-inner-line");
        }



        function updateScrollButtonsVisibility() {
            const visibleTabs = Array.from(tabs).filter(tab => tab.style.display !== "none");
            const activeIndex = visibleTabs.findIndex(tab => tab.classList.contains("active"));

            if (!isLoopScrollEnabled) {
                const isAtTop = activeIndex === 0;
                const isAtBottom = activeIndex === visibleTabs.length - 1;

                if (visibleTabs.length <= 1 || activeIndex === -1) {
                    scrollUpButton.classList.add("disabled");
                    scrollDownButton.classList.add("disabled");
                    return;
                }

                if (isAtTop) {
                    scrollUpButton.classList.add("disabled");
                } else {
                    scrollUpButton.classList.remove("disabled");
                }

                if (isAtBottom) {
                    scrollDownButton.classList.add("disabled");
                } else {
                    scrollDownButton.classList.remove("disabled");
                }
            } else {
                scrollUpButton.classList.remove("disabled");
                scrollDownButton.classList.remove("disabled");
            }
        }

        if (typeof elementorFrontend !== "undefined" && elementorFrontend.isEditMode()) {
            const tabWrapper = tabBtnWrapper;

            if (tabWrapper) {


                let lastHeight = tabWrapper.scrollHeight;
                setInterval(() => {
                    const currentHeight = tabWrapper.scrollHeight;
                    if (currentHeight !== lastHeight) {
                        lastHeight = currentHeight;
                        this.updateScrollAndTimeline();;
                    }
                }, 500);
            }
        }


        tabs.forEach((tab) => {
            if (!tab) return;

            tab.addEventListener("click", () => {
                const target = tab.getAttribute("data-tab");
                if (!target) return;

                for (let i = 0; i < tabs.length; i++) {
                    if (tabs[i]) tabs[i].classList.remove("active");
                }

                for (let i = 0; i < contents.length; i++) {
                    if (contents[i]) contents[i].classList.remove("active");
                }

                for (let i = 0; i < dots.length; i++) {
                    if (dots[i]) dots[i].classList.remove("active-dot");
                }

                tab.classList.add("active");

                const dot = tab.querySelector(".dot");
                if (dot) {
                    dot.classList.add("active-dot");
                }

                const contentEls = wrapper.querySelectorAll("#tab-" + target);
                for (let i = 0; i < contentEls.length; i++) {
                    if (contentEls[i]) contentEls[i].classList.add("active");
                }

                this.updateScrollAndTimeline();
                this.updateLineFillOnStoryChange();

                if (typeof elementorFrontend !== "undefined") {
                    elementorFrontend.hooks.doAction(
                        "frontend/twaeWidget/horizontalSliderInitialize",
                        wrapper
                    );
                }
                setTimeout(() => {
                    this.updateScrollAndTimeline();
                    this.updateLineFillOnStoryChange();
                }, 300);

            });
        });


        if (scrollUpButton) {
            scrollUpButton.addEventListener("click", () => {
                const visibleTabs = Array.from(tabs).filter(
                    (tab) => tab.style.display !== "none"
                );
                const activeIndex = visibleTabs.findIndex((tab) =>
                    tab.classList.contains("active")
                );

                let prevIndex = activeIndex - 1;

                if (prevIndex < 0) {
                    if (isLoopScrollEnabled) {
                        prevIndex = visibleTabs.length - 1;
                    } else {
                        return;
                    }
                }

                visibleTabs[prevIndex].click();
                updateScrollButtonsVisibility();
                requestAnimationFrame(() => {
                    const targetTop = visibleTabs[prevIndex].offsetTop;
                    tabBtnWrapper.scrollTo({ top: targetTop - 10, behavior: "smooth" });

                });
            });
        }

        if (scrollDownButton) {
            scrollDownButton.addEventListener("click", () => {
                const visibleTabs = Array.from(tabs).filter(
                    (tab) => tab.style.display !== "none"
                );
                const activeIndex = visibleTabs.findIndex((tab) =>
                    tab.classList.contains("active")
                );

                let nextIndex = activeIndex + 1;

                if (nextIndex >= visibleTabs.length) {
                    if (isLoopScrollEnabled) {
                        nextIndex = 0;
                    } else {
                        return;
                    }
                }

                visibleTabs[nextIndex].click();
                updateScrollButtonsVisibility();
                tabBtnWrapper.scrollTop =
                    visibleTabs[nextIndex].offsetTop - tabBtnWrapper.offsetTop;
                updateScrollButtonsVisibility();
            });
        }

        if (tabBtnWrapper) {
            let scrollTimeout;
            tabBtnWrapper.addEventListener(
                "wheel",
                (e) => {
                    e.preventDefault();
                    clearTimeout(scrollTimeout);
                    scrollTimeout = setTimeout(() => {
                        const visibleTabs = Array.from(tabs).filter(
                            (tab) => tab.style.display !== "none"
                        );
                        const activeIndex = visibleTabs.findIndex((tab) =>
                            tab.classList.contains("active")
                        );
                        let nextIndex = activeIndex;

                        if (e.deltaY > 0 && activeIndex < visibleTabs.length - 1) {
                            nextIndex++;
                        } else if (e.deltaY < 0 && activeIndex > 0) {
                            nextIndex--;
                        } else if (isLoopScrollEnabled) {
                            if (e.deltaY < 0 && activeIndex === 0) {
                                nextIndex = visibleTabs.length - 1;
                            } else if (
                                e.deltaY > 0 &&
                                activeIndex === visibleTabs.length - 1
                            ) {
                                nextIndex = 0;
                            }
                        }

                        if (nextIndex !== activeIndex) {
                            visibleTabs[nextIndex].click();
                            tabBtnWrapper.scrollTop =
                                visibleTabs[nextIndex].offsetTop - tabBtnWrapper.offsetTop;
                            updateScrollButtonsVisibility();
                        }
                    }, 100);
                }, { passive: false }
            );

            tabBtnWrapper.addEventListener("scroll", () => {
                this.updateLineFillOnStoryChange();
            });
        }

        const yearSet = new Set();
        tabButtons.forEach((btn) => {
            const year = btn.getAttribute("data-year");
            if (year) yearSet.add(year);
        });

        if (yearSelect) {
            const yearOptions = Array.from(yearSet).sort();
            yearSelect.innerHTML = '<option value="all">All</option>';
            yearOptions.forEach((year) => {
                const option = document.createElement("option");
                option.value = year;
                option.textContent = year;
                yearSelect.appendChild(option);
            });

            yearSelect.addEventListener("change", () => {
                const selectedYear = yearSelect.value;
                let firstVisibleTab = null;

                tabButtons.forEach((btn) => {
                    const year = btn.getAttribute("data-year");
                    if (selectedYear === "all" || year === selectedYear) {
                        btn.style.display = "block";
                        if (!firstVisibleTab) firstVisibleTab = btn;
                    } else {
                        btn.style.display = "none";
                    }
                });

                tabs.forEach((tab) => tab.classList.remove("active"));
                contents.forEach((content) => content.classList.remove("active"));
                dots.forEach((dot) => dot.classList.remove("active-dot"));

                if (firstVisibleTab) {
                    tabBtnWrapper.scrollTop = 0;
                    requestAnimationFrame(() => {
                        firstVisibleTab.click();
                        requestAnimationFrame(() => {
                            this.updateScrollAndTimeline();;
                            this.updateLineFillOnStoryChange();
                        });
                    });
                }
                requestAnimationFrame(() => {
                    this.updateScrollAndTimeline();;
                    this.updateLineFillOnStoryChange();
                    updateScrollButtonsVisibility();
                });
            });
        }

        if (elementorFrontend.isEditMode() && this.isLineFillingEnabled && lineInner) {
            lineInner.style.height = "0px";
        }
        requestAnimationFrame(() => {
            updateScrollButtonsVisibility();
        });

        this.updateScrollAndTimeline();;
        this.updateLineFillOnStoryChange();
    }


    updateScrollAndTimeline() {
        const wrapper = this.elements.$mainwrapper[0];
        if (!wrapper) return;
        const widgetId = this.$element.data("id");
        const tabBtnWrapper = wrapper.querySelector(`#tabBtnWrapper-${widgetId}`);
        const timelineLine = wrapper.querySelector(`#timelineLine-${widgetId}`);
        const tabButtons = wrapper.querySelectorAll(".twae-modern-vertical-timeline-tab-btn");
        const TabMenu = wrapper.querySelector(".twae-modern-vertical-timeline-tab-menu");

        if (!wrapper || !tabBtnWrapper || !timelineLine || !TabMenu) return;

        const visibleButtons = Array.from(tabButtons).filter(btn => btn.style.display !== "none");

        if (visibleButtons.length > 0) {
            if (visibleButtons.length < 3) {
                timelineLine.style.top = "42px";
                timelineLine.style.height = "90%";
                const firstDot = visibleButtons[0].querySelector(".dot");
                if (firstDot) {
                    const firstDotCenter = firstDot.offsetLeft + firstDot.offsetWidth / 2;
                    timelineLine.style.left = `${firstDotCenter + 10}px`;
                    timelineLine.style.transform = "translateX(-50%)";
                }
                return;
            }

            const firstDot = visibleButtons[0].querySelector(".dot");
            const lastDot = visibleButtons[visibleButtons.length - 1].querySelector(".dot");
            if (!firstDot || !lastDot) return;

            const wrapperRect = tabBtnWrapper.getBoundingClientRect();
            const topOffset = firstDot.getBoundingClientRect().top - wrapperRect.top + tabBtnWrapper.scrollTop + firstDot.offsetHeight / 2;
            const bottomOffset = lastDot.getBoundingClientRect().top - wrapperRect.top + tabBtnWrapper.scrollTop + lastDot.offsetHeight / 2;
            let height = Math.max(bottomOffset - topOffset, 0);

            const isMobile = window.innerWidth < 700;
            const allButtons = wrapper.querySelectorAll(".twae-modern-vertical-timeline-tab-btn");
            const activeIndex = [...allButtons].findIndex(btn => btn.classList.contains("active"));
            const isLastTab = activeIndex === allButtons.length - 1;


            const firstDotCenter = firstDot.offsetLeft + firstDot.offsetWidth / 2;
            timelineLine.style.left = `${firstDotCenter + 10}px`;
            timelineLine.style.transform = "translateX(-50%)";

            timelineLine.style.top = `${topOffset}px`;

            if (isMobile && isLastTab) {
                const lastVisibleContent = wrapper.querySelector(".twae-modern-vertical-timeline-tab-content.active");

                if (lastVisibleContent) {
                    const contentRect = lastVisibleContent.getBoundingClientRect();
                    const wrapperRect = wrapper.getBoundingClientRect();
                    const extraHeight = (contentRect.bottom - wrapperRect.top) - topOffset;

                    if (isMobile && isLastTab) {
                        height += Math.max(extraHeight - 220);
                    } else {
                        height += extraHeight;
                    }

                }
            }

            timelineLine.style.height = `${height}px`;

        }
    }

    updateLineFillOnStoryChange() {
        if (!this.isLineFillingEnabled) return;


        this.updateScrollAndTimeline();

        const wrapper = this.elements.$mainwrapper[0];
        if (!wrapper) return;

        const widgetId = this.$element.data("id");
        const lineOuter = wrapper.querySelector(`#timelineLine-${widgetId}`);
        const lineInner = lineOuter ? lineOuter.querySelector(".twae-inner-line") : null;
        const tabBtnWrapper = wrapper.querySelector(`#tabBtnWrapper-${widgetId}`);
        const tabs = wrapper.querySelectorAll(".twae-modern-vertical-timeline-tab-btn");

        if (!lineOuter || !lineInner || !tabBtnWrapper || !tabs.length) return;

        const visibleTabs = Array.from(tabs).filter(tab => tab.style.display !== "none");
        const activeIndex = visibleTabs.findIndex(tab => tab.classList.contains("active"));
        const totalTabs = visibleTabs.length;

        if (activeIndex === -1 || totalTabs === 0) return;

        let fillHeight;
        if (totalTabs <= 1) {
            fillHeight = lineOuter.offsetHeight;
        } else if (totalTabs < 4) {
            const segmentHeight = lineOuter.offsetHeight / (totalTabs - 1);
            fillHeight = activeIndex * segmentHeight + 100;
        } else {
            const progress = activeIndex / (totalTabs - 1);
            fillHeight = lineOuter.offsetHeight * progress + 100;
        }

        lineInner.style.height = `${Math.min(fillHeight, lineOuter.offsetHeight)}px`;

        visibleTabs.forEach((tab, index) => {
            const story = tab.closest(".twae-line");
            const icon = tab.querySelector(".twae-icon");
            const isInFill = index <= activeIndex;

            if (story) {
                story.classList.toggle("twae-out-viewport", !isInFill);
            }

            if (icon) {
                const iconDot = icon.querySelector(".twae-icondot");
                if (isInFill) {
                    icon.style.borderColor = "var(--tw-line-filling-color)";
                    icon.style.borderStyle = "solid";
                    if (iconDot) {
                        iconDot.style.borderColor = "var(--tw-line-filling-color)";
                        iconDot.style.borderStyle = "solid";
                    }
                } else {
                    icon.style.borderColor = "";
                    icon.style.borderStyle = "";
                    if (iconDot) {
                        iconDot.style.borderColor = "";
                        iconDot.style.borderStyle = "";
                    }
                }
            }
        });
    }

    moveTabContentsBasedOnScreen() {
        const wrapper = this.elements && this.elements.$mainwrapper && this.elements.$mainwrapper[0];
        if (!wrapper) return;

        const isEditor = typeof elementorFrontend !== 'undefined' && elementorFrontend.isEditMode();
        const currentDevice = isEditor ? elementorFrontend.getCurrentDeviceMode() : (window.innerWidth >= 700 ? 'desktop' : 'mobile');
        const isDesktop = currentDevice === 'desktop' || currentDevice === 'tablet';

        const desktopBox = wrapper.querySelector('.twae-modern-vertical-timeline-tab-content-box');
        const tabContents = wrapper.querySelectorAll('.twae-modern-vertical-timeline-tab-content');

        tabContents.forEach((content) => {
            const tabIndex = content.getAttribute('data-tab-index');
            const tabBtn = wrapper.querySelector(`.twae-modern-vertical-timeline-tab-btn[data-tab="${tabIndex}"]`);

            if (!tabBtn || !content) return;

            // Prevent duplicate insertion
            const alreadyInBox = desktopBox && Array.from(desktopBox.children).includes(content);

            if (isDesktop) {
                if (desktopBox && !alreadyInBox) {
                    desktopBox.appendChild(content);
                }
            } else {
                const nextEl = tabBtn.nextElementSibling;
                if (nextEl !== content) {
                    tabBtn.parentNode.insertBefore(content, nextEl);
                }
            }
        });

        requestAnimationFrame(() => {
            if (typeof this.updateScrollAndTimeline === "function") this.updateScrollAndTimeline();
            if (typeof this.updateLineFillOnStoryChange === "function") this.updateLineFillOnStoryChange();
        });
    }

    observeSidebarRepeaterClicks() {
        if (typeof elementor === "undefined" || typeof elementorFrontend === "undefined" || !elementorFrontend.isEditMode()) return;

        const wrapper = this.$element[0];
        if (!wrapper.classList.contains("elementor-element-editable")) return;
        if (!wrapper.querySelector(".twae-modern-vertical-timeline")) return;
        const widgetId = this.$element.data("id");
        const panelEl = elementor.panel && elementor.panel.el;
        if (!wrapper || !widgetId || !panelEl) return;

        // 🔐 Check if this is the currently active widget
        const isActive = wrapper.classList.contains("elementor-element-editable");
        if (!isActive) {
            console.warn(`⛔ Skipping: widget ${widgetId} is not the active one`);
            return;
        }

        const titleButtons = panelEl.querySelectorAll('.elementor-repeater-row-item-title');
        titleButtons.forEach((titleBtn, index) => {
            if (titleBtn.dataset.twaeClickAttached) return;
            titleBtn.dataset.twaeClickAttached = "true";

            titleBtn.addEventListener('click', () => {
                const layoutButtons = wrapper.querySelectorAll('.twae-modern-vertical-timeline-tab-btn');
                const targetButton = layoutButtons[index];

                if (targetButton) {
                    targetButton.click();
                    const tabBtnWrapper = wrapper.querySelector(`#tabBtnWrapper-${widgetId}`);
                    if (tabBtnWrapper) {
                        requestAnimationFrame(() => {
                            tabBtnWrapper.scrollTo({
                                top: targetButton.offsetTop - 10,
                                behavior: 'smooth'
                            });
                        });
                    }


                }
            });
        });


    }


    observeDuplicateItemClicks() {
        if (typeof elementor === "undefined" || typeof elementorFrontend === "undefined" || !elementorFrontend.isEditMode()) return;

        setTimeout(() => {
            const wrapper = this.$element[0];
            if (!wrapper.querySelector(".twae-modern-vertical-timeline")) return;
            if (!wrapper.classList.contains("elementor-element-editable")) return;
            const widgetId = this.$element.data("id");

            if (!wrapper || !widgetId) return;

            const isActive = wrapper.classList.contains("elementor-element-editable");
            if (!isActive) return;

            const panelEl = elementor.panel && elementor.panel.el;
            if (!panelEl) return;

            const duplicateButtons = panelEl.querySelectorAll('.elementor-repeater-tool-duplicate');

            duplicateButtons.forEach((duplicateBtn, index) => {
                if (duplicateBtn.dataset.twaeDuplicateAttached) return;
                duplicateBtn.dataset.twaeDuplicateAttached = "true";

                duplicateBtn.addEventListener("click", () => {


                    setTimeout(() => {
                        const tabButtons = wrapper.querySelectorAll('.twae-modern-vertical-timeline-tab-btn');

                        const nextIndex = index + 1;
                        const targetTab = tabButtons[nextIndex];

                        if (targetTab) {
                            targetTab.click();

                            const tabBtnWrapper = wrapper.querySelector(`#tabBtnWrapper-${widgetId}`);
                            if (tabBtnWrapper) {
                                requestAnimationFrame(() => {
                                    tabBtnWrapper.scrollTo({
                                        top: targetTab.offsetTop - 10,
                                        behavior: "smooth"
                                    });
                                });
                            }


                        } else {
                            console.warn(`⚠️ Could not find duplicated tab at index ${nextIndex}`);
                        }

                    }, 600); // Wait for duplication to finish
                });
            });


        }, 500);
    }


    observeRepeaterFocusAndSync() {
        if (typeof elementor === "undefined" || typeof elementorFrontend === "undefined" || !elementorFrontend.isEditMode()) return;

        const wrapper = this.$element[0];
        if (!wrapper.classList.contains("elementor-element-editable")) return;
        if (!wrapper.querySelector(".twae-modern-vertical-timeline")) return;
        const panelEl = elementor.panel && elementor.panel.el;
        if (!wrapper || !panelEl) return;

        let currentActiveEditableRow = null;

        // Debounce helper
        let debounceTimer = null;
        const debounce = (fn, delay = 100) => {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(fn, delay);
        };

        const syncTabIfNeeded = () => {
            // Make sure the current widget is the one being edited
            if (!wrapper.classList.contains("elementor-element-editable")) return;

            const allRows = panelEl.querySelectorAll('.elementor-repeater-fields');

            for (let i = 0; i < allRows.length; i++) {
                const row = allRows[i];
                const isEditable = row.querySelector('.elementor-repeater-row-controls.editable');

                if (isEditable && isEditable !== currentActiveEditableRow) {
                    currentActiveEditableRow = isEditable;

                    const tabButtons = wrapper.querySelectorAll('.twae-modern-vertical-timeline-tab-btn');
                    const targetTab = tabButtons[i];
                    if (targetTab) {
                        targetTab.click();

                        const widgetId = this.$element.data("id");
                        const tabBtnWrapper = wrapper.querySelector(`#tabBtnWrapper-${widgetId}`);
                        if (tabBtnWrapper) {
                            requestAnimationFrame(() => {
                                tabBtnWrapper.scrollTo({
                                    top: targetTab.offsetTop - 10,
                                    behavior: "smooth"
                                });
                            });
                        }


                    }

                    break;
                }
            }
        };

        const observer = new MutationObserver(() => {
            debounce(syncTabIfNeeded, 300); // Prevent over-triggering
        });

        observer.observe(panelEl, {
            childList: true,
            subtree: true,
        });


    }


    observeAddItemClicks() {
        if (typeof elementor === "undefined" || typeof elementorFrontend === "undefined" || !elementorFrontend.isEditMode()) return;
        const wrapper = this.$element[0];
        if (!wrapper.classList.contains("elementor-element-editable")) return;
        if (!wrapper.querySelector(".twae-modern-vertical-timeline")) return;
        setTimeout(() => {
            const panelEl = elementor.panel && elementor.panel.el;
            if (!panelEl) {
                console.warn("⚠️ Elementor panel not ready");
                return;
            }

            const addButton = panelEl.querySelector('.elementor-button.elementor-repeater-add');
            if (!addButton) {
                console.warn("⚠️ Add button not found in panel");
                return;
            }

            if (addButton.dataset.twaeClickAttached) return;
            addButton.dataset.twaeClickAttached = "true";

            addButton.addEventListener('click', () => {


                setTimeout(() => {
                    if (!wrapper.querySelector(".twae-modern-vertical-timeline")) return;

                    if (!wrapper.classList.contains('elementor-element-editable')) {
                        console.warn("⛔ Skipping: Not the currently edited widget");
                        return;
                    }

                    const tabButtons = wrapper.querySelectorAll('.twae-modern-vertical-timeline-tab-btn');
                    const lastTabButton = tabButtons[tabButtons.length - 1];

                    if (lastTabButton) {
                        lastTabButton.click();

                        const widgetId = this.$element.data("id");
                        const tabBtnWrapper = wrapper.querySelector(`#tabBtnWrapper-${widgetId}`);
                        if (tabBtnWrapper) {
                            requestAnimationFrame(() => {
                                const offsetTop = lastTabButton.offsetTop;
                                tabBtnWrapper.scrollTo({
                                    top: offsetTop - 10,
                                    behavior: 'smooth'
                                });
                            });
                        }
                    } else {
                        console.warn("⚠️ No tab button found to auto-click");
                    }

                    this.updateScrollAndTimeline();
                    this.updateLineFillOnStoryChange();
                }, 800);

            });

        }, 700);
    }



}


jQuery(window).on("elementor/frontend/init", () => {
    const addHandler = ($element) => {
        elementorFrontend.elementsHandler.addHandler(modernDesign, { $element });
    };

    elementorFrontend.hooks.addAction(
        "frontend/element_ready/timeline-widget-addon.default",
        addHandler
    );
});

window.addEventListener("resize", () => {
    const allElements = document.querySelectorAll(".elementor-widget-timeline-widget-addon");

    allElements.forEach(el => {
        const view = elementorFrontend.getView ? elementorFrontend.getView(el) : null;
        if (!view || !view.added || !view.widgetType) return;

        const handler = elementorFrontend.elementsHandler.getHandler(el);

        if (handler && handler instanceof modernDesign) {
            handler.moveTabContentsBasedOnScreen();

            requestAnimationFrame(() => {
                const wrapper = handler.elements.$mainwrapper[0];
                const widgetId = handler.$element.data("id");
                const tabBtnWrapper = wrapper.querySelector(`#tabBtnWrapper-${widgetId}`);

                if (tabBtnWrapper) {
                    tabBtnWrapper.scrollTop = 0;
                }

                requestAnimationFrame(() => {
                    handler.updateScrollAndTimeline();
                    handler.updateLineFillOnStoryChange();
                });
            });
        }
    });
});