<?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.
    $general_text = "Let's gather some basic details about your website and business. This information helps Aysa understand your niche and tailor SEO strategies specifically for you.";
    echo wp_kses_post(aysa_display_typing_text_section($general_text, 'general'));
}
?>

<div class="aysa-wizard-section">
    <div class="aysa-wizard-header">
        <h2>Website and Business Details</h2>
        <p class="aysa-text-muted">These details help AYSA personalize the workspace, recommendations, and content for your business.</p>

        <div class="aysa-info-box">
            <span class="dashicons dashicons-info-outline"></span>
            <p>Did you know? Personalized content improves SEO performance by up to 85%! Complete these details to ensure we provide tailored recommendations and boost your website's search visibility.</p>
        </div>
    </div>

    <form id="aysa-general-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="general">
        <input type="hidden" name="nonce" value="<?php echo esc_attr(wp_create_nonce('aysa_nonce')); ?>">

        <div class="aysa-form-container">
            <!-- Company Information -->
            <div class="aysa-card">
                <div class="aysa-card-header">
                    <span class="dashicons dashicons-building"></span>
                    <h3>Company Information</h3>
                    <div id="generation-status" class="aysa-status-indicator">
                        <span class="dashicons dashicons-update aysa-spinning"></span> Generating info...
                    </div>
                </div>

                <div class="aysa-form-group">
                    <label for="company_name">Company Name <span class="aysa-required">*</span></label>
                    <input type="text" id="company_name" name="company_name" class="aysa-input" required>
                    <p class="aysa-text-muted">Enter the official name of your business. This will help personalize your SEO recommendations based on your brand.</p>
                </div>

                <div class="aysa-form-group">
                    <label for="brand_name">Brand <span class="aysa-required">*</span></label>
                    <input type="text" id="brand_name" name="brand_name" class="aysa-input" required>
                    <p class="aysa-text-muted">Enter your brand name as you want it to appear in content.</p>
                </div>

                <div class="aysa-form-group">
                    <label for="company_description">Company Description</label>
                    <textarea id="company_description" name="company_description" class="aysa-textarea" rows="4"></textarea>
                    <p class="aysa-text-muted">Provide a concise yet detailed description of your company. Highlight key services or products to improve how search engines understand your business.</p>
                </div>

                <div class="aysa-form-group">
                    <label for="support_phone">Support Phone Number <span class="aysa-required">*</span></label>
                    <input type="tel" id="support_phone" name="support_phone" class="aysa-input" required>
                    <p class="aysa-text-muted">Provide the phone number that customers can use to contact your support team. This will be displayed on your website and in search results if applicable.</p>
                </div>

                <div class="aysa-form-group">
                    <label for="support_email">Support Email</label>
                    <input type="email" id="support_email" name="support_email" class="aysa-input">
                    <p class="aysa-text-muted">Enter the main email address where customers or users can reach out for support. Make sure it's valid, as it will be used in communications and structured data.</p>
                </div>
            </div>

            <!-- Website Information -->
            <div class="aysa-card">
                <div class="aysa-card-header">
                    <span class="dashicons dashicons-admin-site"></span>
                    <h3>Website Information</h3>
                </div>

                <div class="aysa-form-group">
                    <label for="website">Website<span class="aysa-required">*</span></label>
                    <input type="url" id="website" name="website" class="aysa-input" placeholder="https://example.com" required>
                    <p class="aysa-text-muted">Enter the full URL of your website. This is the site we will help optimize with SEO strategies and recommendations.</p>
                </div>

                <div class="aysa-form-group">
                    <label for="website-type">Website type<span class="aysa-required">*</span></label>
                    <select id="website-type" name="website_type" class="aysa-select" required>
                        <option value="">...Select an Industry</option>
                        <option value="blog">Blog</option>
                        <option value="ecommerce">E-commerce</option>
                        <option value="corporate">Corporate</option>
                        <option value="portfolio">Portfolio</option>
                        <option value="news">News</option>
                        <option value="education">Education</option>
                        <option value="nonprofit">Non-profit</option>
                        <option value="other">Other</option>
                    </select>
                    <p class="aysa-text-muted">Select the type of website you manage. This will help us tailor the SEO recommendations based on your site's structure and content.</p>
                </div>
                
                <div id="other-website-type-container" class="aysa-form-group" style="display: none;">
                    <label for="other-website-type">Specify Website Type<span class="aysa-required">*</span></label>
                    <input type="text" id="other-website-type" name="other_website_type" class="aysa-input" placeholder="Enter your website type">
                    <p class="aysa-text-muted">Please specify your website type since you selected "Other".</p>
                </div>
            </div>

            <!-- Business Details -->
            <div class="aysa-card">
                <div class="aysa-card-header">
                    <span class="dashicons dashicons-store"></span>
                    <h3>Business Details</h3>
                </div>

                <div class="aysa-form-group">
                    <label for="shipping">Shipping<span class="aysa-required">*</span></label>
                    <input type="text" id="shipping" name="shipping" class="aysa-input" placeholder="Ex: Free delivery within Bragadiru area" required>
                    <p class="aysa-text-muted">Enter the available shipping options you provide to your customers. This can improve your visibility in local searches.</p>
                </div>

                <div class="aysa-form-group">
                    <label for="payment-method">Payment Method<span class="aysa-required">*</span></label>
                    <input type="text" id="payment-method" name="payment_method" class="aysa-input" placeholder="Ex: Credit Card, PayPal" required>
                    <p class="aysa-text-muted">Enter the payment methods you accept. This information can enhance user trust and improve conversion rates.</p>
                </div>

                <div class="aysa-form-group">
                    <label for="industry">Industry<span class="aysa-required">*</span></label>
                    <select id="industry" name="industry" class="aysa-select" required>
                        <option value="">...Select an Industry</option>
                        <option value="retail">Retail</option>
                        <option value="florist">Florist</option>
                        <option value="technology">Technology</option>
                        <option value="healthcare">Healthcare</option>
                        <option value="finance">Finance</option>
                        <option value="education">Education</option>
                        <option value="hospitality">Hospitality</option>
                        <option value="manufacturing">Manufacturing</option>
                        <option value="real-estate">Real Estate</option>
                        <option value="other">Other</option>
                    </select>
                    <p class="aysa-text-muted">Choose the industry that best matches your business to help us refine your SEO strategy for your market niche.</p>
                </div>
                
                <div id="other-industry-container" class="aysa-form-group" style="display: none;">
                    <label for="other-industry">Specify Industry<span class="aysa-required">*</span></label>
                    <input type="text" id="other-industry" name="other_industry" class="aysa-input" placeholder="Enter your industry">
                    <p class="aysa-text-muted">Please specify your industry since you selected "Other".</p>
                </div>

                <div class="aysa-form-group">
                    <label for="company-info">Business Information<span class="aysa-required">*</span></label>
                    <textarea id="company-info" name="company_info" class="aysa-textarea" rows="4" required></textarea>
                    <p class="aysa-text-muted">Provide detailed information about your business operations, services, and market position. This helps search engines understand your business context.</p>
                </div>
            </div>
        </div>
    </form>
