// Step navigation and form handling functionality

// Function to handle checkbox selection in step 5
function toggleSingleCheckbox(checkbox, fieldName) {
    // Allow multiple selections in step 5
    // Special handling for "Others" checkbox remains the same
    if (fieldName === 'Others') {
        // Don't uncheck "Others" when another checkbox is selected
        return;
    }
}



function getStepIdFromNumber(stepNumber) {
    // Get the step mapping from the server-side data
    const stepMapping = window.stepMapping || {};
    return stepMapping[stepNumber] || stepNumber.toString();
}

// Function to update progress bar dynamically
function updateProgressBar(completedSteps) {
    const progressBar = document.querySelector('.progress_bar');
    if (!progressBar) return;

    const spans = progressBar.querySelectorAll('span');
    spans.forEach((span, index) => {
        const stepNumber = parseInt(span.getAttribute('data-step-number'));
        const isCompleted = completedSteps.includes(stepNumber);

        if (isCompleted) {
            span.classList.add('step_completed');
            span.setAttribute('data-step-completed', 'true');
        } else {
            span.classList.remove('step_completed');
            span.setAttribute('data-step-completed', 'false');
        }
    });
}

// Function to get current step information
function getCurrentStepInfo() {
    const currentStepElement = document.querySelector('.progress_bar span.current_step');
    if (currentStepElement) {
        return {
            stepNumber: parseInt(currentStepElement.getAttribute('data-step-number')),
            stepId: currentStepElement.getAttribute('data-step-id'),
            isCompleted: currentStepElement.getAttribute('data-step-completed') === 'true'
        };
    }
    return null;
}

// Function to get all completed steps
function getCompletedSteps() {
    const completedSpans = document.querySelectorAll('.progress_bar span.step_completed');
    return Array.from(completedSpans).map(span => parseInt(span.getAttribute('data-step-number')));
}

// Function to validate step accessibility
function validateStepAccessibility(targetStepNumber) {
    const currentStepInfo = getCurrentStepInfo();
    if (!currentStepInfo) return true; // Fallback to allow navigation

    const targetStepElement = document.querySelector(`.progress_bar span[data-step-number="${targetStepNumber}"]`);
    if (!targetStepElement) return true; // Fallback to allow navigation

    // Check if step is accessible based on data attribute
    const isStepAccessible = targetStepElement.getAttribute('data-step-accessible') === 'true';

    // Additional OTP validation for steps after OTP
    if (targetStepNumber > 2) { // Steps after OTP (step 2)
        const isOTPValidated = document.querySelector('input[name="OTPValidated"]')?.value === 'true';
        const isAdminSkipped = document.querySelector('input[name="AdminSkippedOTP"]')?.value === 'true';
        const isAdminAction = document.querySelector('input[name="UserEmailID"]')?.value ||
            document.querySelector('input[name="loggedInUserEmail"]')?.value ||
            document.querySelector('input[name="EditingEmail"]')?.value ||
            document.querySelector('input[name="AdminEmail"]')?.value;

        // If not admin and OTP not validated/skipped, show error and redirect to personnel details
        if (!isAdminAction && !isOTPValidated && !isAdminSkipped) {
            if (typeof showFormToast === 'function') {
                showFormToast('OTP Authentication is required to access the further steps. Please complete OTP verification first.', 'warning');
            } else {
                console.warn('OTP Authentication required: Please complete OTP verification first.');
            }
            window.location.href = '/SubdomainForm/Step/stp_personneldetails';
            return false;
        }
    }

    return isStepAccessible;
}

function redirect(url) {
    // This function is kept for backward compatibility but should not be used
    // Use redirectToStep or redirectToPreviousStep instead
    console.warn("redirect() function is deprecated. Use redirectToStep() or redirectToPreviousStep() instead.");
    window.location.href = "/SubdomainForm/Step/" + url;
}

function redirectToStep(stepId) {
    // Navigate to step using StepId
    let url = "/SubdomainForm/Step/" + stepId;

    // Preserve query parameters from current URL
    const currentUrl = new URL(window.location);
    const currentParams = currentUrl.searchParams;

    // Add query parameters to the new URL
    if (currentParams.toString()) {
        url += '?' + currentParams.toString();
    }

    window.location.href = url;
}

