<?php

namespace GriffinForms\Admin\App\Html\Modals\FormThemes;

trait Scripts
{
    /**
     * Outputs all JavaScript for the FormThemes modal.
     */
    public function getModalJs()
    {
        $this->modalPreludeJs();
        $this->modalShowEventJs();
        $this->categorySelectJs();
        $this->applyThemeButtonJs();
        $this->importThemeFormJs();
        $this->getRequestsJs();
    }

    /**
     * Outputs shared helpers and state setup for the modal.
     */
    protected function modalPreludeJs()
    {
        echo '
        // FormThemes Modal State and Helpers
        const formthemesModalId = "#griffinforms-builder-modal-formthemes";
        const formthemesCategoriesWrapper = $("#griffinforms-formthemes-categories-container");
        const formthemesContentWrapper = $("#griffinforms-formthemes-content-container");
        const formthemesSelectPane = $("#griffinforms-formthemes-select-theme");
        const formthemesMessageContainer = $("#griffinforms-formthemes-message-container");
        const formthemesContentScroller = $("#griffinforms-formthemes-select-theme .griffinforms-formthemes-content");
        const themePageSize = 6;
        const swatchPlaceholderHeight = 320;

        if (typeof window.griffinformsActiveThemeCategory === "undefined") {
            window.griffinformsActiveThemeCategory = null;
        }

        if (typeof window.griffinformsThemePagination === "undefined") {
            window.griffinformsThemePagination = null;
        }

        const applyThemeDefaultLabel = "' . esc_js(__('Apply Theme', 'griffinforms-form-builder')) . '";
        const applyThemeAppliedLabel = "' . esc_js(__('Applied', 'griffinforms-form-builder')) . '";
        const applyThemeApplyingLabel = "' . esc_js(__('Applying…', 'griffinforms-form-builder')) . '";
        const GF_THEME_FONT_ATTR = "data-gf-theme-font";

        function griffinformsResolveTransparentBgColor(color) {
            if (!color || typeof color !== "string") return "#ffffff";
            const c = color.trim().toLowerCase();
            if (c === "" || c === "transparent") return "#ffffff";
            if (/^rgba?\s*\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*0\s*\)$/.test(c)) return "#ffffff";
            return color;
        }