</div>
<div id="aysa-autofill-overlay" class="aysa-autofill-overlay" style="display:none;">
    <div class="aysa-autofill-overlay-card">
        <span class="dashicons dashicons-update aysa-spinning"></span>
        <h4>Generating company data...</h4>
        <p>Please wait. We are analyzing the website and filling the form automatically.</p>
    </div>
</div>

<style>
/* Enhanced styling with modern design */
.aysa-wizard-section {
    max-width: 100%;
    margin: 24px;
    padding: 0;
    font-family: 'Roboto', sans-serif;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.aysa-wizard-header {
    padding: 24px 32px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-wizard-header h2 {
    font-size: 24px;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 8px;
}

.aysa-text-muted {
    color: #666;
    font-size: 14px;
    line-height: 1.6;
    margin-bottom: 8px;
}

.aysa-info-box {
    background: #f8f9fa;
    border-left: 4px solid #0066ff;
    padding: 16px;
    border-radius: 4px;
    margin: 16px 0 0 0;
}

.aysa-info-box .dashicons {
    font-size: 24px;
    color: #0066ff;
    width: 24px;
    height: 24px;
}

.aysa-info-box p {
    margin: 0;
    font-size: 14px;
    color: #1a1a1a;
    line-height: 1.6;
}

.aysa-form-container {
    padding: 32px;
}

.aysa-card {
    background: transparent;
    border-radius: 0;
    box-shadow: none;
    padding: 0;
    margin-bottom: 32px;
}

.aysa-card:hover {
    transform: none;
    box-shadow: none;
}

.aysa-card-header {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    align-items: center;
}

.aysa-card-header .dashicons {
    font-size: 24px;
    width: 24px;
    height: 24px;
    color: #0066ff;
    margin-right: 8px;
}

.aysa-card-header h3 {
    font-size: 20px;
    font-weight: 600;
    color: #1a1a1a;
    margin: 0;
    flex-grow: 1;
}

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

.aysa-form-group:last-child {
    margin-bottom: 0;
}

.aysa-form-group.full-width {
    max-width: 100%;
}

.aysa-form-group label {
    display: block;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 8px;
}

.aysa-required {
    color: #dc3545;
    margin-left: 4px;
}

.aysa-input,
.aysa-select,
.aysa-textarea {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 14px;
    color: #1a1a1a;
}

.aysa-select {
    background-image: none !important;
    background: white !important;
}

select.aysa-select::-ms-expand {
    display: none !important;
}

.aysa-select option::after,
.aysa-select option::before,
.aysa-select::after,
.aysa-select::before {
    display: none !important;
    content: none !important;
}

/* Pentru a elimina posibile icoane din interiorul select */
.aysa-select .dashicons,
.aysa-select span,
.aysa-select i {
    display: none !important;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .aysa-wizard-section {
        margin: 16px;
    }
    
    .aysa-wizard-header,
    .aysa-form-container {
        padding: 20px;
    }
    
    .aysa-wizard-header h2 {
        font-size: 24px;
    }
    
    .aysa-card-header h3 {
        font-size: 18px;
    }

    .aysa-form-group {
        max-width: 100%;
    }
}

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

.aysa-btn-primary {
    background-color: #0066ff;
    color: #fff;
}

.aysa-btn-primary:hover {
    background-color: #0052cc;
}

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

/* Auto Generate Info loading spinner */
.aysa-loading {
    position: relative;
    pointer-events: none;
}

.aysa-loading:after {
    content: '';
    position: absolute;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(255,255,255,0.3);
    border-radius: 50%;
    border-top-color: #fff;
    animation: aysa-spin 1s ease-in-out infinite;
    left: calc(50% - 8px);
    top: calc(50% - 8px);
}

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

/* Styling for empty fields */
.aysa-field-empty {
    border: 1px solid #dc3545 !important;
    background-color: rgba(220, 53, 69, 0.05) !important;
}

.aysa-field-empty:focus {
    box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25) !important;
}

/* Tooltip for empty fields */
.aysa-field-empty-tooltip {
    position: relative;
}

.aysa-field-empty-tooltip:after {
    content: "No data available - please fill in manually";
    position: absolute;
    background: #dc3545;
    color: white;
    padding: 5px 10px;
    border-radius: 4px;
    font-size: 12px;
    bottom: calc(100% + 5px);
    left: 0;
    white-space: nowrap;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease;
    z-index: 100;
}

.aysa-field-empty-tooltip:before {
    content: "";
    position: absolute;
    border: 5px solid transparent;
    border-top-color: #dc3545;
    top: -10px;
    left: 10px;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease;
    z-index: 100;
}

.aysa-field-empty:focus + .aysa-field-empty-tooltip:after,
.aysa-field-empty:focus + .aysa-field-empty-tooltip:before,
.aysa-field-empty:hover + .aysa-field-empty-tooltip:after,
.aysa-field-empty:hover + .aysa-field-empty-tooltip:before {
    opacity: 1;
    visibility: visible;
}

/* Spinning animation for auto-generation */
.aysa-spinning {
    animation: aysa-spin 2s linear infinite;
}

/* Status indicator styles */
.aysa-status-indicator {
    display: flex;
    align-items: center;
    font-size: 14px;
    font-weight: 500;
    padding: 8px 14px;
    border-radius: 4px;
    background-color: #e9f5ff;
    color: #0066ff;
    min-height: 36px;
}

.aysa-status-indicator .dashicons {
    margin-right: 6px;
}

.aysa-status-error {
    background-color: #ffebee;
    color: #d32f2f;
}

.aysa-status-loading {
    background-color: #e9f5ff;
    color: #0052cc;
}

.aysa-status-success {
    background-color: #e8f5e9;
    color: #2e7d32;
}

.aysa-autofill-overlay {
    position: fixed;
    inset: 0;
    background: rgba(16, 24, 40, 0.45);
    z-index: 99999;
    display: flex;
    align-items: center;
    justify-content: center;
}

.aysa-autofill-overlay-card {
    width: min(92vw, 540px);
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 20px 50px rgba(0, 0, 0, 0.2);
    padding: 24px;
    text-align: center;
}

.aysa-autofill-overlay-card .dashicons {
    width: 34px;
    height: 34px;
    font-size: 34px;
    color: #0052cc;
}

.aysa-autofill-overlay-card h4 {
    margin: 12px 0 8px;
    font-size: 21px;
    color: #0f172a;
}

.aysa-autofill-overlay-card p {
    margin: 0;
    color: #334155;
    font-size: 14px;
}
</style>

<script>
jQuery(document).ready(function($) {
    const DEBUG_AUTOFILL = false;
    const setupNonce = '<?php echo esc_attr(wp_create_nonce('aysa_nonce')); ?>';
    const currentHost = (window.location && window.location.hostname) ? window.location.hostname : '';
    const $statusIndicator = $('#generation-status');
    const $overlay = $('#aysa-autofill-overlay');
    let autofillInProgress = false;
    const safeStringify = (value) => {
        try {
            return JSON.stringify(value, null, 2);
        } catch (e) {
            return String(value);
        }
    };
    const setDebug = (endpoint, payload, response) => {
        if (!DEBUG_AUTOFILL) {
            return;
        }
    };

    const setAutofillLoading = (isLoading, message) => {
        autofillInProgress = !!isLoading;
        if (isLoading) {
            try {
                document.dispatchEvent(new CustomEvent('aysa:general-autofill-started', {
                    detail: {
                        message: message || 'Gathering your website details now. Please wait a moment and then confirm what looks correct.'
                    }
                }));
            } catch (e) {}
            $overlay.show();
            $statusIndicator
                .removeClass('aysa-status-error aysa-status-success')
                .addClass('aysa-status-loading')
                .html('<span class="dashicons dashicons-update aysa-spinning"></span> ' + (message || 'Generating info...'));
            $('#aysa-next-step').prop('disabled', true);
            return;
        }
        $overlay.hide();
        $('#aysa-next-step').prop('disabled', false);
    };
    const getAccessKey = () => {
        try {
            return (window.AYSA_ACCESS_KEY || localStorage.getItem('aysa_access_key') || sessionStorage.getItem('aysa_access_key') || '').trim();
        } catch (e) {
            return '';
        }
    };

    function getTargetWebsiteUrl() {
        const fieldValue = ($('#website').val() || '').trim();
        if (fieldValue) {
            return fieldValue;
        }
        return '<?php echo esc_js(home_url('/')); ?>';
    }

    function callGeneralAutofill(projectId, forceGenerate) {
        const payload = {
            action: 'aysa_setup_general_autofill',
            nonce: setupNonce,
            project_id: projectId || 0,
            website: getTargetWebsiteUrl(),
            force_generate: forceGenerate ? '1' : '0',
            access_key: getAccessKey(),
            site_host: currentHost
        };
        const endpoint = ajaxurl + '?action=aysa_setup_general_autofill';
        setAutofillLoading(true, forceGenerate ? 'Generating info...' : 'Loading saved info...');
        setDebug(endpoint, payload, 'Pending...');

        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: payload
        }).done(function(resp) {
            setDebug(undefined, undefined, resp);
        }).fail(function(xhr, status, error) {
            setDebug(undefined, undefined, {
                status: status,
                error: error,
                http_status: xhr && xhr.status ? xhr.status : 0,
                response_text: xhr && xhr.responseText ? xhr.responseText : ''
            });
        }).always(function() {
            setAutofillLoading(false);
        });
    }

    // Get project ID from API
    function getProjectId() {
        // First try to get from localStorage
        let projectId = localStorage.getItem('aysa_project_id');
        if (projectId) {
            return projectId;
        }

        // Fallback to project ID stored in WP options (server-side configuration)
        const phpProjectId = '<?php echo intval(get_option('aysa_project_id', 0)); ?>';
        if (phpProjectId && Number(phpProjectId) > 0) {
            localStorage.setItem('aysa_project_id', phpProjectId);
            return phpProjectId;
        }

        return null;
    }

    const projectId = getProjectId() || 0;

    // Store project ID in a hidden input
    $('#aysa-general-form').append(`
        <input type="hidden" name="project_id" value="${projectId}">
    `);

    // Auto-generate company information on page load
    // Load autofilled information from server-side extractor endpoint.
    callGeneralAutofill(projectId, false)
            .done(function(response) {
                if (!response || !response.success || !response.data) {
                    $statusIndicator.html('<span class="dashicons dashicons-warning"></span> Generation Failed').addClass('aysa-status-error');
                    return;
                }
                const data = response.data;
                const source = (data && data.source) ? String(data.source) : 'unknown';
                // If data exists and has actual values (not placeholder values)
                if (data && (data.companyName || data.supportPhoneNumber || data.companyDescription || data.businessInformation)) {
                    console.log('Found generated data:', data);
                if (source.indexOf('api_setup_general_autofill') === 0) {
                    $statusIndicator
                        .removeClass('aysa-status-error aysa-status-loading')
                        .addClass('aysa-status-success')
                        .html('<span class="dashicons dashicons-yes-alt"></span> AI Autofill Loaded');
                } else if (source === 'setup_general_autofill_saved_wizard') {
                    $statusIndicator
                        .removeClass('aysa-status-error aysa-status-loading')
                        .addClass('aysa-status-success')
                        .html('<span class="dashicons dashicons-database-view"></span> Loaded from database');
                } else if (source === 'setup_general_autofill_local_fallback') {
                    $statusIndicator.html('<span class="dashicons dashicons-warning"></span> Local fallback loaded').addClass('aysa-status-error');
                } else {
                    $statusIndicator.html('<span class="dashicons dashicons-database-view"></span> Data Loaded').removeClass('aysa-spinning');
                }
                    
                    // Fill the form with the retrieved data
                    populateFormWithData(data);
                    notifyConversationAutofillReady(data, source);
                    
                } else {
                // No custom data found, update status text to show we're generating
                $statusIndicator.html('<span class="dashicons dashicons-update aysa-spinning"></span> Generating new data...');
                    
                    // Generate new data
                generateCompanyInfo(projectId, $statusIndicator);
                }
            })
            .fail(function(xhr, status, error) {
                // Error getting data, try to generate new data
                console.error('Error checking for existing data:', error);
            $statusIndicator.html('<span class="dashicons dashicons-update aysa-spinning"></span> Generating new data...');
                
                // Generate new data
            generateCompanyInfo(projectId, $statusIndicator);
            });
    
    // Function to generate company information
    function generateCompanyInfo(projectId, $statusIndicator) {
        // Call server-side autofill endpoint (crawl + extract)
        callGeneralAutofill(projectId, true)
            .done(function(response) {
                if (!response || !response.success || !response.data) {
                    throw new Error('Invalid autofill response');
                }
                const data = response.data;
                const source = (data && data.source) ? String(data.source) : 'unknown';
                // Populate form with the generated data
                populateFormWithData(data);
                notifyConversationAutofillReady(data, source);
                
                // Reset status state with success message
                if (source.indexOf('api_setup_general_autofill') === 0) {
                    $statusIndicator
                        .removeClass('aysa-status-error aysa-status-loading')
                        .addClass('aysa-status-success')
                        .html('<span class="dashicons dashicons-yes"></span> AI Info Generated');
                } else {
                    $statusIndicator.html('<span class="dashicons dashicons-warning"></span> Generated (local fallback)');
                }
            })
            .fail(function(xhr, status, error) {
                console.error('Error generating company information:', error);
                
                // Reset status state with error message
                $statusIndicator.html('<span class="dashicons dashicons-warning"></span> Generation Failed');
                
                // Show error message
                alert('Failed to generate company information. Please refresh the page or enter details manually.');
            });
    }

    function notifyConversationAutofillReady(data, source) {
        if (typeof window.aysaSetupConversationRefresh === 'function') {
            window.aysaSetupConversationRefresh('general_autofill_ready');
        }
        try {
            document.dispatchEvent(new CustomEvent('aysa:general-autofill-ready', {
                detail: {
                    data: data || {},
                    source: source || ''
                }
            }));
        } catch (e) {}
    }
    
    // Funcție pentru verificarea și corectarea valorilor "Other" pre-completate
    function checkAndCorrectOtherValues() {
        // Verificarea pentru Website Type
        if ($('#website-type').val() === 'other' && $('#other-website-type').val()) {
            const otherWebsiteType = $('#other-website-type').val().trim().toLowerCase();
            
            // Verificăm dacă există în dropdown
            let websiteTypeFound = false;
            $('#website-type option').each(function() {
                const optionValue = $(this).val().toLowerCase();
                const optionText = $(this).text().toLowerCase();
                
                if (otherWebsiteType === optionValue || otherWebsiteType === optionText) {
                    // Selectăm direct această opțiune în loc de "Other"
                    $('#website-type').val(optionValue);
                    $('#other-website-type').val('');
                    $('#other-website-type-container').hide();
                    websiteTypeFound = true;
                    return false;
                }
            });
        }
        
        // Verificarea pentru Industry
        if ($('#industry').val() === 'other' && $('#other-industry').val()) {
            const otherIndustry = $('#other-industry').val().trim().toLowerCase();
            
            // Verificăm dacă există în dropdown
            let industryFound = false;
            $('#industry option').each(function() {
                const optionValue = $(this).val().toLowerCase();
                const optionText = $(this).text().toLowerCase();
                
                if (otherIndustry === optionValue || otherIndustry === optionText) {
                    // Selectăm direct această opțiune în loc de "Other"
                    $('#industry').val(optionValue);
                    $('#other-industry').val('');
                    $('#other-industry-container').hide();
                    industryFound = true;
                    return false;
                }
            });
        }
    }
    
    // Function to populate form with data
    function pickAutofillValue() {
        for (let i = 0; i < arguments.length; i++) {
            const candidate = arguments[i];
            if (Array.isArray(candidate)) {
                const normalizedArray = candidate
                    .map(item => String(item || '').trim())
                    .filter(item => item !== '');
                if (normalizedArray.length > 0) {
                    return normalizedArray.join(', ');
                }
                continue;
            }

            if (candidate && typeof candidate === 'object') {
                continue;
            }

            const normalized = String(candidate || '').trim();
            if (normalized !== '') {
                return normalized;
            }
        }

        return '';
    }

    function normalizeAutofillData(response) {
        const root = response && typeof response === 'object' ? response : {};
        const sections = root.sections && typeof root.sections === 'object' ? root.sections : {};
        const websiteInfo = sections.website_information && typeof sections.website_information === 'object'
            ? sections.website_information
            : {};
        const companyInfo = sections.company_information && typeof sections.company_information === 'object'
            ? sections.company_information
            : {};
        const businessDetails = sections.business_details && typeof sections.business_details === 'object'
            ? sections.business_details
            : {};

        return {
            companyName: pickAutofillValue(root.companyName, companyInfo.company_name, companyInfo.name),
            brand: pickAutofillValue(root.brand, companyInfo.brand, companyInfo.brand_name),
            companyDescription: pickAutofillValue(root.companyDescription, companyInfo.company_description, companyInfo.description),
            supportPhoneNumber: pickAutofillValue(root.supportPhoneNumber, companyInfo.support_phone, companyInfo.phone),
            supportEmailAddress: pickAutofillValue(root.supportEmailAddress, companyInfo.support_email, companyInfo.email),
            websiteUrl: pickAutofillValue(root.websiteUrl, websiteInfo.website, websiteInfo.url),
            websiteType: pickAutofillValue(root.websiteType, websiteInfo.website_type, websiteInfo.type),
            shippingOptions: pickAutofillValue(root.shippingOptions, businessDetails.shipping, businessDetails.shipping_options),
            paymentMethods: pickAutofillValue(
                root.paymentMethods,
                root.paymentMethod,
                businessDetails.payment_method,
                businessDetails.payment_methods,
                businessDetails.payments,
                businessDetails.payment
            ),
            industry: pickAutofillValue(root.industry, businessDetails.industry, businessDetails.category),
            businessInformation: pickAutofillValue(root.businessInformation, businessDetails.business_information, businessDetails.description)
        };
    }

    function populateFormWithData(response) {
        const normalized = normalizeAutofillData(response);

        // Remove any existing highlighting
        $('.aysa-input, .aysa-select, .aysa-textarea').removeClass('aysa-field-empty');
        
        // Fill in the form fields with the returned data and highlight empty ones
        setFieldValue('#company_name', normalized.companyName);
        setFieldValue('#brand_name', normalized.brand);
        setFieldValue('#company_description', normalized.companyDescription);
        setFieldValue('#support_phone', normalized.supportPhoneNumber);
        setFieldValue('#support_email', normalized.supportEmailAddress);
        
        // Website info
        setFieldValue('#website', normalized.websiteUrl);
        setSelectValue('#website-type', normalized.websiteType);
        
        // Business details
        setFieldValue('#shipping', normalized.shippingOptions);
        setFieldValue('#payment-method', normalized.paymentMethods);
        setSelectValue('#industry', normalized.industry);
        
        // Use businessInformation field with fallback to companyDescription or empty string
        setFieldValue('#company-info', 
            normalized.businessInformation || 
            normalized.companyDescription || 
            '');
        
        // Apelăm verificarea după ce toate datele au fost populate
        setTimeout(checkAndCorrectOtherValues, 500);
    }
    
    // Helper functions to set field values and highlight empty ones
    function setFieldValue(selector, value) {
        const $field = $(selector);
        if (!value || value.trim() === '') {
            $field.val('').addClass('aysa-field-empty');
        } else {
            $field.val(value).removeClass('aysa-field-empty');
        }
    }
    
    function setSelectValue(selector, value) {
        const $select = $(selector);
        if (!value || value.trim() === '') {
            $select.val('').addClass('aysa-field-empty');
        } else {
            let incomingValue = value.trim().toLowerCase();
            if (selector === '#website-type') {
                if (incomingValue === 'business' || incomingValue === 'company') {
                    incomingValue = 'corporate';
                }
                if (incomingValue === 'e-commerce') {
                    incomingValue = 'ecommerce';
                }
            }
            if (selector === '#industry') {
                if (incomingValue === 'flowers') {
                    incomingValue = 'florist';
                }
            }

            // Normalizez valorile pentru potrivire tolerantă
            let found = false;
            $select.find('option').each(function() {
                const optVal = $(this).val().toLowerCase().replace(/[^a-z0-9]/g, '');
                const valNorm = incomingValue.replace(/[^a-z0-9]/g, '');
                if (optVal === valNorm) {
                    $select.val($(this).val()).removeClass('aysa-field-empty');
                    found = true;
                    return false;
                }
            });
            if (!found) {
                // fallback: existing logic pentru "other"
                if (incomingValue === 'other' || !$select.find('option[value="' + incomingValue + '"]').length) {
                    $select.val('other').removeClass('aysa-field-empty').trigger('change');
                    // Set the "Other" field value
                    const otherFieldId = selector === '#website-type' ? '#other-website-type' : '#other-industry';
                    $(otherFieldId).val(value).removeClass('aysa-field-empty');
                } else {
                    $select.val('').addClass('aysa-field-empty');
                }
            }
        }
    }
    
    // Toggle fields for "Other" options
    $('#website-type').on('change', function() {
        if ($(this).val() === 'other') {
            $('#other-website-type-container').slideDown();
            $('#other-website-type').prop('required', true);
        } else {
            $('#other-website-type-container').slideUp();
            $('#other-website-type').prop('required', false);
        }
    });
    
    $('#industry').on('change', function() {
        if ($(this).val() === 'other') {
            $('#other-industry-container').slideDown();
            $('#other-industry').prop('required', true);
        } else {
            $('#other-industry-container').slideUp();
            $('#other-industry').prop('required', false);
        }
    });
    
    // Handle form submission to include custom fields
    $('#aysa-general-form').on('submit', function() {
        // If "Other" is selected, use the custom value
        if ($('#website-type').val() === 'other') {
            const customType = $('#other-website-type').val();
            if (customType) {
                // Add a hidden field with the combined value
                $(this).append('<input type="hidden" name="actual_website_type" value="' + customType + '">');
            }
        }
        
        if ($('#industry').val() === 'other') {
            const customIndustry = $('#other-industry').val();
            if (customIndustry) {
                // Add a hidden field with the combined value
                $(this).append('<input type="hidden" name="actual_industry" value="' + customIndustry + '">');
            }
        }
    });
    
    // Character counter for description
    $('#website-description').on('input', function() {
        const count = $(this).val().length;
        $('#description-count').text(count);
        
        // Change color based on ideal length
        if (count > 160) {
            $('#description-count').css('color', '#d93025');
        } else if (count > 140) {
            $('#description-count').css('color', '#e67c22');
        } else {
            $('#description-count').css('color', '#0f9d58');
        }
    }).trigger('input'); // Trigger on load
    
    // Show/hide local business fields based on business type selection
    $('#business-type').on('change', function() {
        if ($(this).val() === 'local') {
            $('#local-business-fields').show().addClass('show');
        } else {
            $('#local-business-fields').removeClass('show');
            setTimeout(function() {
                if (!$('#local-business-fields').hasClass('show')) {
                    $('#local-business-fields').hide();
                }
            }, 300);
        }
    });
    
    // Fancy input transitions
    $('.aysa-input, .aysa-textarea, .aysa-select').on('focus', function() {
        $(this).closest('.aysa-form-group').find('label').css('color', '#1a73e8');
    }).on('blur', function() {
        $(this).closest('.aysa-form-group').find('label').css('color', '');
    });
    
    // Form submission handling
    if (!window.aysaWizardUseGlobalNavigation) {
    $('#aysa-next-step').on('click', function(e) {
        // Prevent the default navigation
        e.preventDefault();
        if (autofillInProgress) {
            alert('Please wait until data generation is finished.');
            return;
        }
        
        // Validate the form
        if ($('#aysa-general-form')[0].checkValidity()) {
            // Show loading state
            $(this).html('<span class="aysa-spinner"></span> Saving...').prop('disabled', true);
            
            // Serialize the form data
            const formData = $('#aysa-general-form').serialize();
            
            // Save the data via AJAX
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: formData + '&action=aysa_save_wizard_data&nonce=' + encodeURIComponent(setupNonce),
                success: function(response) {
                    if (response.success) {
                        // Show success indicator before proceeding
                        $('#aysa-next-step').html('<span class="dashicons dashicons-yes"></span> Saved!');
                        setTimeout(function() {
                            // Proceed to next step
                            window.location.href = '?page=aysa-setup-seo-profile&step=objectives';
                        }, 500);
                    } else {
                        // Show error message and reset button
                        alert(response.data.message || 'An error occurred. Please try again.');
                        $('#aysa-next-step').html('Next <span class="dashicons dashicons-arrow-right-alt"></span>').prop('disabled', false);
                    }
                },
                error: function() {
                    alert('A server error occurred. Please try again.');
                    $('#aysa-next-step').html('Next <span class="dashicons dashicons-arrow-right-alt"></span>').prop('disabled', false);
                }
            });
        } else {
            // Trigger HTML5 validation
            $('#aysa-general-form')[0].reportValidity();
        }
    });
    
    // Handle previous button
    $('#aysa-prev-step').on('click', function(e) {
        e.preventDefault();
        window.location.href = '?page=aysa-setup-seo-profile&step=integrations';
    });
    }
    
    // Add highlight effect to cards on hover
    $('.aysa-card').hover(
        function() {
            $(this).css('border-color', '#1a73e8');
        },
        function() {
            $(this).css('border-color', '#e0e0e0');
        }
    );

    // New logic for other website type
    $('#other-website-type').on('blur', function() {
        const enteredValue = $(this).val().trim().toLowerCase();
        let found = false;
        
        // Verificăm dacă valoarea introdusă există deja în dropdown
        $('#website-type option').each(function() {
            const optionValue = $(this).val().toLowerCase();
            const optionText = $(this).text().toLowerCase();
            
            if (enteredValue === optionValue || enteredValue === optionText) {
                // Am găsit o potrivire! Selectăm această opțiune
                $('#website-type').val(optionValue).trigger('change');
                found = true;
                return false; // Ieșim din bucla .each()
            }
        });
        
        // Dacă am găsit o potrivire, resetăm câmpul "Other" și ascundem containerul
        if (found) {
            $(this).val('');
            $('#other-website-type-container').slideUp();
        }
    });

    // Aceeași funcționalitate pentru câmpul "Other Industry"
    $('#other-industry').on('blur', function() {
        const enteredValue = $(this).val().trim().toLowerCase();
        let found = false;
        
        // Verificăm dacă valoarea introdusă există deja în dropdown
        $('#industry option').each(function() {
            const optionValue = $(this).val().toLowerCase();
            const optionText = $(this).text().toLowerCase();
            
            if (enteredValue === optionValue || enteredValue === optionText) {
                // Am găsit o potrivire! Selectăm această opțiune
                $('#industry').val(optionValue).trigger('change');
                found = true;
                return false; // Ieșim din bucla .each()
            }
        });
        
        // Dacă am găsit o potrivire, resetăm câmpul "Other" și ascundem containerul
        if (found) {
            $(this).val('');
            $('#other-industry-container').slideUp();
        }
    });
});
</script> 