// List of steps that are hidden from progress bar (should be skipped during navigation)
const HIDDEN_STEPS = ['stp_aisuggestproductdetails'];

function isStepHidden(stepId) {
    return HIDDEN_STEPS.includes(stepId);
}

function getPreviousVisibleStep(currentStepId, previousStepId) {
    // If the previous step is not hidden, return it
    if (!isStepHidden(previousStepId)) {
        return previousStepId;
    }

    // If previous step is hidden, find the actual previous visible step
    // Get the step mapping (maps step numbers to step IDs)
    const stepMapping = window.stepMapping || {};

    // Find the step number for the current step
    let currentStepNumber = null;
    for (const [stepNum, stepId] of Object.entries(stepMapping)) {
        if (stepId === currentStepId) {
            currentStepNumber = parseInt(stepNum);
            break;
        }
    }

    // If we found the current step number, look for the previous visible step
    if (currentStepNumber !== null && currentStepNumber > 1) {
        // Look backwards from current step to find the first non-hidden step
        for (let stepNum = currentStepNumber - 1; stepNum >= 1; stepNum--) {
            const candidateStepId = stepMapping[stepNum];
            if (candidateStepId && !isStepHidden(candidateStepId)) {
                return candidateStepId;
            }
        }
    }

    // Special case: if current step is stp_solutionwouldexploredetails and previous is hidden
    // Go directly to stp_expectedusercountdetails (step 8)
    if (currentStepId === 'stp_solutionwouldexploredetails' && isStepHidden(previousStepId)) {
        return 'stp_expectedusercountdetails';
    }

    // Fallback: return the original previous step
    return previousStepId;
}

function resolvePreviousStepId() {
    const fromWindow = (window.previousStep || '').trim();
    if (fromWindow) {
        return fromWindow;
    }

    const hiddenPrevious = document.querySelector('input[name="PreviousStep"]');
    if (hiddenPrevious && hiddenPrevious.value) {
        return hiddenPrevious.value.trim();
    }

    return '';
}

function redirectToPreviousStep(event) {
    if (event && typeof event.preventDefault === 'function') {
        event.preventDefault();
    }

    // Use the existing form and submit it with navigation="back"
    const form = document.querySelector('form');

    if (!form) {
        console.error('No form found for back navigation');
        return;
    }

    // Remove any existing navigation input
    const existingNav = form.querySelector('input[name="navigation"]');
    if (existingNav) {
        existingNav.remove();
    }

    // Create a hidden input for navigation="back"
    const navigationInput = document.createElement('input');
    navigationInput.type = 'hidden';
    navigationInput.name = 'navigation';
    navigationInput.value = 'back';
    form.appendChild(navigationInput);

    // Temporarily remove the required attribute from all inputs to bypass validation
    const requiredInputs = form.querySelectorAll('[required]');
    const removedRequired = [];
    requiredInputs.forEach(input => {
        if (input.hasAttribute('required')) {
            removedRequired.push(input);
            input.removeAttribute('required');
        }
    });

    // Store for restoration
    form.dataset.removedRequired = JSON.stringify(removedRequired.map(inp => inp.name || inp.id));

    // Submit the form - this will POST to the controller
    form.submit();
}

