/**
 * LolaCore Playbooks admin page — list, toggle, delete, manual editor.
 * Loaded only on the Playbooks submenu (independent of settings-page hooks).
 */
jQuery(document).ready(function ($) {
    if (typeof lolacore_ajax === 'undefined') {
        // eslint-disable-next-line no-console
        console.error('[LolaCore] lolacore_ajax is missing on the Playbooks page.');
        return;
    }

    const i18n = typeof lolacore_playbooks_i18n !== 'undefined' ? lolacore_playbooks_i18n : {};
    let messageFadeTimeout = null;

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

    function replaceToken(str, value) {
        return String(str).replace('%s', value);
    }

    function escapeHtml(text) {
        return $('<div>').text(String(text)).html();
    }

    function showMessage(msg, type, options) {
        options = options || {};
        const color = type === 'success' ? '#00a32a' : '#d63638';
        const dismissLabel = t('dismissMessage', 'Dismiss');
        const persistent = type === 'error' && options.persistent !== false;
        const html =
            '<div style="padding:10px;margin-bottom:15px;border-left:4px solid ' +
            color +
            ';background:#fff;box-shadow:0 1px 1px rgba(0,0,0,0.04);">' +
            '<p style="margin:0 0 8px;">' +
            escapeHtml(msg) +
            '</p>' +
            (persistent
                ? '<button type="button" class="button-link lc-dismiss-message" style="padding:0;">' +
                  escapeHtml(dismissLabel) +
                  '</button>'
                : '') +
            '</div>';

        const $container = $('#lolacore-settings-messages');
        if (!$container.length) {
            window.alert(msg);
            return;
        }

        if (messageFadeTimeout) {
            clearTimeout(messageFadeTimeout);
            messageFadeTimeout = null;
        }

        $container.stop(true, true).html(html).show().css('opacity', 1);

        $container.find('.lc-dismiss-message').on('click', function () {
            if (messageFadeTimeout) {
                clearTimeout(messageFadeTimeout);
                messageFadeTimeout = null;
            }
            $container.fadeOut(200);
        });

        if (persistent) {
            return;
        }

        const delay = type === 'error' ? 15000 : 6000;
        messageFadeTimeout = setTimeout(function () {
            $container.fadeOut();
            messageFadeTimeout = null;
        }, delay);
    }

    function showDistillErrorAck(message) {
        const messageHtml =
            '<p>' +
            escapeHtml(message) +
            '</p><p>' +
            escapeHtml(
                t(
                    'distillErrorHint',
                    'You can fix the draft in the editor below, or use Regenerate with instructions.'
                )
            ) +
            '</p>';
        showAckModal(t('distillFailedTitle', 'Distillation failed'), messageHtml);
    }

    function formatNumber(value) {
        const n = Number(value);
        if (!Number.isFinite(n)) {
            return String(value);
        }
        return n.toLocaleString();
    }

    function showAckModal(title, messageHtml) {
        const $modal = $('#lc-ack-modal');
        if (!$modal.length) {
            window.alert(messageHtml.replace(/<[^>]+>/g, ''));
            return;
        }

        $('#lc-ack-title').text(title);
        $('#lc-ack-message').html(messageHtml);

        $('#btn-ack-ok')
            .off('click')
            .on('click', function () {
                $modal.fadeOut(200);
            });

        $modal.fadeIn(200);
    }

    function showDocumentTooLongAck(data) {
        const charCount = data.char_count;
        const maxChars = data.max_chars || lolacore_ajax.playbook_upload_max_chars || 40000;
        const overBy = Number(charCount) - Number(maxChars);

        const messageHtml =
            '<p>' +
            replaceToken(t('documentTooLongChars', 'Your document has %s characters of extracted text.'), '<strong>' + formatNumber(charCount) + '</strong>') +
            '</p><p>' +
            replaceToken(t('documentTooLongMax', 'The maximum is %s characters.'), '<strong>' + formatNumber(maxChars) + '</strong>') +
            (overBy > 0
                ? replaceToken(t('documentTooLongOver', ' (about %s over the limit).'), '<strong>' + formatNumber(overBy) + '</strong>')
                : '.') +
            '</p><p>' +
            t(
                'documentTooLongHint',
                'Upload a shorter section (for example one chapter), or ask Lola in the chat to help you build a playbook from the parts you need.'
            ) +
            '</p>';

        showAckModal(t('documentTooLongTitle', 'Document too long'), messageHtml);
    }

    function handleDistillErrorResponse(data) {
        if (data && data.code === 'document_too_long') {
            showDocumentTooLongAck(data);
            return true;
        }
        return false;
    }

    function showConfirmModal(title, message, btnText, btnType, onConfirm) {
        const $modal = $('#lc-confirm-modal');
        if (!$modal.length) {
            if (window.confirm(message.replace(/<[^>]+>/g, ''))) {
                onConfirm();
            }
            return;
        }

        $('#lc-confirm-title').text(title);
        $('#lc-confirm-message').html(message);

        const $btnConfirm = $('#btn-confirm-ok');
        $btnConfirm.text(btnText).removeClass('primary danger ghost').addClass(btnType);

        $btnConfirm.off('click').on('click', function () {
            $modal.fadeOut(200);
            if (typeof onConfirm === 'function') {
                onConfirm();
            }
        });

        $('#btn-confirm-cancel')
            .off('click')
            .on('click', function () {
                $modal.fadeOut(200);
            });

        $modal.fadeIn(200);
    }

    function readFrontmatterName(content) {
        if (!content || content.indexOf('---') !== 0) {
            return '';
        }
        const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
        if (!match) {
            return '';
        }
        const nameLine = match[1].match(/^name:\s*(.+)$/m);
        return nameLine ? nameLine[1].trim() : '';
    }

    // Keep slug field in sync while editing new playbooks.
    $('#lolacore-playbook-content').on('input', function () {
        const $slugField = $('#lolacore-playbook-slug');
        if (!$slugField.length) {
            return;
        }
        const name = readFrontmatterName($(this).val());
        if (name) {
            $slugField.val(name);
        }
    }).trigger('input');

    // --- Toggle ---
    $(document).on('change', '.lolacore-playbook-toggle', function () {
        const $toggle = $(this);
        const slug = $toggle.data('playbookSlug');
        const enabled = $toggle.is(':checked');

        $toggle.prop('disabled', true);

        $.ajax({
            url: lolacore_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'lolacore_playbook_toggle',
                _ajax_nonce: lolacore_ajax.nonce,
                playbook_slug: slug,
                enabled: enabled ? '1' : '0',
            },
        })
            .done(function (res) {
                if (res.success) {
                    showMessage(res.data.message, 'success');
                } else {
                    $toggle.prop('checked', !enabled);
                    showMessage((res.data && res.data.message) || t('toggleFailed', 'Toggle failed.'), 'error');
                }
            })
            .fail(function () {
                $toggle.prop('checked', !enabled);
                showMessage(t('toggleServerError', 'Server error while toggling playbook.'), 'error');
            })
            .always(function () {
                $toggle.prop('disabled', false);
            });
    });

    // --- Delete ---
    $(document).on('click', '.lc-playbook-delete-btn', function () {
        const $btn = $(this);
        const slug = $btn.data('playbookSlug');
        const $row = $btn.closest('.lc-skill-row');

        showConfirmModal(
            t('deletePlaybookTitle', 'Delete playbook'),
            replaceToken(
                t('deletePlaybookConfirm', 'Delete playbook "%s"? This cannot be undone.'),
                '<strong>' + $('<span>').text(slug).html() + '</strong>'
            ),
            t('delete', 'Delete'),
            'danger',
            function () {
                $btn.prop('disabled', true);
                $.ajax({
                    url: lolacore_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'lolacore_playbook_delete',
                        _ajax_nonce: lolacore_ajax.nonce,
                        playbook_slug: slug,
                    },
                })
                    .done(function (res) {
                        if (res.success) {
                            $row.addClass('lc-skill-row--removing');
                            setTimeout(function () {
                                $row.remove();
                            }, 400);
                            showMessage(res.data.message, 'success');
                        } else {
                            showMessage((res.data && res.data.message) || t('deleteFailed', 'Delete failed.'), 'error');
                        }
                    })
                    .fail(function () {
                        showMessage(t('deleteServerError', 'Server error while deleting playbook.'), 'error');
                    })
                    .always(function () {
                        $btn.prop('disabled', false);
                    });
            }
        );
    });

    // --- Reload ---
    $('#lolacore-reload-playbooks').on('click', function () {
        const $btn = $(this);
        $btn.prop('disabled', true).text(t('reloading', 'Reloading…'));

        $.ajax({
            url: lolacore_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'lolacore_playbook_reload',
                _ajax_nonce: lolacore_ajax.nonce,
            },
        })
            .done(function (res) {
                if (res.success) {
                    showMessage(res.data.message, 'success');
                    setTimeout(function () {
                        window.location.reload();
                    }, 1200);
                } else {
                    showMessage((res.data && res.data.message) || t('reloadFailed', 'Reload failed.'), 'error');
                    $btn.prop('disabled', false).text(t('reloadPlaybooks', 'Reload playbooks'));
                }
            })
            .fail(function () {
                showMessage(t('reloadServerError', 'Server error while reloading playbooks.'), 'error');
                $btn.prop('disabled', false).text(t('reloadPlaybooks', 'Reload playbooks'));
            });
    });

    // --- View ---
    $(document).on('click', '.lc-playbook-view-btn', function () {
        const $row = $(this).closest('.lc-skill-row');
        $row.find('.lc-skill-viewer').slideToggle(200);
    });

    // --- Upload + distill review ---
    let distillSourceText = '';

    function setDistillOverlay(visible, message) {
        const $overlay = $('#lolacore-playbook-distill-overlay');
        if (message) {
            $('#lolacore-playbook-distill-status').text(message);
        }
        $overlay.toggle(!!visible);
    }

    function showDistillReview(draft, validation) {
        $('#lolacore-playbooks-list').hide();
        $('#lolacore-playbook-distill-review').show();
        $('#lolacore-playbook-distill-content').val(draft);
        syncDistillSlugFromContent(draft);

        const $warn = $('#lolacore-playbook-distill-validation');
        if (validation && validation.valid === false && validation.error) {
            $warn
                .removeClass('notice-warning')
                .addClass('notice-error')
                .text(validation.error)
                .show();
            showMessage(validation.error, 'error', { persistent: true });
            $('html, body').animate({ scrollTop: $warn.offset().top - 80 }, 200);
        } else if (validation && validation.warnings && validation.warnings.length) {
            $warn.removeClass('notice-error').addClass('notice-warning').text(validation.warnings.join(' ')).show();
            $('html, body').animate({ scrollTop: $('#lolacore-playbook-distill-review').offset().top - 40 }, 200);
        } else {
            $warn.hide().text('').removeClass('notice-error').addClass('notice-warning');
            $('html, body').animate({ scrollTop: $('#lolacore-playbook-distill-review').offset().top - 40 }, 200);
        }
    }

    function syncDistillSlugFromContent(content) {
        const name = readFrontmatterName(content);
        if (name) {
            $('#lolacore-playbook-distill-slug').val(name);
            $('#lolacore-playbook-distill-save').attr('data-playbook-slug', name);
        }
    }

    $('#lolacore-playbook-distill-content').on('input', function () {
        syncDistillSlugFromContent($(this).val());
    });

    function resetDistillReview() {
        distillSourceText = '';
        $('#lolacore-playbook-distill-instructions').val('');
        $('#lolacore-playbook-distill-content').val('');
        $('#lolacore-playbook-distill-slug').val('');
        $('#lolacore-playbook-distill-review').hide();
        $('#lolacore-playbooks-list').show();
        $('#lolacore-playbook-upload-input').val('');
    }

    function distillRequest(formData, isFormData) {
        setDistillOverlay(true, t('distillingDocument', 'Distilling document…'));

        const ajaxOptions = {
            url: lolacore_ajax.ajax_url,
            type: 'POST',
            data: formData,
            headers: {},
        };

        if (isFormData) {
            ajaxOptions.processData = false;
            ajaxOptions.contentType = false;
        }

        $.ajax(ajaxOptions)
            .done(function (res) {
                if (!res || !res.success) {
                    if (res && res.data && handleDistillErrorResponse(res.data)) {
                        return;
                    }
                    const msg =
                        (res && res.data && res.data.message) ||
                        t('distillEmptyDraft', 'Distillation returned an empty draft.');
                    showDistillErrorAck(msg);
                    return;
                }
                if (!res.data || !res.data.draft) {
                    showDistillErrorAck(t('distillEmptyDraft', 'Distillation returned an empty draft.'));
                    return;
                }
                if (res.data.source_text) {
                    distillSourceText = res.data.source_text;
                }
                showDistillReview(res.data.draft, res.data);
            })
            .fail(function (xhr) {
                const data = xhr.responseJSON && xhr.responseJSON.data;
                if (handleDistillErrorResponse(data)) {
                    return;
                }
                let msg = t('distillFailed', 'Distillation failed.');
                if (data && data.message) {
                    msg = data.message;
                } else if (xhr.responseJSON && xhr.responseJSON.message) {
                    msg = xhr.responseJSON.message;
                }
                showDistillErrorAck(msg);
            })
            .always(function () {
                setDistillOverlay(false);
            });
    }

    $('#lolacore-playbook-upload-btn').on('click', function () {
        $('#lolacore-playbook-upload-input').trigger('click');
    });

    $('#lolacore-playbook-upload-input').on('change', function () {
        const file = this.files && this.files[0];
        if (!file) {
            return;
        }

        const formData = new FormData();
        formData.append('action', 'lolacore_playbook_distill');
        formData.append('_ajax_nonce', lolacore_ajax.nonce);
        formData.append('file', file);

        distillRequest(formData, true);
    });

    $('#lolacore-playbook-distill-regenerate').on('click', function () {
        if (!distillSourceText) {
            showMessage(t('sourceTextUnavailable', 'Original source text is unavailable. Upload the document again.'), 'error');
            return;
        }

        const instructions = $('#lolacore-playbook-distill-instructions').val();
        const payload = {
            action: 'lolacore_playbook_distill',
            _ajax_nonce: lolacore_ajax.nonce,
            source_text: distillSourceText,
        };
        if (instructions) {
            payload.instructions = instructions;
        }

        distillRequest(payload, false);
    });

    $('#lolacore-playbook-distill-cancel').on('click', function () {
        resetDistillReview();
    });

    // --- Distill review save ---
    $(document).on('click', '#lolacore-playbook-distill-save', function () {
        const $btn = $(this);
        const content = $('#lolacore-playbook-distill-content').val();
        let slug = $('#lolacore-playbook-distill-slug').val() || $btn.attr('data-playbook-slug');

        const nameFromContent = readFrontmatterName(content);
        if (nameFromContent) {
            slug = nameFromContent;
            $('#lolacore-playbook-distill-slug').val(nameFromContent);
        }

        if (!content || !String(content).trim()) {
            showMessage(t('contentEmpty', 'Playbook content cannot be empty.'), 'error');
            return;
        }
        if (!slug || !String(slug).trim()) {
            showMessage(t('frontmatterNameRequired', 'Add a name: field in the YAML frontmatter.'), 'error');
            return;
        }

        const saveLabel = $btn.text();
        $btn.prop('disabled', true).text(t('saving', 'Saving…'));

        $.ajax({
            url: lolacore_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'lolacore_playbook_save',
                _ajax_nonce: lolacore_ajax.nonce,
                playbook_id: 0,
                playbook_slug: slug,
                content: content,
            },
        })
            .done(function (res) {
                if (res.success) {
                    showMessage(res.data.message, 'success');
                    if (res.data.redirect) {
                        setTimeout(function () {
                            window.location.href = res.data.redirect;
                        }, 1200);
                    }
                } else {
                    showMessage((res.data && res.data.message) || t('saveFailed', 'Save failed.'), 'error');
                }
            })
            .fail(function (xhr) {
                let msg = t('saveServerError', 'Server error while saving playbook.');
                if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    msg = xhr.responseJSON.data.message;
                }
                showMessage(msg, 'error');
            })
            .always(function () {
                $btn.prop('disabled', false).text(saveLabel);
            });
    });

    // --- Manual save (delegated — works on editor view) ---
    $(document).on('click', '#lolacore-playbook-save', function () {
        const $btn = $(this);
        const isNew = String($btn.attr('data-is-new')) === '1';
        const content = $('#lolacore-playbook-content').val();
        let slug = isNew ? $('#lolacore-playbook-slug').val() : $btn.attr('data-playbook-slug');

        const nameFromContent = readFrontmatterName(content);
        if (nameFromContent) {
            slug = nameFromContent;
            if (isNew && $('#lolacore-playbook-slug').length) {
                $('#lolacore-playbook-slug').val(nameFromContent);
            }
        }

        if (!content || !String(content).trim()) {
            showMessage(t('contentEmpty', 'Playbook content cannot be empty.'), 'error');
            return;
        }
        if (!slug || !String(slug).trim()) {
            showMessage(
                t('frontmatterNameOrSlug', 'Add a name: field in the YAML frontmatter (or fill in the slug).'),
                'error'
            );
            return;
        }

        const saveLabel = $btn.text();
        $btn.prop('disabled', true).text(t('saving', 'Saving…'));

        $.ajax({
            url: lolacore_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'lolacore_playbook_save',
                _ajax_nonce: lolacore_ajax.nonce,
                playbook_id: $btn.attr('data-playbook-id') || 0,
                playbook_slug: slug,
                content: content,
            },
        })
            .done(function (res) {
                if (res.success) {
                    showMessage(res.data.message, 'success');
                    if (res.data.redirect) {
                        setTimeout(function () {
                            window.location.href = res.data.redirect;
                        }, 1200);
                    }
                } else {
                    showMessage((res.data && res.data.message) || t('saveFailed', 'Save failed.'), 'error');
                }
            })
            .fail(function (xhr) {
                let msg = t('saveServerError', 'Server error while saving playbook.');
                if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    msg = xhr.responseJSON.data.message;
                }
                showMessage(msg, 'error');
            })
            .always(function () {
                $btn.prop('disabled', false).text(saveLabel);
            });
    });
});
