<?php
// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Define current step early to avoid undefined variable errors
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.Security.NonceVerification.Recommended -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
$current_step = isset($_GET['step']) ? sanitize_text_field(wp_unslash($_GET['step'])) : 'integrations';
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.Security.NonceVerification.Recommended -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
$setup_error_code = isset($_GET['aysa_setup_error']) ? sanitize_key((string) wp_unslash($_GET['aysa_setup_error'])) : '';
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
$setup_error_messages = array(
    'google_not_connected' => 'Google must be connected before you can finish Setup SEO Profile. Please connect Google in the Integrations step.',
    'general_incomplete' => 'Complete all required fields in General Information.',
    'objectives_incomplete' => 'Select at least one objective in the Objectives step.',
    'seo_settings_incomplete' => 'Complete all required fields in SEO Settings.',
    'competition_incomplete' => 'Add at least one seed keyword in Competition & Keywords.',
    'tone_incomplete' => 'Select a Tone of Voice to continue.',
    'auth_required' => 'The authentication session is no longer valid. Go back to Integrations and reconnect your account.',
    'setup_incomplete' => 'Setup SEO Profile is not complete yet.',
);
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
$setup_error_message = isset($setup_error_messages[$setup_error_code]) ? $setup_error_messages[$setup_error_code] : '';

// Function to display the typing text section
if (!function_exists('aysa_display_typing_text_section')) {
    function aysa_display_typing_text_section($text_to_type, $element_id_suffix) {
        return '';
    }
}
?>

