/**
 * WPFAQBlock – AI FAQ Generator JS
 *
 * Handles the "Write with AI" modal:
 *   - Open / close
 *   - Tone & audience selectors
 *   - Call wpfaqblock_generate_ai AJAX action (sends tone + language)
 *   - Render checkable result list
 *   - Insert selected FAQs via wpfaqblock_create_faq
 *
 * @package WPFAQBlock
 * @since   3.0.0
 */
(function () {
    'use strict';

    var builder = window.wpfaqblockBuilder || {};
    var noticeFn = builder.showNotice || function () { };

    var data    = window.wpfaqblockData || {};
    var nonce   = data.nonce   || '';
    var ajaxUrl = data.ajaxUrl || '';

    var aiOptions = window.wpfaqblockAIOptions || {
        tones: { professional: 'Professional', friendly: 'Friendly', humorous: 'Humorous' },
        audiences: {
            general: 'General Public',
            customers: 'Existing Customers',
            technical: 'Technical Experts',
            buyers: 'Potential Buyers'
        }
    };

    // ── Modal elements ───────────────────────────────────────────────
    var modal      = document.getElementById('faqb-ai-modal');
    var overlay    = document.getElementById('faqb-ai-overlay');
    var closeBtn   = document.getElementById('faqb-ai-close');
    var openBtn    = document.getElementById('faqb-btn-ai');
    var topicInput = document.getElementById('faqb-ai-topic');
    var countSel   = document.getElementById('faqb-ai-count');
    var groupSel   = document.getElementById('faqb-ai-group');
    var genBtn     = document.getElementById('faqb-ai-generate');
    var resultsBox = document.getElementById('faqb-ai-results');
    var resultList = document.getElementById('faqb-ai-results-list');
    var insertBtn  = document.getElementById('faqb-ai-insert');
    var keyNotice  = document.getElementById('faqb-ai-key-notice');
    var aiNotices  = document.getElementById('faqb-ai-notices');

    if (!modal) { return; }

    document.addEventListener('DOMContentLoaded', function () {
        injectAiControls();

        if (openBtn)  openBtn.addEventListener('click', openModal);
        if (closeBtn) closeBtn.addEventListener('click', closeModal);
        if (overlay)  overlay.addEventListener('click', closeModal);
        if (genBtn)   genBtn.addEventListener('click', handleGenerate);
        if (insertBtn) insertBtn.addEventListener('click', handleInsert);

        builder.showAiNotice = function (type, msg) {
            if (!aiNotices) return;
            var cls = type === 'error'
                ? 'faqb-notice faqb-notice--error'
                : 'faqb-notice faqb-notice--success';
            aiNotices.innerHTML = '<div class="' + cls + '">' + msg + '</div>';
            aiNotices.style.display = 'block';
        };
    });

    // ── Inject tone + audience selectors into the modal ─────────────
    function injectAiControls() {
        var form = modal.querySelector('.faqb-ai-form');
        if (!form) { return; }

        if (document.getElementById('faqb-ai-tone')) {
            return;
        }

        var wrap = document.createElement('div');
        wrap.className = 'faqb-ai-extra-controls';
        wrap.style.cssText = 'display:flex;gap:12px;margin-top:12px;flex-wrap:wrap;';

        wrap.appendChild(buildSelect(
            'faqb-ai-tone',
            'Tone',
            aiOptions.tones,
            'professional'
        ));

        wrap.appendChild(buildSelect(
            'faqb-ai-audience',
            'Target Audience',
            aiOptions.audiences,
            'general'
        ));

        // Insert BEFORE the Generate button row.
        if (genBtn && genBtn.parentElement) {
            form.insertBefore(wrap, genBtn.parentElement);
        }
    }

    /**
     * Build a labeled select.
     *
     * @param {string}  id       Element ID.
     * @param {string}  label    Label text.
     * @param {Object}  options  { value: label } map.
     * @param {string}  def      Default selected value.
     * @returns {HTMLElement}
     */
    function buildSelect(id, label, options, def) {
        var group = document.createElement('div');
        group.className = 'faqb-modal__field faqb-ai-dynamic-field';

        var lbl = document.createElement('label');
        lbl.className = 'faqb-modal__label';
        lbl.htmlFor   = id;

        var iconClass = label.toLowerCase().includes('tone') ? 'dashicons-admin-customizer' : 'dashicons-groups';
        var lblHtml   = '<span class="dashicons ' + iconClass + '"></span> ' + label;
        lbl.innerHTML = lblHtml;

        var wrap = document.createElement('div');
        wrap.className = 'faqb-modal__select-wrap';

        var sel = document.createElement('select');
        sel.id        = id;
        sel.className = 'faqb-modal__select';

        if (options && typeof options === 'object') {
            Object.keys(options).forEach(function (key) {
                var opt = document.createElement('option');
                opt.value   = key;
                opt.text    = options[key];
                if (key === def) { opt.selected = true; }
                sel.appendChild(opt);
            });
        } else {
            // Fallback when option data is not available.
            var opt = document.createElement('option');
            opt.value   = def;
            opt.text    = def.charAt(0).toUpperCase() + def.slice(1);
            sel.appendChild(opt);
        }

        wrap.appendChild(sel);
        group.appendChild(lbl);
        group.appendChild(wrap);
        return group;
    }

    // ── Open / Close ────────────────────────────────────────────────
    function openModal() {
        if (modal)      modal.style.display = 'flex';
        if (overlay)    overlay.style.display = 'block';
        if (resultsBox) resultsBox.style.display = 'none';
        if (keyNotice)  keyNotice.style.display = 'none';
        if (topicInput) topicInput.focus();
    }

    function closeModal() {
        if (modal)   modal.style.display = 'none';
        if (overlay) overlay.style.display = 'none';
    }

    // ── Generate ────────────────────────────────────────────────────
    function handleGenerate() {
        var topic    = topicInput ? topicInput.value.trim() : '';
        var count    = countSel  ? countSel.value           : '5';
        var group    = groupSel  ? groupSel.value           : '0';
        var toneSel  = document.getElementById('faqb-ai-tone');
        var audSel   = document.getElementById('faqb-ai-audience');
        var tone     = toneSel ? toneSel.value : 'professional';
        var audience = audSel ? audSel.value : 'general';

        // Reset previous validation
        if (topicInput) topicInput.style.borderColor = '';
        if (groupSel)   groupSel.style.borderColor = '';

        if (!topic) {
            if (topicInput) {
                topicInput.style.borderColor = '#ef4444';
                topicInput.focus();
            }
            builder.showAiNotice && builder.showAiNotice('error', 'Please tell us what your FAQ is about.');
            return;
        }

        if (group === '0') {
            if (groupSel) groupSel.style.borderColor = '#ef4444';
            builder.showAiNotice && builder.showAiNotice('error', 'Please select a Target Category first.');
            return;
        }

        if (parseInt(count) < 1) {
            builder.showAiNotice && builder.showAiNotice('error', 'Please enter a valid number of FAQs.');
            return;
        }

        if (aiNotices) aiNotices.style.display = 'none';

        var genText = genBtn.querySelector('.faqb-ai-gen-text');
        var genIcon = genBtn.querySelector('.faqb-ai-gen-icon');
        var oldIcon = genIcon ? genIcon.innerHTML : '';

        genBtn.disabled = true;
        if (genText) genText.textContent = 'Generating…';
        if (genIcon) {
            genIcon.innerHTML = '<path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"><animateTransform attributeName="transform" type="rotate" from="0 12 12" to="360 12 12" dur="1s" repeatCount="indefinite"/></path>';
        }
        if (keyNotice)  keyNotice.style.display = 'none';
        if (resultsBox) resultsBox.style.display = 'none';

        var fd = new FormData();
        fd.append('action',   'wpfaqblock_generate_ai');
        fd.append('nonce',    nonce);
        fd.append('topic',    topic);
        fd.append('count',    count);
        fd.append('tone',     tone);
        fd.append('audience', audience);

        fetch(ajaxUrl, { method: 'POST', body: fd })
            .then(function (r) { return r.json(); })
            .then(function (res) {
                genBtn.disabled = false;
                if (genText) genText.textContent = 'Generate FAQs';
                if (genIcon) genIcon.innerHTML = oldIcon;

                if (!res.success) {
                    if (res.data && res.data.missing_key) {
                        if (keyNotice) keyNotice.style.display = 'block';
                    } else {
                        builder.showAiNotice && builder.showAiNotice('error', (res.data && res.data.message) || 'Error.');
                    }
                    return;
                }

                renderResults(res.data.faqs || []);
            })
            .catch(function () {
                genBtn.disabled = false;
                if (genText) genText.textContent = 'Generate FAQs';
                if (genIcon) genIcon.innerHTML = oldIcon;
                builder.showAiNotice && builder.showAiNotice('error', 'Request failed.');
            });
    }

    // ── Render result checkboxes ─────────────────────────────────────
    function renderResults(faqs) {
        if (!resultList) { return; }
        resultList.innerHTML = '';

        if (!faqs.length) {
            resultList.innerHTML = '<p class="faqb-ai-empty-msg">No FAQs generated. Try a different topic.</p>';
            if (resultsBox) resultsBox.style.display = 'block';
            return;
        }

        faqs.forEach(function (faq, i) {
            var id  = 'faqb-ai-item-' + i;
            var div = document.createElement('div');
            div.className = 'faqb-ai-result-item is-selected';

            var chk       = document.createElement('input');
            chk.type      = 'checkbox';
            chk.id        = id;
            chk.checked   = true;
            chk.dataset.question = faq.question;
            chk.dataset.answer   = faq.answer;

            var textWrap      = document.createElement('div');
            textWrap.className = 'faqb-ai-result-item__text';

            var label   = document.createElement('label');
            label.htmlFor = id;

            var qEl       = document.createElement('div');
            qEl.className = 'faqb-ai-result-item__q';
            qEl.innerHTML = '<span class="dashicons dashicons-editor-help"></span> ' + faq.question;

            var aEl       = document.createElement('div');
            aEl.className = 'faqb-ai-result-item__a';
            aEl.textContent = faq.answer.substring(0, 140) + (faq.answer.length > 140 ? '…' : '');

            label.appendChild(qEl);
            label.appendChild(aEl);
            textWrap.appendChild(label);

            div.addEventListener('click', function (e) {
                if (e.target !== chk) { chk.checked = !chk.checked; }
                div.classList.toggle('is-selected', chk.checked);
            });
            chk.addEventListener('change', function () {
                div.classList.toggle('is-selected', chk.checked);
            });

            div.appendChild(chk);
            div.appendChild(textWrap);
            resultList.appendChild(div);
        });

        if (resultsBox) resultsBox.style.display = 'block';
    }

    // ── Insert selected ──────────────────────────────────────────────
    function handleInsert() {
        var groupId   = groupSel ? groupSel.value : '0';
        var checkboxes = resultList
            ? resultList.querySelectorAll('input[type="checkbox"]:checked')
            : [];

        if (!checkboxes.length) {
            noticeFn('error', 'Select at least one FAQ to insert.');
            return;
        }

        insertBtn.disabled   = true;
        insertBtn.textContent = 'Inserting…';

        var items   = Array.from(checkboxes);
        var pending = items.length;

        items.forEach(function (chk) {
            var fd = new FormData();
            fd.append('action',   'wpfaqblock_create_faq');
            fd.append('nonce',    nonce);
            fd.append('question', chk.dataset.question);
            fd.append('answer',   chk.dataset.answer);
            fd.append('group_id', groupId);
            fd.append('status',   '1');

            fetch(ajaxUrl, { method: 'POST', body: fd })
                .then(function (r) { return r.json(); })
                .then(function (res) {
                    if (res.success && builder.insertNewItem) {
                        try {
                            builder.insertNewItem(
                                res.data.post_id,
                                res.data.question,
                                groupId,
                                chk.dataset.answer,
                                true
                            );
                        } catch (e) {
                            console.error('Error inserting item:', e);
                        }
                    }
                })
                .catch(function (err) {
                    console.error('AJAX Error:', err);
                })
                .finally(function () {
                    pending--;
                    if (pending === 0) {
                        insertBtn.disabled   = false;
                        insertBtn.textContent = 'Insert Selected FAQs';
                        closeModal();
                        if (typeof noticeFn === 'function') {
                            noticeFn('success', items.length + ' FAQ(s) inserted successfully.');
                        }
                    }
                });
        });
    }

})();
