(function($) {
    'use strict';

    var $editor = $('#seo-fury-htaccess-editor');
    var $status = $('#seo-fury-htaccess-status');
    var codeMirrorInstance = null;

    // Initialize CodeMirror if available
    if (typeof wp !== 'undefined' && wp.codeEditor) {
        var editorSettings = wp.codeEditor.defaultSettings ?
            _.clone(wp.codeEditor.defaultSettings) : {};
        editorSettings.codemirror = $.extend({}, editorSettings.codemirror, {
            mode: 'application/x-httpd-php',
            lineNumbers: true,
            lineWrapping: true,
            indentUnit: 4,
            tabSize: 4,
            matchBrackets: true,
        });
        var instance = wp.codeEditor.initialize($editor, editorSettings);
        codeMirrorInstance = instance.codemirror;
    }

    function getEditorContent() {
        return codeMirrorInstance ? codeMirrorInstance.getValue() : $editor.val();
    }

    function setEditorContent(content) {
        if (codeMirrorInstance) {
            codeMirrorInstance.setValue(content);
        } else {
            $editor.val(content);
        }
    }

    function appendToEditor(text) {
        var current = getEditorContent();
        var separator = current.trim() ? '\n\n' : '';
        setEditorContent(current + separator + text);
        // Scroll to end
        if (codeMirrorInstance) {
            codeMirrorInstance.setCursor(codeMirrorInstance.lineCount(), 0);
            codeMirrorInstance.focus();
        }
    }

    // Save .htaccess
    $(document).on('click', '#seo-fury-htaccess-save', function() {
        var $btn = $(this);
        $btn.prop('disabled', true);
        $status.html('<span style="color:#666;">' + (seoFuryHtaccess.i18n.saving || 'Saving...') + '</span>');

        $.ajax({
            url: seoFuryHtaccess.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_fury_save_htaccess',
                nonce: seoFuryHtaccess.nonce,
                content: getEditorContent()
            },
            success: function(response) {
                if (response.success) {
                    if (response.data.unverified) {
                        $status.html('<span style="color:#bd8600;">&#9888; ' + response.data.message + '</span>');
                    } else {
                        $status.html('<span style="color:#00a32a;">&#10004; ' + response.data.message + '</span>');
                    }
                    // Update restore button text if backup time changed
                    if (response.data.backup_time) {
                        var restoreBtn = $('#seo-fury-htaccess-restore');
                        if (restoreBtn.length === 0) {
                            // Create restore button
                            $btn.after(' <button type="button" id="seo-fury-htaccess-restore" class="button button-secondary">' +
                                (seoFuryHtaccess.i18n.restoreBackup || 'Restore Backup') + ' (' + response.data.backup_time + ')</button>');
                        } else {
                            restoreBtn.text((seoFuryHtaccess.i18n.restoreBackup || 'Restore Backup') + ' (' + response.data.backup_time + ')');
                        }
                    }
                } else {
                    var msg = response.data.message || (seoFuryHtaccess.i18n.saveFailed || 'Save failed');
                    if (response.data.rolled_back) {
                        msg = '&#9888; ' + msg;
                    }
                    $status.html('<span style="color:#d63638;">' + msg + '</span>');
                }
            },
            error: function() {
                $status.html('<span style="color:#d63638;">&#10006; ' + (seoFuryHtaccess.i18n.connectionError || 'Connection error') + '</span>');
            },
            complete: function() {
                $btn.prop('disabled', false);
            }
        });
    });

    // Restore backup
    $(document).on('click', '#seo-fury-htaccess-restore', function() {
        if (!confirm(seoFuryHtaccess.i18n.confirmRestore || 'Are you sure you want to restore the backup?')) {
            return;
        }

        var $btn = $(this);
        $btn.prop('disabled', true);
        $status.html('<span style="color:#666;">' + (seoFuryHtaccess.i18n.restoring || 'Restoring...') + '</span>');

        $.ajax({
            url: seoFuryHtaccess.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_fury_restore_htaccess',
                nonce: seoFuryHtaccess.nonce
            },
            success: function(response) {
                if (response.success) {
                    setEditorContent(response.data.content);
                    $status.html('<span style="color:#00a32a;">&#10004; ' + response.data.message + '</span>');
                } else {
                    $status.html('<span style="color:#d63638;">&#10006; ' + response.data.message + '</span>');
                }
            },
            error: function() {
                $status.html('<span style="color:#d63638;">&#10006; ' + (seoFuryHtaccess.i18n.connectionError || 'Connection error') + '</span>');
            },
            complete: function() {
                $btn.prop('disabled', false);
            }
        });
    });

    // Preset insert buttons
    $(document).on('click', '.seo-fury-htaccess-preset-btn', function() {
        var presetKey = $(this).data('preset');
        if (seoFuryHtaccess.presets && seoFuryHtaccess.presets[presetKey]) {
            appendToEditor(seoFuryHtaccess.presets[presetKey]);
        }
    });

})(jQuery);