<div class="aysa-dashboard-wrapper">
    <div class="aysa-dashboard-container">
        <!-- Header Section -->
        <?php if ($current_step !== 'seo-profile-complete'): ?>
        <div class="aysa-dashboard-header">
            <div class="aysa-dashboard-title">
                <h1><span class="dashicons dashicons-admin-settings"></span> Setup SEO Profile</h1>
                <p>Configure your SEO settings to get the most out of Aysa.ai</p>
            </div>
            <div class="aysa-dashboard-user">
                <?php
                // Use the credits component
                if (class_exists('Aysa_Credits_Component')) {
                    Aysa_Credits_Component::display();
                } else {
                    echo '<div class="aysa-credits-component"><span class="aysa-credits-value">Credits: <span class="aysa-credits-amount"><span class="aysa-loading-spinner"></span></span></span></div>';
                }
                ?>
                <!-- <span class="aysa-user">Username (Project ID)</span> -->
            </div>
        </div>

        <?php if ($setup_error_message !== ''): ?>
        <div class="notice notice-warning is-dismissible" style="margin:12px 0 8px 0;">
            <p><strong>Setup incomplet:</strong> <?php echo esc_html($setup_error_message); ?></p>
        </div>
        <?php endif; ?>

        <!-- Steps Progress Bar -->
        <div class="aysa-wizard-progress">
            <div class="aysa-wizard-steps">
                <?php
                // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                $steps = [
                    'integrations' => ['icon' => 'dashicons-admin-plugins', 'label' => 'Integrations'],
                    'general' => ['icon' => 'dashicons-admin-site-alt', 'label' => 'General Information'],
                    'objectives' => ['icon' => 'dashicons-chart-bar', 'label' => 'Objectives'],
                    'seo-settings' => ['icon' => 'dashicons-admin-settings', 'label' => 'SEO Settings'],
                    'competition' => ['icon' => 'dashicons-chart-line', 'label' => 'Competition & Keywords'],
                    'tone-of-voice' => ['icon' => 'dashicons-format-quote', 'label' => 'Tone of Voice']
                ];
                
                // Set step index for progress calculation
                // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                $step_index = array_search($current_step, array_keys($steps));
                if ($step_index === false) {
                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                    $step_index = 0;
                }
                // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                $total_steps = count($steps);
                // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                $progress_percentage = (int) round((($step_index + 1) / max(1, $total_steps)) * 100);
                
                // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                $step_num = 1;
                // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                foreach ($steps as $step_key => $step_data) {
                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                    $is_active = ($step_key === $current_step);
                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                    $is_completed = array_search($step_key, array_keys($steps)) < array_search($current_step, array_keys($steps));
                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                    $class = $is_active ? 'active' : ($is_completed ? 'completed' : '');
                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                    $step_url = admin_url('admin.php?page=aysa-setup-seo-profile&step=' . $step_key);
                    ?>
                    <a href="<?php echo esc_url($step_url); ?>" class="aysa-wizard-step <?php echo esc_attr($class); ?>" data-step="<?php echo esc_attr($step_key); ?>">
                        <div class="aysa-step-icon-wrapper">
                            <?php if ($is_completed): ?>
                                <div class="aysa-step-number completed"><span class="dashicons dashicons-yes"></span></div>
                            <?php else: ?>
                                <div class="aysa-step-number"><?php echo esc_html($step_num); ?></div>
                            <?php endif; ?>
                            <span class="aysa-step-icon dashicons <?php echo esc_attr($step_data['icon']); ?>"></span>
                        </div>
                        <div class="aysa-step-label"><?php echo esc_html($step_data['label']); ?></div>
                    </a>
                    <?php
                    $step_num++;
                }
                ?>
            </div>
            <div class="aysa-progress-bar">
                <div class="aysa-progress" style="width: <?php echo esc_attr($progress_percentage); ?>%;"></div>
            </div>
        </div>
        <?php endif; ?>

        <script>
        (function() {
            const AYSA_API_BASE = `${window.AYSA_API_BASE || 'https://api.aysa.ai'}/`;
            const WP_AJAX_URL = <?php echo json_encode(admin_url('admin-ajax.php')); ?>;
            const WP_NONCE = <?php echo json_encode(wp_create_nonce('aysa_nonce')); ?>;

            function isAysaApiUrl(url) {
                return typeof url === 'string' && url.indexOf(AYSA_API_BASE) === 0;
            }

            function normalizeEndpoint(url) {
                try {
                    const parsed = new URL(url);
                    return parsed.pathname.replace(/^\/+/, '') + (parsed.search || '');
                } catch (e) {
                    return String(url || '').replace(/^https?:\/\/[^/]+\//i, '');
                }
            }

            function parsePayload(data) {
                if (!data) return {};
                if (typeof data === 'string') {
                    try {
                        const parsed = JSON.parse(data);
                        if (parsed && typeof parsed === 'object') return parsed;
                    } catch (e) {}
                    const params = new URLSearchParams(data);
                    const out = {};
                    params.forEach((v, k) => { out[k] = v; });
                    return out;
                }
                if (typeof data === 'object') return data;
                return {};
            }

            function getAccessKey() {
                if (typeof window.AYSA_ACCESS_KEY === 'string' && window.AYSA_ACCESS_KEY.trim() !== '') {
                    return window.AYSA_ACCESS_KEY.trim();
                }
                try {
                    const fromLocal = localStorage.getItem('aysa_access_key');
                    if (fromLocal && fromLocal.trim() !== '') return fromLocal.trim();
                } catch (e) {}
                try {
                    const fromSession = sessionStorage.getItem('aysa_access_key');
                    if (fromSession && fromSession.trim() !== '') return fromSession.trim();
                } catch (e) {}
                return '';
            }

            function setupProxyRequest(method, url, data) {
                const payload = parsePayload(data);
                const body = new URLSearchParams({
                    action: 'aysa_setup_api_proxy',
                    nonce: WP_NONCE,
                    access_key: getAccessKey(),
                    site_host: window.location.hostname || '',
                    endpoint: normalizeEndpoint(url),
                    method: String(method || 'GET').toUpperCase(),
                    payload: JSON.stringify(payload || {})
                });

                return window.fetch(WP_AJAX_URL, {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                    body: body.toString()
                }).then(async (resp) => {
                    const raw = await resp.text();
                    let json = null;
                    try {
                        json = JSON.parse(raw);
                    } catch (e) {
                        throw new Error('Invalid proxy JSON response');
                    }
                    if (!resp.ok || !json || !json.success) {
                        const msg = json && json.data && json.data.message ? json.data.message : 'Setup proxy request failed';
                        throw new Error(msg);
                    }
                    if (json.data && typeof json.data === 'object' && Object.prototype.hasOwnProperty.call(json.data, 'result')) {
                        return json.data.result;
                    }
                    return json.data;
                });
            }

            const originalFetch = window.fetch ? window.fetch.bind(window) : null;
            if (originalFetch) {
                window.fetch = function(input, init) {
                    const url = typeof input === 'string' ? input : (input && input.url ? input.url : '');
                    if (!isAysaApiUrl(url)) {
                        return originalFetch(input, init);
                    }
                    const method = (init && init.method) ? init.method : 'GET';
                    const data = init && init.body ? init.body : null;
                    return setupProxyRequest(method, url, data).then((dataObj) => {
                        return new Response(JSON.stringify(dataObj), {
                            status: 200,
                            headers: { 'Content-Type': 'application/json' }
                        });
                    });
                };
            }

            function wrapJqueryAjax() {
                if (!window.jQuery || !window.jQuery.ajax || window.jQuery.ajax.__aysaSetupWrapped) return;
                const $ = window.jQuery;
                const originalAjax = $.ajax;

                const wrappedAjax = function(options) {
                    const opts = (typeof options === 'string') ? { url: options } : $.extend(true, {}, options || {});
                    if (!isAysaApiUrl(opts.url)) {
                        return originalAjax.apply($, arguments);
                    }

                    const dfd = $.Deferred();
                    const method = (opts.type || opts.method || 'GET').toUpperCase();
                    setupProxyRequest(method, opts.url, opts.data)
                        .then((data) => {
                            if (typeof opts.success === 'function') {
                                opts.success(data, 'success', { status: 200 });
                            }
                            dfd.resolve(data, 'success', { status: 200 });
                        })
                        .catch((err) => {
                            const xhrLike = { status: 500, responseText: String(err && err.message ? err.message : err) };
                            if (typeof opts.error === 'function') {
                                opts.error(xhrLike, 'error', xhrLike.responseText);
                            }
                            dfd.reject(xhrLike, 'error', xhrLike.responseText);
                        });

                    return dfd.promise();
                };

                wrappedAjax.__aysaSetupWrapped = true;
                $.ajax = wrappedAjax;
            }

            wrapJqueryAjax();
            document.addEventListener('DOMContentLoaded', wrapJqueryAjax);
        })();
        </script>

        <?php if ($current_step !== 'seo-profile-complete'): ?>
        <div class="aysa-setup-conversation-panel" id="aysa-setup-conversation-panel">
            <div class="aysa-setup-conversation-header">
                <div>
                    <h3>AYSA</h3>
                    <p>SEO setup chat</p>
                </div>
                <div class="aysa-setup-conversation-top-actions">
                    <label class="aysa-setup-language-switcher" for="aysa-setup-conversation-language">
                        <span>Language</span>
                        <select id="aysa-setup-conversation-language">
                            <option value="en">English</option>
                            <option value="ro">Romanian</option>
                            <option value="bg">Bulgarian</option>
                        </select>
                    </label>
                </div>
            </div>
            <div class="aysa-setup-conversation-messages" id="aysa-setup-conversation-messages">
                <div class="aysa-setup-conversation-empty">Loading project context...</div>
            </div>
            <div class="aysa-setup-conversation-suggested" id="aysa-setup-conversation-suggested"></div>
            <div class="aysa-setup-conversation-status" id="aysa-setup-conversation-status">Preparing the conversation.</div>
            <form class="aysa-setup-conversation-form" id="aysa-setup-conversation-form">
                <textarea id="aysa-setup-conversation-input" rows="3" placeholder="Tell AYSA what you want to complete or ask it to analyze the website."></textarea>
                <div class="aysa-setup-conversation-actions">
                    <button type="submit" class="aysa-btn aysa-btn-primary" id="aysa-setup-conversation-send">Send</button>
                </div>
            </form>
        </div>
        <?php endif; ?>

        <script>
        window.aysaWizardUseGlobalNavigation = true;
        </script>

        <!-- Wizard Content -->
        <div class="aysa-wizard-content">
            <?php
            // Handle completion page display
            if ($current_step === 'seo-profile-complete') {
                include_once AYSA_PLUGIN_DIR . 'admin/partials/wizard/seo-profile-complete.php';
            } else {
                // Include the appropriate step file
                // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                $step_file = AYSA_PLUGIN_DIR . 'admin/partials/wizard/' . $current_step . '.php';
                if (file_exists($step_file)) {
                    include_once $step_file;
                } else {
                    // Default to integrations if the step file doesn't exist
                    include_once AYSA_PLUGIN_DIR . 'admin/partials/wizard/integrations.php';
                }
            }
            ?>
        </div>

        <!-- Wizard Footer -->
        <?php if ($current_step !== 'seo-profile-complete'): ?>
        <div class="aysa-wizard-footer">
            <?php if ($current_step !== 'integrations'): ?>
                <button id="aysa-prev-step" class="aysa-btn aysa-btn-secondary">
                    <span class="dashicons dashicons-arrow-left-alt"></span> Previous
                </button>
            <?php endif; ?>
            
            <?php if ($current_step === 'tone-of-voice'): ?>
                <?php
                // After setup completion, go directly to Keyword Discovery.
                // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                $finish_url = admin_url('admin.php?page=aysa-research&tab=keyword-discovery');
                ?>
                <button type="button" class="aysa-btn aysa-btn-primary" onclick="aysaFinishSetup('<?php echo esc_js($finish_url); ?>')">
                    Finish <span class="dashicons dashicons-yes-alt"></span>
                </button>
            <?php else: ?>
                <button type="button" id="aysa-next-step" class="aysa-btn aysa-btn-primary">
                    Next <span class="dashicons dashicons-arrow-right-alt"></span>
                </button>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<style>
/* Base Styles */
.aysa-dashboard-wrapper {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    color: #333;
    background-color: #f8f9fa;
    padding: 25px;
    width: 100%;
    min-height: 100vh;
    box-sizing: border-box;
    margin: 0;
    margin-right: 0;
    margin-left: -20px; /* Compensate for WordPress admin margin */
}

/* Special styling for completion page */
.aysa-dashboard-wrapper.completion-page {
    padding: 0;
    margin: 0;
    background: #f8f9fa;
    min-height: 100vh;
}

.aysa-dashboard-wrapper.completion-page .aysa-dashboard-container {
    padding: 0;
    max-width: none;
}

.aysa-dashboard-wrapper.completion-page .aysa-wizard-content {
    background: none;
    box-shadow: none;
    border: none;
    padding: 0;
    margin: 0;
}

.aysa-dashboard-container {
    width: 100%;
    margin: 0 auto;
    padding: 0 20px;
    max-width: 100%;
    box-sizing: border-box;
}

/* Header Styles */
.aysa-dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-dashboard-title h1 {
    font-size: 28px;
    margin: 0 0 8px;
    font-weight: 600;
    color: #202124;
    display: flex;
    align-items: center;
    letter-spacing: -0.5px;
}

.aysa-dashboard-title h1 .dashicons {
    font-size: 28px;
    width: 28px;
    height: 28px;
    margin-right: 10px;
    color: #1a73e8;
}

.aysa-dashboard-title p {
    margin: 0;
    color: #5f6368;
    font-size: 15px;
    line-height: 1.4;
}

.aysa-dashboard-user {
    display: flex;
    align-items: center;
    gap: 15px;
}

.aysa-btn-text {
    background: none;
    color: #1a73e8;
    padding: 0;
    border: none;
    font-size: 14px;
    cursor: pointer;
    font-weight: 500;
}

.aysa-btn-text:hover {
    text-decoration: underline;
    color: #1765cc;
}

/* Improved focus handling */
button:focus, a:focus {
    outline: none;
}

/* Only apply focus removal to navigation elements, not form inputs */
.aysa-wizard-step:focus, 
.aysa-wizard-step:focus-visible, 
.aysa-btn:focus {
    outline: none;
}

/* Form elements need focus indicators and interaction */
input, select, textarea {
    background-color: #fff;
    border: 1px solid #ddd;
    padding: 8px 12px;
    border-radius: 4px;
    width: 100%;
    font-size: 14px;
    box-sizing: border-box;
    transition: border-color 0.3s;
}

input:focus, select:focus, textarea:focus {
    border-color: #1a73e8;
    box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
}

/* Wizard Progress Bar */
.aysa-wizard-progress {
    margin-bottom: 40px;
    width: 100%;
    overflow: visible;
    position: relative;
}

.aysa-wizard-steps {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
    position: relative;
    width: 100%;
    overflow: visible;
    z-index: 1;
}

.aysa-wizard-steps::before {
    content: '';
    position: absolute;
    top: 25px;
    left: 0;
    right: 0;
    height: 3px;
    background-color: #e0e0e0;
    z-index: 0;
}

.aysa-wizard-steps::after {
    content: '';
    position: absolute;
    top: 25px;
    left: 0;
    right: 0;
    height: 3px;
    background: rgba(0,0,0,0.03);
    z-index: 0;
    border-radius: 6px;
}

.aysa-wizard-step {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 16.6%;
    position: relative;
    z-index: 1;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s ease;
}

.aysa-wizard-step:hover {
    transform: translateY(-3px);
}

.aysa-wizard-step:hover .aysa-step-label {
    color: #1a73e8;
}

.aysa-wizard-step:hover .aysa-step-number:not(.completed) {
    background-color: #e0e0e0;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.aysa-wizard-step.active {
    pointer-events: none;
    z-index: 3;
    position: relative;
}

.aysa-wizard-step.completed:hover .aysa-step-number {
    background-color: #0b8043;
    transform: scale(1.05);
}

.aysa-step-icon-wrapper {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
    padding: 5px;
}

.aysa-step-number {
    width: 34px;
    height: 34px;
    background-color: #e0e0e0;
    color: #5f6368;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    position: relative;
    z-index: 2;
    border: 2px solid #fff;
    transition: all 0.3s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    -webkit-tap-highlight-color: transparent;
}

.aysa-step-number.completed {
    background-color: #0f9d58;
    color: white;
}

.aysa-step-icon {
    position: absolute;
    font-size: 14px;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #5f6368;
}

.aysa-wizard-step.active .aysa-step-number {
    background-color: #1a73e8;
    color: white;
    border: 2px solid #fff;
    z-index: 5;
    box-shadow: 0 0 0 4px rgba(26, 115, 232, 0.2);
    -webkit-tap-highlight-color: transparent;
}

.aysa-wizard-step:active .aysa-step-number {
    transform: scale(0.95);
}

.aysa-wizard-step:focus .aysa-step-number {
    box-shadow: none !important;
    outline: none !important;
}

.aysa-wizard-step.completed .aysa-step-number {
    background-color: #0f9d58;
    color: white;
}

.aysa-wizard-step.completed .aysa-step-number .dashicons {
    font-size: 16px;
}

.aysa-step-label {
    font-size: 14px;
    color: #5f6368;
    text-align: center;
    line-height: 1.3;
    transition: color 0.3s ease;
    font-weight: 500;
}

.aysa-wizard-step.active .aysa-step-label {
    color: #1a73e8;
    font-weight: 600;
}

.aysa-wizard-step.completed .aysa-step-label {
    color: #0f9d58;
}

.aysa-progress-bar {
    height: 6px;
    background-color: #e0e0e0;
    border-radius: 6px;
    overflow: hidden;
    position: relative;
    z-index: 1;
    margin-top: 5px;
}

.aysa-progress {
    height: 100%;
    background: linear-gradient(90deg, #1a73e8, #0f9d58);
    transition: width 0.5s ease;
    border-radius: 6px;
}

/* Fix for active tab circle */
.aysa-wizard-steps .aysa-wizard-step.active .aysa-step-number {
    position: relative;
    z-index: 5;
    border: 2px solid #fff;
    background-color: #1a73e8;
    color: white;
}

/* Ensure the active number doesn't get clipped */
.aysa-wizard-step.active .aysa-step-icon-wrapper::before {
    content: '';
    position: absolute;
    width: 42px;
    height: 42px;
    border-radius: 50%;
    background-color: transparent;
    z-index: 4;
}

/* Wizard Content */
.aysa-wizard-content {
    background-color: white;
    border-radius: 10px;
    padding: 40px;
    box-shadow: 0 3px 15px rgba(0, 0, 0, 0.08);
    margin-bottom: 30px;
    border: 1px solid #e0e0e0;
}

.aysa-setup-conversation-panel {
    position: fixed;
    top: 56px;
    right: 24px;
    bottom: 24px;
    width: 430px;
    left: auto;
    background:
        radial-gradient(circle at top left, rgba(225, 240, 255, 0.95), transparent 34%),
        linear-gradient(180deg, #f7fbff 0%, #f2f6fb 100%);
    z-index: 9998;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: stretch;
    justify-content: flex-start;
    padding: 18px 18px 16px;
    border: 1px solid rgba(199, 214, 229, 0.95);
    border-radius: 24px;
    box-shadow: 0 30px 90px rgba(18, 38, 61, 0.16);
    backdrop-filter: blur(12px);
}

.aysa-setup-conversation-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 12px;
    width: 100%;
    margin: 0 0 10px;
}

.aysa-setup-conversation-header h3 {
    margin: 0 0 6px;
    font-size: 28px;
    color: #12304a;
    letter-spacing: -0.03em;
}

.aysa-setup-conversation-header p {
    margin: 0;
    color: #59708a;
    font-size: 14px;
}

.aysa-setup-conversation-top-actions {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.aysa-setup-language-switcher {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-size: 12px;
    font-weight: 600;
    color: #4f6784;
}

.aysa-setup-language-switcher select {
    min-width: 120px;
    border: 1px solid #c8d4e3;
    border-radius: 12px;
    background: #ffffff;
    color: #153a63;
    padding: 8px 12px;
    font-size: 13px;
}

.aysa-setup-reset-btn {
    border: 1px solid #cbd7e6;
    background: #fff;
    color: #3b526b;
    border-radius: 999px;
    padding: 8px 12px;
    font-size: 12px;
    cursor: pointer;
}

.aysa-setup-conversation-messages {
    width: 100%;
    min-height: 280px;
    flex: 1 1 auto;
    overflow-y: auto;
    padding: 24px 22px 12px;
    background: rgba(255,255,255,0.88);
    border: 1px solid rgba(205, 218, 232, 0.95);
    border-radius: 22px;
    box-shadow: 0 24px 80px rgba(27, 49, 78, 0.08);
    backdrop-filter: blur(10px);
}

.aysa-setup-conversation-suggested {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    padding: 12px 0 2px;
}

.aysa-setup-conversation-empty {
    padding: 16px 18px;
    border-radius: 16px;
    background: #f3f7fb;
    color: #5f7083;
    font-size: 14px;
}

.aysa-setup-conversation-bubble {
    margin-bottom: 14px;
    padding: 16px 18px;
    border-radius: 18px;
    font-size: 15px;
    line-height: 1.6;
    white-space: pre-wrap;
    max-width: min(680px, 92%);
}

.aysa-setup-conversation-bubble.assistant {
    background: #ffffff;
    color: #17395c;
    border-top-left-radius: 8px;
    border: 1px solid #d9e5f0;
    box-shadow: 0 10px 28px rgba(18, 48, 74, 0.05);
}

.aysa-setup-conversation-bubble.user {
    background: #17395c;
    color: #fff;
    border-top-right-radius: 8px;
    margin-left: auto;
}

.aysa-setup-suggested-btn {
    border: 1px solid #c9d9ea;
    background: #ffffff;
    color: #20456f;
    border-radius: 999px;
    padding: 10px 16px;
    font-size: 14px;
    line-height: 1.2;
    cursor: pointer;
    transition: background .15s ease, border-color .15s ease, transform .15s ease;
}

.aysa-setup-suggested-btn:hover {
    background: #f5f9fd;
    border-color: #9ab7d6;
    transform: translateY(-1px);
}

.aysa-setup-suggested-btn.is-primary {
    background: #245fdb;
    color: #ffffff;
    border-color: #245fdb;
}

.aysa-setup-suggested-btn.is-primary:hover {
    background: #1a4fbc;
    border-color: #1a4fbc;
}

.aysa-setup-conversation-status {
    width: 100%;
    padding: 10px 4px 12px;
    color: #66788b;
    font-size: 13px;
}

.aysa-setup-conversation-form {
    width: 100%;
    padding: 0;
    background: transparent;
}

.aysa-setup-conversation-form textarea {
    width: 100%;
    resize: vertical;
    min-height: 110px;
    border: 1px solid #c9d8e8;
    border-radius: 18px;
    padding: 16px 18px;
    font-size: 15px;
    line-height: 1.55;
    box-sizing: border-box;
    background: rgba(255,255,255,0.96);
    box-shadow: 0 16px 48px rgba(19, 43, 70, 0.08);
}

.aysa-setup-conversation-actions {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
}

@media (max-width: 960px) {
    .aysa-setup-conversation-panel {
        left: 12px;
        right: 12px;
        top: 46px;
        bottom: 12px;
        width: auto;
        padding: 18px 14px;
    }
}

body.folded .aysa-setup-conversation-panel {
    right: 24px;
}

.aysa-chat-mode-active .aysa-dashboard-container {
    padding-right: 470px;
}

.aysa-chat-mode-active .aysa-dashboard-header,
.aysa-chat-mode-active .aysa-wizard-progress,
.aysa-chat-mode-active .aysa-wizard-footer,
.aysa-chat-mode-active .aysa-wizard-content {
    margin-right: 0;
}

@media (max-width: 960px) {
    .aysa-chat-mode-active .aysa-dashboard-container {
        padding-right: 20px;
    }
}

.aysa-wizard-section {
    margin-bottom: 35px;
}

.aysa-wizard-section h2 {
    font-size: 22px;
    margin: 0 0 18px;
    color: #202124;
    font-weight: 600;
    display: flex;
    align-items: center;
    letter-spacing: -0.3px;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 12px;
}

.aysa-wizard-section h2 .dashicons {
    margin-right: 10px;
    color: #1a73e8;
    font-size: 24px;
    width: 24px;
    height: 24px;
}

.aysa-text-muted {
    color: #5f6368;
    font-size: 15px;
    margin-bottom: 20px;
    line-height: 1.5;
}

.aysa-form-group {
    margin-bottom: 25px;
}

.aysa-form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 15px;
    color: #3c4043;
}

.aysa-info-box {
    background-color: #e8f0fe;
    border-left: 4px solid #1a73e8;
    padding: 16px 22px;
    border-radius: 6px;
    margin-bottom: 30px;
    display: flex;
    align-items: center;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.03);
}

.aysa-info-box p {
    margin: 0;
    color: #1a73e8;
    font-size: 15px;
    line-height: 1.5;
}

/* Improved form field interaction */
.aysa-input, .aysa-form-group input[type="text"], .aysa-form-group input[type="email"], 
.aysa-form-group input[type="password"], .aysa-form-group input[type="url"], 
.aysa-form-group input[type="tel"], .aysa-form-group select, .aysa-form-group textarea {
    width: 100%;
    padding: 12px 14px;
    border: 1px solid #dadce0;
    border-radius: 6px;
    font-size: 15px;
    transition: all 0.2s;
    background-color: #f8f9fa;
    box-shadow: none; /* Override WordPress default focus */
    outline: none; /* Start with no outline */
    position: relative; /* Make sure it's above other elements */
    z-index: 1; /* Ensure proper stacking */
}

.aysa-input:focus, .aysa-form-group input[type="text"]:focus, .aysa-form-group input[type="email"]:focus,
.aysa-form-group input[type="password"]:focus, .aysa-form-group input[type="url"]:focus,
.aysa-form-group input[type="tel"]:focus, .aysa-form-group select:focus, .aysa-form-group textarea:focus {
    border-color: #1a73e8;
    box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.15);
    background-color: #fff;
    outline: none; /* Remove default browser outline */
    z-index: 2; /* Higher z-index when focused */
}

