(function ($) {
    'use strict';

    function notify(message, status) {
        if (window.ultraguardManager && typeof window.ultraguardManager.showNotification === 'function') {
            window.ultraguardManager.showNotification(message, status || 'info');
            return;
        }

        if (message) {
            window.alert(message);
        }
    }

    function showGeneratedKey(message, key) {
        var box = $('#ultraguard-api-generated-key');
        if (!box.length) {
            return;
        }

        if (!key) {
            box.addClass('is-hidden').empty();
            return;
        }

        box.removeClass('is-hidden').html(
            '<strong>' + (message || 'API key created') + '</strong><br><code>' + key + '</code>'
        );
    }

    $(document).on('click', '#ultraguard-api-create-key', function (event) {
        event.preventDefault();

        var button = $(this);
        var originalText = button.text();
        button.prop('disabled', true).text(ultraguardApiSecurity.i18n.creating || 'Creating...');

        $.post(ultraguardApiSecurity.ajaxUrl, {
            action: 'ultraguard_api_create_key',
            nonce: ultraguardApiSecurity.nonce,
            key_name: $('[name="api-key-name"]').val() || '',
            allowed_routes: [$('[name="api-key-route"]').val() || ''],
            rate_limit: $('[name="api-key-rate"]').val() || 60,
            expires_at: $('[name="api-key-expiry"]').val() || ''
        }).done(function (response) {
            var payload = response && response.data ? response.data : {};
            if (response && response.success) {
                showGeneratedKey(payload.message || '', payload.generated_key || '');
                notify(payload.message || ultraguardApiSecurity.i18n.created || 'API key created.', 'success');
                return;
            }

            showGeneratedKey('', '');
            notify(payload.message || ultraguardApiSecurity.i18n.failed || 'Failed', 'error');
        }).fail(function () {
            showGeneratedKey(ultraguardApiSecurity.i18n.failed || 'Failed', '');
            notify(ultraguardApiSecurity.i18n.failed || 'Failed', 'error');
        }).always(function () {
            button.prop('disabled', false).text(originalText);
        });
    });
}(jQuery));
