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

// Display typing text for this section
if (function_exists('aysa_display_typing_text_section')) {
    // 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.
    $integrations_text = "Welcome to the Integrations step! Here, you can connect Aysa with other services you use, like Google Analytics or social media platforms. This helps Aysa gather more data to provide comprehensive SEO insights.";
    echo wp_kses_post(aysa_display_typing_text_section($integrations_text, 'integrations'));
}
?>

<div class="aysa-wizard-section">
    <h2><span class="dashicons dashicons-admin-plugins"></span> API Integrations</h2>
    <p class="aysa-text-muted">Start here. Connect Google first so AYSA can understand how your website performs and what people search before you continue with the rest of setup.</p>

    <div class="aysa-onboarding-alert">
        <div class="aysa-onboarding-alert-icon">
            <span class="dashicons dashicons-lightbulb"></span>
        </div>
        <div class="aysa-onboarding-alert-content">
            <h3>Step 1: Connect Google before anything else</h3>
            <p>AYSA needs two Google data sources to guide your SEO setup properly: Google Search Console and Google Analytics. If you already use them, connect the Google account that manages this website. If you do not have them yet, use the buttons below to open Google and create them first.</p>
            <ul>
                <li><strong>Google Search Console</strong> shows what people search for before they click your website in Google.</li>
                <li><strong>Google Analytics</strong> shows what visitors do after they arrive on your website.</li>
            </ul>
        </div>
    </div>
    
    <div class="aysa-info-box">
        <div class="aysa-info-box-icon">
            <span class="dashicons dashicons-info"></span>
        </div>
        <div class="aysa-info-box-content">
            <p>If Google shows a warning screen during authorization, it is the standard Google consent screen. Continue only with the Google account that manages this website, then come back here and click <strong>Refresh status</strong>.</p>
        </div>
    </div>

    <?php
    $aysa_project_id = intval(get_option('aysa_project_id', 0));
    ?>
    <div class="aysa-google-oauth-box">
        <div class="aysa-google-oauth-header">
            <h3>Google OAuth Integration</h3>
            <span class="aysa-badge aysa-badge-required">Live</span>
        </div>
        <p class="aysa-text-muted">Connect once, then AYSA keeps the Google connection refreshed automatically in the background.</p>
        <div id="aysa-google-oauth-status" class="aysa-google-oauth-status">Checking connection...</div>
        <div class="aysa-google-oauth-actions">
            <button type="button" class="button button-primary" id="aysa-google-connect-btn">Connect Google account</button>
            <button type="button" class="button" id="aysa-google-refresh-btn">Refresh status</button>
            <button type="button" class="button button-secondary" id="aysa-google-disconnect-btn">Disconnect</button>
        </div>
        <p class="description">Project ID: <code id="aysa-google-project-id"><?php echo esc_html((string) $aysa_project_id); ?></code></p>
        <p class="description">Use the same Google account that manages your website in Search Console and Analytics.</p>
    </div>
    
    <form id="aysa-integrations-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
        <input type="hidden" name="action" value="aysa_save_wizard_data">
        <input type="hidden" name="step" value="integrations">
        
        <div class="aysa-integration-cards">
            <div class="aysa-integration-card">
                <div class="aysa-integration-card-header">
                    <div class="aysa-integration-icon">
                        <img src="<?php echo esc_url(AYSA_PLUGIN_URL . 'assets/images/google-search-console.svg'); ?>" alt="Google Search Console" onerror="this.src='<?php echo esc_url(AYSA_PLUGIN_URL . 'assets/images/placeholder.svg'); ?>'; this.onerror='';">
                        <span class="aysa-integration-icon-fallback dashicons dashicons-google"></span>
                    </div>
                    <h3>Google Search Console <span class="aysa-badge aysa-badge-optional" id="aysa-gsc-badge">Not connected</span></h3>
                </div>
                <div class="aysa-integration-card-body">
                    <p>Search Console tells AYSA which Google searches already bring impressions and clicks to your website.</p>
                    <div class="aysa-google-step-list">
                        <div><strong>1.</strong> Click <strong>Connect Google account</strong>.</div>
                        <div><strong>2.</strong> Choose the Google account that manages this website in Search Console.</div>
                        <div><strong>3.</strong> Come back here and click <strong>Refresh status</strong>.</div>
                    </div>
                    <p class="description" id="aysa-gsc-status-detail">Detected Search Console properties: 0</p>
                    <div class="aysa-selection-row">
                        <label for="aysa-gsc-select"><strong>Search Console property used by AYSA</strong></label>
                        <select id="aysa-gsc-select" class="aysa-input" disabled>
                            <option value="">Connect Google to load available properties</option>
                        </select>
                    </div>
                    <p class="aysa-integration-help">Do not have Search Console yet? Open Google Search Console, add your website, and verify ownership. After that, return here and refresh the connection.</p>
                    <div class="aysa-provider-actions">
                        <button type="button" class="button button-primary aysa-provider-connect-btn">Connect Google account</button>
                        <a href="https://search.google.com/search-console" target="_blank" rel="noopener noreferrer" class="button">Open Search Console</a>
                        <a href="https://search.google.com/search-console/welcome" target="_blank" rel="noopener noreferrer" class="button">Create Search Console property</a>
                    </div>
                </div>
            </div>

            <div class="aysa-integration-card">
                <div class="aysa-integration-card-header">
                    <div class="aysa-integration-icon">
                        <img src="<?php echo esc_url(AYSA_PLUGIN_URL . 'assets/images/google-analytics.svg'); ?>" alt="Google Analytics" onerror="this.src='<?php echo esc_url(AYSA_PLUGIN_URL . 'assets/images/placeholder.svg'); ?>'; this.onerror='';">
                        <span class="aysa-integration-icon-fallback dashicons dashicons-chart-area"></span>
                    </div>
                    <h3>Google Analytics <span class="aysa-badge aysa-badge-optional" id="aysa-ga4-badge">Not connected</span></h3>
                </div>
                <div class="aysa-integration-card-body">
                    <p>Analytics tells AYSA what visitors do after they arrive on your website, which pages matter most, and where traffic drops.</p>
                    <div class="aysa-google-step-list">
                        <div><strong>1.</strong> Click <strong>Connect Google account</strong>.</div>
                        <div><strong>2.</strong> Approve Analytics access for the same Google account.</div>
                        <div><strong>3.</strong> Review the detected properties after <strong>Refresh status</strong>.</div>
                    </div>
                    <p class="description" id="aysa-ga4-status-detail">Detected GA4 properties: 0</p>
                    <div class="aysa-selection-row">
                        <label for="aysa-ga4-select"><strong>GA4 property used by AYSA</strong></label>
                        <select id="aysa-ga4-select" class="aysa-input" disabled>
                            <option value="">Connect Google to load available properties</option>
                        </select>
                    </div>
                    <p class="aysa-integration-help">Do not have Google Analytics yet? Open Google Analytics, create a property for this website, then come back here and refresh the connection.</p>
                    <div class="aysa-provider-actions">
                        <button type="button" class="button button-primary aysa-provider-connect-btn">Connect Google account</button>
                        <a href="https://analytics.google.com/" target="_blank" rel="noopener noreferrer" class="button">Open Analytics</a>
                        <a href="https://analytics.google.com/analytics/web/" target="_blank" rel="noopener noreferrer" class="button">Create Analytics property</a>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Subscription Agreement -->
        <div class="aysa-agreement-section">
            <div class="aysa-form-group">
                <div class="aysa-checkbox-item">
                    <input type="checkbox" id="terms-agreement" name="terms_agreement" required>
                    <label for="terms-agreement">I agree to the <a href="https://aysa.ai/terms/" target="_blank">Terms of Service</a> and <a href="https://aysa.ai/privacy/" target="_blank">Privacy Policy</a></label>
                </div>
            </div>
        </div>
        <div class="aysa-google-selection-actions">
            <button type="button" class="button" id="aysa-google-save-selection-btn" disabled>Save Selected Properties</button>
            <span class="description" id="aysa-google-selection-hint">AYSA will try to match the property by domain automatically. If the match is not exact, choose it manually.</span>
        </div>
    </form>
