<?php
/**
 * Role Editor - Dedicated Admin Page
 * Full-page interface for managing user roles and capabilities
 *
 * @package Switchboard
 * @since 1.3.0
 */

if (!defined('ABSPATH')) {
    exit;
}

global $wp_roles;

// Get selected role from URL or default to first role
$selected_role = isset($_GET['role']) ? sanitize_key($_GET['role']) : 'subscriber';
$role_obj = get_role($selected_role);

// Fallback if role doesn't exist
if (!$role_obj) {
    $selected_role = 'subscriber';
    $role_obj = get_role($selected_role);
}

// Get all capabilities across all roles
$all_caps = [];
foreach ($wp_roles->roles as $role) {
    if (isset($role['capabilities'])) {
        $all_caps = array_merge($all_caps, array_keys($role['capabilities']));
    }
}
$all_caps = array_unique($all_caps);
sort($all_caps);

// Count enabled capabilities for selected role
$enabled_count = 0;
foreach ($all_caps as $cap) {
    if (isset($role_obj->capabilities[$cap]) && $role_obj->capabilities[$cap]) {
        $enabled_count++;
    }
}

// Default WordPress roles (cannot be deleted)
$default_roles = ['administrator', 'editor', 'author', 'contributor', 'subscriber'];
$is_default_role = in_array($selected_role, $default_roles);
?>