/* Remove any pointer events blocking on wrapper elements */
.aysa-form-group, .aysa-integration-card-body, .aysa-input-password, .aysa-wizard-content {
    pointer-events: auto;
}

/* Only remove outline for buttons and navigation, not form inputs */
.aysa-btn:focus, .aysa-wizard-step:focus {
    outline: none;
}

/* Wizard Focus styles - fix for safari */
.aysa-wizard-step {
    pointer-events: auto; /* Ensure clicks work */
}

/* Fix for any pointer-events issues in elements */
.aysa-form-group label, .aysa-checkbox-item, .aysa-checkbox-item label {
    pointer-events: auto;
}

.aysa-required {
    color: #d93025;
    font-weight: 600;
}

.aysa-checkbox-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    padding: 8px 0;
}

.aysa-checkbox-item input[type="checkbox"] {
    margin-right: 12px;
    transform: scale(1.1);
}

.aysa-checkbox-item label {
    font-size: 15px;
    color: #3c4043;
    font-weight: normal;
}

.aysa-checkbox-item a {
    color: #1a73e8;
    text-decoration: none;
    font-weight: 500;
}

.aysa-checkbox-item a:hover {
    text-decoration: underline;
}

/* Wizard Footer */
.aysa-wizard-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
}

.aysa-btn {
    display: inline-flex;
    align-items: center;
    padding: 12px 24px;
    border-radius: 6px;
    font-size: 15px;
    font-weight: 600;
    cursor: pointer;
    border: none;
    transition: all 0.2s;
}

