(function() {
    "use strict";
    (function(element, components) {
        const el = element.createElement;
        const {useState: useState, createRoot: createRoot, Fragment: Fragment, useEffect: useEffect} = element;
        const {ColorPicker: ColorPicker, Panel: Panel, PanelBody: PanelBody, PanelRow: PanelRow, Modal: Modal} = components;
        function DynamicModal() {
            const [modalData, setModalData] = useState({
                isOpen: false,
                currentIndex: 0,
                items: []
            });
            const goToNext = () => {
                setModalData(prev => ({
                    ...prev,
                    currentIndex: (prev.currentIndex + 1) % prev.items.length
                }));
            };
            const goToPrev = () => {
                setModalData(prev => ({
                    ...prev,
                    currentIndex: (prev.currentIndex - 1 + prev.items.length) % prev.items.length
                }));
            };
            const closeModal = () => setModalData(prev => ({
                ...prev,
                isOpen: false
            }));
            useEffect(() => {
                const handleTriggerClick = e => {
                    const trigger = e.target.closest("[data-qrcdr-admin-modal]");
                    if (!trigger) return;
                    e.preventDefault();
                    const groupName = trigger.getAttribute("data-modal-group");
                    let items = [];
                    let startIndex = 0;
                    if (groupName) {
                        const groupTriggers = Array.from(document.querySelectorAll(`[data-modal-group="${groupName}"]`));
                        items = groupTriggers.map(t => {
                            const selector = t.getAttribute("data-qrcdr-admin-modal");
                            const target = document.querySelector(selector);
                            return {
                                title: t.getAttribute("data-modal-title") || "",
                                content: target ? target.innerHTML : ""
                            };
                        });
                        startIndex = groupTriggers.indexOf(trigger);
                    } else {
                        const selector = trigger.getAttribute("data-qrcdr-admin-modal");
                        const targetElement = document.querySelector(selector);
                        items = [ {
                            title: trigger.getAttribute("data-modal-title") || "",
                            content: targetElement ? targetElement.innerHTML : ""
                        } ];
                    }
                    setModalData({
                        isOpen: true,
                        currentIndex: startIndex,
                        items: items
                    });
                };
                const handleKeyDown = e => {
                    setModalData(current => {
                        if (!current.isOpen || current.items.length <= 1) return current;
                        if (e.key === "ArrowRight") {
                            return {
                                ...current,
                                currentIndex: (current.currentIndex + 1) % current.items.length
                            };
                        }
                        if (e.key === "ArrowLeft") {
                            return {
                                ...current,
                                currentIndex: (current.currentIndex - 1 + current.items.length) % current.items.length
                            };
                        }
                        return current;
                    });
                };
                document.addEventListener("click", handleTriggerClick);
                document.addEventListener("keydown", handleKeyDown);
                return () => {
                    document.removeEventListener("click", handleTriggerClick);
                    document.removeEventListener("keydown", handleKeyDown);
                };
            }, []);
            if (!modalData.isOpen || modalData.items.length === 0) return null;
            const currentItem = modalData.items[modalData.currentIndex];
            return el(Modal, {
                title: currentItem.title,
                onRequestClose: closeModal,
                className: "qrcdr-navigation-modal"
            }, el("div", {
                className: "qrcdr-modal-master-wrapper",
                style: {
                    position: "relative"
                }
            }, el("div", {
                dangerouslySetInnerHTML: {
                    __html: currentItem.content
                },
                className: "qrcdr-custom-modal-content"
            })), modalData.items.length > 1 && el("div", {
                className: "qrcdr-modal-nav-overlay"
            }, el(components.Button, {
                className: "nav-button prev",
                onClick: goToPrev,
                icon: "arrow-left-alt2",
                label: "Precedente"
            }), el(components.Button, {
                className: "nav-button next",
                onClick: goToNext,
                icon: "arrow-right-alt2",
                label: "Successivo"
            })));
        }
        function QrcdrColorPicker({initialColor: initialColor, inputName: inputName}) {
            const [color, setColor] = useState(initialColor);
            const wrapperStyle = {
                backgroundColor: color,
                padding: "15px",
                border: "1px solid #c3c4c7",
                borderRadius: "4px",
                display: "inline-block"
            };
            return el("div", {
                style: wrapperStyle
            }, el(ColorPicker, {
                color: color,
                onChangeComplete: newColor => setColor(newColor.hex),
                disableAlpha: true
            }), el("input", {
                type: "hidden",
                name: inputName,
                value: color
            }));
        }
        function ColorSettingsPanel({initialQrColor: initialQrColor, initialBgColor: initialBgColor, nameQrColor: nameQrColor, nameBgColor: nameBgColor}) {
            const [qrColor, setQrColor] = useState(initialQrColor);
            const [bgColor, setBgColor] = useState(initialBgColor);
            const placeholderContainerStyle = {
                marginBottom: "20px",
                maxWidth: "140px"
            };
            const placeholderOuterStyle = {
                backgroundColor: bgColor,
                width: "140px",
                height: "140px",
                padding: "0",
                boxSizing: "border-box",
                transition: "background-color 0.3s ease",
                display: "flex",
                alignItems: "center",
                justifyContent: "center"
            };
            const colorPickersContainerStyle = {
                display: "flex",
                gap: "30px"
            };
            return el(Fragment, {}, el("div", {
                style: placeholderContainerStyle
            }, el("div", {
                style: placeholderOuterStyle
            }, el("svg", {
                width: "100%",
                height: "100%",
                viewBox: "-260 40 520 520",
                fill: qrColor,
                xmlns: "http://www.w3.org/2000/svg",
                "aria-hidden": "true",
                focusable: "false",
                style: {
                    transition: "fill 0.3s ease"
                }
            }, el("polygon", {
                points: "100,360 60,360 60,320 20.1,320 20.1,440.1 60,440.1 60,480 100,480"
            }), el("rect", {
                x: "100",
                y: "480",
                width: "40",
                height: "40"
            }), el("rect", {
                x: "180",
                y: "480",
                width: "40",
                height: "40"
            }), el("polygon", {
                points: "220,320 179.9,320 179.9,360 139.9,360 139.9,480 179.9,480 179.9,440.1 220,440.1"
            }), el("rect", {
                x: "20",
                y: "480",
                width: "40",
                height: "40"
            }), el("rect", {
                x: "-140",
                y: "160",
                width: "40",
                height: "40"
            }), el("path", {
                d: "M-220,80v200h199.9V80H-220z M-60,239.9h-119.9V120h120v119.9H-60z"
            }), el("rect", {
                x: "100",
                y: "160",
                width: "40",
                height: "40"
            }), el("path", {
                d: "M20.1,80v200H220V80H20.1z M179.9,239.9H60V120h120v119.9H179.9z"
            }), el("rect", {
                x: "-140",
                y: "400",
                width: "40",
                height: "40"
            }), el("path", {
                d: "M-220,320v200h199.9V320H-220z M-60,480h-119.9V360h120V480H-60z"
            })))), el("div", {
                style: colorPickersContainerStyle
            }, el("div", {}, el(ColorPicker, {
                color: qrColor,
                onChangeComplete: newColor => setQrColor(newColor.hex),
                disableAlpha: true
            }), el("input", {
                type: "hidden",
                name: nameQrColor,
                value: qrColor
            }), el("p", {
                className: "description"
            }, qrcdrAdminVars.i18n.fgColor)), el("div", {}, el(ColorPicker, {
                color: bgColor,
                onChangeComplete: newColor => setBgColor(newColor.hex),
                disableAlpha: true
            }), el("input", {
                type: "hidden",
                name: nameBgColor,
                value: bgColor
            }), el("p", {
                className: "description"
            }, qrcdrAdminVars.i18n.bgColor))));
        }
        function initializeDynamicModals() {
            const modalRoot = document.createElement("div");
            modalRoot.id = "qrcdr-dynamic-modal-root";
            document.body.appendChild(modalRoot);
            const root = createRoot(modalRoot);
            root.render(el(DynamicModal));
        }
        function initializeColorSettingsPanel() {
            const rootElement = document.getElementById("qrcdr-color-settings-root");
            if (!rootElement) return;
            const {qrColor: qrColor, qrBgcolor: qrBgcolor, nameQrColor: nameQrColor, nameQrBgcolor: nameQrBgcolor} = rootElement.dataset;
            const root = createRoot(rootElement);
            root.render(el(ColorSettingsPanel, {
                initialQrColor: qrColor,
                initialBgColor: qrBgcolor,
                nameQrColor: nameQrColor,
                nameBgColor: nameQrBgcolor
            }));
        }
        function initializeRangeSliders() {
            const rangeSliderRoots = document.querySelectorAll(".qrcdr-range-slider-wrapper");
            if (!rangeSliderRoots.length) return;
            rangeSliderRoots.forEach(rootElement => {
                const rangeInput = rootElement.querySelector(".qrcdr-range-slider-input");
                const rangeDisplay = rootElement.querySelector(".qrcdr-range-slider-display");
                if (rangeInput && rangeDisplay) {
                    rangeInput.addEventListener("input", e => {
                        rangeDisplay.textContent = e.target.value;
                        rootElement.style.borderRadius = e.target.value + "px";
                    });
                }
            });
        }
        function initializeColorPickers() {
            const colorPickerRoots = document.querySelectorAll(".qrcdr-color-picker-component");
            if (!colorPickerRoots.length) return;
            colorPickerRoots.forEach(rootElement => {
                const {initialColor: initialColor, inputName: inputName} = rootElement.dataset;
                if (initialColor && inputName) {
                    const root = createRoot(rootElement);
                    root.render(el(QrcdrColorPicker, {
                        initialColor: initialColor,
                        inputName: inputName
                    }));
                }
            });
        }
        function initializeTabs() {
            const tabContainer = document.querySelector(".qrcdr-tab-nav");
            if (!tabContainer) return;
            const navTabs = tabContainer.querySelectorAll(".nav-tab");
            const tabContents = tabContainer.querySelectorAll(".tabs-content");
            const refererInput = document.querySelector('input[name="_wp_http_referer"]');
            navTabs.forEach(tab => {
                tab.addEventListener("click", e => {
                    e.preventDefault();
                    navTabs.forEach(t => t.classList.remove("nav-tab-active"));
                    tabContents.forEach(c => c.classList.remove("active"));
                    tab.classList.add("nav-tab-active");
                    const targetContent = document.getElementById(`qrcdr-tab-${tab.dataset.tabId}`);
                    if (targetContent) {
                        targetContent.classList.add("active");
                    }
                    if (refererInput) {
                        const currentUrl = new URL(window.location.protocol + "//" + window.location.host + refererInput.value);
                        currentUrl.searchParams.set("tab", tab.dataset.tabId);
                        refererInput.value = currentUrl.pathname + currentUrl.search;
                    }
                });
            });
        }
        function initializeMediaUploader() {
            let mediaUploader;
            const placeholderUploadBtn = document.querySelector(".qrcdr-placeholder-upload");
            if (placeholderUploadBtn) {
                placeholderUploadBtn.addEventListener("click", e => {
                    e.preventDefault();
                    mediaUploader = wp.media({
                        title: qrcdrAdminVars.i18n.choosePlaceholder,
                        button: {
                            text: qrcdrAdminVars.i18n.chooseImage
                        },
                        multiple: false
                    });
                    mediaUploader.on("select", () => {
                        const attachment = mediaUploader.state().get("selection").first().toJSON();
                        document.querySelector(".qrcdr-placeholder").value = attachment.url;
                        document.querySelector(".qrcdr-get-placeholder").innerHTML = `<img src="${attachment.url}">`;
                    });
                    mediaUploader.open();
                });
            }
            const placeholderResetBtn = document.querySelector(".qrcdr-placeholder-reset");
            if (placeholderResetBtn) {
                placeholderResetBtn.addEventListener("click", e => {
                    e.preventDefault();
                    const defaultUrl = e.currentTarget.dataset.default;
                    document.querySelector(".qrcdr-placeholder").value = defaultUrl;
                    document.querySelector(".qrcdr-get-placeholder").innerHTML = `<img src="${defaultUrl}">`;
                });
            }
            const watermarksUploadBtn = document.querySelector(".qrcdr-watermarks-upload");
            if (watermarksUploadBtn) {
                watermarksUploadBtn.addEventListener("click", e => {
                    e.preventDefault();
                    mediaUploader = wp.media({
                        title: qrcdrAdminVars.i18n.chooseWatermarks,
                        button: {
                            text: qrcdrAdminVars.i18n.chooseWatermarks
                        },
                        multiple: "add"
                    });
                    mediaUploader.on("select", () => {
                        const attachments = mediaUploader.state().get("selection").toJSON();
                        const ids = [];
                        const previewContainer = document.querySelector(".qrcdr-get-watermarks");
                        previewContainer.innerHTML = "";
                        attachments.forEach(item => {
                            ids.push(item.id);
                            const thumbUrl = item.sizes.thumbnail ? item.sizes.thumbnail.url : item.url;
                            previewContainer.innerHTML += `<div data-id="${item.id}" class="qrcdr-wrap-watermark"><img src="${thumbUrl}"><a href="#" class="qrcdr-remove-template"><svg width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M16 8A8 8 0 110 8a8 8 0 0116 0zm-4.146-3.146a.5.5 0 00-.708-.708L8 7.293 4.854 4.146a.5.5 0 10-.708.708L7.293 8l-3.147 3.146a.5.5 0 00.708.708L8 8.707l3.146 3.147a.5.5 0 00.708-.708L8.707 8l3.147-3.146z" clip-rule="evenodd"/></svg></a></div>`;
                        });
                        document.querySelector(".qrcdr-watermarks").value = ids.join(",");
                    });
                    mediaUploader.open();
                });
            }
            const watermarksContainer = document.querySelector(".qrcdr-get-watermarks");
            if (watermarksContainer) {
                watermarksContainer.addEventListener("click", e => {
                    const removeBtn = e.target.closest(".qrcdr-remove-template");
                    if (!removeBtn) return;
                    e.preventDefault();
                    const wrapper = removeBtn.closest(".qrcdr-wrap-watermark");
                    const idToRemove = wrapper.dataset.id;
                    const hiddenInput = document.querySelector(".qrcdr-watermarks");
                    const currentIds = hiddenInput.value.split(",");
                    const newIds = currentIds.filter(id => id !== idToRemove);
                    hiddenInput.value = newIds.join(",");
                    wrapper.remove();
                });
            }
        }
        document.addEventListener("DOMContentLoaded", () => {
            initializeColorPickers();
            initializeTabs();
            initializeMediaUploader();
            initializeRangeSliders();
            initializeColorSettingsPanel();
            initializeDynamicModals();
        });
    })(window.wp.element, window.wp.components);
})();