        function griffinformsTintColor(hex, whiteFraction) {
            if (!hex || typeof hex !== "string") return hex;
            const clean = hex.replace(/^#/, "");
            if (clean.length !== 6 && clean.length !== 3) return hex;
            const full = clean.length === 3
                ? clean.split("").map(c => c + c).join("")
                : clean;
            const r = parseInt(full.slice(0, 2), 16);
            const g = parseInt(full.slice(2, 4), 16);
            const b = parseInt(full.slice(4, 6), 16);
            const tr = Math.round(r + (255 - r) * whiteFraction);
            const tg = Math.round(g + (255 - g) * whiteFraction);
            const tb = Math.round(b + (255 - b) * whiteFraction);
            return "#" + [tr, tg, tb].map(v => v.toString(16).padStart(2, "0")).join("");
        }

        function griffinformsToggleModalSpinner() {
            const spinner = $(formthemesModalId + " .griffinforms-modal-spinner");
            if (spinner.length) {
                spinner.toggleClass("d-none");
            }
        }

        function griffinformsRenderFormThemeNotice(variant, message) {
            const container = $(formthemesMessageContainer);
            if (!container.length) {
                if (variant === "danger") {
                    console.error("FormTheme Error:", message);
                } else {
                    console.log("FormTheme Success:", message);
                }
                return;
            }

            if (typeof message !== "string" || message.trim() === "") {
                container.empty();
                return;
            }

            const noticeClass = variant === "success" ? "gf-notice-success" : "gf-notice-danger";
            const notice = jQuery("<div>", { class: "gf-notice " + noticeClass, role: "alert" });
            notice.text(message);
            container.empty().append(notice);
        }

        function griffinformsShowFormThemeError(message) {
            griffinformsRenderFormThemeNotice("danger", message);
        }

        function griffinformsShowFormThemeSuccess(message) {
            griffinformsRenderFormThemeNotice("success", message);
        }

        function griffinformsBuildThemeFontUrl(fontName) {
            if (!fontName) {
                return "";
            }
            const encoded = encodeURIComponent(fontName.trim()).replace(/%20/g, "+");
            return "https://fonts.googleapis.com/css2?family=" + encoded + ":wght@400;500;600;700&display=swap";
        }

        function griffinformsClearThemeFonts() {
            const links = document.querySelectorAll("link[" + GF_THEME_FONT_ATTR + "]");
            links.forEach(function(link) {
                if (link && link.parentNode) {
                    link.parentNode.removeChild(link);
                }
            });
        }

        function griffinformsApplyThemeFonts(fonts) {
            griffinformsClearThemeFonts();

            if (!Array.isArray(fonts) || fonts.length === 0) {
                return;
            }

            const head = document.head || document.getElementsByTagName("head")[0];
            if (!head) {
                return;
            }

            fonts.forEach(function(fontName) {
                const trimmed = (fontName || "").trim();
                if (!trimmed) {
                    return;
                }

                const fontUrl = griffinformsBuildThemeFontUrl(trimmed);
                if (!fontUrl) {
                    return;
                }

                const link = document.createElement("link");
                link.rel = "stylesheet";
                link.href = fontUrl;
                link.setAttribute(GF_THEME_FONT_ATTR, "1");
                link.setAttribute("data-gf-font-name", trimmed);
                head.appendChild(link);
            });
        }

        function griffinformsSetFormAreaBgColor(pageBgColor) {
            const normalizedBgColor = typeof pageBgColor === "string" ? pageBgColor.trim() : "";
            const seedStyleId = "griffinforms-form-area-bg-seed";
            let seedStyle = document.getElementById(seedStyleId);

            window._gfFormAreaBgColor = normalizedBgColor;

            if (normalizedBgColor) {
                if (!seedStyle) {
                    seedStyle = document.createElement("style");
                    seedStyle.id = seedStyleId;
                    (document.head || document.documentElement).appendChild(seedStyle);
                }
                seedStyle.textContent = "#griffinforms-form-area { background-color: " + normalizedBgColor + " !important; }";
            } else if (seedStyle && seedStyle.parentNode) {
                seedStyle.parentNode.removeChild(seedStyle);
            }

            const formArea = document.getElementById("griffinforms-form-area");
            if (!formArea) {
                return;
            }

            if (normalizedBgColor) {
                formArea.style.setProperty("background-color", normalizedBgColor, "important");
            } else {
                formArea.style.removeProperty("background-color");
            }
        }

        function griffinformsResetThemePagination(category) {
            window.griffinformsThemePagination = {
                category: category || null,
                offset: 0,
                limit: themePageSize,
                loading: false,
                hasMore: true
            };
        }

        function griffinformsGetThemePagination() {
            if (!window.griffinformsThemePagination) {
                griffinformsResetThemePagination(null);
            }
            return window.griffinformsThemePagination;
        }

        function griffinformsRenderThemePlaceholderItems(count) {
            const total = Math.max(1, parseInt(count, 10) || themePageSize);
            let html = "";

            for (let i = 0; i < total; i += 1) {
                html += `
                    <div class="griffinforms-theme-tile griffinforms-theme-placeholder h-100 d-flex flex-column">
                        <div class="griffinforms-theme-tile-swatch mb-3">
                            <div class="griffinforms-theme-placeholder-swatch placeholder-glow">
                                <div class="placeholder w-100 griffinforms-theme-placeholder-block" style="height: ${swatchPlaceholderHeight}px;"></div>
                            </div>
                        </div>
                        <div class="placeholder-glow mb-2">
                            <span class="placeholder griffinforms-theme-placeholder-origin"></span>
                        </div>
                        <div class="placeholder-glow mb-3">
                            <span class="placeholder griffinforms-theme-placeholder-title"></span>
                        </div>
                        <div class="placeholder-glow mb-3">
                            <span class="placeholder d-block griffinforms-theme-placeholder-text mb-2"></span>
                            <span class="placeholder d-block griffinforms-theme-placeholder-text-short"></span>
                        </div>
                        <div class="d-flex gap-2 justify-content-between align-items-center mt-auto pt-2">
                            <span class="placeholder griffinforms-theme-placeholder-btn flex-fill"></span>
                            <span class="placeholder griffinforms-theme-placeholder-btn flex-fill"></span>
                        </div>
                    </div>`;
            }

            return html;
        }

        function griffinformsRenderThemePlaceholders(count) {
            return `<div class="griffinforms-theme-grid">${griffinformsRenderThemePlaceholderItems(count)}</div>`;
        }

        function griffinformsRemoveThemePlaceholders() {
            formthemesContentWrapper.find(".griffinforms-theme-placeholder").remove();
        }

        function griffinformsResolveActiveFormId() {
            let formId = null;

            try {
                if (window.sessionStorage) {
                    const stored = parseInt(window.sessionStorage.getItem("gfFormId"), 10);
                    if (!isNaN(stored) && stored > 0) {
                        formId = stored;
                    }
                }
            } catch (e) {}

            if ((!formId || formId < 1) && formthemesSelectPane.length) {
                const paneAttr = parseInt(formthemesSelectPane.attr("data-active-form-id"), 10);
                if (!isNaN(paneAttr) && paneAttr > 0) {
                    formId = paneAttr;
                }
            }

            if ((!formId || formId < 1) && Array.isArray(window.selectedForms) && window.selectedForms.length > 0) {
                const candidate = parseInt(window.selectedForms[0], 10);
                if (!isNaN(candidate) && candidate > 0) {
                    formId = candidate;
                }
            }

            if (!formId || formId < 1) {
                const layoutForm = $("#griffinforms-app-presentationarea-formlayout").find("[data-gf-formid]").first();
                if (layoutForm.length) {
                    const candidate = parseInt(layoutForm.attr("data-gf-formid"), 10);
                    if (!isNaN(candidate) && candidate > 0) {
                        formId = candidate;
                    }
                }
            }

            return formId && formId > 0 ? formId : null;
        }

        function griffinformsGetButtonLabel(button) {
            const label = button.find(".gf-btn-label");
            return label.length ? label.text() : button.text();
        }

        function griffinformsSetButtonLabel(button, text) {
            const label = button.find(".gf-btn-label");
            if (label.length) {
                label.text(text);
            } else {
                button.text(text);
            }
        }

        function griffinformsSetAppliedIcon(button, isApplied) {
            const checkCircleIcon = \'<svg class="gf-icon" style="width: 1.2rem; height: 1.2rem; flex-shrink: 0; fill: currentColor;" viewBox="0 0 24 24">\' +
                \'<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />\' +
                \'</svg>\';

            if (isApplied) {
                if (button.find(\'.gf-icon\').length === 0) {
                    button.prepend(checkCircleIcon);
                }
            } else {
                button.find(\'.gf-icon\').remove();
            }
        }

        function griffinformsSyncThemeButtons() {
            formthemesContentWrapper.find(".griffinforms-apply-theme-btn").each(function() {
                const btn = $(this);
                const originalAttr = btn.attr("data-original-label");
                const storedOriginal = btn.data("originalLabel");
                const original = storedOriginal || originalAttr || applyThemeDefaultLabel;
                btn.data("originalLabel", original);

                if (btn.attr("data-status") === "applied") {
                    btn.data("status", "applied");
                    griffinformsSetButtonLabel(btn, applyThemeAppliedLabel);
                }
            });
        }

        function griffinformsClearAppliedState() {
            formthemesContentWrapper.find(".griffinforms-theme-tile").removeClass("selected");
            formthemesContentWrapper.find(".griffinforms-apply-theme-btn").each(function() {
                const btn = $(this);
                const original = btn.data("originalLabel") || applyThemeDefaultLabel;
                griffinformsSetButtonLabel(btn, original);
                btn.data("status", "");
                btn.attr("data-status", "");
                btn.removeClass("gf-btn-dark").addClass("gf-btn-primary");
                griffinformsSetAppliedIcon(btn, false);
            });
        }

        function griffinformsMarkAppliedTheme(themeId) {
            griffinformsClearAppliedState();

            if (!themeId) {
                return;
            }

            const selectedTile = formthemesContentWrapper.find(\'.griffinforms-theme-tile[data-theme-id="\' + themeId + \'"]\');
            if (selectedTile.length) {
                selectedTile.addClass("selected");
                const activeBtn = selectedTile.find(".griffinforms-apply-theme-btn");
                griffinformsSetButtonLabel(activeBtn, applyThemeAppliedLabel);
                activeBtn.data("status", "applied");
                activeBtn.attr("data-status", "applied");
                activeBtn.removeClass("gf-btn-primary").addClass("gf-btn-dark");
                griffinformsSetAppliedIcon(activeBtn, true);
            }
        }

        function griffinformsMaybeLoadMoreThemes() {
            const state = griffinformsGetThemePagination();

            if (!state) {
                return;
            }
            if (state.loading) {
                return;
            }
            if (!state.hasMore) {
                return;
            }
            if (!state.category) {
                return;
            }

            const scroller = $("#griffinforms-formthemes-select-theme .griffinforms-formthemes-content");

            if (!scroller.length) {
                return;
            }

            const scrollerElement = scroller.get(0);
            if (!scrollerElement) {
                return;
            }

            const scrollTop = scroller.scrollTop();
            const scrollHeight = scrollerElement.scrollHeight;
            const clientHeight = scroller.outerHeight();
            const remaining = scrollHeight - scrollTop - clientHeight;

            // Load more if: (1) scrolled near bottom OR (2) content doesn\'t fill viewport
            const shouldLoadMore = remaining <= 160 || scrollHeight <= clientHeight;

            if (shouldLoadMore) {
                griffinformsGetFormThemesByCategory(state.category, {
                    offset: state.offset,
                    append: true
                });
            }
        }

        window.griffinformsResolveActiveFormId = griffinformsResolveActiveFormId;
        window.griffinformsShowFormThemeError = griffinformsShowFormThemeError;
        window.griffinformsShowFormThemeSuccess = griffinformsShowFormThemeSuccess;
        window.griffinformsMarkAppliedTheme = griffinformsMarkAppliedTheme;
        window.griffinformsSyncThemeButtons = griffinformsSyncThemeButtons;
        window.griffinformsSetButtonLabel = griffinformsSetButtonLabel;
        window.griffinformsGetButtonLabel = griffinformsGetButtonLabel;
        window.griffinformsRenderThemePlaceholders = griffinformsRenderThemePlaceholders;
        window.griffinformsRemoveThemePlaceholders = griffinformsRemoveThemePlaceholders;
        window.griffinformsResetThemePagination = griffinformsResetThemePagination;
        window.griffinformsGetThemePagination = griffinformsGetThemePagination;
        window.griffinformsMaybeLoadMoreThemes = griffinformsMaybeLoadMoreThemes;
        window.griffinformsApplyThemeFonts = griffinformsApplyThemeFonts;
        window.griffinformsClearThemeFonts = griffinformsClearThemeFonts;

        $(document).ready(function() {
            if (Array.isArray(window.griffinformsInitialThemeFonts) && window.griffinformsInitialThemeFonts.length > 0) {
                griffinformsApplyThemeFonts(window.griffinformsInitialThemeFonts);
            } else {
                griffinformsClearThemeFonts();
            }
        });
        ';
    }

    /**
     * Outputs JavaScript to handle modal show event.
     */
    protected function modalShowEventJs()
    {
        echo '
            const formthemesModal = $(formthemesModalId);

            if (formthemesModal.length) {
                formthemesModal.on("show.bs.modal", function() {
                    if (!formthemesCategoriesWrapper.find(".griffinforms-theme-category-btn").length) {
                        griffinformsGetFormThemeCategories();
                    }

                    // Attach scroll event listener when modal is shown
                    const contentScroller = $("#griffinforms-formthemes-select-theme .griffinforms-formthemes-content");

                    if (contentScroller.length) {
                        contentScroller.off("scroll", griffinformsMaybeLoadMoreThemes);
                        contentScroller.on("scroll", function(e) {
                            griffinformsMaybeLoadMoreThemes();
                        });

                        // Check immediately if we should load more
                        griffinformsMaybeLoadMoreThemes();
                    }
                });

                // Clear import form when modal is closed
                formthemesModal.on("hide.bs.modal", function() {
                    const importForm = document.getElementById("griffinforms-import-theme-form");
                    if (importForm) {
                        importForm.dispatchEvent(new CustomEvent("griffinforms-clear-form"));
                    }
                });
            }

            // Command palette context: scroll to a specific theme tile, or activate a tab.
            document.addEventListener("gf-palette-modal-context", function(e) {
                if (!e.detail || e.detail.modal_id !== "griffinforms-builder-modal-formthemes") { return; }
                var ctx    = e.detail.context || {};
                var tab    = ctx.tab;
                var themeId = ctx.theme_id;
                formthemesModal.one("shown.bs.modal", function() {
                    if (tab) {
                        var tabBtn = document.getElementById("griffinforms-formthemes-" + tab + "-tab");
                        if (tabBtn) { tabBtn.click(); }
                    }
                    if (themeId) {
                        setTimeout(function() {
                            var tile = formthemesContentWrapper.find(\'.griffinforms-theme-tile[data-theme-id="\' + themeId + \'"]\');
                            if (tile.length) {
                                tile[0].scrollIntoView({ behavior: "smooth", block: "center" });
                                tile.addClass("gf-palette-highlight");
                                setTimeout(function() { tile.removeClass("gf-palette-highlight"); }, 1500);
                            }
                        }, 100);
                    }
                });
            });
        ';
    }

    /**
     * Outputs JavaScript to handle category selection.
     */
    protected function categorySelectJs()
    {
        echo '
            $(document).on("click", ".griffinforms-theme-category-btn", function() {
                const categoryBtn = $(this);
                const category = (categoryBtn.data("category") || "").toString();

                if (!category) {
                    return;
                }

                if (categoryBtn.hasClass("active") && window.griffinformsThemePagination && window.griffinformsThemePagination.category === category) {
                    return;
                }

                $(".griffinforms-theme-category-btn").removeClass("active");
                categoryBtn.addClass("active");
                window.griffinformsActiveThemeCategory = category;

                griffinformsResetThemePagination(category);

                if (typeof formthemesContentScroller !== "undefined" && formthemesContentScroller.length) {
                    formthemesContentScroller.scrollTop(0);
                }

                griffinformsGetFormThemesByCategory(category, { offset: 0 });
            });
        ';
    }

    /**
     * Outputs JavaScript to handle applying a theme to the active form.
     */
    protected function applyThemeButtonJs()
    {
        echo '
            $(document).on("click", ".griffinforms-apply-theme-btn", function() {
                const button = $(this);
                const themeId = parseInt(button.data("theme-id"), 10);

                if (Number.isNaN(themeId)) {
                    griffinformsShowFormThemeError("' . esc_js(__('Invalid theme selection.', 'griffinforms-form-builder')) . '");
                    return;
                }

                const formId = griffinformsResolveActiveFormId();
                if (!formId) {
                    griffinformsShowFormThemeError("' . esc_js(__('Please select or open a form before applying a theme.', 'griffinforms-form-builder')) . '");
                    return;
                }

                const originalLabel = button.data("originalLabel") || griffinformsGetButtonLabel(button);
                button.data("originalLabel", originalLabel);
                button.data("status", "");

                griffinformsSetButtonLabel(button, applyThemeApplyingLabel);
                button.prop("disabled", true).addClass("is-disabled").attr("aria-busy", "true");
                griffinformsToggleModalSpinner();

                griffinformsApplyFormTheme(formId, themeId)
                    .done(function(response) {
                        if (response && response.success) {
                            const message = response.data && response.data.message
                                ? response.data.message
                                : "' . esc_js(__('Theme applied to form.', 'griffinforms-form-builder')) . '";

                            griffinformsShowFormThemeSuccess(message);
                            if (typeof statusbarMsg === "function") {
                                statusbarMsg("success", message);
                            }

                            try {
                                if (window.sessionStorage) {
                                    window.sessionStorage.setItem("gfFormId", formId);
                                }
                            } catch (e) {}

                            try {
                                document.dispatchEvent(new Event("form-layout"));
                            } catch (e) {}

                            try {
                                document.dispatchEvent(new CustomEvent("form-updated", { detail: { type: "theme", formId: formId } }));
                            } catch (e) {}

                            try {
                                document.dispatchEvent(new CustomEvent("form-theme-applied", { detail: { formId: formId, themeId: themeId, changed: !!(response.data && response.data.changed) } }));
                            } catch (e) {}

                            // Update data-gf-theme-id attribute on form container
                            if (response.data && response.data.theme_id !== undefined) {
                                const formContainer = $(".griffinforms-app-formlayout-form");
                                if (formContainer.length) {
                                    formContainer.attr("data-gf-theme-id", parseInt(response.data.theme_id, 10));
                                }
                            }

                            if (response.data) {
                                if (response.data.has_theme) {
                                    griffinformsApplyThemeFonts(response.data.external_fonts || []);
                                } else {
                                    griffinformsClearThemeFonts();
                                }

                                if ("page_bg_color" in response.data) {
                                    const rawBgColor = response.data.has_theme ? (response.data.page_bg_color || "") : "";
                                    const resolvedBgColor = rawBgColor ? griffinformsResolveTransparentBgColor(rawBgColor) : "";
                                    const pageBgColor = resolvedBgColor ? griffinformsTintColor(resolvedBgColor, 0.7) : "";
                                    griffinformsSetFormAreaBgColor(pageBgColor);
                                }
                            }

                            griffinformsMarkAppliedTheme(themeId);
                            button.data("status", "applied");

                            // Clear modal contents and close after successful apply.
                            formthemesCategoriesWrapper.empty();
                            formthemesContentWrapper.empty();
                            if (formthemesMessageContainer.length) {
                                formthemesMessageContainer.empty();
                            }

                            window.griffinformsActiveThemeCategory = null;
                            window.griffinformsThemePagination = null;

                            const modalElement = $(formthemesModalId).get(0);
                            if (modalElement && typeof bootstrap !== "undefined" && typeof bootstrap.Modal !== "undefined") {
                                const modalInstance = bootstrap.Modal.getInstance(modalElement) || new bootstrap.Modal(modalElement);
                                modalInstance.hide();
                            } else {
                                $(formthemesModalId).modal("hide");
                            }
                        } else {
                            const message = response && response.data && response.data.msg
                                ? response.data.msg
                                : "' . esc_js(__('Unable to apply theme.', 'griffinforms-form-builder')) . '";

                            griffinformsShowFormThemeError(message);
                            if (typeof statusbarMsg === "function") {
                                statusbarMsg("danger", message);
                            }
                        }
                    })
                    .fail(function(xhr, status) {
                        const message = "' . esc_js(__('Could not apply theme. Please try again.', 'griffinforms-form-builder')) . '";
                        griffinformsShowFormThemeError(message);
                        if (typeof statusbarMsg === "function") {
                            statusbarMsg("danger", message + " (" + status + ")");
                        }
                    })
                    .always(function() {
                        griffinformsToggleModalSpinner();
                        button.prop("disabled", false).removeClass("is-disabled").attr("aria-busy", "false");
                        if (button.data("status") !== "applied") {
                            griffinformsSetButtonLabel(button, button.data("originalLabel"));
                        }
                    });
            });
        ';
    }

    /**
     * Outputs JavaScript for the Import Theme form.
     */
    protected function importThemeFormJs()
    {
        echo '
        // Import Theme Form Handling
        (function() {
            const importForm = document.getElementById("griffinforms-import-theme-form");
            const nameInput = document.getElementById("theme-name-input");
            const categorySelect = document.getElementById("theme-category-select");
            const descriptionTextarea = document.getElementById("theme-description-textarea");
            const jsonFileInput = document.getElementById("theme-json-file");
            const submitButton = document.getElementById("griffinforms-import-theme-submit");
            const messageDiv = document.getElementById("griffinforms-import-theme-message");
            const messageText = document.getElementById("griffinforms-import-theme-message-text");
            const importThemeTab = document.getElementById("griffinforms-formthemes-import-theme-tab");

            if (!importForm) return;

            // Clear form when modal is closed
            importForm.addEventListener("griffinforms-clear-form", function() {
                clearImportForm();
            });

            // Populate categories dropdown when Import tab is shown
            importThemeTab.addEventListener("shown.bs.tab", function() {
                populateImportCategories();
            });

            // Handle file input change - read JSON and auto-populate fields
            jsonFileInput.addEventListener("change", function() {
                if (!this.files || !this.files[0]) {
                    clearValidationMessage("theme-json-error");
                    return;
                }

                const file = this.files[0];

                // Check file size (1 MB = 1048576 bytes)
                if (file.size > 1048576) {
                    showValidationError("theme-json-error", "' . esc_js(__('File size exceeds 1 MB limit.', 'griffinforms-form-builder')) . '");
                    return;
                }

                const reader = new FileReader();
                reader.onload = function(e) {
                    try {
                        const jsonContent = e.target.result;
                        const parsedJson = JSON.parse(jsonContent);

                        // Validate basic structure
                        if (!parsedJson || typeof parsedJson !== "object") {
                            showValidationError("theme-json-error", "' . esc_js(__('Invalid JSON format.', 'griffinforms-form-builder')) . '");
                            return;
                        }

                        clearValidationMessage("theme-json-error");

                        // Auto-populate name if empty and available in JSON
                        if (!nameInput.value.trim() && parsedJson.theme_name) {
                            nameInput.value = parsedJson.theme_name;
                            nameInput.classList.add("is-autofilled");
                        }

                        // Auto-populate description if empty and available in JSON
                        if (!descriptionTextarea.value.trim() && parsedJson.theme_description) {
                            descriptionTextarea.value = parsedJson.theme_description;
                            descriptionTextarea.classList.add("is-autofilled");
                        }

                        // Auto-populate category if empty and available in JSON
                        if (!categorySelect.value && parsedJson.theme_category) {
                            categorySelect.value = parsedJson.theme_category;
                            categorySelect.classList.add("is-autofilled");
                        }
                    } catch (error) {
                        showValidationError("theme-json-error", "' . esc_js(__('Invalid JSON format.', 'griffinforms-form-builder')) . '");
                    }
                };
                reader.readAsText(file);
            });

            // Handle form submission
            importForm.addEventListener("submit", function(e) {
                e.preventDefault();

                // Clear previous messages
                hideMessage();
                clearAllValidationErrors();

                // Validate form
                if (!validateImportForm()) {
                    return;
                }

                // Lock form during submission
                lockForm();

                // Read file content
                const file = jsonFileInput.files[0];
                const reader = new FileReader();

                reader.onerror = function() {
                    showMessage("danger", "' . esc_js(__('Failed to read file.', 'griffinforms-form-builder')) . '");
                    unlockForm();
                };

                reader.onload = function(e) {
                    try {
                        const jsonContent = e.target.result;

                        // Send AJAX request using jQuery (more reliable)
                        jQuery.ajax({
                            url: ajaxurl,
                            type: "POST",
                            data: {
                                action: "importFormTheme",
                                nonce: "' . esc_js(wp_create_nonce('import_form_theme')) . '",
                                theme_name: nameInput.value.trim(),
                                theme_category: categorySelect.value,
                                theme_description: descriptionTextarea.value.trim(),
                                theme_json: jsonContent
                            },
                            dataType: "json",
                            success: function(response) {
                                if (response.success) {
                                    // Show success message
                                    showMessage("success", response.data.msg);

                                    // Clear form after 1.5 seconds
                                    setTimeout(function() {
                                        clearImportForm();

                                        // Switch to Select Theme tab
                                        const selectThemeTab = new bootstrap.Tab(document.getElementById("griffinforms-formthemes-select-theme-tab"));
                                        selectThemeTab.show();

                                        // Hide success message after 2 seconds
                                        setTimeout(function() {
                                            hideMessage();
                                        }, 2000);
                                    }, 1500);
                                } else {
                                    // Show error message
                                    showMessage("danger", response.data.msg);

                                    // Highlight the field with error if specified
                                    if (response.data.field) {
                                        showValidationError(response.data.field + "-error", response.data.msg);
                                    }
                                }

                                unlockForm();
                            },
                            error: function(xhr, status, error) {
                                console.error("Import AJAX error:", {
                                    status: status,
                                    error: error,
                                    statusCode: xhr.status,
                                    responseText: xhr.responseText,
                                    responseJSON: xhr.responseJSON
                                });

                                let errorMsg = "' . esc_js(__('An error occurred. Please try again.', 'griffinforms-form-builder')) . '";
                                try {
                                    const response = jQuery.parseJSON(xhr.responseText);
                                    if (response && response.data && response.data.msg) {
                                        errorMsg = response.data.msg;
                                    }
                                } catch (e) {
                                    // Use default message if response is not JSON
                                }

                                showMessage("danger", errorMsg);
                                unlockForm();
                            }
                        });
                    } catch (error) {
                        console.error("File processing error:", error);
                        showMessage("danger", "' . esc_js(__('An error occurred while processing the file.', 'griffinforms-form-builder')) . '");
                        unlockForm();
                    }
                };

                reader.readAsText(file);
            });

            // Helper functions
            function populateImportCategories() {
                jQuery.ajax({
                    url: ajaxurl,
                    type: "POST",
                    data: {
                        action: "getFormThemeCategories",
                        nonce: "' . esc_js(wp_create_nonce('get_form_theme_categories')) . '"
                    },
                    dataType: "json",
                    success: function(response) {
                        if (response.success && response.data.categories) {
                            const categories = response.data.categories;
                            categorySelect.innerHTML = "<option value=\"\">-- ' . esc_js(__('Select Category', 'griffinforms-form-builder')) . ' --</option>";

                            categories.forEach(function(category) {
                                const option = document.createElement("option");
                                const categoryValue = typeof category === "string" ? category : (category.category || category);
                                option.value = categoryValue;
                                // Capitalize the first letter of each word
                                option.textContent = categoryValue.charAt(0).toUpperCase() + categoryValue.slice(1);
                                categorySelect.appendChild(option);
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("Error loading categories:", status, error);
                    }
                });
            }

            function validateImportForm() {
                let isValid = true;

                // Validate name
                const nameValue = nameInput.value.trim();
                if (!nameValue) {
                    showValidationError("theme-name-error", "' . esc_js(__('Theme name is required', 'griffinforms-form-builder')) . '");
                    isValid = false;
                } else if (nameValue.length > 100) {
                    showValidationError("theme-name-error", "' . esc_js(__('Theme name cannot exceed 100 characters', 'griffinforms-form-builder')) . '");
                    isValid = false;
                }

                // Validate category
                if (!categorySelect.value) {
                    showValidationError("theme-category-error", "' . esc_js(__('Category is required', 'griffinforms-form-builder')) . '");
                    isValid = false;
                }

                // Validate description length
                const descriptionValue = descriptionTextarea.value.trim();
                if (descriptionValue.length > 500) {
                    showValidationError("theme-description-error", "' . esc_js(__('Description cannot exceed 500 characters', 'griffinforms-form-builder')) . '");
                    isValid = false;
                }

                // Validate JSON file
                if (!jsonFileInput.files || !jsonFileInput.files[0]) {
                    showValidationError("theme-json-error", "' . esc_js(__('JSON file is required', 'griffinforms-form-builder')) . '");
                    isValid = false;
                } else {
                    const file = jsonFileInput.files[0];
                    if (file.size > 1048576) {
                        showValidationError("theme-json-error", "' . esc_js(__('File size exceeds 1 MB limit', 'griffinforms-form-builder')) . '");
                        isValid = false;
                    }
                }

                return isValid;
            }

            function showValidationError(elementId, message) {
                const element = document.getElementById(elementId);
                if (element) {
                    element.textContent = message;
                    element.style.display = "block";
                }
            }

            function clearValidationMessage(elementId) {
                const element = document.getElementById(elementId);
                if (element) {
                    element.textContent = "";
                    element.style.display = "none";
                }
            }

            function clearAllValidationErrors() {
                ["theme-name-error", "theme-category-error", "theme-description-error", "theme-json-error"].forEach(function(id) {
                    clearValidationMessage(id);
                });
            }

            function showMessage(type, message) {
                const noticeClass = type === "success" ? "gf-notice-success" : "gf-notice-danger";
                messageDiv.className = "gf-notice " + noticeClass;
                messageDiv.setAttribute("role", "alert");
                messageText.textContent = message;
                messageDiv.style.display = "block";
            }

            function hideMessage() {
                messageDiv.style.display = "none";
                messageDiv.className = "gf-notice";
                messageText.textContent = "";
            }

            function lockForm() {
                nameInput.disabled = true;
                categorySelect.disabled = true;
                descriptionTextarea.disabled = true;
                jsonFileInput.disabled = true;
                submitButton.disabled = true;
            }

            function unlockForm() {
                nameInput.disabled = false;
                categorySelect.disabled = false;
                descriptionTextarea.disabled = false;
                jsonFileInput.disabled = false;
                submitButton.disabled = false;
            }

            function clearImportForm() {
                nameInput.value = "";
                categorySelect.value = "";
                descriptionTextarea.value = "";
                jsonFileInput.value = "";
                nameInput.classList.remove("is-autofilled");
                descriptionTextarea.classList.remove("is-autofilled");
                categorySelect.classList.remove("is-autofilled");
                clearAllValidationErrors();
            }
        })();
        ';
    }
}