<div class="wrap sb-module-wrap">
    <!-- Header -->
    <div class="sb-module-header">
        <div class="sb-module-header-left">
            <svg class="sb-module-title-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"></path>
            </svg>
            <div>
                <h1 class="sb-module-title">
                    <?php esc_html_e('Role Editor', 'wpswitchboard'); ?>
                    <span class="switchboard-badge">SWITCHBOARD PRO</span>
                </h1>
                <p class="sb-module-subtitle">
                    <?php esc_html_e('Manage user role permissions and capabilities with precision', 'wpswitchboard'); ?>
                </p>
            </div>
        </div>
        <div class="sb-module-header-right">
            <a href="https://developer.wordpress.org/plugins/users/roles-and-capabilities/" target="_blank" class="sb-module-help-link">
                <span class="dashicons dashicons-editor-help"></span>
                <?php esc_html_e('Capabilities Reference', 'wpswitchboard'); ?>
            </a>
            <button type="button" id="create-role-btn" class="sb-module-button sb-module-button-primary">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                <?php esc_html_e('Create New Role', 'wpswitchboard'); ?>
            </button>
        </div>
    </div>

    <!-- Warning Banner -->
    <div class="sb-role-editor-warning">
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M8 1L1 14h14L8 1z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><path d="M8 6v3M8 11v1" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
        <span><?php esc_html_e('Be careful when modifying capabilities - incorrect settings can break your site or lock users out of the admin area.', 'wpswitchboard'); ?></span>
    </div>

    <!-- Main Layout: Sidebar + Content -->
    <div class="sb-module-layout">
        <!-- Left Sidebar: Role List -->
        <div class="sb-module-sidebar">
            <div class="sb-sidebar-card">
                <div class="sb-sidebar-card-header">
                    <h3><?php esc_html_e('Roles', 'wpswitchboard'); ?></h3>
                </div>
                <div class="sb-sidebar-card-body sb-role-list">
                    <?php foreach ($wp_roles->roles as $role_key => $role_data) :
                        $user_count = count(get_users(['role' => $role_key]));
                        $is_active = ($role_key === $selected_role);
                        $is_default = in_array($role_key, $default_roles);
                        // Count capabilities for this role
                        $role_caps_count = 0;
                        if (isset($role_data['capabilities'])) {
                            foreach ($role_data['capabilities'] as $cap => $granted) {
                                if ($granted) $role_caps_count++;
                            }
                        }
                    ?>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=switchboard-role-editor&role=' . $role_key)); ?>"
                           class="sb-role-item <?php echo $is_active ? 'active' : ''; ?>"
                           data-role="<?php echo esc_attr($role_key); ?>">
                            <div class="sb-role-item-info">
                                <span class="sb-role-item-name"><?php echo esc_html($role_data['name']); ?></span>
                                <span class="sb-role-item-meta">
                                    <span class="sb-role-item-caps"><?php echo esc_html($role_caps_count); ?> <?php esc_html_e('caps', 'wpswitchboard'); ?></span>
                                    <span class="sb-role-item-sep">&middot;</span>
                                    <span class="sb-role-item-count"><?php echo esc_html(number_format_i18n($user_count)); ?> <?php echo esc_html(_n('user', 'users', $user_count, 'wpswitchboard')); ?></span>
                                </span>
                            </div>
                            <?php if (!$is_default) : ?>
                                <span class="sb-role-item-badge"><?php esc_html_e('Custom', 'wpswitchboard'); ?></span>
                            <?php endif; ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Role Info Card -->
            <div class="sb-sidebar-card">
                <div class="sb-sidebar-card-header">
                    <h3><?php esc_html_e('Role Info', 'wpswitchboard'); ?></h3>
                </div>
                <div class="sb-sidebar-card-body">
                    <div class="sb-role-info-item">
                        <span class="sb-role-info-label"><?php esc_html_e('Role Slug', 'wpswitchboard'); ?></span>
                        <code class="sb-role-info-value"><?php echo esc_html($selected_role); ?></code>
                    </div>
                    <div class="sb-role-info-item">
                        <span class="sb-role-info-label"><?php esc_html_e('Display Name', 'wpswitchboard'); ?></span>
                        <span class="sb-role-info-value"><?php echo esc_html($wp_roles->roles[$selected_role]['name']); ?></span>
                    </div>
                    <div class="sb-role-info-item">
                        <span class="sb-role-info-label"><?php esc_html_e('Capabilities', 'wpswitchboard'); ?></span>
                        <span class="sb-role-info-value"><?php echo esc_html($enabled_count . ' / ' . count($all_caps)); ?></span>
                    </div>
                    <div class="sb-role-info-item">
                        <span class="sb-role-info-label"><?php esc_html_e('Type', 'wpswitchboard'); ?></span>
                        <span class="sb-role-info-value">
                            <?php echo $is_default_role ? esc_html__('WordPress Default', 'wpswitchboard') : esc_html__('Custom Role', 'wpswitchboard'); ?>
                        </span>
                    </div>

                    <!-- Role Actions -->
                    <div class="sb-role-actions">
                        <?php if ($is_default_role) : ?>
                            <button type="button" id="reset-role-btn" class="sb-module-button sb-module-button-secondary sb-module-button-sm sb-module-button-full" data-role="<?php echo esc_attr($selected_role); ?>">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg>
                                <?php esc_html_e('Reset to Default', 'wpswitchboard'); ?>
                            </button>
                        <?php else : ?>
                            <button type="button" id="delete-role-btn" class="sb-module-button sb-module-button-danger sb-module-button-sm sb-module-button-full" data-role="<?php echo esc_attr($selected_role); ?>">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><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"></path></svg>
                                <?php esc_html_e('Delete Role', 'wpswitchboard'); ?>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Content: Capabilities Table -->
        <div class="sb-module-columns-main">
            <div class="sb-module-container">
                <form id="role-capabilities-form" method="post">
                    <input type="hidden" name="role" value="<?php echo esc_attr($selected_role); ?>">
                    <?php wp_nonce_field('switchboard_role_editor', 'switchboard_role_editor_nonce'); ?>

                    <!-- Capabilities Card Header -->
                    <div class="sb-card">
                        <div class="sb-card-header sb-card-header-with-actions">
                            <div>
                                <h2 class="sb-card-title">
                                    <?php
                                    /* translators: %s: role name */
                                    printf(esc_html__('Capabilities for %s', 'wpswitchboard'), '<span class="sb-text-primary">' . esc_html($wp_roles->roles[$selected_role]['name']) . '</span>');
                                    ?>
                                </h2>
                                <p class="sb-card-subtitle" id="capabilities-count">
                                    <?php
                                    /* translators: %1$d: enabled capabilities count, %2$d: total capabilities count */
                                    printf(esc_html__('%1$d of %2$d capabilities enabled', 'wpswitchboard'), $enabled_count, count($all_caps));
                                    ?>
                                </p>
                            </div>
                            <div class="sb-card-actions">
                                <div class="sb-search-box">
                                    <svg class="sb-search-icon" width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="7" cy="7" r="5" stroke="currentColor" stroke-width="2"/><path d="M11 11l3 3" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
                                    <input type="text" id="capability-search" class="sb-search-input" placeholder="<?php esc_attr_e('Search capabilities...', 'wpswitchboard'); ?>">
                                </div>
                                <div class="sb-bulk-actions">
                                    <button type="button" id="select-all-visible" class="sb-bulk-btn" title="<?php esc_attr_e('Select all visible capabilities', 'wpswitchboard'); ?>">
                                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 12l2 2 4-4"/></svg>
                                        <?php esc_html_e('Select All', 'wpswitchboard'); ?>
                                    </button>
                                    <button type="button" id="deselect-all-visible" class="sb-bulk-btn" title="<?php esc_attr_e('Deselect all visible capabilities', 'wpswitchboard'); ?>">
                                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>
                                        <?php esc_html_e('Deselect All', 'wpswitchboard'); ?>
                                    </button>
                                </div>
                                <button type="submit" class="sb-module-button sb-module-button-primary" id="save-capabilities-btn">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><polyline points="17 21 17 13 7 13 7 21"></polyline><polyline points="7 3 7 8 15 8"></polyline></svg>
                                    <?php esc_html_e('Save Changes', 'wpswitchboard'); ?>
                                </button>
                            </div>
                        </div>

                        <!-- Category Tabs -->
                        <div class="sb-category-tabs">
                            <button type="button" class="sb-category-tab active" data-category="all"><?php esc_html_e('All', 'wpswitchboard'); ?></button>
                            <?php foreach (SwitchboardSimpleRoleEditor::get_categories() as $cat_key => $cat_label) : ?>
                                <button type="button" class="sb-category-tab" data-category="<?php echo esc_attr($cat_key); ?>"><?php echo esc_html($cat_label); ?></button>
                            <?php endforeach; ?>
                        </div>

                        <!-- Capabilities Table -->
                        <div class="sb-table-container">
                            <table class="sb-table sb-table-capabilities">
                                <thead>
                                    <tr>
                                        <th class="sb-th-capability"><?php esc_html_e('Capability', 'wpswitchboard'); ?></th>
                                        <th class="sb-th-description"><?php esc_html_e('Description', 'wpswitchboard'); ?></th>
                                        <th class="sb-th-enabled"><?php esc_html_e('Enabled', 'wpswitchboard'); ?></th>
                                    </tr>
                                </thead>
                                <tbody id="capabilities-tbody">
                                    <?php
                                    // Sort: enabled first, then alphabetically
                                    $enabled_caps = [];
                                    $disabled_caps = [];
                                    foreach ($all_caps as $cap) {
                                        $has_cap = isset($role_obj->capabilities[$cap]) && $role_obj->capabilities[$cap];
                                        if ($has_cap) {
                                            $enabled_caps[] = $cap;
                                        } else {
                                            $disabled_caps[] = $cap;
                                        }
                                    }
                                    sort($enabled_caps);
                                    sort($disabled_caps);
                                    $sorted_caps = array_merge($enabled_caps, $disabled_caps);

                                    foreach ($sorted_caps as $cap) :
                                        $has_cap = isset($role_obj->capabilities[$cap]) && $role_obj->capabilities[$cap];
                                        $cap_info = SwitchboardSimpleRoleEditor::get_capability_info($cap);
                                        $danger_class = '';
                                        $danger_icon = '';

                                        if ($cap_info['danger'] === 2) {
                                            $danger_class = ' sb-cap-danger-high';
                                            $danger_icon = '<span class="sb-cap-danger-badge sb-cap-danger-high" title="' . esc_attr__('Grants significant access - assign carefully', 'wpswitchboard') . '"><svg width="12" height="12" viewBox="0 0 16 16" fill="none"><path d="M8 1L1 14h14L8 1z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/><path d="M8 6v3M8 11v1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg></span>';
                                        } elseif ($cap_info['danger'] === 1) {
                                            $danger_class = ' sb-cap-danger-moderate';
                                            $danger_icon = '<span class="sb-cap-danger-badge sb-cap-danger-moderate" title="' . esc_attr__('Elevated access - review before assigning', 'wpswitchboard') . '"><svg width="12" height="12" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="6" stroke="currentColor" stroke-width="1.5"/><path d="M8 5v4M8 11v1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg></span>';
                                        }

                                        $categories = SwitchboardSimpleRoleEditor::get_categories();
                                    ?>
                                        <tr class="sb-cap-row<?php echo $has_cap ? ' sb-cap-enabled' : ''; ?><?php echo $danger_class; ?>"
                                            data-capability="<?php echo esc_attr($cap); ?>"
                                            data-category="<?php echo esc_attr($cap_info['category']); ?>"
                                            data-description="<?php echo esc_attr(strtolower($cap_info['desc'])); ?>">
                                            <td class="sb-td-capability">
                                                <div class="sb-cap-name-wrapper">
                                                    <code class="sb-cap-code"><?php echo esc_html($cap); ?></code>
                                                    <?php echo $danger_icon; ?>
                                                </div>
                                            </td>
                                            <td class="sb-td-description">
                                                <span class="sb-cap-description"><?php echo esc_html($cap_info['desc']); ?></span>
                                                <span class="sb-cap-category-badge sb-cap-cat-<?php echo esc_attr($cap_info['category']); ?>">
                                                    <?php echo esc_html($categories[$cap_info['category']] ?? ucfirst($cap_info['category'])); ?>
                                                </span>
                                            </td>
                                            <td class="sb-td-enabled">
                                                <label class="sb-toggle">
                                                    <input type="checkbox"
                                                           name="capabilities[<?php echo esc_attr($cap); ?>]"
                                                           value="1"
                                                           <?php checked($has_cap, true); ?>
                                                           class="sb-toggle-input">
                                                    <span class="sb-toggle-slider"></span>
                                                </label>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                            <!-- Empty Search State -->
                            <div id="sb-empty-search" class="sb-empty-state" style="display: none;">
                                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                                    <circle cx="11" cy="11" r="8"></circle>
                                    <path d="M21 21l-4.35-4.35"></path>
                                </svg>
                                <p class="sb-empty-title"><?php esc_html_e('No capabilities found', 'wpswitchboard'); ?></p>
                                <p class="sb-empty-desc"><?php esc_html_e('Try adjusting your search or filter criteria', 'wpswitchboard'); ?></p>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Toast Notification -->
    <div id="sb-toast" class="sb-toast" style="display: none;">
        <div class="sb-toast-content">
            <svg class="sb-toast-icon sb-toast-success" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
            <svg class="sb-toast-icon sb-toast-error" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>
            <span class="sb-toast-message"></span>
        </div>
    </div>

    <!-- Create New Role Modal -->
    <div id="create-role-modal" class="sb-role-modal" style="display: none;">
        <div class="sb-role-modal-overlay"></div>
        <div class="sb-module-card sb-role-modal-content">
            <div class="sb-module-card-header sb-role-modal-header">
                <div class="sb-module-card-header-left">
                    <h2 class="sb-module-card-title"><?php esc_html_e('Create New Role', 'wpswitchboard'); ?></h2>
                    <p class="sb-module-card-desc"><?php esc_html_e('Define a new user role with custom capabilities', 'wpswitchboard'); ?></p>
                </div>
                <button type="button" class="sb-role-modal-close" id="close-create-modal">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
                </button>
            </div>
            <div class="sb-module-card-body">
                <div class="sb-module-form-group">
                    <label for="new-role-id" class="sb-module-form-label">
                        <?php esc_html_e('Role ID (slug)', 'wpswitchboard'); ?>
                        <span class="sb-module-required">*</span>
                    </label>
                    <input type="text" id="new-role-id" class="sb-module-input" placeholder="<?php esc_attr_e('e.g., store_manager', 'wpswitchboard'); ?>">
                    <p class="sb-module-form-help"><?php esc_html_e('Lowercase letters, numbers, and underscores only. This cannot be changed later.', 'wpswitchboard'); ?></p>
                </div>
                <div class="sb-module-form-group">
                    <label for="new-role-name" class="sb-module-form-label">
                        <?php esc_html_e('Display Name', 'wpswitchboard'); ?>
                        <span class="sb-module-required">*</span>
                    </label>
                    <input type="text" id="new-role-name" class="sb-module-input" placeholder="<?php esc_attr_e('e.g., Store Manager', 'wpswitchboard'); ?>">
                    <p class="sb-module-form-help"><?php esc_html_e('The friendly name shown in the admin interface.', 'wpswitchboard'); ?></p>
                </div>
                <div class="sb-module-form-group">
                    <label for="copy-from-role" class="sb-module-form-label"><?php esc_html_e('Copy Capabilities From', 'wpswitchboard'); ?></label>
                    <select id="copy-from-role" class="sb-module-select">
                        <option value=""><?php esc_html_e('None (start with read only)', 'wpswitchboard'); ?></option>
                        <?php foreach ($wp_roles->roles as $role_key => $role_data) : ?>
                            <option value="<?php echo esc_attr($role_key); ?>"><?php echo esc_html($role_data['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="sb-module-form-help"><?php esc_html_e('Optionally inherit capabilities from an existing role as a starting point.', 'wpswitchboard'); ?></p>
                </div>
            </div>
            <div class="sb-module-card-footer sb-role-modal-footer">
                <button type="button" class="sb-module-button" id="cancel-create-role"><?php esc_html_e('Cancel', 'wpswitchboard'); ?></button>
                <button type="button" class="sb-module-button sb-module-button-primary" id="submit-create-role">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                    <?php esc_html_e('Create Role', 'wpswitchboard'); ?>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Track current category filter
    let currentCategory = "all";

    // Track unsaved changes
    let hasUnsavedChanges = false;
    const initialState = getFormState();

    function getFormState() {
        return $("#role-capabilities-form").serialize();
    }

    function checkForChanges() {
        hasUnsavedChanges = getFormState() !== initialState;
    }

    // Warn on page leave if unsaved changes
    $(window).on("beforeunload", function(e) {
        if (hasUnsavedChanges) {
            e.preventDefault();
            return "<?php echo esc_js(__('You have unsaved changes. Are you sure you want to leave?', 'wpswitchboard')); ?>";
        }
    });

    // Show toast notification
    function showToast(message, type = "success") {
        const $toast = $("#sb-toast");
        $toast.find(".sb-toast-message").text(message);
        $toast.removeClass("sb-toast-success sb-toast-error").addClass("sb-toast-" + type);
        $toast.fadeIn(200);
        setTimeout(function() {
            $toast.fadeOut(200);
        }, 3000);
    }

    // Update empty state visibility
    function updateEmptyState() {
        const visibleRows = $(".sb-cap-row:visible").length;
        if (visibleRows === 0) {
            $("#sb-empty-search").show();
            $(".sb-table-capabilities").hide();
        } else {
            $("#sb-empty-search").hide();
            $(".sb-table-capabilities").show();
        }
    }

    // Bulk actions
    $("#select-all-visible").on("click", function() {
        $(".sb-cap-row:visible").each(function() {
            const $checkbox = $(this).find("input[type='checkbox']");
            if (!$checkbox.is(":checked")) {
                $checkbox.prop("checked", true).trigger("change");
            }
        });
        checkForChanges();
    });

    $("#deselect-all-visible").on("click", function() {
        $(".sb-cap-row:visible").each(function() {
            const $checkbox = $(this).find("input[type='checkbox']");
            if ($checkbox.is(":checked")) {
                $checkbox.prop("checked", false).trigger("change");
            }
        });
        checkForChanges();
    });

    // Keyboard shortcut: Ctrl/Cmd + S to save
    $(document).on("keydown", function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === "s") {
            e.preventDefault();
            $("#role-capabilities-form").submit();
        }
    });

    // Category tab filtering
    $(".sb-category-tab").on("click", function() {
        $(".sb-category-tab").removeClass("active");
        $(this).addClass("active");
        currentCategory = $(this).data("category");
        applyFilters();
    });

    // Search functionality
    $("#capability-search").on("input", function() {
        applyFilters();
    });

    // Combined filter function
    function applyFilters() {
        const searchTerm = $("#capability-search").val().toLowerCase();

        $(".sb-cap-row").each(function() {
            const capName = $(this).data("capability").toLowerCase();
            const capDesc = $(this).data("description") || "";
            const capCategory = $(this).data("category");

            const categoryMatch = currentCategory === "all" || capCategory === currentCategory;
            const searchMatch = !searchTerm || capName.includes(searchTerm) || capDesc.includes(searchTerm);

            if (categoryMatch && searchMatch) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });

        updateCategoryCounts();
        updateEmptyState();
    }

    // Update category tab counts
    function updateCategoryCounts() {
        const searchTerm = $("#capability-search").val().toLowerCase();

        $(".sb-category-tab").each(function() {
            const cat = $(this).data("category");
            let count = 0;

            $(".sb-cap-row").each(function() {
                const capName = $(this).data("capability").toLowerCase();
                const capDesc = $(this).data("description") || "";
                const capCategory = $(this).data("category");

                const searchMatch = !searchTerm || capName.includes(searchTerm) || capDesc.includes(searchTerm);
                const categoryMatch = cat === "all" || capCategory === cat;

                if (searchMatch && categoryMatch) {
                    count++;
                }
            });

            if (searchTerm && cat !== "all") {
                const baseText = $(this).text().split(" (")[0];
                if (count > 0) {
                    $(this).text(baseText + " (" + count + ")").show();
                } else {
                    $(this).text(baseText).hide();
                }
            } else {
                const baseText = $(this).text().split(" (")[0];
                $(this).text(baseText).show();
            }
        });
    }

    // Checkbox change updates count and row styling
    $("#capabilities-tbody").on("change", "input[type='checkbox']", function() {
        const row = $(this).closest(".sb-cap-row");
        if ($(this).is(":checked")) {
            row.addClass("sb-cap-enabled");
        } else {
            row.removeClass("sb-cap-enabled");
        }

        // Update count display
        const enabledCount = $(".sb-cap-row.sb-cap-enabled").length;
        const totalCount = $(".sb-cap-row").length;
        $("#capabilities-count").text(enabledCount + " <?php echo esc_js(__('of', 'wpswitchboard')); ?> " + totalCount + " <?php echo esc_js(__('capabilities enabled', 'wpswitchboard')); ?>");

        // Track unsaved changes
        checkForChanges();
    });

    // Save capabilities via AJAX
    $("#role-capabilities-form").on("submit", function(e) {
        e.preventDefault();

        const $btn = $("#save-capabilities-btn");
        const originalHtml = $btn.html();
        $btn.prop("disabled", true).html('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="sb-spin"><circle cx="12" cy="12" r="10"></circle></svg> <?php echo esc_js(__('Saving...', 'wpswitchboard')); ?>');

        $.ajax({
            url: ajaxurl,
            type: "POST",
            data: $(this).serialize() + "&action=switchboard_save_role_capabilities&nonce=" + $("#switchboard_role_editor_nonce").val(),
            success: function(response) {
                if (response.success) {
                    hasUnsavedChanges = false;
                    showToast("<?php echo esc_js(__('Capabilities saved successfully', 'wpswitchboard')); ?>", "success");
                    $btn.html('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg> <?php echo esc_js(__('Saved!', 'wpswitchboard')); ?>');
                    setTimeout(function() {
                        $btn.prop("disabled", false).html(originalHtml);
                    }, 2000);
                } else {
                    showToast("<?php echo esc_js(__('Failed to save:', 'wpswitchboard')); ?> " + (response.data && response.data.message ? response.data.message : "<?php echo esc_js(__('Unknown error', 'wpswitchboard')); ?>"), "error");
                    $btn.prop("disabled", false).html(originalHtml);
                }
            },
            error: function() {
                showToast("<?php echo esc_js(__('Failed to save capabilities. Please try again.', 'wpswitchboard')); ?>", "error");
                $btn.prop("disabled", false).html(originalHtml);
            }
        });
    });

    // Reset Role Button
    $("#reset-role-btn").on("click", function() {
        const role = $(this).data("role");

        if (!confirm("<?php echo esc_js(__('Are you sure you want to reset this role to WordPress default capabilities? This cannot be undone.', 'wpswitchboard')); ?>")) {
            return;
        }

        const $btn = $(this);
        $btn.prop("disabled", true).html('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="sb-spin"><circle cx="12" cy="12" r="10"></circle></svg> <?php echo esc_js(__('Resetting...', 'wpswitchboard')); ?>');

        $.ajax({
            url: ajaxurl,
            type: "POST",
            data: {
                action: "switchboard_reset_role",
                role: role,
                nonce: "<?php echo esc_js(wp_create_nonce('switchboard_reset_role')); ?>"
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert("<?php echo esc_js(__('Failed to reset role:', 'wpswitchboard')); ?> " + (response.data && response.data.message ? response.data.message : "<?php echo esc_js(__('Unknown error', 'wpswitchboard')); ?>"));
                    $btn.prop("disabled", false).html('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg> <?php echo esc_js(__('Reset to Default', 'wpswitchboard')); ?>');
                }
            },
            error: function() {
                alert("<?php echo esc_js(__('Failed to reset role. Please try again.', 'wpswitchboard')); ?>");
                $btn.prop("disabled", false).html('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg> <?php echo esc_js(__('Reset to Default', 'wpswitchboard')); ?>');
            }
        });
    });

    // Delete Role Button
    $("#delete-role-btn").on("click", function() {
        const role = $(this).data("role");

        if (!confirm("<?php echo esc_js(__('Are you sure you want to delete this role? Users with this role will need to be reassigned. This action cannot be undone.', 'wpswitchboard')); ?>")) {
            return;
        }

        const $btn = $(this);
        $btn.prop("disabled", true).html('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="sb-spin"><circle cx="12" cy="12" r="10"></circle></svg> <?php echo esc_js(__('Deleting...', 'wpswitchboard')); ?>');

        $.ajax({
            url: ajaxurl,
            type: "POST",
            data: {
                action: "switchboard_delete_role",
                role: role,
                nonce: "<?php echo esc_js(wp_create_nonce('switchboard_delete_role')); ?>"
            },
            success: function(response) {
                if (response.success) {
                    window.location.href = "<?php echo esc_url(admin_url('admin.php?page=switchboard-role-editor&role=subscriber')); ?>";
                } else {
                    alert("<?php echo esc_js(__('Failed to delete role:', 'wpswitchboard')); ?> " + (response.data && response.data.message ? response.data.message : "<?php echo esc_js(__('Unknown error', 'wpswitchboard')); ?>"));
                    $btn.prop("disabled", false).html('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><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"></path></svg> <?php echo esc_js(__('Delete Role', 'wpswitchboard')); ?>');
                }
            },
            error: function() {
                alert("<?php echo esc_js(__('Failed to delete role. Please try again.', 'wpswitchboard')); ?>");
                $btn.prop("disabled", false).html('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><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"></path></svg> <?php echo esc_js(__('Delete Role', 'wpswitchboard')); ?>');
            }
        });
    });

    // Create New Role Modal
    $("#create-role-btn").on("click", function() {
        $("#create-role-modal").fadeIn(200);
        $("#new-role-id").focus();
    });

    $("#close-create-modal, #cancel-create-role, .sb-role-modal-overlay").on("click", function() {
        $("#create-role-modal").fadeOut(200);
        $("#new-role-id").val("");
        $("#new-role-name").val("");
        $("#copy-from-role").val("");
    });

    $("#submit-create-role").on("click", function() {
        const roleId = $("#new-role-id").val().trim();
        const roleName = $("#new-role-name").val().trim();
        const copyFrom = $("#copy-from-role").val();

        if (!roleId) {
            alert("<?php echo esc_js(__('Please enter a Role ID', 'wpswitchboard')); ?>");
            return;
        }

        if (!roleName) {
            alert("<?php echo esc_js(__('Please enter a Display Name', 'wpswitchboard')); ?>");
            return;
        }

        if (!/^[a-z0-9_]+$/.test(roleId)) {
            alert("<?php echo esc_js(__('Role ID must contain only lowercase letters, numbers, and underscores', 'wpswitchboard')); ?>");
            return;
        }

        const $btn = $(this);
        $btn.prop("disabled", true).text("<?php echo esc_js(__('Creating...', 'wpswitchboard')); ?>");

        $.ajax({
            url: ajaxurl,
            type: "POST",
            data: {
                action: "switchboard_create_role",
                role_id: roleId,
                role_name: roleName,
                copy_from: copyFrom,
                nonce: "<?php echo esc_js(wp_create_nonce('switchboard_create_role')); ?>"
            },
            success: function(response) {
                if (response.success) {
                    $("#create-role-modal").fadeOut(200);
                    window.location.href = "<?php echo esc_url(admin_url('admin.php?page=switchboard-role-editor&role=')); ?>" + roleId;
                } else {
                    alert("<?php echo esc_js(__('Failed to create role:', 'wpswitchboard')); ?> " + (response.data && response.data.message ? response.data.message : "<?php echo esc_js(__('Unknown error', 'wpswitchboard')); ?>"));
                    $btn.prop("disabled", false).text("<?php echo esc_js(__('Create Role', 'wpswitchboard')); ?>");
                }
            },
            error: function() {
                alert("<?php echo esc_js(__('Failed to create role. Please try again.', 'wpswitchboard')); ?>");
                $btn.prop("disabled", false).text("<?php echo esc_js(__('Create Role', 'wpswitchboard')); ?>");
            }
        });
    });
});
</script>