.aysa-btn .dashicons {
    font-size: 18px;
    width: 18px;
    height: 18px;
}

.aysa-btn-primary {
    background-color: #1a73e8;
    color: white;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.aysa-btn-primary:hover {
    background-color: #1765cc;
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
    transform: translateY(-1px);
}

.aysa-btn-primary .dashicons {
    margin-left: 8px;
}

.aysa-btn-secondary {
    background-color: #f1f3f4;
    color: #3c4043;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.aysa-btn-secondary:hover {
    background-color: #e8eaed;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    transform: translateY(-1px);
}

.aysa-btn-secondary .dashicons {
    margin-right: 8px;
}

/* Keep wizard navigation buttons stable during QA and real usage. */
.aysa-wizard-footer .aysa-btn,
#aysa-next-step,
#aysa-prev-step {
    transition: none !important;
    animation: none !important;
    transform: none !important;
    min-width: 108px;
}

.aysa-wizard-footer .aysa-btn:hover,
#aysa-next-step:hover,
#aysa-prev-step:hover,
.aysa-wizard-footer .aysa-btn:focus,
#aysa-next-step:focus,
#aysa-prev-step:focus {
    transition: none !important;
    animation: none !important;
    transform: none !important;
}

/* Responsive Styles */
@media (max-width: 991px) {
    .aysa-dashboard-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .aysa-dashboard-user {
        margin-top: 15px;
        flex-wrap: wrap;
        width: 100%;
    }
    
    .aysa-wizard-steps::before {
        top: 25px;
    }
    
    .aysa-step-label {
        font-size: 13px;
    }
}

@media (max-width: 767px) {
    .aysa-dashboard-wrapper {
        padding: 15px;
        margin-left: -10px; /* Reduced negative margin for mobile */
    }
    
    .aysa-wizard-content {
        padding: 25px;
    }
    
    .aysa-wizard-steps {
        overflow-x: auto;
        justify-content: flex-start;
        padding-bottom: 5px;
        margin-right: -20px; /* Allow scrolling without cutoff */
    }
    
    .aysa-wizard-step {
        min-width: 100px;
        width: auto;
        margin-right: 20px;
    }
    
    .aysa-wizard-steps::before {
        display: none;
    }
    
    .aysa-wizard-footer {
        flex-direction: column;
        gap: 10px;
    }
    
    .aysa-btn {
        width: 100%;
        justify-content: center;
    }
}

/* Animation */
@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}

.aysa-wizard-step.active .aysa-step-number {
    animation: none;
}

/* Badge styles for form items */
.aysa-badge {
    display: inline-block;
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
    margin-left: 8px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.aysa-badge-required {
    background-color: #fce8e6;
    color: #d93025;
}

.aysa-badge-optional {
    background-color: #e8f0fe;
    color: #1a73e8;
}

/* Card styles for items */
.aysa-card {
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    transition: all 0.2s;
    background-color: #ffffff;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.aysa-card:hover {
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
    border-color: #dadce0;
    transform: translateY(-2px);
}

.aysa-card h3 {
    margin-top: 0;
    margin-bottom: 15px;
    font-size: 18px;
    font-weight: 600;
    color: #202124;
}

/* Animation for loading states */
.aysa-spinner {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 2px solid rgba(255,255,255,0.3);
    border-radius: 50%;
    border-top-color: white;
    animation: aysa-spin 0.8s linear infinite;
    margin-right: 8px;
    vertical-align: middle;
}

@keyframes aysa-spin {
    to { transform: rotate(360deg); }
}

/* Feedback animations */
@keyframes aysa-success-animation {
    0% { transform: scale(0.5); opacity: 0; }
    50% { transform: scale(1.2); opacity: 1; }
    100% { transform: scale(1); opacity: 1; }
}

.aysa-success-icon {
    animation: aysa-success-animation 0.5s ease-out;
}

/* Highlight animation for active steps */
@keyframes highlight-pulse {
    0% { box-shadow: 0 0 0 0 rgba(26, 115, 232, 0.4); }
    70% { box-shadow: 0 0 0 10px rgba(26, 115, 232, 0); }
    100% { box-shadow: 0 0 0 0 rgba(26, 115, 232, 0); }
}

/* Styles for the dynamic text in wizard steps */
.aysa-wizard-intro-text {
    background-color: #e6f7ea; /* Verde pal în loc de gri */
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 30px;
    max-width: 95%;
    margin-left: auto;
    margin-right: auto;
    border: 1px solid #d1dde5;
}

.aysa-wizard-intro-text .aysa-chat-message {
    padding: 10px 15px;
    border-radius: 15px;
    line-height: 1.6;
    text-align: left;
    max-width: 100%;
}

.aysa-wizard-intro-text .aysa-ai-message {
    background-color: #e1f0ff; /* Light blue for AI messages, similar to welcome page */
    color: #333;
    display: inline-block;
    border-bottom-left-radius: 0;
    width: auto; /* Adjust based on content */
}

.aysa-wizard-intro-text .aysa-ai-message p {
    margin: 0;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    font-size: 1.2rem;
    font-weight: 600;
}

/* Blinking cursor effect for wizard steps */
.aysa-wizard-intro-text .aysa-ai-message p::after {
    content: '|';
    display: inline-block;
    animation: blink-animation 1s infinite;
    font-weight: bold;
}

.aysa-wizard-intro-text .aysa-ai-message p.typing-done::after {
    animation: none;
    content: '';
}

/* Define the blink animation */
@keyframes blink-animation {
    to {
        visibility: hidden;
    }
}

.aysa-ai-message .aysa-eyes-img, .aysa-wizard-intro-text .aysa-eyes-img {
    width: 67px;
    height: auto;
    /* border-radius: 50%; */
    /* object-fit: cover; */
    display: block;
    margin: 0;
    background: #e6f7ea;
}
</style>

<script>
// Define global function for finishing setup (must be outside jQuery ready for onclick to work)
window.aysaFinishSetup = function(finishUrl) {
    // Show loading state
    var button = document.querySelector('button[onclick*="aysaFinishSetup"]');
    if (button) {
        button.innerHTML = '<span class="dashicons dashicons-update"></span> Saving & Finishing...';
        button.disabled = true;
    }
    
    // Save current step data first, then finish setup
    saveCurrentWizardStepData(function(success) {
        if (!success) {
            aysaAlert('Failed to save current step. Please try again.', 'Warning');
            if (button) {
                button.innerHTML = 'Finish <span class="dashicons dashicons-yes-alt"></span>';
                button.disabled = false;
            }
            return;
        }
        markSetupCompleted(finishUrl);
    });
};

// Save current wizard form data via local WP AJAX endpoint.
function saveCurrentWizardStepData(callback) {
    var currentStep = '<?php echo esc_js($current_step); ?>';
    var form = document.querySelector('.aysa-wizard-content form');
    if (!form || currentStep === 'integrations') {
        callback(true);
        return;
    }

    if (!validateCurrentWizardStep(currentStep, form)) {
        callback(false);
        return;
    }

    var formData = new FormData(form);
    formData.set('action', 'aysa_save_wizard_data');
    formData.set('step', currentStep);
    if (!formData.get('nonce')) {
        formData.set('nonce', '<?php echo esc_attr(wp_create_nonce('aysa_nonce')); ?>');
    }

    var payload = new URLSearchParams(formData).toString();
    jQuery.ajax({
        url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
        type: 'POST',
        dataType: 'json',
        data: payload,
        success: function(response) {
            callback(!!(response && response.success));
        },
        error: function() {
            callback(false);
        }
    });
}

function validateCurrentWizardStep(currentStep, form) {
    if (!form) {
        return true;
    }

    if (currentStep === 'general') {
        var requiredSelectors = [
            '#company_name',
            '#brand_name',
            '#support_phone',
            '#website',
            '#website-type',
            '#shipping',
            '#payment-method',
            '#industry',
            '#company-info'
        ];

        for (var i = 0; i < requiredSelectors.length; i++) {
            var field = form.querySelector(requiredSelectors[i]);
            if (!field) {
                continue;
            }

            var value = '';
            if (field.tagName === 'SELECT') {
                value = String(field.value || '').trim();
            } else {
                value = String(field.value || '').trim();
            }

            if (!value) {
                if (typeof field.focus === 'function') {
                    field.focus();
                }
                if (typeof field.reportValidity === 'function') {
                    field.reportValidity();
                } else {
                    alert('Please complete all required fields from General Information before continuing.');
                }
                return false;
            }
        }
    }

    if (currentStep === 'objectives') {
        var checkedObjectives = form.querySelectorAll('input[name="objectives[]"]:checked');
        if (!checkedObjectives || checkedObjectives.length === 0) {
            alert('Please select at least one objective before continuing.');
            return false;
        }
    }

    if (currentStep === 'seo-settings') {
        var seoRequiredSelectors = [
            '#targeted_search_engine',
            '#targeted_country',
            '#targeted_region',
            '#primary_language'
        ];

        for (var j = 0; j < seoRequiredSelectors.length; j++) {
            var seoField = form.querySelector(seoRequiredSelectors[j]);
            if (!seoField) {
                continue;
            }

            if (!String(seoField.value || '').trim()) {
                if (typeof seoField.focus === 'function') {
                    seoField.focus();
                }
                if (typeof seoField.reportValidity === 'function') {
                    seoField.reportValidity();
                } else {
                    alert('Please complete the required SEO settings before continuing.');
                }
                return false;
            }
        }
    }

    if (currentStep === 'competition') {
        var keywordField = form.querySelector('#keyword1');
        if (keywordField && !String(keywordField.value || '').trim()) {
            if (typeof keywordField.focus === 'function') {
                keywordField.focus();
            }
            alert('Please enter at least one seed keyword before continuing.');
            return false;
        }
    }

    if (currentStep === 'tone-of-voice') {
        var selectedTone = form.querySelector('input[name="tone"]:checked');
        if (!selectedTone) {
            alert('Please choose a tone of voice before finishing setup.');
            return false;
        }
    }

    if (typeof form.reportValidity === 'function') {
        return form.reportValidity();
    }

    return true;
}

// Helper function to mark setup as completed
function markSetupCompleted(finishUrl) {
    // Create AJAX request using vanilla JavaScript
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '<?php echo esc_url(admin_url('admin-ajax.php')); ?>', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            // Always redirect regardless of response
            window.location.href = finishUrl;
        }
    };
    
    // Prepare data
    var data = 'action=aysa_mark_setup_completed&nonce=<?php echo esc_attr(wp_create_nonce('aysa_setup_nonce')); ?>';
    
    // Send request
    xhr.send(data);
    
    // Fallback timeout in case AJAX fails
    setTimeout(function() {
        window.location.href = finishUrl;
    }, 3000);
}