</div>

<style>
/* Integration page specific styles */
.aysa-integration-cards {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 30px;
    max-width: 800px; /* Limit width since we only have 2 cards */
}

.aysa-onboarding-alert {
    display: flex;
    gap: 16px;
    align-items: flex-start;
    max-width: 980px;
    margin: 0 0 20px;
    padding: 18px 20px;
    border-radius: 14px;
    border: 1px solid #f4c7c3;
    background: #fff4f2;
}

.aysa-onboarding-alert-icon {
    width: 42px;
    height: 42px;
    flex: 0 0 42px;
    border-radius: 999px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #ffffff;
    color: #c2410c;
    border: 1px solid #fed7aa;
}

.aysa-onboarding-alert-content h3 {
    margin: 0 0 8px;
    font-size: 18px;
    line-height: 1.3;
    color: #7c2d12;
}

.aysa-onboarding-alert-content p {
    margin: 0;
    color: #7a4a31;
    line-height: 1.6;
}

.aysa-onboarding-alert-content ul {
    margin: 12px 0 0 18px;
    color: #7a4a31;
}

.aysa-onboarding-alert-content li + li {
    margin-top: 6px;
}

.aysa-google-oauth-box {
    background: #fff;
    border: 1px solid #dcdcde;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 20px;
    max-width: 800px;
}

