/**
 * WPFAQBlock editor AI FAQ generator.
 *
 * Runs only on single post edit screens where the server renders the
 * WPFAQBlock editor AI meta box.
 *
 * @package WPFAQBlock
 * @since   2.0.0
 */
(function () {
    'use strict';

    var config = window.wpfaqblockEditorAI || {};
    var i18n = config.i18n || {};
    var root = document.getElementById('wpfaqblock-editor-ai-box');

    if (!root) {
        return;
    }

    var generateBtn = document.getElementById('wpfaqblock-editor-ai-generate');
    var saveBtn = document.getElementById('wpfaqblock-editor-ai-save');
    var notice = document.getElementById('wpfaqblock-editor-ai-notice');
    var results = document.getElementById('wpfaqblock-editor-ai-results');
    var list = document.getElementById('wpfaqblock-editor-ai-list');
    var groupSelect = document.getElementById('wpfaqblock-editor-ai-group');
    var postId = parseInt(root.getAttribute('data-post-id') || '0', 10) || 0;
    var postType = root.getAttribute('data-post-type') || config.postType || '';

    function text(key, fallback) {
        return i18n[key] || fallback;
    }

    function getEditorStore() {
        if (!window.wp || !window.wp.data || !window.wp.data.select) {
            return null;
        }

        try {
            return window.wp.data.select('core/editor');
        } catch (e) {
            return null;
        }
    }

    function normalizeEditedValue(value) {
        if (!value) {
            return '';
        }

        if (typeof value === 'string') {
            return value;
        }

        if (typeof value.raw === 'string') {
            return value.raw;
        }

        if (typeof value.rendered === 'string') {
            return value.rendered;
        }

        return String(value);
    }

    function getCurrentTitle() {
        var store = getEditorStore();
        var title = '';

        if (store && store.getEditedPostAttribute) {
            title = normalizeEditedValue(store.getEditedPostAttribute('title'));
        }

        if (!title) {
            var titleField = document.getElementById('title');
            title = titleField ? titleField.value : '';
        }

        return title;
    }

    function getCurrentContent() {
        var store = getEditorStore();
        var content = '';

        if (store && store.getEditedPostContent) {
            content = normalizeEditedValue(store.getEditedPostContent());
        }

        if (!content && store && store.getEditedPostAttribute) {
            content = normalizeEditedValue(store.getEditedPostAttribute('content'));
        }

        if (!content && window.tinyMCE && window.tinyMCE.get('content')) {
            content = window.tinyMCE.get('content').getContent();
        }

        if (!content) {
            var contentField = document.getElementById('content');
            content = contentField ? contentField.value : '';
        }

        return content;
    }

    function stripTags(value) {
        return String(value || '').replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
    }

    function setNotice(type, message, showSettingsLink) {
        if (!notice) {
            return;
        }

        notice.hidden = false;
        notice.className = 'wpfaqblock-editor-ai-notice is-' + type;
        notice.textContent = message;

        if (showSettingsLink && config.settingsUrl) {
            var link = document.createElement('a');
            link.href = config.settingsUrl;
            link.textContent = text('settings', 'Open Settings');
            link.target = '_blank';
            link.rel = 'noopener noreferrer';
            notice.appendChild(document.createTextNode(' '));
            notice.appendChild(link);
        }
    }

    function clearNotice() {
        if (!notice) {
            return;
        }

        notice.hidden = true;
        notice.textContent = '';
        notice.className = 'wpfaqblock-editor-ai-notice';
    }

    function setButtonLoading(button, loading, loadingLabel, readyLabel) {
        if (!button) {
            return;
        }

        button.disabled = loading;
        button.textContent = loading ? loadingLabel : readyLabel;
    }

    function request(action, payload) {
        var formData = new FormData();
        formData.append('action', action);
        formData.append('nonce', config.nonce || '');

        Object.keys(payload || {}).forEach(function (key) {
            formData.append(key, payload[key]);
        });

        return fetch(config.ajaxUrl || '', {
            method: 'POST',
            body: formData
        }).then(function (response) {
            return response.json();
        });
    }

    function renderFaqs(faqs) {
        if (!list || !results) {
            return;
        }

        list.innerHTML = '';

        if (!faqs.length) {
            setNotice('error', 'No FAQs were generated.');
            results.hidden = true;
            return;
        }

        faqs.forEach(function (faq, index) {
            var item = document.createElement('div');
            item.className = 'wpfaqblock-editor-ai-item';

            var header = document.createElement('label');
            header.className = 'wpfaqblock-editor-ai-item__check';

            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.checked = true;

            var checkText = document.createElement('span');
            checkText.textContent = 'FAQ ' + (index + 1);

            var question = document.createElement('input');
            question.type = 'text';
            question.className = 'widefat wpfaqblock-editor-ai-item__question';
            question.value = faq.question || '';
            question.setAttribute('aria-label', 'FAQ question');

            var answer = document.createElement('textarea');
            answer.className = 'widefat wpfaqblock-editor-ai-item__answer';
            answer.rows = 4;
            answer.value = faq.answer || '';
            answer.setAttribute('aria-label', 'FAQ answer');

            header.appendChild(checkbox);
            header.appendChild(checkText);
            item.appendChild(header);
            item.appendChild(question);
            item.appendChild(answer);
            list.appendChild(item);
        });

        results.hidden = false;
    }

    function collectSelectedFaqs() {
        if (!list) {
            return [];
        }

        return Array.prototype.slice.call(list.querySelectorAll('.wpfaqblock-editor-ai-item')).map(function (item) {
            var checkbox = item.querySelector('input[type="checkbox"]');
            var question = item.querySelector('.wpfaqblock-editor-ai-item__question');
            var answer = item.querySelector('.wpfaqblock-editor-ai-item__answer');

            if (!checkbox || !checkbox.checked) {
                return null;
            }

            return {
                question: question ? question.value.trim() : '',
                answer: answer ? answer.value.trim() : ''
            };
        }).filter(function (faq) {
            return faq && faq.question && faq.answer;
        });
    }

    function handleGenerate() {
        var title = getCurrentTitle();
        var content = getCurrentContent();
        var plain = stripTags(title + ' ' + content);

        clearNotice();

        if (!plain) {
            setNotice('error', text('emptyContent', 'Add content to this editor before generating FAQs.'));
            return;
        }

        if (results) {
            results.hidden = true;
        }

        setButtonLoading(
            generateBtn,
            true,
            text('generating', 'Generating...'),
            text('generate', 'Generate FAQs')
        );

        request('wpfaqblock_generate_editor_faqs', {
            post_id: postId,
            post_type: postType,
            source_title: title,
            source_content: content
        }).then(function (response) {
            setButtonLoading(
                generateBtn,
                false,
                text('generating', 'Generating...'),
                text('generate', 'Generate FAQs')
            );

            if (!response || !response.success) {
                var data = response && response.data ? response.data : {};
                setNotice(
                    'error',
                    data.message || text('requestFailed', 'AI request failed. Please try again.'),
                    !!data.missing_key
                );
                return;
            }

            renderFaqs(response.data && response.data.faqs ? response.data.faqs : []);

            if (response.data && response.data.truncated) {
                setNotice('info', 'Large content was trimmed before sending it to AI.');
            } else {
                setNotice('success', 'Review the generated FAQs, then save the selected items.');
            }
        }).catch(function () {
            setButtonLoading(
                generateBtn,
                false,
                text('generating', 'Generating...'),
                text('generate', 'Generate FAQs')
            );
            setNotice('error', text('requestFailed', 'AI request failed. Please try again.'));
        });
    }

    function handleSave() {
        var faqs = collectSelectedFaqs();

        clearNotice();

        if (!faqs.length) {
            setNotice('error', text('selectFaqs', 'Select at least one FAQ to save.'));
            return;
        }

        setButtonLoading(
            saveBtn,
            true,
            text('saving', 'Saving...'),
            text('save', 'Save Selected FAQs')
        );

        request('wpfaqblock_save_editor_ai_faqs', {
            post_id: postId,
            post_type: postType,
            group_id: groupSelect ? groupSelect.value : '0',
            faqs: JSON.stringify(faqs)
        }).then(function (response) {
            setButtonLoading(
                saveBtn,
                false,
                text('saving', 'Saving...'),
                text('save', 'Save Selected FAQs')
            );

            if (!response || !response.success) {
                setNotice('error', response && response.data && response.data.message ? response.data.message : text('saveFailed', 'Could not save FAQs. Please try again.'));
                return;
            }

            setNotice('success', response.data && response.data.message ? response.data.message : 'FAQs saved.');
        }).catch(function () {
            setButtonLoading(
                saveBtn,
                false,
                text('saving', 'Saving...'),
                text('save', 'Save Selected FAQs')
            );
            setNotice('error', text('saveFailed', 'Could not save FAQs. Please try again.'));
        });
    }

    if (generateBtn) {
        generateBtn.addEventListener('click', handleGenerate);
    }

    if (saveBtn) {
        saveBtn.addEventListener('click', handleSave);
    }
})();