jQuery(document).ready(function($) {
    // Update progress bar based on current step
    const steps = ['integrations', 'general', 'objectives', 'seo-settings', 'competition', 'tone-of-voice'];
    const currentStep = '<?php echo esc_js($current_step); ?>';
    const currentIndex = steps.indexOf(currentStep);
    
    // Mark previous steps as completed
    for(let i = 0; i < currentIndex; i++) {
        $(`.aysa-wizard-step[data-step="${steps[i]}"]`).addClass('completed');
    }
    
    // Helper function to smoothly animate the progress bar
    function updateProgressBar() {
        const progressPercentage = (currentIndex / (steps.length - 1)) * 100;
        $('.aysa-progress').css('width', progressPercentage + '%');
    }
    
    // Call the function on page load
    updateProgressBar();
    
    // Add hover effects to steps
    $('.aysa-wizard-step').hover(
        function() {
            if (!$(this).hasClass('active') && !$(this).hasClass('completed')) {
                $(this).find('.aysa-step-number').css('transform', 'scale(1.05)');
            }
        },
        function() {
            if (!$(this).hasClass('active') && !$(this).hasClass('completed')) {
                $(this).find('.aysa-step-number').css('transform', 'scale(1)');
            }
        }
    );
    
    // Fix for any click handlers on document that might interfere with form inputs
    $(document).on('click', function(e) {
        // Don't interfere with input fields
        if ($(e.target).is('input, select, textarea') || $(e.target).parents('label').length || 
            $(e.target).parents('.aysa-input-password').length) {
            return;
        }
        
        // Only blur navigation elements, not form fields
        if ($(e.target).is('.aysa-wizard-step, .aysa-btn') || 
            $(e.target).parents('.aysa-wizard-step, .aysa-btn').length) {
            $(e.target).blur();
        }
    });

    var pageUrl = '<?php echo esc_url(admin_url("admin.php?page=aysa-setup-seo-profile")); ?>';
    var dashboardUrl = '<?php echo esc_url(admin_url("admin.php?page=aysa")); ?>';
    var finishUrl = '<?php echo esc_url(admin_url("admin.php?page=aysa-research&tab=keyword-discovery")); ?>';
    var wizardSteps = <?php echo wp_json_encode(array_keys($steps)); ?>;
    var current = '<?php echo esc_js($current_step); ?>';
    var wizardNonce = '<?php echo esc_attr(wp_create_nonce('aysa_nonce')); ?>';
    var conversationI18n = {
        en: {
            loadingContext: 'Loading project context...',
            emptyConversation: 'The conversation is empty for now.',
            preparing: 'Preparing the conversation.',
            bootstrapLoading: 'Loading context and history.',
            messageLoading: 'Analyzing your message and updating the setup.',
            connectButtonMissing: 'I could not find the Google connect button on this step.',
            connectGoogleWindow: 'The Google window is opening. You choose the account, come back here, and I will continue from where we stopped.',
            setupCompleteRedirect: 'Setup complete. Finishing and redirecting.',
            advancingTo: 'Step completed. Continuing to ',
            localSaveFailed: 'I filled the fields, but local saving failed.',
            cannotProcess: 'The conversation could not be processed.',
            waitingNext: 'Waiting for your next detail.',
            currentStepReady: 'The current step can be closed.',
            contextUpdated: 'Context updated.',
            communicationError: 'Communication error with AYSA setup conversation.',
            writeMessage: 'Write a message before sending.',
            generalAutofillRunning: 'I am gathering the main details about your business now. Please wait a moment, then I will ask you to confirm what looks correct.',
            integrationsIntro: 'Start with Google Search Console and Google Analytics. If you are not sure what they are, use the quick buttons below and I will explain each one in plain language.',
            resetConfirm: 'Start over and clear the current setup chat?',
            resetRunning: 'Starting over.',
            resetFailed: 'The setup chat could not be reset.',
            placeholder: 'Ask things like “What is Search Console?” or “Guide me step by step.”',
            send: 'Send',
            reset: 'Start over',
            language: 'Language',
            seoSetupChat: 'SEO setup chat'
        },
        ro: {
            loadingContext: 'Încarc contextul proiectului...',
            emptyConversation: 'Conversația este goală momentan.',
            preparing: 'Pregătesc conversația.',
            bootstrapLoading: 'Încarc contextul și istoricul.',
            messageLoading: 'Analizez mesajul și actualizez setup-ul.',
            connectButtonMissing: 'Nu am găsit butonul de conectare Google pe acest pas.',
            connectGoogleWindow: 'Se deschide fereastra Google. Tu alegi contul, revii aici, iar eu continui de unde am rămas.',
            setupCompleteRedirect: 'Setup complet. Finalizez și redirecționez.',
            advancingTo: 'Pas completat. Continui spre ',
            localSaveFailed: 'Am completat câmpurile, dar salvarea locală a eșuat.',
            cannotProcess: 'Conversația nu a putut fi procesată.',
            waitingNext: 'Aștept următorul detaliu de la tine.',
            currentStepReady: 'Pasul curent poate fi închis.',
            contextUpdated: 'Context actualizat.',
            communicationError: 'Eroare de comunicare cu AYSA setup conversation.',
            writeMessage: 'Scrie un mesaj înainte să trimiți.',
            generalAutofillRunning: 'Adun acum datele principale despre businessul tău. Te rog așteaptă puțin, apoi îți voi cere să confirmi ce este corect.',
            integrationsIntro: 'Începe cu Google Search Console și Google Analytics. Dacă nu știi ce sunt, folosește butoanele de mai jos și îți explic pe scurt, pe înțeles.',
            resetConfirm: 'Pornești de la capăt și ștergi conversația curentă de setup?',
            resetRunning: 'Pornesc de la capăt.',
            resetFailed: 'Conversația de setup nu a putut fi resetată.',
            placeholder: 'Întreabă, de exemplu: „Ce este Search Console?” sau „Ghidează-mă pas cu pas.”',
            send: 'Trimite',
            reset: 'Pornește de la capăt',
            language: 'Limbă',
            seoSetupChat: 'Chat configurare SEO'
        },
        bg: {
            loadingContext: 'Зареждам контекста на проекта...',
            emptyConversation: 'Разговорът е празен засега.',
            preparing: 'Подготвям разговора.',
            bootstrapLoading: 'Зареждам контекста и историята.',
            messageLoading: 'Анализирам съобщението и обновявам настройката.',
            connectButtonMissing: 'Не намерих бутона за свързване с Google на тази стъпка.',
            connectGoogleWindow: 'Отваря се прозорецът на Google. Ти избираш акаунта, връщаш се тук и аз продължавам оттам, откъдето спряхме.',
            setupCompleteRedirect: 'Настройката е завършена. Приключвам и пренасочвам.',
            advancingTo: 'Стъпката е завършена. Продължавам към ',
            localSaveFailed: 'Попълних полетата, но локалното запазване не успя.',
            cannotProcess: 'Разговорът не можа да бъде обработен.',
            waitingNext: 'Очаквам следващия детайл от теб.',
            currentStepReady: 'Текущата стъпка може да бъде затворена.',
            contextUpdated: 'Контекстът е обновен.',
            communicationError: 'Грешка при комуникация с AYSA setup conversation.',
            writeMessage: 'Напиши съобщение, преди да изпратиш.',
            generalAutofillRunning: 'Сега събирам основните данни за бизнеса ти. Моля, изчакай малко, след което ще те помоля да потвърдиш кое е вярно.',
            integrationsIntro: 'Започни с Google Search Console и Google Analytics. Ако не знаеш какво са, използвай бутоните по-долу и ще ти обясня накратко.',
            resetConfirm: 'Да нулирам ли локалния setup и чат сесията за тест?',
            resetRunning: 'Нулирам setup теста.',
            resetFailed: 'Тестът не можа да бъде нулиран.',
            placeholder: 'Попитай например „Какво е Search Console?“ или „Води ме стъпка по стъпка.“',
            send: 'Изпрати',
            reset: 'Нулирай теста',
            language: 'Език',
            seoSetupChat: 'SEO setup чат'
        }
    };
    var conversationState = {
        bootstrapped: false,
        busy: false,
        sessionId: null,
        bootstrapTimer: null,
        pollTimer: null,
        pendingRunId: null,
        suggestedActions: [],
        language: ''
    };

    function normalizeConversationLanguage(value) {
        var lang = String(value || '').toLowerCase().trim();
        if (lang === 'ro' || lang === 'bg' || lang === 'en') {
            return lang;
        }
        return 'en';
    }

    function getConversationLanguage() {
        if (conversationState.language) {
            return normalizeConversationLanguage(conversationState.language);
        }
        try {
            return normalizeConversationLanguage(localStorage.getItem('aysa_setup_chat_language') || 'en');
        } catch (e) {
            return 'en';
        }
    }

    function setConversationLanguage(lang) {
        conversationState.language = normalizeConversationLanguage(lang);
        try {
            localStorage.setItem('aysa_setup_chat_language', conversationState.language);
        } catch (e) {}
    }

    function getDefaultSuggestedActions() {
        if (current === 'integrations') {
            return [
                { label: 'Explain what Search Console does', type: 'send_message', message: 'Explain in simple terms what Google Search Console does and why I need it for this website.', style: 'primary' },
                { label: 'Explain what Google Analytics does', type: 'send_message', message: 'Explain in simple terms what Google Analytics does and why I need it for this website.' },
                { label: 'Guide me step by step', type: 'send_message', message: 'Guide me step by step to connect Google Search Console and Google Analytics for this website.' },
                { label: 'Connect Google now', type: 'connect_google' }
            ];
        }
        return [];
    }

    function tConversation(key) {
        var lang = getConversationLanguage();
        var dict = conversationI18n[lang] || conversationI18n.en;
        if (Object.prototype.hasOwnProperty.call(dict, key)) {
            return dict[key];
        }
        return (conversationI18n.en && conversationI18n.en[key]) ? conversationI18n.en[key] : key;
    }

    function refreshConversationStaticUi() {
        $('#aysa-setup-conversation-language').val(getConversationLanguage());
        $('#aysa-setup-conversation-messages .aysa-setup-conversation-empty').text(tConversation('loadingContext'));
        if (!$('#aysa-setup-conversation-messages').children().length) {
            $('#aysa-setup-conversation-messages').html('<div class="aysa-setup-conversation-empty">' + escapeConversationText(tConversation('loadingContext')) + '</div>');
        }
        $('#aysa-setup-conversation-status').text(tConversation('preparing'));
        $('#aysa-setup-conversation-input').attr('placeholder', tConversation('placeholder'));
        $('#aysa-setup-conversation-send').text(tConversation('send'));
        $('#aysa-setup-reset-btn').text(tConversation('reset'));
        $('.aysa-setup-language-switcher span').text(tConversation('language'));
        $('.aysa-setup-conversation-header p').text(tConversation('seoSetupChat'));
    }

    function normalizeComparableValue(value) {
        return String(value || '')
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .toLowerCase()
            .trim();
    }

    function setBestFieldValue($fields, value) {
        if (!$fields.length || value === null || String(value).trim() === '') {
            return;
        }

        if ($fields.is('select')) {
            var rawValue = String(value).trim();
            var normalizedIncoming = normalizeComparableValue(rawValue);
            var matched = false;

            $fields.find('option').each(function() {
                var optionValue = String($(this).val() || '').trim();
                var optionText = String($(this).text() || '').trim();
                if (optionValue === rawValue || optionText === rawValue) {
                    $fields.val(optionValue).trigger('change');
                    matched = true;
                    return false;
                }
                if (
                    normalizeComparableValue(optionValue) === normalizedIncoming
                    || normalizeComparableValue(optionText) === normalizedIncoming
                ) {
                    $fields.val(optionValue).trigger('change');
                    matched = true;
                    return false;
                }
            });

            if (!matched) {
                $fields.val(rawValue).trigger('change');
            }
            return;
        }

        $fields.val(value).trigger('change');
    }

    function applySavedDataToForm(data) {
        var $form = $('.aysa-wizard-content form').first();
        if (!$form.length || !data || typeof data !== 'object') {
            return;
        }
        Object.keys(data).forEach(function(name) {
            if (name === 'action' || name === 'step' || name === 'nonce') {
                return;
            }
            var value = data[name];
            var $fields = $form.find('[name=\"' + name + '\"]');
            if (!$fields.length) {
                $fields = $form.find('[name=\"' + name + '[]\"]');
            }
            if (!$fields.length) {
                return;
            }
            if ($fields.is(':radio')) {
                if (value !== null && String(value).trim() !== '') {
                    $fields.prop('checked', false);
                    $fields.filter('[value=\"' + String(value) + '\"]').prop('checked', true).trigger('change');
                }
                return;
            }
            if ($fields.is(':checkbox')) {
                $fields.prop('checked', false);
                if (Array.isArray(value)) {
                    value.forEach(function(v) {
                        $fields.filter('[value=\"' + String(v) + '\"]').prop('checked', true).trigger('change');
                    });
                } else if (value !== null && String(value).trim() !== '') {
                    $fields.filter('[value=\"' + String(value) + '\"]').prop('checked', true).trigger('change');
                }
                return;
            }
            if (value !== null && String(value).trim() !== '') {
                setBestFieldValue($fields, value);
            }
        });
    }

    function loadSavedDataForCurrentStep() {
        var $form = $('.aysa-wizard-content form').first();
        if (!$form.length || current === 'integrations') {
            return;
        }
        $.ajax({
            url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_get_wizard_data',
                step: current,
                nonce: wizardNonce
            },
            success: function(resp) {
                if (resp && resp.success && resp.data && resp.data.data) {
                    applySavedDataToForm(resp.data.data);
                }
            }
        });
    }
    loadSavedDataForCurrentStep();

    function getSetupProjectId() {
        var fromLocal = '';
        try {
            fromLocal = localStorage.getItem('aysa_project_id') || '';
        } catch (e) {}
        if (fromLocal && parseInt(fromLocal, 10) > 0) {
            return fromLocal;
        }
        return '<?php echo intval(get_option('aysa_project_id', 0)); ?>';
    }

    function getAccessKeyForConversation() {
        if (typeof window.AYSA_ACCESS_KEY === 'string' && window.AYSA_ACCESS_KEY.trim() !== '') {
            return window.AYSA_ACCESS_KEY.trim();
        }
        try {
            var fromLocal = localStorage.getItem('aysa_access_key');
            if (fromLocal && fromLocal.trim() !== '') {
                return fromLocal.trim();
            }
        } catch (e) {}
        return '';
    }

    function setConversationStatus(text) {
        $('#aysa-setup-conversation-status').text(text || '');
    }

    function escapeConversationText(text) {
        return $('<div/>').text(String(text || '')).html();
    }

    function renderConversationMessages(messages) {
        var $box = $('#aysa-setup-conversation-messages');
        if (!$box.length) {
            return;
        }
        $box.empty();
        if (!Array.isArray(messages) || !messages.length) {
            $box.html('<div class="aysa-setup-conversation-empty">' + escapeConversationText(tConversation('emptyConversation')) + '</div>');
            return;
        }
        messages.forEach(function(item) {
            var role = item && item.role === 'user' ? 'user' : 'assistant';
            var text = item && item.message ? item.message : '';
            $box.append('<div class="aysa-setup-conversation-bubble ' + role + '">' + escapeConversationText(text) + '</div>');
        });
        $box.scrollTop($box[0].scrollHeight);
    }

    function appendConversationMessage(role, text) {
        var $box = $('#aysa-setup-conversation-messages');
        if (!$box.length) {
            return;
        }
        $box.find('.aysa-setup-conversation-empty').remove();
        $box.append('<div class="aysa-setup-conversation-bubble ' + role + '">' + escapeConversationText(text) + '</div>');
        $box.scrollTop($box[0].scrollHeight);
    }

    function maybeAppendAssistantNotice(text) {
        var notice = String(text || '').trim();
        if (!notice) {
            return;
        }
        var $last = $('#aysa-setup-conversation-messages .aysa-setup-conversation-bubble.assistant').last();
        if ($last.length && String($last.text() || '').trim() === notice) {
            return;
        }
        appendConversationMessage('assistant', notice);
    }

    function renderSuggestedActions(actions) {
        var $box = $('#aysa-setup-conversation-suggested');
        if (!$box.length) {
            return;
        }
        if (!Array.isArray(actions) || !actions.length) {
            actions = getDefaultSuggestedActions();
        }
        conversationState.suggestedActions = Array.isArray(actions) ? actions.slice() : [];
        $box.empty();
        if (!Array.isArray(actions) || !actions.length) {
            return;
        }

        actions.forEach(function(action, index) {
            if (!action || typeof action !== 'object') {
                return;
            }
            var label = action.label ? String(action.label) : '';
            if (!label) {
                return;
            }
            var style = action.style === 'primary' ? ' is-primary' : '';
            $box.append('<button type="button" class="aysa-setup-suggested-btn' + style + '" data-action-index="' + index + '">' + escapeConversationText(label) + '</button>');
        });
    }

    function applyConversationUpdates(updates) {
        if (!updates || typeof updates !== 'object') {
            return;
        }
        if (updates[current]) {
            applySavedDataToForm(updates[current]);
            setTimeout(function() {
                applySavedDataToForm(updates[current]);
            }, 400);
        }
    }

    function triggerGoogleOauthFromConversation() {
        if (current !== 'integrations') {
            return false;
        }
        var $connectBtn = $('#aysa-google-connect-btn');
        if (!$connectBtn.length) {
            setConversationStatus(tConversation('connectButtonMissing'));
            return false;
        }
        setConversationStatus(tConversation('connectGoogleWindow'));
        $connectBtn.trigger('click');
        return true;
    }

    function applyConversationClientActions(actions) {
        if (!Array.isArray(actions) || !actions.length) {
            return;
        }
        actions.forEach(function(action) {
            if (action === 'focus_input') {
                $('#aysa-setup-conversation-input').trigger('focus');
                return;
            }
            if (action === 'open_keyword_discovery') {
                window.location.href = '<?php echo esc_js(admin_url('admin.php?page=aysa-research&tab=keyword-discovery')); ?>';
            }
        });
    }

    function sendPresetConversationMessage(message) {
        var text = String(message || '').trim();
        if (!text) {
            return;
        }
        appendConversationMessage('user', text);
        $('#aysa-setup-conversation-input').val('');
        sendConversation('message', text);
    }

    $(document).on('click', '.aysa-setup-suggested-btn', function() {
        var idx = parseInt($(this).attr('data-action-index') || '-1', 10);
        var action = (idx >= 0 && Array.isArray(conversationState.suggestedActions)) ? conversationState.suggestedActions[idx] : null;
        if (!action || typeof action !== 'object') {
            return;
        }

        if (action.type === 'connect_google') {
            triggerGoogleOauthFromConversation();
            return;
        }
        if (action.type === 'open_url' && action.url) {
            window.open(String(action.url), '_blank', 'noopener,noreferrer');
            return;
        }
        if (action.type === 'send_message' && action.message) {
            sendPresetConversationMessage(String(action.message));
            return;
        }
        if (action.type === 'focus_input') {
            $('#aysa-setup-conversation-input').trigger('focus');
        }
    });

    function bootstrapConversation(reason) {
        if (!$('#aysa-setup-conversation-panel').length) {
            return;
        }
        if (conversationState.bootstrapTimer) {
            clearTimeout(conversationState.bootstrapTimer);
            conversationState.bootstrapTimer = null;
        }
        if (reason === 'general_autofill_ready' && current !== 'general') {
            return;
        }
        sendConversation('bootstrap', '');
    }

    function maybeAdvanceFromConversation(result) {
        if (!result || !result.actions || !result.actions.should_advance || !result.next_step) {
            return;
        }
        var advanceDelay = parseInt(result.actions.advance_delay_ms || 0, 10);
        var doAdvance = function() {
            if (result.next_step === 'seo-profile-complete') {
                setConversationStatus(tConversation('setupCompleteRedirect'));
                if (typeof window.aysaFinishSetup === 'function') {
                    window.aysaFinishSetup(finishUrl);
                }
                return;
            }
            if (result.next_step === current) {
                return;
            }
            setConversationStatus(tConversation('advancingTo') + result.next_step + '.');
            saveCurrentWizardStepData(function(success) {
                if (!success) {
                    setConversationStatus(tConversation('localSaveFailed'));
                    return;
                }
                window.location.href = pageUrl + '&step=' + result.next_step;
            });
        };
        if (advanceDelay > 0) {
            window.setTimeout(doAdvance, advanceDelay);
            return;
        }
        doAdvance();
    }

    function stopConversationPoll() {
        if (conversationState.pollTimer) {
            clearTimeout(conversationState.pollTimer);
            conversationState.pollTimer = null;
        }
    }

    function processConversationResult(result) {
        conversationState.sessionId = result.session_id || null;
        if (Array.isArray(result.messages) && result.messages.length) {
            renderConversationMessages(result.messages);
        } else if (result.assistant_message) {
            appendConversationMessage('assistant', result.assistant_message);
        }

        applyConversationUpdates(result.wp_updates || {});
        applyConversationClientActions(result.client_actions || []);
        renderSuggestedActions(result.suggested_actions || []);
        if (result.assistant_message) {
            setConversationStatus(result.ready_to_advance ? tConversation('currentStepReady') : tConversation('waitingNext'));
        } else {
            setConversationStatus(tConversation('contextUpdated'));
        }
        maybeAdvanceFromConversation(result);
    }

    function pollConversationStatus(taskPayload) {
        stopConversationPoll();
        conversationState.pollTimer = setTimeout(function() {
            var payload = Object.assign({
                action: 'aysa_conversation_async_status',
                nonce: wizardNonce,
                task: 'setup',
                site_host: window.location.hostname || '',
                project_id: getSetupProjectId(),
                current_step: current,
                conversation_language: getConversationLanguage(),
                mode: 'bootstrap',
                run_id: conversationState.pendingRunId || ''
            }, taskPayload || {});
            $.ajax({
                url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                type: 'POST',
                dataType: 'json',
                data: payload,
                success: function(resp) {
                    var data = resp && resp.success && resp.data ? resp.data : null;
                    var status = data && data.status ? String(data.status) : 'failed';
                    if (status === 'queued' || status === 'running') {
                        setConversationStatus(status === 'queued' ? 'Queued...' : 'Running...');
                        pollConversationStatus(taskPayload);
                        return;
                    }
                    conversationState.pendingRunId = null;
                    if (status === 'completed' && data.result && data.result.result) {
                        processConversationResult(data.result.result);
                        return;
                    }
                    var errorMessage = (data && data.error) ? String(data.error) : tConversation('cannotProcess');
                    setConversationStatus(errorMessage);
                },
                error: function(xhr) {
                    conversationState.pendingRunId = null;
                    var text = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message
                        ? xhr.responseJSON.data.message
                        : tConversation('communicationError');
                    setConversationStatus(text);
                },
                complete: function() {
                    if (!conversationState.pendingRunId) {
                        conversationState.busy = false;
                        $('#aysa-setup-conversation-send').prop('disabled', false);
                    }
                }
            });
        }, 1200);
    }

    function sendConversation(mode, userMessage) {
        if (conversationState.busy) {
            return;
        }
        conversationState.busy = true;
        $('#aysa-setup-conversation-send').prop('disabled', true);
        setConversationStatus(mode === 'bootstrap' ? tConversation('bootstrapLoading') : tConversation('messageLoading'));

        $.ajax({
            url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_conversation_async_start',
                task: 'setup',
                nonce: wizardNonce,
                access_key: getAccessKeyForConversation(),
                site_host: window.location.hostname || '',
                project_id: getSetupProjectId(),
                current_step: current,
                conversation_language: getConversationLanguage(),
                mode: mode,
                user_message: userMessage || ''
            },
            success: function(resp) {
                if (!resp || !resp.success || !resp.data) {
                    var message = resp && resp.data && resp.data.message ? resp.data.message : tConversation('cannotProcess');
                    setConversationStatus(message);
                    conversationState.pendingRunId = null;
                    return;
                }
                conversationState.pendingRunId = String(resp.data.run_id || resp.data.runId || '');
                var status = resp.data.status ? String(resp.data.status) : '';
                if (status === 'completed' && resp.data.result && resp.data.result.result) {
                    conversationState.pendingRunId = null;
                    processConversationResult(resp.data.result.result);
                    return;
                }
                setConversationStatus(status === 'queued' ? 'Queued...' : 'Running...');
                pollConversationStatus({
                    access_key: getAccessKeyForConversation(),
                    user_message: userMessage || '',
                    mode: mode
                });
            },
            error: function(xhr) {
                var text = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message
                    ? xhr.responseJSON.data.message
                    : tConversation('communicationError');
                setConversationStatus(text);
                conversationState.pendingRunId = null;
            },
            complete: function() {
                if (!conversationState.pendingRunId) {
                    conversationState.busy = false;
                    $('#aysa-setup-conversation-send').prop('disabled', false);
                }
            }
        });
    }

    if ($('#aysa-setup-conversation-panel').length && !conversationState.bootstrapped) {
        $('.aysa-dashboard-wrapper').addClass('aysa-chat-mode-active');
        setConversationLanguage(getConversationLanguage());
        refreshConversationStaticUi();
        conversationState.bootstrapped = true;
        if (current === 'integrations') {
            maybeAppendAssistantNotice(tConversation('integrationsIntro'));
            renderSuggestedActions([]);
        }
        $.ajax({
            url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_conversation_async_status',
                nonce: wizardNonce,
                task: 'setup',
                access_key: getAccessKeyForConversation(),
                site_host: window.location.hostname || '',
                project_id: getSetupProjectId(),
                current_step: current,
                conversation_language: getConversationLanguage(),
                mode: 'bootstrap'
            }
        }).done(function(resp) {
            var data = resp && resp.success && resp.data ? resp.data : null;
            var status = data && data.status ? String(data.status) : '';
            if (status === 'queued' || status === 'running') {
                conversationState.pendingRunId = String(data.run_id || '');
                conversationState.busy = true;
                $('#aysa-setup-conversation-send').prop('disabled', true);
                setConversationStatus(status === 'queued' ? 'Queued...' : 'Running...');
                pollConversationStatus({
                    access_key: getAccessKeyForConversation(),
                    mode: 'bootstrap'
                });
            }
        });
        if (current === 'general') {
            conversationState.bootstrapTimer = setTimeout(function() {
                bootstrapConversation('initial_general_timeout');
            }, 4500);
        } else {
            bootstrapConversation('initial');
        }
    }

    window.aysaSetupConversationRefresh = bootstrapConversation;

    document.addEventListener('aysa:general-autofill-ready', function() {
        bootstrapConversation('general_autofill_ready');
    });

    document.addEventListener('aysa:general-autofill-started', function(event) {
        if (current !== 'general') {
            return;
        }
        var detailMessage = event && event.detail && event.detail.message ? String(event.detail.message) : tConversation('generalAutofillRunning');
        maybeAppendAssistantNotice(detailMessage);
        setConversationStatus(detailMessage);
    });

    $('#aysa-setup-conversation-form').on('submit', function(e) {
        e.preventDefault();
        var text = ($('#aysa-setup-conversation-input').val() || '').trim();
        if (!text) {
            setConversationStatus(tConversation('writeMessage'));
            return;
        }
        appendConversationMessage('user', text);
        $('#aysa-setup-conversation-input').val('');
        sendConversation('message', text);
    });

    $('#aysa-setup-conversation-language').on('change', function() {
        setConversationLanguage($(this).val());
        refreshConversationStaticUi();
        bootstrapConversation('language_change');
    });

    $('#aysa-setup-reset-btn').on('click', function() {
        if (!window.confirm(tConversation('resetConfirm'))) {
            return;
        }
        setConversationStatus(tConversation('resetRunning'));
        $.ajax({
            url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_setup_reset_chat_test',
                nonce: wizardNonce,
                access_key: getAccessKeyForConversation(),
                site_host: window.location.hostname || '',
                project_id: getSetupProjectId()
            },
            success: function(resp) {
                if (!resp || !resp.success) {
                    var message = resp && resp.data && resp.data.message ? resp.data.message : tConversation('resetFailed');
                    setConversationStatus(message);
                    return;
                }
                window.location.href = pageUrl + '&step=integrations';
            },
            error: function() {
                setConversationStatus(tConversation('resetFailed'));
            }
        });
    });

    // Previous step button
    $('#aysa-prev-step').off('click.aysaWizardNav').on('click.aysaWizardNav', function() {
        var idx = wizardSteps.indexOf(current);
        if (idx > 0) {
            window.location.href = pageUrl + '&step=' + wizardSteps[idx - 1];
        }
    });

    // Next button: save current step before navigating.
    $('#aysa-next-step').off('click.aysaWizardNav').on('click.aysaWizardNav', function(e) {
        e.preventDefault();
        var idx = wizardSteps.indexOf(current);
        if (current === 'tone-of-voice') {
            // This should never be reached now since tone-of-voice uses aysaFinishSetup
            window.location.href = dashboardUrl;
        } else if (idx < wizardSteps.length - 1) {
            var nextUrl = pageUrl + '&step=' + wizardSteps[idx + 1];
            saveCurrentWizardStepData(function(success) {
                if (!success) {
                    alert('Failed to save current step. Please try again.');
                    return;
                }
                window.location.href = nextUrl;
            });
        }
    });
    
    // Fallback event handler for Finish button (in case onclick doesn't work)
    $(document).on('click', '.aysa-btn-primary:contains("Finish")', function(e) {
        e.preventDefault();
        
        if (current === 'tone-of-voice') {
            // Get the finish URL from onclick attribute
            var onclickAttr = $(this).attr('onclick');
            if (onclickAttr) {
                var urlMatch = onclickAttr.match(/aysaFinishSetup\('([^']+)'\)/);
                if (urlMatch && urlMatch[1]) {
                    var finishUrl = urlMatch[1];
                    
                    // Call the global function
                    if (typeof window.aysaFinishSetup === 'function') {
                        window.aysaFinishSetup(finishUrl);
                    } else {
                        window.location.href = finishUrl;
                    }
                }
            }
        }
    });

    // End of document ready
});
    
