<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DRACS - Dell Rack & Asset Control System</title>
    <link rel="icon" type="image/svg+xml" href="{{ url_for('static', filename='images/dracs.svg') }}">
    <style>
        * {
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        h1 {
            color: #333;
            margin-top: 0;
            border-bottom: 3px solid #007bff;
            padding-bottom: 10px;
        }

        .filters {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 6px;
            margin-bottom: 20px;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }

        .filter-group-left {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
        }

        .filter-group label {
            font-weight: 600;
            margin-bottom: 5px;
            color: #555;
            font-size: 14px;
        }

        .filter-row {
            display: flex;
            gap: 8px;
        }

        .checkbox-row {
            display: flex;
            gap: 15px;
            margin-top: 8px;
            flex-wrap: wrap;
        }

        .checkbox-label {
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 400;
            font-size: 13px;
            color: #555;
            cursor: pointer;
        }

        .checkbox-label input[type="checkbox"] {
            cursor: pointer;
        }

        .warranty-combined-row {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-top: 5px;
            flex-wrap: wrap;
        }

        .warranty-expires-inline {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .warranty-expires-inline label {
            font-weight: 400;
            font-size: 13px;
            color: #555;
            margin: 0;
            white-space: nowrap;
        }

        .warranty-expires-inline select {
            min-width: 100px;
        }

        input[type="text"],
        select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            background-color: #ffffff;
            color: #333;
        }

        input[type="text"]::placeholder {
            color: #999;
        }

        input[type="text"]:focus,
        select:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
        }

        select {
            flex: 1;
        }

        select.operator {
            flex: 0 0 70px;
        }

        select[multiple] {
            min-height: 100px;
            padding: 4px;
        }

        select[multiple] option {
            padding: 6px 8px;
            margin: 2px 0;
            border-radius: 3px;
        }

        select[multiple] option:checked {
            background: linear-gradient(#007bff, #007bff);
            color: white;
        }

        .results-info {
            margin-bottom: 15px;
            color: #666;
            font-size: 14px;
        }

        .select-all-btn {
            padding: 6px 12px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: background-color 0.2s;
        }

        .select-all-btn:hover {
            background-color: #218838;
        }

        .select-all-btn:active {
            background-color: #1e7e34;
        }

        .select-shown-btn {
            padding: 6px 12px;
            background-color: #17a2b8;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: background-color 0.2s;
            margin-left: 10px;
        }

        .select-shown-btn:hover {
            background-color: #138496;
        }

        .select-shown-btn:active {
            background-color: #117a8b;
        }

        .custom-filter-buttons {
            display: flex;
            flex-direction: row;
            gap: 8px;
            align-items: center;
            flex-wrap: wrap;
        }

        .custom-filter-btn, .clear-filter-btn, .clear-all-btn {
            padding: 8px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.2s;
            white-space: nowrap;
        }

        .custom-filter-btn {
            background-color: #007bff;
            color: white;
        }

        .custom-filter-btn:hover {
            background-color: #0056b3;
        }

        .clear-filter-btn {
            background-color: #ffc107;
            color: #333;
        }

        .clear-filter-btn:hover {
            background-color: #e0a800;
        }

        .clear-all-btn {
            background-color: #dc3545;
            color: white;
        }

        .clear-all-btn:hover {
            background-color: #c82333;
        }

        #custom-filter-textarea, #discover-textarea {
            width: 100%;
            min-height: 200px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: monospace;
            font-size: 13px;
            resize: vertical;
        }

        .table-scroll-container {
            max-height: 60vh;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 0;
        }

        thead {
            background-color: #007bff;
            color: white;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        th {
            padding: 12px;
            text-align: left;
            font-weight: 600;
            border-bottom: 2px solid #0056b3;
        }

        td {
            padding: 10px 12px;
            border-bottom: 1px solid #eee;
        }

        /* Right-align warranty expiration date column */
        th:nth-child(6),
        td:nth-child(6) {
            text-align: right;
        }

        tbody tr:hover {
            background-color: #f8f9fa;
        }

        tbody tr.hidden {
            display: none;
        }

        /* Warranty expiration highlighting */
        /* Warranty expiration highlighting - cell only (not entire row) */
        td.warranty-expired {
            background-color: #ffcccc !important;  /* Light red */
        }

        td.warranty-expiring {
            background-color: #ffffcc !important;  /* Light yellow */
        }

        /* Firmware and BIOS version highlighting */
        td.firmware-outdated-1 {
            background-color: #ffffcc !important;  /* Light yellow - 1 version behind */
        }

        td.firmware-outdated-2plus {
            background-color: #ffcccc !important;  /* Light red - 2+ versions behind */
        }

        td.bios-outdated-1 {
            background-color: #ffffcc !important;  /* Light yellow - 1 version behind */
        }

        td.bios-outdated-2plus {
            background-color: #ffcccc !important;  /* Light red - 2+ versions behind */
        }

        .no-results {
            text-align: center;
            padding: 40px;
            color: #999;
            font-size: 16px;
        }

        /* Pagination controls */
        .pagination-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
            padding: 15px 0;
            border-top: 1px solid #ddd;
        }

        .pagination-controls {
            display: flex;
            gap: 5px;
            align-items: center;
        }

        .pagination-controls button {
            padding: 6px 12px;
            border: 1px solid #ddd;
            background-color: white;
            color: #333;
            cursor: pointer;
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.2s;
        }

        .pagination-controls button:hover:not(:disabled) {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }

        .pagination-controls button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .pagination-controls button.active {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
            font-weight: 600;
        }

        .pagination-arrow {
            font-weight: bold;
        }

        .page-size-selector {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .page-size-selector label {
            font-size: 14px;
            color: #555;
            font-weight: 600;
        }

        .page-size-selector select {
            padding: 6px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            background-color: white;
            cursor: pointer;
        }

        @media (max-width: 1024px) {
            .filters {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            table {
                font-size: 12px;
            }

            th, td {
                padding: 8px 6px;
            }
        }

        /* Header with login link */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .logo {
            height: 48px;
            width: auto;
        }

        .auth-section {
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .login-link, .logout-link {
            color: #007bff;
            text-decoration: none;
            font-size: 14px;
            cursor: pointer;
            padding: 6px 12px;
            border: 1px solid #007bff;
            border-radius: 4px;
            transition: all 0.2s;
        }

        .login-link:hover, .logout-link:hover {
            background-color: #007bff;
            color: white;
        }

        .username-display {
            font-size: 14px;
            color: #666;
        }

        /* Modal overlay */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-overlay.active {
            display: flex;
        }

        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            width: 90%;
            max-width: 400px;
        }

        .modal-large {
            max-width: 1000px;
        }

        #job-queue-table-container {
            max-height: 500px;
            overflow-y: auto;
        }

        #job-queue-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }

        #job-queue-table th,
        #job-queue-table td {
            padding: 8px;
            text-align: left;
            border: 1px solid #ddd;
        }

        #job-queue-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            position: sticky;
            top: 0;
            z-index: 1;
        }

        #job-queue-table tbody tr:hover {
            background-color: #f8f9fa;
        }

        .modal-header {
            margin-bottom: 20px;
        }

        .modal-header h2 {
            margin: 0;
            color: #333;
        }

        .modal-body {
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #555;
        }

        .form-group input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .modal-footer {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        .firmware-log {
            font-family: monospace;
            font-size: 13px;
            white-space: pre-wrap;
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 12px;
            max-height: 400px;
            overflow-y: auto;
        }

        .tsr-progress-bar {
            width: 100%;
            height: 20px;
            background-color: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
            margin-top: 8px;
        }

        .tsr-progress-fill {
            height: 100%;
            background-color: #007bff;
            transition: width 0.5s ease;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
        }

        .btn-primary {
            background-color: #007bff;
            color: white;
        }

        .btn-primary:hover {
            background-color: #0056b3;
        }

        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #545b62;
        }

        .btn-success {
            background-color: #28a745;
            color: white;
        }

        .btn-success:hover {
            background-color: #218838;
        }

        .btn-success:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }

        .btn-primary:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }

        .btn-power-on {
            background-color: #28a745;
            color: white;
        }

        .btn-power-on:hover {
            background-color: #218838;
        }

        .btn-power-off {
            background-color: #dc3545;
            color: white;
        }

        .btn-power-off:hover {
            background-color: #c82333;
        }

        .btn-force {
            background-color: #dc3545;
            color: white;
        }

        .btn-force:hover {
            background-color: #c82333;
        }

        .btn-force:disabled {
            background-color: #6c757d;
            color: white;
            cursor: not-allowed;
        }

        .btn-reboot-graceful {
            background-color: #fd7e14;
            color: white;
        }

        .btn-reboot-graceful:hover {
            background-color: #e8690b;
        }

        .btn-reboot-hard {
            background-color: #e83e8c;
            color: white;
        }

        .btn-reboot-hard:hover {
            background-color: #d63384;
        }

        /* Row selection */
        tbody tr {
            cursor: pointer;
        }

        tbody tr, tbody tr * {
            user-select: none;  /* Prevent text selection when shift-clicking for range select */
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
        }

        tbody tr.selected {
            background-color: #cce5ff !important;
            font-weight: 500;
        }

        /* Admin actions container */
        .admin-actions {
            margin-bottom: 15px;
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .firmware-update-container, .bios-update-container, .job-queue-container, .clear-job-queue-container {
            position: relative;
            display: inline-block;
        }

        .firmware-version-select, .bios-version-select {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            background-color: #007bff;
            color: white;
            transition: all 0.2s;
        }

        .firmware-version-select:hover, .bios-version-select:hover {
            background-color: #0056b3;
        }

        .firmware-version-select:disabled, .bios-version-select:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }

        #update-bios-btn.unavailable {
            background-color: #6c757d;
            cursor: not-allowed;
            padding: 8px 16px;
            line-height: 1.2;
        }

        #update-bios-btn.unavailable .subtitle {
            display: block;
            font-size: 11px;
            font-weight: normal;
            margin-top: 2px;
            opacity: 0.8;
        }

        /* Notification message */
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            z-index: 2000;
            display: none;
            max-width: 400px;
        }

        .notification.active {
            display: block;
        }

        .notification.success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .notification.error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        .notification .close-btn {
            float: right;
            margin-left: 15px;
            font-size: 20px;
            font-weight: bold;
            cursor: pointer;
            color: inherit;
            opacity: 0.5;
        }

        .notification .close-btn:hover {
            opacity: 1;
        }

        /* Firmware confirmation modal styling */
        .firmware-details {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            margin: 15px 0;
        }

        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #e9ecef;
        }

        .detail-row:last-child {
            border-bottom: none;
        }

        .detail-label {
            font-weight: 600;
            color: #555;
        }

        .detail-value {
            color: #333;
            font-family: monospace;
        }

        .firmware-warning {
            margin-top: 15px;
            font-weight: 500;
            color: #333;
            text-align: center;
        }

        /* Theme Toggle */
        .theme-toggle {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-left: 20px;
        }

        .theme-toggle label {
            font-size: 14px;
            color: #555;
            font-weight: 500;
        }

        .toggle-switch {
            position: relative;
            width: 50px;
            height: 24px;
            background-color: #ccc;
            border-radius: 12px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .toggle-switch::after {
            content: '';
            position: absolute;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-color: white;
            top: 2px;
            left: 2px;
            transition: transform 0.3s;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }

        .toggle-switch.active {
            background-color: #007bff;
        }

        .toggle-switch.active::after {
            transform: translateX(26px);
        }

        /* Dark Theme Styles */
        body.dark-theme {
            background-color: #1a1a1a;
        }

        body.dark-theme .container {
            background-color: #2d2d2d;
            color: #e0e0e0;
        }

        body.dark-theme h1 {
            color: #e0e0e0;
            border-bottom-color: #007bff;
        }

        body.dark-theme .filters {
            background-color: #3a3a3a;
        }

        body.dark-theme .filter-group label {
            color: #b0b0b0;
        }

        body.dark-theme .checkbox-label {
            color: #b0b0b0;
        }

        body.dark-theme .warranty-expires-inline label {
            color: #b0b0b0;
        }

        body.dark-theme input[type="text"],
        body.dark-theme select {
            background-color: #4a4a4a;
            color: #e0e0e0;
            border-color: #555;
        }

        body.dark-theme input[type="text"]:focus,
        body.dark-theme select:focus {
            border-color: #007bff;
            background-color: #3a3a3a;
        }

        body.dark-theme input[type="text"]::placeholder {
            color: #777;
        }

        body.dark-theme select[multiple] option:checked {
            background: linear-gradient(#007bff, #007bff);
        }

        body.dark-theme .results-info {
            color: #b0b0b0;
        }

        body.dark-theme .select-all-btn {
            background-color: #1e7e34;
        }

        body.dark-theme .select-all-btn:hover {
            background-color: #28a745;
        }

        body.dark-theme .select-all-btn:active {
            background-color: #218838;
        }

        body.dark-theme .select-shown-btn {
            background-color: #138496;
        }

        body.dark-theme .select-shown-btn:hover {
            background-color: #117a8b;
        }

        body.dark-theme .select-shown-btn:active {
            background-color: #10707f;
        }

        body.dark-theme .custom-filter-btn {
            background-color: #0056b3;
        }

        body.dark-theme .custom-filter-btn:hover {
            background-color: #004494;
        }

        body.dark-theme .clear-filter-btn {
            background-color: #e0a800;
            color: #222;
        }

        body.dark-theme .clear-filter-btn:hover {
            background-color: #c69500;
        }

        body.dark-theme .clear-all-btn {
            background-color: #c82333;
        }

        body.dark-theme .clear-all-btn:hover {
            background-color: #bd2130;
        }

        body.dark-theme #custom-filter-textarea, body.dark-theme #discover-textarea {
            background-color: #333;
            color: #e0e0e0;
            border-color: #555;
        }

        body.dark-theme .table-scroll-container {
            border-color: #555;
        }

        body.dark-theme thead {
            background-color: #1e5a8e;
        }

        body.dark-theme th {
            border-bottom-color: #003d5c;
        }

        body.dark-theme td {
            border-bottom-color: #444;
        }

        body.dark-theme tbody tr:hover {
            background-color: #3a3a3a;
        }

        body.dark-theme tbody tr.selected {
            background-color: #2a6ba8 !important;  /* Slightly lighter than header blue (#1e5a8e) */
        }

        body.dark-theme .no-results {
            color: #888;
        }

        body.dark-theme .theme-toggle label {
            color: #b0b0b0;
        }

        body.dark-theme .auth-section {
            color: #e0e0e0;
        }

        body.dark-theme .login-link,
        body.dark-theme .logout-link {
            color: #4da3ff;
        }

        body.dark-theme .login-link:hover,
        body.dark-theme .logout-link:hover {
            color: #66b3ff;
        }

        body.dark-theme .btn {
            background-color: #1e5a8e;
            color: #e0e0e0;
            border-color: #1e5a8e;
        }

        body.dark-theme .btn:hover:not(:disabled) {
            background-color: #2a6ba8;
        }

        body.dark-theme .btn-secondary {
            background-color: #555;
            border-color: #555;
        }

        body.dark-theme .btn-secondary:hover {
            background-color: #666;
        }

        body.dark-theme .btn-primary:disabled {
            background-color: #555;
            border-color: #555;
        }

        body.dark-theme .btn-success {
            background-color: #1e7e34;
            border-color: #1e7e34;
        }

        body.dark-theme .btn-success:hover:not(:disabled) {
            background-color: #28a745;
        }

        body.dark-theme .btn-success:disabled {
            background-color: #555;
            border-color: #555;
        }

        body.dark-theme .btn-power-on {
            background-color: #1e7e34;
            border-color: #1e7e34;
        }

        body.dark-theme .btn-power-on:hover {
            background-color: #28a745;
        }

        body.dark-theme .btn-power-off {
            background-color: #c82333;
            border-color: #c82333;
        }

        body.dark-theme .btn-power-off:hover {
            background-color: #dc3545;
        }

        body.dark-theme .btn-force {
            background-color: #c82333;
            border-color: #c82333;
        }

        body.dark-theme .btn-force:hover {
            background-color: #dc3545;
        }

        body.dark-theme .btn-force:disabled {
            background-color: #495057;
            border-color: #495057;
        }

        body.dark-theme .btn-reboot-graceful {
            background-color: #e8690b;
            border-color: #e8690b;
        }

        body.dark-theme .btn-reboot-graceful:hover {
            background-color: #fd7e14;
        }

        body.dark-theme .btn-reboot-hard {
            background-color: #d63384;
            border-color: #d63384;
        }

        body.dark-theme .btn-reboot-hard:hover {
            background-color: #e83e8c;
        }

        body.dark-theme .firmware-version-select,
        body.dark-theme .bios-version-select {
            background-color: #1e5a8e;
            color: #e0e0e0;
            border-color: #1e5a8e;
        }

        body.dark-theme .firmware-version-select:hover,
        body.dark-theme .bios-version-select:hover {
            background-color: #2a6ba8;
        }

        body.dark-theme .firmware-version-select:disabled,
        body.dark-theme .bios-version-select:disabled {
            background-color: #555;
            border-color: #555;
        }

        body.dark-theme #update-bios-btn.unavailable {
            background-color: #555;
            border-color: #555;
        }

        body.dark-theme .modal-overlay {
            background-color: rgba(0, 0, 0, 0.8);
        }

        body.dark-theme .modal-content {
            background-color: #2d2d2d;
            color: #e0e0e0;
        }

        body.dark-theme .modal-header {
            border-bottom-color: #444;
        }

        body.dark-theme .modal-header h2 {
            color: #e0e0e0;
        }

        body.dark-theme .modal-footer {
            border-top-color: #444;
        }

        body.dark-theme #job-queue-table th {
            background-color: #3a3a3a;
            color: #e0e0e0;
            border-color: #555;
        }

        body.dark-theme #job-queue-table td {
            border-color: #555;
            color: #e0e0e0;
        }

        body.dark-theme #job-queue-table tbody tr:hover {
            background-color: #3a3a3a;
        }

        body.dark-theme .form-group label {
            color: #b0b0b0;
        }

        body.dark-theme input[type="text"],
        body.dark-theme input[type="password"] {
            background-color: #4a4a4a;
            color: #e0e0e0;
            border-color: #555;
        }

        body.dark-theme .notification {
            background-color: #2d2d2d;
            border-color: #555;
        }

        body.dark-theme .notification.success {
            background-color: #1e4d2b;
            border-color: #2d7a3e;
            color: #90ee90;
        }

        body.dark-theme .notification.error {
            background-color: #5c1e1e;
            border-color: #8a2e2e;
            color: #ff6b6b;
        }

        body.dark-theme .admin-actions {
            background-color: transparent;
        }

        body.dark-theme .pagination-container {
            border-top-color: #444;
        }

        body.dark-theme .pagination-controls button {
            background-color: #4a4a4a;
            color: #e0e0e0;
            border-color: #555;
        }

        body.dark-theme .pagination-controls button:hover:not(:disabled) {
            background-color: #1e5a8e;
            border-color: #1e5a8e;
        }

        body.dark-theme .pagination-controls button.active {
            background-color: #1e5a8e;
            border-color: #1e5a8e;
        }

        body.dark-theme .page-size-selector label {
            color: #b0b0b0;
        }

        body.dark-theme .page-size-selector select {
            background-color: #4a4a4a;
            color: #e0e0e0;
            border-color: #555;
        }

        body.dark-theme .modal-body {
            color: #e0e0e0;
        }

        body.dark-theme .firmware-log {
            background-color: #1a1a1a;
            border-color: #555;
            color: #e0e0e0;
        }

        body.dark-theme .tsr-progress-bar {
            background-color: #3a3a3a;
        }

        body.dark-theme .tsr-progress-fill {
            background-color: #1e5a8e;
        }

        body.dark-theme .firmware-details {
            background-color: #3a3a3a;
        }

        body.dark-theme .detail-row {
            border-bottom-color: #555;
        }

        body.dark-theme .detail-label {
            color: #b0b0b0;
        }

        body.dark-theme .detail-value {
            color: #e0e0e0;
        }

        body.dark-theme #firmware-new-version,
        body.dark-theme #bios-new-version {
            color: #4da3ff !important;
        }

        body.dark-theme .firmware-warning {
            color: #b0b0b0;
        }

        /* Dark theme highlight colors - darker shades for visibility with light text */
        body.dark-theme td.warranty-expired {
            background-color: #660000 !important;  /* Dark red */
        }

        body.dark-theme td.warranty-expiring {
            background-color: #665500 !important;  /* Dark amber/yellow */
        }

        body.dark-theme td.firmware-outdated-1 {
            background-color: #665500 !important;  /* Dark amber/yellow */
        }

        body.dark-theme td.firmware-outdated-2plus {
            background-color: #660000 !important;  /* Dark red */
        }

        body.dark-theme td.bios-outdated-1 {
            background-color: #665500 !important;  /* Dark amber/yellow */
        }

        body.dark-theme td.bios-outdated-2plus {
            background-color: #660000 !important;  /* Dark red */
        }

        /* Context Menu */
        .context-menu {
            position: fixed;
            background-color: white;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            padding: 5px 0;
            z-index: 10000;
            display: none;
            min-width: 120px;
        }

        .context-menu-item {
            padding: 8px 16px;
            cursor: pointer;
            font-size: 14px;
            color: #333;
        }

        .context-menu-item:hover {
            background-color: #007bff;
            color: white;
        }

        body.dark-theme .context-menu {
            background-color: #2b2b2b;
            border-color: #444;
        }

        body.dark-theme .context-menu-item {
            color: #e0e0e0;
        }

        body.dark-theme .context-menu-item:hover {
            background-color: #0056b3;
        }

        /* Make table cells user-selectable for better UX */
        #systems-table td {
            user-select: text;
            cursor: text;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-left">
                <img src="{{ url_for('static', filename='images/dracs.svg') }}" alt="DRACS Logo" class="logo">
                <h1 style="margin: 0; border: none; padding: 0;">DRACS Inventory</h1>
                <div class="theme-toggle">
                    <label for="theme-toggle-switch">Dark Mode</label>
                    <div id="theme-toggle-switch" class="toggle-switch" onclick="toggleTheme()"></div>
                </div>
            </div>
            <div class="auth-section">
                <select id="site-select" onchange="switchSite(this.value)" style="margin-right: 4px; padding: 4px 8px; border-radius: 4px; border: 1px solid #ccc;">
                    {% for site in all_sites %}
                    <option value="{{ site }}" {% if site == current_site %}selected{% endif %}>{{ site }}</option>
                    {% endfor %}
                </select>
                {% if is_superadmin %}
                <a href="/sites?site={{ current_site }}" class="logout-link" style="margin-right: 8px;" title="Site Management">&#9881;</a>
                {% endif %}
                {% if is_authenticated %}
                    <span class="username-display">Logged in as <strong>{{ username }}</strong> ({{ user_role }})</span>
                    {% if user_role == 'admin' %}
                    <a href="/users?site={{ current_site }}" class="logout-link" style="margin-right: 8px;">Users</a>
                    {% endif %}
                    <a href="#" class="logout-link" onclick="showSelfPasswordModal(event)" style="margin-right: 8px;">Password</a>
                    <a href="#" class="logout-link" onclick="handleLogout(event)">Logout</a>
                {% else %}
                    <a href="#" class="login-link" onclick="showLoginModal(event)">Login</a>
                {% endif %}
            </div>
        </div>

        <div class="filters">
            <div class="filter-group-left">
                <div class="filter-group">
                    <label for="hostname-filter">Hostname Filter</label>
                    <input type="text" id="hostname-filter" placeholder="Type to filter by hostname...">
                </div>

                <div class="filter-group">
                    <label for="servicetag-filter">Service Tag Filter</label>
                    <input type="text" id="servicetag-filter" placeholder="Type to filter by service tag...">
                </div>

                <div class="filter-group">
                    <label>Warranty Filters</label>
                    <div class="warranty-combined-row">
                        <label class="checkbox-label">
                            <input type="checkbox" id="warranty-expired">
                            Warranty Expired
                        </label>
                        <div class="warranty-expires-inline">
                            <label for="warranty-expires">Expires in</label>
                            <select id="warranty-expires">
                                <option value="">(none)</option>
                                <option value="30">30 days</option>
                                <option value="60">60 days</option>
                                <option value="90">90 days</option>
                                <option value="180">180 days</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="filter-group">
                    <label>Custom Filters</label>
                    <div class="custom-filter-buttons">
                        <button class="custom-filter-btn" onclick="showCustomFilterModal()">Custom Filter</button>
                        <button class="clear-filter-btn" onclick="clearCustomFilter()">Clear Filter</button>
                        <button class="clear-all-btn" onclick="clearAllFilters()">Clear All</button>
                    </div>
                </div>
            </div>

            <div class="filter-group">
                <label for="model-filter">Host Types (Ctrl+Click for multiple)</label>
                <select id="model-filter" multiple>
                    <!-- Options will be populated by JavaScript -->
                </select>
            </div>

            <div class="filter-group">
                <label>Firmware Version</label>
                <div class="filter-row">
                    <select id="firmware-version">
                        <option value="">(all versions)</option>
                    </select>
                    <select id="firmware-operator" class="operator">
                        <option value="">(none)</option>
                        <option value="<=">&lt;=</option>
                        <option value="<">&lt;</option>
                        <option value=">=">>=</option>
                        <option value=">">&gt;</option>
                        <option value="=">=</option>
                    </select>
                </div>
                <div class="checkbox-row">
                    <label class="checkbox-label">
                        <input type="checkbox" id="firmware-current">
                        Current Firmware
                    </label>
                    <label class="checkbox-label">
                        <input type="checkbox" id="firmware-older">
                        Older Firmware
                    </label>
                    <label class="checkbox-label">
                        <input type="checkbox" id="firmware-oldest">
                        Oldest Firmware
                    </label>
                </div>
            </div>

            <div class="filter-group">
                <label>BIOS Version</label>
                <div class="filter-row">
                    <select id="bios-version">
                        <option value="">(all versions)</option>
                    </select>
                    <select id="bios-operator" class="operator">
                        <option value="">(none)</option>
                        <option value="<=">&lt;=</option>
                        <option value="<">&lt;</option>
                        <option value=">=">>=</option>
                        <option value=">">&gt;</option>
                        <option value="=">=</option>
                    </select>
                </div>
                <div class="checkbox-row">
                    <label class="checkbox-label">
                        <input type="checkbox" id="bios-current">
                        Current BIOS
                    </label>
                    <label class="checkbox-label">
                        <input type="checkbox" id="bios-older">
                        Older BIOS
                    </label>
                    <label class="checkbox-label">
                        <input type="checkbox" id="bios-oldest">
                        Oldest BIOS
                    </label>
                </div>
            </div>
        </div>

        {% if user_role == 'admin' %}
        <div class="admin-actions">
            <button id="discover-btn" class="btn btn-success" onclick="showDiscoverModal()" style="background-color: #28a745;">
                Discover
            </button>
            <button id="delete-btn" class="btn" onclick="showDeleteModal()" disabled style="background-color: #dc3545; color: white;">
                Delete
            </button>
            <button id="refresh-btn" class="btn btn-success" onclick="handleRefreshSelected()" disabled>
                Refresh Selected (<span id="selected-count">0</span>)
            </button>
            <button id="refresh-all-btn" class="btn btn-success" onclick="handleRefreshAll()">
                Refresh All Systems
            </button>
            <div class="firmware-update-container">
                <button id="update-firmware-btn" class="btn btn-primary" disabled>
                    Update Firmware
                </button>
                <select id="firmware-version-select" class="firmware-version-select" style="display: none;" onchange="handleFirmwareVersionSelect(event)">
                    <option value="">Select firmware version...</option>
                </select>
            </div>
            <div class="bios-update-container">
                <button id="update-bios-btn" class="btn btn-primary" disabled>
                    Update BIOS
                </button>
                <select id="bios-version-select" class="bios-version-select" style="display: none;" onchange="handleBiosVersionSelect(event)">
                    <option value="">Select BIOS version...</option>
                </select>
            </div>
            <div class="job-queue-container">
                <button id="job-queue-btn" class="btn btn-primary" disabled onclick="handleJobQueueClick()">
                    Job Queue
                </button>
            </div>
            <div class="clear-job-queue-container">
                <button id="clear-job-queue-btn" class="btn btn-primary" disabled onclick="handleClearJobQueueClick()">
                    Clear Job Queue
                </button>
            </div>
        </div>
        {% endif %}

        {% if user_role == 'admin' %}
        <div style="margin-bottom: 10px;">
            {% if vnc_enabled %}
            <button id="console-btn" class="btn btn-primary" disabled onclick="handleConsoleClick()">
                Console
            </button>
            {% endif %}
            <button id="power-btn" class="btn btn-primary" disabled onclick="handlePowerClick()">
                Power
            </button>
            <button id="latest-firmware-btn" class="btn btn-primary" disabled onclick="handleLatestFirmwareClick()">
                Latest Firmware
            </button>
            <button id="latest-bios-btn" class="btn btn-primary" disabled onclick="handleLatestBiosClick()">
                Latest BIOS
            </button>
            <button id="force-firmware-btn" class="btn btn-force" disabled onclick="handleForceFirmwareClick()">
                Force Firmware
            </button>
            <button id="force-bios-btn" class="btn btn-force" disabled onclick="handleForceBiosClick()">
                Force BIOS
            </button>
            <button id="generate-tsr-btn" class="btn btn-primary" disabled onclick="handleGenerateTsrClick()">
                Generate TSR
            </button>
            <button id="view-tsr-btn" class="btn btn-primary" disabled onclick="handleViewTsrClick()">
                View TSRs
            </button>
        </div>
        {% elif user_role == 'user' %}
        <div style="margin-bottom: 10px;">
            {% if vnc_enabled %}
            <button id="console-btn" class="btn btn-primary" disabled onclick="handleConsoleClick()">
                Console
            </button>
            {% endif %}
            <button id="generate-tsr-btn" class="btn btn-primary" disabled onclick="handleGenerateTsrClick()">
                Generate TSR
            </button>
            <button id="view-tsr-btn" class="btn btn-primary" disabled onclick="handleViewTsrClick()">
                View TSRs
            </button>
            <div class="job-queue-container" style="display: inline-block;">
                <button id="job-queue-btn" class="btn btn-primary" disabled onclick="handleJobQueueClick()">
                    Job Queue
                </button>
            </div>
        </div>
        {% else %}
        <div style="margin-bottom: 10px;">
            <button id="view-tsr-btn" class="btn btn-primary" disabled onclick="handleViewTsrClick()">
                View TSRs
            </button>
        </div>
        {% endif %}

        {% if is_authenticated %}
        <div style="margin-bottom: 10px;">
            <button id="select-all-btn" class="select-all-btn" onclick="toggleSelectAll()">Select All</button>
            <button id="select-shown-btn" class="select-shown-btn" onclick="selectShown()">Select Shown</button>
        </div>
        {% endif %}

        <div class="results-info">
            Showing <span id="results-count">0</span> of <span id="total-count">0</span> systems
        </div>

        <!-- Scrollable table container -->
        <div class="table-scroll-container">
            <table id="systems-table">
                <thead>
                    <tr>
                        <th>Service Tag</th>
                        <th>Hostname</th>
                        <th>Model</th>
                        <th>Firmware</th>
                        <th>BIOS</th>
                        <th>Warranty Expiration Date</th>
                    </tr>
                </thead>
                <tbody id="table-body">
                    <!-- Rows will be populated by JavaScript -->
                </tbody>
            </table>

            <div id="no-results" class="no-results" style="display: none;">
                No systems match your filters
            </div>
        </div>

        <!-- Pagination Controls -->
        <div id="pagination-container" class="pagination-container">
            <div class="pagination-controls">
                <button id="prev-page" class="pagination-arrow" onclick="goToPreviousPage()">&laquo; Previous</button>
                <div id="page-numbers"></div>
                <button id="next-page" class="pagination-arrow" onclick="goToNextPage()">Next &raquo;</button>
            </div>
            <div class="page-size-selector">
                <label for="page-size">Show:</label>
                <select id="page-size" onchange="handlePageSizeChange(event)">
                    <option value="20">20</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                    <option value="500">500</option>
                    <option value="1000">1000</option>
                    <option value="-1">ALL</option>
                </select>
            </div>
        </div>

        <!-- Login Modal -->
        <div id="login-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Admin Login</h2>
                </div>
                <div class="modal-body">
                    <form id="login-form" onsubmit="handleLogin(event)">
                        <div class="form-group">
                            <label for="username">Username</label>
                            <input type="text" id="username" name="username" required autocomplete="username">
                        </div>
                        <div class="form-group">
                            <label for="password">Password</label>
                            <input type="password" id="password" name="password" required autocomplete="current-password">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="hideLoginModal()">Cancel</button>
                    <button type="submit" form="login-form" class="btn btn-primary">Login</button>
                </div>
            </div>
        </div>

        {% if user_role == 'admin' %}
        <div id="user-management-modal" class="modal-overlay">
            <div class="modal-content" style="max-width: 700px;">
                <div class="modal-header">
                    <h2>User Management</h2>
                </div>
                <div class="modal-body">
                    <div id="user-list-container">
                        <table id="user-table" style="width: 100%; border-collapse: collapse; margin-bottom: 16px;">
                            <thead>
                                <tr>
                                    <th style="text-align: left; padding: 6px; border-bottom: 2px solid #ccc;">Username</th>
                                    <th style="text-align: left; padding: 6px; border-bottom: 2px solid #ccc;">Role</th>
                                    <th style="text-align: left; padding: 6px; border-bottom: 2px solid #ccc;">Created</th>
                                    <th style="text-align: center; padding: 6px; border-bottom: 2px solid #ccc;">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="user-table-body"></tbody>
                        </table>
                    </div>
                    <hr style="margin: 12px 0;">
                    <h3 style="margin: 8px 0;">Add User</h3>
                    <form id="add-user-form" onsubmit="handleAddUser(event)">
                        <div style="display: flex; gap: 8px; align-items: flex-end; flex-wrap: wrap;">
                            <div class="form-group" style="margin-bottom: 0;">
                                <label for="new-username">Username</label>
                                <input type="text" id="new-username" required minlength="3" maxlength="32" pattern="[a-zA-Z0-9_-]+" autocomplete="off">
                            </div>
                            <div class="form-group" style="margin-bottom: 0;">
                                <label for="new-password">Password</label>
                                <input type="password" id="new-password" required autocomplete="new-password">
                            </div>
                            <div class="form-group" style="margin-bottom: 0;">
                                <label for="new-confirm-password">Confirm</label>
                                <input type="password" id="new-confirm-password" required autocomplete="new-password">
                            </div>
                            <div class="form-group" style="margin-bottom: 0;">
                                <label for="new-role">Role</label>
                                <select id="new-role">
                                    <option value="user">user</option>
                                    <option value="admin">admin</option>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-primary" style="height: 34px;">Add</button>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="hideUserManagementModal()">Close</button>
                </div>
            </div>
        </div>

        <div id="change-password-modal" class="modal-overlay">
            <div class="modal-content" style="max-width: 400px;">
                <div class="modal-header">
                    <h2>Change Password</h2>
                </div>
                <div class="modal-body">
                    <p>Changing password for <strong id="cp-username-display"></strong></p>
                    <form id="change-password-form" onsubmit="submitChangePassword(event)">
                        <input type="hidden" id="cp-username">
                        <div class="form-group">
                            <label for="cp-new-password">New Password</label>
                            <input type="password" id="cp-new-password" required autocomplete="new-password">
                        </div>
                        <div class="form-group">
                            <label for="cp-confirm-password">Confirm Password</label>
                            <input type="password" id="cp-confirm-password" required autocomplete="new-password">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="hideChangePasswordModal()">Cancel</button>
                    <button type="submit" form="change-password-form" class="btn btn-primary">Change Password</button>
                </div>
            </div>
        </div>
        {% endif %}

        {% if is_authenticated %}
        <div id="self-password-modal" class="modal-overlay">
            <div class="modal-content" style="max-width: 400px;">
                <div class="modal-header">
                    <h2>Change Your Password</h2>
                </div>
                <div class="modal-body">
                    <form id="self-password-form" onsubmit="submitSelfPasswordChange(event)">
                        <div class="form-group">
                            <label for="sp-current-password">Current Password</label>
                            <input type="password" id="sp-current-password" required autocomplete="current-password">
                        </div>
                        <div class="form-group">
                            <label for="sp-new-password">New Password</label>
                            <input type="password" id="sp-new-password" required autocomplete="new-password">
                        </div>
                        <div class="form-group">
                            <label for="sp-confirm-password">Confirm New Password</label>
                            <input type="password" id="sp-confirm-password" required autocomplete="new-password">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="hideSelfPasswordModal()">Cancel</button>
                    <button type="submit" form="self-password-form" class="btn btn-primary">Change Password</button>
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Notification -->
        <div id="notification" class="notification">
            <span class="close-btn" onclick="hideNotification()">&times;</span>
            <span id="notification-message"></span>
        </div>

        <!-- Firmware Update Confirmation Modal -->
        <div id="firmware-confirm-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Confirm Firmware Update</h2>
                </div>
                <div class="modal-body">
                    <p id="firmware-confirm-message"></p>
                    <div class="firmware-details">
                        <div class="detail-row">
                            <span class="detail-label">Host:</span>
                            <span id="firmware-hostname" class="detail-value"></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">Current Version:</span>
                            <span id="firmware-current-version" class="detail-value"></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">New Version:</span>
                            <span id="firmware-new-version" class="detail-value" style="font-weight: 600; color: #007bff;"></span>
                        </div>
                    </div>
                    <p class="firmware-warning">Are you sure you want to proceed with this firmware update?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelFirmwareUpdate()">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="confirmFirmwareUpdate()">Yes, Update Firmware</button>
                </div>
            </div>
        </div>

        <!-- BIOS Update Confirmation Modal -->
        <div id="bios-confirm-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Confirm BIOS Update</h2>
                </div>
                <div class="modal-body">
                    <p id="bios-confirm-message"></p>
                    <div class="firmware-details">
                        <div class="detail-row">
                            <span class="detail-label">Host:</span>
                            <span id="bios-hostname" class="detail-value"></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">Current Version:</span>
                            <span id="bios-current-version" class="detail-value"></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">New Version:</span>
                            <span id="bios-new-version" class="detail-value" style="font-weight: 600; color: #007bff;"></span>
                        </div>
                    </div>
                    <p class="firmware-warning">Are you sure you want to proceed with this BIOS update?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelBiosUpdate()">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="confirmBiosUpdate()">Yes, Update BIOS</button>
                </div>
            </div>
        </div>

        <!-- Force Firmware Modal -->
        <div id="force-firmware-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Force Firmware Update</h2>
                </div>
                <div class="modal-body" id="force-firmware-body">
                    <p style="color: #dc3545; font-weight: bold;">WARNING!  Use this option with caution!  Do not power off the system during this process.</p>
                    <p>Host: <strong id="force-firmware-hostname"></strong></p>
                    <p>Current Firmware: <strong id="force-firmware-current"></strong></p>
                    <select id="force-firmware-select" class="firmware-version-select" onchange="selectForceVersion('firmware')">
                        <option value="">Select Firmware Version...</option>
                    </select>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelForceUpdate()">Cancel</button>
                </div>
            </div>
        </div>

        <!-- Force Firmware Confirm Modal -->
        <div id="force-firmware-confirm-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Confirm Force Firmware</h2>
                </div>
                <div class="modal-body">
                    <p style="color: #dc3545; font-weight: bold;" id="force-firmware-confirm-msg"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelForceUpdate()">Cancel</button>
                    <button type="button" class="btn btn-force" onclick="confirmForceUpdate('firmware')">OK</button>
                </div>
            </div>
        </div>

        <!-- Force BIOS Modal -->
        <div id="force-bios-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Force BIOS Update</h2>
                </div>
                <div class="modal-body" id="force-bios-body">
                    <p style="color: #dc3545; font-weight: bold;">WARNING!  Use this option with caution!</p>
                    <p>Host: <strong id="force-bios-hostname"></strong></p>
                    <p>Current BIOS: <strong id="force-bios-current"></strong></p>
                    <select id="force-bios-select" class="bios-version-select" onchange="selectForceVersion('bios')">
                        <option value="">Select BIOS Version...</option>
                    </select>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelForceUpdate()">Cancel</button>
                </div>
            </div>
        </div>

        <!-- Force BIOS Confirm Modal -->
        <div id="force-bios-confirm-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Confirm Force BIOS</h2>
                </div>
                <div class="modal-body">
                    <p style="color: #dc3545; font-weight: bold;" id="force-bios-confirm-msg"></p>
                    <p>If you choose to apply this version you will still need to REBOOT the system.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelForceUpdate()">Cancel</button>
                    <button type="button" class="btn btn-force" onclick="confirmForceUpdate('bios')">OK</button>
                </div>
            </div>
        </div>

        <!-- Power Off Confirmation Modal -->
        <div id="power-off-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Power Action</h2>
                </div>
                <div class="modal-body">
                    <p>Select a power action for <strong id="power-off-hostname"></strong>:</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelPowerAction()">Cancel</button>
                    <button type="button" class="btn btn-reboot-graceful" onclick="confirmPowerAction('powercycle')">Graceful Reboot</button>
                    <button type="button" class="btn btn-reboot-hard" onclick="confirmPowerAction('hardreset')">Hard Reboot</button>
                    <button type="button" class="btn btn-power-on" onclick="confirmPowerAction('graceshutdown')">Graceful Shutdown</button>
                    <button type="button" class="btn btn-power-off" onclick="confirmPowerAction('powerdown')">Hard Power Off</button>
                </div>
            </div>
        </div>

        <!-- Power On Confirmation Modal -->
        <div id="power-on-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Confirm Power On</h2>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to power on <strong id="power-on-hostname"></strong>?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelPowerAction()">Cancel</button>
                    <button type="button" class="btn btn-power-on" onclick="confirmPowerAction('powerup')">Yes, Power On</button>
                </div>
            </div>
        </div>

        <!-- Latest Firmware Confirm Modal -->
        <div id="latest-firmware-confirm-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Check Latest Firmware</h2>
                </div>
                <div class="modal-body">
                    <p>Check for the latest firmware for <strong id="latest-firmware-model"></strong>?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelLatestFirmware()">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="proceedLatestFirmware()">Proceed</button>
                </div>
            </div>
        </div>

        <!-- Latest Firmware Status Modal -->
        <div id="latest-firmware-status-modal" class="modal-overlay">
            <div class="modal-content modal-large">
                <div class="modal-header">
                    <h2>Latest Firmware Check</h2>
                </div>
                <div class="modal-body">
                    <div id="latest-firmware-log" class="firmware-log"></div>
                </div>
                <div class="modal-footer" id="latest-firmware-footer" style="display: none;">
                </div>
            </div>
        </div>

        <!-- Latest BIOS Confirm Modal -->
        <div id="latest-bios-confirm-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Check Latest BIOS</h2>
                </div>
                <div class="modal-body">
                    <p>Check for the latest BIOS for <strong id="latest-bios-model"></strong>?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelLatestBios()">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="proceedLatestBios()">Proceed</button>
                </div>
            </div>
        </div>

        <!-- Latest BIOS Status Modal -->
        <div id="latest-bios-status-modal" class="modal-overlay">
            <div class="modal-content modal-large">
                <div class="modal-header">
                    <h2>Latest BIOS Check</h2>
                </div>
                <div class="modal-body">
                    <div id="latest-bios-log" class="firmware-log"></div>
                </div>
                <div class="modal-footer" id="latest-bios-footer" style="display: none;">
                </div>
            </div>
        </div>

        <!-- TSR Confirm Modal -->
        <div id="tsr-confirm-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Generate TSR</h2>
                </div>
                <div class="modal-body">
                    <p>Generate a Tech Support Report for <strong id="tsr-confirm-hostname"></strong>?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelTsr()">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="proceedTsr()">Proceed</button>
                </div>
            </div>
        </div>

        <!-- Clear Job Queue Confirm Modal -->
        <div id="clear-jq-confirm-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Clear Job Queue</h2>
                </div>
                <div class="modal-body">
                    <p id="clear-jq-confirm-message"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelClearJobQueue()">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="proceedClearJobQueue()">OK</button>
                </div>
            </div>
        </div>

        <!-- TSR Status Modal -->
        <div id="tsr-status-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>TSR — <span id="tsr-status-hostname"></span></h2>
                </div>
                <div class="modal-body" id="tsr-status-body">
                </div>
                <div class="modal-footer" id="tsr-status-footer">
                </div>
            </div>
        </div>

        <!-- Job Queue Modal -->
        <div id="job-queue-modal" class="modal-overlay">
            <div class="modal-content modal-large">
                <div class="modal-header">
                    <h2>Job Queue - <span id="job-queue-hostname"></span></h2>
                </div>
                <div class="modal-body">
                    <div id="job-queue-table-container">
                        <table id="job-queue-table">
                            <thead>
                                <tr>
                                    <th>Job ID</th>
                                    <th>Job Name</th>
                                    <th>Status</th>
                                    <th>Actual Start Time</th>
                                    <th>Actual Completion Time</th>
                                    <th>Message</th>
                                    <th>Percent Complete</th>
                                </tr>
                            </thead>
                            <tbody id="job-queue-tbody">
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" onclick="dismissJobQueue()">Dismiss</button>
                </div>
            </div>
        </div>

        <!-- Custom Filter Modal -->
        <div id="discover-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Bulk Host Discovery</h2>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="discover-textarea">Enter hostnames (one per line)</label>
                        <textarea id="discover-textarea" placeholder="host01.example.com&#10;host02.example.com&#10;host03.example.com"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="hideDiscoverModal()">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="submitDiscover()">OK</button>
                </div>
            </div>
        </div>

        <div id="delete-confirm-modal" class="modal-overlay">
            <div class="modal-content" style="max-width: 450px;">
                <div class="modal-header">
                    <h2>Confirm Deletion</h2>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete <strong id="delete-count-display">0</strong> selected host(s)?</p>
                    <p style="color: #dc3545; font-size: 0.9em;">This action cannot be undone.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="hideDeleteModal()">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="submitDelete()" style="background-color: #dc3545;">OK</button>
                </div>
            </div>
        </div>

        <div id="custom-filter-modal" class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Custom Hostname Filter</h2>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="custom-filter-textarea">Enter hostnames (one per line)</label>
                        <textarea id="custom-filter-textarea" placeholder="hostname1&#10;hostname2&#10;hostname3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="hideCustomFilterModal()">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="applyCustomFilter()">Apply Filter</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Site management
        const currentSite = '{{ current_site|default("Default", true) }}';
        function apiUrl(path) {
            const sep = path.includes('?') ? '&' : '?';
            return path + sep + 'site=' + encodeURIComponent(currentSite);
        }
        function switchSite(siteName) {
            const url = new URL(window.location);
            url.searchParams.set('site', siteName);
            window.location.href = url.toString();
        }
        // Authentication and admin functionality
        let isAuthenticated = {{ 'true' if is_authenticated else 'false' }};
        let userRole = '{{ user_role|default("", true) }}';
        let selectedRows = [];  // Changed to array for multi-select
        let selectedSystems = [];  // Changed to array for multi-select
        let refreshFrequency = {{ refresh_frequency }};  // Auto-refresh frequency in seconds
        let highlightExpired = {{ 'true' if highlight_expired else 'false' }};  // Highlight expired warranties
        let highlightExpiring = {{ highlight_expiring }};  // Days threshold for expiring warning
        let autoRefreshTimer = null;
        let isRefreshing = false;  // Prevent concurrent refreshes
        let lastClickedRow = null;  // For shift-click range selection
        let shiftKeyAnchorRow = null;  // Anchor point for shift+arrow key selection
        let customFilterHostnames = [];  // Array of hostnames for custom filtering
        let pendingFirmwareUpdate = null;  // Store pending firmware update info
        let pendingBiosUpdate = null;  // Store pending BIOS update info
        let firmwareFirstConfirmation = false;  // Track two-stage confirmation for large batches
        let biosFirstConfirmation = false;  // Track two-stage confirmation for large batches
        let currentPowerState = null;
        let currentPowerHostname = null;

        // Pagination state
        let currentPage = 1;
        let pageSize = {{ default_page_size }};
        let totalPages = 1;

        // Firmware and BIOS highlighting
        let highlightFirmware = {{ 'true' if highlight_firmware else 'false' }};
        let highlightBios = {{ 'true' if highlight_bios else 'false' }};
        let firmwareVersionsByModel = {};  // Firmware versions grouped by model, each sorted newest first
        let biosVersionsByModel = {};  // BIOS versions grouped by model, each sorted newest first

        console.log('DRACS: JavaScript loaded, isAuthenticated:', isAuthenticated, 'refreshFrequency:', refreshFrequency);

        // Theme Toggle
        function toggleTheme() {
            const body = document.body;
            const toggleSwitch = document.getElementById('theme-toggle-switch');

            if (body.classList.contains('dark-theme')) {
                // Switch to light theme
                body.classList.remove('dark-theme');
                toggleSwitch.classList.remove('active');
                localStorage.setItem('theme', 'light');
            } else {
                // Switch to dark theme
                body.classList.add('dark-theme');
                toggleSwitch.classList.add('active');
                localStorage.setItem('theme', 'dark');
            }
        }

        // Apply saved theme on page load
        function applySavedTheme() {
            const savedTheme = localStorage.getItem('theme');
            const body = document.body;
            const toggleSwitch = document.getElementById('theme-toggle-switch');

            if (savedTheme === 'dark') {
                body.classList.add('dark-theme');
                if (toggleSwitch) {
                    toggleSwitch.classList.add('active');
                }
            }
        }

        // Apply theme immediately on load
        applySavedTheme();

        // Modal functions
        function showLoginModal(event) {
            event.preventDefault();
            document.getElementById('login-modal').classList.add('active');
            document.getElementById('username').focus();
        }

        function hideLoginModal() {
            document.getElementById('login-modal').classList.remove('active');
            document.getElementById('login-form').reset();
        }

        function showUserManagementModal(event) {
            event.preventDefault();
            document.getElementById('user-management-modal').classList.add('active');
            loadUserList();
        }

        function hideUserManagementModal() {
            document.getElementById('user-management-modal').classList.remove('active');
        }

        async function loadUserList() {
            try {
                const response = await fetch('/api/users');
                const data = await response.json();
                if (!data.success) return;
                const tbody = document.getElementById('user-table-body');
                tbody.innerHTML = '';
                data.users.forEach(u => {
                    const tr = document.createElement('tr');
                    const created = u.created_at ? u.created_at.split('T')[0] : '-';
                    tr.innerHTML = `
                        <td style="padding: 6px; border-bottom: 1px solid #eee;">${u.username}</td>
                        <td style="padding: 6px; border-bottom: 1px solid #eee;">${u.role}</td>
                        <td style="padding: 6px; border-bottom: 1px solid #eee;">${created}</td>
                        <td style="padding: 6px; border-bottom: 1px solid #eee; text-align: center;">
                            <button class="btn btn-secondary" style="font-size: 12px; padding: 2px 8px;" onclick="handleToggleRole('${u.username}', '${u.role}')">
                                ${u.role === 'admin' ? 'Demote' : 'Promote'}
                            </button>
                            <button class="btn btn-secondary" style="font-size: 12px; padding: 2px 8px;" onclick="handleChangePassword('${u.username}')">
                                Password
                            </button>
                            <button class="btn btn-force" style="font-size: 12px; padding: 2px 8px;" onclick="handleDeleteUser('${u.username}')">
                                Delete
                            </button>
                        </td>
                    `;
                    tbody.appendChild(tr);
                });
                if (data.users.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="4" style="padding: 12px; text-align: center; color: #888;">No users. Only the superadmin (config) account exists.</td></tr>';
                }
            } catch (e) {
                console.error('Failed to load users:', e);
            }
        }

        async function handleAddUser(event) {
            event.preventDefault();
            const username = document.getElementById('new-username').value;
            const password = document.getElementById('new-password').value;
            const confirm = document.getElementById('new-confirm-password').value;
            const role = document.getElementById('new-role').value;
            if (password !== confirm) {
                showNotification('Passwords do not match', 'error');
                return;
            }
            try {
                const response = await fetch('/api/users', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({username, password, role})
                });
                const data = await response.json();
                showNotification(data.message, data.success ? 'success' : 'error');
                if (data.success) {
                    document.getElementById('add-user-form').reset();
                    loadUserList();
                }
            } catch (e) {
                showNotification('Error creating user', 'error');
            }
        }

        async function handleDeleteUser(username) {
            if (!window.confirm(`Delete user "${username}"?`)) return;
            try {
                const response = await fetch(`/api/users/${username}`, {method: 'DELETE'});
                const data = await response.json();
                showNotification(data.message, data.success ? 'success' : 'error');
                if (data.success) loadUserList();
            } catch (e) {
                showNotification('Error deleting user', 'error');
            }
        }

        async function handleToggleRole(username, currentRole) {
            const newRole = currentRole === 'admin' ? 'user' : 'admin';
            try {
                const response = await fetch(`/api/users/${username}`, {
                    method: 'PATCH',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({role: newRole})
                });
                const data = await response.json();
                showNotification(data.message, data.success ? 'success' : 'error');
                if (data.success) loadUserList();
            } catch (e) {
                showNotification('Error updating role', 'error');
            }
        }

        function handleChangePassword(username) {
            document.getElementById('cp-username').value = username;
            document.getElementById('cp-username-display').textContent = username;
            document.getElementById('change-password-form').reset();
            document.getElementById('cp-username').value = username;
            document.getElementById('change-password-modal').classList.add('active');
            document.getElementById('cp-new-password').focus();
        }

        function hideChangePasswordModal() {
            document.getElementById('change-password-modal').classList.remove('active');
            document.getElementById('change-password-form').reset();
        }

        async function submitChangePassword(event) {
            event.preventDefault();
            const username = document.getElementById('cp-username').value;
            const newPassword = document.getElementById('cp-new-password').value;
            const confirm = document.getElementById('cp-confirm-password').value;
            if (newPassword !== confirm) {
                showNotification('Passwords do not match', 'error');
                return;
            }
            try {
                const response = await fetch(`/api/users/${username}`, {
                    method: 'PATCH',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({password: newPassword})
                });
                const data = await response.json();
                showNotification(data.message, data.success ? 'success' : 'error');
                if (data.success) hideChangePasswordModal();
            } catch (e) {
                showNotification('Error changing password', 'error');
            }
        }

        function showSelfPasswordModal(event) {
            event.preventDefault();
            document.getElementById('self-password-modal').classList.add('active');
            document.getElementById('sp-current-password').focus();
        }

        function hideSelfPasswordModal() {
            document.getElementById('self-password-modal').classList.remove('active');
            document.getElementById('self-password-form').reset();
        }

        async function submitSelfPasswordChange(event) {
            event.preventDefault();
            const currentPassword = document.getElementById('sp-current-password').value;
            const newPassword = document.getElementById('sp-new-password').value;
            const confirm = document.getElementById('sp-confirm-password').value;
            if (newPassword !== confirm) {
                showNotification('New passwords do not match', 'error');
                return;
            }
            try {
                const response = await fetch(apiUrl('/api/change-password'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({current_password: currentPassword, new_password: newPassword})
                });
                const data = await response.json();
                showNotification(data.message, data.success ? 'success' : 'error');
                if (data.success) hideSelfPasswordModal();
            } catch (e) {
                showNotification('Error changing password', 'error');
            }
        }

        // Login handler
        async function handleLogin(event) {
            event.preventDefault();
            console.log('DRACS: handleLogin called');

            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            console.log('DRACS: Attempting login for user:', username);

            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ username, password })
                });

                // Check if response is JSON
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    const text = await response.text();
                    console.error('Non-JSON response:', text);
                    showNotification('Server error: Expected JSON response', 'error');
                    return;
                }

                const data = await response.json();

                if (data.success) {
                    showNotification(data.message, 'success');
                    hideLoginModal();
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                } else {
                    showNotification(data.message, 'error');
                }
            } catch (error) {
                console.error('Login error:', error);
                showNotification('Login failed: ' + error.message, 'error');
            }
        }

        // Logout handler
        async function handleLogout(event) {
            event.preventDefault();

            try {
                const response = await fetch('/logout', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });

                const data = await response.json();

                if (data.success) {
                    showNotification(data.message, 'success');
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                }
            } catch (error) {
                showNotification('Logout failed: ' + error.message, 'error');
            }
        }

        // Row selection handler (supports multi-select with Ctrl/Cmd+Click and Shift+Click for range)
        function handleRowClick(event) {
            const row = event.target.closest('tr');
            if (!row) return;

            // Check modifier keys (multi-select only for authenticated users)
            const isMultiSelect = isAuthenticated && (event.ctrlKey || event.metaKey);
            const isRangeSelect = isAuthenticated && event.shiftKey;

            // Prevent text selection when shift-clicking for range selection
            if (isRangeSelect) {
                event.preventDefault();
            }

            // Extract system data from row
            const cells = row.getElementsByTagName('td');
            const systemData = {
                service_tag: cells[0].textContent,
                hostname: cells[1].textContent,
                model: cells[2].textContent
            };

            if (isRangeSelect && lastClickedRow) {
                // Shift+Click: Select range from lastClickedRow to this row
                const tableBodyEl = document.getElementById('table-body');
                const allRows = Array.from(tableBodyEl.querySelectorAll('tr:not(.hidden)'));

                const startIndex = allRows.indexOf(lastClickedRow);
                const endIndex = allRows.indexOf(row);

                if (startIndex !== -1 && endIndex !== -1) {
                    const minIndex = Math.min(startIndex, endIndex);
                    const maxIndex = Math.max(startIndex, endIndex);

                    // Clear current selection
                    selectedRows.forEach(r => r.classList.remove('selected'));
                    selectedRows = [];
                    selectedSystems = [];

                    // Select all rows in the range
                    for (let i = minIndex; i <= maxIndex; i++) {
                        const rangeRow = allRows[i];
                        rangeRow.classList.add('selected');
                        selectedRows.push(rangeRow);

                        const rangeCells = rangeRow.getElementsByTagName('td');
                        selectedSystems.push({
                            service_tag: rangeCells[0].textContent,
                            hostname: rangeCells[1].textContent,
                            model: rangeCells[2].textContent
                        });
                    }

                    // Set anchor to the original starting point (lastClickedRow) for shift+arrow navigation
                    shiftKeyAnchorRow = lastClickedRow;
                    // Don't update lastClickedRow - it stays as the starting point for future shift-clicks
                }
            } else if (isMultiSelect) {
                // Ctrl/Cmd+Click: Toggle individual row
                const rowIndex = selectedRows.indexOf(row);

                if (rowIndex > -1) {
                    // Deselect this row
                    row.classList.remove('selected');
                    selectedRows.splice(rowIndex, 1);
                    selectedSystems.splice(rowIndex, 1);

                    // If we just deselected the anchor, update it to the first remaining selected row
                    if (shiftKeyAnchorRow === row) {
                        shiftKeyAnchorRow = selectedRows.length > 0 ? selectedRows[0] : null;
                    }
                } else {
                    // Select this row
                    row.classList.add('selected');
                    selectedRows.push(row);
                    selectedSystems.push(systemData);

                    // Set anchor if not already set
                    if (!shiftKeyAnchorRow) {
                        shiftKeyAnchorRow = row;
                    }
                }

                // Update lastClickedRow for future range selections
                lastClickedRow = row;
            } else {
                // Normal click: Single-select mode
                const rowIndex = selectedRows.indexOf(row);

                // Clear all selections
                selectedRows.forEach(r => r.classList.remove('selected'));
                selectedRows = [];
                selectedSystems = [];

                if (rowIndex === -1) {
                    // Select this row
                    row.classList.add('selected');
                    selectedRows.push(row);
                    selectedSystems.push(systemData);
                }

                // Update lastClickedRow for future range selections
                lastClickedRow = row;
                // Set anchor for shift+arrow key selection
                shiftKeyAnchorRow = row;
            }

            // Update button state and count
            const selectedCount = selectedSystems.length;
            console.log('DRACS: Updated selection - count:', selectedCount, 'systems:', selectedSystems);
            const selectedCountEl = document.getElementById('selected-count');
            if (selectedCountEl) selectedCountEl.textContent = selectedCount;
            const refreshBtnEl = document.getElementById('refresh-btn');
            if (refreshBtnEl) refreshBtnEl.disabled = selectedCount === 0;
            const deleteBtnEl = document.getElementById('delete-btn');
            if (deleteBtnEl) deleteBtnEl.disabled = selectedCount === 0;

            // Update firmware and job queue button states
            updateFirmwareButtonState();
            updateForceButtonState();
            updateJobQueueButtonState();
            updateClearJobQueueButtonState();
            updateConsoleButtonState();
            updatePowerButtonState();
            updateLatestFirmwareButtonState();
            updateLatestBiosButtonState();
            updateGenerateTsrButtonState();
            updateViewTsrButtonState();
            updateSelectAllButtonText();
            updateSelectShownButtonText();
        }

        // Update select all button text based on current selection state
        function updateSelectAllButtonText() {
            const selectAllBtn = document.getElementById('select-all-btn');
            if (!selectAllBtn) return;

            const visibleRows = Array.from(tableBody.querySelectorAll('tr:not(.hidden)'));
            if (visibleRows.length === 0) {
                selectAllBtn.textContent = 'Select All';
                return;
            }

            const allSelected = visibleRows.every(row => row.classList.contains('selected'));
            selectAllBtn.textContent = allSelected ? 'Deselect All' : 'Select All';
        }

        function updateSelectShownButtonText() {
            const selectShownBtn = document.getElementById('select-shown-btn');
            if (!selectShownBtn) return;

            // Get rows that are visible (pass filters) AND displayed on current page
            const allRows = Array.from(tableBody.querySelectorAll('tr'));
            const shownRows = allRows.filter(row =>
                !row.classList.contains('hidden') &&
                row.style.display !== 'none'
            );

            if (shownRows.length === 0) {
                selectShownBtn.textContent = 'Select Shown';
                return;
            }

            const allShownSelected = shownRows.every(row => row.classList.contains('selected'));
            selectShownBtn.textContent = allShownSelected ? 'Deselect Shown' : 'Select Shown';
        }

        // Toggle select only systems shown on current page
        function selectShown() {
            const selectShownBtn = document.getElementById('select-shown-btn');

            // Get rows that are visible (pass filters) AND displayed on current page
            const allRows = Array.from(tableBody.querySelectorAll('tr'));
            const shownRows = allRows.filter(row =>
                !row.classList.contains('hidden') &&
                row.style.display !== 'none'
            );

            if (shownRows.length === 0) {
                return;
            }

            // Check if all shown rows are currently selected
            const allShownSelected = shownRows.every(row => row.classList.contains('selected'));

            if (allShownSelected) {
                // Deselect all shown rows
                shownRows.forEach(row => {
                    row.classList.remove('selected');
                    const rowIndex = selectedRows.indexOf(row);
                    if (rowIndex > -1) {
                        selectedRows.splice(rowIndex, 1);
                        selectedSystems.splice(rowIndex, 1);
                    }
                });
                selectShownBtn.textContent = 'Select Shown';

                // Clear anchor if no rows left selected
                if (selectedRows.length === 0) {
                    shiftKeyAnchorRow = null;
                    lastClickedRow = null;
                }
            } else {
                // Clear current selection
                selectedRows.forEach(r => r.classList.remove('selected'));
                selectedRows = [];
                selectedSystems = [];

                // Select all shown rows
                shownRows.forEach(row => {
                    row.classList.add('selected');
                    selectedRows.push(row);

                    const cells = row.getElementsByTagName('td');
                    selectedSystems.push({
                        service_tag: cells[0].textContent,
                        hostname: cells[1].textContent,
                        model: cells[2].textContent
                    });
                });

                selectShownBtn.textContent = 'Deselect Shown';

                // Set anchor and lastClickedRow to first selected row
                if (shownRows.length > 0) {
                    shiftKeyAnchorRow = shownRows[0];
                    lastClickedRow = shownRows[0];
                }
            }

            // Update selected count immediately
            const selectedCountEl = document.getElementById('selected-count');
            if (selectedCountEl) {
                selectedCountEl.textContent = selectedSystems.length;
            }

            // Update refresh button state immediately
            const refreshBtn = document.getElementById('refresh-btn');
            if (refreshBtn) {
                refreshBtn.disabled = selectedSystems.length === 0;
            }

            // Update other button states (these may be slower)
            updateBiosButtonState();
            updateFirmwareButtonState();
            updateForceButtonState();
            updateJobQueueButtonState();
            updateClearJobQueueButtonState();
            updateConsoleButtonState();
            updatePowerButtonState();
            updateLatestFirmwareButtonState();
            updateLatestBiosButtonState();
            updateGenerateTsrButtonState();
            updateViewTsrButtonState();
            updateSelectAllButtonText();
        }

        // Toggle select all visible systems
        function toggleSelectAll() {
            const selectAllBtn = document.getElementById('select-all-btn');
            const visibleRows = Array.from(tableBody.querySelectorAll('tr:not(.hidden)'));

            if (visibleRows.length === 0) {
                return;
            }

            // Check if all visible rows are currently selected
            const allSelected = visibleRows.every(row => row.classList.contains('selected'));

            if (allSelected) {
                // Deselect all visible rows
                visibleRows.forEach(row => {
                    row.classList.remove('selected');
                });
                selectedRows = [];
                selectedSystems = [];
                selectAllBtn.textContent = 'Select All';

                // Clear anchor when deselecting all
                shiftKeyAnchorRow = null;
                lastClickedRow = null;
            } else {
                // Select all visible rows
                selectedRows = [];
                selectedSystems = [];

                visibleRows.forEach(row => {
                    row.classList.add('selected');
                    selectedRows.push(row);

                    const cells = row.getElementsByTagName('td');
                    selectedSystems.push({
                        service_tag: cells[0].textContent,
                        hostname: cells[1].textContent,
                        model: cells[2].textContent
                    });
                });

                selectAllBtn.textContent = 'Deselect All';

                // Set anchor and lastClickedRow to first selected row
                if (visibleRows.length > 0) {
                    shiftKeyAnchorRow = visibleRows[0];
                    lastClickedRow = visibleRows[0];
                }
            }

            // Update button states
            updateRefreshButtonState();
            updateBiosButtonState();
            updateFirmwareButtonState();
            updateForceButtonState();
            updateJobQueueButtonState();
            updateClearJobQueueButtonState();
            updateConsoleButtonState();
            updatePowerButtonState();
            updateLatestFirmwareButtonState();
            updateLatestBiosButtonState();
            updateGenerateTsrButtonState();
            updateViewTsrButtonState();

            // Update selected count if it exists
            const selectedCountEl = document.getElementById('selected-count');
            if (selectedCountEl) {
                selectedCountEl.textContent = selectedSystems.length;
            }

            // Update Select Shown button text
            updateSelectShownButtonText();
        }

        // Refresh selected systems
        async function handleRefreshSelected() {
            if (selectedSystems.length === 0) return;

            const refreshBtn = document.getElementById('refresh-btn');
            const originalText = refreshBtn.textContent;
            refreshBtn.disabled = true;
            refreshBtn.textContent = `Refreshing ${selectedSystems.length} system(s)...`;

            try {
                const response = await fetch(apiUrl('/api/refresh-multiple'), {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        systems: selectedSystems
                    })
                });

                // Check if response is JSON
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    const text = await response.text();
                    console.error('Non-JSON response:', text);
                    showNotification('Server error: Expected JSON response', 'error');
                    refreshBtn.disabled = false;
                    refreshBtn.textContent = originalText;
                    return;
                }

                const data = await response.json();

                if (data.success) {
                    showNotification(data.message, 'success');
                    // Refresh table data to show the updated information
                    setTimeout(() => {
                        console.log('DRACS: Manual refresh triggered table reload');
                        refreshTableData();
                        // Re-enable button after table refresh
                        refreshBtn.disabled = selectedSystems.length === 0;
                        refreshBtn.textContent = originalText;
                    }, 1000);
                } else {
                    showNotification(data.message, 'error');
                    refreshBtn.disabled = selectedSystems.length === 0;
                    refreshBtn.textContent = originalText;
                }
            } catch (error) {
                console.error('Refresh error:', error);
                showNotification('Refresh failed: ' + error.message, 'error');
                refreshBtn.disabled = false;
                refreshBtn.textContent = originalText;
            }
        }

        // Refresh all systems
        async function handleRefreshAll() {
            if (!confirm('This will refresh all systems in the database. This may take several minutes. Continue?')) {
                return;
            }

            const refreshAllBtn = document.getElementById('refresh-all-btn');
            const originalText = refreshAllBtn.textContent;
            refreshAllBtn.disabled = true;
            refreshAllBtn.textContent = 'Refreshing all systems...';

            try {
                const response = await fetch(apiUrl('/api/refresh-all'), {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });

                // Check if response is JSON
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    const text = await response.text();
                    console.error('Non-JSON response:', text);
                    showNotification('Server error: Expected JSON response', 'error');
                    refreshAllBtn.disabled = false;
                    refreshAllBtn.textContent = originalText;
                    return;
                }

                const data = await response.json();

                if (data.success) {
                    showNotification(data.message, 'success');
                    // Reload data after 1 second
                    setTimeout(() => {
                        console.log('DRACS: Refresh all triggered table reload');
                        refreshTableData();
                        // Re-enable button after table refresh
                        refreshAllBtn.disabled = false;
                        refreshAllBtn.textContent = originalText;
                    }, 1000);
                } else {
                    showNotification(data.message, 'error');
                    refreshAllBtn.disabled = false;
                    refreshAllBtn.textContent = originalText;
                }
            } catch (error) {
                console.error('Refresh all error:', error);
                showNotification('Refresh all failed: ' + error.message, 'error');
                refreshAllBtn.disabled = false;
                refreshAllBtn.textContent = originalText;
            }
        }

        // Refresh table data without full page reload
        async function refreshTableData() {
            // Prevent concurrent refreshes
            if (isRefreshing) {
                console.log('DRACS: Refresh already in progress, skipping...');
                return;
            }

            try {
                isRefreshing = true;
                console.log('DRACS: Refreshing table data...');
                const response = await fetch(apiUrl('/api/systems'));
                const data = await response.json();

                console.log('DRACS: Received', data.length, 'systems from API');

                // Get fresh references to DOM elements
                const tableBodyEl = document.getElementById('table-body');
                const hostnameFilterEl = document.getElementById('hostname-filter');
                const servicetagFilterEl = document.getElementById('servicetag-filter');
                const modelFilterEl = document.getElementById('model-filter');
                const biosVersionEl = document.getElementById('bios-version');
                const biosOperatorEl = document.getElementById('bios-operator');
                const firmwareVersionEl = document.getElementById('firmware-version');
                const firmwareOperatorEl = document.getElementById('firmware-operator');
                const totalCountEl = document.getElementById('total-count');
                const selectedCountEl = document.getElementById('selected-count');

                if (!tableBodyEl) {
                    console.error('DRACS: table-body element not found!');
                    return;
                }

                // Save current filter values
                const hostnameText = hostnameFilterEl.value;
                const servicetagText = servicetagFilterEl.value;
                const biosVersionValue = biosVersionEl.value;
                const biosOperatorValue = biosOperatorEl.value;
                const firmwareVersionValue = firmwareVersionEl.value;
                const firmwareOperatorValue = firmwareOperatorEl.value;
                const selectedModelValues = Array.from(modelFilterEl.selectedOptions).map(opt => opt.value);

                console.log('DRACS: Current filters - hostname:', hostnameText, 'models:', selectedModelValues);

                // Remember currently selected service tags
                const selectedTags = selectedSystems.map(s => s.service_tag);

                // Remember the service tag of the last clicked row for range selection
                const lastClickedTag = lastClickedRow ? lastClickedRow.getElementsByTagName('td')[0].textContent : null;

                // Remember the service tag of the shift key anchor row
                const shiftAnchorTag = shiftKeyAnchorRow ? shiftKeyAnchorRow.getElementsByTagName('td')[0].textContent : null;

                // Clear selection arrays
                selectedRows = [];
                selectedSystems = [];
                lastClickedRow = null;  // Will be restored below if found
                shiftKeyAnchorRow = null;  // Will be restored below if found

                // Clear current table before rebuilding
                console.log('DRACS: Clearing table, current row count:', tableBodyEl.children.length);
                tableBodyEl.innerHTML = '';
                console.log('DRACS: Table cleared, row count:', tableBodyEl.children.length);

                // Update systems array with new data and recalculate versions
                systems = data;
                calculateAllVersions();
                updateVersionDropdowns();

                // Rebuild table
                data.forEach(system => {
                    const row = createRow(system);
                    tableBodyEl.appendChild(row);

                    // Re-select previously selected rows
                    if (selectedTags.includes(system.svc_tag)) {
                        row.classList.add('selected');
                        selectedRows.push(row);
                        const cells = row.getElementsByTagName('td');
                        selectedSystems.push({
                            service_tag: cells[0].textContent,
                            hostname: cells[1].textContent,
                            model: cells[2].textContent
                        });
                    }

                    // Restore lastClickedRow reference
                    if (lastClickedTag && system.svc_tag === lastClickedTag) {
                        lastClickedRow = row;
                    }

                    // Restore shiftKeyAnchorRow reference
                    if (shiftAnchorTag && system.svc_tag === shiftAnchorTag) {
                        shiftKeyAnchorRow = row;
                    }
                });

                console.log('DRACS: Table rebuilt, row count:', tableBodyEl.children.length);

                // Update counts
                if (totalCountEl) totalCountEl.textContent = data.length;
                if (selectedCountEl) selectedCountEl.textContent = selectedSystems.length;

                // Restore filter values (in case they got cleared somehow)
                hostnameFilterEl.value = hostnameText;
                servicetagFilterEl.value = servicetagText;
                biosVersionEl.value = biosVersionValue;
                biosOperatorEl.value = biosOperatorValue;
                firmwareVersionEl.value = firmwareVersionValue;
                firmwareOperatorEl.value = firmwareOperatorValue;

                // Restore model selections
                Array.from(modelFilterEl.options).forEach(option => {
                    option.selected = selectedModelValues.includes(option.value);
                });

                console.log('DRACS: Reapplying filters...');
                // Reapply filters
                applyFilters();

                // Update firmware and job queue button states after refresh
                if (isAuthenticated) {
                    updateFirmwareButtonState();
            updateForceButtonState();
                    updateJobQueueButtonState();
                    updateClearJobQueueButtonState();
                    updatePowerButtonState();
                    updateLatestFirmwareButtonState();
                    updateLatestBiosButtonState();
                    updateGenerateTsrButtonState();
                    updateViewTsrButtonState();
                }

                console.log('DRACS: Table refresh complete, visible rows:', document.querySelectorAll('#table-body tr:not(.hidden)').length);
            } catch (error) {
                console.error('Error refreshing table data:', error);
            } finally {
                isRefreshing = false;
            }
        }

        // Update Firmware button state and populate versions
        async function updateFirmwareButtonState() {
            const updateBtn = document.getElementById('update-firmware-btn');
            if (!updateBtn) return;
            const versionSelect = document.getElementById('firmware-version-select');
            const biosUpdateBtn = document.getElementById('update-bios-btn');
            const biosVersionSelect = document.getElementById('bios-version-select');

            if (selectedSystems.length === 0) {
                updateBtn.style.display = 'inline-block';
                updateBtn.disabled = true;
                versionSelect.style.display = 'none';

                biosUpdateBtn.style.display = 'inline-block';
                biosUpdateBtn.disabled = true;
                biosUpdateBtn.classList.remove('unavailable');
                biosUpdateBtn.innerHTML = 'Update BIOS';
                biosVersionSelect.style.display = 'none';
                return;
            }

            // Check if all selected systems are the same model
            const firstModel = selectedSystems[0].model;
            const allSameModel = selectedSystems.every(sys => sys.model === firstModel);

            if (!allSameModel) {
                // Mixed models - disable both buttons
                updateBtn.style.display = 'inline-block';
                updateBtn.disabled = true;
                updateBtn.innerHTML = 'Update Firmware<span class="subtitle">(Mixed models)</span>';
                versionSelect.style.display = 'none';

                biosUpdateBtn.style.display = 'inline-block';
                biosUpdateBtn.disabled = true;
                biosUpdateBtn.classList.remove('unavailable');
                biosUpdateBtn.innerHTML = 'Update BIOS<span class="subtitle">(Mixed models)</span>';
                biosVersionSelect.style.display = 'none';
                return;
            }

            // All same model - find highest and lowest firmware versions among selected systems
            const selectedFirmwareVersions = selectedSystems
                .map(sys => selectedRows[selectedSystems.indexOf(sys)].dataset.firmwareVersion)
                .filter(v => v);

            let highestSelectedFirmware = null;
            let lowestSelectedFirmware = null;
            for (const version of selectedFirmwareVersions) {
                if (!highestSelectedFirmware || compareVersions(version, highestSelectedFirmware) > 0) {
                    highestSelectedFirmware = version;
                }
                if (!lowestSelectedFirmware || compareVersions(version, lowestSelectedFirmware) < 0) {
                    lowestSelectedFirmware = version;
                }
            }

            // Get all firmware versions for this model
            const modelFirmwareVersions = firmwareVersionsByModel[firstModel] || [];
            const newestFirmware = modelFirmwareVersions.length > 0 ? modelFirmwareVersions[0] : null;

            // Check if ALL selected hosts already have the newest firmware
            const allAtNewest = selectedSystems.every(sys => {
                const sysIndex = selectedSystems.indexOf(sys);
                const sysFirmware = selectedRows[sysIndex].dataset.firmwareVersion;
                return sysFirmware === newestFirmware;
            });

            if (newestFirmware && allAtNewest) {
                // All selected hosts are already at the latest firmware
                updateBtn.style.display = 'inline-block';
                updateBtn.disabled = true;
                updateBtn.innerHTML = 'Update Firmware';
                versionSelect.style.display = 'none';
            } else {
                const isSingleHost = selectedSystems.length === 1;
                const availableVersions = modelFirmwareVersions.filter(version => {
                    if (isSingleHost) {
                        if (!highestSelectedFirmware) return true;
                        return compareVersions(version, highestSelectedFirmware) > 0;
                    } else {
                        if (!highestSelectedFirmware) return true;
                        return compareVersions(version, highestSelectedFirmware) >= 0;
                    }
                });

                if (availableVersions && availableVersions.length > 0) {
                    // Show firmware dropdown with available versions
                    updateBtn.style.display = 'none';
                    versionSelect.style.display = 'inline-block';
                    populateFirmwareVersions(versionSelect, availableVersions);
                } else {
                    // No firmware updates available
                    updateBtn.style.display = 'inline-block';
                    updateBtn.disabled = true;
                    updateBtn.innerHTML = 'Update Firmware';
                    versionSelect.style.display = 'none';
                }
            }

            // Update BIOS button state
            await updateBiosButtonState(firstModel, highestSelectedFirmware, modelFirmwareVersions);
        }

        // Update BIOS button state
        async function updateBiosButtonState(model, highestSelectedFirmware, modelFirmwareVersions) {
            const biosUpdateBtn = document.getElementById('update-bios-btn');
            const biosVersionSelect = document.getElementById('bios-version-select');

            // Get the newest firmware version for this model
            const newestFirmware = modelFirmwareVersions && modelFirmwareVersions.length > 0 ? modelFirmwareVersions[0] : null;

            // Check if ALL selected systems have the newest firmware
            const allHaveNewestFirmware = selectedSystems.every(sys => {
                const sysIndex = selectedSystems.indexOf(sys);
                const sysFirmware = selectedRows[sysIndex].dataset.firmwareVersion;
                return sysFirmware === newestFirmware;
            });

            if (!allHaveNewestFirmware) {
                // Not all systems have newest firmware - BIOS update unavailable
                biosUpdateBtn.style.display = 'inline-block';
                biosUpdateBtn.disabled = true;
                biosUpdateBtn.classList.add('unavailable');
                biosUpdateBtn.innerHTML = 'Update BIOS unavailable<span class="subtitle">(Update Firmware First)</span>';
                biosVersionSelect.style.display = 'none';
            } else {
                // All systems have newest firmware - find highest BIOS among selected
                const selectedBiosVersions = selectedSystems
                    .map(sys => selectedRows[selectedSystems.indexOf(sys)].dataset.biosVersion)
                    .filter(v => v);

                let highestSelectedBios = null;
                for (const version of selectedBiosVersions) {
                    if (!highestSelectedBios || compareVersions(version, highestSelectedBios) > 0) {
                        highestSelectedBios = version;
                    }
                }

                // Get all BIOS versions for this model
                const modelBiosVersions = biosVersionsByModel[model] || [];
                const newestBios = modelBiosVersions.length > 0 ? modelBiosVersions[0] : null;

                // Check if ALL selected hosts already have the newest BIOS
                const allAtNewestBios = selectedBiosVersions.every(v =>
                    newestBios && compareVersions(v, newestBios) === 0
                );

                if (allAtNewestBios && newestBios) {
                    // All selected hosts are already at the latest BIOS - disable
                    biosUpdateBtn.style.display = 'inline-block';
                    biosUpdateBtn.disabled = true;
                    biosUpdateBtn.classList.remove('unavailable');
                    biosUpdateBtn.innerHTML = 'Update BIOS';
                    biosVersionSelect.style.display = 'none';
                } else {
                    const isSingleHostBios = selectedSystems.length === 1;
                    const availableBiosVersions = modelBiosVersions.filter(version => {
                        if (isSingleHostBios) {
                            if (!highestSelectedBios) return true;
                            return compareVersions(version, highestSelectedBios) > 0;
                        } else {
                            if (!highestSelectedBios) return true;
                            return compareVersions(version, highestSelectedBios) >= 0;
                        }
                    });

                    if (availableBiosVersions && availableBiosVersions.length > 0) {
                        // Show BIOS dropdown with available versions
                        biosUpdateBtn.style.display = 'none';
                        biosVersionSelect.style.display = 'inline-block';
                        populateBiosVersions(biosVersionSelect, availableBiosVersions);
                    } else {
                        // No BIOS versions available
                        biosUpdateBtn.style.display = 'inline-block';
                        biosUpdateBtn.disabled = true;
                        biosUpdateBtn.classList.remove('unavailable');
                        biosUpdateBtn.innerHTML = 'Update BIOS';
                        biosVersionSelect.style.display = 'none';
                    }
                }
            }
        }

        // Update Job Queue button state
        function updateJobQueueButtonState() {
            const jobQueueBtn = document.getElementById('job-queue-btn');
            if (!jobQueueBtn) return;

            if (selectedSystems.length === 1) {
                jobQueueBtn.disabled = false;
            } else {
                jobQueueBtn.disabled = true;
            }
        }

        // Update Clear Job Queue button state
        function updateClearJobQueueButtonState() {
            const clearJobQueueBtn = document.getElementById('clear-job-queue-btn');
            if (!clearJobQueueBtn) return;

            if (selectedSystems.length >= 1) {
                clearJobQueueBtn.disabled = false;
            } else {
                clearJobQueueBtn.disabled = true;
            }
        }

        function updateConsoleButtonState() {
            const consoleBtn = document.getElementById('console-btn');
            if (!consoleBtn) return;

            if (selectedSystems.length === 1) {
                consoleBtn.disabled = false;
            } else {
                consoleBtn.disabled = true;
            }
        }

        async function handleConsoleClick() {
            if (selectedSystems.length !== 1) return;

            const hostname = selectedSystems[0].hostname;
            try {
                const response = await fetch(apiUrl('/api/vnc-session'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ hostname: hostname })
                });
                const data = await response.json();
                if (data.success) {
                    window.open('/console/' + data.token, '_blank',
                        'width={{ vnc_console_width }},height={{ vnc_console_height }},menubar=no,toolbar=no,location=no,status=no,scrollbars=no');
                } else {
                    showNotification(data.message, 'error');
                }
            } catch (error) {
                showNotification('Failed to open console: ' + error.message, 'error');
            }
        }

        function updatePowerButtonState() {
            const powerBtn = document.getElementById('power-btn');
            if (!powerBtn) return;

            if (selectedSystems.length === 1) {
                const hostname = selectedSystems[0].hostname;
                if (hostname !== currentPowerHostname) {
                    powerBtn.classList.remove('btn-power-on', 'btn-power-off');
                    currentPowerState = null;
                    currentPowerHostname = hostname;
                    powerBtn.textContent = 'Power ...';
                    powerBtn.disabled = true;
                }
                checkPowerStatus(hostname);
            } else {
                powerBtn.classList.remove('btn-power-on', 'btn-power-off');
                currentPowerState = null;
                currentPowerHostname = null;
                powerBtn.textContent = 'Power';
                powerBtn.disabled = true;
            }
        }

        async function checkPowerStatus(hostname) {
            const powerBtn = document.getElementById('power-btn');
            if (!powerBtn) return;

            try {
                const response = await fetch(apiUrl('/api/power-status'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ hostname: hostname })
                });
                const data = await response.json();

                if (selectedSystems.length !== 1 || selectedSystems[0].hostname !== hostname) return;

                powerBtn.classList.remove('btn-power-on', 'btn-power-off');

                if (data.success) {
                    currentPowerState = data.status;
                    if (data.status === 'on') {
                        powerBtn.textContent = 'Power Off';
                        powerBtn.classList.add('btn-power-on');
                        powerBtn.disabled = false;
                    } else {
                        powerBtn.textContent = 'Power On';
                        powerBtn.classList.add('btn-power-off');
                        powerBtn.disabled = false;
                    }
                } else {
                    currentPowerState = null;
                    powerBtn.textContent = 'Power Unknown';
                    powerBtn.disabled = true;
                }
            } catch (error) {
                if (selectedSystems.length === 1 && selectedSystems[0].hostname === hostname) {
                    currentPowerState = null;
                    powerBtn.classList.remove('btn-power-on', 'btn-power-off');
                    powerBtn.textContent = 'Power Unknown';
                    powerBtn.disabled = true;
                }
            }
        }

        function handlePowerClick() {
            if (selectedSystems.length !== 1 || !currentPowerState) return;

            const hostname = selectedSystems[0].hostname;

            if (currentPowerState === 'on') {
                document.getElementById('power-off-hostname').textContent = hostname;
                document.getElementById('power-off-modal').classList.add('active');
            } else {
                document.getElementById('power-on-hostname').textContent = hostname;
                document.getElementById('power-on-modal').classList.add('active');
            }
        }

        async function confirmPowerAction(action) {
            cancelPowerAction();

            if (selectedSystems.length !== 1) return;

            const hostname = selectedSystems[0].hostname;
            const powerBtn = document.getElementById('power-btn');
            if (powerBtn) {
                powerBtn.disabled = true;
                powerBtn.textContent = 'Power ...';
                powerBtn.classList.remove('btn-power-on', 'btn-power-off');
            }

            try {
                const response = await fetch(apiUrl('/api/power-action'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ hostname: hostname, action: action })
                });
                const data = await response.json();

                if (data.success) {
                    showNotification(data.message, 'success');
                } else {
                    showNotification(data.message, 'error');
                }
            } catch (error) {
                showNotification('Power action failed: ' + error.message, 'error');
            }

            setTimeout(() => {
                if (selectedSystems.length === 1) {
                    checkPowerStatus(selectedSystems[0].hostname);
                }
            }, 3000);
        }

        function cancelPowerAction() {
            document.getElementById('power-off-modal').classList.remove('active');
            document.getElementById('power-on-modal').classList.remove('active');
        }

        function updateLatestFirmwareButtonState() {
            const btn = document.getElementById('latest-firmware-btn');
            if (!btn) return;
            btn.disabled = selectedSystems.length !== 1;
        }

        function handleLatestFirmwareClick() {
            if (selectedSystems.length !== 1) return;
            const model = selectedSystems[0].model;
            document.getElementById('latest-firmware-model').textContent = model;
            document.getElementById('latest-firmware-confirm-modal').classList.add('active');
        }

        function cancelLatestFirmware() {
            document.getElementById('latest-firmware-confirm-modal').classList.remove('active');
        }

        async function proceedLatestFirmware() {
            document.getElementById('latest-firmware-confirm-modal').classList.remove('active');

            const hostname = selectedSystems[0].hostname;
            const model = selectedSystems[0].model;

            const selectedRow = selectedRows[0];
            let currentVersion = '';
            if (selectedRow) {
                currentVersion = selectedRow.dataset.firmwareVersion || '';
            }

            const logEl = document.getElementById('latest-firmware-log');
            const footerEl = document.getElementById('latest-firmware-footer');
            logEl.innerHTML = '';
            footerEl.style.display = 'none';
            footerEl.innerHTML = '';
            document.getElementById('latest-firmware-status-modal').classList.add('active');

            try {
                const response = await fetch(apiUrl('/api/latest-firmware'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ model: model, hostname: hostname, current_version: currentVersion })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    buffer = lines.pop();

                    for (const line of lines) {
                        if (!line.startsWith('data: ')) continue;
                        const data = JSON.parse(line.substring(6));

                        if (data.type === 'status') {
                            const div = document.createElement('div');
                            div.textContent = data.message;
                            logEl.appendChild(div);
                            logEl.scrollTop = logEl.scrollHeight;
                        } else if (data.type === 'append') {
                            const lastDiv = logEl.lastElementChild;
                            if (lastDiv) {
                                lastDiv.textContent += data.message;
                            }
                        } else if (data.type === 'error') {
                            const div = document.createElement('div');
                            div.style.color = '#dc3545';
                            div.textContent = data.message;
                            logEl.appendChild(div);
                            logEl.scrollTop = logEl.scrollHeight;
                            footerEl.innerHTML = '<button type="button" class="btn btn-secondary" onclick="closeLatestFirmwareDialog()">OK</button>';
                            footerEl.style.display = 'flex';
                        } else if (data.type === 'complete') {
                            footerEl.style.display = 'flex';
                            if (data.already_current) {
                                footerEl.innerHTML = '<button type="button" class="btn btn-secondary" onclick="closeLatestFirmwareDialog()">OK</button>';
                            } else {
                                const div = document.createElement('div');
                                div.textContent = 'Update ' + data.hostname + ' to firmware version ' + data.version + '?';
                                div.style.fontWeight = '600';
                                div.style.marginTop = '8px';
                                logEl.appendChild(div);
                                logEl.scrollTop = logEl.scrollHeight;
                                footerEl.innerHTML =
                                    '<button type="button" class="btn btn-secondary" onclick="closeLatestFirmwareDialog()">Cancel</button>' +
                                    '<button type="button" class="btn btn-primary" onclick="confirmLatestFirmwareUpdate(\'' +
                                    data.version.replace(/'/g, "\\'") + '\', \'' +
                                    data.hostname.replace(/'/g, "\\'") + '\', \'' +
                                    data.model.replace(/'/g, "\\'") + '\')">Proceed</button>';
                            }
                        }
                    }
                }
            } catch (error) {
                const div = document.createElement('div');
                div.style.color = '#dc3545';
                div.textContent = 'Connection error: ' + error.message;
                logEl.appendChild(div);
                footerEl.innerHTML = '<button type="button" class="btn btn-secondary" onclick="closeLatestFirmwareDialog()">OK</button>';
                footerEl.style.display = 'flex';
            }
        }

        async function confirmLatestFirmwareUpdate(version, hostname, model) {
            closeLatestFirmwareDialog();

            try {
                const response = await fetch(apiUrl('/api/firmware-update'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ hostname: hostname, target_version: version, model: model })
                });
                const data = await response.json();
                if (data.success) {
                    showNotification(data.message, 'success');
                } else {
                    showNotification(data.message, 'error');
                }
            } catch (error) {
                showNotification('Firmware update failed: ' + error.message, 'error');
            }
        }

        function closeLatestFirmwareDialog() {
            document.getElementById('latest-firmware-status-modal').classList.remove('active');
        }

        function updateLatestBiosButtonState() {
            const btn = document.getElementById('latest-bios-btn');
            if (!btn) return;
            btn.disabled = selectedSystems.length !== 1;
        }

        function handleLatestBiosClick() {
            if (selectedSystems.length !== 1) return;
            const model = selectedSystems[0].model;
            document.getElementById('latest-bios-model').textContent = model;
            document.getElementById('latest-bios-confirm-modal').classList.add('active');
        }

        function cancelLatestBios() {
            document.getElementById('latest-bios-confirm-modal').classList.remove('active');
        }

        async function proceedLatestBios() {
            document.getElementById('latest-bios-confirm-modal').classList.remove('active');

            const hostname = selectedSystems[0].hostname;
            const model = selectedSystems[0].model;

            const selectedRow = selectedRows[0];
            let currentVersion = '';
            if (selectedRow) {
                currentVersion = selectedRow.dataset.biosVersion || '';
            }

            const logEl = document.getElementById('latest-bios-log');
            const footerEl = document.getElementById('latest-bios-footer');
            logEl.innerHTML = '';
            footerEl.style.display = 'none';
            footerEl.innerHTML = '';
            document.getElementById('latest-bios-status-modal').classList.add('active');

            try {
                const response = await fetch(apiUrl('/api/latest-bios'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ model: model, hostname: hostname, current_version: currentVersion })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    buffer = lines.pop();

                    for (const line of lines) {
                        if (!line.startsWith('data: ')) continue;
                        const data = JSON.parse(line.substring(6));

                        if (data.type === 'status') {
                            const div = document.createElement('div');
                            div.textContent = data.message;
                            logEl.appendChild(div);
                            logEl.scrollTop = logEl.scrollHeight;
                        } else if (data.type === 'append') {
                            const lastDiv = logEl.lastElementChild;
                            if (lastDiv) {
                                lastDiv.textContent += data.message;
                            }
                        } else if (data.type === 'error') {
                            const div = document.createElement('div');
                            div.style.color = '#dc3545';
                            div.textContent = data.message;
                            logEl.appendChild(div);
                            logEl.scrollTop = logEl.scrollHeight;
                            footerEl.innerHTML = '<button type="button" class="btn btn-secondary" onclick="closeLatestBiosDialog()">OK</button>';
                            footerEl.style.display = 'flex';
                        } else if (data.type === 'complete') {
                            footerEl.style.display = 'flex';
                            if (data.already_current) {
                                footerEl.innerHTML = '<button type="button" class="btn btn-secondary" onclick="closeLatestBiosDialog()">OK</button>';
                            } else {
                                const div = document.createElement('div');
                                div.textContent = 'Update ' + data.hostname + ' to BIOS version ' + data.version + '?';
                                div.style.fontWeight = '600';
                                div.style.marginTop = '8px';
                                logEl.appendChild(div);
                                logEl.scrollTop = logEl.scrollHeight;
                                footerEl.innerHTML =
                                    '<button type="button" class="btn btn-secondary" onclick="closeLatestBiosDialog()">Cancel</button>' +
                                    '<button type="button" class="btn btn-primary" onclick="confirmLatestBiosUpdate(\'' +
                                    data.version.replace(/'/g, "\\'") + '\', \'' +
                                    data.hostname.replace(/'/g, "\\'") + '\', \'' +
                                    data.model.replace(/'/g, "\\'") + '\')">Proceed</button>';
                            }
                        }
                    }
                }
            } catch (error) {
                const div = document.createElement('div');
                div.style.color = '#dc3545';
                div.textContent = 'Connection error: ' + error.message;
                logEl.appendChild(div);
                footerEl.innerHTML = '<button type="button" class="btn btn-secondary" onclick="closeLatestBiosDialog()">OK</button>';
                footerEl.style.display = 'flex';
            }
        }

        async function confirmLatestBiosUpdate(version, hostname, model) {
            closeLatestBiosDialog();

            try {
                const response = await fetch(apiUrl('/api/bios-update'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ hostname: hostname, target_bios: version, model: model })
                });
                const data = await response.json();
                if (data.success) {
                    showNotification(data.message, 'success');
                } else {
                    showNotification(data.message, 'error');
                }
            } catch (error) {
                showNotification('BIOS update failed: ' + error.message, 'error');
            }
        }

        function closeLatestBiosDialog() {
            document.getElementById('latest-bios-status-modal').classList.remove('active');
        }

        let tsrPollTimer = null;

        function updateGenerateTsrButtonState() {
            const btn = document.getElementById('generate-tsr-btn');
            if (!btn) return;
            btn.disabled = selectedSystems.length !== 1;
        }

        function handleGenerateTsrClick() {
            if (selectedSystems.length !== 1) return;
            const hostname = selectedSystems[0].hostname;
            document.getElementById('tsr-confirm-hostname').textContent = hostname;
            document.getElementById('tsr-confirm-modal').classList.add('active');
        }

        function updateViewTsrButtonState() {
            const btn = document.getElementById('view-tsr-btn');
            if (!btn) return;
            btn.disabled = selectedSystems.length !== 1;
        }

        function handleViewTsrClick() {
            if (selectedSystems.length !== 1) return;
            const hostname = selectedSystems[0].hostname;
            const url = window.location.origin + '/tsr/' + hostname + '/';
            fetch(apiUrl('/api/tsr-ensure-index'), {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({hostname: hostname})
            }).finally(function() {
                window.open(url, '_blank');
            });
        }

        function cancelTsr() {
            document.getElementById('tsr-confirm-modal').classList.remove('active');
        }

        async function proceedTsr() {
            document.getElementById('tsr-confirm-modal').classList.remove('active');

            const hostname = selectedSystems[0].hostname;
            const serviceTag = selectedSystems[0].service_tag;

            document.getElementById('tsr-status-hostname').textContent = hostname;
            const bodyEl = document.getElementById('tsr-status-body');
            const footerEl = document.getElementById('tsr-status-footer');
            bodyEl.innerHTML = '<p>Checking TSR status...</p>';
            footerEl.innerHTML = '<button type="button" class="btn btn-secondary" onclick="closeTsrDialog()">Close</button>';
            document.getElementById('tsr-status-modal').classList.add('active');

            try {
                const response = await fetch(apiUrl('/api/tsr-status'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ hostname: hostname })
                });
                const data = await response.json();

                if (!data.success) {
                    bodyEl.innerHTML = '<p style="color: #dc3545;">' + (data.message || 'Failed to check TSR status') + '</p>';
                    return;
                }

                if (data.state === 'running') {
                    showTsrRunning(hostname, data.percent_complete || '0');
                } else if (data.state === 'completed') {
                    showTsrCompleted(hostname, data.tsr_url, serviceTag);
                } else {
                    showTsrNone(hostname, serviceTag);
                }
            } catch (error) {
                bodyEl.innerHTML = '<p style="color: #dc3545;">Error: ' + error.message + '</p>';
            }
        }

        function showTsrRunning(hostname, pct) {
            const bodyEl = document.getElementById('tsr-status-body');
            const footerEl = document.getElementById('tsr-status-footer');
            const pctNum = parseInt(pct, 10) || 0;

            bodyEl.innerHTML =
                '<p>TSR currently running for ' + hostname + '. ' + pctNum + '% completed.</p>' +
                '<div class="tsr-progress-bar"><div class="tsr-progress-fill" style="width: ' + pctNum + '%;"></div></div>';
            footerEl.innerHTML = '<button type="button" class="btn btn-secondary" onclick="closeTsrDialog()">Close</button>';

            startTsrPolling(hostname);
        }

        function showTsrCompleted(hostname, tsrUrl, serviceTag) {
            const bodyEl = document.getElementById('tsr-status-body');
            const footerEl = document.getElementById('tsr-status-footer');

            bodyEl.innerHTML =
                '<p>View completed TSR collections <a href="' + tsrUrl + '" target="_blank">here</a>.</p>';
            footerEl.innerHTML =
                '<button type="button" class="btn btn-secondary" onclick="closeTsrDialog()">Close</button>' +
                '<button type="button" class="btn btn-primary" onclick="startNewTsr(\'' +
                hostname.replace(/'/g, "\\'") + '\', \'' +
                serviceTag.replace(/'/g, "\\'") + '\')">Start New Collection</button>';
        }

        function showTsrNone(hostname, serviceTag) {
            const bodyEl = document.getElementById('tsr-status-body');
            const footerEl = document.getElementById('tsr-status-footer');

            bodyEl.innerHTML = '<p>No active or completed TSR collections found for ' + hostname + '.</p>';
            footerEl.innerHTML =
                '<button type="button" class="btn btn-secondary" onclick="closeTsrDialog()">Close</button>' +
                '<button type="button" class="btn btn-primary" onclick="startNewTsr(\'' +
                hostname.replace(/'/g, "\\'") + '\', \'' +
                serviceTag.replace(/'/g, "\\'") + '\')">Start New Collection</button>';
        }

        async function startNewTsr(hostname, serviceTag) {
            const bodyEl = document.getElementById('tsr-status-body');
            const footerEl = document.getElementById('tsr-status-footer');

            bodyEl.innerHTML = '<p>Initiating TSR collection...</p>';
            footerEl.innerHTML = '<button type="button" class="btn btn-secondary" onclick="closeTsrDialog()">Close</button>';

            try {
                const response = await fetch(apiUrl('/api/tsr-collect'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ hostname: hostname, service_tag: serviceTag })
                });
                const data = await response.json();

                if (data.success) {
                    bodyEl.innerHTML =
                        '<p>TSR initiated for ' + hostname + '.</p>' +
                        '<p>TSR currently running for ' + hostname + '. 0% completed.</p>' +
                        '<div class="tsr-progress-bar"><div class="tsr-progress-fill" style="width: 0%;"></div></div>';
                    startTsrPolling(hostname);
                } else {
                    bodyEl.innerHTML = '<p style="color: #dc3545;">' + data.message + '</p>';
                }
            } catch (error) {
                bodyEl.innerHTML = '<p style="color: #dc3545;">Error: ' + error.message + '</p>';
            }
        }

        function startTsrPolling(hostname) {
            stopTsrPolling();
            tsrPollTimer = setInterval(async () => {
                try {
                    const response = await fetch(apiUrl('/api/tsr-status'), {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({ hostname: hostname })
                    });
                    const data = await response.json();
                    if (!data.success) return;

                    const bodyEl = document.getElementById('tsr-status-body');
                    if (!bodyEl) { stopTsrPolling(); return; }

                    if (data.state === 'running') {
                        const pctNum = parseInt(data.percent_complete, 10) || 0;
                        bodyEl.innerHTML =
                            '<p>TSR currently running for ' + hostname + '. ' + pctNum + '% completed.</p>' +
                            '<div class="tsr-progress-bar"><div class="tsr-progress-fill" style="width: ' + pctNum + '%;"></div></div>';
                    } else if (data.state === 'completed') {
                        stopTsrPolling();
                        const footerEl = document.getElementById('tsr-status-footer');
                        bodyEl.innerHTML =
                            '<p>TSR collection complete for ' + hostname + '.</p>' +
                            '<p>View completed TSR collections <a href="' + data.tsr_url + '" target="_blank">here</a>.</p>';
                        footerEl.innerHTML = '<button type="button" class="btn btn-secondary" onclick="closeTsrDialog()">Close</button>';
                    } else if (data.state === 'none') {
                        stopTsrPolling();
                    }
                } catch (error) {
                    // ignore polling errors
                }
            }, 15000);
        }

        function stopTsrPolling() {
            if (tsrPollTimer) {
                clearInterval(tsrPollTimer);
                tsrPollTimer = null;
            }
        }

        function closeTsrDialog() {
            stopTsrPolling();
            document.getElementById('tsr-status-modal').classList.remove('active');
        }

        // Fetch firmware versions for the selected system's model
        async function fetchFirmwareVersions(system) {
            try {
                // Get the selected row to extract current firmware version
                const selectedRow = selectedRows[0];
                const cells = selectedRow.getElementsByTagName('td');
                const currentFirmwareVersion = cells[3].textContent.trim(); // Column index 3 is firmware
                const model = system.model;

                if (!model) {
                    console.log('DRACS: No model found for selected system');
                    return [];
                }

                console.log('DRACS: Fetching firmware versions for model:', model, 'current version:', currentFirmwareVersion);

                const response = await fetch(`/api/firmware-versions/${encodeURIComponent(model)}`);
                const data = await response.json();

                if (!data.success) {
                    console.error('DRACS: Failed to fetch firmware versions:', data.message);
                    return [];
                }

                console.log('DRACS: Received versions:', data.versions);

                // Filter to only versions newer than current
                const newerVersions = data.versions.filter(version => {
                    const comparison = compareVersions(version, currentFirmwareVersion);
                    return comparison > 0; // Only include if version > currentVersion
                });

                console.log('DRACS: Newer versions:', newerVersions);

                return newerVersions;
            } catch (error) {
                console.error('DRACS: Error fetching firmware versions:', error);
                return [];
            }
        }

        // Populate firmware version dropdown
        function populateFirmwareVersions(selectElement, versions) {
            // Clear existing options
            selectElement.innerHTML = '<option value="">Select firmware version...</option>';

            // Sort versions in descending order (newest first)
            const sortedVersions = versions.slice().sort((a, b) => compareVersions(b, a));

            // Add newer versions
            sortedVersions.forEach(version => {
                const option = document.createElement('option');
                option.value = version;
                option.textContent = version;
                selectElement.appendChild(option);
            });
        }

        // Fetch BIOS versions for the selected system's model
        async function fetchBiosVersions(system) {
            try {
                // Get the selected row to extract current BIOS version
                const selectedRow = selectedRows[0];
                const cells = selectedRow.getElementsByTagName('td');
                const currentBiosVersion = cells[4].textContent.trim(); // Column index 4 is BIOS
                const model = system.model;

                if (!model) {
                    console.log('DRACS: No model found for selected system');
                    return [];
                }

                console.log('DRACS: Fetching BIOS versions for model:', model, 'current version:', currentBiosVersion);

                const response = await fetch(`/api/bios-versions/${encodeURIComponent(model)}`);
                const data = await response.json();

                if (!data.success) {
                    console.error('DRACS: Failed to fetch BIOS versions:', data.message);
                    return [];
                }

                console.log('DRACS: Received BIOS versions:', data.versions);

                // Filter to only versions newer than current
                const newerVersions = data.versions.filter(version => {
                    const comparison = compareVersions(version, currentBiosVersion);
                    return comparison > 0; // Only include if version > currentVersion
                });

                console.log('DRACS: Newer BIOS versions:', newerVersions);

                return newerVersions;
            } catch (error) {
                console.error('DRACS: Error fetching BIOS versions:', error);
                return [];
            }
        }

        // Populate BIOS version dropdown
        function populateBiosVersions(selectElement, versions) {
            // Clear existing options
            selectElement.innerHTML = '<option value="">Select BIOS version...</option>';

            // Sort versions in descending order (newest first)
            const sortedVersions = versions.slice().sort((a, b) => compareVersions(b, a));

            // Add newer versions
            sortedVersions.forEach(version => {
                const option = document.createElement('option');
                option.value = version;
                option.textContent = version;
                selectElement.appendChild(option);
            });
        }

        // Handle firmware version selection
        function handleFirmwareVersionSelect(event) {
            const selectedVersion = event.target.value;

            if (!selectedVersion) {
                return; // User selected the placeholder option
            }

            // Filter to only systems that need updating (don't already have the target version)
            const systemsNeedingUpdate = selectedSystems
                .map((sys, idx) => ({
                    hostname: sys.hostname,
                    currentVersion: selectedRows[idx].dataset.firmwareVersion,
                    serviceTag: sys.service_tag,
                    model: sys.model
                }))
                .filter(sys => compareVersions(selectedVersion, sys.currentVersion) > 0);

            // Check if any systems actually need updating
            if (systemsNeedingUpdate.length === 0) {
                showNotification('All selected systems already have version ' + selectedVersion, 'error');
                event.target.value = '';
                return;
            }

            // Store pending update info for systems that need updating
            pendingFirmwareUpdate = {
                systems: systemsNeedingUpdate,
                newVersion: selectedVersion,
                totalSelected: selectedSystems.length
            };

            const updateCount = pendingFirmwareUpdate.systems.length;

            // Check if we need two-stage confirmation (more than 10 hosts)
            if (updateCount > 10) {
                // First stage: Simple confirmation
                firmwareFirstConfirmation = true;
                const hostnameElement = document.getElementById('firmware-hostname');
                hostnameElement.textContent = `${updateCount} hosts selected`;
                // Show the "Host:" label for first stage
                const hostnameLabel = hostnameElement.previousElementSibling;
                if (hostnameLabel && hostnameLabel.classList.contains('detail-label')) {
                    hostnameLabel.style.display = '';
                }
                document.getElementById('firmware-current-version').textContent = 'N/A';
                document.getElementById('firmware-new-version').textContent = selectedVersion;
                document.querySelector('#firmware-confirm-modal .firmware-warning').textContent = 'Are you sure?';

                const modalTitle = document.querySelector('#firmware-confirm-modal .modal-header h2');
                if (modalTitle) {
                    modalTitle.textContent = 'Confirm Firmware Update';
                }

                document.getElementById('firmware-confirm-modal').classList.add('active');
            } else {
                // Normal confirmation for <= 10 hosts
                firmwareFirstConfirmation = false;
                const hostnamesList = pendingFirmwareUpdate.systems.map(s => s.hostname).join(', ');
                const isBulk = pendingFirmwareUpdate.systems.length > 1;
                const totalCount = pendingFirmwareUpdate.totalSelected;

                // Show the "Host:" label for normal confirmations
                const hostnameElement = document.getElementById('firmware-hostname');
                const hostnameLabel = hostnameElement.previousElementSibling;
                if (hostnameLabel && hostnameLabel.classList.contains('detail-label')) {
                    hostnameLabel.style.display = '';
                }

                if (isBulk || totalCount > 1) {
                    hostnameElement.textContent = `${updateCount} of ${totalCount} selected systems: ${hostnamesList}`;
                    document.getElementById('firmware-current-version').textContent = 'Multiple';
                } else {
                    document.getElementById('firmware-hostname').textContent = pendingFirmwareUpdate.systems[0].hostname;
                    document.getElementById('firmware-current-version').textContent = pendingFirmwareUpdate.systems[0].currentVersion;
                }
                document.getElementById('firmware-new-version').textContent = selectedVersion;
                document.querySelector('#firmware-confirm-modal .firmware-warning').textContent = 'Are you sure you want to proceed with this firmware update?';

                const modalTitle = document.querySelector('#firmware-confirm-modal .modal-header h2');
                if (modalTitle) {
                    modalTitle.textContent = isBulk ? 'Confirm BULK Firmware Update' : 'Confirm Firmware Update';
                }

                document.getElementById('firmware-confirm-modal').classList.add('active');
            }

            // Reset dropdown to placeholder
            event.target.value = '';
        }

        // Confirm firmware update
        async function confirmFirmwareUpdate() {
            if (!pendingFirmwareUpdate) return;

            // Check if this is the first confirmation for large batch
            if (firmwareFirstConfirmation) {
                // Move to second confirmation stage
                firmwareFirstConfirmation = false;

                const updateCount = pendingFirmwareUpdate.systems.length;
                const first10 = pendingFirmwareUpdate.systems.slice(0, 10).map(s => s.hostname).join('<br>');
                const hostnamesList = `<strong>Selection:</strong> ${updateCount} systems<br>${first10}<br>...`;

                const hostnameElement = document.getElementById('firmware-hostname');
                hostnameElement.innerHTML = hostnamesList;
                // Hide the "Host:" label for multi-host display
                const hostnameLabel = hostnameElement.previousElementSibling;
                if (hostnameLabel && hostnameLabel.classList.contains('detail-label')) {
                    hostnameLabel.style.display = 'none';
                }
                document.getElementById('firmware-current-version').textContent = 'Multiple';
                document.getElementById('firmware-new-version').textContent = pendingFirmwareUpdate.newVersion;
                document.querySelector('#firmware-confirm-modal .firmware-warning').textContent = 'Are you sure you want to proceed with this firmware update?';

                const modalTitle = document.querySelector('#firmware-confirm-modal .modal-header h2');
                if (modalTitle) {
                    modalTitle.textContent = 'Confirm BULK Firmware Update';
                }

                // Modal is already open, just updated content
                return;
            }

            // Capture values we need before clearing pendingFirmwareUpdate
            const updateInfo = {
                systems: pendingFirmwareUpdate.systems,
                newVersion: pendingFirmwareUpdate.newVersion
            };
            const isBulk = updateInfo.systems.length > 1;
            console.log('DRACS: User confirmed firmware update to version:', updateInfo.newVersion,
                        'for', isBulk ? `${updateInfo.systems.length} hosts` : updateInfo.systems[0].hostname);

            // Close the confirmation modal first
            document.getElementById('firmware-confirm-modal').classList.remove('active');

            // Clear pending update early to allow new selections
            pendingFirmwareUpdate = null;

            if (isBulk) {
                // Bulk update - skip iDRAC test and initiate all updates
                showNotification(`Initiating bulk firmware update for ${updateInfo.systems.length} hosts...`, 'success');

                try {
                    let successCount = 0;
                    let failCount = 0;

                    for (const system of updateInfo.systems) {
                        try {
                            const updateResponse = await fetch('/api/firmware-update', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                body: JSON.stringify({
                                    hostname: system.hostname,
                                    target_version: updateInfo.newVersion,
                                    model: system.model
                                })
                            });

                            const updateData = await updateResponse.json();

                            if (updateData.success) {
                                successCount++;
                                console.log('DRACS: Firmware update initiated for:', system.hostname);
                            } else {
                                failCount++;
                                console.error('DRACS: Firmware update failed for:', system.hostname, updateData.message);
                            }
                        } catch (error) {
                            failCount++;
                            console.error('DRACS: Error initiating firmware update for:', system.hostname, error);
                        }
                    }

                    showNotification(`Bulk firmware update: ${successCount} initiated, ${failCount} failed`,
                                   failCount === 0 ? 'success' : 'error');
                } catch (error) {
                    console.error('DRACS: Error in bulk firmware update:', error);
                    showNotification('Bulk firmware update failed: ' + error.message, 'error');
                }
            } else {
                // Single host update - test iDRAC first
                const system = updateInfo.systems[0];
                showNotification('Testing iDRAC connectivity...', 'success');

                try {
                    const response = await fetch('/api/test-idrac', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            hostname: system.hostname
                        })
                    });

                    const data = await response.json();

                    if (data.success) {
                        // iDRAC access succeeded
                        showNotification(data.message, 'success');
                        console.log('DRACS: iDRAC connectivity test passed');

                        // Proceed with actual firmware update
                        setTimeout(async () => {
                            showNotification('Initiating firmware update...', 'success');

                            try {
                                const updateResponse = await fetch('/api/firmware-update', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json',
                                    },
                                    body: JSON.stringify({
                                        hostname: system.hostname,
                                        target_version: updateInfo.newVersion,
                                        model: system.model
                                    })
                                });

                                const updateData = await updateResponse.json();

                                if (updateData.success) {
                                    showNotification(updateData.message, 'success');
                                    console.log('DRACS: Firmware update initiated successfully');
                                } else {
                                    showNotification(updateData.message, 'error');
                                    console.error('DRACS: Firmware update failed:', updateData.message);
                                }
                            } catch (error) {
                                console.error('DRACS: Error initiating firmware update:', error);
                                showNotification('Firmware update failed: ' + error.message, 'error');
                            }
                        }, 2000);
                    } else {
                        // iDRAC access failed
                        showNotification(data.message, 'error');
                        console.error('DRACS: iDRAC connectivity test failed:', data.message);
                    }
                } catch (error) {
                    console.error('DRACS: Error testing iDRAC connectivity:', error);
                    showNotification('iDRAC Access Failed: ' + error.message, 'error');
                }
            }
        }

        // Cancel firmware update
        function cancelFirmwareUpdate() {
            console.log('DRACS: User cancelled firmware update');

            // Close modal and clear pending update
            document.getElementById('firmware-confirm-modal').classList.remove('active');
            pendingFirmwareUpdate = null;
            firmwareFirstConfirmation = false;
        }

        // Handle BIOS version selection
        function handleBiosVersionSelect(event) {
            const selectedVersion = event.target.value;

            if (!selectedVersion) {
                return; // User selected the placeholder option
            }

            // Filter to only systems that need updating (don't already have the target version)
            const systemsNeedingUpdate = selectedSystems
                .map((sys, idx) => ({
                    hostname: sys.hostname,
                    currentVersion: selectedRows[idx].dataset.biosVersion,
                    serviceTag: sys.service_tag,
                    model: sys.model
                }))
                .filter(sys => compareVersions(selectedVersion, sys.currentVersion) > 0);

            // Check if any systems actually need updating
            if (systemsNeedingUpdate.length === 0) {
                showNotification('All selected systems already have BIOS version ' + selectedVersion, 'error');
                event.target.value = '';
                return;
            }

            // Store pending update info for systems that need updating
            pendingBiosUpdate = {
                systems: systemsNeedingUpdate,
                newVersion: selectedVersion,
                totalSelected: selectedSystems.length
            };

            const updateCount = pendingBiosUpdate.systems.length;

            // Check if we need two-stage confirmation (more than 10 hosts)
            if (updateCount > 10) {
                // First stage: Simple confirmation
                biosFirstConfirmation = true;
                const hostnameElement = document.getElementById('bios-hostname');
                hostnameElement.textContent = `${updateCount} hosts selected`;
                // Show the "Host:" label for first stage
                const hostnameLabel = hostnameElement.previousElementSibling;
                if (hostnameLabel && hostnameLabel.classList.contains('detail-label')) {
                    hostnameLabel.style.display = '';
                }
                document.getElementById('bios-current-version').textContent = 'N/A';
                document.getElementById('bios-new-version').textContent = selectedVersion;
                document.querySelector('#bios-confirm-modal .firmware-warning').textContent = 'Are you sure?';

                const modalTitle = document.querySelector('#bios-confirm-modal .modal-header h2');
                if (modalTitle) {
                    modalTitle.textContent = 'Confirm BIOS Update';
                }

                document.getElementById('bios-confirm-modal').classList.add('active');
            } else {
                // Normal confirmation for <= 10 hosts
                biosFirstConfirmation = false;
                const hostnamesList = pendingBiosUpdate.systems.map(s => s.hostname).join(', ');
                const isBulk = pendingBiosUpdate.systems.length > 1;
                const totalCount = pendingBiosUpdate.totalSelected;

                // Show the "Host:" label for normal confirmations
                const hostnameElement = document.getElementById('bios-hostname');
                const hostnameLabel = hostnameElement.previousElementSibling;
                if (hostnameLabel && hostnameLabel.classList.contains('detail-label')) {
                    hostnameLabel.style.display = '';
                }

                if (isBulk || totalCount > 1) {
                    hostnameElement.textContent = `${updateCount} of ${totalCount} selected systems: ${hostnamesList}`;
                    document.getElementById('bios-current-version').textContent = 'Multiple';
                } else {
                    document.getElementById('bios-hostname').textContent = pendingBiosUpdate.systems[0].hostname;
                    document.getElementById('bios-current-version').textContent = pendingBiosUpdate.systems[0].currentVersion;
                }
                document.getElementById('bios-new-version').textContent = selectedVersion;
                document.querySelector('#bios-confirm-modal .firmware-warning').textContent = 'Are you sure you want to proceed with this BIOS update?';

                const modalTitle = document.querySelector('#bios-confirm-modal .modal-header h2');
                if (modalTitle) {
                    modalTitle.textContent = isBulk ? 'Confirm BULK BIOS Update' : 'Confirm BIOS Update';
                }

                document.getElementById('bios-confirm-modal').classList.add('active');
            }

            // Reset dropdown to placeholder
            event.target.value = '';
        }

        // Confirm BIOS update
        async function confirmBiosUpdate() {
            if (!pendingBiosUpdate) return;

            // Check if this is the first confirmation for large batch
            if (biosFirstConfirmation) {
                // Move to second confirmation stage
                biosFirstConfirmation = false;

                const updateCount = pendingBiosUpdate.systems.length;
                const first10 = pendingBiosUpdate.systems.slice(0, 10).map(s => s.hostname).join('<br>');
                const hostnamesList = `<strong>Selection:</strong> ${updateCount} systems<br>${first10}<br>...`;

                const hostnameElement = document.getElementById('bios-hostname');
                hostnameElement.innerHTML = hostnamesList;
                // Hide the "Host:" label for multi-host display
                const hostnameLabel = hostnameElement.previousElementSibling;
                if (hostnameLabel && hostnameLabel.classList.contains('detail-label')) {
                    hostnameLabel.style.display = 'none';
                }
                document.getElementById('bios-current-version').textContent = 'Multiple';
                document.getElementById('bios-new-version').textContent = pendingBiosUpdate.newVersion;
                document.querySelector('#bios-confirm-modal .firmware-warning').textContent = 'Are you sure you want to proceed with this BIOS update?';

                const modalTitle = document.querySelector('#bios-confirm-modal .modal-header h2');
                if (modalTitle) {
                    modalTitle.textContent = 'Confirm BULK BIOS Update';
                }

                // Modal is already open, just updated content
                return;
            }

            // Capture values we need before clearing pendingBiosUpdate
            const updateInfo = {
                systems: pendingBiosUpdate.systems,
                newVersion: pendingBiosUpdate.newVersion
            };
            const isBulk = updateInfo.systems.length > 1;
            console.log('DRACS: User confirmed BIOS update to version:', updateInfo.newVersion,
                        'for', isBulk ? `${updateInfo.systems.length} hosts` : updateInfo.systems[0].hostname);

            // Close the confirmation modal first
            document.getElementById('bios-confirm-modal').classList.remove('active');

            // Clear pending update early to allow new selections
            pendingBiosUpdate = null;

            if (isBulk) {
                // Bulk update - skip iDRAC test and initiate all updates
                showNotification(`Initiating bulk BIOS update for ${updateInfo.systems.length} hosts...`, 'success');

                try {
                    let successCount = 0;
                    let failCount = 0;

                    for (const system of updateInfo.systems) {
                        try {
                            const updateResponse = await fetch('/api/bios-update', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                body: JSON.stringify({
                                    hostname: system.hostname,
                                    target_bios: updateInfo.newVersion,
                                    model: system.model
                                })
                            });

                            const updateData = await updateResponse.json();

                            if (updateData.success) {
                                successCount++;
                                console.log('DRACS: BIOS update initiated for:', system.hostname);
                            } else {
                                failCount++;
                                console.error('DRACS: BIOS update failed for:', system.hostname, updateData.message);
                            }
                        } catch (error) {
                            failCount++;
                            console.error('DRACS: Error initiating BIOS update for:', system.hostname, error);
                        }
                    }

                    showNotification(`Bulk BIOS update: ${successCount} initiated, ${failCount} failed`,
                                   failCount === 0 ? 'success' : 'error');
                } catch (error) {
                    console.error('DRACS: Error in bulk BIOS update:', error);
                    showNotification('Bulk BIOS update failed: ' + error.message, 'error');
                }
            } else {
                // Single host update - test iDRAC first
                const system = updateInfo.systems[0];
                showNotification('Testing iDRAC connectivity...', 'success');

                try {
                    const response = await fetch('/api/test-idrac', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            hostname: system.hostname
                        })
                    });

                    const data = await response.json();

                    if (data.success) {
                        // iDRAC access succeeded
                        showNotification(data.message, 'success');
                        console.log('DRACS: iDRAC connectivity test passed');

                        // Proceed with actual BIOS update
                        setTimeout(async () => {
                            showNotification('Initiating BIOS update...', 'success');

                            try {
                                const updateResponse = await fetch('/api/bios-update', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json',
                                    },
                                    body: JSON.stringify({
                                        hostname: system.hostname,
                                        target_bios: updateInfo.newVersion,
                                        model: system.model
                                    })
                                });

                                const updateData = await updateResponse.json();

                                if (updateData.success) {
                                    showNotification(updateData.message, 'success');
                                    console.log('DRACS: BIOS update initiated successfully');
                                } else {
                                    showNotification(updateData.message, 'error');
                                    console.error('DRACS: BIOS update failed:', updateData.message);
                                }
                            } catch (error) {
                                console.error('DRACS: Error initiating BIOS update:', error);
                                showNotification('BIOS update failed: ' + error.message, 'error');
                            }
                        }, 2000);
                    } else {
                        // iDRAC access failed
                        showNotification(data.message, 'error');
                        console.error('DRACS: iDRAC connectivity test failed:', data.message);
                    }
                } catch (error) {
                    console.error('DRACS: Error testing iDRAC connectivity:', error);
                    showNotification('iDRAC Access Failed: ' + error.message, 'error');
                }
            }
        }

        // Cancel BIOS update
        function cancelBiosUpdate() {
            console.log('DRACS: User cancelled BIOS update');

            // Close modal and clear pending update
            document.getElementById('bios-confirm-modal').classList.remove('active');
            pendingBiosUpdate = null;
            biosFirstConfirmation = false;
        }

        // Handle Job Queue button click
        async function handleJobQueueClick() {
            if (selectedSystems.length !== 1) {
                showNotification('Please select exactly one system', 'error');
                return;
            }

            const system = selectedSystems[0];
            showNotification('Testing iDRAC connectivity...', 'success');

            try {
                const response = await fetch('/api/test-idrac', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        hostname: system.hostname
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // iDRAC access succeeded
                    showNotification(data.message, 'success');
                    console.log('DRACS: iDRAC connectivity test passed for job queue');

                    // Fetch job queue data
                    setTimeout(async () => {
                        showNotification('Fetching job queue...', 'success');

                        try {
                            const jobResponse = await fetch('/api/job-queue', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                body: JSON.stringify({
                                    hostname: system.hostname
                                })
                            });

                            const jobData = await jobResponse.json();

                            if (jobData.success) {
                                showNotification('Job queue retrieved successfully', 'success');
                                displayJobQueue(system.hostname, jobData.jobs);
                            } else {
                                showNotification(jobData.message, 'error');
                                console.error('DRACS: Job queue fetch failed:', jobData.message);
                            }
                        } catch (error) {
                            console.error('DRACS: Error fetching job queue:', error);
                            showNotification('Job queue fetch failed: ' + error.message, 'error');
                        }
                    }, 2000);
                } else {
                    // iDRAC access failed
                    showNotification(data.message, 'error');
                    console.error('DRACS: iDRAC connectivity test failed:', data.message);
                }
            } catch (error) {
                console.error('DRACS: Error testing iDRAC connectivity:', error);
                showNotification('iDRAC Access Failed: ' + error.message, 'error');
            }
        }

        // Display job queue in modal
        function displayJobQueue(hostname, jobs) {
            document.getElementById('job-queue-hostname').textContent = hostname;
            const tbody = document.getElementById('job-queue-tbody');
            tbody.innerHTML = '';

            if (!jobs || jobs.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="7" style="text-align: center;">No jobs found</td>';
                tbody.appendChild(row);
            } else {
                jobs.forEach(job => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${job.job_id || ''}</td>
                        <td>${job.job_name || ''}</td>
                        <td>${job.status || ''}</td>
                        <td>${job.actual_start_time || ''}</td>
                        <td>${job.actual_completion_time || ''}</td>
                        <td>${job.message || ''}</td>
                        <td>${job.percent_complete || ''}</td>
                    `;
                    tbody.appendChild(row);
                });
            }

            document.getElementById('job-queue-modal').classList.add('active');
        }

        // Dismiss job queue modal
        function dismissJobQueue() {
            document.getElementById('job-queue-modal').classList.remove('active');
            document.getElementById('job-queue-tbody').innerHTML = '';
        }

        // Handle Clear Job Queue button click
        function handleClearJobQueueClick() {
            if (selectedSystems.length === 0) {
                showNotification('Please select at least one system', 'error');
                return;
            }

            const hostCount = selectedSystems.length;
            let confirmMsg;
            if (hostCount === 1) {
                confirmMsg = `You are about to clear all non-applied jobs on <strong>${selectedSystems[0].hostname}</strong>.  Are you sure?`;
            } else {
                confirmMsg = `You are about to clear all non-applied jobs on <strong>${hostCount}</strong> hosts.  Are you sure?`;
            }

            document.getElementById('clear-jq-confirm-message').innerHTML = confirmMsg;
            document.getElementById('clear-jq-confirm-modal').classList.add('active');
        }

        function cancelClearJobQueue() {
            document.getElementById('clear-jq-confirm-modal').classList.remove('active');
        }

        async function proceedClearJobQueue() {
            document.getElementById('clear-jq-confirm-modal').classList.remove('active');

            try {
                const response = await fetch('/api/clear-job-queue', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        hostnames: selectedSystems.map(sys => sys.hostname)
                    })
                });

                const data = await response.json();

                if (data.success) {
                    showNotification(data.message, 'success');
                } else {
                    showNotification(data.message, 'error');
                }
            } catch (error) {
                console.error('DRACS: Error clearing job queue:', error);
                showNotification('Clear job queue failed: ' + error.message, 'error');
            }
        }

        // Force Firmware/BIOS state
        let forceTarget = null;
        let forceVersion = null;

        function updateForceButtonState() {
            const forceFwBtn = document.getElementById('force-firmware-btn');
            const forceBiosBtn = document.getElementById('force-bios-btn');
            if (!forceFwBtn || !forceBiosBtn) return;

            if (selectedSystems.length === 1) {
                forceFwBtn.disabled = false;
                forceBiosBtn.disabled = false;
            } else {
                forceFwBtn.disabled = true;
                forceBiosBtn.disabled = true;
            }
        }

        async function handleForceFirmwareClick() {
            if (selectedSystems.length !== 1) return;
            const sys = selectedSystems[0];
            const hostname = sys.hostname;
            const model = sys.model;
            const currentVersion = selectedRows[0].dataset.firmwareVersion;

            forceTarget = { hostname, model, currentVersion, type: 'firmware' };

            document.getElementById('force-firmware-hostname').textContent = hostname;
            document.getElementById('force-firmware-current').textContent = currentVersion;

            try {
                const resp = await fetch(`/api/available-firmware/${encodeURIComponent(model)}`);
                const data = await resp.json();
                if (!data.success) {
                    showNotification(data.message, 'error');
                    return;
                }
                const versions = data.versions.filter(v => v !== currentVersion);
                const select = document.getElementById('force-firmware-select');
                select.innerHTML = '<option value="">Select Firmware Version...</option>';
                versions.forEach(v => {
                    const opt = document.createElement('option');
                    opt.value = v;
                    opt.textContent = v;
                    select.appendChild(opt);
                });
                if (versions.length === 0) {
                    showNotification('No other firmware versions available on disk.', 'error');
                    return;
                }
                document.getElementById('force-firmware-modal').classList.add('active');
            } catch (error) {
                showNotification('Failed to fetch available firmware: ' + error.message, 'error');
            }
        }

        async function handleForceBiosClick() {
            if (selectedSystems.length !== 1) return;
            const sys = selectedSystems[0];
            const hostname = sys.hostname;
            const model = sys.model;
            const currentVersion = selectedRows[0].dataset.biosVersion;

            forceTarget = { hostname, model, currentVersion, type: 'bios' };

            document.getElementById('force-bios-hostname').textContent = hostname;
            document.getElementById('force-bios-current').textContent = currentVersion;

            try {
                const resp = await fetch(`/api/available-bios/${encodeURIComponent(model)}`);
                const data = await resp.json();
                if (!data.success) {
                    showNotification(data.message, 'error');
                    return;
                }
                const versions = data.versions.filter(v => v !== currentVersion);
                const select = document.getElementById('force-bios-select');
                select.innerHTML = '<option value="">Select BIOS Version...</option>';
                versions.forEach(v => {
                    const opt = document.createElement('option');
                    opt.value = v;
                    opt.textContent = v;
                    select.appendChild(opt);
                });
                if (versions.length === 0) {
                    showNotification('No other BIOS versions available on disk.', 'error');
                    return;
                }
                document.getElementById('force-bios-modal').classList.add('active');
            } catch (error) {
                showNotification('Failed to fetch available BIOS: ' + error.message, 'error');
            }
        }

        function selectForceVersion(type) {
            const selectId = type === 'firmware' ? 'force-firmware-select' : 'force-bios-select';
            const version = document.getElementById(selectId).value;
            if (!version) return;

            forceVersion = version;
            const hostname = forceTarget.hostname;

            document.getElementById(`force-${type}-modal`).classList.remove('active');

            const label = type === 'firmware' ? 'Firmware' : 'BIOS';
            document.getElementById(`force-${type}-confirm-msg`).textContent =
                `WARNING! You are about to change the ${label} on ${hostname} to ${version}.  Are you sure you want to proceed?`;
            document.getElementById(`force-${type}-confirm-modal`).classList.add('active');
        }

        function cancelForceUpdate() {
            document.getElementById('force-firmware-modal').classList.remove('active');
            document.getElementById('force-bios-modal').classList.remove('active');
            document.getElementById('force-firmware-confirm-modal').classList.remove('active');
            document.getElementById('force-bios-confirm-modal').classList.remove('active');
            forceTarget = null;
            forceVersion = null;
        }

        async function confirmForceUpdate(type) {
            document.getElementById(`force-${type}-confirm-modal`).classList.remove('active');

            const hostname = forceTarget.hostname;
            const model = forceTarget.model;
            const version = forceVersion;
            const label = type === 'firmware' ? 'Firmware' : 'BIOS';

            try {
                const endpoint = type === 'firmware' ? '/api/firmware-update' : '/api/bios-update';
                const body = type === 'firmware'
                    ? { hostname, target_version: version, model }
                    : { hostname, target_bios: version, model };

                const resp = await fetch(endpoint, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(body)
                });
                const data = await resp.json();
                if (data.success) {
                    showNotification(`Initiating ${label} ${version} for ${hostname}`, 'success');
                } else {
                    showNotification(data.message, 'error');
                }
            } catch (error) {
                showNotification(`Force ${label} update failed: ${error.message}`, 'error');
            }

            forceTarget = null;
            forceVersion = null;
        }

        // Auto-refresh functionality
        function startAutoRefresh() {
            if (refreshFrequency > 0) {
                console.log('DRACS: Starting auto-refresh every', refreshFrequency, 'seconds');
                autoRefreshTimer = setInterval(() => {
                    console.log('DRACS: Auto-refreshing table data');
                    refreshTableData();
                }, refreshFrequency * 1000);
            } else {
                console.log('DRACS: Auto-refresh disabled (frequency = 0)');
            }
        }

        function stopAutoRefresh() {
            if (autoRefreshTimer) {
                clearInterval(autoRefreshTimer);
                autoRefreshTimer = null;
                console.log('DRACS: Auto-refresh stopped');
            }
        }

        // Notification functions
        function showNotification(message, type) {
            const notification = document.getElementById('notification');
            const messageSpan = document.getElementById('notification-message');

            messageSpan.textContent = message;
            notification.className = 'notification active ' + type;

            // Auto-hide success messages after 5 seconds
            if (type === 'success') {
                setTimeout(() => {
                    hideNotification();
                }, 5000);
            }
        }

        function hideNotification() {
            document.getElementById('notification').classList.remove('active');
        }

        // Custom Filter Functions
        function showDiscoverModal() {
            document.getElementById('discover-textarea').value = '';
            document.getElementById('discover-modal').classList.add('active');
            document.getElementById('discover-textarea').focus();
        }
        function hideDiscoverModal() {
            document.getElementById('discover-modal').classList.remove('active');
        }
        async function submitDiscover() {
            const text = document.getElementById('discover-textarea').value.trim();
            if (!text) { hideDiscoverModal(); return; }
            const hostnames = text.split('\n').map(h => h.trim()).filter(h => h);
            if (hostnames.length === 0) { hideDiscoverModal(); return; }
            hideDiscoverModal();
            showNotification('Queuing discovery for ' + hostnames.length + ' host(s)...', 'success');
            try {
                const response = await fetch(apiUrl('/api/discover'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({hostnames: hostnames})
                });
                const data = await response.json();
                if (data.success) {
                    showNotification(data.message, 'success');
                } else {
                    showNotification(data.message || 'Discovery failed', 'error');
                }
            } catch (err) {
                showNotification('Discovery request failed: ' + err.message, 'error');
            }
        }

        function showDeleteModal() {
            if (selectedSystems.length === 0) return;
            document.getElementById('delete-count-display').textContent = selectedSystems.length;
            document.getElementById('delete-confirm-modal').classList.add('active');
        }
        function hideDeleteModal() {
            document.getElementById('delete-confirm-modal').classList.remove('active');
        }
        async function submitDelete() {
            const hostnames = selectedSystems.map(s => s.hostname);
            hideDeleteModal();
            try {
                const response = await fetch(apiUrl('/api/delete-systems'), {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({hostnames: hostnames})
                });
                const data = await response.json();
                if (data.success) {
                    showNotification(data.message, 'success');
                    selectedRows = [];
                    selectedSystems = [];
                    refreshTableData();
                } else {
                    showNotification(data.message || 'Delete failed', 'error');
                }
            } catch (err) {
                showNotification('Delete request failed: ' + err.message, 'error');
            }
        }

        function showCustomFilterModal() {
            document.getElementById('custom-filter-modal').classList.add('active');
            document.getElementById('custom-filter-textarea').focus();
        }

        function hideCustomFilterModal() {
            document.getElementById('custom-filter-modal').classList.remove('active');
        }

        function applyCustomFilter() {
            const textarea = document.getElementById('custom-filter-textarea');
            const input = textarea.value.trim();

            if (input === '') {
                customFilterHostnames = [];
            } else {
                // Split by newlines and filter out empty lines
                customFilterHostnames = input.split('\n')
                    .map(line => line.trim().toLowerCase())
                    .filter(line => line.length > 0);
            }

            hideCustomFilterModal();
            applyFilters();

            if (customFilterHostnames.length > 0) {
                showNotification(`Custom filter applied: ${customFilterHostnames.length} hostname${customFilterHostnames.length > 1 ? 's' : ''}`, 'success');
            }
        }

        function clearCustomFilter() {
            customFilterHostnames = [];
            document.getElementById('custom-filter-textarea').value = '';
            applyFilters();
            showNotification('Custom filter cleared', 'success');
        }

        function clearAllFilters() {
            // Clear text input filters
            document.getElementById('hostname-filter').value = '';
            document.getElementById('servicetag-filter').value = '';

            // Clear model filter (multi-select)
            const modelFilter = document.getElementById('model-filter');
            for (let option of modelFilter.options) {
                option.selected = false;
            }

            // Clear warranty filters
            document.getElementById('warranty-expired').checked = false;
            document.getElementById('warranty-expires').value = '';

            // Clear firmware filters
            document.getElementById('firmware-version').value = '';
            document.getElementById('firmware-operator').value = '';
            document.getElementById('firmware-current').checked = false;
            document.getElementById('firmware-older').checked = false;
            document.getElementById('firmware-oldest').checked = false;

            // Clear BIOS filters
            document.getElementById('bios-version').value = '';
            document.getElementById('bios-operator').value = '';
            document.getElementById('bios-current').checked = false;
            document.getElementById('bios-older').checked = false;
            document.getElementById('bios-oldest').checked = false;

            // Clear custom filter
            customFilterHostnames = [];
            document.getElementById('custom-filter-textarea').value = '';

            applyFilters();
            showNotification('All filters cleared', 'success');
        }

        // Close modal on background click
        document.getElementById('login-modal').addEventListener('click', function(event) {
            if (event.target === this) {
                hideLoginModal();
            }
        });

        // Close user management modal on background click
        const userMgmtModal = document.getElementById('user-management-modal');
        if (userMgmtModal) {
            userMgmtModal.addEventListener('click', function(event) {
                if (event.target === this) {
                    hideUserManagementModal();
                }
            });
        }

        // Close change password modal on background click
        const cpModal = document.getElementById('change-password-modal');
        if (cpModal) {
            cpModal.addEventListener('click', function(event) {
                if (event.target === this) {
                    hideChangePasswordModal();
                }
            });
        }

        // Close self-service password modal on background click
        const spModal = document.getElementById('self-password-modal');
        if (spModal) {
            spModal.addEventListener('click', function(event) {
                if (event.target === this) {
                    hideSelfPasswordModal();
                }
            });
        }

        // Close discover modal on background click
        document.getElementById('discover-modal').addEventListener('click', function(event) {
            if (event.target === this) { hideDiscoverModal(); }
        });

        // Close delete confirmation modal on background click
        document.getElementById('delete-confirm-modal').addEventListener('click', function(event) {
            if (event.target === this) { hideDeleteModal(); }
        });

        // Close firmware confirmation modal on background click
        document.getElementById('firmware-confirm-modal').addEventListener('click', function(event) {
            if (event.target === this) {
                cancelFirmwareUpdate();
            }
        });

        // Close BIOS confirmation modal on background click
        document.getElementById('bios-confirm-modal').addEventListener('click', function(event) {
            if (event.target === this) {
                cancelBiosUpdate();
            }
        });

        // Close job queue modal on background click
        document.getElementById('job-queue-modal').addEventListener('click', function(event) {
            if (event.target === this) {
                dismissJobQueue();
            }
        });

        // Close custom filter modal on background click
        document.getElementById('custom-filter-modal').addEventListener('click', function(event) {
            if (event.target === this) {
                hideCustomFilterModal();
            }
        });

        // Embed data from Flask
        let systems = {{ systems_json | safe }};  // Use let instead of const so it can be reassigned during refresh
        const biosVersions = {{ bios_versions_json | safe }};
        const firmwareVersions = {{ firmware_versions_json | safe }};
        const models = {{ models_json | safe }};

        // Get filter elements
        const hostnameFilter = document.getElementById('hostname-filter');
        const servicetagFilter = document.getElementById('servicetag-filter');
        const modelFilter = document.getElementById('model-filter');
        const biosVersionSelect = document.getElementById('bios-version');
        const biosOperatorSelect = document.getElementById('bios-operator');
        const firmwareVersionSelect = document.getElementById('firmware-version');
        const firmwareOperatorSelect = document.getElementById('firmware-operator');
        const firmwareCurrentCheck = document.getElementById('firmware-current');
        const firmwareOlderCheck = document.getElementById('firmware-older');
        const firmwareOldestCheck = document.getElementById('firmware-oldest');
        const biosCurrentCheck = document.getElementById('bios-current');
        const biosOlderCheck = document.getElementById('bios-older');
        const biosOldestCheck = document.getElementById('bios-oldest');
        const warrantyExpiredCheck = document.getElementById('warranty-expired');
        const warrantyExpiresSelect = document.getElementById('warranty-expires');
        const tableBody = document.getElementById('table-body');
        const resultsCount = document.getElementById('results-count');
        const totalCount = document.getElementById('total-count');
        const noResults = document.getElementById('no-results');

        // Populate version dropdowns
        biosVersions.forEach(version => {
            const option = document.createElement('option');
            option.value = version;
            option.textContent = version;
            biosVersionSelect.appendChild(option);
        });

        firmwareVersions.forEach(version => {
            const option = document.createElement('option');
            option.value = version;
            option.textContent = version;
            firmwareVersionSelect.appendChild(option);
        });

        // Populate model multi-select dropdown
        models.forEach(model => {
            const option = document.createElement('option');
            option.value = model;
            option.textContent = model;
            modelFilter.appendChild(option);
        });

        // Version comparison function
        function parseVersion(versionStr) {
            if (!versionStr) return [];
            return versionStr.split('.').map(part => {
                const num = parseInt(part, 10);
                return isNaN(num) ? 0 : num;
            });
        }

        function compareVersions(v1, v2) {
            const parts1 = parseVersion(v1);
            const parts2 = parseVersion(v2);
            const maxLen = Math.max(parts1.length, parts2.length);

            for (let i = 0; i < maxLen; i++) {
                const p1 = parts1[i] || 0;
                const p2 = parts2[i] || 0;

                if (p1 < p2) return -1;
                if (p1 > p2) return 1;
            }
            return 0;
        }

        function matchesVersionFilter(systemVersion, filterVersion, operator) {
            if (!operator || !filterVersion) return true;
            if (!systemVersion) return false;

            const cmp = compareVersions(systemVersion, filterVersion);

            switch (operator) {
                case '<=': return cmp <= 0;
                case '<': return cmp < 0;
                case '>=': return cmp >= 0;
                case '>': return cmp > 0;
                case '=': return cmp === 0;
                default: return true;
            }
        }

        // Create table row
        function createRow(system) {
            const row = document.createElement('tr');
            row.dataset.hostname = (system.name || '').toLowerCase();
            row.dataset.serviceTag = (system.svc_tag || '').toLowerCase();
            row.dataset.model = system.model || '';
            row.dataset.biosVersion = system.bios_version || '';
            row.dataset.firmwareVersion = system.idrac_version || '';
            row.dataset.expEpoch = system.exp_epoch || '';

            row.innerHTML = `
                <td>${system.svc_tag || ''}</td>
                <td>${system.name || ''}</td>
                <td>${system.model || ''}</td>
                <td>${system.idrac_version || ''}</td>
                <td>${system.bios_version || ''}</td>
                <td>${system.exp_date || ''}</td>
            `;

            // Get cells for highlighting
            const cells = row.getElementsByTagName('td');

            // Apply warranty expiration highlighting to the expiration date cell (column 5)
            if (system.exp_epoch) {
                const currentTime = Math.floor(Date.now() / 1000);  // Current time in seconds (UNIX timestamp)
                const expirationTime = parseInt(system.exp_epoch);

                if (highlightExpired && expirationTime < currentTime) {
                    // Warranty has expired - highlight cell in red
                    cells[5].classList.add('warranty-expired');
                } else if (highlightExpiring > 0) {
                    // Check if warranty is expiring soon
                    const daysUntilExpiration = (expirationTime - currentTime) / (60 * 60 * 24);
                    if (daysUntilExpiration > 0 && daysUntilExpiration <= highlightExpiring) {
                        // Warranty expiring within threshold - highlight cell in yellow
                        cells[5].classList.add('warranty-expiring');
                    }
                }
            }

            // Apply firmware and BIOS version highlighting to cells

            // Firmware highlighting (column index 3)
            if (highlightFirmware && system.model && system.idrac_version) {
                const modelVersions = firmwareVersionsByModel[system.model];
                if (modelVersions && modelVersions.length > 0) {
                    const versionsBehind = getVersionsBehind(system.idrac_version, modelVersions);
                    if (versionsBehind === 1) {
                        cells[3].classList.add('firmware-outdated-1');
                    } else if (versionsBehind >= 2) {
                        cells[3].classList.add('firmware-outdated-2plus');
                    }
                }
            }

            // BIOS highlighting (column index 4)
            if (highlightBios && system.model && system.bios_version) {
                const modelVersions = biosVersionsByModel[system.model];
                if (modelVersions && modelVersions.length > 0) {
                    const versionsBehind = getVersionsBehind(system.bios_version, modelVersions);
                    if (versionsBehind === 1) {
                        cells[4].classList.add('bios-outdated-1');
                    } else if (versionsBehind >= 2) {
                        cells[4].classList.add('bios-outdated-2plus');
                    }
                }
            }

            return row;
        }

        // Calculate how many versions behind a given version is
        function getVersionsBehind(currentVersion, allVersionsSorted) {
            if (!currentVersion || !allVersionsSorted || allVersionsSorted.length === 0) {
                return 0;
            }

            // Find the index of the current version in the sorted list (newest first)
            const currentIndex = allVersionsSorted.findIndex(v => v === currentVersion);

            if (currentIndex === -1) {
                // Version not found in list, assume it's outdated
                return allVersionsSorted.length;
            }

            // If index is 0, it's the newest version
            // If index is 1, it's one version behind
            // If index is 2+, it's 2+ versions behind
            return currentIndex;
        }

        // Calculate all unique firmware and BIOS versions from systems data
        function calculateAllVersions() {
            // Reset the objects
            firmwareVersionsByModel = {};
            biosVersionsByModel = {};

            // Defensive check
            if (!systems || !Array.isArray(systems)) {
                console.warn('DRACS: systems is not an array in calculateAllVersions');
                return;
            }

            // Group firmware versions by model
            systems.forEach(system => {
                if (system.model && system.idrac_version) {
                    if (!firmwareVersionsByModel[system.model]) {
                        firmwareVersionsByModel[system.model] = new Set();
                    }
                    firmwareVersionsByModel[system.model].add(system.idrac_version);
                }
            });

            // Convert sets to sorted arrays (newest first)
            for (const model in firmwareVersionsByModel) {
                firmwareVersionsByModel[model] = Array.from(firmwareVersionsByModel[model])
                    .sort((a, b) => compareVersions(b, a));
            }

            // Group BIOS versions by model
            systems.forEach(system => {
                if (system.model && system.bios_version) {
                    if (!biosVersionsByModel[system.model]) {
                        biosVersionsByModel[system.model] = new Set();
                    }
                    biosVersionsByModel[system.model].add(system.bios_version);
                }
            });

            // Convert sets to sorted arrays (newest first)
            for (const model in biosVersionsByModel) {
                biosVersionsByModel[model] = Array.from(biosVersionsByModel[model])
                    .sort((a, b) => compareVersions(b, a));
            }

            console.log('DRACS: Calculated firmware versions by model:', firmwareVersionsByModel);
            console.log('DRACS: Calculated BIOS versions by model:', biosVersionsByModel);
        }

        // Update firmware and BIOS version dropdowns based on selected models
        function updateVersionDropdowns() {
            const selectedModels = Array.from(modelFilter.selectedOptions).map(opt => opt.value);

            // Save currently selected values
            const currentFirmwareVersion = firmwareVersionSelect.value;
            const currentBiosVersion = biosVersionSelect.value;

            // Determine which versions to show
            let firmwareVersionsToShow, biosVersionsToShow;

            if (selectedModels.length === 0) {
                // No models selected - show all versions
                firmwareVersionsToShow = firmwareVersions;
                biosVersionsToShow = biosVersions;
            } else {
                // Models selected - show only versions that exist in selected models
                const firmwareVersionSet = new Set();
                const biosVersionSet = new Set();

                selectedModels.forEach(model => {
                    // Add firmware versions for this model
                    if (firmwareVersionsByModel[model]) {
                        firmwareVersionsByModel[model].forEach(version => {
                            firmwareVersionSet.add(version);
                        });
                    }

                    // Add BIOS versions for this model
                    if (biosVersionsByModel[model]) {
                        biosVersionsByModel[model].forEach(version => {
                            biosVersionSet.add(version);
                        });
                    }
                });

                // Convert to sorted arrays (newest first)
                firmwareVersionsToShow = Array.from(firmwareVersionSet).sort((a, b) => compareVersions(b, a));
                biosVersionsToShow = Array.from(biosVersionSet).sort((a, b) => compareVersions(b, a));
            }

            // Rebuild firmware version dropdown
            firmwareVersionSelect.innerHTML = '<option value="">(all versions)</option>';
            firmwareVersionsToShow.forEach(version => {
                const option = document.createElement('option');
                option.value = version;
                option.textContent = version;
                firmwareVersionSelect.appendChild(option);
            });

            // Rebuild BIOS version dropdown
            biosVersionSelect.innerHTML = '<option value="">(all versions)</option>';
            biosVersionsToShow.forEach(version => {
                const option = document.createElement('option');
                option.value = version;
                option.textContent = version;
                biosVersionSelect.appendChild(option);
            });

            // Restore previously selected values if they still exist in the filtered lists
            if (currentFirmwareVersion && firmwareVersionsToShow.includes(currentFirmwareVersion)) {
                firmwareVersionSelect.value = currentFirmwareVersion;
            }
            if (currentBiosVersion && biosVersionsToShow.includes(currentBiosVersion)) {
                biosVersionSelect.value = currentBiosVersion;
            }
        }

        // Filter rows
        function applyFilters() {
            const hostnameText = hostnameFilter.value.toLowerCase();
            const servicetagText = servicetagFilter.value.toLowerCase();
            const biosVersion = biosVersionSelect.value;
            const biosOperator = biosOperatorSelect.value;
            const firmwareVersion = firmwareVersionSelect.value;
            const firmwareOperator = firmwareOperatorSelect.value;

            // Get checkbox states
            const firmwareCurrent = firmwareCurrentCheck.checked;
            const firmwareOlder = firmwareOlderCheck.checked;
            const firmwareOldest = firmwareOldestCheck.checked;
            const biosCurrent = biosCurrentCheck.checked;
            const biosOlder = biosOlderCheck.checked;
            const biosOldest = biosOldestCheck.checked;
            const warrantyExpired = warrantyExpiredCheck.checked;
            const warrantyExpiresDays = warrantyExpiresSelect.value;

            // Get selected models from multi-select
            const selectedModels = Array.from(modelFilter.selectedOptions).map(opt => opt.value);

            let visibleCount = 0;

            const rows = tableBody.querySelectorAll('tr');
            rows.forEach(row => {
                const hostname = row.dataset.hostname;
                const servicetag = row.dataset.serviceTag;
                const rowModel = row.dataset.model;
                const rowBiosVersion = row.dataset.biosVersion;
                const rowFirmwareVersion = row.dataset.firmwareVersion;

                // Check hostname filter
                const hostnameMatch = !hostnameText || hostname.includes(hostnameText);

                // Check service tag filter
                const servicetagMatch = !servicetagText || servicetag.includes(servicetagText);

                // Check custom hostname filter (if custom filter is active, hostname must be in the list)
                const customFilterMatch = customFilterHostnames.length === 0 || customFilterHostnames.includes(hostname.toLowerCase());

                // Check model filter (if any models selected, row model must be in the list)
                const modelMatch = selectedModels.length === 0 || selectedModels.includes(rowModel);

                // Check BIOS version filter
                const biosMatch = matchesVersionFilter(rowBiosVersion, biosVersion, biosOperator);

                // Check firmware version filter
                const firmwareMatch = matchesVersionFilter(rowFirmwareVersion, firmwareVersion, firmwareOperator);

                // Check firmware age filter
                let firmwareAgeMatch = true;
                if (firmwareCurrent || firmwareOlder || firmwareOldest) {
                    // At least one checkbox is selected, apply age filter
                    const modelFirmwareVersions = firmwareVersionsByModel[rowModel] || [];
                    const versionIndex = modelFirmwareVersions.indexOf(rowFirmwareVersion);

                    const isCurrent = versionIndex === 0;
                    const isOlder = versionIndex === 1;
                    const isOldest = versionIndex >= 2;

                    // If all 3 are checked, show everything (same as none checked)
                    if (firmwareCurrent && firmwareOlder && firmwareOldest) {
                        firmwareAgeMatch = true;
                    } else {
                        firmwareAgeMatch = (firmwareCurrent && isCurrent) ||
                                          (firmwareOlder && isOlder) ||
                                          (firmwareOldest && isOldest);
                    }
                }

                // Check BIOS age filter
                let biosAgeMatch = true;
                if (biosCurrent || biosOlder || biosOldest) {
                    // At least one checkbox is selected, apply age filter
                    const modelBiosVersions = biosVersionsByModel[rowModel] || [];
                    const versionIndex = modelBiosVersions.indexOf(rowBiosVersion);

                    const isCurrent = versionIndex === 0;
                    const isOlder = versionIndex === 1;
                    const isOldest = versionIndex >= 2;

                    // If all 3 are checked, show everything (same as none checked)
                    if (biosCurrent && biosOlder && biosOldest) {
                        biosAgeMatch = true;
                    } else {
                        biosAgeMatch = (biosCurrent && isCurrent) ||
                                      (biosOlder && isOlder) ||
                                      (biosOldest && isOldest);
                    }
                }

                // Check warranty filter
                let warrantyMatch = true;
                const rowExpEpoch = row.dataset.expEpoch;
                if (warrantyExpired || warrantyExpiresDays) {
                    if (rowExpEpoch) {
                        const currentTime = Math.floor(Date.now() / 1000);
                        const expirationTime = parseInt(rowExpEpoch);
                        const isExpired = expirationTime < currentTime;
                        const daysUntilExpiration = (expirationTime - currentTime) / (60 * 60 * 24);

                        if (warrantyExpired && warrantyExpiresDays) {
                            // Both filters active: show expired OR expiring within X days
                            warrantyMatch = isExpired || (daysUntilExpiration > 0 && daysUntilExpiration <= parseInt(warrantyExpiresDays));
                        } else if (warrantyExpired) {
                            // Only expired checkbox: show only expired
                            warrantyMatch = isExpired;
                        } else if (warrantyExpiresDays) {
                            // Only expires-in selector: show expiring within X days but NOT already expired
                            warrantyMatch = !isExpired && daysUntilExpiration > 0 && daysUntilExpiration <= parseInt(warrantyExpiresDays);
                        }
                    } else {
                        // No warranty data available, exclude from filtered results
                        warrantyMatch = false;
                    }
                }

                // Show row if all filters match
                if (hostnameMatch && servicetagMatch && customFilterMatch && modelMatch && biosMatch && firmwareMatch && firmwareAgeMatch && biosAgeMatch && warrantyMatch) {
                    row.classList.remove('hidden');
                    visibleCount++;
                } else {
                    row.classList.add('hidden');
                }
            });

            // Update results count
            resultsCount.textContent = visibleCount;

            // Show/hide no results message
            if (visibleCount === 0 && rows.length > 0) {
                noResults.style.display = 'block';
                document.getElementById('systems-table').style.display = 'none';
                document.getElementById('pagination-container').style.display = 'none';
            } else {
                noResults.style.display = 'none';
                document.getElementById('systems-table').style.display = 'table';
                document.getElementById('pagination-container').style.display = 'flex';
            }

            // Update pagination after filters are applied
            updatePagination();

            // Update select all button text based on new visible rows
            updateSelectAllButtonText();
            updateSelectShownButtonText();
        }

        // Pagination functions
        function updatePagination() {
            // Defensive check
            if (!tableBody) {
                console.error('DRACS: tableBody element not found in updatePagination');
                return;
            }

            const rows = tableBody.querySelectorAll('tr');
            console.log('DRACS: updatePagination - total rows:', rows.length);

            // Get visible rows (not hidden by filters)
            const visibleRows = Array.from(rows).filter(row => !row.classList.contains('hidden'));
            const visibleCount = visibleRows.length;

            console.log('DRACS: updatePagination - visible rows:', visibleCount, 'current page:', currentPage, 'page size:', pageSize);

            // Calculate total pages
            if (pageSize === -1) {
                // Show all
                totalPages = 1;
            } else {
                totalPages = Math.max(1, Math.ceil(visibleCount / pageSize));
            }

            // Ensure current page is within bounds
            if (currentPage > totalPages) {
                console.log('DRACS: Current page', currentPage, 'exceeds total pages', totalPages, '- resetting to page', totalPages);
                currentPage = totalPages;
            }
            if (currentPage < 1) {
                currentPage = 1;
            }

            console.log('DRACS: updatePagination - calculated total pages:', totalPages, 'final current page:', currentPage);

            // Apply pagination display
            applyPagination(visibleRows);

            // Update pagination controls
            updatePaginationControls();
        }

        function applyPagination(visibleRows) {
            // Defensive check
            if (!visibleRows || !Array.isArray(visibleRows)) {
                console.warn('DRACS: visibleRows is not valid in applyPagination');
                return;
            }

            // First, hide all rows for pagination
            const rows = tableBody.querySelectorAll('tr');
            rows.forEach(row => {
                // Only hide if not already hidden by filters
                if (!row.classList.contains('hidden')) {
                    row.style.display = 'none';
                }
            });

            // Show only rows for current page
            if (pageSize === -1) {
                // Show all visible rows
                visibleRows.forEach(row => {
                    row.style.display = '';
                });
            } else {
                const startIndex = (currentPage - 1) * pageSize;
                const endIndex = startIndex + pageSize;

                console.log('DRACS: Pagination showing rows', startIndex, 'to', Math.min(endIndex, visibleRows.length) - 1, 'of', visibleRows.length);

                for (let i = startIndex; i < endIndex && i < visibleRows.length; i++) {
                    visibleRows[i].style.display = '';
                }
            }
        }

        function updatePaginationControls() {
            // Update prev/next buttons
            document.getElementById('prev-page').disabled = currentPage === 1;
            document.getElementById('next-page').disabled = currentPage === totalPages;

            // Generate page number buttons
            const pageNumbersDiv = document.getElementById('page-numbers');
            pageNumbersDiv.innerHTML = '';

            if (totalPages <= 1) {
                // Don't show page numbers if only one page
                return;
            }

            // Calculate which page numbers to show
            let startPage = Math.max(1, currentPage - 2);
            let endPage = Math.min(totalPages, currentPage + 2);

            // Always show first page
            if (startPage > 1) {
                addPageButton(1);
                if (startPage > 2) {
                    const ellipsis = document.createElement('span');
                    ellipsis.textContent = '...';
                    ellipsis.style.padding = '6px 8px';
                    pageNumbersDiv.appendChild(ellipsis);
                }
            }

            // Show page numbers
            for (let i = startPage; i <= endPage; i++) {
                addPageButton(i);
            }

            // Always show last page
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    const ellipsis = document.createElement('span');
                    ellipsis.textContent = '...';
                    ellipsis.style.padding = '6px 8px';
                    pageNumbersDiv.appendChild(ellipsis);
                }
                addPageButton(totalPages);
            }
        }

        function addPageButton(pageNum) {
            const button = document.createElement('button');
            button.textContent = pageNum;
            button.onclick = () => goToPage(pageNum);
            if (pageNum === currentPage) {
                button.classList.add('active');
            }
            document.getElementById('page-numbers').appendChild(button);
        }

        function goToPage(pageNum) {
            currentPage = pageNum;
            updatePagination();
        }

        function goToPreviousPage() {
            if (currentPage > 1) {
                currentPage--;
                updatePagination();
            }
        }

        function goToNextPage() {
            if (currentPage < totalPages) {
                currentPage++;
                updatePagination();
            }
        }

        function handlePageSizeChange(event) {
            pageSize = parseInt(event.target.value);
            currentPage = 1;  // Reset to first page when changing page size
            updatePagination();
        }

        // Initialize table
        function initTable() {
            // Calculate all unique versions before creating rows
            calculateAllVersions();

            // Update version dropdowns based on any selected models
            updateVersionDropdowns();

            systems.forEach(system => {
                const row = createRow(system);
                tableBody.appendChild(row);
            });

            totalCount.textContent = systems.length;
            resultsCount.textContent = systems.length;

            if (systems.length === 0) {
                noResults.textContent = 'No systems found in database';
                noResults.style.display = 'block';
                document.getElementById('systems-table').style.display = 'none';
                document.getElementById('pagination-container').style.display = 'none';
            } else {
                // Initialize pagination
                document.getElementById('page-size').value = pageSize;
                updatePagination();
            }
        }

        // Add event listeners
        hostnameFilter.addEventListener('input', applyFilters);
        servicetagFilter.addEventListener('input', applyFilters);
        modelFilter.addEventListener('change', () => {
            updateVersionDropdowns();
            applyFilters();
        });
        biosVersionSelect.addEventListener('change', applyFilters);
        biosOperatorSelect.addEventListener('change', applyFilters);
        firmwareVersionSelect.addEventListener('change', applyFilters);
        firmwareOperatorSelect.addEventListener('change', applyFilters);
        firmwareCurrentCheck.addEventListener('change', applyFilters);
        firmwareOlderCheck.addEventListener('change', applyFilters);
        firmwareOldestCheck.addEventListener('change', applyFilters);
        biosCurrentCheck.addEventListener('change', applyFilters);
        biosOlderCheck.addEventListener('change', applyFilters);
        biosOldestCheck.addEventListener('change', applyFilters);
        warrantyExpiredCheck.addEventListener('change', applyFilters);
        warrantyExpiresSelect.addEventListener('change', applyFilters);

        // Initialize on page load
        initTable();

        // Add row click handler to table body
        document.getElementById('table-body').addEventListener('click', handleRowClick);

        if (isAuthenticated) {
            // Prevent text selection when shift-clicking for range selection
            document.getElementById('table-body').addEventListener('mousedown', function(e) {
                if (e.shiftKey) {
                    e.preventDefault();
                }
            });
        }

        // Start auto-refresh if enabled
        startAutoRefresh();

        // Context Menu functionality
        const contextMenu = document.createElement('div');
        contextMenu.className = 'context-menu';
        contextMenu.id = 'cell-context-menu';
        contextMenu.innerHTML = '<div class="context-menu-item" onclick="copyCellValue()">Copy</div>';
        document.body.appendChild(contextMenu);

        let currentCellValue = '';
        let currentClickedRow = null;
        let currentCellIndex = -1;

        // Keyboard navigation with shift+arrow keys for selection
        document.addEventListener('keydown', function(e) {
            if (!isAuthenticated || !shiftKeyAnchorRow) return;

            // Only handle arrow keys with shift modifier
            if (e.shiftKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {
                e.preventDefault();

                const allRows = Array.from(tableBody.querySelectorAll('tr:not(.hidden)'));
                const anchorIndex = allRows.indexOf(shiftKeyAnchorRow);
                const currentIndex = allRows.indexOf(lastClickedRow || shiftKeyAnchorRow);

                if (anchorIndex === -1 || currentIndex === -1) return;

                let targetIndex = currentIndex;

                if (e.key === 'ArrowUp' && currentIndex > 0) {
                    targetIndex = currentIndex - 1;
                } else if (e.key === 'ArrowDown' && currentIndex < allRows.length - 1) {
                    targetIndex = currentIndex + 1;
                } else {
                    return; // Can't move further
                }

                // Clear all current selections
                selectedRows.forEach(r => r.classList.remove('selected'));
                selectedRows = [];
                selectedSystems = [];

                // Select all rows from anchor to target (inclusive)
                const minIndex = Math.min(anchorIndex, targetIndex);
                const maxIndex = Math.max(anchorIndex, targetIndex);

                for (let i = minIndex; i <= maxIndex; i++) {
                    const row = allRows[i];
                    row.classList.add('selected');
                    selectedRows.push(row);

                    const cells = row.getElementsByTagName('td');
                    selectedSystems.push({
                        service_tag: cells[0].textContent,
                        hostname: cells[1].textContent,
                        model: cells[2].textContent
                    });
                }

                // Update lastClickedRow to the new position
                lastClickedRow = allRows[targetIndex];

                // Scroll the target row into view
                allRows[targetIndex].scrollIntoView({ block: 'nearest', behavior: 'smooth' });

                // Update selected count immediately
                const selectedCountEl = document.getElementById('selected-count');
                if (selectedCountEl) {
                    selectedCountEl.textContent = selectedSystems.length;
                }

                // Update refresh button immediately
                const refreshBtn = document.getElementById('refresh-btn');
                if (refreshBtn) {
                    refreshBtn.disabled = selectedSystems.length === 0;
                }

                // Update other button states
                updateBiosButtonState();
                updateFirmwareButtonState();
            updateForceButtonState();
                updateJobQueueButtonState();
                updateClearJobQueueButtonState();
                updatePowerButtonState();
                updateLatestFirmwareButtonState();
                updateLatestBiosButtonState();
                updateGenerateTsrButtonState();
                updateViewTsrButtonState();
                updateSelectAllButtonText();
                updateSelectShownButtonText();
            }
        });

        // Arrow key navigation for single-row selection
        document.addEventListener('keydown', function(e) {
            if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;
            if (e.shiftKey || e.ctrlKey || e.metaKey) return;
            if (selectedRows.length !== 1) return;

            e.preventDefault();

            const allRows = Array.from(tableBody.querySelectorAll('tr:not(.hidden)'));
            const currentIndex = allRows.indexOf(selectedRows[0]);
            if (currentIndex === -1) return;

            let targetIndex;
            if (e.key === 'ArrowUp' && currentIndex > 0) {
                targetIndex = currentIndex - 1;
            } else if (e.key === 'ArrowDown' && currentIndex < allRows.length - 1) {
                targetIndex = currentIndex + 1;
            } else {
                return;
            }

            selectedRows[0].classList.remove('selected');
            selectedRows = [];
            selectedSystems = [];

            const targetRow = allRows[targetIndex];
            targetRow.classList.add('selected');
            selectedRows.push(targetRow);

            const cells = targetRow.getElementsByTagName('td');
            selectedSystems.push({
                service_tag: cells[0].textContent,
                hostname: cells[1].textContent,
                model: cells[2].textContent
            });

            lastClickedRow = targetRow;
            shiftKeyAnchorRow = targetRow;
            targetRow.scrollIntoView({ block: 'nearest', behavior: 'smooth' });

            updateViewTsrButtonState();
            updateGenerateTsrButtonState();
        });

        // Add right-click event listener to table body only (not headers)
        document.getElementById('table-body').addEventListener('contextmenu', function(e) {
            // Always prevent default browser context menu
            e.preventDefault();

            // Check if the target is a table data cell (not header)
            const target = e.target;
            if (target.tagName === 'TD') {
                // Get the parent row and cell index
                currentClickedRow = target.parentElement;
                const cells = Array.from(currentClickedRow.getElementsByTagName('td'));
                currentCellIndex = cells.indexOf(target);

                // Get the cell text content
                currentCellValue = target.textContent.trim();

                // Position the context menu at mouse location
                contextMenu.style.left = e.pageX + 'px';
                contextMenu.style.top = e.pageY + 'px';
                contextMenu.style.display = 'block';
            }
        });

        // Hide context menu when clicking elsewhere
        document.addEventListener('click', function(e) {
            if (!contextMenu.contains(e.target)) {
                contextMenu.style.display = 'none';
            }
        });

        // Hide context menu on scroll
        document.addEventListener('scroll', function() {
            contextMenu.style.display = 'none';
        });

        // Copy cell value function
        function copyCellValue() {
            if (!currentCellValue) return;

            // Check if admin is logged in, multiple rows are selected, and clicked row is selected
            if (isAuthenticated && selectedRows.length > 1 && currentClickedRow && currentClickedRow.classList.contains('selected')) {
                // Copy the same column from all selected rows
                const columnNames = ['Service Tag', 'Hostname', 'Model', 'Firmware', 'BIOS', 'Warranty Expiration'];
                const columnName = columnNames[currentCellIndex] || 'values';

                const values = selectedRows.map(row => {
                    const cells = row.getElementsByTagName('td');
                    return cells[currentCellIndex] ? cells[currentCellIndex].textContent.trim() : '';
                }).filter(val => val !== '');

                const textToCopy = values.join('\n');
                const count = values.length;

                navigator.clipboard.writeText(textToCopy).then(function() {
                    showNotification(`Copied ${count} ${columnName} to clipboard`, 'success');
                    contextMenu.style.display = 'none';
                }).catch(function(err) {
                    showNotification('Failed to copy: ' + err, 'error');
                    contextMenu.style.display = 'none';
                });
            } else {
                // Single cell copy (original behavior)
                navigator.clipboard.writeText(currentCellValue).then(function() {
                    showNotification('Copied to clipboard: ' + currentCellValue, 'success');
                    contextMenu.style.display = 'none';
                }).catch(function(err) {
                    showNotification('Failed to copy: ' + err, 'error');
                    contextMenu.style.display = 'none';
                });
            }
        }
    </script>
</body>
</html>