<style>
/* Role Editor Page Styles */
.sb-role-editor-warning {
    display: flex;
    align-items: center;
    gap: 8px;
    background: #fef2f2;
    border: 1px solid #fecaca;
    padding: 10px 16px;
    border-radius: 6px;
    font-size: 13px;
    color: #991b1b;
    margin-bottom: 20px;
}

.sb-role-editor-warning svg {
    flex-shrink: 0;
    color: #dc2626;
}

/* Sidebar Styles */
.sb-module-sidebar {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.sb-sidebar-card {
    background: white;
    border: 1px solid var(--gray-200);
    border-radius: 8px;
    overflow: hidden;
}

.sb-sidebar-card-header {
    padding: 12px 16px;
    border-bottom: 1px solid var(--gray-200);
    background: var(--gray-50);
}

.sb-sidebar-card-header h3 {
    margin: 0;
    font-size: 13px;
    font-weight: 600;
    color: var(--gray-700);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.sb-sidebar-card-body {
    padding: 0;
}

/* Role List */
.sb-role-list {
    /* No max-height - show all roles */
}

.sb-role-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 16px;
    border-bottom: 1px solid var(--gray-100);
    text-decoration: none;
    color: var(--gray-700);
    transition: all 0.15s;
}

.sb-role-item:last-child {
    border-bottom: none;
}

.sb-role-item:hover {
    background: var(--gray-50);
}

.sb-role-item.active {
    background: var(--primary-50);
    border-left: 3px solid var(--primary-500);
}

.sb-role-item-info {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.sb-role-item-name {
    font-weight: 500;
    font-size: 13px;
    color: var(--gray-800);
}

.sb-role-item.active .sb-role-item-name {
    color: var(--primary-700);
}

.sb-role-item-meta {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 11px;
    color: var(--gray-500);
}

.sb-role-item-sep {
    color: var(--gray-300);
}

.sb-role-item-caps {
    color: var(--gray-600);
    font-weight: 500;
}

.sb-role-item-count {
    color: var(--gray-500);
}

.sb-role-item-badge {
    font-size: 9px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    padding: 2px 6px;
    background: var(--primary-100);
    color: var(--primary-700);
    border-radius: 3px;
}

/* Role Info */
.sb-role-info-item {
    padding: 10px 16px;
    border-bottom: 1px solid var(--gray-100);
}

.sb-role-info-item:last-child {
    border-bottom: none;
}

.sb-role-info-label {
    display: block;
    font-size: 11px;
    color: var(--gray-500);
    margin-bottom: 2px;
}

.sb-role-info-value {
    font-size: 13px;
    color: var(--gray-800);
    font-weight: 500;
}

code.sb-role-info-value {
    font-family: "SF Mono", Monaco, Consolas, monospace;
    background: var(--gray-100);
    padding: 2px 6px;
    border-radius: 3px;
    font-size: 12px;
}

.sb-role-actions {
    padding: 12px 16px;
    border-top: 1px solid var(--gray-200);
    background: var(--gray-50);
}

/* Card Styles */
.sb-card {
    background: white;
    border: 1px solid var(--gray-200);
    border-radius: 8px;
    overflow: hidden;
}

.sb-card-header {
    padding: 16px 20px;
    border-bottom: 1px solid var(--gray-200);
}

.sb-card-header-with-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
}

.sb-card-title {
    margin: 0 0 4px 0;
    font-size: 16px;
    font-weight: 600;
    color: var(--gray-900);
}

.sb-card-subtitle {
    margin: 0;
    font-size: 13px;
    color: var(--gray-500);
}

.sb-card-actions {
    display: flex;
    gap: 12px;
    align-items: center;
}

.sb-text-primary {
    color: var(--primary-600);
}

/* Search Box */
.sb-search-box {
    position: relative;
    display: inline-flex;
    align-items: center;
}

.sb-search-icon {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--gray-400);
    pointer-events: none;
    width: 14px;
    height: 14px;
    flex-shrink: 0;
}

