(function ($) {
    'use strict';

    var S;

    function showMsg($el, text, variant) {
        if (!$el.length) {
            return;
        }
        $el.removeClass('is-error is-success is-info');
        if (variant === 'error') {
            $el.addClass('is-error');
        } else if (variant === 'success') {
            $el.addClass('is-success');
        } else {
            $el.addClass('is-info');
        }
        $el.text(text || '').prop('hidden', !text);
    }

    function spin($sp, on) {
        if ($sp.length) {
            $sp.toggleClass('is-active', !!on);
        }
    }

    function applyBadge($panel, active, hasKey) {
        var $b = $panel.find('.pg-license-badge');
        $b.removeClass('pg-license-badge--ok pg-license-badge--warn pg-license-badge--off');
        if (active) {
            $b.addClass('pg-license-badge--ok').text(S.badge_active);
        } else if (hasKey) {
            $b.addClass('pg-license-badge--warn').text(S.badge_pending);
        } else {
            $b.addClass('pg-license-badge--off').text(S.badge_none);
        }
    }

    function formatLicenseKey(value) {
        value = String(value || '').toUpperCase().replace(/[^A-Z0-9]/g, '');
        if (value.length > 4) {
            value = value.match(/.{1,4}/g).join('-');
        }
        var parts = value.split('-');
        if (parts.length > 5) {
            value = parts.slice(0, 5).join('-');
        }
        return value;
    }

    function postActivate(licenseKey, $panel, $sp, $msgEl) {
        spin($sp, true);
        showMsg($msgEl, S.working, 'info');

        $.ajax({
            url: pulsegridThemeLicense.ajax_url,
            type: 'POST',
            data: {
                action: 'pulsegrid_theme_activate_license',
                nonce: pulsegridThemeLicense.nonce,
                license_key: licenseKey || ''
            },
            success: function (response) {
                spin($sp, false);
                if (response && response.success) {
                    showMsg($msgEl, response.data.message || '', 'success');
                    window.location.reload();
                } else {
                    var message = (response && response.data && response.data.message) || S.error;
                    showMsg($msgEl, message, 'error');
                }
            },
            error: function () {
                spin($sp, false);
                showMsg($msgEl, S.network, 'error');
            }
        });
    }

    function postDeactivate($panel, $sp, $msgEl) {
        spin($sp, true);
        showMsg($msgEl, S.working, 'info');

        $.ajax({
            url: pulsegridThemeLicense.ajax_url,
            type: 'POST',
            data: {
                action: 'pulsegrid_theme_deactivate_license',
                nonce: pulsegridThemeLicense.nonce
            },
            success: function (response) {
                spin($sp, false);
                if (response && response.success) {
                    showMsg($msgEl, response.data.message || '', 'success');
                    window.location.reload();
                } else {
                    var message = (response && response.data && response.data.message) || S.error;
                    showMsg($msgEl, message, 'error');
                }
            },
            error: function () {
                spin($sp, false);
                showMsg($msgEl, S.network, 'error');
            }
        });
    }

    $(document).ready(function () {
        var $panel = $('[data-pg-license-panel]');
        if (!$panel.length || typeof pulsegridThemeLicense === 'undefined') {
            return;
        }

        S = pulsegridThemeLicense.strings || {};

        var $sp = $panel.find('.pg-license-spinner');
        var $msgEl = $panel.find('[data-pg-license-msg]');
        var $modalActivate = $panel.find('[data-pg-license-modal="activate"]');
        var $modalDeactivate = $panel.find('[data-pg-license-modal="deactivate"]');
        var pendingLicenseKey = null;
        var $modalTrigger = null;

        function closeAnyModal() {
            pendingLicenseKey = null;
            $modalActivate.prop('hidden', true);
            $modalDeactivate.prop('hidden', true);
            $('body').removeClass('pg-license-modal-open');
            $(document).off('keydown.pgLicenseModal');
            if ($modalTrigger && $modalTrigger.length) {
                $modalTrigger.trigger('focus');
            }
            $modalTrigger = null;
        }

        function openActivateModal(key, $trigger) {
            if (!$modalActivate.length) {
                postActivate(key, $panel, $sp, $msgEl);
                return;
            }
            pendingLicenseKey = key;
            $modalTrigger = $trigger;
            $modalDeactivate.prop('hidden', true);
            $modalActivate.prop('hidden', false);
            $('body').addClass('pg-license-modal-open');
            $(document).on('keydown.pgLicenseModal', function (e) {
                if (e.key === 'Escape') {
                    e.preventDefault();
                    closeAnyModal();
                }
            });
            setTimeout(function () {
                $modalActivate.find('[data-pg-license-do="activate"]').trigger('focus');
            }, 0);
        }

        function openDeactivateModal($trigger) {
            if (!$modalDeactivate.length) {
                postDeactivate($panel, $sp, $msgEl);
                return;
            }
            $modalTrigger = $trigger;
            $modalActivate.prop('hidden', true);
            $modalDeactivate.prop('hidden', false);
            $('body').addClass('pg-license-modal-open');
            $(document).on('keydown.pgLicenseModal', function (e) {
                if (e.key === 'Escape') {
                    e.preventDefault();
                    closeAnyModal();
                }
            });
            setTimeout(function () {
                $modalDeactivate.find('[data-pg-license-do="deactivate"]').trigger('focus');
            }, 0);
        }

        $('#pg-license-key-input').on('input', function () {
            $(this).val(formatLicenseKey($(this).val()));
        });

        $panel.on('click', '[data-pg-license-modal-close]', function (e) {
            e.preventDefault();
            closeAnyModal();
        });

        $panel.on('click', '[data-pg-license-do]', function (e) {
            e.preventDefault();
            var act = $(this).data('pg-license-do');
            if (act === 'activate') {
                var key = pendingLicenseKey;
                closeAnyModal();
                if (key) {
                    postActivate(key, $panel, $sp, $msgEl);
                }
            } else if (act === 'deactivate') {
                closeAnyModal();
                postDeactivate($panel, $sp, $msgEl);
            }
        });

        $panel.on('click', '.pg-license-btn[data-action="activate"]', function (e) {
            var key = $.trim($panel.find('#pg-license-key-input').val() || '');
            if (!key) {
                showMsg($msgEl, S.need_key || '', 'error');
                return;
            }
            openActivateModal(key, $(e.currentTarget));
        });

        $panel.on('click', '.pg-license-btn[data-action="deactivate"]', function (e) {
            openDeactivateModal($(e.currentTarget));
        });
    });
})(jQuery);
