// jQuery(document).ready(function($) {
//     const headingsInput = document.getElementById('brain-pod-ai-writer-headings');
//     const tagify = new Tagify(headingsInput, {
//         maxTags: 10,
//         delimiters: ';'
//     });
// });

jQuery(document).ready(function($) {
    const $logTitleButton = $('#brain-pod-ai-writer-log-title');

    $logTitleButton.on('click', function() {
        let currentTitle;

        // Check if the Gutenberg Block Editor is active
        if (wp.data.select('core/editor')) {
            currentTitle = wp.data.select('core/editor').getEditedPostAttribute('title');
        } else {
            currentTitle = $('#title').val();
        }

        console.log('Current Post Title:', currentTitle);
    });
});

let checkStatusTimer;

function checkStatus(jobId) {
    fetch('https://start.brainpod.ai/api/v1/article_status/' + jobId)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            // Check API errors here...
            //...
            if (data.status === 'passed') {
                const htmlContent = data.generated_text.replace(/\n/g, '<br>');
                const contentWithoutH1 = htmlContent.replace(/<h1>.*?<\/h1>/ig, '');
                if (wp.data.select('core/editor')) {
                    // Gutenberg Editor
                    const block = wp.blocks.createBlock('core/paragraph', {
                        content: contentWithoutH1
                    });
                    // Remove all blocks and insert the new block
                    const currentBlocks = wp.data.select('core/editor').getBlocks();
                    currentBlocks.forEach((block) => {
                        wp.data.dispatch('core/block-editor').removeBlock(block.clientId);
                    });
                    wp.data.dispatch('core/block-editor').insertBlock(block);
                    jQuery("#brain-pod-ai-writer-generate").prop("disabled", false);
                    jQuery('#brain-pod-ai-writer-loading').hide();

                } else if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                    // Classic Editor
                    tinyMCE.get('content').setContent(contentWithoutH1);
                } else {
                    // HTML Textarea
                    jQuery('#content').val(contentWithoutH1);
                }
                clearInterval(checkStatusTimer);
            }
        })
        .catch(e => {
            console.error('There has been a problem with your fetch operation: ', e.message);
        });
}

jQuery(document).ready(function($) {
    const $generateButton = $('#brain-pod-ai-writer-generate');
    
    $generateButton.on('click', function() {
        const apiKey = brainPodAIWriter.apiKey;
        const headings = $('#brain-pod-ai-writer-headings').val().split(';');
        const length = $('#brain-pod-ai-writer-length').val();
        let postTitle;
    
        if (wp.data.select('core/editor')) {
            postTitle = wp.data.select('core/editor').getEditedPostAttribute('title');
        } else {
            postTitle = $('#title').val();
        }
    
        if (!postTitle || postTitle.trim() === '') {
            alert('Post title cannot be empty. Please enter a title before generating content.');
            return;
        }
    
        const data = {
            task: 'article',
            title: postTitle,
            headings: headings,
            add_image: false,
            length: length,
            inputs: '{}'
        };
    
        const requestOptions = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + apiKey
            },
            body: JSON.stringify(data)
        };
        var loadingMessages = [
            "Crafting your article with precision and excellence. Please wait...",
            "Composing a premium article tailored for you. Please be patient...",
            "Harnessing AI to deliver a top-tier article. Just a moment...",
            "Perfecting your content using advanced AI algorithms. Hold tight...",
            "Dedicated to bringing you the best. Crafting your article now...",
            "Conjuring an expertly-written article for you. A moment, please..."
        ];
    
        function getRandomMessage() {
            var randomIndex = Math.floor(Math.random() * loadingMessages.length);
            return loadingMessages[randomIndex];
        }
        var message = getRandomMessage();
        $('#brain-pod-ai-writer-loading').text(message).show();
        $("#brain-pod-ai-writer-generate").prop("disabled", true);
    
        fetch('https://start.brainpod.ai/api/v1', requestOptions)
            .then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                const jobId = data.jobId;
                // Start the timer to check the status every 5 seconds
                checkStatusTimer = setInterval(() => checkStatus(jobId), 5000);
            })
            .catch(e => {
                console.error('There has been a problem with your fetch operation: ', e.message);
            });
    });
});

// BULK ARTICLE

jQuery(document).ready(function($) {
    // Initialize tagify on the keywords input field
    var keywordsInput = document.getElementById('brain-pod-ai-writer-keywords');
    if (keywordsInput) {
        var tagify = new Tagify(keywordsInput);
    }

    var keywordSourceRadios = document.getElementsByName('keywords-source');
    var keywordsCsvInput = document.getElementById('brain-pod-ai-writer-keywords-csv');
    var keywordCountElement = document.getElementById('keyword-count');
    var tokenCountElement = document.getElementById('token-count');

    function updateKeywordAndTokenCounts() {
        var keywordCount = 0;
        if (document.getElementById('input-keywords').checked) {
            // Calculate keyword count from Tagify
            keywordCount = tagify.value.length;
        } else if (document.getElementById('upload-csv').checked && keywordsCsvInput.files.length > 0) {
            // Calculate keyword count from CSV
            // This is a simple and not fully accurate way to get the count of keywords.
            // You would probably need to parse the CSV properly for more accurate results.
            var reader = new FileReader();
            reader.onload = function(e) {
                var contents = e.target.result;
                keywordCount = contents.split('\n').length;
                keywordCountElement.textContent = keywordCount;
                tokenCountElement.textContent = keywordCount * 3000; // 3000 tokens per keyword
            };
            reader.readAsText(keywordsCsvInput.files[0]);
        }

        keywordCountElement.textContent = keywordCount;
        tokenCountElement.textContent = keywordCount * 3000; // 3000 tokens per keyword
    }

    // Update keyword and token counts whenever keywords source radio buttons change
    keywordSourceRadios.forEach(function(radio) {
        radio.addEventListener('change', function() {
            updateKeywordAndTokenCounts();
        });
    });

    // Update keyword and token counts whenever keywords input changes
    tagify.on('change', function(e) {
        updateKeywordAndTokenCounts();
    });

    // Update keyword and token counts whenever keywords CSV input changes
    keywordsCsvInput.addEventListener('change', function() {
        updateKeywordAndTokenCounts();
    });
});