function redirectToPage(stepNumber = 1, isConfirmationRequired = false) {
    // Convert step number to StepId
    const stepId = getStepIdFromNumber(stepNumber);

    // Validate step accessibility
    if (!validateStepAccessibility(stepNumber)) {
        const currentStepInfo = getCurrentStepInfo();
        const currentStepNumber = currentStepInfo ? currentStepInfo.stepNumber : 1;
        console.log(`Step ${stepNumber} is not accessible from current step ${currentStepNumber}`);
        return;
    }

    if (isConfirmationRequired) {
        var response = window.confirm("Do you want to reset the data while navigating to the first page?\r\nClick OK to reset and go to the first page.\r\nClick Cancel to go to the first page without resetting the data.")
        if (response == true) {
            // If true then clear server session, then local/sessionStorage, then navigate to first page.
            fetch('/SubdomainForm/ClearSession', { method: 'POST', credentials: 'same-origin' })
                .finally(function () {
                    if (window.sessionStorage) sessionStorage.clear();
                    if (window.localStorage) localStorage.clear();
                    // Optionally clear cookies if needed (uncomment below if required)
                    document.cookie.split(';').forEach(function (c) { document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/'); });
                    window.location.href = "/SubdomainForm/Step/" + stepId;
                });
        } else {
            // Direct Navigate to first page
            window.location.href = "/SubdomainForm/Step/" + stepId;
        }
    } else {
        // Direct Navigate to first page
        window.location.href = "/SubdomainForm/Step/" + stepId;
    }
}

// Function to handle back button on step 2 without validation
function goBack() {
    // Instead of creating a new form, use the existing form but bypass validation
    const form = document.querySelector('form');

    // Create a hidden input for navigation
    const navigationInput = document.createElement('input');
    navigationInput.type = 'hidden';
    navigationInput.name = 'navigation';
    navigationInput.value = 'back';
    form.appendChild(navigationInput);

    // Temporarily remove the required attribute from all inputs
    const requiredInputs = form.querySelectorAll('[required]');
    requiredInputs.forEach(input => {
        input.removeAttribute('required');
    });

    // Submit the form
    form.submit();
}

// Currency switching functionality for all suites
function switchCurrencyAllSuites(currency) {
    // Update active tab
    document.querySelectorAll('.tablist .tab').forEach(tab => {
        tab.classList.remove('active');
        if (tab.getAttribute('data-currency') === currency) {
            tab.classList.add('active');
        }
    });

    // Update currency symbol and price for all suites
    document.querySelectorAll('.currency-symbol').forEach(symbol => {
        symbol.textContent = currency === 'INR' ? '₹' : '$';
    });

    document.querySelectorAll('.price-display').forEach(price => {
        price.textContent = price.getAttribute(`data-${currency.toLowerCase()}`);
    });

    // Update hidden currency field
    document.getElementById('selectedCurrency').value = currency;
}

// Step 8 loader functionality
document.addEventListener('DOMContentLoaded', function () {
    const formContent = document.getElementById("formContent");
    const question = document.getElementById("question");

    if (formContent && formContent.classList) {
        formContent.classList.add("slideIn_animation");
    }

    if (question && question.classList) {
        question.classList.add("slideIn_animation");
    }

    const currentStep = window.currentStepTitle || "";

    if (currentStep === "Our AI suggests the best product for you.") {
        // Show loader and hide form content
        const loaderSection = document.getElementById('loaderSection');
        const formContent = document.getElementById('formContent');

        if (loaderSection && formContent) {
            loaderSection.style.display = 'block';
            formContent.style.display = 'none';

            // After 3 seconds, automatically submit the form to go to next step
            setTimeout(function () {
                const form = document.querySelector('form');
                if (form) {
                    // Create a hidden input for navigation
                    const navigationInput = document.createElement('input');
                    navigationInput.type = 'hidden';
                    navigationInput.name = 'navigation';
                    navigationInput.value = 'next';
                    form.appendChild(navigationInput);

                    // Submit the form
                    form.submit();
                }
            }, 3000); // 3 seconds
        }
    }
});

function updateColorBox(colorInput, index) {
    // Get the color box and color code elements by their IDs
    const colorBox = document.getElementById('colorBox_' + index);
    const colorCode = document.getElementById('colorCode_' + index);

    if (colorBox) {
        // Update the background color of the color box
        colorBox.style.background = colorInput.value;

        // Remove AI_suggested class since user manually changed the color
        colorBox.classList.remove('AI_suggested');

        // Store user selection for color
        storeColorSelection(index, colorInput.value);
    }

    if (colorCode) {
        // Update the color code text
        colorCode.textContent = colorInput.value;
    }
}

// Function to store user's color selection
function storeColorSelection(index, colorValue) {
    const stepId = 'stp_colorforyourplatformdetails';
    const userSelection = {
        stepId: stepId,
        fieldName: 'Color',
        colorIndex: index,
        selectedColor: colorValue,
        timestamp: Date.now(),
        isUserOverride: true
    };

    sessionStorage.setItem('userSelection_' + stepId + '_' + index, JSON.stringify(userSelection));
    console.log('Color selection stored:', userSelection);

    // Check for default colors and log OpenAI extraction failures
    if (stepId === 'stp_colorforyourplatformdetails') {
        // Check for default colors that indicate OpenAI extraction failed
        if (colorValue === '#007bff') {
            console.log('Color extraction failed: {stepId: "stp_colorforyourplatformdetails", fieldName: "PrimaryColor", errorType: "OpenAI_API_Failed", defaultColor: "#007bff", timestamp: ' + Date.now() + '}');
            console.log('ERROR - OpenAI API key not configured, using default colors: #007bff, #6c757d, #28a745');
            console.log('ERROR - OpenAI API failed to fetch colors, using default colors: #007bff, #6c757d, #28a745');
            console.log('ERROR - BrandingService exception occurred, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - No URL provided for color extraction, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - BrandingService not available, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - Exception in GetBranding_OpenAI, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - AI color extraction failed, using default colors: Primary=#007bff, Secondary=#6c757d, Tertiary=#28a745');
        } else if (colorValue === '#6c757d') {
            console.log('Color extraction failed: {stepId: "stp_colorforyourplatformdetails", fieldName: "SecondaryColor", errorType: "OpenAI_API_Failed", defaultColor: "#6c757d", timestamp: ' + Date.now() + '}');
            console.log('ERROR - OpenAI API key not configured, using default colors: #007bff, #6c757d, #28a745');
            console.log('ERROR - OpenAI API failed to fetch colors, using default colors: #007bff, #6c757d, #28a745');
            console.log('ERROR - BrandingService exception occurred, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - No URL provided for color extraction, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - BrandingService not available, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - Exception in GetBranding_OpenAI, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - AI color extraction failed, using default colors: Primary=#007bff, Secondary=#6c757d, Tertiary=#28a745');
        } else if (colorValue === '#28a745') {
            console.log('Color extraction failed: {stepId: "stp_colorforyourplatformdetails", fieldName: "TertiaryColor", errorType: "OpenAI_API_Failed", defaultColor: "#28a745", timestamp: ' + Date.now() + '}');
            console.log('ERROR - OpenAI API key not configured, using default colors: #007bff, #6c757d, #28a745');
            console.log('ERROR - OpenAI API failed to fetch colors, using default colors: #007bff, #6c757d, #28a745');
            console.log('ERROR - BrandingService exception occurred, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - No URL provided for color extraction, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - BrandingService not available, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - Exception in GetBranding_OpenAI, using default colors: Primary=#007bff, Secondary=#6c757d');
            console.log('ERROR - AI color extraction failed, using default colors: Primary=#007bff, Secondary=#6c757d, Tertiary=#28a745');
        }
    }
}

// Function to initialize color boxes when page loads
function initializeColorBoxes() {
    // Find all color input fields
    const colorInputs = document.querySelectorAll('input[type="color"]');
    colorInputs.forEach(function (input) {
        // Extract the index from the input ID (e.g., "colorInput_0" -> 0)
        const match = input.id.match(/colorInput_(\d+)/);
        if (match) {
            const index = parseInt(match[1]);
            // Update the color box to match the input value
            updateColorBox(input, index);
        }
    });
}

function sanitizeExpectedUserValueForSlider(value) {
    const min = 0;
    const max = 100000;
    const numericValue = parseInt(value, 10);
    if (isNaN(numericValue)) {
        return min;
    }
    return Math.max(min, Math.min(max, numericValue));
}

function updateRangeValue(index, value) {
    // Update the display element with the current slider value
    const rangeValueDisplay = document.getElementById('rangeValue_' + index);
    if (rangeValueDisplay) {
        // Format the number with commas for readability if needed
        const formattedValue = sanitizeExpectedUserValueForSlider(value).toLocaleString();
        rangeValueDisplay.textContent = formattedValue;
    }
}

function updateRangeValueToPreset(index, value) {
    // Update the slider to the closest preset value
    const slider = document.getElementById('slider_' + index);
    const sanitizedValue = sanitizeExpectedUserValueForSlider(value);
    if (slider) {
        slider.value = sanitizedValue;
    }
    // Update the display
    const rangeValueDisplay = document.getElementById('rangeValue_' + index);
    if (rangeValueDisplay) {
        rangeValueDisplay.value = sanitizedValue;

        // Remove mandatory field class if value is set
        if (typeof removeMandatoryFieldClass === 'function' && sanitizedValue && sanitizedValue > 0) {
            removeMandatoryFieldClass(rangeValueDisplay);
        }
    }
}

onPasteupdateRangeValueToPreset = function (event) {
    let value = event.clipboardData.getData('text/plain');
    const sanitizedValue = sanitizeExpectedUserValueForSlider(value);
    if (sanitizedValue < 0) {
        event.preventDefault();
    }
};

function showLoader() {
    const loaderSection = document.getElementById('loaderSection');
    const formContent = document.getElementById('formContent');

    if (loaderSection && formContent) {
        loaderSection.style.display = 'block';
        formContent.style.display = 'none';
    }
}

// Initialize all range sliders
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('input[type="range"]').forEach(slider => {
        const id = slider.id;
        if (id && id.startsWith('slider_')) {
            const index = id.split('_')[1];
            // Set initial value if needed
            if (!slider.value) {
                slider.value = 1000;
            }
            slider.value = sanitizeExpectedUserValueForSlider(slider.value);

            // Snap to closest preset value on initialization
            updateRangeValueToPreset(index, slider.value);

            // Add an extra change event handler for edge cases
            slider.addEventListener('change', function () {
                updateRangeValueToPreset(index, this.value);
            });

            // Add input event handler for real-time updates
            slider.addEventListener('input', function () {
                updateRangeValueToPreset(index, this.value);
            });
        }
    });

    // Initialize range value inputs
    document.querySelectorAll('input[id^="rangeValue_"]').forEach(input => {
        const id = input.id;
        if (id && id.startsWith('rangeValue_')) {
            const index = id.split('_')[1];

            // Add event listeners for manual input
            input.addEventListener('input', function () {
                if (typeof removeMandatoryFieldClass === 'function' && this.value && parseInt(this.value) > 0) {
                    removeMandatoryFieldClass(this);
                }
            });

            input.addEventListener('change', function () {
                const sanitizedValue = sanitizeExpectedUserValueForSlider(this.value);
                this.value = sanitizedValue;
                if (typeof removeMandatoryFieldClass === 'function' && sanitizedValue && sanitizedValue > 0) {
                    removeMandatoryFieldClass(this);
                }
                updateRangeValueToPreset(index, sanitizedValue);
            });
        }
    });
});

