/**
 * Biscotti CMP - Connection Wizard JavaScript
 * 
 * Handles the Website ID connection flow for linking WordPress to Biscotti Cloud.
 * 
 * @package Biscotti_CMP
 * @since 3.0.0
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        var config = window.biscottiAdmin || {};

        $('#biscotti-connect-btn').on('click', function() {
            var $btn = $(this);
            var websiteId = $('#biscotti-website-id').val().trim();
            var $status = $('#biscotti-connection-status');

            if (!websiteId) {
                $status.html('<div class="notice notice-error inline"><p>' +
                    (config.i18n?.connectionError || 'Please enter a Website ID.') + '</p></div>');
                return;
            }

            // UUID format validation
            var uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
            if (!uuidRegex.test(websiteId)) {
                $status.html('<div class="notice notice-error inline"><p>' +
                    (config.i18n?.invalidWebsiteIdFormat || 'Invalid Website ID format. Expected: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') + '</p></div>');
                return;
            }

            $btn.prop('disabled', true).text(config.i18n?.connecting || 'Connecting...');
            $status.html('<div class="notice notice-info inline"><p>⏳ ' +
                (config.i18n?.connecting || 'Connecting...') + '</p></div>');

            $.ajax({
                url: config.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'biscotti_save_credentials',
                    nonce: config.nonce,
                    website_id: websiteId
                },
                success: function(res) {
                    if (res.success && res.data) {
                        var msg = '✅ ' + (res.data.message || config.i18n?.connected || 'Connected!');
                        if (res.data.plan) {
                            msg += ' (Plan: ' + res.data.plan.toUpperCase() + ')';
                        }
                        if (res.data.domain) {
                            msg += ' — ' + res.data.domain;
                        }
                        $status.html('<div class="notice notice-success inline"><p>' + msg + '</p></div>');

                        // Redirect to dashboard after 2 seconds
                        setTimeout(function() {
                            window.location.href = config.dashboardUrl || window.location.href.replace(/page=biscotti-wizard/, 'page=biscotti-cmp');
                        }, 2000);
                    } else {
                        $status.html('<div class="notice notice-error inline"><p>' +
                            (res.data || config.i18n?.connectionError || 'Connection failed.') + '</p></div>');
                    }
                },
                error: function(xhr, status, error) {
                    $status.html('<div class="notice notice-error inline"><p>❌ ' +
                        (config.i18n?.connectionError || 'Connection error.') +
                        ' (' + error + ')</p></div>');
                },
                complete: function() {
                    $btn.prop('disabled', false).text(config.i18n?.connect || 'Connect');
                }
            });
        });

        // Allow Enter key in Website ID field
        $('#biscotti-website-id').on('keypress', function(e) {
            if (e.which === 13) {
                e.preventDefault();
                $('#biscotti-connect-btn').click();
            }
        });
    });

})(jQuery);