.aysa-google-oauth-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
}

.aysa-google-oauth-header h3 {
    margin: 0;
    font-size: 16px;
}

.aysa-google-oauth-status {
    margin: 10px 0 12px;
    padding: 10px 12px;
    border-radius: 6px;
    background: #f6f7f7;
    border: 1px solid #dcdcde;
}

.aysa-google-oauth-status.is-success {
    background: #edfaef;
    border-color: #91d5a4;
    color: #135e2d;
}

.aysa-google-oauth-status.is-error {
    background: #fdecec;
    border-color: #efb0b0;
    color: #8a1f1f;
}

.aysa-google-oauth-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.aysa-google-step-list {
    margin: 10px 0 12px;
    display: grid;
    gap: 6px;
    font-size: 13px;
    color: #334155;
}

.aysa-provider-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    margin-top: 8px;
}

.aysa-selection-row {
    margin-top: 10px;
}

.aysa-selection-row label {
    display: block;
    margin-bottom: 6px;
}

.aysa-google-selection-actions {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 12px;
    flex-wrap: wrap;
}

.aysa-integration-card {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
    overflow: hidden;
    transition: box-shadow 0.3s ease, transform 0.2s ease;
    border: 1px solid #e0e0e0;
}

.aysa-integration-card:hover {
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
}

.aysa-integration-card-header {
    padding: 15px 20px;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    align-items: center;
}

.aysa-integration-icon {
    position: relative;
    width: 36px;
    height: 36px;
    margin-right: 12px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.aysa-integration-icon img {
    width: 36px;
    height: 36px;
    border-radius: 6px;
    object-fit: contain;
}

.aysa-integration-icon-fallback {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: #5f6368;
    background-color: #f1f3f4;
    z-index: -1;
}

.aysa-integration-card-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
    color: #202124;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
}

.aysa-integration-card-body {
    padding: 20px;
}

.aysa-integration-card-body p {
    margin-top: 0;
    margin-bottom: 15px;
    color: #5f6368;
    font-size: 14px;
}

