/**
 * LiveLang Admin Dashboard Scripts
 * Handles tab switching, AJAX translations management, and switcher preview.
 */
jQuery(document).ready(function($) {
    var $navItems = $(".livelang-nav-item");
    var $panels = $(".livelang-tab-panel");

    /**
     * Activate a specific tab
     */
    function activateTab(name) {
        if (!name) name = 'general';

        $navItems.removeClass("is-active");
        $navItems.filter('[data-livelang-tab="' + name + '"]').addClass("is-active");

        $panels.hide().removeClass("is-active");
        var $activePanel = $("#livelang-tab-" + name);
        
        if ($activePanel.length) {
            $activePanel.fadeIn(200).addClass("is-active");
        } else {
            // Fallback to general if tab ID not found
            $("#livelang-tab-general").show().addClass("is-active");
            $navItems.filter('[data-livelang-tab="general"]').addClass("is-active");
        }

        // Load languages if the Language Manager tab is opened
        if (name === "languages") {
            loadLanguages();
        }
    }

    // Initial State: URL Param 'tab' takes priority, then localStorage, then default 'general'
    var urlParams = new URLSearchParams(window.location.search);
    var activeTab = urlParams.get("tab") || localStorage.getItem("livelang_active_tab") || "general";
    activateTab(activeTab);

    // Sidebar Tab Click Handler
    $navItems.on("click", function(e) {
        var tab = $(this).attr("data-livelang-tab");
        if (tab) {
            e.preventDefault();
            activateTab(tab);
            localStorage.setItem("livelang_active_tab", tab);
            
            // Update URL without reload to keep it in sync
            if (window.history.pushState) {
                var newUrl = new URL(window.location.href);
                newUrl.searchParams.set('tab', tab);
                window.history.pushState({path:newUrl.href}, '', newUrl.href);
            }
        }
    });

    function showToast(msg) {
        $(".livelang-toast").remove();
        var $toast = $('<div class="livelang-toast"><span>⚡</span> ' + msg + '</div>');
        $("body").append($toast);
        setTimeout(function() { $toast.addClass("show"); }, 10);
        setTimeout(function() {
            $toast.removeClass("show");
            setTimeout(function() { $toast.remove(); }, 300);
        }, 3000);
    }

    $("#livelang-quick-flush-btn, #livelang-flush-cache-btn, #livelang-flush-cache-btn-main").on("click", function (e) {
        e.preventDefault();
        var $btn = $(this);
        $btn.attr("disabled", true).css("opacity", "0.5");

        $.ajax({
            url: LiveLangAdminSettings.ajaxUrl,
            type: "POST",
            data: {
                action: "livelang_flush_cache",
                _ajax_nonce: $btn.data("nonce"),
            },
            success: function (response) {
                if (response.success) {
                    showToast("Translation cache flushed successfully!");
                } else {
                    showToast("Unable to flush cache.");
                }
            },
            error: function () {
                showToast("Server error occurred.");
            },
            complete: function () {
                $btn.attr("disabled", false).css("opacity", "1");
            },
        });
    });

    /**
     * Translations screen: Danger Zone. Deletion always requires an
     * explicit scope plus typing "DELETE" - nothing here can be triggered
     * by a single accidental click.
     */
    var $dangerScope = $("#livelang-danger-scope");
    var $dangerLanguage = $("#livelang-danger-language");
    var $dangerConfirmWrap = $("#livelang-danger-confirm-wrap");
    var $dangerConfirmInput = $("#livelang-danger-confirm-input");
    var $dangerSubmit = $("#livelang-danger-submit");

    function updateDangerZoneState() {
        var scope = $dangerScope.val();
        $dangerLanguage.toggle(scope === "language");
        $dangerConfirmWrap.toggle(!!scope);

        var confirmed = $dangerConfirmInput.val().trim().toUpperCase() === "DELETE";
        var scopeReady = !!scope && (scope !== "language" || !!$dangerLanguage.val());
        $dangerSubmit.prop("disabled", !(scope && scopeReady && confirmed));
    }

    if ($dangerScope.length) {
        $dangerScope.on("change", updateDangerZoneState);
        $dangerLanguage.on("change", updateDangerZoneState);
        $dangerConfirmInput.on("input", updateDangerZoneState);

        $dangerSubmit.on("click", function () {
            var scope = $dangerScope.val();
            var language = $dangerLanguage.val();
            var confirmText = $dangerConfirmInput.val().trim();

            if (
                !confirm(
                    "This will permanently delete translation data. This cannot be undone. Continue?",
                )
            ) {
                return;
            }

            var $btn = $(this);
            $btn.prop("disabled", true).text("Deleting…");

            $.ajax({
                url: LiveLangAdminSettings.ajaxUrl,
                type: "POST",
                data: {
                    action: "livelang_clear_translations",
                    _ajax_nonce: $btn.data("nonce"),
                    scope: scope,
                    language: language,
                    confirm_text: confirmText,
                },
                success: function (response) {
                    if (response.success) {
                        alert("Translation data deleted.");
                        location.reload();
                    } else {
                        alert(
                            "Error: " +
                                (response.data && response.data.message
                                    ? response.data.message
                                    : "Unable to delete."),
                        );
                    }
                },
                error: function () {
                    alert("A server error occurred.");
                },
                complete: function () {
                    $btn.prop("disabled", false).text("Permanently Delete");
                    updateDangerZoneState();
                },
            });
        });
    }

    /**
     * Language Manager Logic
     */
    var languagesCount = 0;

    function loadLanguages() {
        $.ajax({
            url: LiveLangAdminSettings.ajaxUrl,
            type: "POST",
            data: {
                action: "livelang_get_languages",
                _ajax_nonce: LiveLangAdminSettings.langNonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    renderLanguages(response.data);
                    initSortable();
                }
            }
        });
    }

    function renderLanguages(languages) {
        var $tbody = $("#livelang-languages-tbody");
        if (!$tbody.length) return;

        $tbody.empty();
        languagesCount = languages.length;

        if (languagesCount === 0) {
            $tbody.html('<tr><td colspan="5" style="text-align:center; padding:40px; color:#94a3b8;">No languages found.</td></tr>');
            updateAddBtnUI();
            return;
        }

        updateAddBtnUI();

        languages.forEach(function(lang) {
            var $row = $('<tr data-code="' + lang.code + '">');
            
            $row.append('<td style="cursor:move; color:#cbd5e1; font-size:18px;">⋮⋮</td>');
            $row.append('<td><span class="livelang-header-badge" style="background:#f1f5f9; color:#475569; margin:0;">' + lang.code.toUpperCase() + '</span></td>');
            
            var $labelInput = $('<input type="text" value="' + lang.label + '" style="width:100%; padding:6px 10px; border:1px solid #e2e8f0; border-radius:6px;">');
            $row.append($('<td>').append($labelInput));

            var $defaultRadio = $('<input type="radio" name="default_language" value="' + lang.code + '"' + (lang.is_default == 1 ? ' checked' : '') + '>');
            $row.append($('<td style="text-align:center;">').append($defaultRadio));

            var $actions = $('<td style="text-align:right;">');
            var $saveBtn = $('<button class="livelang-btn livelang-btn-outline" style="padding:4px 8px; margin-right:6px;" title="Save Changes"><span class="dashicons dashicons-saved" style="font-size:16px;"></span></button>');
            var $delBtn = $('<button class="livelang-btn livelang-btn-outline" style="padding:4px 8px; color:var(--livelang-danger);" title="Remove"><span class="dashicons dashicons-trash" style="font-size:16px;"></span></button>');
            
            $saveBtn.on("click", function() { updateLanguage(lang.code, $labelInput.val()); });
            $delBtn.on("click", function() { if (confirm("Remove this language?")) deleteLanguage(lang.code); });
            $defaultRadio.on("change", function() { if (this.checked) setDefaultLanguage(lang.code); });

            $actions.append($saveBtn).append($delBtn);
            $row.append($actions);

            $tbody.append($row);
        });
    }

    function updateAddBtnUI() {
        var $addBtn = $("#livelang-add-language-btn");
        if (!$addBtn.length) return;

        if (!LiveLangAdminSettings.isPro && languagesCount >= 3) {
            $addBtn.css('opacity', '0.6').attr('title', 'Limit reached. Upgrade to Pro.');
        } else {
            $addBtn.css('opacity', '1').attr('title', '');
        }
    }

    function initSortable() {
        var $tbody = $("#livelang-languages-tbody");
        if (!$tbody.length) return;

        $tbody.sortable({
            items: "tr",
            update: function() {
                var order = [];
                $tbody.find("tr").each(function() { order.push($(this).data("code")); });
                reorderLanguages(order);
            }
        });
    }

    /**
     * Show a beautiful Pro upgrade modal
     */
    function showProModal(featureName) {
        var $modal = $('<div class="livelang-modal-overlay">' +
            '<div class="livelang-modal">' +
                '<div class="livelang-modal-header">' +
                    '<h3>🚀 ' + (featureName || 'Pro Feature') + '</h3>' +
                    '<button class="livelang-modal-close">&times;</button>' +
                '</div>' +
                '<div class="livelang-modal-body">' +
                    '<p>You\'ve reached the limit of the free version. To unlock unlimited languages and premium features, please upgrade to LiveLang Pro.</p>' +
                '</div>' +
                '<div class="livelang-modal-footer">' +
                    '<a href="' + LiveLangAdminSettings.planUpgradeUrl + '" class="livelang-btn livelang-btn-primary">View Pricing & Upgrade</a>' +
                    '<button class="livelang-btn livelang-btn-outline livelang-modal-close">Maybe Later</button>' +
                '</div>' +
            '</div>' +
        '</div>');

        $("body").append($modal);
        
        // Use a small timeout to trigger CSS animation
        setTimeout(function() {
            $modal.addClass("livelang-modal-fade-in");
        }, 10);

        $modal.on("click", ".livelang-modal-close", function() {
            $modal.removeClass("livelang-modal-fade-in");
            setTimeout(function() { $modal.remove(); }, 400);
        });
    }

    function addLanguage() {
        if (!LiveLangAdminSettings.isPro && languagesCount >= 3) {
            showProModal('Unlimited Languages');
            return;
        }

        var $codeInput = $("#livelang-language-code");
        var code = $codeInput.val();
        var label = $codeInput.find("option:selected").text().split(" (")[0];

        if (!code) {
            alert("Please select a language.");
            return;
        }

        $.ajax({
            url: LiveLangAdminSettings.ajaxUrl,
            type: "POST",
            data: {
                action: "livelang_add_language",
                _ajax_nonce: LiveLangAdminSettings.langNonce,
                code: code,
                label: label
            },
            success: function(response) {
                if (response.success) loadLanguages();
                else {
                    if (response.data && response.data.message && response.data.message.indexOf('limit') !== -1) {
                         showProModal('Unlimited Languages');
                    } else {
                        alert(response.data.message || "Error adding language");
                    }
                }
            }
        });
    }

    function updateLanguage(code, label) {
        $.ajax({
            url: LiveLangAdminSettings.ajaxUrl,
            type: "POST",
            data: {
                action: "livelang_update_language",
                _ajax_nonce: LiveLangAdminSettings.langNonce,
                code: code,
                label: label
            },
            success: function(response) {
                if (response.success) alert("Language updated.");
                else alert(response.data.message || "Error updating language");
            }
        });
    }

    function deleteLanguage(code) {
        $.ajax({
            url: LiveLangAdminSettings.ajaxUrl,
            type: "POST",
            data: {
                action: "livelang_delete_language",
                _ajax_nonce: LiveLangAdminSettings.langNonce,
                code: code
            },
            success: function(response) {
                if (response.success) loadLanguages();
                else alert(response.data.message || "Error deleting language");
            }
        });
    }

    function reorderLanguages(order) {
        $.ajax({
            url: LiveLangAdminSettings.ajaxUrl,
            type: "POST",
            data: {
                action: "livelang_reorder_languages",
                _ajax_nonce: LiveLangAdminSettings.langNonce,
                order: order
            }
        });
    }

    function setDefaultLanguage(code) {
        $.ajax({
            url: LiveLangAdminSettings.ajaxUrl,
            type: "POST",
            data: {
                action: "livelang_set_default_language",
                _ajax_nonce: LiveLangAdminSettings.langNonce,
                code: code
            },
            success: function(response) {
                if (response.success) loadLanguages();
            }
        });
    }

    // Add Language Button Event
    $("#livelang-add-language-btn").on("click", function(e) { e.preventDefault(); addLanguage(); });


    /**
     * Floating Switcher Preview Logic
     */
    var $pos = $("#livelang-switcher-position");
    var $bg = $("#livelang-switcher-bg-color");
    var $txt = $("#livelang-switcher-text-color");
    var $acc = $("#livelang-switcher-accent-color");
    var $en = $("#livelang-switcher-enabled");
    var $prev = $("#livelang-floating-preview");

    function updatePreview() {
        if (!$prev.length) return;

        // Enabled/Disabled state
        if ($en.length && !$en.is(":checked")) $prev.addClass("is-disabled");
        else $prev.removeClass("is-disabled");

        // Position - ensure hyphenated classes match CSS
        var currentPos = $pos.val() || 'bottom-right';
        $prev.removeClass('bottom-right bottom-left top-right top-left').addClass(currentPos);

        // Styles
        var bgVal = $bg.val();
        var txtVal = $txt.val();
        var accVal = $acc.val();

        $prev.find(".livelang-preview-btn").css({
            'background-color': bgVal,
            'color': txtVal,
            'border-color': bgVal
        });

        $prev.find(".livelang-preview-dropdown").css({
            'background-color': bgVal,
            'color': txtVal
        });

        $prev.find(".livelang-dropdown-item.active").css({
            'border-left-color': accVal,
            'color': accVal
        });
    }

    if ($pos.length) {
        $([$pos[0], $bg[0], $txt[0], $acc[0], $en[0]]).on("change input", updatePreview);
        updatePreview();
    }

    /**
     * Translations table: "select all" checkbox + disable bulk Apply
     * until at least one row (or an action) is selected.
     */
    var $selectAll = $("#livelang-select-all");
    var $rowCheckboxes = $(".livelang-row-checkbox");
    var $bulkForm = $("#livelang-bulk-form");

    $selectAll.on("change", function () {
        $rowCheckboxes.prop("checked", $(this).is(":checked"));
    });

    $rowCheckboxes.on("change", function () {
        var allChecked = $rowCheckboxes.length === $rowCheckboxes.filter(":checked").length;
        $selectAll.prop("checked", allChecked);
    });

    if ($bulkForm.length) {
        $bulkForm.on("submit", function (e) {
            var action = $bulkForm.find('select[name="bulk_action"]').val();
            var anyChecked = $rowCheckboxes.filter(":checked").length > 0;
            if (!action || !anyChecked) {
                e.preventDefault();
                alert(
                    !action
                        ? "Please choose a bulk action first."
                        : "Please select at least one row."
                );
            }
        });
    }
});