</script>

<!-- Additional CSS fixes for form interactions -->
<style id="aysa-form-fix">
/* Limit interaction fixes to the setup wizard only. */
.aysa-dashboard-wrapper input,
.aysa-dashboard-wrapper select,
.aysa-dashboard-wrapper textarea,
.aysa-dashboard-wrapper button,
.aysa-dashboard-wrapper a {
    pointer-events: auto !important;
}

.aysa-dashboard-wrapper input[type="text"],
.aysa-dashboard-wrapper input[type="email"],
.aysa-dashboard-wrapper input[type="password"],
.aysa-dashboard-wrapper input[type="tel"],
.aysa-dashboard-wrapper input[type="url"],
.aysa-dashboard-wrapper select,
.aysa-dashboard-wrapper textarea {
    pointer-events: auto !important;
    -webkit-user-select: text !important;
    user-select: text !important;
    -webkit-appearance: auto !important;
    appearance: auto !important;
    position: relative !important;
    z-index: 2 !important;
}

/* Fix for select dropdowns */
.aysa-dashboard-wrapper select {
    -webkit-appearance: menulist !important;
    appearance: menulist !important;
}

/* Override all other z-index settings */
.aysa-wizard-content {
    position: relative;
    z-index: 10;
}

/* Fix for checkboxes */
.aysa-dashboard-wrapper input[type="checkbox"] {
    -webkit-appearance: checkbox !important;
    appearance: checkbox !important;
    opacity: 1 !important;
    position: static !important;
}

