"use strict"; 
jQuery(document).ready(function($){
    const modelData = JSON.parse($('#aiomatic_video_models').text());
    const $model = $('#aiomatic_model');
    const $duration = $('#aiomatic_duration');
    const $resolution = $('#aiomatic_resolution');
    const $prompt = $('#aiomatic_prompt');
    const $generateBtn = $('#aiomatic_generate_video');
    const $status = $('#aiomatic_video_status');
    const $videoRows = $('#aiomatic_video_rows');
    const $pendingRows = $('#aiomatic_pending_rows');

    function updateOptions(modelName){
        const model = modelData[modelName];
        if(!model) return;
        $duration.empty();
        model.durations.forEach(sec => {
            $duration.append(`<option value="${sec}">${sec} ${model.unit}</option>`);
        });
        $resolution.empty();
        Object.values(model.resolutions).forEach(res => {
            $resolution.append(`<option value="${res.name}">${res.label} ($${res.price.toFixed(2)}/s)</option>`);
        });
    }
    updateOptions($model.val());
    $model.on('change', function(){
        updateOptions($(this).val());
    });

    $generateBtn.on('click', function(){
        const modelVal = $model.val();
        const durationVal = $duration.val();
        const resolutionVal = $resolution.val();
        const promptVal = $prompt.val().trim();

        if(!promptVal){
            alert('Please enter a prompt.');
            return;
        }

        $status.html('<div class="spinner"></div> <em>Requesting video generation...</em>');
        $generateBtn.prop('disabled', true);

        $.post(aiomaticVideoGen.ajaxurl, {
            action: 'aiomatic_generate_video',
            nonce: aiomaticVideoGen.nonce,
            prompt: promptVal,
            duration: durationVal,
            resolution: resolutionVal,
            model: modelVal
        }, function(response){
            $generateBtn.prop('disabled', false);
            if(response.success){
                const videoId = response.data.id;
                $status.html(`<p>Video requested. ID: ${videoId}</p>`);
                $pendingRows.prepend(`
                    <div class="pending-item" data-video-id="${videoId}">
                        <span>Video ID: ${videoId}</span>
                        <span class="status-text"><em>Processing...</em></span>
                    </div>
                `);
                pollVideoStatus(videoId);
            } else {
                $status.html(`<p style="color:red;">${response.data.message}</p>`);
            }
        });
    });

    function pollVideoStatus(video_id){
        let interval = setInterval(() => {
            $.post(aiomaticVideoGen.ajaxurl, {
                action: 'aiomatic_check_video_status',
                nonce: aiomaticVideoGen.nonce,
                video_id
            }, function(response){
                if(response.success){
                    const data = response.data[0];
                    const $item = $(`.pending-item[data-video-id="${video_id}"]`);
                    if(data.status === 'completed'){
                        clearInterval(interval);
                        $item.remove();
                        $videoRows.prepend(`
                            <div class="video-card" data-attachment-id="${data.attachment_id}">
                                <p><strong>${data.id}</strong> (${data.model})</p>
                                <p>Resolution: ${data.size || 'N/A'}, Duration: ${data.seconds || 'N/A'}s</p>
                                <video src="${data.url}" controls></video>
                                <div class="actions">
                                    <a href="${data.url}" download class="download">Download</a>
                                    <button class="delete">Delete</button>
                                </div>
                            </div>
                        `);
                        $status.html('<p><strong>Video completed!</strong></p>');
                    } else if(data.status === 'failed'){
                        clearInterval(interval);
                        $item.find('.status-text').html(`<span style="color:red;">Failed: ${data.error.message}</span>`);
                    } else {
                        $item.find('.status-text').html(`<em>Status: ${data.status}</em>`);
                    }
                }
            });
        }, 5000); 
    }

    $('.pending-item').each(function(){
        const videoId = $(this).data('video-id');
        pollVideoStatus(videoId);
    });

    $videoRows.on('click', '.delete', function(){
        const $card = $(this).closest('.video-card');
        const attachmentId = $card.data('attachment-id');
        if(confirm('Are you sure you want to delete this video?')){
            $.post(aiomaticVideoGen.ajaxurl, {
                action: 'aiomatic_delete_video',
                nonce: aiomaticVideoGen.nonce,
                attachment_id: attachmentId
            }, function(response){
                if(response.success){
                    $card.remove();
                } else {
                    alert(response.data.message);
                }
            });
        }
    });
    $videoRows.on('click', '.details-toggle', function() {
        const $details = $(this).closest('.video-card').find('.video-details');
        $details.slideToggle(200);
    });
});