<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require_once 'auth.php';
checkLogin();

// Verify Admin Role
if (($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: dashboard.php");
    exit();
}

require_once 'config.php';

$pending_users = [];
$active_users = [];
$users_by_ship = [];
$ships = [];
$pdo = null;

try {
    $pdo = getDBConnection();
    if ($pdo) {
        $stmt = $pdo->query("SELECT id, username, status, created_at FROM users WHERE status = 'pending' ORDER BY created_at DESC");
        $pending_users = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];

        // 1. Get all sub-admins and their company info
        $stmt = $pdo->query("SELECT id, username, role, status, legal_name, address, responsible_name, cuit 
                            FROM users 
                            WHERE role = 'sub-adm' AND status = 'active' 
                            ORDER BY username ASC");
        $all_sub_adms = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 2. Get all ships
        $stmt = $pdo->query("SELECT * FROM ships ORDER BY name ASC");
        $ships = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 3. Enhance ships with associated users (Both Admins and Viewers)
        foreach ($ships as &$ship) {
            $shipId = $ship['ship_id'];

            // Defaults
            if (empty($ship['icon'])) {
                $ship['icon'] = ($ship['type'] ?? 'buque') === 'equipo' ? '⚙️' : '🚢';
            }
            if (empty($ship['type'])) {
                $ship['type'] = 'buque';
            }

            // Fetch all users associated with this ship
            $stmt = $pdo->prepare("
                SELECT u.id, u.username, u.role, u.legal_name, u.address, u.responsible_name, u.cuit
                FROM users u
                JOIN user_ships us ON u.id = us.user_id
                WHERE us.ship_id = :ship_id
            ");
            $stmt->execute([':ship_id' => $shipId]);
            $associated_users = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $ship['admins'] = array_filter($associated_users, function ($u) {
                return $u['role'] === 'sub-adm';
            });
            $ship['viewers'] = array_filter($associated_users, function ($u) {
                return $u['role'] === 'user';
            });

            // For backward compatibility in some parts of the code
            $ship['admin_username'] = !empty($ship['admins']) ? reset($ship['admins'])['username'] : '';
            $ship['legal_name'] = !empty($ship['admins']) ? reset($ship['admins'])['legal_name'] : '';
            $ship['address'] = !empty($ship['admins']) ? reset($ship['admins'])['address'] : '';
            $ship['responsible_name'] = !empty($ship['admins']) ? reset($ship['admins'])['responsible_name'] : '';
            $ship['cuit'] = !empty($ship['admins']) ? reset($ship['admins'])['cuit'] : '';
        }
        unset($ship);

        // Si no tienen icon, asignar uno por defecto según el type
        foreach ($ships as &$ship) {
            if (empty($ship['icon'])) {
                $ship['icon'] = ($ship['type'] ?? 'buque') === 'equipo' ? '⚙️' : '🚢';
            }
            if (empty($ship['type'])) {
                $ship['type'] = 'buque';
            }
        }
        unset($ship);

        // 3. Enhance ships with sensor configs
        foreach ($ships as &$ship) {
            try {
                $shipId = trim($ship['ship_id']);

                // Obtener configuraciones de temperatura por sensor, usando sensor_positions como base
                $stmt = $pdo->prepare("
                    SELECT sp.sensor_id, sp.label as position_label,
                           stc.sensor_label, stc.max_temp, stc.min_temp,
                           COALESCE(stc.sensor_label, sp.label, CONCAT('Sensor ', sp.sensor_id)) as display_label,
                           COALESCE(stc.max_temp, :def_max) as max_temp,
                           COALESCE(stc.min_temp, :def_min) as min_temp
                    FROM sensor_positions sp
                    LEFT JOIN sensor_temperature_config stc ON sp.buque_id = stc.buque_id AND sp.sensor_id = stc.sensor_id
                    WHERE sp.buque_id = :ship_id
                    ORDER BY sp.sensor_id
                ");
                $stmt->execute([
                    ':ship_id' => $shipId,
                    ':def_max' => $ship['max_temp'] ?? 27.00,
                    ':def_min' => $ship['min_temp'] ?? -40.00
                ]);
                $ship['sensor_configs'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

                // No longer need the "if (empty($ship['sensor_configs']))" block since the JOIN handles it
            } catch (PDOException $e) {
                error_log("Error fetching ship data: " . $e->getMessage());
            }
        }
        unset($ship);

        // 4. Group ships by primary admin
        $grouped_ships = [];
        $unassigned_admin_name = 'Administrador General (Sin asignar a cliente)';

        foreach ($ships as $ship) {
            $adminName = !empty($ship['admin_username']) ? $ship['admin_username'] : $unassigned_admin_name;
            if (!isset($grouped_ships[$adminName])) {
                $grouped_ships[$adminName] = [];
            }
            $grouped_ships[$adminName][] = $ship;
        }

        // Sort keys to look better, but keep unassigned at the bottom maybe?
        ksort($grouped_ships);
        // If unassigned exists, move it to the end
        if (isset($grouped_ships[$unassigned_admin_name])) {
            $unassigned = $grouped_ships[$unassigned_admin_name];
            unset($grouped_ships[$unassigned_admin_name]);
            $grouped_ships[$unassigned_admin_name] = $unassigned;
        }

    }
} catch (PDOException $e) {
    error_log("Admin.php DB Error: " . $e->getMessage());
}

// Obtener meses disponibles con datos para cada buque
$monthly_reports = [];
$debug_info = []; // Para debugging
if ($pdo) {
    try {
        // Obtener todos los buques únicos que tienen datos en mediciones (igual que ver_datos.php)
        $buquesConDatos = [];
        try {
            $stmtBuques = $pdo->query("SELECT DISTINCT buque_id FROM mediciones ORDER BY buque_id ASC");
            $buquesConDatos = $stmtBuques->fetchAll(PDO::FETCH_COLUMN);
            $debug_info['buques_en_mediciones'] = $buquesConDatos;
        } catch (PDOException $e) {
            error_log("Error obteniendo buques con datos: " . $e->getMessage());
            $debug_info['error_buques'] = $e->getMessage();
        }

        // Crear un mapa de buques para acceso rápido
        $shipsMap = [];
        foreach ($ships as $ship) {
            $shipsMap[trim($ship['ship_id'])] = $ship['name'];
        }
        $debug_info['buques_en_ships'] = array_keys($shipsMap);

        // Procesar todos los buques que tienen datos (de ships y de mediciones)
        $allBuques = array_unique(array_merge(
            array_map(function ($s) {
                return trim($s['ship_id']);
            }, $ships),
            array_map('trim', $buquesConDatos)
        ));

        // Si no hay buques en ships pero hay en mediciones, usar solo los de mediciones
        if (empty($allBuques) && !empty($buquesConDatos)) {
            $allBuques = array_map('trim', $buquesConDatos);
        }

        $debug_info['buques_a_procesar'] = $allBuques;

        foreach ($allBuques as $buqueId) {
            $buqueId = trim($buqueId);
            if (empty($buqueId))
                continue;

            try {
                // Primero verificar cuántos registros hay para este buque
                $countStmt = $pdo->prepare("SELECT COUNT(*) as total FROM mediciones WHERE buque_id = :buque_id");
                $countStmt->execute([':buque_id' => $buqueId]);
                $countResult = $countStmt->fetch(PDO::FETCH_ASSOC);
                $totalRegistros = $countResult['total'] ?? 0;

                // Obtener una muestra de fechas para debug
                $sampleStmt = $pdo->prepare("SELECT fecha FROM mediciones WHERE buque_id = :buque_id LIMIT 5");
                $sampleStmt->execute([':buque_id' => $buqueId]);
                $sampleDates = $sampleStmt->fetchAll(PDO::FETCH_COLUMN);

                // Obtener meses disponibles para este buque
                // Usar alias con comillas invertidas para evitar conflictos con palabras reservadas
                $stmt = $pdo->prepare("
                    SELECT DISTINCT 
                        YEAR(fecha) AS anio, 
                        MONTH(fecha) AS mes,
                        DATE_FORMAT(fecha, '%Y-%m') AS periodo
                    FROM mediciones 
                    WHERE buque_id = :buque_id 
                    AND fecha IS NOT NULL
                    ORDER BY anio DESC, mes DESC
                ");
                $stmt->execute([':buque_id' => $buqueId]);
                $monthsRaw = $stmt->fetchAll(PDO::FETCH_ASSOC);

                // Mapear los resultados al formato esperado
                $months = [];
                foreach ($monthsRaw as $row) {
                    $months[] = [
                        'year' => (int) $row['anio'],
                        'month' => (int) $row['mes'],
                        'year_month' => $row['periodo']
                    ];
                }

                // Debug para este buque
                $debug_info['buques_detalle'][$buqueId] = [
                    'total_registros' => $totalRegistros,
                    'meses_encontrados' => count($months),
                    'meses' => $months,
                    'sample_dates' => $sampleDates
                ];

                // Obtener nombre del buque (de ships si existe, sino usar el ID)
                $shipName = isset($shipsMap[$buqueId]) ? $shipsMap[$buqueId] : $buqueId;

                $monthly_reports[$buqueId] = [
                    'name' => $shipName,
                    'months' => $months ? $months : []
                ];
            } catch (PDOException $e) {
                error_log("Error obteniendo meses para buque {$buqueId}: " . $e->getMessage());
                $debug_info['errores'][$buqueId] = $e->getMessage();
                $shipName = isset($shipsMap[$buqueId]) ? $shipsMap[$buqueId] : $buqueId;
                $monthly_reports[$buqueId] = [
                    'name' => $shipName,
                    'months' => []
                ];
            }
        }

        // Si no se encontraron buques con datos, al menos mostrar los de ships
        if (empty($monthly_reports) && !empty($ships)) {
            foreach ($ships as $ship) {
                $monthly_reports[$ship['ship_id']] = [
                    'name' => $ship['name'],
                    'months' => []
                ];
            }
        }
    } catch (PDOException $e) {
        error_log("Error general obteniendo reportes mensuales: " . $e->getMessage());
        $debug_info['error_general'] = $e->getMessage();
        // Crear estructura vacía para los buques registrados
        foreach ($ships as $ship) {
            $monthly_reports[$ship['ship_id']] = [
                'name' => $ship['name'],
                'months' => []
            ];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Panel Administrativo - TECNOTRACK MARINE</title>
    <link rel="stylesheet" href="styles/main.css?v=1.1.0">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif;
            background: #0a0e27;
            color: #e6f1ff;
            overflow-x: hidden;
        }

        .admin-layout {
            display: flex;
            min-height: 100vh;
        }

        /* SIDEBAR */
        .sidebar {
            width: 280px;
            background: linear-gradient(180deg, #0d1421 0%, #050a10 100%);
            border-right: 1px solid rgba(0, 242, 255, 0.1);
            position: fixed;
            height: 100vh;
            left: 0;
            top: 0;
            overflow-y: auto;
            z-index: 1000;
            transition: transform 0.3s ease;
        }

        .sidebar-header {
            padding: 24px 20px;
            border-bottom: 1px solid rgba(0, 242, 255, 0.1);
        }

        .sidebar-title {
            width: 100%;
        }

        .sidebar-title h1 {
            font-size: 18px;
            font-weight: 700;
            color: #00f2ff;
            margin: 0;
        }

        .sidebar-title p {
            font-size: 11px;
            color: #8892b0;
            margin: 2px 0 0 0;
        }

        .sidebar-menu {
            padding: 20px 0;
        }

        .menu-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 20px;
            color: #8892b0;
            text-decoration: none;
            transition: all 0.2s;
            border-left: 3px solid transparent;
            cursor: pointer;
        }

        .menu-item:hover {
            background: rgba(0, 242, 255, 0.05);
            color: #00f2ff;
            border-left-color: #00f2ff;
        }

        .menu-item.active {
            background: rgba(0, 242, 255, 0.1);
            color: #00f2ff;
            border-left-color: #00f2ff;
        }

        .menu-item-icon {
            font-size: 20px;
            width: 24px;
            text-align: center;
        }

        .menu-item-text {
            font-size: 14px;
            font-weight: 500;
        }

        .menu-badge {
            margin-left: auto;
            background: rgba(255, 77, 77, 0.2);
            color: #ff4d4d;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
        }

        .sidebar-footer {
            padding: 20px;
            border-top: 1px solid rgba(0, 242, 255, 0.1);
            margin-top: auto;
        }

        .user-profile {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px;
            background: rgba(0, 242, 255, 0.05);
            border-radius: 8px;
        }

        .user-avatar {
            width: 36px;
            height: 36px;
            background: linear-gradient(135deg, #00f2ff, #0099cc);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: #000;
            font-size: 14px;
        }

        .user-info {
            flex: 1;
        }

        .user-name {
            font-size: 13px;
            font-weight: 600;
            color: #fff;
        }

        .user-role {
            font-size: 11px;
            color: #8892b0;
        }

        /* MAIN CONTENT */
        .main-content {
            flex: 1;
            margin-left: 280px;
            padding: 0;
            background: #0a0e27;
            min-width: 0;
            overflow-x: hidden;
        }

        .topbar {
            background: rgba(13, 20, 33, 0.8);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(0, 242, 255, 0.1);
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .topbar-title {
            font-size: 24px;
            font-weight: 700;
            color: #fff;
        }

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

        .btn-icon {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            border: 1px solid rgba(0, 242, 255, 0.2);
            background: rgba(0, 242, 255, 0.05);
            color: #00f2ff;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 18px;
        }

        .btn-icon:hover {
            background: rgba(0, 242, 255, 0.1);
            border-color: #00f2ff;
        }

        .topbar-actions {
            position: relative;
        }

        .icon-option {
            font-size: 2rem;
            padding: 15px;
            background: rgba(0, 242, 255, 0.05);
            border: 1px solid rgba(0, 242, 255, 0.1);
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 70px;
            height: 70px;
        }

        .icon-option:hover {
            background: rgba(0, 242, 255, 0.15);
            border-color: rgba(0, 242, 255, 0.3);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 242, 255, 0.1);
        }

        .icon-option.active {
            background: rgba(0, 242, 255, 0.2);
            border-color: #00f2ff;
            box-shadow: 0 0 15px rgba(0, 242, 255, 0.2);
        }

        .menu-dropdown {
            position: absolute;
            top: calc(100% + 8px);
            right: 0;
            background: linear-gradient(135deg, #0d1421, #050a10);
            border: 1px solid rgba(0, 242, 255, 0.3);
            border-radius: 12px;
            padding: 8px;
            min-width: 220px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .menu-dropdown-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            color: #e6f1ff;
            text-decoration: none;
            border-radius: 8px;
            transition: all 0.2s;
            font-size: 14px;
            font-weight: 500;
        }

        .menu-dropdown-item:hover {
            background: rgba(0, 242, 255, 0.1);
            color: #00f2ff;
        }

        .menu-dropdown-item span {
            font-size: 18px;
            width: 24px;
            text-align: center;
        }

        .content-area {
            padding: 32px;
            max-width: 1400px;
        }

        /* STATS GRID */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            margin-bottom: 32px;
        }

        .stat-card {
            background: linear-gradient(135deg, rgba(0, 242, 255, 0.05), rgba(0, 242, 255, 0.02));
            border: 1px solid rgba(0, 242, 255, 0.1);
            border-radius: 12px;
            padding: 24px;
            transition: all 0.3s;
        }

        .stat-card:hover {
            border-color: rgba(0, 242, 255, 0.3);
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(0, 242, 255, 0.1);
        }

        .stat-label {
            font-size: 13px;
            color: #8892b0;
            font-weight: 500;
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-value {
            font-size: 32px;
            font-weight: 700;
            color: #00f2ff;
            text-shadow: 0 0 20px rgba(0, 242, 255, 0.3);
        }

        /* SHIPS GRID */
        .ships-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 24px;
            margin-bottom: 24px;
            align-items: start;
            /* Evita que los cards se estiren juntos */
        }

        @media (max-width: 1400px) {
            .ships-grid {
                grid-template-columns: repeat(3, 1fr);
            }
        }

        @media (max-width: 1024px) {
            .ships-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

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

        .ship-card {
            background: rgba(13, 20, 33, 0.6);
            border: 1px solid rgba(0, 242, 255, 0.1);
            border-radius: 16px;
            padding: 24px;
            transition: all 0.3s;
            display: flex;
            flex-direction: column;
            height: auto;
            /* Altura automática, no se estira */
            align-self: start;
            /* Cada card se alinea al inicio */
            cursor: pointer;
        }

        .ship-card:hover {
            border-color: rgba(0, 242, 255, 0.3);
            transform: translateY(-4px);
            box-shadow: 0 8px 24px rgba(0, 242, 255, 0.15);
        }

        .ship-card-header {
            display: flex;
            align-items: flex-start;
            gap: 12px;
            margin-bottom: 16px;
        }

        .ship-card-icon {
            font-size: 32px;
            line-height: 1;
        }

        .ship-card-title {
            font-size: 18px;
            font-weight: 600;
            color: #00f2ff;
            margin: 0 0 4px 0;
        }

        .ship-card-id {
            font-size: 13px;
            color: #8892b0;
            margin: 0;
        }

        .ship-card-body {
            flex: 1;
            margin-bottom: 16px;
        }

        .ship-card-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid rgba(0, 242, 255, 0.05);
        }

        .ship-card-info:last-child {
            border-bottom: none;
        }

        .ship-card-label {
            font-size: 13px;
            color: #8892b0;
        }

        .ship-card-value {
            font-size: 14px;
            font-weight: 600;
            color: #00f2ff;
        }

        .ship-card-actions {
            display: flex;
            gap: 8px;
            margin-top: auto;
        }

        /* CONTENT CARDS */
        .content-card {
            background: rgba(13, 20, 33, 0.6);
            border: 1px solid rgba(0, 242, 255, 0.1);
            border-radius: 16px;
            padding: 32px;
            margin-bottom: 24px;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 1px solid rgba(0, 242, 255, 0.1);
        }

        .card-title {
            font-size: 20px;
            font-weight: 700;
            color: #fff;
        }

        .btn-primary {
            padding: 10px 20px;
            background: linear-gradient(135deg, #00f2ff, #0099cc);
            color: #000;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 242, 255, 0.3);
        }

        .btn-secondary {
            padding: 8px 16px;
            background: rgba(0, 242, 255, 0.1);
            color: #00f2ff;
            border: 1px solid rgba(0, 242, 255, 0.2);
            border-radius: 6px;
            font-weight: 600;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-secondary:hover {
            background: rgba(0, 242, 255, 0.2);
            border-color: #00f2ff;
        }

        .btn-danger {
            padding: 8px 16px;
            background: rgba(255, 77, 77, 0.1);
            color: #ff4d4d;
            border: 1px solid rgba(255, 77, 77, 0.2);
            border-radius: 6px;
            font-weight: 600;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-danger:hover {
            background: rgba(255, 77, 77, 0.2);
            border-color: #ff4d4d;
        }

        .btn-compact {
            padding: 6px 10px !important;
            font-size: 13px !important;
            border-radius: 6px !important;
            min-width: fit-content;
            color: #fff !important;
        }

        .icon-btn,
        .icon-option {
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28px;
            background: rgba(0, 242, 255, 0.05);
            border: 1px solid rgba(0, 242, 255, 0.2);
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
            color: #fff;
        }

        .icon-btn:hover,
        .icon-option:hover {
            background: rgba(0, 242, 255, 0.15);
            border-color: #00f2ff;
            transform: scale(1.1);
        }

        .icon-btn.active,
        .icon-option.active {
            background: rgba(0, 242, 255, 0.25);
            border-color: #00f2ff;
            box-shadow: 0 0 15px rgba(0, 242, 255, 0.3);
        }

        .btn-success {
            padding: 8px 16px;
            background: rgba(0, 255, 136, 0.1);
            color: #00ff88;
            border: 1px solid rgba(0, 255, 136, 0.2);
            border-radius: 6px;
            font-weight: 600;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-success:hover {
            background: rgba(0, 255, 136, 0.2);
            border-color: #00ff88;
        }

        /* ITEMS LIST */
        .items-list {
            display: grid;
            gap: 12px;
        }

        .item-card {
            background: rgba(5, 10, 16, 0.5);
            border: 1px solid rgba(0, 242, 255, 0.1);
            border-radius: 10px;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.2s;
        }

        .item-card:hover {
            border-color: rgba(0, 242, 255, 0.3);
            background: rgba(5, 10, 16, 0.7);
            transform: translateX(4px);
        }

        .item-info h3 {
            font-size: 16px;
            font-weight: 600;
            color: #fff;
            margin-bottom: 6px;
        }

        .item-info p {
            font-size: 13px;
            color: #8892b0;
            margin: 2px 0;
        }

        .item-actions {
            display: flex;
            gap: 8px;
        }

        /* MONTHLY REPORTS - HISTORIAL STYLE */
        .reports-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 1px solid rgba(0, 242, 255, 0.1);
            flex-wrap: wrap;
            gap: 16px;
        }

        .reports-title {
            font-size: 24px;
            font-weight: 700;
            color: #fff;
            margin: 0 0 8px 0;
        }

        .reports-subtitle {
            color: #8892b0;
            font-size: 14px;
            margin: 0;
        }

        .reports-info {
            color: #8892b0;
            font-size: 14px;
        }

        .history-table-container-full {
            background: rgba(5, 10, 16, 0.5);
            border: 1px solid rgba(0, 242, 255, 0.1);
            border-radius: 12px;
            overflow: hidden;
            overflow-x: auto;
            width: 100%;
            margin-bottom: 24px;
        }

        .history-table-full {
            width: 100%;
            border-collapse: collapse;
            min-width: 800px;
        }

        .empty-state-full {
            text-align: center;
            padding: 80px 20px;
            color: #8892b0;
            background: rgba(5, 10, 16, 0.5);
            border: 1px solid rgba(0, 242, 255, 0.1);
            border-radius: 12px;
        }

        /* PAGINACIÓN */
        .pagination-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 0;
            flex-wrap: wrap;
            gap: 16px;
        }

        .pagination-info {
            color: #8892b0;
            font-size: 14px;
        }

        .pagination {
            display: flex;
            gap: 8px;
            align-items: center;
            flex-wrap: wrap;
        }

        .pagination-btn {
            padding: 8px 16px;
            background: rgba(0, 242, 255, 0.1);
            color: #00f2ff;
            border: 1px solid rgba(0, 242, 255, 0.2);
            border-radius: 6px;
            text-decoration: none;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.2s;
            cursor: pointer;
        }

        .pagination-btn:hover {
            background: rgba(0, 242, 255, 0.2);
            border-color: #00f2ff;
            transform: translateY(-1px);
        }

        .pagination-btn.active {
            background: linear-gradient(135deg, #00f2ff, #0099cc);
            color: #000;
            border-color: #00f2ff;
        }

        .pagination-dots {
            color: #8892b0;
            padding: 0 8px;
        }

        /* REPORTS BY SHIP SECTION */
        .reports-by-ship-section {
            margin-bottom: 48px;
        }

        .reports-history-section {
            margin-top: 48px;
        }

        .section-subtitle {
            font-size: 20px;
            font-weight: 700;
            color: #00f2ff;
            margin-bottom: 24px;
            padding-bottom: 12px;
            border-bottom: 2px solid rgba(0, 242, 255, 0.2);
        }

        .reports-grid-by-ship {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
            gap: 20px;
        }

        .ship-report-card {
            background: rgba(5, 10, 16, 0.5);
            border: 1px solid rgba(0, 242, 255, 0.1);
            border-radius: 12px;
            padding: 24px;
            transition: all 0.3s;
        }

        .ship-report-card:hover {
            border-color: rgba(0, 242, 255, 0.3);
            box-shadow: 0 8px 24px rgba(0, 242, 255, 0.1);
        }

        .ship-report-header {
            margin-bottom: 20px;
            padding-bottom: 16px;
            border-bottom: 1px solid rgba(0, 242, 255, 0.1);
        }

        .ship-report-header-content {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .ship-report-icon {
            width: 48px;
            height: 48px;
            background: linear-gradient(135deg, rgba(0, 242, 255, 0.2), rgba(0, 242, 255, 0.1));
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }

        .ship-report-title {
            font-size: 18px;
            font-weight: 600;
            color: #00f2ff;
            margin: 0 0 4px 0;
        }

        .ship-report-subtitle {
            font-size: 13px;
            color: #8892b0;
            margin: 0;
        }

        .months-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 12px;
        }

        .month-card {
            background: rgba(13, 20, 33, 0.5);
            border: 1px solid rgba(0, 242, 255, 0.1);
            border-radius: 8px;
            padding: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.2s;
        }

        .month-card:hover {
            border-color: #00f2ff;
            background: rgba(13, 20, 33, 0.8);
        }

        .month-info h4 {
            font-size: 15px;
            font-weight: 600;
            color: #fff;
            margin-bottom: 4px;
        }

        .month-info p {
            font-size: 12px;
            color: #8892b0;
            margin: 0;
        }

        .btn-download {
            padding: 6px 12px;
            background: linear-gradient(135deg, #00ff88, #00cc6a);
            color: #000;
            border: none;
            border-radius: 6px;
            font-weight: 600;
            font-size: 12px;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            transition: all 0.2s;
        }

        .btn-download:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 255, 136, 0.3);
        }

        .history-table-full thead {
            background: rgba(13, 20, 33, 0.5);
        }

        .history-table-full th {
            padding: 16px 24px;
            text-align: left;
            font-size: 12px;
            font-weight: 600;
            color: #8892b0;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 1px solid rgba(0, 242, 255, 0.1);
        }

        .history-table-full tbody tr {
            border-bottom: 1px solid rgba(0, 242, 255, 0.05);
            transition: all 0.2s;
        }

        .history-table-full tbody tr:hover {
            background: rgba(0, 242, 255, 0.03);
        }

        .history-table-full tbody tr:last-child {
            border-bottom: none;
        }

        .history-table-full td {
            padding: 16px 24px;
            font-size: 14px;
            color: #e6f1ff;
        }

        .history-date {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .history-date-month {
            font-weight: 600;
            color: #fff;
            font-size: 15px;
        }

        .history-date-year {
            font-size: 12px;
            color: #8892b0;
        }

        .history-actions {
            display: flex;
            justify-content: flex-end;
            flex-wrap: wrap;
            gap: 6px;
        }

        .history-actions .btn-compact {
            margin: 0 !important;
            white-space: nowrap;
        }

        .btn-download-history {
            padding: 8px 16px;
            background: linear-gradient(135deg, #00ff88, #00cc6a);
            color: #000;
            border: none;
            border-radius: 6px;
            font-weight: 600;
            font-size: 13px;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s;
        }

        .btn-download-history:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 255, 136, 0.3);
        }

        .history-empty {
            padding: 40px 24px;
            text-align: center;
            color: #8892b0;
        }

        /* EMPTY STATE */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #8892b0;
        }

        .empty-state-icon {
            font-size: 64px;
            margin-bottom: 16px;
            opacity: 0.3;
        }

        .empty-state h3 {
            font-size: 18px;
            color: #fff;
            margin-bottom: 8px;
        }

        /* MODALS */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.85);
            backdrop-filter: blur(4px);
            align-items: center;
            justify-content: center;
            z-index: 10000;
        }

        .modal-content {
            background: linear-gradient(135deg, #0d1421, #050a10);
            padding: 32px;
            border: 1px solid rgba(0, 242, 255, 0.3);
            border-radius: 16px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 20px 60px rgba(0, 242, 255, 0.2);
        }

        .modal-content h3 {
            font-size: 22px;
            font-weight: 700;
            color: #00f2ff;
            margin-bottom: 8px;
        }

        .modal-content p {
            font-size: 14px;
            color: #8892b0;
            margin-bottom: 24px;
        }

        .modal-input {
            width: 100%;
            padding: 12px 16px;
            margin-bottom: 16px;
            background: rgba(5, 10, 16, 0.8);
            border: 1px solid rgba(0, 242, 255, 0.2);
            color: #fff;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.2s;
        }

        .modal-input:focus {
            outline: none;
            border-color: #00f2ff;
            box-shadow: 0 0 0 3px rgba(0, 242, 255, 0.1);
        }

        .tab-button {
            transition: all 0.2s;
        }

        .tab-button:hover {
            background: rgba(0, 242, 255, 0.05) !important;
        }

        .user-search-result {
            user-select: none;
        }

        .modal-actions {
            display: flex;
            gap: 12px;
            margin-top: 24px;
        }

        .modal-actions button {
            flex: 1;
        }

        .modal-close {
            background: transparent;
            border: none;
            color: #8892b0;
            font-size: 28px;
            cursor: pointer;
            line-height: 1;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
            height: 32px;
            width: 32px;
            border-radius: 50%;
        }

        .modal-close:hover {
            color: #ff4d4d;
            background: rgba(255, 77, 77, 0.1);
            transform: rotate(90deg);
        }

        /* RESPONSIVE */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }

            .sidebar.open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .content-area {
                padding: 20px;
            }
        }

        /* HIDE/SHOW SECTIONS */
        .tab-section {
            display: none;
        }

        .tab-section.active {
            display: block;
        }

        /* FULL WIDTH FOR REPORTS */
        #section-reports {
            width: 100%;
            max-width: 100%;
        }

        #section-reports .content-area {
            padding: 32px;
            max-width: 100%;
        }
    </style>
</head>

<body>
    <div class="admin-layout">
        <!-- SIDEBAR -->
        <aside class="sidebar">
            <div class="sidebar-header">
                <div class="sidebar-title">
                    <h1>TECNOTRACK</h1>
                    <p>Panel Administrativo</p>
                </div>
            </div>

            <nav class="sidebar-menu">
                <a href="#" class="menu-item active" onclick="switchSection('dashboard'); return false;">
                    <span class="menu-item-icon">📊</span>
                    <span class="menu-item-text">Dashboard</span>
                </a>
                <a href="#" class="menu-item" onclick="switchSection('ships'); return false;">
                    <span class="menu-item-icon">⚙️</span>
                    <span class="menu-item-text">Equipos controlados</span>
                </a>
                <a href="#" class="menu-item" onclick="switchSection('users'); return false;">
                    <span class="menu-item-icon">👥</span>
                    <span class="menu-item-text">Usuarios</span>
                    <?php if (count($pending_users) > 0): ?>
                        <span class="menu-badge"><?php echo count($pending_users); ?></span>
                    <?php endif; ?>
                </a>
                <a href="#" class="menu-item" onclick="switchSection('reports'); return false;">
                    <span class="menu-item-icon">📥</span>
                    <span class="menu-item-text">Reportes</span>
                </a>
            </nav>

            <div class="sidebar-footer">
                <div class="user-profile">
                    <div class="user-avatar"><?php echo strtoupper(substr($_SESSION['username'] ?? 'A', 0, 1)); ?></div>
                    <div class="user-info">
                        <div class="user-name"><?php echo htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></div>
                        <div class="user-role">
                            <?php echo ($_SESSION['username'] ?? '') === 'admin' ? 'Admin staff' : 'Admin asignado'; ?>
                        </div>
                    </div>
                </div>
                <a href="dashboard.php"
                    style="display: block; margin-top: 12px; padding: 10px; text-align: center; background: rgba(0, 242, 255, 0.1); border-radius: 8px; color: #00f2ff; text-decoration: none; font-size: 13px; font-weight: 600;">
                    ← Volver al Dashboard
                </a>
            </div>
        </aside>

        <!-- MAIN CONTENT -->
        <main class="main-content">
            <div class="topbar">
                <h1 class="topbar-title" id="pageTitle">Dashboard</h1>
                <div class="topbar-actions">
                    <button class="btn-icon" onclick="toggleMenu()" title="Menú">☰</button>
                    <div id="menuDropdown" class="menu-dropdown" style="display: none;">
                        <a href="dashboard.php" class="menu-dropdown-item">
                            <span>📊</span> Dashboard Principal
                        </a>
                        <a href="api/logout.php" class="menu-dropdown-item">
                            <span>🚪</span> Cerrar Sesión
                        </a>
                    </div>
                </div>
            </div>

            <div class="content-area">
                <!-- DASHBOARD SECTION -->
                <div id="section-dashboard" class="tab-section active">
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-label">Equipos Registrados</div>
                            <div class="stat-value"><?php echo count($ships); ?></div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-label">Usuarios Pendientes</div>
                            <div class="stat-value"><?php echo count($pending_users); ?></div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-label">Usuarios Activos</div>
                            <div class="stat-value"><?php echo count($active_users); ?></div>
                        </div>
                    </div>

                    <div class="content-card">
                        <div class="card-header">
                            <h2 class="card-title">Resumen del Sistema</h2>
                        </div>
                        <p style="color: #8892b0; line-height: 1.6;">
                            Bienvenido al panel administrativo de TECNOTRACK. Desde aquí puedes gestionar equipos
                            controlados,
                            usuarios y descargar reportes mensuales. Utiliza el menú lateral para navegar entre las
                            diferentes secciones.
                        </p>
                    </div>
                </div>

                <!-- SHIPS SECTION -->
                <div id="section-ships" class="tab-section">
                    <div style="display: flex; justify-content: flex-end; margin-bottom: 24px;">
                        <button class="btn-primary" onclick="openShipModal()">
                            <span>+</span> Agregar buque / equipo
                        </button>
                    </div>
                    <?php if (empty($grouped_ships)): ?>
                        <div class="empty-state-full">
                            <div class="empty-state-icon">🚢</div>
                            <h3>No hay equipos registrados</h3>
                            <p>Crea tu primer equipo para comenzar</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($grouped_ships as $adminName => $clientShips): ?>
                            <div class="client-group">
                                <div class="client-header">
                                    <span style="font-size: 1.4rem;">👤</span>
                                    <span class="client-name">Cliente: <?php echo htmlspecialchars($adminName); ?></span>
                                    <span class="client-badge"><?php echo count($clientShips); ?>
                                        <?php echo count($clientShips) === 1 ? 'equipo' : 'equipos'; ?></span>
                                </div>
                                <div class="ships-grid">
                                    <?php foreach ($clientShips as $ship): ?>
                                        <div class="ship-card" onclick="showCompanyModal({
                                            name: '<?php echo addslashes($ship['name']); ?>',
                                            ship_id: '<?php echo addslashes($ship['ship_id']); ?>',
                                            legal_name: '<?php echo addslashes($ship['legal_name'] ?? ''); ?>',
                                            address: '<?php echo addslashes($ship['address'] ?? ''); ?>',
                                            responsible: '<?php echo addslashes($ship['responsible_name'] ?? ''); ?>',
                                            cuit: '<?php echo addslashes($ship['cuit'] ?? ''); ?>',
                                            admin: '<?php echo addslashes($ship['admin_username'] ?? ''); ?>'
                                        })">
                                            <div class="ship-card-header">
                                                <div class="ship-card-icon"><?php echo htmlspecialchars($ship['icon'] ?? '🚢'); ?>
                                                </div>
                                                <div>
                                                    <h3 class="ship-card-title"><?php echo htmlspecialchars($ship['name']); ?></h3>
                                                    <p class="ship-card-id">ID: <?php echo htmlspecialchars($ship['ship_id']); ?>
                                                    </p>
                                                </div>
                                            </div>
                                            <div class="ship-card-body">
                                                <div class="ship-card-info" style="margin-bottom: 8px;">
                                                    <span class="ship-card-label">Admin Principal:</span>
                                                    <div style="margin-top: 4px;">
                                                        <?php if (empty($ship['admins'])): ?>
                                                            <span style="color: #8892b0; font-size: 13px;">Sin asignar</span>
                                                        <?php else: ?>
                                                            <?php foreach ($ship['admins'] as $adm): ?>
                                                                <div style="color: #00f2ff; font-weight: 600; font-size: 13px;">👤
                                                                    <?php echo htmlspecialchars($adm['username']); ?>
                                                                </div>
                                                            <?php endforeach; ?>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>

                                                <div class="ship-card-info"
                                                    style="margin-bottom: 12px; padding-top: 8px; border-top: 1px solid rgba(255,255,255,0.05);">
                                                    <span class="ship-card-label">Usuarios de Visualización:</span>
                                                    <div style="margin-top: 4px; max-height: 60px; overflow-y: auto;">
                                                        <?php if (empty($ship['viewers'])): ?>
                                                            <span style="color: #8892b0; font-size: 12px;">Ninguno</span>
                                                        <?php else: ?>
                                                            <?php foreach ($ship['viewers'] as $view): ?>
                                                                <div style="color: #fff; font-size: 12px; margin-bottom: 2px;">👁️
                                                                    <?php echo htmlspecialchars($view['username']); ?>
                                                                </div>
                                                            <?php endforeach; ?>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>

                                                <button class="btn-secondary"
                                                    onclick="event.stopPropagation(); toggleSensorConfigs('<?php echo $ship['ship_id']; ?>')"
                                                    style="width: 100%; border-radius: 6px; padding: 10px; font-weight: 600; display: flex; align-items: center; justify-content: center; gap: 10px;">
                                                    📊 Configurar Sensores
                                                    <span id="toggleIcon_<?php echo $ship['ship_id']; ?>">▼</span>
                                                </button>
                                            </div>

                                            <div id="sensorConfigs_<?php echo $ship['ship_id']; ?>"
                                                onclick="event.stopPropagation();"
                                                style="display: none; margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(0, 242, 255, 0.1);">
                                                <?php if (!empty($ship['sensor_configs'])): ?>
                                                    <?php foreach ($ship['sensor_configs'] as $config): ?>
                                                        <div class="sensor-config-item"
                                                            data-sensor-id="<?php echo htmlspecialchars($config['sensor_id']); ?>"
                                                            style="margin-bottom: 8px; padding: 8px; background: rgba(0, 242, 255, 0.05); border-radius: 4px;">
                                                            <div
                                                                style="color: #00f2ff; font-weight: 600; font-size: 13px; margin-bottom: 6px; display: flex; gap: 8px; justify-content: space-between; align-items: center;">
                                                                <input type="text" class="sensor-label-input"
                                                                    value="<?php echo htmlspecialchars($config['display_label'] ?? 'Sensor ' . $config['sensor_id']); ?>"
                                                                    style="background: transparent; border: 1px solid rgba(0,242,255,0.2); color: #fff; border-radius: 4px; padding: 2px 6px; width: 100%; font-size: 13px; flex: 1; min-width: 0;">
                                                                <button class="btn-danger btn-compact"
                                                                    onclick="openDeleteSensorModal('<?php echo $ship['ship_id']; ?>', <?php echo $config['sensor_id']; ?>)"
                                                                    style="padding: 2px 8px; font-size: 12px; flex-shrink: 0;">✕</button>
                                                            </div>
                                                            <div
                                                                style="display: flex; justify-content: space-between; gap: 10px; font-size: 12px; color: #8892b0;">
                                                                <div style="flex:1;">
                                                                    Máx (°C):
                                                                    <input type="number" step="0.1" class="sensor-max-temp modal-input"
                                                                        value="<?php echo htmlspecialchars($config['max_temp']); ?>"
                                                                        style="padding: 4px 8px; min-height: unset; margin-top:2px; font-size: 12px; width: 100%; box-sizing: border-box;">
                                                                </div>
                                                                <div style="flex:1;">
                                                                    Mín (°C):
                                                                    <input type="number" step="0.1" class="sensor-min-temp modal-input"
                                                                        value="<?php echo htmlspecialchars($config['min_temp']); ?>"
                                                                        style="padding: 4px 8px; min-height: unset; margin-top:2px; font-size: 12px; width: 100%; box-sizing: border-box;">
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                    <div style="margin-top: 12px; display: flex; gap: 8px;">
                                                        <button class="btn-secondary btn-compact"
                                                            onclick="addSensor('<?php echo $ship['ship_id']; ?>')" style="flex: 1;">+
                                                            Agregar Sensor</button>
                                                        <button class="btn-primary btn-compact"
                                                            onclick="saveSensorConfigs('<?php echo $ship['ship_id']; ?>')"
                                                            style="flex: 1;">Guardar</button>
                                                    </div>
                                                <?php else: ?>
                                                    <div style="color: #8892b0; font-size: 12px; text-align: center; padding: 8px;">
                                                        No hay sensores configurados
                                                    </div>
                                                <?php endif; ?>
                                            </div>

                                            <div class="ship-card-actions"
                                                style="margin-top: 16px; padding-top: 16px; border-top: 1px solid rgba(255, 255, 255, 0.05); display: flex; gap: 8px;">
                                                <button class="btn-secondary"
                                                    onclick="event.stopPropagation(); openAssignModal('<?php echo $ship['ship_id']; ?>', '<?php echo htmlspecialchars($ship['name']); ?>')"
                                                    style="flex: 1;">
                                                    Asignar
                                                </button>
                                                <button class="btn-secondary"
                                                    onclick="event.stopPropagation(); openEditShipModal(<?php echo htmlspecialchars(json_encode($ship)); ?>)"
                                                    style="flex: 1; border-color: var(--cyan-glow); color: var(--cyan-glow);">
                                                    Editar
                                                </button>
                                                <?php if (($_SESSION['username'] ?? '') === 'admin'): ?>
                                                    <button class="btn-danger"
                                                        onclick="event.stopPropagation(); openDeleteShipModal('<?php echo $ship['ship_id']; ?>', '<?php echo htmlspecialchars($ship['name']); ?>')"
                                                        style="padding: 8px 12px;">
                                                        🗑️
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <!-- USERS SECTION -->
            <div id="section-users" class="tab-section">
                <div class="reports-header">
                    <div>
                        <h2 class="reports-title">Pendientes de Aprobación</h2>
                    </div>
                </div>

                <?php if (empty($pending_users)): ?>
                    <div class="empty-state-full">
                        <div class="empty-state-icon">✅</div>
                        <h3>No hay solicitudes pendientes</h3>
                    </div>
                <?php else: ?>
                    <div class="history-table-container-full">
                        <table class="history-table-full">
                            <thead>
                                <tr>
                                    <th>Usuario</th>
                                    <th>Fecha de Solicitud</th>
                                    <th style="text-align: right;">Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($pending_users as $u): ?>
                                    <tr id="user-<?php echo $u['id']; ?>">
                                        <td>
                                            <strong
                                                style="color: #00f2ff;"><?php echo htmlspecialchars($u['username']); ?></strong>
                                        </td>
                                        <td>
                                            <span
                                                style="color: #8892b0;"><?php echo date('d/m/Y H:i', strtotime($u['created_at'])); ?></span>
                                        </td>
                                        <td class="history-actions">
                                            <button class="btn-success"
                                                onclick="updateStatus(<?php echo $u['id']; ?>, 'active')"
                                                style="margin-right: 8px;">Aprobar</button>
                                            <button class="btn-danger"
                                                onclick="updateStatus(<?php echo $u['id']; ?>, 'rejected')">Rechazar</button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>

                <div class="reports-header" style="margin-top: 48px;">
                    <div>
                        <h2 class="reports-title">Usuarios por Buque / Equipo</h2>
                    </div>
                    <div style="flex: 1; max-width: 400px; margin-left: 24px;">
                        <input type="text" id="userSearchInput" class="modal-input"
                            placeholder="🔍 Buscar por buque o usuario..."
                            style="width: 100%; padding: 10px 16px; font-size: 14px;" onkeyup="filterUsersTable()">
                    </div>
                </div>

                <?php
                // Preparar todos los usuarios en una sola lista para la tabla
                // Obtener todos los usuarios activos directamente desde la BD para asegurar datos actualizados
                $allUsersList = [];
                $stmtAll = $pdo->query("SELECT u.id, u.username, u.role, u.ship_id, u.created_at, s.name as ship_name, s.icon as ship_icon
                                            FROM users u 
                                            LEFT JOIN ships s ON u.ship_id = s.ship_id 
                                            WHERE u.status = 'active' AND u.role != 'admin' 
                                            ORDER BY u.ship_id, u.role DESC, u.created_at DESC");
                $allUsersFromDB = $stmtAll ? $stmtAll->fetchAll(PDO::FETCH_ASSOC) : [];

                foreach ($allUsersFromDB as $user) {
                    $allUsersList[] = [
                        'id' => $user['id'],
                        'username' => $user['username'],
                        'role' => ($user['role'] === 'sub-adm') ? 'Admin asignado' : 'Usuario',
                        'ship_id' => $user['ship_id'] ?? 'sin_buque',
                        'ship_name' => $user['ship_name'] ?? ($user['ship_id'] ?? 'Sin Buque Asignado'),
                        'ship_icon' => $user['ship_icon'] ?? '🚢',
                        'created_at' => $user['created_at']
                    ];
                }
                ?>

                <?php if (empty($allUsersList)): ?>
                    <div class="empty-state-full">
                        <div class="empty-state-icon">👤</div>
                        <h3>No hay usuarios activos</h3>
                    </div>
                <?php else: ?>
                    <div class="history-table-container-full">
                        <table class="history-table-full" id="usersTable">
                            <thead>
                                <tr>
                                    <th>Buque/ Equipo</th>
                                    <th>ID </th>
                                    <th>Usuario</th>
                                    <th>Rol</th>
                                    <th>Fecha de Alta</th>
                                    <th style="text-align: right;">Acciones</th>
                                </tr>
                            </thead>
                            <tbody id="usersTableBody">
                                <?php
                                foreach ($allUsersList as $user):
                                    // Fetch all assigned ships for this user
                                    $userShipsStmt = $pdo->prepare("SELECT s.ship_id, s.name FROM ships s JOIN user_ships us ON s.ship_id = us.ship_id WHERE us.user_id = :uid");
                                    $userShipsStmt->execute([':uid' => $user['id']]);
                                    $userAssignedShips = $userShipsStmt->fetchAll(PDO::FETCH_ASSOC);

                                    $shipNames = array_column($userAssignedShips, 'name');
                                    $shipIds = array_column($userAssignedShips, 'ship_id');
                                    $displayShips = !empty($shipNames) ? implode(', ', $shipNames) : 'Sin Buque';
                                    $idsJson = json_encode($shipIds);
                                    ?>
                                    <tr class="user-row"
                                        data-username="<?php echo htmlspecialchars(strtolower($user['username'])); ?>"
                                        data-role="<?php echo htmlspecialchars(strtolower($user['role'])); ?>"
                                        data-ship="<?php echo htmlspecialchars(strtolower($displayShips)); ?>">
                                        <td>
                                            <div class="user-info">
                                                <div class="user-avatar">
                                                    <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
                                                </div>
                                                <strong
                                                    style="color: #00f2ff;"><?php echo htmlspecialchars($displayShips); ?></strong>
                                            </div>
                                        </td>
                                        <td>
                                            <span style="color: #8892b0; font-size: 13px;">
                                                <?php echo !empty($shipIds) ? implode(', ', $shipIds) : '---'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <strong
                                                style="color: #00f2ff;"><?php echo htmlspecialchars($user['username']); ?></strong>
                                        </td>
                                        <td>
                                            <span style="color: #8892b0;"><?php echo htmlspecialchars($user['role']); ?></span>
                                        </td>
                                        <td>
                                            <span
                                                style="color: #8892b0;"><?php echo date('d/m/Y', strtotime($user['created_at'])); ?></span>
                                        </td>
                                        <td class="history-actions">
                                            <?php if ($user['role'] === 'Admin asignado'): ?>
                                                <button class="btn-secondary btn-compact"
                                                    onclick="openRemoveAdminModal(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['username']); ?>', '<?php echo htmlspecialchars($displayShips); ?>')"
                                                    style="margin-right: 8px; background: #6c5ce7; color: #fff; border-color: #6c5ce7;">Quitar
                                                    Admin</button>
                                            <?php endif; ?>
                                            <button class="btn-secondary btn-compact"
                                                onclick='openChangeShipModal(<?php echo $user['id']; ?>, "<?php echo htmlspecialchars($user['username']); ?>", <?php echo $idsJson; ?>)'
                                                style="margin-right: 8px;">Gestionar Buques</button>
                                            <button class="btn-secondary btn-compact"
                                                onclick="openChangePasswordModal(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['username']); ?>')"
                                                style="margin-right: 8px;">Contraseña</button>
                                            <button class="btn-danger btn-compact"
                                                onclick="openDeleteUserModal(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['username']); ?>', '<?php echo htmlspecialchars($displayShips); ?>')"
                                                style="margin-right: 8px;">Quitar Acceso</button>
                                            <button class="btn-danger btn-compact"
                                                onclick="openDeleteUserCompletelyModal(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['username']); ?>')"
                                                style="background: #ff4d4d; border-color: #ff4d4d;">Eliminar
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <div id="noUsersFound" style="display: none; padding: 40px; text-align: center; color: #8892b0;">
                            <p>No se encontraron usuarios que coincidan con la búsqueda</p>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- REPORTS SECTION -->
            <div id="section-reports" class="tab-section">
                <div class="reports-header">
                    <div>
                        <p class="reports-subtitle">Historial completo de reportes Excel disponibles</p>
                    </div>
                    <div id="reportsInfo" class="reports-info">
                        <?php
                        $totalMeses = 0;
                        foreach ($monthly_reports as $r) {
                            if (!empty($r['months'])) {
                                $totalMeses += count($r['months']);
                            }
                        }
                        if ($totalMeses > 0) {
                            echo "Total: $totalMeses reportes disponibles";
                        }
                        ?>
                    </div>
                </div>

                <!-- VISTA UNIFICADA DE HISTORIAL -->
                <?php
                // Preparar todos los reportes en una sola lista para ordenar
                $allReports = [];
                $monthNames = [
                    1 => 'Enero',
                    2 => 'Febrero',
                    3 => 'Marzo',
                    4 => 'Abril',
                    5 => 'Mayo',
                    6 => 'Junio',
                    7 => 'Julio',
                    8 => 'Agosto',
                    9 => 'Septiembre',
                    10 => 'Octubre',
                    11 => 'Noviembre',
                    12 => 'Diciembre'
                ];

                foreach ($monthly_reports as $ship_id => $report) {
                    foreach ($report['months'] as $monthData) {
                        $allReports[] = [
                            'ship_id' => $ship_id,
                            'ship_name' => $report['name'],
                            'year' => $monthData['year'],
                            'month' => $monthData['month'],
                            'month_name' => $monthNames[(int) $monthData['month']] ?? 'Mes',
                            'sort_key' => $monthData['year'] * 100 + (int) $monthData['month']
                        ];
                    }
                }

                // Ordenar por año y mes descendente (más reciente primero)
                usort($allReports, function ($a, $b) {
                    return $b['sort_key'] - $a['sort_key'];
                });

                // Paginación
                $itemsPerPage = 50;
                $totalItems = count($allReports);
                $totalPages = ceil($totalItems / $itemsPerPage);
                $currentPage = isset($_GET['page']) ? max(1, min((int) $_GET['page'], $totalPages)) : 1;
                $startIndex = ($currentPage - 1) * $itemsPerPage;
                $paginatedReports = array_slice($allReports, $startIndex, $itemsPerPage);
                ?>
                <?php if (empty($allReports)): ?>
                    <div class="empty-state-full">
                        <div class="empty-state-icon">📊</div>
                        <h3>No hay reportes disponibles</h3>
                        <p>Los reportes aparecerán aquí cuando haya datos registrados</p>
                    </div>
                <?php else: ?>
                    <div class="history-table-container-full">
                        <table class="history-table-full">
                            <thead>
                                <tr>
                                    <th>Buque</th>
                                    <th>ID Buque</th>
                                    <th>Período</th>
                                    <th>Mes</th>
                                    <th>Año</th>
                                    <th style="text-align: right;">Acción</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($paginatedReports as $reportItem):
                                    $monthNum = str_pad($reportItem['month'], 2, '0', STR_PAD_LEFT);
                                    ?>
                                    <tr>
                                        <td>
                                            <div style="display: flex; align-items: center; gap: 8px;">
                                                <span
                                                    style="font-size: 18px;"><?php echo htmlspecialchars($user['ship_icon'] ?? '🚢'); ?></span>
                                                <strong
                                                    style="color: #00f2ff;"><?php echo htmlspecialchars($reportItem['ship_name']); ?></strong>
                                            </div>
                                        </td>
                                        <td>
                                            <span
                                                style="color: #8892b0; font-size: 13px;"><?php echo htmlspecialchars($reportItem['ship_id']); ?></span>
                                        </td>
                                        <td>
                                            <div class="history-date">
                                                <span class="history-date-month"><?php echo $reportItem['month_name']; ?></span>
                                                <span class="history-date-year"><?php echo $reportItem['year']; ?></span>
                                            </div>
                                        </td>
                                        <td><?php echo $reportItem['month_name']; ?></td>
                                        <td><?php echo $reportItem['year']; ?></td>
                                        <td class="history-actions">
                                            <a href="api/export_monthly.php?buque_id=<?php echo urlencode($reportItem['ship_id']); ?>&year=<?php echo $reportItem['year']; ?>&month=<?php echo $monthNum; ?>"
                                                class="btn-download-history" target="_blank">
                                                <span>⬇️</span> Descargar Excel
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <?php if ($totalPages > 1): ?>
                        <div class="pagination-container">
                            <div class="pagination-info">
                                Mostrando <?php echo $startIndex + 1; ?> -
                                <?php echo min($startIndex + $itemsPerPage, $totalItems); ?> de <?php echo $totalItems; ?>
                                reportes
                            </div>
                            <div class="pagination">
                                <?php if ($currentPage > 1): ?>
                                    <a href="?page=<?php echo $currentPage - 1; ?>" class="pagination-btn">« Anterior</a>
                                <?php endif; ?>

                                <?php
                                $startPage = max(1, $currentPage - 2);
                                $endPage = min($totalPages, $currentPage + 2);

                                if ($startPage > 1): ?>
                                    <a href="?page=1" class="pagination-btn">1</a>
                                    <?php if ($startPage > 2): ?>
                                        <span class="pagination-dots">...</span>
                                    <?php endif; ?>
                                <?php endif; ?>

                                <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                                    <a href="?page=<?php echo $i; ?>"
                                        class="pagination-btn <?php echo $i === $currentPage ? 'active' : ''; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                <?php endfor; ?>

                                <?php if ($endPage < $totalPages): ?>
                                    <?php if ($endPage < $totalPages - 1): ?>
                                        <span class="pagination-dots">...</span>
                                    <?php endif; ?>
                                    <a href="?page=<?php echo $totalPages; ?>" class="pagination-btn"><?php echo $totalPages; ?></a>
                                <?php endif; ?>

                                <?php if ($currentPage < $totalPages): ?>
                                    <a href="?page=<?php echo $currentPage + 1; ?>" class="pagination-btn">Siguiente »</a>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
    </div>
    </main>
    </div>

    <!-- MODALES -->
    <div id="shipModal" class="modal-overlay" onclick="if(event.target===this) closeModal('shipModal')">
        <div class="modal-content" style="max-width: 500px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                <h3 id="shipModalTitle" style="margin: 0;">⚙️ Nuevo Buque / Equipo</h3>
                <button class="modal-close" onclick="closeModal('shipModal')">&times;</button>
            </div>
            <p style="color: #8892b0; margin-bottom: 20px;">Ingresa los datos del nuevo buque o equipo</p>

            <label style="display: block; color: #fff; font-size: 14px; font-weight: 600; margin-bottom: 8px;">
                Tipo:
            </label>
            <select id="newShipType" class="modal-input" onchange="updateShipModal()" style="margin-bottom: 16px;">
                <option value="buque">🚢 Buque</option>
                <option value="equipo">⚙️ Equipo</option>
            </select>

            <label style="display: block; color: #fff; font-size: 14px; font-weight: 600; margin-bottom: 8px;">
                Icono:
            </label>
            <div id="iconSelector"
                style="display: grid; grid-template-columns: repeat(6, 1fr); gap: 8px; margin-bottom: 16px;">
                <button type="button" class="icon-option active" data-icon="🚢" onclick="selectIcon('🚢')">🚢</button>
                <button type="button" class="icon-option" data-icon="⚙️" onclick="selectIcon('⚙️')">⚙️</button>
                <button type="button" class="icon-option" data-icon="🏭" onclick="selectIcon('🏭')">🏭</button>
                <button type="button" class="icon-option" data-icon="🚛" onclick="selectIcon('🚛')">🚛</button>
                <button type="button" class="icon-option" data-icon="📦" onclick="selectIcon('📦')">📦</button>
                <button type="button" class="icon-option" data-icon="🔧" onclick="selectIcon('🔧')">🔧</button>
            </div>
            <input type="hidden" id="selectedIcon" value="🚢">

            <label style="display: block; color: #fff; font-size: 14px; font-weight: 600; margin-bottom: 8px;">
                ID (ej: BUQUE-02, EQUIPO-01):
            </label>
            <input type="text" id="newShipId" class="modal-input" placeholder="ID del buque o equipo"
                style="margin-bottom: 16px;">

            <label style="display: block; color: #fff; font-size: 14px; font-weight: 600; margin-bottom: 8px;">
                Nombre:
            </label>
            <input type="text" id="newShipName" class="modal-input" placeholder="Nombre del buque o equipo"
                style="margin-bottom: 16px;">

            <label style="display: block; color: #fff; font-size: 14px; font-weight: 600; margin-bottom: 8px;">
                Cantidad de Sensores:
            </label>
            <input type="number" id="newShipSensors" class="modal-input" placeholder="Ej: 14" min="1" max="16"
                value="14" style="margin-bottom: 20px;">

            <div class="modal-actions">
                <button class="btn-primary" onclick="createShip()" style="flex: 1;">Crear</button>
                <button class="btn-secondary" onclick="closeModal('shipModal')" style="flex: 1;">Cancelar</button>
            </div>
        </div>
    </div>

    <div id="editShipModal" class="modal-overlay" onclick="if(event.target===this) closeModal('editShipModal')">
        <div class="modal-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                <h3 style="margin: 0;">✏️ Editar Buque / Equipo</h3>
                <button class="modal-close" onclick="closeModal('editShipModal')">&times;</button>
            </div>
            <input type="hidden" id="editOldShipId">

            <label style="color: #8892b0; font-size: 12px; margin-bottom: 4px; display: block;">ID del Buque:</label>
            <input type="text" id="editShipId" class="modal-input" placeholder="ID del Buque">

            <label
                style="color: #8892b0; font-size: 12px; margin-top: 12px; margin-bottom: 4px; display: block;">Nombre:</label>
            <input type="text" id="editShipName" class="modal-input" placeholder="Nombre">

            <div style="margin: 15px 0;">
                <label style="color: #8892b0; font-size: 12px; display: block; margin-bottom: 4px;">Tipo:</label>
                <select id="editShipType" class="modal-input">
                    <option value="buque">Buque 🚢</option>
                    <option value="equipo">Equipo Industrial ⚙️</option>
                </select>
            </div>

            <div style="margin-bottom: 20px;">
                <label style="color: #8892b0; font-size: 12px; display: block; margin-bottom: 8px;">Icono:</label>
                <div id="editIconPicker" class="icon-picker"
                    style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px;">
                    <button class="icon-option" onclick="selectEditIcon('🚢', this)">🚢</button>
                    <button class="icon-option" onclick="selectEditIcon('⛴️', this)">⛴️</button>
                    <button class="icon-option" onclick="selectEditIcon('⚙️', this)">⚙️</button>
                    <button class="icon-option" onclick="selectEditIcon('🏢', this)">🏢</button>
                    <button class="icon-option" onclick="selectEditIcon('🧊', this)">🧊</button>
                </div>
                <input type="hidden" id="editSelectedIcon" value="🚢">
            </div>

            <div class="modal-actions">
                <button class="btn-primary" onclick="updateShip()" style="flex: 1;">Guardar Cambios</button>
                <button class="btn-secondary" onclick="closeModal('editShipModal')" style="flex: 1;">Cancelar</button>
            </div>
        </div>
    </div>

    <div id="assignModal" class="modal-overlay" onclick="if(event.target===this) closeModal('assignModal')">
        <div class="modal-content" style="max-width: 600px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3 id="assignModalTitle" style="margin: 0;">👤 Asignar Administrador</h3>
                <button class="modal-close" onclick="closeModal('assignModal')">&times;</button>
            </div>
            <input type="hidden" id="assignShipId">

            <!-- Tabs para elegir entre buscar usuario o crear nuevo -->
            <div style="display: flex; gap: 8px; margin-bottom: 20px; border-bottom: 1px solid rgba(0, 242, 255, 0.1);">
                <button id="tabSearchUser" class="tab-button active" onclick="switchAssignTab('search')"
                    style="flex: 1; padding: 10px; background: rgba(0, 242, 255, 0.1); border: none; border-bottom: 2px solid #00f2ff; color: #00f2ff; cursor: pointer; font-weight: 600;">
                    🔍 Buscar Usuario
                </button>
                <button id="tabCreateUser" class="tab-button" onclick="switchAssignTab('create')"
                    style="flex: 1; padding: 10px; background: transparent; border: none; border-bottom: 2px solid transparent; color: #8892b0; cursor: pointer; font-weight: 600;">
                    ➕ Crear Nuevo
                </button>
            </div>

            <!-- Panel de búsqueda de usuario -->
            <div id="searchUserPanel">
                <p style="color: #8892b0; margin-bottom: 16px;">Busca un usuario existente para asignarlo como
                    administrador</p>
                <input type="text" id="searchUserInput" class="modal-input"
                    placeholder="🔍 Buscar usuario por nombre..." onkeyup="searchUsersForAdmin()"
                    style="margin-bottom: 16px;">
                <div id="searchUsersResults"
                    style="max-height: 300px; overflow-y: auto; border: 1px solid rgba(0, 242, 255, 0.1); border-radius: 8px; padding: 12px; background: rgba(5, 10, 16, 0.5);">
                    <p style="color: #8892b0; text-align: center; margin: 20px 0;">Escribe para buscar usuarios...</p>
                </div>
                <p id="assignSearchError"
                    style="color: #ff4d4d; font-size: 13px; text-align: center; margin-top: 10px; display: none;"></p>
            </div>

            <!-- Panel de crear nuevo usuario -->
            <div id="createUserPanel" style="display: none;">
                <p style="color: #8892b0; margin-bottom: 16px;">Crear una nueva cuenta de administrador para este buque
                </p>
                <input type="text" id="adminUser" class="modal-input" placeholder="Usuario">
                <input type="password" id="adminPass" class="modal-input" placeholder="Contraseña"
                    style="margin-top: 12px; margin-bottom: 20px;">

                <h4
                    style="color: #00f2ff; margin-bottom: 12px; border-bottom: 1px solid rgba(0, 242, 255, 0.1); padding-bottom: 8px;">
                    Datos de la Empresa</h4>
                <input type="text" id="legalName" class="modal-input" placeholder="Nombre/Razón Social"
                    style="margin-bottom: 12px;">
                <input type="text" id="companyAddress" class="modal-input" placeholder="Dirección"
                    style="margin-bottom: 12px;">
                <input type="text" id="responsibleName" class="modal-input" placeholder="Nombre de responsable"
                    style="margin-bottom: 12px;">
                <input type="text" id="companyCuit" class="modal-input" placeholder="CUIT" style="margin-bottom: 12px;">
            </div>

            <div class="modal-actions" style="margin-top: 20px;">
                <button class="btn-primary" id="assignActionButton" onclick="createShipAdmin()" style="flex: 1;">Crear
                    Admin</button>
                <button class="btn-secondary" onclick="closeModal('assignModal')" style="flex: 1;">Cancelar</button>
            </div>
        </div>
    </div>

    <!-- MODAL DE INFORMACIÓN DE EMPRESA -->
    <div id="companyModal" class="modal-overlay" onclick="if(event.target===this) closeModal('companyModal')">
        <div class="modal-content" style="max-width: 500px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3 style="margin: 0;">🏢 Información de la Empresa</h3>
                <button class="modal-close" onclick="closeModal('companyModal')">&times;</button>
            </div>
            <div id="companyDetailsContent" style="margin-top: 20px;">
                <!-- Dinámico -->
            </div>
            <div class="modal-actions" style="margin-top: 24px;">
                <a id="goToTempLink" href="#" class="btn-primary"
                    style="flex: 2; text-decoration: none; display: flex; align-items: center; justify-content: center;">Ver
                    historial de temperaturas 🌡️</a>
                <button class="btn-secondary" onclick="closeModal('companyModal')" style="flex: 1;">Cerrar</button>
            </div>
        </div>
    </div>

    <div id="assignUserShipModal" class="modal-overlay"
        onclick="if(event.target===this) closeModal('assignUserShipModal')">
        <div class="modal-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3 style="margin: 0;">🚢 Asignar Buque a Usuario</h3>
                <button class="modal-close" onclick="closeModal('assignUserShipModal')">&times;</button>
            </div>
            <p id="assignUserInfo" style="color: #8892b0;"></p>
            <input type="hidden" id="assignUserId">
            <select id="assignShipSelect" class="modal-input">
                <option value="">-- Seleccionar Buque --</option>
                <?php foreach ($ships as $s): ?>
                    <option value="<?php echo htmlspecialchars($s['ship_id']); ?>">
                        <?php echo htmlspecialchars($s['name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <div class="modal-actions">
                <button class="btn-primary" onclick="confirmAssignShip()" style="flex: 1;">Guardar</button>
                <button class="btn-secondary" onclick="closeModal('assignUserShipModal')"
                    style="flex: 1;">Cancelar</button>
            </div>
        </div>
    </div>

    <div id="deleteShipModal" class="modal-overlay" onclick="if(event.target===this) closeModal('deleteShipModal')">
        <div class="modal-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                <h3 style="margin: 0;">🗑️ Eliminar Buque</h3>
                <button class="modal-close" onclick="closeModal('deleteShipModal')">&times;</button>
            </div>
            <p style="color: #ff4d4d; font-weight: 600; margin-bottom: 16px;">⚠️ Esta acción no se puede deshacer</p>
            <p id="deleteShipInfo" style="color: #8892b0; margin-bottom: 24px;"></p>
            <input type="hidden" id="deleteShipId">
            <label style="display: block; color: #fff; font-size: 14px; font-weight: 600; margin-bottom: 8px;">
                Confirma tu contraseña para eliminar:
            </label>
            <input type="password" id="deleteShipPassword" class="modal-input" placeholder="Ingresa tu contraseña">
            <div class="modal-actions">
                <button class="btn-danger" onclick="confirmDeleteShip()" style="flex: 1;">Eliminar Buque</button>
                <button class="btn-secondary" onclick="closeModal('deleteShipModal')" style="flex: 1;">Cancelar</button>
            </div>
        </div>
    </div>

    <!-- ELIMINAR SENSOR MODAL -->
    <div id="deleteSensorModal" class="modal-overlay" onclick="if(event.target===this) closeModal('deleteSensorModal')">
        <div class="modal-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                <h3 style="margin: 0;">🗑️ Eliminar Sensor</h3>
                <button class="modal-close" onclick="closeModal('deleteSensorModal')">&times;</button>
            </div>
            <p style="color: #ff4d4d; font-weight: 600; margin-bottom: 16px;">⚠️ Perderás el historial gráfico
                registrado bajo este sensor.</p>
            <p id="deleteSensorInfo" style="color: #8892b0; margin-bottom: 24px;"></p>
            <input type="hidden" id="deleteSensorShipId">
            <input type="hidden" id="deleteSensorId">
            <div class="modal-actions">
                <button class="btn-danger" onclick="confirmDeleteSensor()" style="flex: 1;">Sí, Eliminar</button>
                <button class="btn-secondary" onclick="closeModal('deleteSensorModal')"
                    style="flex: 1;">Cancelar</button>
            </div>
        </div>
    </div>

    <div id="changePasswordModal" class="modal-overlay"
        onclick="if(event.target===this) closeModal('changePasswordModal')">
        <div class="modal-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3 style="margin: 0;">🔑 Cambiar Contraseña</h3>
                <button class="modal-close" onclick="closeModal('changePasswordModal')">&times;</button>
            </div>
            <p id="changePasswordInfo" style="color: #8892b0; margin-bottom: 24px;"></p>
            <input type="hidden" id="changePasswordUserId">
            <label style="display: block; color: #fff; font-size: 14px; font-weight: 600; margin-bottom: 8px;">
                Confirma tu contraseña de administrador:
            </label>
            <input type="password" id="adminPasswordConfirm" class="modal-input"
                placeholder="Ingresa tu contraseña de admin">
            <label
                style="display: block; color: #fff; font-size: 14px; font-weight: 600; margin-bottom: 8px; margin-top: 16px;">
                Nueva contraseña para el usuario:
            </label>
            <input type="password" id="newUserPassword" class="modal-input" placeholder="Nueva contraseña">
            <div class="modal-actions">
                <button class="btn-primary" onclick="confirmChangePassword()" style="flex: 1;">Cambiar
                    Contraseña</button>
                <button class="btn-secondary" onclick="closeModal('changePasswordModal')"
                    style="flex: 1;">Cancelar</button>
            </div>
        </div>
    </div>

    <div id="removeAdminModal" class="modal-overlay" onclick="if(event.target===this) closeModal('removeAdminModal')">
        <div class="modal-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                <h3 style="margin: 0;">⚠️ Quitar Administrador</h3>
                <button class="modal-close" onclick="closeModal('removeAdminModal')">&times;</button>
            </div>
            <p style="color: #8892b0; margin-bottom: 16px;">
                ¿Estás seguro de que deseas quitar el rol de administrador a este usuario?
                El usuario se convertirá en usuario común pero seguirá asignado al buque.
            </p>
            <input type="hidden" id="removeAdminUserId">
            <p id="removeAdminInfo" style="color: #8892b0; margin-bottom: 24px;"></p>
            <label style="display: block; color: #fff; font-size: 14px; font-weight: 600; margin-bottom: 8px;">
                Confirma tu contraseña de administrador:
            </label>
            <input type="password" id="removeAdminPassword" class="modal-input"
                placeholder="Ingresa tu contraseña de admin">
            <div class="modal-actions">
                <button class="btn-danger" onclick="confirmRemoveAdmin()"
                    style="flex: 1; background: #6c5ce7; color: #fff; border-color: #6c5ce7;">Quitar Admin</button>
                <button class="btn-secondary" onclick="closeModal('removeAdminModal')"
                    style="flex: 1;">Cancelar</button>
            </div>
        </div>
    </div>

    <!-- MODAL ELIMINAR USUARIO COMPLETAMENTE -->
    <div id="deleteUserCompletelyModal" class="modal-overlay"
        onclick="if(event.target===this) closeModal('deleteUserCompletelyModal')">
        <div class="modal-content" style="max-width: 450px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                <h3 style="margin: 0;">🗑️ Eliminar Usuario Permanentemente</h3>
                <button class="modal-close" onclick="closeModal('deleteUserCompletelyModal')">&times;</button>
            </div>
            <p id="deleteUserCompletelyInfo" style="color: #8892b0; margin-bottom: 16px;"></p>
            <input type="hidden" id="deleteUserCompletelyId">

            <p style="color: #ff4d4d; font-size: 12px; margin-bottom: 8px;">Esta acción no se puede deshacer. Confirma
                tu contraseña de administrador:</p>
            <input type="password" id="deleteUserAdminPass" class="modal-input" placeholder="Contraseña Admin Staff">

            <div class="modal-actions" style="margin-top: 20px;">
                <button class="btn-danger" onclick="deleteUserCompletely()" style="flex: 1;">ELIMINAR
                    COMPLETAMENTE</button>
                <button class="btn-secondary" onclick="closeModal('deleteUserCompletelyModal')"
                    style="flex: 1;">Cancelar</button>
            </div>
        </div>
    </div>

    <div id="deleteUserModal" class="modal-overlay" onclick="if(event.target===this) closeModal('deleteUserModal')">
        <div class="modal-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                <h3 style="margin: 0;">🗑️ Eliminar Usuario del Buque</h3>
                <button class="modal-close" onclick="closeModal('deleteUserModal')">&times;</button>
            </div>
            <p style="color: #ff4d4d; font-weight: 600; margin-bottom: 16px;">⚠️ Esta acción eliminará al usuario del
                buque</p>
            <p id="deleteUserInfo" style="color: #8892b0; margin-bottom: 24px;"></p>
            <input type="hidden" id="deleteUserId">
            <label style="display: block; color: #fff; font-size: 14px; font-weight: 600; margin-bottom: 8px;">
                Confirma tu contraseña de administrador:
            </label>
            <input type="password" id="deleteUserPassword" class="modal-input"
                placeholder="Ingresa tu contraseña de admin">
            <div class="modal-actions">
                <button class="btn-danger" onclick="confirmDeleteUser()" style="flex: 1;">Eliminar del Buque</button>
                <button class="btn-secondary" onclick="closeModal('deleteUserModal')" style="flex: 1;">Cancelar</button>
            </div>
        </div>
    </div>

    <!-- MODAL: GESTIONAR BUQUES ASIGNADOS -->
    <div id="changeShipModal" class="modal-overlay" style="display: none;">
        <div class="modal-content" style="max-width: 500px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3 style="margin: 0; color: var(--cyan-glow); display: flex; align-items: center; gap: 10px;">
                    <span style="font-size: 1.5rem;">🚢</span> Gestionar Buques Asignados
                </h3>
                <button class="modal-close" onclick="closeModal('changeShipModal')">&times;</button>
            </div>

            <p id="changeShipInfo" style="color: #8892b0; margin-bottom: 20px; font-size: 0.95rem;"></p>
            <input type="hidden" id="changeShipUserId">

            <div style="margin-bottom: 20px;">
                <label style="display: block; color: #fff; margin-bottom: 12px; font-weight: 600; font-size: 0.9rem;">
                    Seleccionar buques para el administrador:
                </label>
                <div id="shipChecklistContainer"
                    style="background: rgba(5, 10, 16, 0.5); border: 1px solid rgba(0, 242, 255, 0.1); border-radius: 8px; padding: 15px; max-height: 250px; overflow-y: auto;">
                    <?php
                    $pdo = getDBConnection();
                    $allShipsStmt = $pdo->query("SELECT ship_id, name FROM ships ORDER BY name ASC");
                    $allShips = $allShipsStmt->fetchAll(PDO::FETCH_ASSOC);
                    foreach ($allShips as $s): ?>
                        <label
                            style="display: flex; align-items: center; gap: 12px; padding: 8px; border-radius: 6px; cursor: pointer; transition: background 0.2s;"
                            onmouseover="this.style.background='rgba(255,255,255,0.05)'"
                            onmouseout="this.style.background='transparent'">
                            <input type="checkbox" name="ship_ids[]" value="<?php echo htmlspecialchars($s['ship_id']); ?>"
                                class="ship-checkbox">
                            <span style="color: #fff; font-size: 0.9rem;"><?php echo htmlspecialchars($s['name']); ?></span>
                        </label>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="modal-actions" style="margin-top: 30px;">
                <button class="modal-btn cancel" onclick="closeModal('changeShipModal')">CANCELAR</button>
                <button class="modal-btn confirm" onclick="confirmChangeShip()">GUARDAR CAMBIOS</button>
            </div>
        </div>
    </div>

    <script>
        function switchSection(section) {
            // Ocultar todas las secciones
            document.querySelectorAll('.tab-section').forEach(s => s.classList.remove('active'));
            document.querySelectorAll('.menu-item').forEach(m => m.classList.remove('active'));

            const targetSection = document.getElementById('section-' + section);
            if (!targetSection) return;

            // Mostrar sección seleccionada
            targetSection.classList.add('active');

            // Actualizar menú
            document.querySelectorAll('.sidebar-menu .menu-item').forEach(item => {
                if (item.getAttribute('onclick') && item.getAttribute('onclick').includes(`'${section}'`)) {
                    item.classList.add('active');
                }
            });

            // Actualizar título
            const titles = {
                'dashboard': 'Dashboard',
                'ships': 'Gestión de equipos controlados',
                'users': 'Gestión de Usuarios',
                'reports': 'Reportes Mensuales'
            };
            document.getElementById('pageTitle').textContent = titles[section] || 'Dashboard';

            // Persistencia en URL
            window.location.hash = section;
        }

        // Inicializar sección desde el hash
        window.addEventListener('load', () => {
            const hash = window.location.hash.replace('#', '');
            if (hash) {
                switchSection(hash);
            }
        });

        // Corrección inmediata de la tabla de usuarios (Compactar y una sola línea)
        function fixUsersTableLayout() {
            const rows = document.querySelectorAll('#usersTableBody tr');
            rows.forEach(row => {
                const actionsCell = row.querySelector('.history-actions');
                if (actionsCell) {
                    actionsCell.style.whiteSpace = 'nowrap';
                    actionsCell.style.display = 'flex';
                    actionsCell.style.gap = '4px';
                    actionsCell.style.alignItems = 'center';

                    actionsCell.querySelectorAll('button').forEach(btn => {
                        btn.classList.add('btn-compact');
                        btn.style.marginRight = '0';
                        btn.style.color = '#fff';
                        const text = btn.textContent.trim();
                        if (text.includes('Cambiar Buque')) btn.textContent = 'Buque';
                        if (text.includes('Cambiar Contraseña')) btn.textContent = 'Pass';
                        if (text.includes('Quitar de Buque')) btn.textContent = 'Quitar';
                        if (text.includes('Eliminar Permanente') || text.includes('Eliminar')) btn.textContent = 'Eliminar';
                    });
                }

                const shipCell = row.cells[0];
                if (shipCell) {
                    const shipNameElem = shipCell.querySelector('strong');
                    if (shipNameElem) shipNameElem.parentElement.style.whiteSpace = 'nowrap';
                }
            });
        }

        window.addEventListener('load', fixUsersTableLayout);
        window.addEventListener('hashchange', fixUsersTableLayout);

        function toggleSidebar() {
            if (window.innerWidth <= 768) {
                document.querySelector('.sidebar').classList.toggle('open');
            }
        }

        function toggleMenu() {
            const dropdown = document.getElementById('menuDropdown');
            dropdown.style.display = dropdown.style.display === 'none' ? 'block' : 'none';
        }

        // Cerrar el menú al hacer clic fuera
        document.addEventListener('click', function (event) {
            const dropdown = document.getElementById('menuDropdown');
            const btn = event.target.closest('.btn-icon');
            if (!btn && !dropdown.contains(event.target)) {
                dropdown.style.display = 'none';
            }
        });

        function openShipModal() {
            document.getElementById('shipModal').style.display = 'flex';
            document.getElementById('newShipId').value = '';
            document.getElementById('newShipName').value = '';
            document.getElementById('newShipType').value = 'buque';
            selectIcon('🚢');
            updateShipModal();
        }

        function updateShipModal() {
            const type = document.getElementById('newShipType').value;
            const title = document.getElementById('shipModalTitle');
            const idInput = document.getElementById('newShipId');
            const nameInput = document.getElementById('newShipName');

            if (type === 'buque') {
                title.innerHTML = '🚢 Nuevo Buque';
                idInput.placeholder = 'ID Buque (ej: BUQUE-02)';
                nameInput.placeholder = 'Nombre del Buque';
                selectIcon('🚢');
            } else {
                title.innerHTML = '⚙️ Nuevo Equipo';
                idInput.placeholder = 'ID Equipo (ej: EQUIPO-01)';
                nameInput.placeholder = 'Nombre del Equipo';
                selectIcon('⚙️');
            }
        }

        function selectIcon(icon) {
            document.getElementById('selectedIcon').value = icon;
            // Actualizar visualmente los botones de icono
            document.querySelectorAll('#iconSelector .icon-option').forEach(btn => {
                btn.classList.toggle('active', btn.getAttribute('data-icon') === icon);
            });
        }

        function selectEditIcon(icon, btn) {
            document.getElementById('editSelectedIcon').value = icon;
            // Actualizar visualmente los botones de icono
            document.querySelectorAll('#editIconPicker .icon-option').forEach(b => {
                b.classList.remove('active');
            });
            btn.classList.add('active');
        }

        function openEditShipModal(ship) {
            document.getElementById('editOldShipId').value = ship.ship_id;
            document.getElementById('editShipId').value = ship.ship_id;
            document.getElementById('editShipName').value = ship.name;
            document.getElementById('editShipType').value = ship.type || 'buque';
            document.getElementById('editSelectedIcon').value = ship.icon || '🚢';

            // Resaltar icono actual
            const buttons = document.querySelectorAll('#editIconPicker .icon-btn');
            buttons.forEach(btn => {
                btn.classList.toggle('active', btn.textContent === (ship.icon || '🚢'));
            });

            document.getElementById('editShipModal').style.display = 'flex';
        }

        async function updateShip() {
            const oldId = document.getElementById('editOldShipId').value;
            const newId = document.getElementById('editShipId').value.trim();
            const name = document.getElementById('editShipName').value.trim();
            const type = document.getElementById('editShipType').value;
            const icon = document.getElementById('editSelectedIcon').value;

            console.log('--- Iniciando Update de Buque ---');
            console.log('ID Original:', oldId);
            console.log('Nuevo ID:', newId);
            console.log('Nombre:', name);
            console.log('Tipo:', type);
            console.log('Icono:', icon);

            if (!newId || !name) {
                alert('⚠️ Complete todos los campos');
                return;
            }

            const confirmBtn = document.querySelector('#editShipModal .btn-primary');
            const originalText = confirmBtn.textContent;
            confirmBtn.disabled = true;
            confirmBtn.textContent = 'Guardando...';

            try {
                const res = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'update_ship',
                        old_id: oldId,
                        new_id: newId,
                        name: name,
                        type: type,
                        icon: icon
                    })
                });

                if (!res.ok) throw new Error(`HTTP Error: ${res.status}`);
                
                const data = await res.json();
                console.log('Respuesta del servidor:', data);

                if (data.success) {
                    confirmBtn.textContent = '✅ ¡Guardado!';
                    setTimeout(() => location.reload(), 800);
                } else {
                    alert('❌ Error: ' + (data.message || 'Error al actualizar el buque'));
                    confirmBtn.disabled = false;
                    confirmBtn.textContent = originalText;
                }
            } catch (e) {
                console.error('Error en fetch:', e);
                alert('❌ Error de conexión: ' + e.message);
                confirmBtn.disabled = false;
                confirmBtn.textContent = originalText;
            }
        }

        async function deleteUserCompletely() {
            const userId = document.getElementById('deleteUserCompletelyId').value;
            const password = document.getElementById('deleteUserAdminPass').value.trim();

            if (!password) {
                alert('Ingresa tu contraseña de administrador');
                return;
            }

            try {
                const res = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'delete_user_completely',
                        user_id: userId,
                        password: password
                    })
                });
                const data = await res.json();
                if (data.success) {
                    alert('Usuario eliminado permanentemente');
                    location.reload();
                } else {
                    alert(data.message || 'Error al eliminar usuario');
                }
            } catch (e) {
                alert('Error de conexión');
            }
        }

        function openDeleteUserCompletelyModal(userId, username) {
            document.getElementById('deleteUserCompletelyId').value = userId;
            document.getElementById('deleteUserCompletelyInfo').textContent = `¿Estás seguro de que deseas eliminar permanentemente al usuario "${username}"? Esta acción borrará al usuario de la base de datos y todas sus asignaciones.`;
            document.getElementById('deleteUserCompletelyModal').style.display = 'flex';
            document.getElementById('deleteUserAdminPass').value = '';
        }

        function openAssignModal(shipId, shipName) {
            document.getElementById('assignShipId').value = shipId;
            document.getElementById('assignModalTitle').textContent = `👤 Asignar Administrador - ${shipName}`;
            document.getElementById('assignModal').style.display = 'flex';
            document.getElementById('adminUser').value = '';
            document.getElementById('adminPass').value = '';
            document.getElementById('searchUserInput').value = '';
            document.getElementById('searchUsersResults').innerHTML = '<p style="color: #8892b0; text-align: center; margin: 20px 0;">Escribe para buscar usuarios...</p>';
            selectedUserId = null;
            switchAssignTab('search'); // Resetear a la pestaña de búsqueda
        }

        function openAssignUserShipModal(userId, username) {
            document.getElementById('assignUserId').value = userId;
            document.getElementById('assignUserInfo').textContent = `Usuario: ${username}`;
            document.getElementById('assignUserShipModal').style.display = 'flex';
            document.getElementById('assignShipSelect').value = '';
        }

        function openDeleteShipModal(shipId, shipName) {
            document.getElementById('deleteShipId').value = shipId;
            document.getElementById('deleteShipInfo').textContent = `¿Estás seguro de que deseas eliminar el buque "${shipName}" (${shipId})? Esta acción eliminará permanentemente el buque y todos sus datos asociados.`;
            document.getElementById('deleteShipModal').style.display = 'flex';
            document.getElementById('deleteShipPassword').value = '';
        }

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        function showCompanyModal(data) {
            const content = document.getElementById('companyDetailsContent');
            const link = document.getElementById('goToTempLink');

            content.innerHTML = `
                <div style="background: rgba(0, 242, 255, 0.05); border-radius: 12px; padding: 20px; border: 1px solid rgba(0, 242, 255, 0.1);">
                    <div style="margin-bottom: 12px;">
                        <span style="color: #8892b0; font-size: 13px;">Nombre / Razón Social:</span>
                        <div style="color: #00f2ff; font-weight: 600; font-size: 16px;">${data.legal_name || 'No definida'}</div>
                    </div>
                    <div style="margin-bottom: 12px;">
                        <span style="color: #8892b0; font-size: 13px;">Dirección:</span>
                        <div style="color: #fff;">${data.address || 'No definida'}</div>
                    </div>
                    <div style="margin-bottom: 12px; display: flex; gap: 20px;">
                        <div style="flex: 1;">
                            <span style="color: #8892b0; font-size: 13px;">Responsable:</span>
                            <div style="color: #fff;">${data.responsible || 'No definido'}</div>
                        </div>
                        <div style="flex: 1;">
                            <span style="color: #8892b0; font-size: 13px;">CUIT:</span>
                            <div style="color: #fff;">${data.cuit || 'No definido'}</div>
                        </div>
                    </div>
                    <div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid rgba(0, 242, 255, 0.1);">
                        <span style="color: #8892b0; font-size: 13px;">Administrador de Buque:</span>
                        <div style="color: #00f2ff; font-weight: 600;">${data.admin || 'Sin asignar'}</div>
                    </div>
                </div>
            `;

            link.innerHTML = 'Ver historial de temperaturas 🌡️';
            link.href = `ver_datos.php?buque_id=${encodeURIComponent(data.ship_id)}`;

            document.getElementById('companyModal').style.display = 'flex';
        }

        async function createShip() {
            const shipId = document.getElementById('newShipId').value.trim();
            const name = document.getElementById('newShipName').value.trim();
            const type = document.getElementById('newShipType').value;
            const icon = document.getElementById('selectedIcon').value;

            const sensors = document.getElementById('newShipSensors').value || 14;

            if (!shipId || !name) {
                alert('Complete todos los campos');
                return;
            }

            try {
                const res = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'create_ship',
                        ship_id: shipId,
                        name: name,
                        type: type,
                        icon: icon,
                        sensors: parseInt(sensors, 10)
                    })
                });
                const data = await res.json();
                if (data.success) {
                    location.reload();
                } else {
                    alert(data.message || 'Error al crear el buque');
                }
            } catch (e) {
                alert('Error de conexión');
            }
        }

        async function createShipAdmin() {
            const shipId = document.getElementById('assignShipId').value;
            const user = document.getElementById('adminUser').value.trim();
            const pass = document.getElementById('adminPass').value.trim();

            const legalName = document.getElementById('legalName').value.trim();
            const address = document.getElementById('companyAddress').value.trim();
            const responsible = document.getElementById('responsibleName').value.trim();
            const cuit = document.getElementById('companyCuit').value.trim();

            if (!user || !pass) {
                alert('Complete los campos de usuario y contraseña');
                return;
            }

            try {
                const res = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'create_ship_admin',
                        ship_id: shipId,
                        username: user,
                        password: pass,
                        legal_name: legalName,
                        address: address,
                        responsible_name: responsible,
                        cuit: cuit
                    })
                });
                const data = await res.json();
                if (data.success) {
                    alert('Administrador y datos de empresa creados con éxito');
                    closeModal('assignModal');
                    location.reload();
                } else {
                    alert(data.message || 'Error al crear el administrador');
                }
            } catch (e) {
                alert('Error de conexión');
            }
        }

        async function assignExistingUserAsAdmin() {
            const errorDiv = document.getElementById('assignSearchError');
            const showError = (msg, isSuccess = false) => {
                if (errorDiv) {
                    errorDiv.style.display = 'block';
                    errorDiv.style.color = isSuccess ? '#00ff88' : '#ff4d4d';
                    errorDiv.textContent = msg;
                } else {
                    alert(msg);
                }
            };

            try {
                const shipId = document.getElementById('assignShipId').value;

                if (!selectedUserId) {
                    showError('Por favor, busca y selecciona un usuario de la lista de resultados primero.');
                    return;
                }

                const res = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'assign_existing_user_as_admin',
                        ship_id: shipId,
                        user_id: selectedUserId
                    })
                });

                if (!res.ok) {
                    throw new Error(`Error HTTP: ${res.status}`);
                }

                const data = await res.json();
                if (data.success) {
                    showError('Usuario asignado como administrador con éxito. Actualizando...', true);
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showError(data.message || 'Error al asignar el usuario');
                }
            } catch (e) {
                showError('Error de conexión o de red: ' + e.message);
                console.error(e);
            }
        }

        async function confirmAssignShip() {
            const userId = document.getElementById('assignUserId').value;
            const shipId = document.getElementById('assignShipSelect').value;
            if (!shipId) {
                alert('Seleccione un buque');
                return;
            }

            try {
                const res = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ action: 'assign_ship_user', user_id: userId, ship_id: shipId })
                });
                const data = await res.json();
                if (data.success) {
                    alert('Buque asignado correctamente');
                    location.reload();
                } else {
                    alert(data.message || 'Error al asignar el buque');
                }
            } catch (e) {
                alert('Error de conexión');
            }
        }

        async function updateStatus(userId, status) {
            const action = status === 'active' ? 'APROBAR' : status === 'rejected' ? 'RECHAZAR' : 'REVOCAR';
            if (!confirm(`¿Confirmar ${action} este usuario?`)) return;

            try {
                const response = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ action: 'update_status', userId, status })
                });
                const result = await response.json();

                if (result.success) {
                    location.reload();
                } else {
                    alert('Error: ' + (result.message || 'Desconocido'));
                }
            } catch (error) {
                alert('Error de conexión');
            }
        }

        async function confirmDeleteShip() {
            const shipId = document.getElementById('deleteShipId').value;
            const password = document.getElementById('deleteShipPassword').value.trim();

            if (!password) {
                alert('Por favor ingresa tu contraseña para confirmar');
                return;
            }

            const modal = document.getElementById('deleteShipModal');
            const confirmBtn = modal.querySelector('.btn-danger');
            const originalText = confirmBtn.textContent;

            confirmBtn.disabled = true;
            confirmBtn.textContent = 'Eliminando...';

            try {
                const response = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'delete_ship',
                        ship_id: shipId,
                        password: password
                    })
                });
                const result = await response.json();

                if (result.success) {
                    // Buscar el card del buque y eliminarlo dinámicamente
                    const shipCards = document.querySelectorAll('.ship-card');
                    let foundCard = null;
                    shipCards.forEach(card => {
                        const idText = card.querySelector('.ship-card-id')?.textContent || '';
                        if (idText.includes(shipId)) {
                            foundCard = card;
                        }
                    });

                    if (foundCard) {
                        foundCard.style.opacity = '0';
                        foundCard.style.transform = 'scale(0.9)';
                        foundCard.style.transition = 'all 0.4s ease';
                        setTimeout(() => {
                            const parentGrid = foundCard.parentElement;
                            foundCard.remove();

                            // Si el grid queda vacío, podemos manejar la sección entera del cliente
                            if (parentGrid && parentGrid.querySelectorAll('.ship-card').length === 0) {
                                const clientContainer = parentGrid.closest('.client-container');
                                if (clientContainer) {
                                    clientContainer.style.opacity = '0';
                                    setTimeout(() => clientContainer.remove(), 400);
                                }
                            }
                        }, 400);
                    }
                    modal.style.display = 'none';
                    document.getElementById('deleteShipPassword').value = '';
                } else {
                    alert('Error: ' + (result.message || 'No se pudo eliminar el buque'));
                }
            } catch (error) {
                console.error('Error deleting ship:', error);
                alert('Error de conexión');
            } finally {
                confirmBtn.disabled = false;
                confirmBtn.textContent = originalText;
            }
        }

        function openChangePasswordModal(userId, username) {
            document.getElementById('changePasswordUserId').value = userId;
            document.getElementById('changePasswordInfo').textContent = `Cambiar contraseña del usuario: ${username}`;
            document.getElementById('changePasswordModal').style.display = 'flex';
            document.getElementById('adminPasswordConfirm').value = '';
            document.getElementById('newUserPassword').value = '';
        }

        function openRemoveAdminModal(userId, username, shipName) {
            document.getElementById('removeAdminUserId').value = userId;
            document.getElementById('removeAdminInfo').textContent = `Usuario: ${username} | Buque: ${shipName}`;
            document.getElementById('removeAdminModal').style.display = 'flex';
            document.getElementById('removeAdminPassword').value = '';
        }

        async function confirmRemoveAdmin() {
            const userId = document.getElementById('removeAdminUserId').value;
            const password = document.getElementById('removeAdminPassword').value.trim();

            if (!password) {
                alert('Por favor ingresa tu contraseña de administrador');
                return;
            }

            try {
                const response = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'remove_admin_role',
                        user_id: userId,
                        admin_password: password
                    })
                });
                const result = await response.json();

                if (result.success) {
                    alert('Rol de administrador removido correctamente. El usuario ahora es usuario común.');
                    closeModal('removeAdminModal');
                    location.reload();
                } else {
                    alert('Error: ' + (result.message || 'No se pudo remover el rol de administrador'));
                }
            } catch (error) {
                alert('Error de conexión');
            }
        }

        function openDeleteUserModal(userId, username, shipName) {
            document.getElementById('deleteUserId').value = userId;
            document.getElementById('deleteUserInfo').textContent = `¿Estás seguro de que deseas eliminar al usuario "${username}" del buque "${shipName}"?`;
            document.getElementById('deleteUserModal').style.display = 'flex';
            document.getElementById('deleteUserPassword').value = '';
        }

        function openChangeShipModal(userId, username, currentShipIds) {
            document.getElementById('changeShipUserId').value = userId;
            document.getElementById('changeShipInfo').textContent = `Gestionar buques para: ${username}`;

            // Clear all checkboxes first
            const checkboxes = document.querySelectorAll('.ship-checkbox');
            checkboxes.forEach(cb => cb.checked = false);

            // If currentShipIds is a string/comma-separated, split it
            const assignedIds = (typeof currentShipIds === 'string') ? currentShipIds.split(',') : (Array.isArray(currentShipIds) ? currentShipIds : []);

            checkboxes.forEach(cb => {
                if (assignedIds.includes(cb.value)) {
                    cb.checked = true;
                }
            });

            document.getElementById('changeShipModal').style.display = 'flex';
        }

        async function confirmChangeShip() {
            const userId = document.getElementById('changeShipUserId').value;
            const checkboxes = document.querySelectorAll('.ship-checkbox:checked');
            const selectedShipIds = Array.from(checkboxes).map(cb => cb.value);

            if (selectedShipIds.length === 0) {
                if (!confirm('Este usuario quedará sin ningún buque asignado. ¿Continuar?')) {
                    return;
                }
            }

            try {
                const response = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'sync_user_ships',
                        user_id: userId,
                        ship_ids: selectedShipIds
                    })
                });
                const result = await response.json();

                if (result.success) {
                    alert('Asignación de buques actualizada correctamente');
                    location.reload();
                } else {
                    alert('Error: ' + (result.message || 'No se pudo actualizar la asignación'));
                }
            } catch (error) {
                alert('Error de conexión');
            }
        }

        async function confirmChangePassword() {
            const userId = document.getElementById('changePasswordUserId').value;
            const adminPassword = document.getElementById('adminPasswordConfirm').value.trim();
            const newPassword = document.getElementById('newUserPassword').value.trim();

            if (!adminPassword || !newPassword) {
                alert('Por favor completa todos los campos');
                return;
            }

            if (newPassword.length < 6) {
                alert('La nueva contraseña debe tener al menos 6 caracteres');
                return;
            }

            try {
                const response = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'change_user_password',
                        user_id: userId,
                        admin_password: adminPassword,
                        new_password: newPassword
                    })
                });
                const result = await response.json();

                if (result.success) {
                    alert('Contraseña cambiada correctamente');
                    closeModal('changePasswordModal');
                } else {
                    alert('Error: ' + (result.message || 'No se pudo cambiar la contraseña'));
                }
            } catch (error) {
                alert('Error de conexión');
            }
        }

        async function confirmDeleteUser() {
            const userId = document.getElementById('deleteUserId').value;
            const password = document.getElementById('deleteUserPassword').value.trim();

            if (!password) {
                alert('Por favor ingresa tu contraseña de administrador');
                return;
            }

            try {
                const response = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'delete_user_from_ship',
                        user_id: userId,
                        password: password
                    })
                });
                const result = await response.json();

                if (result.success) {
                    alert('Usuario eliminado del buque correctamente');
                    location.reload();
                } else {
                    alert('Error: ' + (result.message || 'No se pudo eliminar el usuario'));
                }
            } catch (error) {
                alert('Error de conexión');
            }
        }

        function filterUsersTable() {
            const searchInput = document.getElementById('userSearchInput');
            if (!searchInput) return;

            const searchTerm = searchInput.value.toLowerCase().trim();
            const rows = document.querySelectorAll('#usersTableBody .user-row');
            const noResults = document.getElementById('noUsersFound');
            const table = document.getElementById('usersTable');

            if (!rows.length || !table) return;

            let visibleCount = 0;

            rows.forEach(row => {
                const shipData = (row.getAttribute('data-ship') || '').toLowerCase();
                const username = (row.getAttribute('data-username') || '').toLowerCase();
                const role = (row.getAttribute('data-role') || '').toLowerCase();

                const matches =
                    shipData.includes(searchTerm) ||
                    username.includes(searchTerm) ||
                    role.includes(searchTerm);

                if (matches || searchTerm === '') {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            });

            // Mostrar/ocultar mensaje de no resultados
            if (visibleCount === 0 && searchTerm !== '') {
                if (noResults) noResults.style.display = 'block';
                table.style.display = 'none';
            } else {
                if (noResults) noResults.style.display = 'none';
                table.style.display = 'table';
            }
        }

        let selectedUserId = null;

        function switchAssignTab(tab) {
            const searchPanel = document.getElementById('searchUserPanel');
            const createPanel = document.getElementById('createUserPanel');
            const searchTab = document.getElementById('tabSearchUser');
            const createTab = document.getElementById('tabCreateUser');
            const actionButton = document.getElementById('assignActionButton');

            if (tab === 'search') {
                searchPanel.style.display = 'block';
                createPanel.style.display = 'none';
                searchTab.style.background = 'rgba(0, 242, 255, 0.1)';
                searchTab.style.borderBottom = '2px solid #00f2ff';
                searchTab.style.color = '#00f2ff';
                createTab.style.background = 'transparent';
                createTab.style.borderBottom = '2px solid transparent';
                createTab.style.color = '#8892b0';
                actionButton.textContent = 'Asignar Usuario';
                actionButton.onclick = () => assignExistingUserAsAdmin();
            } else {
                searchPanel.style.display = 'none';
                createPanel.style.display = 'block';
                createTab.style.background = 'rgba(0, 242, 255, 0.1)';
                createTab.style.borderBottom = '2px solid #00f2ff';
                createTab.style.color = '#00f2ff';
                searchTab.style.background = 'transparent';
                searchTab.style.borderBottom = '2px solid transparent';
                searchTab.style.color = '#8892b0';
                actionButton.textContent = 'Crear Admin';
                actionButton.onclick = () => createShipAdmin();
            }
        }

        async function searchUsersForAdmin() {
            const searchTerm = document.getElementById('searchUserInput').value.trim();
            const resultsDiv = document.getElementById('searchUsersResults');
            const shipId = document.getElementById('assignShipId').value;

            if (searchTerm.length < 2) {
                resultsDiv.innerHTML = '<p style="color: #8892b0; text-align: center; margin: 20px 0;">Escribe al menos 2 caracteres para buscar...</p>';
                selectedUserId = null;
                return;
            }

            try {
                const response = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'search_users',
                        search_term: searchTerm,
                        ship_id: shipId
                    })
                });
                const result = await response.json();

                if (result.success && result.users && result.users.length > 0) {
                    let html = '';
                    result.users.forEach(user => {
                        const isCurrentAdmin = user.role === 'sub-adm' && user.ship_id === shipId;
                        const isOtherAdmin = user.role === 'sub-adm' && user.ship_id !== shipId && user.ship_id !== null;
                        html += `
                            <div class="user-search-result" 
                                 onclick="selectUserForAdmin(this, ${user.id}, this.getAttribute('data-username'), ${isCurrentAdmin ? 'true' : 'false'}, ${isOtherAdmin ? 'true' : 'false'})"
                                 data-username="${user.username.replace(/"/g, '&quot;')}"
                                 style="padding: 12px; margin-bottom: 8px; border: 1px solid rgba(0, 242, 255, 0.1); border-radius: 8px; cursor: pointer; transition: all 0.2s; background: rgba(0, 242, 255, 0.05);">
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div>
                                        <strong style="color: #00f2ff;">${user.username}</strong>
                                        <span style="color: #8892b0; font-size: 12px; margin-left: 8px;">(${user.role === 'user' ? 'Usuario' : 'Admin asignado'})</span>
                                        ${user.ship_id ? `<div style="color: #8892b0; font-size: 11px; margin-top: 4px;">Buque: ${user.ship_id}</div>` : ''}
                                    </div>
                                    ${isCurrentAdmin ? '<span style="color: #00ff88; font-size: 12px;">✓ Ya es admin</span>' : ''}
                                    ${isOtherAdmin ? '<span style="color: #ff4d4d; font-size: 12px;">⚠ Admin de otro buque</span>' : ''}
                                </div>
                            </div>
                        `;
                    });
                    resultsDiv.innerHTML = html;
                } else {
                    resultsDiv.innerHTML = '<p style="color: #8892b0; text-align: center; margin: 20px 0;">No se encontraron usuarios</p>';
                    selectedUserId = null;
                }
            } catch (error) {
                resultsDiv.innerHTML = '<p style="color: #ff4d4d; text-align: center; margin: 20px 0;">Error al buscar usuarios</p>';
                selectedUserId = null;
            }
        }

        function selectUserForAdmin(el, userId, username, isCurrentAdmin, isOtherAdmin) {
            const errorDiv = document.getElementById('assignSearchError');
            if (errorDiv) {
                errorDiv.style.display = 'none';
                errorDiv.textContent = '';
            }

            if (isCurrentAdmin) {
                if (errorDiv) {
                    errorDiv.style.display = 'block';
                    errorDiv.style.color = '#ff4d4d';
                    errorDiv.textContent = 'El usuario ya es administrador de este buque.';
                }
                return;
            }

            if (isOtherAdmin) {
                if (errorDiv) {
                    errorDiv.style.display = 'block';
                    errorDiv.style.color = '#ffb84d';
                    errorDiv.textContent = 'Aviso: Seleccionaste un usuario que ya es admin de otro buque. Pulsa "Asignar Usuario" para confirmarlo en este buque también.';
                }
            }

            selectedUserId = userId;
            const results = document.querySelectorAll('.user-search-result');
            results.forEach(r => {
                r.style.border = '1px solid rgba(0, 242, 255, 0.1)';
                r.style.background = 'rgba(0, 242, 255, 0.05)';
            });

            if (el && el.style) {
                el.style.border = '2px solid #00f2ff';
                el.style.background = 'rgba(0, 242, 255, 0.15)';
            }
        }

        function toggleSensorConfigs(shipId) {
            console.log('Toggling sensors for ship:', shipId);
            // Cerrar todos los demás desplegables primero
            const allConfigDivs = document.querySelectorAll('[id^="sensorConfigs_"]');
            const allIcons = document.querySelectorAll('[id^="toggleIcon_"]');

            allConfigDivs.forEach(div => {
                if (div.id !== 'sensorConfigs_' + shipId) {
                    div.style.display = 'none';
                }
            });

            allIcons.forEach(icon => {
                if (icon.id !== 'toggleIcon_' + shipId) {
                    icon.textContent = '▼';
                }
            });

            // Toggle del card específico
            const configDiv = document.getElementById('sensorConfigs_' + shipId);
            const icon = document.getElementById('toggleIcon_' + shipId);

            if (!configDiv || !icon) return;

            if (configDiv.style.display === 'none' || configDiv.style.display === '') {
                configDiv.style.display = 'block';
                icon.textContent = '▲';
                // Actualizar hash sin recargar para persistencia si el usuario refresca manualmente
                history.pushState(null, null, '#sensors_' + shipId);
            } else {
                configDiv.style.display = 'none';
                icon.textContent = '▼';
                // Limpiar hash si se cierra
                if (window.location.hash === '#sensors_' + shipId) {
                    history.pushState(null, null, window.location.pathname + window.location.search);
                }
            }
        }

        async function saveSensorConfigs(shipId) {
            const container = document.getElementById(`sensorConfigs_${shipId}`);
            if (!container) return;

            const items = container.querySelectorAll('.sensor-config-item');
            const configs = [];

            items.forEach(item => {
                const sensorId = item.dataset.sensorId;
                const label = item.querySelector('.sensor-label-input').value;
                const maxTemp = item.querySelector('.sensor-max-temp').value;
                const minTemp = item.querySelector('.sensor-min-temp').value;

                configs.push({
                    sensor_id: parseInt(sensorId),
                    sensor_label: label,
                    max_temp: parseFloat(maxTemp),
                    min_temp: parseFloat(minTemp)
                });
            });

            // Find and disable save button to prevent double clicks
            const saveBtn = event?.target?.closest('button') || container.querySelector('.btn-primary');
            const originalText = saveBtn ? saveBtn.textContent : '';
            if (saveBtn) {
                saveBtn.disabled = true;
                saveBtn.textContent = 'Guardando...';
            }

            try {
                const response = await fetch('api/sensor_temperature_config.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        ship_id: shipId,
                        configs: configs
                    })
                });

                const data = await response.json();
                if (data.success) {
                    // Feedback visual sin recargar
                    if (saveBtn) {
                        saveBtn.style.background = '#28a745';
                        saveBtn.textContent = '✅ Guardado';
                        setTimeout(() => {
                            saveBtn.disabled = false;
                            saveBtn.style.background = '';
                            saveBtn.textContent = originalText;
                        }, 2000);
                    }
                } else {
                    alert('Error al guardar: ' + (data.message || 'Error desconocido'));
                    if (saveBtn) {
                        saveBtn.disabled = false;
                        saveBtn.textContent = originalText;
                    }
                }
            } catch (error) {
                console.error('Error saving configs:', error);
                alert('Error de conexión al guardar la configuración.');
                if (saveBtn) {
                    saveBtn.disabled = false;
                    saveBtn.textContent = originalText;
                }
            }
        }

        function openDeleteSensorModal(shipId, sensorId) {
            document.getElementById('deleteSensorShipId').value = shipId;
            document.getElementById('deleteSensorId').value = sensorId;
            document.getElementById('deleteSensorInfo').innerHTML = `¿Estás seguro de que deseas eliminar permanentemente el <strong>Sensor #${sensorId}</strong>?`;
            document.getElementById('deleteSensorModal').style.display = 'flex';
        }

        async function confirmDeleteSensor() {
            const shipId = document.getElementById('deleteSensorShipId').value;
            const sensorId = document.getElementById('deleteSensorId').value;

            console.log('Confirmando eliminación de sensor:', sensorId, 'para buque:', shipId);

            const modal = document.getElementById('deleteSensorModal');
            const confirmBtn = modal.querySelector('.btn-danger');
            const originalText = confirmBtn.textContent;

            confirmBtn.disabled = true;
            confirmBtn.textContent = 'Eliminando...';

            try {
                const response = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'delete_sensor_config',
                        ship_id: shipId,
                        sensor_id: parseInt(sensorId, 10)
                    })
                });

                const data = await response.json();
                console.log('Respuesta eliminación:', data);
                if (data.success) {
                    // Buscar el elemento en el DOM y eliminarlo dinámicamente
                    const container = document.getElementById(`sensorConfigs_${shipId}`);
                    if (container) {
                        const sensorItem = container.querySelector(`.sensor-config-item[data-sensor-id="${sensorId}"]`);
                        if (sensorItem) {
                            sensorItem.style.opacity = '0';
                            sensorItem.style.transform = 'translateX(20px)';
                            sensorItem.style.transition = 'all 0.3s ease';
                            setTimeout(() => {
                                sensorItem.remove();
                                // Si no quedan sensores, mostrar mensaje de vacío
                                if (container.querySelectorAll('.sensor-config-item').length === 0) {
                                    const emptyMsg = document.createElement('div');
                                    emptyMsg.style.cssText = "color: #8892b0; font-size: 12px; text-align: center; padding: 8px;";
                                    emptyMsg.textContent = "No hay sensores configurados";
                                    container.prepend(emptyMsg);
                                }
                            }, 300);
                        }
                    }
                    modal.style.display = 'none';
                } else {
                    alert('Error al eliminar: ' + (data.message || 'Error desconocido'));
                }
            } catch (error) {
                console.error('Error al borrar sensor:', error);
                alert('Error de conexión al eliminar.');
            } finally {
                confirmBtn.disabled = false;
                confirmBtn.textContent = originalText;
            }
        }

        async function addSensor(shipId) {
            console.log('Agregando nuevo sensor para buque:', shipId);

            const btn = event?.target;
            if (btn) {
                btn.disabled = true;
                btn.textContent = '+ Agregando...';
            }

            try {
                const response = await fetch('api/admin_actions.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'add_sensor_config',
                        ship_id: shipId
                    })
                });

                const data = await response.json();
                console.log('Respuesta agregado:', data);
                if (data.success) {
                    // En lugar de recargar, obtenemos el nuevo ID y lo agregamos al DOM
                    // Nota: el backend debería devolvernos el ID asignado, pero si no, podemos inferirlo 
                    // o forzar una pequeña actualización parcial. Por ahora, si no tenemos el ID,
                    // buscaremos el MAX actual en el DOM y sumaremos 1, o recargaremos si es necesario.
                    // Para mayor precisión, el backend add_sensor_config ahora debería retornar el nuevo ID.

                    const nextId = data.new_sensor_id || (document.querySelectorAll(`#sensorConfigs_${shipId} .sensor-config-item`).length + 1);

                    const container = document.getElementById(`sensorConfigs_${shipId}`);
                    if (container) {
                        // Quitar el mensaje de "No hay sensores" si existe
                        const emptyMsg = Array.from(container.childNodes).find(node => node.textContent === "No hay sensores configurados");
                        if (emptyMsg) emptyMsg.remove();

                        const buttonsDiv = container.querySelector('div[style*="margin-top: 12px; display: flex;"]');
                        const newSensorHtml = createSensorConfigElement(shipId, nextId, `SENSOR #${nextId}`, 27.0, -40.0);

                        const tempDiv = document.createElement('div');
                        tempDiv.innerHTML = newSensorHtml;
                        const newNode = tempDiv.firstElementChild;
                        newNode.style.opacity = '0';
                        newNode.style.transform = 'translateY(-10px)';

                        container.insertBefore(newNode, buttonsDiv);

                        // Animación de entrada
                        setTimeout(() => {
                            newNode.style.transition = 'all 0.4s ease';
                            newNode.style.opacity = '1';
                            newNode.style.transform = 'translateY(0)';
                        }, 10);
                    }
                } else {
                    alert('Error al agregar sensor: ' + (data.message || 'Error desconocido'));
                }
            } catch (error) {
                console.error('Error al agregar sensor:', error);
                alert('Error de conexión al agregar sensor.');
            } finally {
                if (btn) {
                    btn.disabled = false;
                    btn.textContent = '+ Agregar Sensor';
                }
            }
        }

        function createSensorConfigElement(shipId, sensorId, label, maxTemp, minTemp) {
            return `
                <div class="sensor-config-item" data-sensor-id="${sensorId}"
                    style="margin-bottom: 8px; padding: 8px; background: rgba(0, 242, 255, 0.05); border-radius: 4px;">
                    <div style="color: #00f2ff; font-weight: 600; font-size: 13px; margin-bottom: 6px; display: flex; gap: 8px; justify-content: space-between; align-items: center;">
                        <input type="text" class="sensor-label-input" value="${label}"
                            style="background: transparent; border: 1px solid rgba(0,242,255,0.2); color: #fff; border-radius: 4px; padding: 2px 6px; width: 100%; font-size: 13px; flex: 1; min-width: 0;">
                        <button class="btn-danger btn-compact"
                            onclick="openDeleteSensorModal('${shipId}', ${sensorId})"
                            style="padding: 2px 8px; font-size: 12px; flex-shrink: 0;">✕</button>
                    </div>
                    <div style="display: flex; justify-content: space-between; gap: 10px; font-size: 12px; color: #8892b0;">
                        <div style="flex:1;">
                            Máx (°C):
                            <input type="number" step="0.1" class="sensor-max-temp modal-input" value="${maxTemp}"
                                style="padding: 4px 8px; min-height: unset; margin-top:2px; font-size: 12px; width: 100%; box-sizing: border-box;">
                        </div>
                        <div style="flex:1;">
                            Mín (°C):
                            <input type="number" step="0.1" class="sensor-min-temp modal-input" value="${minTemp}"
                                style="padding: 4px 8px; min-height: unset; margin-top:2px; font-size: 12px; width: 100%; box-sizing: border-box;">
                        </div>
                    </div>
                </div>
            `;
        }


        // Manejar persistencia de filtros y secciones abiertas al cargar
        document.addEventListener('DOMContentLoaded', function () {
            // Verificar si hay un hash de sensores en la URL
            const hash = window.location.hash;
            if (hash && hash.startsWith('#sensors_')) {
                const shipId = hash.replace('#sensors_', '');
                console.log('Abriendo sensores por hash para:', shipId);
                // Dar un pequeño timeout para asegurar que el DOM está listo
                setTimeout(() => {
                    toggleSensorConfigs(shipId);
                    // Hacer scroll suave hasta el card si es necesario
                    const configDiv = document.getElementById('sensorConfigs_' + shipId);
                    if (configDiv) {
                        configDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }
                }, 300);
            }
        });
    </script>
</body>

</html>