.aysa-integration-help {
    font-size: 13px !important;
    line-height: 1.6;
    color: #334155 !important;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 10px 12px;
    margin: 12px 0 0 !important;
}

.aysa-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
    text-transform: uppercase;
}

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

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

.aysa-badge-coming-soon {
    background-color: #f3f4f6;
    color: #6b7280;
}

.aysa-input-help {
    font-size: 12px;
    color: #5f6368;
    margin-top: 5px;
    margin-bottom: 0;
}

.aysa-input-help a {
    color: #1a73e8;
    text-decoration: none;
}

.aysa-input-help a:hover {
    text-decoration: underline;
}

.aysa-input-password {
    position: relative;
    display: flex;
}

.aysa-toggle-password {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    cursor: pointer;
    padding: 0;
    color: #5f6368;
}

.aysa-toggle-password:hover {
    color: #1a73e8;
}

.aysa-toggle-password .dashicons {
    width: 20px;
    height: 20px;
    font-size: 20px;
}

.aysa-agreement-section {
    background-color: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    border: 1px solid #e0e0e0;
}

@media (max-width: 767px) {
    .aysa-integration-cards {
        grid-template-columns: 1fr;
    }
    .aysa-onboarding-alert {
        flex-direction: column;
    }
}

/* Disabled Integration Card Styles */
.aysa-integration-card.aysa-integration-disabled {
    opacity: 0.4;
    pointer-events: none;
    filter: grayscale(70%);
    position: relative;
}

.aysa-integration-card.aysa-integration-disabled:hover {
    transform: none;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
}

/* Keep Coming Soon badge normal (not greyed out) */
.aysa-integration-card.aysa-integration-disabled .aysa-badge-coming-soon {
    opacity: 1;
    filter: none;
    background-color: #ec4899;
    color: #ffffff;
    font-weight: 600;
}

.aysa-integration-card.aysa-integration-disabled .aysa-integration-card-header {
    background-color: #f8f9fa;
}

/* Disable description text */
.aysa-integration-card.aysa-integration-disabled .aysa-integration-card-body p {
    color: #d1d5db;
    opacity: 0.7;
}

.aysa-integration-card.aysa-integration-disabled .aysa-input,
.aysa-integration-card.aysa-integration-disabled .aysa-integration-submit {
    background-color: #f8f9fa;
    color: #9ca3af;
    border-color: #e5e7eb;
    cursor: not-allowed;
}

/* Fix the password toggle button appearance when disabled */
.aysa-integration-card.aysa-integration-disabled .aysa-toggle-password {
    background: none;
    border: none;
    color: #d1d5db;
    cursor: not-allowed;
    opacity: 0.5;
}

.aysa-integration-card.aysa-integration-disabled .aysa-toggle-password:hover {
    color: #d1d5db;
    background: none;
}

.aysa-integration-card.aysa-integration-disabled .aysa-integration-submit {
    background-color: #e5e7eb;
}



.aysa-integration-submit {
    width: auto;
    margin-top: 15px;
    padding: 8px 16px;
    background-color: #1a73e8;
    color: white;
    border: none;
    border-radius: 4px;
    font-weight: 500;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s ease;
    text-align: center;
}

.aysa-integration-submit:hover {
    background-color: #1765cc;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.aysa-integration-submit:active {
    transform: translateY(1px);
}

.aysa-integration-submit.success {
    background-color: #0f9d58;
}

.aysa-integration-submit.error {
    background-color: #d93025;
}

.aysa-integration-status {
    display: none;
    font-size: 13px;
    margin-top: 5px;
    padding: 4px 8px;
    border-radius: 4px;
}

.aysa-integration-status.success {
    display: block;
    color: #0f9d58;
    background-color: #e6f4ea;
}

.aysa-integration-status.error {
    display: block;
    color: #d93025;
    background-color: #fce8e6;
}