.sb-search-input {
    padding: 6px 12px 6px 34px !important;
    font-size: 13px;
    border: 1px solid var(--gray-300);
    border-radius: 6px;
    width: 220px;
    height: 32px;
    box-sizing: border-box;
    transition: all 0.15s;
}

.sb-search-input:focus {
    outline: none;
    border-color: var(--primary-500);
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* Category Tabs */
.sb-category-tabs {
    display: flex;
    flex-wrap: nowrap;
    gap: 6px;
    padding: 12px 20px;
    background: var(--gray-50);
    border-bottom: 1px solid var(--gray-200);
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: thin;
    scrollbar-color: var(--gray-300) transparent;
}

.sb-category-tabs::-webkit-scrollbar {
    height: 4px;
}

.sb-category-tabs::-webkit-scrollbar-track {
    background: transparent;
}

.sb-category-tabs::-webkit-scrollbar-thumb {
    background: var(--gray-300);
    border-radius: 2px;
}

.sb-category-tab {
    flex-shrink: 0;
    padding: 6px 12px;
    font-size: 12px;
    font-weight: 500;
    color: var(--gray-600);
    background: white;
    border: 1px solid var(--gray-200);
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.15s;
    white-space: nowrap;
}

.sb-category-tab:hover {
    border-color: var(--primary-300);
    color: var(--primary-600);
}

.sb-category-tab.active {
    background: var(--primary-500);
    border-color: var(--primary-500);
    color: white;
}

/* Bulk Actions in Header */
.sb-bulk-actions {
    display: flex;
    gap: 6px;
    flex-shrink: 0;
}

.sb-bulk-btn {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 6px 10px;
    font-size: 12px;
    font-weight: 500;
    color: var(--gray-600);
    background: white;
    border: 1px solid var(--gray-300);
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.15s;
    height: 32px;
    box-sizing: border-box;
}

.sb-bulk-btn:hover {
    background: var(--gray-100);
    border-color: var(--gray-400);
    color: var(--gray-800);
}

.sb-bulk-btn svg {
    flex-shrink: 0;
}

/* Empty State */
.sb-empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
    color: var(--gray-400);
}

