/**
 * Guard Dog Session Manager JavaScript
 *
 * Handles session termination actions on the user profile page.
 *
 * @package GuardDog
 * @since 1.9.1
 */

(function($) {
    'use strict';

    /**
     * Initialize session manager functionality.
     */
    function init() {
        bindTerminateSession();
        bindTerminateAllSessions();
    }

    /**
     * Bind click handler for individual session termination.
     */
    function bindTerminateSession() {
        $(document).on('click', '.guard-dog-terminate-session', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var $button = $(this);

            // Prevent double-clicks
            if ($button.prop('disabled')) {
                return;
            }

            var sessionId = $button.data('session-id');
            // Use button-specific nonce or fall back to global nonce
            var nonce = $button.data('nonce') || guardDogSessions.nonce;

            if (!confirm(guardDogSessions.strings.confirmTerminate)) {
                return;
            }

            var originalText = $button.text();
            $button.prop('disabled', true).text(guardDogSessions.strings.terminating);

            $.ajax({
                url: guardDogSessions.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'guard_dog_terminate_session',
                    session_id: sessionId,
                    nonce: nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Show success state briefly, then remove the row
                        $button.text(guardDogSessions.strings.terminated || 'Terminated');
                        var $table = getSessionTable($button);
                        $button.closest('tr').fadeOut(400, function() {
                            $(this).remove();
                            updateSessionCount($table);
                        });
                    } else {
                        alert(response.data.message || guardDogSessions.strings.error);
                        $button.prop('disabled', false).text(originalText);
                    }
                },
                error: function() {
                    alert(guardDogSessions.strings.error);
                    $button.prop('disabled', false).text(originalText);
                }
            });
        });
    }

    /**
     * Bind click handler for terminating all sessions.
     */
    function bindTerminateAllSessions() {
        $(document).on('click', '.guard-dog-terminate-all-sessions', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var $button = $(this);

            // Prevent double-clicks
            if ($button.prop('disabled')) {
                return;
            }

            var userId = $button.data('user-id');
            // Use button-specific nonce or fall back to global nonce
            var nonce = $button.data('nonce') || guardDogSessions.nonce;

            if (!confirm(guardDogSessions.strings.confirmTerminateAll)) {
                return;
            }

            var originalText = $button.text();
            $button.prop('disabled', true).text(guardDogSessions.strings.terminating);
            var $table = getSessionTable($button);

            $.ajax({
                url: guardDogSessions.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'guard_dog_terminate_all_sessions',
                    user_id: userId,
                    include_current: 'false',
                    nonce: nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Remove all rows except the current session
                        $table.find('tbody tr').each(function() {
                            var $row = $(this);
                            // Check for both profile page and admin page current session indicators
                            if ($row.find('.guard-dog-current-session-badge, .guard-dog-current-badge').length === 0) {
                                $row.fadeOut(300, function() {
                                    $(this).remove();
                                    updateSessionCount($table);
                                });
                            }
                        });

                        // Hide the "Terminate All" button
                        $button.fadeOut(300);

                        alert(response.data.message);
                    } else {
                        alert(response.data.message || guardDogSessions.strings.error);
                        $button.prop('disabled', false).text(originalText);
                    }
                },
                error: function() {
                    alert(guardDogSessions.strings.error);
                    $button.prop('disabled', false).text(originalText);
                }
            });
        });
    }

    /**
     * Update session count and hide "Terminate All" button if only one session remains.
     *
     * @param {jQuery} $table Session table to update.
     */
    function updateSessionCount($table) {
        $table = ($table && $table.length) ? $table : $('#guard-dog-sessions-table').first();

        if (!$table.length) {
            return;
        }

        var rowCount = $table.find('tbody tr:visible').length;

        if (rowCount <= 1) {
            getBulkActionButtons($table).fadeOut(300);
        }

        // If no rows left, show a message
        if (rowCount === 0) {
            var noSessionsText = guardDogSessions.strings.noSessions || 'No active sessions found.';
            $table.replaceWith(
                '<p>' + noSessionsText + '</p>'
            );
        }
    }

    /**
     * Find the table that belongs to the clicked session control.
     *
     * Frontend shortcodes can render multiple session surfaces on one page, so
     * prefer the closest surface before falling back to the legacy profile table.
     *
     * @param {jQuery} $element Clicked control.
     * @return {jQuery}
     */
    function getSessionTable($element) {
        var $surface = $element.closest('[data-guard-dog-sessions-surface]');

        if ($surface.length) {
            var $surfaceTable = $surface.find('[data-guard-dog-sessions-table]').first();
            if ($surfaceTable.length) {
                return $surfaceTable;
            }
        }

        var $closestTable = $element.closest('table');
        if ($closestTable.length) {
            return $closestTable;
        }

        return $('#guard-dog-sessions-table').first();
    }

    /**
     * Find bulk action buttons that belong to a table.
     *
     * @param {jQuery} $table Session table.
     * @return {jQuery}
     */
    function getBulkActionButtons($table) {
        var $surface = $table.closest('[data-guard-dog-sessions-surface]');

        if ($surface.length) {
            return $surface.find('.guard-dog-terminate-all-sessions');
        }

        return $('.guard-dog-terminate-all-sessions');
    }

    // Initialize when DOM is ready
    $(document).ready(init);

})(jQuery);