// Function to show image generation loader
function showImageGenerationLoader() {
    // Create loader overlay
    const loaderOverlay = document.createElement('div');
    loaderOverlay.id = 'imageGenerationLoader';
    loaderOverlay.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        z-index: 9999;
        color: white;
        font-family: Arial, sans-serif;
    `;

    loaderOverlay.innerHTML = `
        <div style="text-align: center;">
            <div style="width: 60px; height: 60px; border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto 20px;"></div>
            <h2 style="margin: 0 0 10px 0; font-size: 24px;">Generating AI Content...</h2>
            <p style="margin: 0; font-size: 16px; opacity: 0.8;">Creating personalized recommendations and images for your platform</p>
            <div style="margin-top: 20px; font-size: 14px; opacity: 0.6;">
                <div>• Analyzing your requirements</div>
                <div>• Generating course recommendations</div>
                <div>• Creating custom thumbnails</div>
                <div>• Preparing your platform</div>
            </div>
        </div>
        <style>
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        </style>
    `;

    document.body.appendChild(loaderOverlay);
}

// Function to hide image generation loader
function hideImageGenerationLoader() {
    const loader = document.getElementById('imageGenerationLoader');
    if (loader) {
        loader.remove();
    }
}

// Function to generate images and redirect
async function generateImagesAndRedirect() {
    try {
        console.log('[ImageGeneration] Starting image generation process...');

        // Get current URL parameters to pass to API
        const urlParams = new URLSearchParams(window.location.search);
        const apiUrl = '/SubdomainForm/GenerateImagesAndStoreData' + (urlParams.toString() ? '?' + urlParams.toString() : '');

        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        });

        const result = await response.json();

        if (result.success) {
            console.log('[ImageGeneration] Images generated successfully:', result.data);

            // Store content recommendations in sessionStorage
            if (result.contentRecommendations) {
                sessionStorage.setItem('ContentRecommendations', JSON.stringify(result.contentRecommendations));
                console.log('[ImageGeneration] Content recommendations stored in sessionStorage');
            }

            // Hide loader
            hideImageGenerationLoader();

            // Redirect to Complete page with sessionId and email so live (load-balanced) server shows correct steps and timing
            var q = [];
            var sid = typeof sessionStorage !== 'undefined' && (sessionStorage.getItem('sessionId') || sessionStorage.getItem('ssoSessionId'));
            if (sid) q.push('sessionId=' + encodeURIComponent(sid));
            var em = typeof sessionStorage !== 'undefined' && (sessionStorage.getItem('userEmail') || sessionStorage.getItem('ssoUserEmail'));
            if (em) q.push('email=' + encodeURIComponent(em));
            window.location.href = '/SubdomainForm/Complete' + (q.length ? '?' + q.join('&') : '');
        } else {
            console.error('[ImageGeneration] Failed to generate images:', result.message);

            // Hide loader and show error
            hideImageGenerationLoader();
            alert('Failed to generate content. Please try again.');
        }
    } catch (error) {
        console.error('[ImageGeneration] Error during image generation:', error);

        // Hide loader and show error
        hideImageGenerationLoader();
        alert('An error occurred while generating content. Please try again.');
    }
}

// Function to generate content recommendations and images, then store data
async function generateContentAndStoreData() {
    try {
        console.log('[GenerateContent] Starting content generation and data storage...');

        // First, call GenerateImagesAndStoreData API to get content recommendations and generate images
        // Get current URL parameters to pass to API
        const urlParams = new URLSearchParams(window.location.search);
        const apiUrl = '/SubdomainForm/GenerateImagesAndStoreData' + (urlParams.toString() ? '?' + urlParams.toString() : '');

        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();

        if (result.success) {
            console.log('[GenerateContent] Content recommendations generated successfully:', result.data);

            // Store content recommendations in sessionStorage
            if (result.contentRecommendations) {
                sessionStorage.setItem('ContentRecommendations', JSON.stringify(result.contentRecommendations));
                console.log('[GenerateContent] Content recommendations stored in sessionStorage');

                // Now call SaveStepDetails API to store the data
                await callSaveStepDetailsAPI();
            } else {
                console.error('[GenerateContent] No content recommendations in response');
                hideImageGenerationLoader();
                alert('No content recommendations generated. Please try again.');
            }
        } else {
            console.error('[GenerateContent] Failed to generate content:', result.message);
            hideImageGenerationLoader();
            alert('Failed to generate content. Please try again.');
        }

    } catch (error) {
        console.error('[GenerateContent] Error:', error);
        hideImageGenerationLoader();
        alert('An error occurred while generating content. Please try again.');
    }
}

// Function to call SaveStepDetails API with content data
async function callSaveStepDetailsAPI() {
    try {
        console.log('[SaveStepDetails] Starting API call to store content data...');

        // Get content recommendations from session storage
        const contentRecommendations = sessionStorage.getItem('ContentRecommendations');
        if (!contentRecommendations) {
            console.error('[SaveStepDetails] No content recommendations found in sessionStorage');
            hideImageGenerationLoader();
            alert('No content recommendations found. Please try again.');
            return;
        }

        const contentData = JSON.parse(contentRecommendations);
        console.log('[SaveStepDetails] Content data:', contentData);

        // Create form data with content recommendations
        const formData = new FormData();

        // Add content data for each category
        let fieldIndex = 0;
        Object.keys(contentData).forEach(category => {
            console.log(`[SaveStepDetails] Processing category: ${category}`);
            const items = contentData[category];
            console.log(`[SaveStepDetails] Items for ${category}:`, items);
            if (Array.isArray(items) && items.length > 0) {
                items.forEach((item, itemIndex) => {
                    const parts = item.split(' ~ ');

                    // Handle different field structures based on content type
                    let fieldNames = [];
                    let fieldValues = [];

                    if (category === 'Library' && parts.length >= 5) {
                        // Library: TopicName ~ LibraryName ~ LibraryCategory ~ LibraryThumbnailUrl ~ LibraryDescription
                        fieldNames = ['TopicName', 'LibraryName', 'LibraryCategory', 'LibraryThumbnailUrl', 'LibraryDescription'];
                        fieldValues = [
                            parts[0] || '', // TopicName
                            parts[1] || '', // LibraryName
                            parts[2] || '', // LibraryCategory
                            parts[3] || '', // LibraryThumbnailUrl (remove @ prefix)
                            parts[4] || ''  // LibraryDescription
                        ];
                    } else if (category === 'Course' && parts.length >= 5) {
                        // Course: TopicName ~ CourseName ~ CourseCategory ~ CourseThumbnailUrl ~ CourseDescription
                        fieldNames = ['TopicName', 'CourseName', 'CourseCategory', 'CourseThumbnailUrl', 'CourseDescription'];
                        fieldValues = [
                            parts[0] || '', // TopicName
                            parts[1] || '', // CourseName
                            parts[2] || '', // CourseCategory
                            parts[3] || '', // CourseThumbnailUrl (remove @ prefix)
                            parts[4] || ''  // CourseDescription
                        ];
                    } else if (category === 'Assessment' && parts.length >= 5) {
                        // Assessment: TopicName ~ AssessmentName ~ AssessmentCategory ~ AssessmentThumbnailUrl ~ AssessmentDescription
                        fieldNames = ['TopicName', 'AssessmentName', 'AssessmentCategory', 'AssessmentThumbnailUrl', 'AssessmentDescription'];
                        fieldValues = [
                            parts[0] || '', // TopicName
                            parts[1] || '', // AssessmentName
                            parts[2] || '', // AssessmentCategory
                            parts[3] || '', // AssessmentThumbnailUrl (remove @ prefix)
                            parts[4] || ''  // AssessmentDescription
                        ];
                    } else if (category === 'LP' && parts.length >= 5) {
                        // LP: TopicName ~ LearningpathName ~ LearningpathCategory ~ LearningpathThumbnailUrl ~ LearningpathDescription
                        fieldNames = ['TopicName', 'LearningpathName', 'LearningpathCategory', 'LearningpathThumbnailUrl', 'LearningpathDescription'];
                        fieldValues = [
                            parts[0] || '', // TopicName
                            parts[1] || '', // LearningpathName
                            parts[2] || '', // LearningpathCategory
                            parts[3] || '', // LearningpathThumbnailUrl (remove @ prefix)
                            parts[4] || ''  // LearningpathDescription
                        ];
                    } else if (category === 'ClassroomTraining' && parts.length >= 4) {
                        // ClassroomTraining: ClassroomtrainingBatchname ~ TrainingCategory ~ TrainingName ~ TrainingAgenda
                        fieldNames = ['ClassroomtrainingBatchname', 'TrainingCategory', 'TrainingName', 'TrainingAgenda'];
                        fieldValues = [
                            parts[0] || '', // ClassroomtrainingBatchname
                            parts[1] || '', // TrainingCategory
                            parts[2] || '', // TrainingName
                            parts[3] || ''  // TrainingAgenda
                        ];
                    } else {
                        // Fallback for old format
                        fieldNames = ['Topic', 'Name', 'Description', 'ThumbnailUrl'];
                        fieldValues = [
                            parts[0] || '', // Topic
                            parts[1] || '', // Name
                            parts[2] || '', // Description
                            parts[3] || ''  // ThumbnailUrl (remove @ prefix)
                        ];
                    }

                    // Create separate database entries for each field
                    // Include response number (1 or 2) in the label for sequential saving
                    const responseNumber = itemIndex + 1;
                    fieldNames.forEach((fieldName, fieldNameIndex) => {
                        if (fieldValues[fieldNameIndex]) {
                            console.log(`[SaveStepDetails] Adding field: ${category} Response ${responseNumber} - ${fieldName} = ${fieldValues[fieldNameIndex]}`);
                            // Backend expects: field.Name = LabelName, field.ValueList = LabelValues
                            // We'll create unique labels by combining category, response number, and field name
                            const uniqueLabel = `${category}_Response${responseNumber}_${fieldName}`;
                            formData.append(`Fields[${fieldIndex}].Name`, uniqueLabel);
                            formData.append(`Fields[${fieldIndex}].ValueList`, fieldValues[fieldNameIndex]);
                            fieldIndex++;
                        }
                    });
                });
            }
        });

        // Add other required form fields
        formData.append('stepId', 'stp_productplandetails');

        // Get trial selection data
        const trialSelection = sessionStorage.getItem('trialSelection');
        if (trialSelection) {
            const trialData = JSON.parse(trialSelection);
            formData.append('PricingSuite', trialData.suiteName || '');
            formData.append('purchaseType', trialData.purchaseType || '');
        }

        // Call Step API (the correct endpoint)
        const response = await fetch('/SubdomainForm/Step', {
            method: 'POST',
            body: formData
        });

        if (response.ok) {
            console.log('[SaveStepDetails] Content data stored successfully');
            hideImageGenerationLoader();
            var q = [];
            var sid = typeof sessionStorage !== 'undefined' && (sessionStorage.getItem('sessionId') || sessionStorage.getItem('ssoSessionId'));
            if (sid) q.push('sessionId=' + encodeURIComponent(sid));
            var em = typeof sessionStorage !== 'undefined' && (sessionStorage.getItem('userEmail') || sessionStorage.getItem('ssoUserEmail'));
            if (em) q.push('email=' + encodeURIComponent(em));
            window.location.href = '/SubdomainForm/Complete' + (q.length ? '?' + q.join('&') : '');
        } else {
            console.error('[SaveStepDetails] Failed to store content data');
            hideImageGenerationLoader();
            alert('Failed to store content data. Please try again.');
        }

    } catch (error) {
        console.error('[SaveStepDetails] Error:', error);
        hideImageGenerationLoader();
        alert('An error occurred while storing content data. Please try again.');
    }
}

// Function to add content recommendation data to form
function addTrialDataToForm(form) {
    // Get content recommendations from session storage
    const contentRecommendations = sessionStorage.getItem('ContentRecommendations');
    if (contentRecommendations) {
        try {
            const contentData = JSON.parse(contentRecommendations);

            // Remove existing content data fields if they exist
            const existingFields = form.querySelectorAll('input[name^="LabelName"], input[name^="LabelValues"]');
            existingFields.forEach(field => field.remove());

            // Add content data for each category
            Object.keys(contentData).forEach(category => {
                const items = contentData[category];
                if (Array.isArray(items) && items.length > 0) {
                    items.forEach((item, index) => {
                        const parts = item.split(' ~ ');

                        // Create LabelName field
                        const labelNameField = document.createElement('input');
                        labelNameField.type = 'hidden';
                        labelNameField.name = `LabelName_${category}_${index + 1}`;
                        labelNameField.value = category;
                        form.appendChild(labelNameField);

                        // Create LabelValues field with all the data
                        const labelValues = [];

                        // Add topic
                        if (parts.length > 0) {
                            labelValues.push(`Topic: ${parts[0] || ''}`);
                        }

                        // Topic thumbnail URL removed - no longer needed

                        // Add category name (for Course, LP, Assessment, ClassroomTraining)
                        if (parts.length > 2 && (category === 'Course' || category === 'LP' || category === 'Assessment' || category === 'ClassroomTraining')) {
                            labelValues.push(`Category: ${parts[2] || ''}`);
                        }

                        // Add name
                        const nameIndex = (category === 'Library') ? 2 : 3;
                        if (parts.length > nameIndex) {
                            labelValues.push(`Name: ${parts[nameIndex] || ''}`);
                        }

                        // Add description
                        const descriptionIndex = (category === 'Library') ? 3 : 4;
                        if (parts.length > descriptionIndex) {
                            labelValues.push(`Description: ${parts[descriptionIndex] || ''}`);
                        }

                        // Add thumbnail URL
                        const thumbnailIndex = (category === 'Library') ? 4 : 5;
                        if (parts.length > thumbnailIndex) {
                            labelValues.push(`ThumbnailUrl: ${parts[thumbnailIndex] || ''}`);
                        }

                        // Create LabelValues field
                        const labelValuesField = document.createElement('input');
                        labelValuesField.type = 'hidden';
                        labelValuesField.name = `LabelValues_${category}_${index + 1}`;
                        labelValuesField.value = labelValues.join(' | ');
                        form.appendChild(labelValuesField);
                    });
                }
            });

            console.log('Added content recommendation data to form with LabelName/LabelValues format:', contentData);
        } catch (error) {
            console.error('Error parsing content recommendation data:', error);
        }
    }
}