.sb-empty-state svg {
    margin-bottom: 16px;
    opacity: 0.5;
}

.sb-empty-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--gray-600);
    margin: 0 0 8px 0;
}

.sb-empty-desc {
    font-size: 13px;
    color: var(--gray-500);
    margin: 0;
}

/* Toast Notification */
.sb-toast {
    position: fixed;
    bottom: 30px;
    right: 30px;
    z-index: 100001;
    animation: sb-toast-slide-in 0.3s ease-out;
}

@keyframes sb-toast-slide-in {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.sb-toast-content {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 14px 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(0, 0, 0, 0.05);
    font-size: 14px;
    font-weight: 500;
    color: var(--gray-800);
}

.sb-toast-icon {
    flex-shrink: 0;
}

.sb-toast-success .sb-toast-icon.sb-toast-success {
    display: block;
    color: #10b981;
}

.sb-toast-success .sb-toast-icon.sb-toast-error {
    display: none;
}

.sb-toast-error .sb-toast-icon.sb-toast-success {
    display: none;
}

.sb-toast-error .sb-toast-icon.sb-toast-error {
    display: block;
    color: #ef4444;
}

.sb-toast-message {
    flex: 1;
}

/* Table Styles */
.sb-table-container {
    max-height: calc(100vh - 400px);
    min-height: 400px;
    overflow-y: auto;
}

.sb-table {
    width: 100%;
    border-collapse: collapse;
}

.sb-table thead {
    position: sticky;
    top: 0;
    background: var(--gray-50);
    z-index: 10;
}

.sb-table th {
    text-align: left;
    padding: 10px 16px;
    font-size: 11px;
    font-weight: 600;
    color: var(--gray-600);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-bottom: 1px solid var(--gray-200);
}

.sb-th-capability { width: 30%; }
.sb-th-description { width: auto; }
.sb-th-enabled { width: 80px; text-align: center !important; }

.sb-cap-row {
    border-bottom: 1px solid var(--gray-200);
    transition: background 0.15s;
}

.sb-cap-row:hover {
    background: var(--gray-50);
}

.sb-cap-row.sb-cap-enabled {
    background: var(--primary-50);
}

.sb-cap-row.sb-cap-enabled:hover {
    background: var(--primary-100);
}

.sb-cap-row.sb-cap-danger-high {
    border-left: 3px solid #dc2626;
}

.sb-cap-row.sb-cap-danger-moderate {
    border-left: 3px solid #f59e0b;
}

.sb-cap-row td {
    padding: 10px 16px;
    vertical-align: middle;
}

.sb-td-enabled {
    text-align: center;
}

/* Capability Name */
.sb-cap-name-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
}