.aysa-api-unavailable-notice {
    background-color: #fff3e0;
    border-left: 4px solid #ff9800;
    padding: 16px;
    margin-bottom: 20px;
    border-radius: 4px;
    display: flex;
    align-items: flex-start;
    gap: 12px;
}

.aysa-api-unavailable-notice .dashicons {
    color: #ff9800;
    font-size: 24px;
}

.aysa-api-unavailable-notice p {
    margin: 0;
    color: #5f6368;
    font-size: 14px;
    line-height: 1.5;
}

.aysa-wizard-navigation {
    display: flex;
    justify-content: space-between;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #e0e0e0;
}

.aysa-btn {
    display: inline-flex;
    align-items: center;
    padding: 10px 20px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    border: none;
    text-decoration: none;
}

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

.aysa-btn-primary {
    background-color: #1a73e8;
    color: white;
}

.aysa-btn-primary:hover {
    background-color: #1765cc;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.aysa-btn-secondary {
    background-color: #f1f3f4;
    color: #5f6368;
}

.aysa-btn-secondary:hover {
    background-color: #e8eaed;
    color: #202124;
}

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

.aysa-btn-secondary .dashicons {
    margin-right: 8px;
}
</style>

<script>
jQuery(document).ready(function($) {
    const googleNonce = '<?php echo esc_js(wp_create_nonce("aysa_google_oauth_nonce")); ?>';
    let oauthProjectId = parseInt($('#aysa-google-project-id').text(), 10) || 0;
    if (!oauthProjectId) {
        const localProjectId = parseInt(localStorage.getItem('aysa_project_id') || '0', 10) || 0;
        if (localProjectId > 0) {
            oauthProjectId = localProjectId;
            $('#aysa-google-project-id').text(String(localProjectId));
        }
    }
    function setGoogleStatus(message, type) {
        const $status = $('#aysa-google-oauth-status');
        $status.text(message || 'Unknown status');
        $status.removeClass('is-success is-error is-info');
        if (type === 'success') {
            $status.addClass('is-success');
        } else if (type === 'error') {
            $status.addClass('is-error');
        } else {
            $status.addClass('is-info');
        }
    }

    function setGoogleButtons(connected) {
        $('#aysa-google-connect-btn').prop('disabled', connected);
        $('#aysa-google-disconnect-btn').prop('disabled', !connected);
    }

    function updateProviderCards(data) {
        const connected = !!(data && data.connected);
        const gscCount = parseInt((data && data.gsc_sites_count) || 0, 10);
        const ga4Count = parseInt((data && data.ga4_properties_count) || 0, 10);
        $('#aysa-gsc-badge').text(connected ? 'Connected' : 'Not connected');
        $('#aysa-ga4-badge').text(connected ? 'Connected' : 'Not connected');
        $('#aysa-gsc-status-detail').text(`Detected Search Console properties: ${gscCount}`);
        $('#aysa-ga4-status-detail').text(`Detected GA4 properties: ${ga4Count}`);
        $('#aysa-google-save-selection-btn').prop('disabled', !connected);
    }

    function fillSelect($select, options, selectedValue, placeholder) {
        $select.empty();
        const list = Array.isArray(options) ? options : [];
        if (!list.length) {
            $select.append($('<option>').val('').text(placeholder));
            $select.prop('disabled', true);
            return;
        }
            $select.append($('<option>').val('').text('Select a property'));
        list.forEach((opt) => {
            const val = (opt && opt.id) ? String(opt.id) : '';
            const label = (opt && opt.label) ? String(opt.label) : val;
            if (val) {
                $select.append($('<option>').val(val).text(label));
            }
        });
        if (selectedValue) {
            $select.val(String(selectedValue));
        }
        $select.prop('disabled', false);
    }

    function updateSelectionUI(data) {
        const selectedGsc = (data && data.selected_gsc_site) ? String(data.selected_gsc_site) : '';
        const selectedGa4 = (data && data.selected_ga4_property) ? String(data.selected_ga4_property) : '';
        fillSelect(
            $('#aysa-gsc-select'),
            data && data.gsc_options ? data.gsc_options : [],
            selectedGsc,
            'No Search Console properties found yet'
        );
        fillSelect(
            $('#aysa-ga4-select'),
            data && data.ga4_options ? data.ga4_options : [],
            selectedGa4,
            'No Analytics properties found yet'
        );

        const suggestedGsc = data && data.suggested_gsc_site ? String(data.suggested_gsc_site) : '';
        const suggestedGa4 = data && data.suggested_ga4_property ? String(data.suggested_ga4_property) : '';
        if (selectedGsc && selectedGa4) {
            $('#aysa-google-selection-hint').text('Both properties are selected and saved for this project.');
        } else if (suggestedGsc || suggestedGa4) {
            $('#aysa-google-selection-hint').text('AYSA matched the property automatically where the website match was clear. Complete anything missing manually.');
        } else {
            $('#aysa-google-selection-hint').text('AYSA could not match the correct property with enough confidence. Please select it manually.');
        }
    }

    function aysaGoogleAjax(action, data = {}) {
        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: Object.assign({
                action,
                nonce: googleNonce,
                project_id: oauthProjectId
            }, data)
        });
    }

    async function refreshGoogleOAuthStatus() {
        setGoogleStatus('Checking Google connection...', 'info');
        try {
            const response = await aysaGoogleAjax('aysa_google_status');
            if (response && response.success && response.data && response.data.credentials_configured === false) {
                setGoogleStatus(response.data.message || 'Google OAuth credentials are not configured.', 'error');
                setGoogleButtons(false);
                updateProviderCards({ connected: false, gsc_sites_count: 0, ga4_properties_count: 0 });
                updateSelectionUI({});
                return;
            }
            if (!response || !response.success || !response.data || !response.data.connected) {
                if (response && response.success && response.data && response.data.reauthorize_required) {
                    setGoogleStatus('Token expired and refresh failed. Click Connect Google to re-authorize.', 'error');
                } else {
                    setGoogleStatus('Not connected. Click Connect Google to start OAuth.', 'info');
                }
                setGoogleButtons(false);
                updateProviderCards({ connected: false, gsc_sites_count: 0, ga4_properties_count: 0 });
                updateSelectionUI({});
                return;
            }

            const data = response.data;
            const info = [
                'Connected',
                data.email ? `email: ${data.email}` : '',
                `GSC properties: ${parseInt(data.gsc_sites_count || 0, 10)}`,
                `GA4 properties: ${parseInt(data.ga4_properties_count || 0, 10)}`
            ].filter(Boolean).join(' | ');
            setGoogleStatus(info, 'success');
            setGoogleButtons(true);
            updateProviderCards(data);
            updateSelectionUI(data);
        } catch (error) {
            const message = (error && error.responseJSON && error.responseJSON.data) ? error.responseJSON.data : 'Status check failed.';
            setGoogleStatus(message, 'error');
            setGoogleButtons(false);
            updateProviderCards({ connected: false, gsc_sites_count: 0, ga4_properties_count: 0 });
            updateSelectionUI({});
        }
    }

    $('#aysa-google-connect-btn').on('click', async function() {
        $(this).prop('disabled', true);
        setGoogleStatus('Preparing Google OAuth redirect...', 'info');
        try {
            const response = await aysaGoogleAjax('aysa_google_get_auth_url', {
                return_url: window.location.href
            });
            if (!response || !response.success || !response.data || !response.data.auth_url) {
                throw new Error('Could not generate Google authorization URL.');
            }
            window.location.href = response.data.auth_url;
        } catch (error) {
            const message = (error && error.responseJSON && error.responseJSON.data) ? error.responseJSON.data : (error.message || 'OAuth init failed.');
            setGoogleStatus(message, 'error');
            $(this).prop('disabled', false);
        }
    });

    $('#aysa-google-refresh-btn').on('click', async function() {
        await refreshGoogleOAuthStatus();
    });

    $('.aysa-provider-connect-btn').on('click', function() {
        $('#aysa-google-connect-btn').trigger('click');
    });

    $('#aysa-google-disconnect-btn').on('click', async function() {
        if (!window.confirm('Disconnect Google account for this project?')) {
            return;
        }
        $(this).prop('disabled', true);
        try {
            const response = await aysaGoogleAjax('aysa_google_disconnect');
            if (!response || !response.success) {
                throw new Error('Disconnect failed');
            }
            setGoogleStatus('Google account disconnected.', 'info');
            setGoogleButtons(false);
            updateSelectionUI({});
        } catch (error) {
            const message = (error && error.responseJSON && error.responseJSON.data) ? error.responseJSON.data : 'Disconnect failed.';
            setGoogleStatus(message, 'error');
        } finally {
            $('#aysa-google-disconnect-btn').prop('disabled', false);
        }
    });

    $('#aysa-google-save-selection-btn').on('click', async function() {
        const selectedGsc = ($('#aysa-gsc-select').val() || '').trim();
        const selectedGa4 = ($('#aysa-ga4-select').val() || '').trim();
        if (!selectedGsc && !selectedGa4) {
            setGoogleStatus('Select at least one property before saving.', 'error');
            return;
        }
        const $btn = $(this);
        $btn.prop('disabled', true).text('Saving...');
        try {
            const response = await aysaGoogleAjax('aysa_google_save_properties', {
                selected_gsc_site: selectedGsc,
                selected_ga4_property: selectedGa4
            });
            if (!response || !response.success) {
                throw new Error('Save failed');
            }
            setGoogleStatus('Selected properties saved.', 'success');
            await refreshGoogleOAuthStatus();
        } catch (error) {
            const message = (error && error.responseJSON && error.responseJSON.data) ? error.responseJSON.data : 'Failed to save selected properties.';
            setGoogleStatus(message, 'error');
        } finally {
            $btn.prop('disabled', false).text('Save Selected Properties');
        }
    });

    $('#aysa-next-step').on('click', async function(e) {
        e.preventDefault();

        if (!$('#terms-agreement').is(':checked')) {
            alert('Please agree to the Terms of Service and Privacy Policy');
            return;
        }

        const $nextBtn = $('#aysa-next-step');
        $nextBtn.html('<span class="aysa-spinner"></span> Saving...').prop('disabled', true);

        const formData = $('#aysa-integrations-form').serialize();
        const additionalData = `&project_id=${oauthProjectId}&action=aysa_save_wizard_data`;

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData + additionalData,
            success: function(response) {
                if (response && response.success) {
                    $nextBtn.html('<span class="dashicons dashicons-yes"></span> Saved!');
                    setTimeout(function() {
                        window.location.href = '?page=aysa-setup-seo-profile&step=general';
                    }, 500);
                } else {
                    alert((response && response.data && response.data.message) ? response.data.message : 'An error occurred. Please try again.');
                    $nextBtn.html('Next <span class="dashicons dashicons-arrow-right-alt"></span>').prop('disabled', false);
                }
            },
            error: function() {
                alert('A server error occurred. Please try again.');
                $nextBtn.html('Next <span class="dashicons dashicons-arrow-right-alt"></span>').prop('disabled', false);
            }
        });
    });

    refreshGoogleOAuthStatus();

    const params = new URLSearchParams(window.location.search);
    if (params.get('aysa_google') === 'connected') {
        setGoogleStatus('Google OAuth completed. Validating access...', 'info');
        refreshGoogleOAuthStatus();
        params.delete('aysa_google');
        const cleaned = `${window.location.pathname}?${params.toString()}`.replace(/\?$/, '');
        window.history.replaceState({}, document.title, cleaned);
    }
});
</script> 
