/**
 * QuickLinks Manager - Admin Scripts
 * Version: 2.1.1
 */

jQuery(document).ready(function($) {

    // ========== SVG ICONS ==========
    var icons = {
        dragHandle: '<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><circle cx="9" cy="6" r="1.5"/><circle cx="15" cy="6" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="9" cy="18" r="1.5"/><circle cx="15" cy="18" r="1.5"/></svg>',
        moveUp: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="18 15 12 9 6 15"/></svg>',
        moveDown: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>',
        trash: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>'
    };

    // ========== UTILITY FUNCTIONS ==========
    function escapeHtml(text) {
        return $('<div>').text(text).html();
    }

    function showSaveStatus(message, isSuccess) {
        var $status = $('#qlm-save-status');
        $status.text(message)
            .removeClass('success error')
            .addClass(isSuccess ? 'success' : 'error')
            .addClass('visible');
        setTimeout(function() {
            $status.removeClass('visible');
        }, 3000);
    }

    function updateEmptyState() {
        var hasRows = $('#qlm-links-body tr').length > 0;
        $('#qlm-empty-state').toggle(!hasRows);
    }

    function updateArrowVisibility() {
        var $rows = $('#qlm-links-body tr');
        var totalRows = $rows.length;
        $rows.each(function(index) {
            var $row = $(this);
            $row.attr('data-index', index);
            $row.find('.qlm-move-up').css('visibility', index === 0 ? 'hidden' : 'visible');
            $row.find('.qlm-move-down').css('visibility', index === totalRows - 1 ? 'hidden' : 'visible');
        });
    }

    // ========== TABS ==========
    if ($('#rs-pz-tabs').length) {
        $('#rs-pz-tabs').tabs();
    }

    // ========== NOTICE DISMISSAL ==========
    $('.notice.rs-pz-close').on('click', 'button.notice-dismiss', function() {
        $.post(quickLinksManager.ajax_url, {
            action: 'quicklinks_manager_dismiss_notice',
            nonce: quickLinksManager.nonce
        });
    });

    // ========== ADD NEW LINK ==========
    $('.rs-pz-add-link').on('click', function() {
        var rs_displayText = $('#rs-pz-name').val().trim();
        var rs_url = $('#rs-pz-url').val().trim();
        var rs_newTab = $('#rs-pz-new-tab').is(':checked') ? 1 : 0;

        if (!rs_displayText || !rs_url) {
            alert('Please fill in both Display Text and URL fields.');
            return;
        }

        var newIndex = $('#qlm-links-body tr').length;

        var newRowHtml = '<tr data-index="' + newIndex + '">' +
            '<td class="qlm-col-drag"><span class="qlm-drag-handle" title="Drag to reorder">' + icons.dragHandle + '</span></td>' +
            '<td class="qlm-col-title"><input type="text" class="rs-pz-name qlm-input" value="' + escapeHtml(rs_displayText) + '"></td>' +
            '<td class="qlm-col-url"><input type="text" class="rs-pz-url qlm-input" value="' + escapeHtml(rs_url) + '"></td>' +
            '<td class="qlm-col-newtab"><label class="qlm-toggle"><input type="checkbox" value="1"' + (rs_newTab ? ' checked' : '') + '><span class="qlm-toggle__slider"></span></label></td>' +
            '<td class="qlm-col-actions"><div class="qlm-actions">' +
                '<button type="button" class="qlm-btn qlm-move-up" title="Move up">' + icons.moveUp + '</button>' +
                '<button type="button" class="qlm-btn qlm-move-down" title="Move down">' + icons.moveDown + '</button>' +
                '<button type="button" class="qlm-btn qlm-btn--delete rs-pz-remove-link" title="Delete">' + icons.trash + '</button>' +
            '</div></td>' +
        '</tr>';

        $('#qlm-links-body').append(newRowHtml);

        $('#rs-pz-name').val('');
        $('#rs-pz-url').val('');
        $('#rs-pz-new-tab').prop('checked', false);

        updateArrowVisibility();
        updateEmptyState();
        initSortable();
    });

    // ========== REMOVE LINK ==========
    $(document).on('click', '.rs-pz-remove-link', function() {
        if (confirm('Are you sure you want to delete this link?')) {
            $(this).closest('tr').fadeOut(200, function() {
                $(this).remove();
                updateArrowVisibility();
                updateEmptyState();
            });
        }
    });

    // ========== MOVE UP/DOWN ==========
    $(document).on('click', '.qlm-move-up', function(e) {
        e.preventDefault();
        var $row = $(this).closest('tr');
        var $prev = $row.prev('tr');
        if ($prev.length) {
            $row.insertBefore($prev);
            updateArrowVisibility();
            sendNewOrder();
        }
    });

    $(document).on('click', '.qlm-move-down', function(e) {
        e.preventDefault();
        var $row = $(this).closest('tr');
        var $next = $row.next('tr');
        if ($next.length) {
            $row.insertAfter($next);
            updateArrowVisibility();
            sendNewOrder();
        }
    });

    // ========== SORTABLE (DRAG & DROP) ==========
    function initSortable() {
        $('#qlm-links-body').sortable({
            handle: '.qlm-drag-handle',
            axis: 'y',
            cursor: 'grabbing',
            placeholder: 'qlm-sortable-placeholder',
            update: function() {
                updateArrowVisibility();
                sendNewOrder();
            }
        });
    }
    initSortable();

    // ========== SEND NEW ORDER ==========
    function sendNewOrder() {
        var links = [];
        $('#qlm-links-body tr').each(function() {
            var title = $(this).find('input.rs-pz-name').val();
            var url = $(this).find('input.rs-pz-url').val();
            if (title && url) {
                links.push({
                    rs_pz_title: title,
                    rs_pz_url: url,
                    rs_pz_newtab: $(this).find('.qlm-toggle input[type=checkbox]').is(':checked') ? 1 : 0
                });
            }
        });

        $.ajax({
            url: quickLinksManager.ajax_url,
            type: 'POST',
            data: {
                action: 'quicklinks_manager_update_order',
                links: JSON.stringify(links),
                nonce: quickLinksManager.nonce
            },
            success: function(response) {
                if (!response.success) {
                    console.error('Failed to update order:', response.data);
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', error);
            }
        });
    }

    // ========== SAVE LINKS ==========
    $('#rs-pz-update-links').on('click', function(e) {
        e.preventDefault();

        var $btn = $(this);
        var originalHtml = $btn.html();
        $btn.prop('disabled', true).html('<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="qlm-spinner"><circle cx="12" cy="12" r="10" stroke-dasharray="32" stroke-dashoffset="12"><animateTransform attributeName="transform" type="rotate" from="0 12 12" to="360 12 12" dur="1s" repeatCount="indefinite"/></circle></svg> Saving...');

        var links = [];
        $('#qlm-links-body tr').each(function() {
            var title = $(this).find('input.rs-pz-name').val();
            var url = $(this).find('input.rs-pz-url').val();
            if (title && url) {
                links.push({
                    rs_pz_title: title,
                    rs_pz_url: url,
                    rs_pz_newtab: $(this).find('.qlm-toggle input[type=checkbox]').is(':checked') ? 1 : 0
                });
            }
        });

        var allowedRoles = [];
        $('#qlm-roles-grid input[name="quicklinks_manager_allowed_roles[]"]:checked').each(function() {
            allowedRoles.push($(this).val());
        });

        $.ajax({
            url: quickLinksManager.ajax_url,
            type: 'POST',
            data: {
                action: 'quicklinks_manager_save',
                links: JSON.stringify(links),
                allowed_roles: JSON.stringify(allowedRoles),
                nonce: quickLinksManager.nonce
            },
            success: function(response) {
                $btn.prop('disabled', false).html(originalHtml);
                if (response.success) {
                    showSaveStatus('Links saved successfully!', true);
                } else {
                    showSaveStatus('Error: ' + response.data, false);
                }
            },
            error: function(xhr, status, error) {
                $btn.prop('disabled', false).html(originalHtml);
                showSaveStatus('Error: ' + error, false);
            }
        });
    });

    // ========== EXPORT ==========
    $('#rs-pz-export-data').on('click', function(e) {
        e.preventDefault();
        var $btn = $(this);
        $btn.prop('disabled', true).text('Exporting...');

        $.ajax({
            url: quickLinksManager.ajax_url,
            type: 'POST',
            data: {
                action: 'quicklinks_manager_export',
                nonce: quickLinksManager.nonce
            },
            success: function(response) {
                $btn.prop('disabled', false).text('Export Links');
                var link = document.createElement('a');
                link.href = 'data:application/json;charset=utf-8,' + encodeURIComponent(response);
                link.download = 'quicklinks-export-' + Date.now() + '.json';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            },
            error: function(xhr, status, error) {
                $btn.prop('disabled', false).text('Export Links');
                alert('Export error: ' + error);
            }
        });
    });

    // ========== IMPORT ==========
    $('#rs-pz-import-links-btn').on('click', function(e) {
        e.preventDefault();

        var fileInput = $('#rs-pz-import-links')[0];
        if (fileInput.files.length === 0) {
            alert('Please select a file.');
            return;
        }

        var file = fileInput.files[0];
        if (!file.name.endsWith('.json')) {
            alert('Please select a JSON file.');
            return;
        }

        var $btn = $(this);
        $btn.prop('disabled', true).text('Importing...');

        var formData = new FormData();
        formData.append('file', file);
        formData.append('action', 'quicklinks_manager_import');
        formData.append('nonce', quickLinksManager.nonce);

        $.ajax({
            url: quickLinksManager.ajax_url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                $btn.prop('disabled', false).text('Import Links');
                if (response.success) {
                    alert('Import successful!');
                    location.reload();
                } else {
                    alert('Error: ' + response.data);
                }
            },
            error: function(xhr, status, error) {
                $btn.prop('disabled', false).text('Import Links');
                alert('Import error: ' + error);
            }
        });
    });

    // ========== INIT ==========
    updateEmptyState();
    updateArrowVisibility();

});
