/**
 * Built-plugins library: Playground and Install row actions (post_id only — no code in DOM).
 */
(function () {
    'use strict';

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

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

    const modal = document.getElementById('lc-pb-modal');
    const modalTitle = document.getElementById('lc-pb-modal-title');
    const modalMessage = document.getElementById('lc-pb-modal-message');
    const modalHeader = document.getElementById('lc-pb-modal-header');
    const modalFooter = document.getElementById('lc-pb-modal-footer');
    const modalCancel = document.getElementById('lc-pb-modal-cancel');
    const modalPrimary = document.getElementById('lc-pb-modal-primary');

    let modalPrimaryHandler = null;
    let modalCancelHandler = null;

    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.lolacorePbOriginalText = link.textContent;
            link.textContent = i18n.working || 'Working…';
            link.style.pointerEvents = 'none';
            link.setAttribute('aria-busy', 'true');
        } else {
            if (link.dataset.lolacorePbOriginalText) {
                link.textContent = link.dataset.lolacorePbOriginalText;
            }
            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';
        modalPrimaryHandler = null;
        modalCancelHandler = null;
    }

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

        const tone = options.tone || 'default';
        setModalTone(tone);

        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);
        });

        if (options.showCancel !== false && (options.buttons || []).length === 0) {
            const cancel = document.createElement('button');
            cancel.type = 'button';
            cancel.className = 'lc-action-btn ghost';
            cancel.textContent = i18n.cancel || 'Cancel';
            cancel.addEventListener('click', function () {
                hideModal();
                if (typeof modalCancelHandler === 'function') {
                    modalCancelHandler();
                }
            });
            modalFooter.appendChild(cancel);

            const primary = document.createElement('button');
            primary.type = 'button';
            primary.className = 'lc-action-btn primary';
            primary.textContent = options.primaryLabel || i18n.confirm || 'Confirm';
            primary.addEventListener('click', function () {
                hideModal();
                if (typeof modalPrimaryHandler === 'function') {
                    modalPrimaryHandler();
                }
            });
            modalFooter.appendChild(primary);
        }

        modal.style.display = 'flex';
    }

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

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

    function showInstalledModal(data, link) {
        const message = (data && data.message) || i18n.installed_title || 'Plugin installed';
        const pluginsUrl = (data && data.plugins_url) || '';
        const canActivate = data && data.can_activate;
        const postId = data && data.post_id;

        const buttons = [
            {
                label: i18n.close || 'Close',
                className: 'ghost',
                onClick: function () {
                    window.location.reload();
                }
            }
        ];

        if (pluginsUrl) {
            buttons.unshift({
                label: i18n.open_plugins || 'Open Plugins screen',
                className: 'ghost',
                onClick: function () {
                    window.open(pluginsUrl, '_blank', 'noopener,noreferrer');
                    window.location.reload();
                }
            });
        }

        if (canActivate && postId) {
            buttons.unshift({
                label: i18n.activate_now || 'Activate now',
                className: 'primary',
                onClick: function () {
                    runActivate(link, postId);
                }
            });
        }

        showModal({
            tone: 'success',
            title: i18n.installed_title || 'Plugin installed',
            message: '<p>' + escapeHtml(message) + '</p>',
            showCancel: false,
            buttons: buttons
        });
    }

    function runActivate(link, postId) {
        setLinkBusy(link, true);

        postAction('lolacore_pb_activate', postId)
            .then(function (result) {
                if (result.success) {
                    showModal({
                        tone: 'success',
                        title: i18n.activated_title || 'Plugin activated',
                        message: '<p>' + escapeHtml((result.data && result.data.message) || '') + '</p>',
                        showCancel: false,
                        buttons: [
                            {
                                label: i18n.close || 'Close',
                                className: 'primary',
                                onClick: function () {
                                    window.location.reload();
                                }
                            }
                        ]
                    });
                    return;
                }

                showErrorModal(
                    i18n.activate_failed_title || 'Activation failed',
                    (result.data && result.data.message) || 'Activation failed.'
                );
            })
            .catch(function () {
                showErrorModal(
                    i18n.activate_failed_title || 'Activation failed',
                    'Activation failed. Try again from the Plugins screen.'
                );
            })
            .finally(function () {
                setLinkBusy(link, false);
            });
    }

    function handlePlayground(link, postId, pluginName) {
        setLinkBusy(link, true);

        postAction('lolacore_pb_playground', postId)
            .then(function (result) {
                if (!result.success || !result.data || !result.data.playground_url) {
                    const msg = (result.data && result.data.message) || 'Could not open Playground.';
                    showErrorModal('Playground', msg);
                    return;
                }

                window.open(result.data.playground_url, '_blank', 'noopener,noreferrer');
                postAction('lolacore_pb_playground_opened', postId).catch(function () { /* non-blocking */ });

                if (result.data.install_allowed) {
                    return;
                }

                const name = pluginName || (result.data.name || 'Built plugin');
                showModal({
                    tone: 'default',
                    title: i18n.playground_attest_title || 'Check your plugin in Playground',
                    message: '<p>' + escapeHtml(i18n.playground_attest_message || 'Check the settings page and the front end. When it looks right, install it on your site.') + '</p>',
                    showCancel: false,
                    buttons: [
                        {
                            label: i18n.playground_attest_ready || 'Install on my site',
                            className: 'primary',
                            onClick: function () {
                                hideModal();
                                postAction('lolacore_pb_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_pb_playground_attest', postId, { outcome: 'failed' }).catch(function () {});
                            }
                        }
                    ]
                });
            })
            .catch(function () {
                showErrorModal('Playground', 'Could not open Playground. Try again.');
            })
            .finally(function () {
                setLinkBusy(link, false);
            });
    }

    function runInstall(link, postId, overwrite) {
        setLinkBusy(link, true);

        const extra = overwrite ? { overwrite: '1' } : null;

        return postAction('lolacore_pb_install', postId, extra)
            .then(function (result) {
                if (result.success) {
                    showInstalledModal(result.data, link);
                    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>',
                        showCancel: false,
                        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) || 'Installation failed.'
                );
            })
            .catch(function () {
                showErrorModal(
                    i18n.error_title || 'Installation failed',
                    'Installation failed. Try again.'
                );
            })
            .finally(function () {
                setLinkBusy(link, false);
            });
    }

    function handleInstall(link, postId) {
        showModal({
            tone: 'default',
            title: i18n.install_confirm_title || 'Install on this site',
            message: '<p>' + escapeHtml(i18n.install_confirm_message || '') + '</p>',
            showCancel: false,
            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-pb-action');
        if (!link) {
            return;
        }

        event.preventDefault();

        const postId = parseInt(link.getAttribute('data-post-id') || '0', 10);
        if (!postId) {
            return;
        }

        if (link.classList.contains('lolacore-pb-playground')) {
            const row = link.closest('tr');
            const titleCell = row ? row.querySelector('.column-title strong, .column-title a') : null;
            const pluginName = titleCell ? titleCell.textContent.trim() : '';
            handlePlayground(link, postId, pluginName);
            return;
        }

        if (link.classList.contains('lolacore-pb-install')) {
            handleInstall(link, postId);
        }
    });

    // Tab switching on edit screen (no generated code in JS — 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);
        });
    });
})();