/* Ensure labels are clickable */
.aysa-dashboard-wrapper label {
    pointer-events: auto !important;
    cursor: pointer;
    z-index: 2 !important;
    position: relative !important;
}

/* Fix any wordpress admin interfering styles */
.wp-admin .aysa-dashboard-wrapper input[type="text"], 
.wp-admin .aysa-dashboard-wrapper input[type="email"],
.wp-admin .aysa-dashboard-wrapper input[type="password"],
.wp-admin .aysa-dashboard-wrapper input[type="tel"],
.wp-admin .aysa-dashboard-wrapper input[type="url"],
.wp-admin .aysa-dashboard-wrapper select,
.wp-admin .aysa-dashboard-wrapper textarea {
    z-index: 2 !important;
    position: relative !important;
    pointer-events: auto !important;
}

/* Fix specific plugin elements */
.aysa-dashboard-wrapper .aysa-form-group,
.aysa-dashboard-wrapper .aysa-integration-card,
.aysa-dashboard-wrapper .aysa-integration-card-body,
.aysa-dashboard-wrapper .aysa-input-password,
.aysa-dashboard-wrapper .aysa-toggle-password {
    position: relative !important;
    z-index: 2 !important;
    pointer-events: auto !important;
}

/* Explicit override for any pointer-events: none that might be inheriting */
.aysa-dashboard-wrapper input,
.aysa-dashboard-wrapper select,
.aysa-dashboard-wrapper textarea,
.aysa-dashboard-wrapper button,
.aysa-dashboard-wrapper .aysa-btn,
.aysa-dashboard-wrapper .aysa-form-group,
.aysa-dashboard-wrapper .aysa-card,
.aysa-dashboard-wrapper .aysa-input-password,
.aysa-dashboard-wrapper .aysa-toggle-password {
    pointer-events: auto !important;
}

