/**
 * Form Handler for ClearPost Simple AI Auto Post
 * 
 * This file handles the form submission for generating posts with AI.
 * It manages the AJAX request, form validation, and response handling.
 */
jQuery(document).ready(function($) {
    // Cache DOM elements
    const $form = $('#saiap-generate-form');
    const $submit = $('#saiap-generate-button');
    const $prompt = $('#saiap-prompt');
    const $typeSelect = $('#saiap-type-key');
    
    // Timer variables
    let generationTimer = null;
    let secondsElapsed = 0;
    let originalButtonText = '';
    const MAX_TIMER_SECONDS = 300; // 5 minutes max
	let inlineImagesNoticeId = null;
	let inlineImagesPollTimer = null;
	let inlineImagesPollAttempts = 0;
	let inlineImagesPollingActive = false;
	const INLINE_IMAGES_POLL_INTERVAL_MS = 5000;
	const INLINE_IMAGES_MAX_POLLS = 24;
    
    // Update post type changes
    $('#saiap-post-type').on('change', function() {
        $.ajax({
            url: saiapAdmin.ajaxurl,
            type: 'POST',
            data: {
                'action': 'saiap_get_custom_fields',
                'post_type': $(this).val(),
                'nonce': saiapAdmin.customFieldsNonce 
            },
            success: function(response) {
                if (response.success) {
                    $('#saiap_link_field_name').html(response.data);
                } else {
                    $('#saiap_link_field_name').html('');
                }
            },
            error: function() {
                $('#saiap_link_field_name').html('');
            }
        });
    });

    // Provider change handler
    $('#saiap-provider').on('change', function() {
        const provider = $(this).val();
        $('.openai-settings, .anthropic-settings, .gemini-settings').hide();
        $(`.${provider}-settings`).show();
    });

    // Save defaults button handler
    $('#saiap-save-defaults').on('click', function() {
        const $btn = $(this);
        const originalText = $btn.text();
        $btn.prop('disabled', true).text('Saving...');

        $.post(saiapAdmin.ajaxurl, {
            action: 'saiap_save_defaults',
            nonce: saiapAdmin.formNonce,
            post_type: $('#saiap-post-type').val(),
            post_author: $('#saiap-post-author').val(),
            link_field_name: $('#saiap_link_field_name').val()
        }).done(function(response) {
            if (response.success) {
                $btn.text('Saved!');
                setTimeout(function() {
                    $btn.text(originalText);
                }, 2000);
            } else {
                $btn.text('Error');
                setTimeout(function() {
                    $btn.text(originalText);
                }, 2000);
            }
        }).fail(function() {
            $btn.text('Error');
            setTimeout(function() {
                $btn.text(originalText);
            }, 2000);
        }).always(function() {
            $btn.prop('disabled', false);
        });
    });

    // Populate Post Type Example selector (if present)
    if ($typeSelect.length) {
        // Keep existing default option
        $.ajax({
            url: saiapAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'saiap_post_types_list',
                nonce: saiapAdmin.contextNonce
            }
        }).done(function(resp) {
            if (!resp || !resp.success || !resp.data) {
                // Show post map CTA if licensed user but request failed (likely no post maps)
                showPostMapCtaIfEmpty([]);
                return;
            }
            const items = resp.data.items || resp.data.types || [];
            if (Array.isArray(items)) {
                items.forEach(function(t) {
                    const key = (t.type_key || '').toString();
                    const name = (t.name || key || 'type');
                    if (key) {
                        $typeSelect.append(
                            $('<option>').attr('value', key).text(name)
                        );
                    }
                });
            }
            // Show post map CTA if no post types exist
            showPostMapCtaIfEmpty(items);
        }).fail(function() {
            // Silent fail; selector still usable with Auto‑infer
            // Show post map CTA since we couldn't load post types
            showPostMapCtaIfEmpty([]);
        });
    }

    /**
     * Show the post map CTA banner if the user has no post maps.
     * @param {Array} items - The list of post types from the API
     */
    function showPostMapCtaIfEmpty(items) {
        const $cta = $('#saiap-post-map-cta');
        if (!$cta.length) return;
        
        // Only show if licensed (CTA is only rendered for licensed users in PHP)
        // and if there are no post maps
        if (!items || items.length === 0) {
            $cta.show();
        } else {
            $cta.hide();
        }
    }

    // Populate model selectors via AJAX (mirrors post types list pattern)
    $.ajax({
        url: saiapAdmin.ajaxurl,
        type: 'POST',
        data: {
            action: 'saiap_models_list',
            nonce: saiapAdmin.contextNonce
        }
    }).done(function(resp) {
        if (!resp || !resp.success || !resp.data || !resp.data.providers) return;
        
        const providers = resp.data.providers;
        
        // Update OpenAI models
        if (providers.openai && providers.openai.models) {
            const $openaiSelect = $('#saiap-model');
            const currentVal = $openaiSelect.val();
            $openaiSelect.empty();
            providers.openai.models.forEach(function(m) {
                $openaiSelect.append(
                    $('<option>').attr('value', m.id).text(m.name || m.id)
                );
            });
            // Restore selection if still valid
            if (currentVal && $openaiSelect.find('option[value="' + currentVal + '"]').length) {
                $openaiSelect.val(currentVal);
            }
        }
        
        // Update Anthropic models
        if (providers.anthropic && providers.anthropic.models) {
            const $anthropicSelect = $('#saiap-anthropic-model');
            const currentVal = $anthropicSelect.val();
            $anthropicSelect.empty();
            providers.anthropic.models.forEach(function(m) {
                $anthropicSelect.append(
                    $('<option>').attr('value', m.id).text(m.name || m.id)
                );
            });
            if (currentVal && $anthropicSelect.find('option[value="' + currentVal + '"]').length) {
                $anthropicSelect.val(currentVal);
            }
        }
        
        // Update Gemini models
        if (providers.gemini && providers.gemini.models) {
            const $geminiSelect = $('#saiap-gemini-model');
            const currentVal = $geminiSelect.val();
            $geminiSelect.empty();
            providers.gemini.models.forEach(function(m) {
                $geminiSelect.append(
                    $('<option>').attr('value', m.id).text(m.name || m.id)
                );
            });
            if (currentVal && $geminiSelect.find('option[value="' + currentVal + '"]').length) {
                $geminiSelect.val(currentVal);
            }
        }
    }).fail(function() {
        // Silent fail; dropdowns still have server-rendered options as fallback
    });

    /**
     * Handle form submission
     */
    $form.on('submit', function(e) {
        // Prevent default form submission
        e.preventDefault();
        
        // Validate form
        if (!validateForm()) {
            return false;
        }
        
        // Store original button text
        originalButtonText = $submit.text().trim();
        
        // Disable submit button and update text
        $submit.prop('disabled', true).addClass('disabled');
        $submit.text('Generating...');
        
        // Start the timer
        secondsElapsed = 0;
        
        // Clear any existing timer first
        if (generationTimer) {
            clearInterval(generationTimer);
        }
        
        // Set up the count-up timer
        generationTimer = setInterval(function() {
            secondsElapsed++;
            $submit.text('Generating... ' + secondsElapsed + 's');
            
            // Safety check - stop timer after MAX_TIMER_SECONDS
            if (secondsElapsed >= MAX_TIMER_SECONDS) {
                clearInterval(generationTimer);
                generationTimer = null;
            }
        }, 1000);
        
        // Add skeleton loader only to the context display container, not the ideas container
        $('#saiap-context-display').each(function() {
            if ($(this).is(':empty')) {
                $(this).html('<div class="skeleton-loader" style="height: 200px;"></div>');
            }
        });
        
        // Send form data via AJAX
        $.ajax({
            url: saiapAdmin.ajaxurl,
            type: 'POST',
            data: prepareFormData(),
            success: handleSuccess,
            error: handleError
        });
    });
    
    /**
     * Validate the form before submission
     * @returns {boolean} Whether the form is valid
     */
    function validateForm() {
        // Check if prompt is empty
        if ($prompt.val().trim() === '') {
            showErrorMessage(saiapAdmin.i18n.errorEmptyPrompt);
            $prompt.focus();
            return false;
        }
        
        return true;
    }
    
    /**
     * Prepare form data for submission
     * @returns {Object} The prepared form data
     */
    function prepareFormData() {
        // Get the form data
        const formData = $form.serializeArray();
        const data = {};
        
        // First, capture provider so we know which model field to use
        let selectedProvider = null;

        // Collect non-model fields
        $.each(formData, function(i, field) {
            if (field.name === 'saiap_default_provider') {
                selectedProvider = field.value;
                data['provider'] = field.value;
            } else if (field.name === 'saiap_ai_prompt') {
                data['prompt'] = field.value;
            } else if (
                field.name !== 'saiap_openai_model' &&
                field.name !== 'saiap_anthropic_model' &&
                field.name !== 'saiap_gemini_model'
            ) {
                // Copy any other fields verbatim
                data[field.name] = field.value;
            }
        });

        // Determine the correct model based on the selected provider
        if (!selectedProvider) {
            // Fallback to current UI selection if provider wasn't serialized first
            selectedProvider = $('#saiap-provider').val();
            data['provider'] = selectedProvider;
        }

        switch (selectedProvider) {
            case 'anthropic':
                data['model'] = $('#saiap-anthropic-model').val();
                break;
            case 'gemini':
                data['model'] = $('#saiap-gemini-model').val();
                break;
            case 'openai':
            default:
                data['model'] = $('#saiap-model').val();
                break;
        }

        // Add the action and nonce
        data['action'] = 'saiap_generate_post';
        data['nonce'] = saiapAdmin.formNonce;

        return data;
    }
    
    /**
     * Handle successful AJAX response
     * @param {Object} response The response from the server
     */
    function handleSuccess(response) {
        // Stop the timer
        clearTimerAndResetButton();
        
        // Hide loader (kept as a safeguard)
        if (typeof window.hideLoader === 'function') {
            window.hideLoader();
        }
        
        if (response.success) {
            // Show success message
            showSuccessMessage(response.data.message, response.data.edit_url);

            if (window.saiapTriggerStepCompletion && typeof window.saiapTriggerStepCompletion === 'function' && saiapAdmin && saiapAdmin.licenseKey) {
                window.saiapTriggerStepCompletion(2);
            }

            // If inline images are queued, show a lightweight info notice
            if (response.data && response.data.inline_images_status === 'queued') {
                showInlineImagesNotice('info');
                startInlineImagesStatusPolling(response.data.post_id);
            } else {
                stopInlineImagesStatusPolling();
            }
        } else {
            stopInlineImagesStatusPolling();
            // Show error message
            showErrorMessage(response.data.message || 'An error occurred while generating the post.');
        }
    }
    
    /**
     * Handle AJAX error
     */
    function handleError() {
        // Stop the timer
        clearTimerAndResetButton();
        stopInlineImagesStatusPolling();
        
        // Hide loader (kept as a safeguard)
        if (typeof window.hideLoader === 'function') {
            window.hideLoader();
        }
        
        // Show error message
        showErrorMessage(saiapAdmin.i18n.errorServer);
    }
    
    /**
     * Clear the timer and reset the button state
     */
    function clearTimerAndResetButton() {
        // Clear the timer
        if (generationTimer) {
            clearInterval(generationTimer);
            generationTimer = null;
        }
        
        // Reset the button
        $submit.prop('disabled', false).removeClass('disabled');
        $submit.text(originalButtonText || 'Generate Post');
    }
    
    /**
     * Show a success message
     * @param {string} message The success message
     * @param {string} editUrl The URL to edit the generated post
     */
    function showSuccessMessage(message, editUrl) {
        const noticeId = 'saiap-success-notice-' + Date.now(); // Unique ID for the notice
        const successMessageHTML = `
            <div id="${noticeId}" class="notice notice-success is-dismissible">
                <p>${message}</p>
                <p><a href="${editUrl}" target="_blank">${saiapAdmin.i18n.editPost}</a></p>
                <button type="button" class="notice-dismiss">
                    <span class="screen-reader-text">Dismiss this notice.</span>
                </button>
            </div>
        `;
        $form.before(successMessageHTML);

        // Add click handler for the dismiss button
        $('#' + noticeId + ' .notice-dismiss').on('click', function(e) {
            e.preventDefault();
            $('#' + noticeId).remove();
        });
    }

    /**
     * Show or update the inline images notice.
     * @param {'info'|'success'|'error'} [variant]
     * @param {string} [customText]
     */
    function showInlineImagesNotice(variant = 'info', customText) {
        const defaults = {
            info: (saiapAdmin.i18n && saiapAdmin.i18n.inlineImagesQueued) || 'Inline images are being added in the background. They may take a few seconds to appear in the draft.',
            success: (saiapAdmin.i18n && saiapAdmin.i18n.inlineImagesComplete) || 'Inline images have been added to your draft.',
            error: (saiapAdmin.i18n && saiapAdmin.i18n.inlineImagesError) || 'We could not add inline images automatically. Please open the draft to review.'
        };
        const text = customText || defaults[variant] || defaults.info;
        const variantClasses = {
            info: 'notice notice-info',
            success: 'notice notice-success',
            error: 'notice notice-error'
        };
        const className = (variantClasses[variant] || variantClasses.info) + ' is-dismissible';
        const existingId = inlineImagesNoticeId;
        const $existing = existingId ? $('#' + existingId) : null;

        if ($existing && $existing.length) {
            $existing.attr('class', className);
            $existing.find('p').first().text(text);
            return existingId;
        }

        const noticeId = 'saiap-inline-images-notice-' + Date.now();
        inlineImagesNoticeId = noticeId;
        const noticeHtml = `
            <div id="${noticeId}" class="${className}">
                <p></p>
                <button type="button" class="notice-dismiss">
                    <span class="screen-reader-text">Dismiss this notice.</span>
                </button>
            </div>
        `;
        $form.before(noticeHtml);
        $('#' + noticeId + ' p').first().text(text);

        $('#' + noticeId + ' .notice-dismiss').on('click', function(e) {
            e.preventDefault();
            $('#' + noticeId).remove();
            if (inlineImagesNoticeId === noticeId) {
                inlineImagesNoticeId = null;
            }
            stopInlineImagesStatusPolling();
        });

        return noticeId;
    }

    function showInlineImagesSuccessNotice(insertedCount) {
        const baseText = (saiapAdmin.i18n && saiapAdmin.i18n.inlineImagesComplete) || 'Inline images have been added to your draft.';
        let suffix = '';
        if (insertedCount && insertedCount > 0) {
            suffix = ' (' + insertedCount + ' ' + (insertedCount === 1 ? 'image' : 'images') + ')';
        }
        showInlineImagesNotice('success', baseText + suffix);
    }

    function showInlineImagesErrorNotice(lastError) {
        const baseText = (saiapAdmin.i18n && saiapAdmin.i18n.inlineImagesError) || 'We could not add inline images automatically. Please open the draft to review.';
        const detail = lastError ? ' ' + lastError : '';
        showInlineImagesNotice('error', baseText + detail);
    }

    function startInlineImagesStatusPolling(postId) {
        if (!postId || !saiapAdmin.inlineImagesNonce) {
            return;
        }

        stopInlineImagesStatusPolling();
        inlineImagesPollingActive = true;
        inlineImagesPollAttempts = 0;

        const poll = function() {
            if (!inlineImagesPollingActive) {
                return;
            }

            inlineImagesPollAttempts++;

            $.ajax({
                url: saiapAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action: 'saiap_inline_images_status',
                    nonce: saiapAdmin.inlineImagesNonce,
                    post_id: postId
                }
            }).done(function(resp) {
                if (!resp || !resp.success || !resp.data) {
                    return;
                }

                const status = resp.data.status;
                if (status === 'done') {
                    showInlineImagesSuccessNotice(resp.data.insertedCount || 0);
                    stopInlineImagesStatusPolling();
                    return;
                }
                if (status === 'error') {
                    showInlineImagesErrorNotice(resp.data.lastError || '');
                    stopInlineImagesStatusPolling();
                    return;
                }
                if (status !== 'queued' && status !== 'processing') {
                    stopInlineImagesStatusPolling();
                }
            }).always(function() {
                if (!inlineImagesPollingActive) {
                    return;
                }
                if (inlineImagesPollAttempts >= INLINE_IMAGES_MAX_POLLS) {
                    stopInlineImagesStatusPolling();
                    return;
                }
                inlineImagesPollTimer = window.setTimeout(poll, INLINE_IMAGES_POLL_INTERVAL_MS);
            });
        };

        poll();
    }

    function stopInlineImagesStatusPolling() {
        inlineImagesPollingActive = false;
        if (inlineImagesPollTimer) {
            clearTimeout(inlineImagesPollTimer);
            inlineImagesPollTimer = null;
        }
        inlineImagesPollAttempts = 0;
    }
    
    /**
     * Show an error message
     * @param {string} message The error message
     */
    function showErrorMessage(message) {
        const noticeId = 'saiap-error-notice-' + Date.now(); // Unique ID for the notice
        const errorMessageHTML = `
            <div id="${noticeId}" class="notice notice-error is-dismissible">
                <p>${message}</p>
                <button type="button" class="notice-dismiss">
                    <span class="screen-reader-text">Dismiss this notice.</span>
                </button>
            </div>
        `;
        $form.before(errorMessageHTML);

        // Add click handler for the dismiss button
        $('#' + noticeId + ' .notice-dismiss').on('click', function(e) {
            e.preventDefault();
            $('#' + noticeId).remove();
        });
    }
    
    // Clean up timers when page is unloaded
    $(window).on('beforeunload', function() {
        if (generationTimer) {
            clearInterval(generationTimer);
        }
        stopInlineImagesStatusPolling();
    });
});
