/**
 * Built-blocks library: Playground and Install row actions.
 */
(function () {
    'use strict';

    if (typeof lolacore_bb === 'undefined') {
        return;
    }

    const config = lolacore_bb;
    const i18n = config.i18n || {};

    const modal = document.getElementById('lc-bb-modal');
    const modalTitle = document.getElementById('lc-bb-modal-title');
    const modalMessage = document.getElementById('lc-bb-modal-message');
    const modalHeader = document.getElementById('lc-bb-modal-header');
    const modalFooter = document.getElementById('lc-bb-modal-footer');

    function postAction(action, postId, extra) {
        const body = new URLSearchParams({
            action: action,
            post_id: String(postId),
            _ajax_nonce: config.nonce
        });

        if (extra) {
            Object.keys(extra).forEach(function (key) {
                body.set(key, extra[key]);
            });
        }

        return fetch(config.ajax_url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            credentials: 'same-origin',
            body: body.toString()
        }).then(function (res) {
            return res.json();
        });
    }

    function setLinkBusy(link, busy) {
        if (!link) {
            return;
        }
        if (busy) {
            link.dataset.lolacoreBbOriginalText = link.textContent;
            link.textContent = i18n.working || 'Working…';
            link.style.pointerEvents = 'none';
            link.setAttribute('aria-busy', 'true');
        } else {
            if (link.dataset.lolacoreBbOriginalText) {
                link.textContent = link.dataset.lolacoreBbOriginalText;
            }
            link.style.pointerEvents = '';
            link.removeAttribute('aria-busy');
        }
    }

    function setModalTone(tone) {
        if (!modalHeader) {
            return;
        }
        modalHeader.classList.remove('lc-pb-modal-header--success', 'lc-pb-modal-header--error');
        if (tone === 'success') {
            modalHeader.classList.add('lc-pb-modal-header--success');
        } else if (tone === 'error') {
            modalHeader.classList.add('lc-pb-modal-header--error');
        }
    }

    function hideModal() {
        if (!modal) {
            return;
        }
        modal.style.display = 'none';
    }

    function showModal(options) {
        if (!modal || !modalTitle || !modalMessage || !modalFooter) {
            return;
        }

        setModalTone(options.tone || 'default');
        modalTitle.textContent = options.title || '';
        modalMessage.innerHTML = options.message || '';
        modalFooter.innerHTML = '';

        (options.buttons || []).forEach(function (btn) {
            const el = document.createElement('button');
            el.type = 'button';
            el.className = 'lc-action-btn ' + (btn.className || 'ghost');
            el.textContent = btn.label || '';
            el.addEventListener('click', function () {
                hideModal();
                if (typeof btn.onClick === 'function') {
                    btn.onClick();
                }
            });
            modalFooter.appendChild(el);
        });

        modal.style.display = 'flex';
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function showErrorModal(title, message) {
        showModal({
            tone: 'error',
            title: title || i18n.error_title || 'Installation failed',
            message: '<p>' + escapeHtml(message) + '</p>',
            buttons: [{ label: i18n.close || 'Close', className: 'primary', onClick: function () {} }]
        });
    }

    function showInstalledModal(data) {
        const message = (data && data.message) || i18n.installed_title || 'Block installed';

        showModal({
            tone: 'success',
            title: i18n.installed_title || 'Block installed',
            message: '<p>' + escapeHtml(message) + '</p>',
            buttons: [{
                label: i18n.close || 'Close',
                className: 'primary',
                onClick: function () { window.location.reload(); }
            }]
        });
    }

    function showUninstalledModal(data) {
        const message = (data && data.message) || i18n.uninstalled_title || 'Block uninstalled';

        showModal({
            tone: 'success',
            title: i18n.uninstalled_title || 'Block uninstalled',
            message: '<p>' + escapeHtml(message) + '</p>',
            buttons: [{
                label: i18n.close || 'Close',
                className: 'primary',
                onClick: function () { window.location.reload(); }
            }]
        });
    }

    function handlePlayground(link, postId) {
        setLinkBusy(link, true);
        postAction('lolacore_bb_playground', postId)
            .then(function (result) {
                if (!result.success || !result.data || !result.data.playground_url) {
                    showErrorModal('Playground', (result.data && result.data.message) || 'Could not open Playground.');
                    return;
                }
                window.open(result.data.playground_url, '_blank', 'noopener,noreferrer');
                postAction('lolacore_bb_playground_opened', postId).catch(function () {});
                if (result.data.install_allowed) {
                    return;
                }
                showModal({
                    tone: 'default',
                    title: i18n.playground_attest_title || 'Check your block in Playground',
                    message: '<p>' + escapeHtml(i18n.playground_attest_message || '') + '</p>',
                    buttons: [
                        {
                            label: i18n.playground_attest_ready || 'Install on my site',
                            className: 'primary',
                            onClick: function () {
                                hideModal();
                                postAction('lolacore_bb_playground_attest', postId, { outcome: 'attested' })
                                    .then(function (attestResult) {
                                        if (attestResult.success) {
                                            runInstall(link, postId, false);
                                        }
                                    });
                            }
                        },
                        {
                            label: i18n.playground_attest_issue || "Something's not right",
                            className: 'ghost',
                            onClick: function () {
                                postAction('lolacore_bb_playground_attest', postId, { outcome: 'failed' }).catch(function () {});
                            }
                        }
                    ]
                });
            })
            .catch(function () { showErrorModal('Playground', 'Could not open Playground.'); })
            .finally(function () { setLinkBusy(link, false); });
    }

    function runInstall(link, postId, overwrite) {
        setLinkBusy(link, true);
        const extra = overwrite ? { overwrite: '1' } : null;
        return postAction('lolacore_bb_install', postId, extra)
            .then(function (result) {
                if (result.success) {
                    showInstalledModal(result.data);
                    return;
                }
                if (result.data && result.data.needs_overwrite) {
                    showModal({
                        tone: 'default',
                        title: i18n.overwrite_confirm_title || 'Overwrite installed copy',
                        message: '<p>' + escapeHtml(i18n.overwrite_confirm_message || '') + '</p>',
                        buttons: [
                            { label: i18n.cancel || 'Cancel', className: 'ghost', onClick: function () {} },
                            { label: i18n.overwrite || 'Overwrite', className: 'primary', onClick: function () { runInstall(link, postId, true); } }
                        ]
                    });
                    return;
                }
                showErrorModal(i18n.error_title || 'Installation failed', (result.data && result.data.message) || '');
            })
            .catch(function () { showErrorModal(i18n.error_title || 'Installation failed', 'Installation failed.'); })
            .finally(function () { setLinkBusy(link, false); });
    }

    function runUninstall(link, postId) {
        setLinkBusy(link, true);
        return postAction('lolacore_bb_uninstall', postId)
            .then(function (result) {
                if (result.success) {
                    showUninstalledModal(result.data);
                    return;
                }
                showErrorModal(i18n.error_title || 'Uninstall failed', (result.data && result.data.message) || '');
            })
            .catch(function () { showErrorModal(i18n.error_title || 'Uninstall failed', 'Uninstall failed.'); })
            .finally(function () { setLinkBusy(link, false); });
    }

    function handleUninstall(link, postId) {
        showModal({
            tone: 'default',
            title: i18n.uninstall_confirm_title || 'Uninstall from this site',
            message: '<p>' + escapeHtml(i18n.uninstall_confirm_message || '') + '</p>',
            buttons: [
                { label: i18n.cancel || 'Cancel', className: 'ghost', onClick: function () {} },
                { label: i18n.uninstall_confirm || 'Uninstall', className: 'primary', onClick: function () { runUninstall(link, postId); } }
            ]
        });
    }

    function handleInstall(link, postId) {
        showModal({
            tone: 'default',
            title: i18n.install_confirm_title || 'Install on this site',
            message: '<p>' + escapeHtml(i18n.install_confirm_message || '') + '</p>',
            buttons: [
                { label: i18n.cancel || 'Cancel', className: 'ghost', onClick: function () {} },
                { label: i18n.confirm || 'Install', className: 'primary', onClick: function () { runInstall(link, postId, false); } }
            ]
        });
    }

    if (modal) {
        modal.addEventListener('click', function (event) {
            if (event.target === modal) {
                hideModal();
            }
        });
    }

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && modal && modal.style.display !== 'none') {
            hideModal();
        }
    });

    document.addEventListener('click', function (event) {
        const target = event.target;
        if (!(target instanceof Element)) {
            return;
        }
        const link = target.closest('.lolacore-bb-action');
        if (!link) {
            return;
        }
        event.preventDefault();
        const postId = parseInt(link.getAttribute('data-post-id') || '0', 10);
        if (!postId) {
            return;
        }
        if (link.classList.contains('lolacore-bb-playground')) {
            handlePlayground(link, postId);
            return;
        }
        if (link.classList.contains('lolacore-bb-install')) {
            handleInstall(link, postId);
            return;
        }
        if (link.classList.contains('lolacore-bb-uninstall')) {
            handleUninstall(link, postId);
        }
    });

    // Tab switching on block edit screen (panels are server-rendered).
    document.addEventListener('click', function (event) {
        const target = event.target;
        if (!(target instanceof Element)) {
            return;
        }

        const tab = target.closest('.lolacore-pb-tab');
        if (!tab || !tab.dataset.tab) {
            return;
        }

        const root = tab.closest('.lolacore-pb-edit');
        if (!root) {
            return;
        }

        root.querySelectorAll('.lolacore-pb-tab').forEach(function (btn) {
            const active = btn === tab;
            btn.classList.toggle('is-active', active);
            btn.setAttribute('aria-selected', active ? 'true' : 'false');
        });

        root.querySelectorAll('.lolacore-pb-tab-panel').forEach(function (panel) {
            const show = panel.dataset.panel === tab.dataset.tab;
            panel.classList.toggle('hidden', !show);
        });
    });
})();