/* Fix dropdown arrows */
.aysa-dashboard-wrapper select::-ms-expand {
    display: block !important;
}
</style>

<script>
jQuery(document).ready(function($) {
    // Remove any event handlers that might be blocking input
    $('.aysa-dashboard-wrapper').off('click.aysaBlur');
    
    // Force input fields to be interactive
    $('.aysa-dashboard-wrapper').find('input, select, textarea').each(function() {
        const $this = $(this);
        $this.attr('tabindex', '0');
        $this.css({
            'pointer-events': 'auto',
            'position': 'relative',
            'z-index': '2'
        });
    });
    
    // Check if WordPress is doing something to block events
    $('.aysa-dashboard-wrapper').on('mouseover', 'input, select, textarea', function() {
        const $this = $(this);
        const pointerEvents = $this.css('pointer-events');
        if (pointerEvents === 'none') {
            $this.css('pointer-events', 'auto');
        }
    });
    
    // Fix Click handling
    $('.aysa-dashboard-wrapper').find('input, select, textarea, label').off('click.aysaFormFix').on('click.aysaFormFix', function() {
        if ($(this).is('label')) {
            const forAttr = $(this).attr('for');
            if (forAttr) {
                $(`#${forAttr}`).focus();
            }
        }
    });
});
</script> 

<!-- Fallback script pentru aysaFinishSetup - Vanilla JavaScript -->
<script>
// Ensure aysaFinishSetup is always available (fallback)
(function() {
    // Wait for DOM to be ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initFallback);
    } else {
        initFallback();
    }
    
    function initFallback() {
        // Check if function exists after a short delay
        setTimeout(function() {
            if (typeof window.aysaFinishSetup === 'undefined') {
                window.aysaFinishSetup = function(url) {
                    // Show loading state
                    var button = document.querySelector('button[onclick*="aysaFinishSetup"]');
                    if (button) {
                        button.innerHTML = '<span class="dashicons dashicons-update"></span> Finishing...';
                        button.disabled = true;
                    }
                    
                    // Simple redirect without AJAX as ultimate fallback
                    setTimeout(function() {
                        window.location.href = url;
                    }, 500);
                };
            }
        }, 200);
    }
})();
</script>
