

let editor;
ClassicEditor
    .create( document.querySelector( '#ckeditor' ) )
    .then( newEditor => {
        editor = newEditor;
    } )
    .catch( error => {
        console.error( error );
    } );


function copyToClipboard() {
    var copyText = document.getElementById("chatOutput");
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/
    document.execCommand("copy");
    // alert("Copied the text: " + copyText.value);
}

jQuery(document).ready(function ($) {

    function getValueFromUrl() {
        var url = window.location.href;
        var hashIndex = url.indexOf('#');
        if (hashIndex !== -1) {
            return url.substring(hashIndex + 1);
        }
        return null;
    }

    // Get the value from the URL
    var value = getValueFromUrl();

    console.log(value)

    // Select the option with the corresponding value and set it as selected
    if (value) {
        $('.select_picker option[value="' + value + '"]').attr('selected', 'selected');
        // $('#mySelect').selectpicker('refresh');
    }

    $('.select_picker').selectpicker();


    $('.sub_category_id').on('change', function () {
        var selectedValue = $(this).val();
        console.log(selectedValue);
    });


    $('#conversationSubmit').on('click', function () {
        var categoryID = $('#category').val();
        var description = $('#description').val();
        var service = $('#service').val();
        var creativity_level = $('#creativity_level').val();
        var output = $('#output').val();
        var character = $('#character').val();
        var tone_of_voice = $('#tone_of_voice').val();
        var target_audience = $('#target_action').val();
        var language = $('#language').val();
        var nonce = $('#general_nonce').val();

        if (nonce === '' || categoryID === '' || description === '' || service === '' || creativity_level === '' || output === '' || character === '' || tone_of_voice === '' || target_audience === '' || language === '') {
            Toastify({
                text: "Please fill all the fields",
                className: "alert",
                style: {
                    background: "linear-gradient(to right, #cb0c9f2e, #cb0c9f)",
                }
            }).showToast();
            return;
        }

        // Disable the submit button
        $('#conversationSubmit').prop('disabled', true);

        // Show "AI is thinking" message in CKEditor
        editor.setData("AI is thinking...");

        // Send the input text to the backend using AJAX
        $.ajax({
            url: ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'general_api_request',
                categoryID: categoryID,
                description: description,
                service: service,
                creativity_level: creativity_level,
                output: output,
                character: character,
                tone_of_voice: tone_of_voice,
                target_audience: target_audience,
                language: language,
                nonce: nonce
            },
            success: function (response) {
                console.log(response.data.prompt);

                var data = JSON.parse(response.data);

                // Check the object type of the response
                if (data.object === 'text_completion') {
                    // For "text_completion" object type
                    if (data.choices && data.choices.length > 0) {
                        var messageContent = data.choices[0].text;
                        editor.setData(messageContent);
                    } else {
                        console.error('No message content found in the response (text_completion)');
                        Toastify({
                            text: "No message content found in the response (text_completion)",
                            className: "alert",
                            style: {
                                background: "linear-gradient(to right, #cb0c9f2e, #cb0c9f)",
                            }
                        }).showToast();
                    }
                } else {
                    Toastify({
                        text: "No message content found in the response (chat.completion)",
                        className: "alert",
                        style: {
                            background: "linear-gradient(to right, #cb0c9f2e, #cb0c9f)",
                        }
                    }).showToast();
                }
            },
            error: function (error) {
                Toastify({
                    text: "An error occurred while processing your request.",
                    className: "alert",
                    style: {
                        background: "linear-gradient(to right, #cb0c9f2e, #cb0c9f)",
                    }
                }).showToast();
            },
            complete: function () {
                // Re-enable the submit button after the AJAX call is complete
                $('#conversationSubmit').prop('disabled', false);
            }
        });
    });

});



jQuery(document).ready(function ($) {

    // Function to display the selected image
    function displayImage(input) {
        var file = input.files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#imagePlaceholder').html('<img src="' + e.target.result + '" class="w-full h-full object-cover">');
        }
        reader.readAsDataURL(file);
    }

// Event listener for file input change
    $('#imageToImage').on('change', function() {
        displayImage(this);
    });


    // $('#imageToImage').on('change', function (e) {
    //     var file = e.target.files[0];
    //     var reader = new FileReader();
    //     reader.onload = function (e) {
    //         $('.genrated-images').css('background-image', 'url(' + e.target.result + ')');
    //     };
    //     reader.readAsDataURL(file);
    // });
    //
    // $('#scaleImage').on('change', function (e) {
    //     var file = e.target.files[0];
    //     var reader = new FileReader();
    //     reader.onload = function (e) {
    //         $('.genrated-images').css('background-image', 'url(' + e.target.result + ')');
    //     };
    //     reader.readAsDataURL(file);
    // });

    $('#submitBtn').on('click', function (e) {
        e.preventDefault();

        var formData = {
            type: 'text',
            prompt: $('#imageText').val(),
            numImages: $('#textImageNumber').val(),
            style: $('#textImageStyle').val(),
            orientation: $('input[name="resolution"]:checked').val()
        };

        var ajaxSettings = {
            url: 'your-server-endpoint-url', // Replace with your server URL
            method: 'POST',
            data: formData,
            success: function (response) {
                console.log('Success:', response);
                // Handle the successful response here
            },
            error: function (xhr, status, error) {
                console.log('Error:', error);
                // Handle the error response here
            }
        };
        console.log(formData)
        console.log(ajaxSettings)

        // Send the AJAX request
        // $.ajax(ajaxSettings);
    });

    $('#submitBtnImage').on('click', function (e) {
        e.preventDefault();

        // var formData = new FormData();
        // formData.append('type', 'image');
        // formData.append('image', $('#imageToImage')[0].files[0]);
        // formData.append('prompt', $('#imagePrompt').val());
        // formData.append('numImages', $('#imageNumber').val());
        // formData.append('style', $('#imageStyle').val());

        var formData = {
            type: 'image',
            image: $('#imageToImage')[0].files[0],
            prompt: $('#imagePrompt').val(),
            numImages: $('#imageNumber').val(),
            style: $('#imageStyle').val()
        };



        // var formData = {
        //     type: 'image',
        //     prompt: $('#imagePrompt').val(),
        //     numImages: $('#textImageNumber').val(),
        //     style: $('#textImageStyle').val(),
        //     orientation: $('input[name="resolution"]:checked').val()
        // };
        var ajaxSettings = {
            url: 'your-server-endpoint-url', // Replace with your server URL
            method: 'POST',
            data: formData,
            success: function (response) {
                console.log('Success:', response);
                // Handle the successful response here
            },
            error: function (xhr, status, error) {
                console.log('Error:', error);
                // Handle the error response here
            },
            processData: false,
            contentType: false
        };
        console.log(formData)
        console.log(ajaxSettings)

        // $.ajax(ajaxSettings);
    });

    $('#submitBtnScale').on('click', function (e) {
        e.preventDefault();

        var formData = new FormData();
        formData.append('type', 'upscale');
        formData.append('image', $('#scaleImage')[0].files[0]);


        var ajaxSettings = {
            url: 'your-server-endpoint-url', // Replace with your server URL
            method: 'POST',
            data: formData,
            success: function (response) {
                console.log('Success:', response);
                // Handle the successful response here
            },
            error: function (xhr, status, error) {
                console.log('Error:', error);
                // Handle the error response here
            },
            processData: false,
            contentType: false
        };
        console.log(formData)
        console.log(ajaxSettings)
        // $.ajax(ajaxSettings);
    });

});