.sb-cap-code {
    font-family: "SF Mono", Monaco, Consolas, monospace;
    font-size: 12px;
    background: var(--gray-100);
    padding: 3px 6px;
    border-radius: 4px;
    color: var(--gray-700);
    font-weight: 500;
}

.sb-cap-enabled .sb-cap-code {
    background: var(--primary-100);
    color: var(--primary-700);
}

/* Danger badges */
.sb-cap-danger-badge {
    display: inline-flex;
    align-items: center;
    cursor: help;
}

.sb-cap-danger-badge.sb-cap-danger-high {
    color: #dc2626;
}

.sb-cap-danger-badge.sb-cap-danger-moderate {
    color: #f59e0b;
}

/* Description */
.sb-cap-description {
    display: block;
    font-size: 13px;
    color: var(--gray-600);
    margin-bottom: 4px;
}

/* Category Badge */
.sb-cap-category-badge {
    display: inline-block;
    padding: 2px 8px;
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    border-radius: 3px;
    background: var(--gray-200);
    color: var(--gray-600);
}

.sb-cap-cat-posts { background: #dbeafe; color: #1e40af; }
.sb-cap-cat-users { background: #fce7f3; color: #9d174d; }
.sb-cap-cat-plugins { background: #f3e8ff; color: #7c3aed; }
.sb-cap-cat-settings { background: #fee2e2; color: #b91c1c; }
.sb-cap-cat-media { background: #d1fae5; color: #047857; }
.sb-cap-cat-comments { background: #fef3c7; color: #b45309; }
.sb-cap-cat-taxonomy { background: #e0e7ff; color: #4338ca; }
.sb-cap-cat-multisite { background: #cffafe; color: #0e7490; }
.sb-cap-cat-woocommerce { background: #ede9fe; color: #6d28d9; }
.sb-cap-cat-other { background: #f3f4f6; color: #6b7280; }

/* Toggle Switch */
.sb-toggle {
    position: relative;
    display: inline-block;
    width: 36px;
    height: 20px;
}

.sb-toggle-input {
    opacity: 0;
    width: 0;
    height: 0;
}

.sb-toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: var(--gray-300);
    transition: 0.2s;
    border-radius: 20px;
}

.sb-toggle-slider:before {
    position: absolute;
    content: "";
    height: 16px;
    width: 16px;
    left: 2px;
    bottom: 2px;
    background-color: white;
    transition: 0.2s;
    border-radius: 50%;
    box-shadow: 0 1px 3px rgba(0,0,0,0.2);
}

.sb-toggle-input:checked + .sb-toggle-slider {
    background-color: var(--primary-500);
}

.sb-toggle-input:checked + .sb-toggle-slider:before {
    transform: translateX(16px);
}

.sb-toggle-input:focus + .sb-toggle-slider {
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
}

/* Button Variants */
.sb-module-button-danger {
    background: #dc2626;
    color: white;
    border-color: #dc2626;
}

.sb-module-button-danger:hover {
    background: #b91c1c;
    border-color: #b91c1c;
}

.sb-module-button-sm {
    padding: 6px 12px;
    font-size: 12px;
}

.sb-module-button-full {
    width: 100%;
    justify-content: center;
}

/* Modal Styles - Role Editor specific */
.sb-role-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100000;
    display: flex;
    align-items: center;
    justify-content: center;
}

.sb-role-modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(2px);
}

.sb-role-modal-content {
    position: relative;
    width: 90%;
    max-width: 500px;
    max-height: 90vh;
    overflow: auto;
    animation: sb-modal-appear 0.2s ease-out;
}

@keyframes sb-modal-appear {
    from {
        opacity: 0;
        transform: scale(0.95) translateY(-10px);
    }
    to {
        opacity: 1;
        transform: scale(1) translateY(0);
    }
}

.sb-role-modal-header {
    position: relative;
}

.sb-role-modal-close {
    position: absolute;
    top: 16px;
    right: 16px;
    background: none;
    border: none;
    padding: 6px;
    cursor: pointer;
    color: var(--gray-400);
    border-radius: 6px;
    transition: all 0.15s;
    display: flex;
    align-items: center;
    justify-content: center;
}

.sb-role-modal-close:hover {
    background: var(--gray-100);
    color: var(--gray-700);
}

.sb-role-modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    background: var(--gray-50);
    border-radius: 0 0 8px 8px;
}

/* Form Styles - using sb-module-* pattern for consistency */
.sb-module-form-group {
    margin-bottom: 20px;
}

.sb-module-form-group:last-child {
    margin-bottom: 0;
}

.sb-module-form-label {
    display: block;
    margin-bottom: 6px;
    font-size: 13px;
    font-weight: 600;
    color: var(--gray-700);
}

.sb-module-required {
    color: #dc2626;
    margin-left: 2px;
}

.sb-module-input,
.sb-module-select {
    width: 100%;
    padding: 10px 12px;
    font-size: 14px;
    border: 1px solid var(--gray-300);
    border-radius: 6px;
    background: white;
    color: var(--gray-800);
    transition: all 0.15s;
}

.sb-module-input:focus,
.sb-module-select:focus {
    outline: none;
    border-color: var(--primary-500);
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.sb-module-input::placeholder {
    color: var(--gray-400);
}

.sb-module-form-help {
    margin: 6px 0 0 0;
    font-size: 12px;
    color: var(--gray-500);
    line-height: 1.4;
}

/* Modal Card Overrides */
.sb-role-modal .sb-module-card {
    margin: 0;
    box-shadow: 0 20px 50px rgba(0, 0, 0, 0.25);
}

.sb-role-modal .sb-module-card-header {
    padding-right: 50px;
}

.sb-role-modal .sb-module-card-body {
    padding: 24px;
}

.sb-role-modal .sb-module-card-footer {
    padding: 16px 24px;
}

/* Modal Mobile Responsive */
@media (max-width: 600px) {
    .sb-role-modal-content {
        width: 95%;
        max-width: none;
        margin: 10px;
    }

    .sb-role-modal .sb-module-card-body {
        padding: 16px;
    }

    .sb-role-modal .sb-module-card-footer {
        padding: 12px 16px;
        flex-direction: column;
    }

    .sb-role-modal .sb-module-card-footer .sb-module-button {
        width: 100%;
        justify-content: center;
    }
}

/* Spinner Animation */
.sb-spin {
    animation: sb-spin 1s linear infinite;
}

@keyframes sb-spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

/* Responsive */
@media (max-width: 1200px) {
    .sb-module-layout {
        grid-template-columns: 260px 1fr;
    }
}

@media (max-width: 960px) {
    .sb-module-layout {
        grid-template-columns: 1fr;
    }

    .sb-module-sidebar {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
    }

}

@media (max-width: 782px) {
    .sb-module-sidebar {
        grid-template-columns: 1fr;
    }

    .sb-card-header-with-actions {
        flex-direction: column;
        align-items: flex-start;
    }

    .sb-card-actions {
        width: 100%;
        flex-direction: column;
    }

    .sb-search-input {
        width: 100%;
    }

    .sb-bulk-actions {
        display: none;
    }

    .sb-th-description,
    .sb-td-description {
        display: none;
    }

    .sb-table-container {
        max-height: 50vh;
    }
}
</style>
