{% extends "base.html" %}

{% block title %}Clusters - AtlasUI{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <!-- Breadcrumb -->
        <nav aria-label="breadcrumb" class="mb-2">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="/organizations">Organizations</a></li>
                <li class="breadcrumb-item"><span id="orgNameBreadcrumb">...</span></li>
                <li class="breadcrumb-item active" aria-current="page"><span id="projectNameBreadcrumb">...</span></li>
            </ol>
        </nav>

        <div class="d-flex justify-content-between align-items-center mb-2">
            <h1><i class="bi bi-hdd-rack"></i> Clusters</h1>
            <div>
                <button class="btn btn-success btn-sm me-2" id="createClusterBtn">
                    <i class="bi bi-plus-circle"></i> Create Cluster
                </button>
                <button class="btn btn-outline-success btn-sm" id="refreshBtn">
                    <i class="bi bi-arrow-clockwise"></i> Refresh
                </button>
            </div>
        </div>

        <script>
            const PROJECT_ID_OR_NAME = "{{ project_id_or_name }}";
            let RESOLVED_PROJECT_ID = null;  // Will be set after resolving project name/ID
        </script>

        <!-- Loading indicator -->
        <div id="loadingIndicator" class="text-center my-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">Loading clusters...</p>
        </div>

        <!-- Error message -->
        <div id="errorMessage" class="alert alert-danger d-none" role="alert">
            <i class="bi bi-exclamation-triangle"></i>
            <span id="errorText"></span>
        </div>

        <!-- Clusters table -->
        <div id="clustersTable" class="d-none">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Status</th>
                            <th>Type</th>
                            <th>MongoDB</th>
                            <th>Provider</th>
                            <th>Region</th>
                            <th>Instance</th>
                            <th>Users</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="clustersContainer">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Login Modal -->
<div class="modal fade" id="loginModal" tabindex="-1" aria-labelledby="loginModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="loginModalLabel">
                    <i class="bi bi-key"></i> Login to Cluster
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="loginError" class="alert alert-danger d-none"></div>
                <div id="loginSuccess" class="alert alert-success d-none"></div>

                <form id="loginForm">
                    <input type="hidden" id="clusterConnectionString" />
                    <input type="hidden" id="clusterName" />

                    <div class="mb-3">
                        <label for="username" class="form-label">Username</label>
                        <input type="text" class="form-control" id="username" required autocomplete="username">
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">Password</label>
                        <input type="password" class="form-control" id="password" required autocomplete="current-password">
                    </div>
                </form>

                <!-- Databases list (shown after successful login) -->
                <div id="databasesList" class="d-none mt-3">
                    <h6>Databases:</h6>
                    <div class="table-responsive">
                        <table class="table table-sm table-striped">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Collections</th>
                                    <th>Indexes</th>
                                    <th>Size</th>
                                </tr>
                            </thead>
                            <tbody id="databasesTableBody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="loginBtn">
                    <i class="bi bi-box-arrow-in-right"></i> Login
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addUserModalLabel">
                    <i class="bi bi-person-plus"></i> Add Database User
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="addUserError" class="alert alert-danger d-none"></div>
                <div id="addUserSuccess" class="alert alert-success d-none"></div>

                <form id="addUserForm">
                    <input type="hidden" id="addUserProjectId" />

                    <div class="mb-3">
                        <label for="newUsername" class="form-label">Username <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="newUsername" required>
                        <div class="form-text">Database username for authentication</div>
                    </div>
                    <div class="mb-3">
                        <label for="newPassword" class="form-label">Password <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" id="newPassword" required>
                        <div class="form-text">Must be at least 8 characters</div>
                    </div>
                    <div class="mb-3">
                        <label for="userRole" class="form-label">Role <span class="text-danger">*</span></label>
                        <select class="form-select" id="userRole" required>
                            <option value="">Select a role...</option>
                            <option value="readWrite">Read and Write (readWrite)</option>
                            <option value="read">Read Only (read)</option>
                            <option value="dbAdmin">Database Admin (dbAdmin)</option>
                            <option value="atlasAdmin">Atlas Admin (atlasAdmin)</option>
                        </select>
                        <div class="form-text">User permissions on the database</div>
                    </div>
                    <div class="mb-3">
                        <label for="targetDatabase" class="form-label">Target Database</label>
                        <input type="text" class="form-control" id="targetDatabase" value="admin">
                        <div class="form-text">Database where the role applies (default: admin)</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="addUserBtn">
                    <i class="bi bi-person-plus"></i> Add User
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Details Panel (Offcanvas) -->
<div class="offcanvas offcanvas-end offcanvas-wide" tabindex="-1" id="detailsPanel" aria-labelledby="detailsPanelLabel">
    <div class="offcanvas-header border-bottom">
        <h5 class="offcanvas-title" id="detailsPanelLabel">
            <i class="bi bi-info-circle"></i> Cluster Details
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>
    <div class="offcanvas-body">
        <div id="detailsContent">
            <p class="text-muted">Click on a cluster name to view its details</p>
        </div>
    </div>
</div>

<!-- Logout Confirmation Modal -->
<div class="modal fade" id="logoutModal" tabindex="-1" aria-labelledby="logoutModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="logoutModalLabel">
                    <i class="bi bi-box-arrow-right"></i> Confirm Logout
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>You will be logged out from cluster:</p>
                <p class="text-center"><strong id="logoutClusterName"></strong></p>
                <p class="text-muted small">Your session will be closed and you will need to login again to access this cluster's databases.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmLogoutBtn">
                    <i class="bi bi-box-arrow-right"></i> Logout
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Create Cluster Modal -->
<div class="modal fade" id="createClusterModal" tabindex="-1" aria-labelledby="createClusterModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createClusterModalLabel">
                    <i class="bi bi-plus-circle"></i> Create New Cluster
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="createClusterError" class="alert alert-danger d-none"></div>
                <div id="createClusterSuccess" class="alert alert-success d-none"></div>

                <form id="createClusterForm">
                    <input type="hidden" id="createClusterProjectId" />

                    <div class="mb-3">
                        <label for="clusterNameInput" class="form-label">Cluster Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="clusterNameInput" required
                               placeholder="e.g., my-cluster">
                        <div class="form-text">Must be unique within the project. Lowercase alphanumeric and hyphens only.</div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="providerName" class="form-label">Cloud Provider <span class="text-danger">*</span></label>
                                <select class="form-select" id="providerName" required>
                                    <option value="">Select provider...</option>
                                    <option value="AWS">Amazon Web Services (AWS)</option>
                                    <option value="GCP">Google Cloud Platform (GCP)</option>
                                    <option value="AZURE">Microsoft Azure</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="regionName" class="form-label">Region <span class="text-danger">*</span></label>
                                <select class="form-select" id="regionName" required>
                                    <option value="">Select region...</option>
                                    <option value="US_EAST_1">US East (N. Virginia)</option>
                                    <option value="US_WEST_2">US West (Oregon)</option>
                                    <option value="EU_WEST_1">EU (Ireland)</option>
                                    <option value="EU_CENTRAL_1">EU (Frankfurt)</option>
                                    <option value="AP_SOUTHEAST_1">Asia Pacific (Singapore)</option>
                                </select>
                                <div class="form-text">Region availability depends on provider</div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="instanceSize" class="form-label">Instance Size <span class="text-danger">*</span></label>
                                <select class="form-select" id="instanceSize" required>
                                    <option value="">Select size...</option>
                                    <optgroup label="Free Tier">
                                        <option value="M0">M0 - Free (512MB storage, shared CPU)</option>
                                    </optgroup>
                                    <optgroup label="Flex (Shared Tier)">
                                        <option value="FLEX">Flex - Pay-per-use (auto-scaling shared infrastructure)</option>
                                    </optgroup>
                                    <optgroup label="Dedicated Clusters">
                                        <option value="M10">M10 - 2GB RAM</option>
                                        <option value="M20">M20 - 4GB RAM</option>
                                        <option value="M30">M30 - 8GB RAM</option>
                                        <option value="M40">M40 - 16GB RAM</option>
                                        <option value="M50">M50 - 32GB RAM</option>
                                        <option value="M60">M60 - 64GB RAM</option>
                                        <option value="M80">M80 - 128GB RAM</option>
                                        <option value="M140">M140 - 192GB RAM</option>
                                        <option value="M200">M200 - 256GB RAM</option>
                                        <option value="M300">M300 - 384GB RAM</option>
                                    </optgroup>
                                </select>
                                <div class="form-text">M0 is free tier. Flex auto-scales on shared infrastructure. M10+ are dedicated clusters with fixed resources.</div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="mongoDBVersion" class="form-label">MongoDB Version</label>
                                <select class="form-select" id="mongoDBVersion">
                                    <option value="">Latest version</option>
                                    <option value="8.0">8.0</option>
                                    <option value="7.0">7.0</option>
                                    <option value="6.0">6.0</option>
                                    <option value="5.0">5.0</option>
                                </select>
                                <div class="form-text">Leave blank for latest stable version</div>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="clusterType" class="form-label">Cluster Type <span class="text-danger">*</span></label>
                        <select class="form-select" id="clusterType" required>
                            <option value="REPLICASET">Replica Set (Recommended)</option>
                            <option value="SHARDED">Sharded Cluster</option>
                        </select>
                        <div class="form-text">Replica Set is recommended for most use cases</div>
                    </div>

                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="enableBackup">
                        <label class="form-check-label" for="enableBackup">
                            Enable Cloud Backup (Recommended)
                        </label>
                    </div>

                    <div class="alert alert-info small">
                        <i class="bi bi-info-circle"></i>
                        <strong>Note:</strong> Creating a cluster may take several minutes. M0 (Free Tier) clusters have usage limitations.
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="submitCreateClusterBtn">
                    <i class="bi bi-plus-circle"></i> Create Cluster
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Delete Cluster Confirmation Modal -->
<div class="modal fade" id="deleteClusterModal" tabindex="-1" aria-labelledby="deleteClusterModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteClusterModalLabel">
                    <i class="bi bi-exclamation-triangle-fill"></i> Confirm Cluster Deletion
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- Confirmation Form -->
                <div id="deleteClusterForm">
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <strong>Warning:</strong> This action cannot be undone!
                    </div>
                    <p>You are about to permanently delete the cluster:</p>
                    <p class="text-center"><strong id="deleteClusterName"></strong></p>
                    <p class="text-danger"><strong>All data in this cluster will be lost permanently.</strong></p>
                    <p class="text-muted small">Please ensure you have backups of any important data before proceeding.</p>

                    <div class="mb-3 mt-3">
                        <label for="confirmClusterName" class="form-label">
                            Type the cluster name to confirm deletion:
                        </label>
                        <input type="text" class="form-control" id="confirmClusterName"
                               placeholder="Enter cluster name">
                    </div>

                    <div id="deleteClusterError" class="alert alert-danger d-none mt-3"></div>
                </div>

                <!-- Deletion Progress -->
                <div id="deleteClusterProgress" class="d-none">
                    <div class="text-center mb-3">
                        <div class="spinner-border text-danger mb-3" role="status" style="width: 3rem; height: 3rem;">
                            <span class="visually-hidden">Deleting...</span>
                        </div>
                        <h5 class="text-danger">Deleting Cluster</h5>
                        <p id="deleteClusterProgressText">Initiating cluster deletion...</p>
                    </div>

                    <div class="mb-3">
                        <span id="deleteClusterStatus" class="badge bg-warning text-dark fs-6 py-2 px-3">
                            <i class="bi bi-hourglass-split"></i> DELETING
                        </span>
                    </div>

                    <div class="progress mb-3" style="height: 25px;">
                        <div id="deleteClusterProgressBar" class="progress-bar progress-bar-striped progress-bar-animated bg-danger"
                             role="progressbar" style="width: 10%">
                            <span class="fw-bold">Deleting...</span>
                        </div>
                    </div>

                    <div class="text-muted small">
                        <p id="deleteStep1" class="mb-1"><i class="bi bi-circle"></i> Shutting down cluster</p>
                        <p id="deleteStep2" class="mb-1"><i class="bi bi-circle"></i> Removing resources</p>
                        <p id="deleteStep3" class="mb-1"><i class="bi bi-circle"></i> Finalizing deletion</p>
                    </div>
                </div>

                <!-- Deletion Success -->
                <div id="deleteClusterSuccess" class="alert alert-success d-none mt-3">
                    <div class="text-center">
                        <i class="bi bi-check-circle-fill text-success" style="font-size: 3rem;"></i>
                        <h5 class="mt-2">Cluster Deleted Successfully</h5>
                        <p>The cluster has been permanently removed.</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer" id="deleteClusterFooter">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="cancelDeleteBtn">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteClusterBtn" disabled>
                    <i class="bi bi-trash"></i> Delete Cluster
                </button>
            </div>
            <div class="modal-footer d-none" id="deleteClusterCompleteFooter">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<style>
    h1 {
        font-size: 1.25rem;
    }

    .offcanvas-wide {
        width: 600px !important;
        max-width: 90vw;
    }

    .cluster-name-link {
        cursor: pointer;
        color: #00684a;
        text-decoration: none;
    }

    .cluster-name-link:hover {
        text-decoration: underline;
    }

    /* Cluster creation animations */
    .cluster-creation-animation {
        display: flex;
        justify-content: center;
        gap: 10px;
    }

    @keyframes pulse {
        0%, 100% {
            transform: scale(1);
            opacity: 1;
        }
        50% {
            transform: scale(1.1);
            opacity: 0.8;
        }
    }

    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .pulse-icon {
        animation: pulse 2s ease-in-out infinite;
        display: inline-block;
    }

    .spinning-gear {
        animation: spin 2s linear infinite;
        display: inline-block;
    }

    .fade-in {
        animation: fadeIn 0.5s ease-in;
    }
</style>

<script>
let clusters = [];

document.addEventListener('DOMContentLoaded', function() {
    loadClusters();
    document.getElementById('refreshBtn').addEventListener('click', loadClusters);
});

async function loadClusters() {
    const loading = document.getElementById('loadingIndicator');
    const error = document.getElementById('errorMessage');
    const table = document.getElementById('clustersTable');

    loading.classList.remove('d-none');
    error.classList.add('d-none');
    table.classList.add('d-none');

    try {
        // Fetch all organizations
        const orgsResponse = await fetch('/api/organizations/');
        if (!orgsResponse.ok) throw new Error('Failed to fetch organizations');
        const orgsData = await orgsResponse.json();

        // Find the project by ID or name across all organizations
        let targetProject = null;
        let targetOrg = null;

        for (let org of orgsData.results || []) {
            const projectsResponse = await fetch(`/api/organizations/${org.id}/projects?itemsPerPage=500`);
            if (projectsResponse.ok) {
                const projectsData = await projectsResponse.json();
                const project = (projectsData.results || []).find(p =>
                    p.id === PROJECT_ID_OR_NAME || p.name === PROJECT_ID_OR_NAME
                );
                if (project) {
                    targetProject = project;
                    targetOrg = org;
                    break;
                }
            }
        }

        if (!targetProject) {
            throw new Error(`Project "${PROJECT_ID_OR_NAME}" not found`);
        }

        // Store the resolved project ID for use in other functions
        RESOLVED_PROJECT_ID = targetProject.id;

        // Update breadcrumbs
        document.getElementById('orgNameBreadcrumb').innerHTML =
            `<a href="/organizations/${encodeURIComponent(targetOrg.name)}/projects">${targetOrg.name}</a>`;
        document.getElementById('projectNameBreadcrumb').textContent = targetProject.name;

        // Fetch both regular clusters AND Flex clusters
        const clustersResponse = await fetch(`/api/clusters/${targetProject.id}?itemsPerPage=500`);
        if (!clustersResponse.ok) throw new Error('Failed to fetch clusters');
        const clustersData = await clustersResponse.json();

        // Fetch Flex clusters (separate endpoint as of Jan 2025)
        let flexClustersData = { results: [] };
        try {
            const flexResponse = await fetch(`/api/clusters/${targetProject.id}/flex/list?itemsPerPage=500`);
            if (flexResponse.ok) {
                flexClustersData = await flexResponse.json();
                console.log(`Found ${(flexClustersData.results || []).length} Flex clusters`);
            }
        } catch (err) {
            console.warn('Failed to fetch Flex clusters:', err);
        }

        // Combine regular and Flex clusters
        const allClusters = [
            ...(clustersData.results || []),
            ...(flexClustersData.results || [])
        ];

        console.log(`Total clusters: ${allClusters.length} (${(clustersData.results || []).length} regular + ${(flexClustersData.results || []).length} Flex)`);

        // Fetch users for this project
        let projectUsers = [];
        try {
            const usersResponse = await fetch(`/api/users/${targetProject.id}`);
            if (usersResponse.ok) {
                const usersData = await usersResponse.json();
                projectUsers = usersData.results || [];
            }
        } catch (err) {
            console.warn(`Failed to fetch users for project ${targetProject.id}:`, err);
        }

        // Add project name and users to each cluster
        clusters = allClusters.map(c => ({
            ...c,
            projectName: targetProject.name,
            projectId: targetProject.id,
            users: projectUsers
        }));

        renderClusters();
        loading.classList.add('d-none');
        table.classList.remove('d-none');

    } catch (err) {
        console.error('Error loading clusters:', err);
        loading.classList.add('d-none');
        error.classList.remove('d-none');
        document.getElementById('errorText').textContent = err.message;
    }
}

function renderClusters() {
    const container = document.getElementById('clustersContainer');
    container.innerHTML = '';

    if (clusters.length === 0) {
        container.innerHTML = '<tr><td colspan="9" class="text-center"><div class="alert alert-info mb-0">No clusters found</div></td></tr>';
        return;
    }

    clusters.forEach(cluster => {
        const row = document.createElement('tr');
        const statusClass = getStatusBadgeClass(cluster.stateName);
        const users = cluster.users || [];

        row.innerHTML = `
            <td>
                <a href="javascript:void(0)" class="cluster-name-link" onclick="showClusterDetails('${cluster.id || cluster.name}')">
                    <strong>${cluster.name}</strong>
                </a>
            </td>
            <td><span class="badge ${statusClass}">${cluster.stateName || 'UNKNOWN'}</span></td>
            <td>
                <a href="/clusters/${encodeURIComponent(cluster.name)}/databases" class="text-decoration-none">
                    ${cluster.clusterType || 'N/A'}
                </a>
            </td>
            <td>${cluster.mongoDBVersion || 'N/A'}</td>
            <td>${cluster.providerSettings?.providerName || 'N/A'}</td>
            <td>${cluster.providerSettings?.regionName || 'N/A'}</td>
            <td>${cluster.providerSettings?.instanceSizeName || 'N/A'}</td>
            <td><span class="badge bg-secondary">${users.length}</span></td>
            <td>
                <button class="btn btn-sm btn-outline-primary cluster-login-btn me-1"
                        data-cluster="${cluster.name}"
                        onclick="handleClusterAction('${cluster.name}')">
                    <i class="bi bi-box-arrow-in-right"></i> Login
                </button>
                <button class="btn btn-sm btn-outline-danger"
                        onclick="showDeleteClusterConfirmation('${cluster.name}', '${cluster.projectId}', '${cluster.providerSettings?.providerName || ''}', '${cluster.providerSettings?.instanceSizeName || ''}')">
                    <i class="bi bi-trash"></i> Delete
                </button>
            </td>
        `;
        container.appendChild(row);
    });
}

function formatConnectionString(connectionString) {
    // Insert username:password@ placeholder after the protocol (mongodb:// or mongodb+srv://)
    if (!connectionString) return connectionString;

    // Match mongodb:// or mongodb+srv://
    const match = connectionString.match(/^(mongodb(?:\+srv)?:\/\/)(.*)/);
    if (match) {
        return `${match[1]}<strong>username:password@</strong>${match[2]}`;
    }
    return connectionString;
}

function getStatusBadgeClass(status) {
    switch (status) {
        case 'IDLE':
            return 'bg-success';
        case 'CREATING':
        case 'UPDATING':
            return 'bg-warning';
        case 'DELETING':
        case 'DELETED':
            return 'bg-danger';
        case 'REPAIRING':
            return 'bg-info';
        default:
            return 'bg-secondary';
    }
}

async function showClusterDetails(clusterId) {
    // Find cluster in the clusters array
    const cluster = clusters.find(c => (c.id === clusterId || c.name === clusterId));
    if (!cluster) return;

    const detailsContent = document.getElementById('detailsContent');
    const statusClass = getStatusBadgeClass(cluster.stateName);
    const users = cluster.users || [];

    // Show loading state
    detailsContent.innerHTML = `
        <div class="text-center my-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">Loading cluster details...</p>
        </div>
    `;

    // Open the offcanvas immediately
    const offcanvas = new bootstrap.Offcanvas(document.getElementById('detailsPanel'));
    offcanvas.show();

    try {
        // Fetch additional data in parallel
        const [alertsData, snapshotsData, advancedConfigData] = await Promise.all([
            fetch(`/api/alerts/${cluster.projectId}`).then(r => r.ok ? r.json() : { results: [] }).catch(() => ({ results: [] })),
            fetch(`/api/backups/${cluster.projectId}/${cluster.name}/snapshots`).then(r => r.ok ? r.json() : { results: [] }).catch(() => ({ results: [] })),
            fetch(`/api/clusters/${cluster.projectId}/${cluster.name}/advanced-configuration`).then(r => r.ok ? r.json() : {}).catch(() => ({}))
        ]);

        const alerts = (alertsData.results || []).filter(alert => alert.clusterName === cluster.name);
        const snapshots = snapshotsData.results || [];
        const advancedConfig = advancedConfigData;

    // Build comprehensive details HTML
    let html = `
        <h5 class="mb-3">
            <i class="bi bi-hdd-rack"></i> ${cluster.name}
        </h5>

        <div class="mb-3">
            <span class="badge ${statusClass}">${cluster.stateName || 'UNKNOWN'}</span>
            ${cluster.paused ? '<span class="badge bg-warning text-dark ms-1">PAUSED</span>' : ''}
            ${alerts.length > 0 ? `<span class="badge bg-danger ms-1">${alerts.length} Alert${alerts.length > 1 ? 's' : ''}</span>` : ''}
        </div>

        <div class="mb-3">
            <h6 class="text-muted">Basic Information</h6>
            <table class="table table-sm">
                <tbody>
                    <tr><th width="40%">Name</th><td>${cluster.name}</td></tr>
                    ${cluster.id ? `<tr><th>ID</th><td><code class="small">${cluster.id}</code></td></tr>` : ''}
                    ${cluster.groupId ? `<tr><th>Group ID</th><td><code class="small">${cluster.groupId}</code></td></tr>` : ''}
                    <tr><th>Status</th><td><span class="badge ${statusClass}">${cluster.stateName || 'UNKNOWN'}</span></td></tr>
                    <tr><th>Cluster Type</th><td>${cluster.clusterType || 'N/A'}</td></tr>
                    <tr><th>MongoDB Version</th><td>${cluster.mongoDBVersion || 'N/A'}</td></tr>
                    ${cluster.mongoDBMajorVersion ? `<tr><th>Major Version</th><td>${cluster.mongoDBMajorVersion}</td></tr>` : ''}
                    ${cluster.createDate ? `<tr><th>Created</th><td>${new Date(cluster.createDate).toLocaleString()}</td></tr>` : ''}
                    ${cluster.replicationFactor ? `<tr><th>Replication Factor</th><td>${cluster.replicationFactor}</td></tr>` : ''}
                    ${cluster.numShards ? `<tr><th>Number of Shards</th><td>${cluster.numShards}</td></tr>` : ''}
                    ${cluster.diskSizeGB ? `<tr><th>Disk Size</th><td>${cluster.diskSizeGB} GB</td></tr>` : ''}
                    ${cluster.paused !== undefined ? `<tr><th>Paused</th><td><span class="badge ${cluster.paused ? 'bg-warning' : 'bg-success'}">${cluster.paused ? 'Yes' : 'No'}</span></td></tr>` : ''}
                    ${cluster.backupEnabled !== undefined ? `<tr><th>Backup Enabled</th><td><span class="badge ${cluster.backupEnabled ? 'bg-success' : 'bg-secondary'}">${cluster.backupEnabled ? 'Yes' : 'No'}</span></td></tr>` : ''}
                    ${cluster.providerBackupEnabled !== undefined ? `<tr><th>Provider Backup</th><td><span class="badge ${cluster.providerBackupEnabled ? 'bg-success' : 'bg-secondary'}">${cluster.providerBackupEnabled ? 'Yes' : 'No'}</span></td></tr>` : ''}
                    ${cluster.pitEnabled !== undefined ? `<tr><th>Point-in-Time Restore</th><td><span class="badge ${cluster.pitEnabled ? 'bg-success' : 'bg-secondary'}">${cluster.pitEnabled ? 'Enabled' : 'Disabled'}</span></td></tr>` : ''}
                    ${snapshots.length > 0 ? `<tr><th>Snapshots</th><td><span class="badge bg-info">${snapshots.length}</span></td></tr>` : ''}
                    ${cluster.encryptionAtRestProvider ? `<tr><th>Encryption Provider</th><td>${cluster.encryptionAtRestProvider}</td></tr>` : ''}
                    ${cluster.versionReleaseSystem ? `<tr><th>Version Release System</th><td>${cluster.versionReleaseSystem}</td></tr>` : ''}
                    ${cluster.rootCertType ? `<tr><th>Root Cert Type</th><td>${cluster.rootCertType}</td></tr>` : ''}
                </tbody>
            </table>
        </div>
    `;

    // Provider settings
    if (cluster.providerSettings) {
        html += `
            <div class="mb-3">
                <h6 class="text-muted">Provider Settings</h6>
                <table class="table table-sm">
                    <tbody>
                        ${cluster.providerSettings.providerName ? `<tr><th width="40%">Provider</th><td>${cluster.providerSettings.providerName}</td></tr>` : ''}
                        ${cluster.providerSettings.regionName ? `<tr><th>Region</th><td>${cluster.providerSettings.regionName}</td></tr>` : ''}
                        ${cluster.providerSettings.instanceSizeName ? `<tr><th>Instance Size</th><td>${cluster.providerSettings.instanceSizeName}</td></tr>` : ''}
                        ${cluster.providerSettings.backingProviderName ? `<tr><th>Backing Provider</th><td>${cluster.providerSettings.backingProviderName}</td></tr>` : ''}
                        ${cluster.providerSettings.diskIOPS ? `<tr><th>Disk IOPS</th><td>${cluster.providerSettings.diskIOPS}</td></tr>` : ''}
                        ${cluster.providerSettings.encryptEBSVolume !== undefined ? `<tr><th>Encrypted EBS</th><td><span class="badge ${cluster.providerSettings.encryptEBSVolume ? 'bg-success' : 'bg-secondary'}">${cluster.providerSettings.encryptEBSVolume ? 'Yes' : 'No'}</span></td></tr>` : ''}
                        ${cluster.providerSettings.volumeType ? `<tr><th>Volume Type</th><td>${cluster.providerSettings.volumeType}</td></tr>` : ''}
                    </tbody>
                </table>
            </div>
        `;
    }

    // Auto-scaling settings
    if (cluster.autoScaling || (cluster.providerSettings && cluster.providerSettings.autoScaling)) {
        const autoScaling = cluster.autoScaling || cluster.providerSettings.autoScaling;
        html += `
            <div class="mb-3">
                <h6 class="text-muted">Auto-Scaling</h6>
                <table class="table table-sm">
                    <tbody>
                        ${autoScaling.compute ? `
                            <tr><th width="40%">Compute Enabled</th><td><span class="badge ${autoScaling.compute.enabled ? 'bg-success' : 'bg-secondary'}">${autoScaling.compute.enabled ? 'Yes' : 'No'}</span></td></tr>
                            ${autoScaling.compute.scaleDownEnabled !== undefined ? `<tr><th>Scale Down</th><td><span class="badge ${autoScaling.compute.scaleDownEnabled ? 'bg-success' : 'bg-secondary'}">${autoScaling.compute.scaleDownEnabled ? 'Enabled' : 'Disabled'}</span></td></tr>` : ''}
                            ${autoScaling.compute.minInstanceSize ? `<tr><th>Min Instance</th><td>${autoScaling.compute.minInstanceSize}</td></tr>` : ''}
                            ${autoScaling.compute.maxInstanceSize ? `<tr><th>Max Instance</th><td>${autoScaling.compute.maxInstanceSize}</td></tr>` : ''}
                        ` : ''}
                        ${autoScaling.diskGBEnabled !== undefined ? `<tr><th>Disk Auto-Scaling</th><td><span class="badge ${autoScaling.diskGBEnabled ? 'bg-success' : 'bg-secondary'}">${autoScaling.diskGBEnabled ? 'Enabled' : 'Disabled'}</span></td></tr>` : ''}
                    </tbody>
                </table>
            </div>
        `;
    }

    // Replication specs
    if (cluster.replicationSpecs && cluster.replicationSpecs.length > 0) {
        html += `
            <div class="mb-3">
                <h6 class="text-muted">Replication Specs</h6>
        `;
        cluster.replicationSpecs.forEach((spec, idx) => {
            html += `
                <div class="mb-2">
                    <strong>Region ${idx + 1}: ${spec.zoneName || 'N/A'}</strong>
                    <table class="table table-sm table-bordered mt-1">
                        <tbody>
                            ${spec.numShards ? `<tr><th width="40%">Shards</th><td>${spec.numShards}</td></tr>` : ''}
                            ${spec.regionsConfig ? Object.keys(spec.regionsConfig).map(region => `
                                <tr><th>${region}</th><td>
                                    Priority: ${spec.regionsConfig[region].priority || 0},
                                    Nodes: ${spec.regionsConfig[region].electableNodes || 0} electable,
                                    ${spec.regionsConfig[region].readOnlyNodes || 0} read-only,
                                    ${spec.regionsConfig[region].analyticsNodes || 0} analytics
                                </td></tr>
                            `).join('') : ''}
                        </tbody>
                    </table>
                </div>
            `;
        });
        html += `</div>`;
    }

    // Advanced configuration
    if (advancedConfig && Object.keys(advancedConfig).length > 0) {
        const configKeys = Object.keys(advancedConfig).filter(k => !k.startsWith('_') && k !== 'links');
        if (configKeys.length > 0) {
            html += `
                <div class="mb-3">
                    <h6 class="text-muted">Advanced Configuration</h6>
                    <table class="table table-sm">
                        <tbody>
                            ${configKeys.slice(0, 10).map(key => `
                                <tr><th width="40%">${key}</th><td><code class="small">${JSON.stringify(advancedConfig[key])}</code></td></tr>
                            `).join('')}
                            ${configKeys.length > 10 ? `<tr><td colspan="2" class="small text-muted text-center">...and ${configKeys.length - 10} more settings</td></tr>` : ''}
                        </tbody>
                    </table>
                </div>
            `;
        }
    }

    // Bi-Connector
    if (cluster.biConnector) {
        html += `
            <div class="mb-3">
                <h6 class="text-muted">BI Connector</h6>
                <table class="table table-sm">
                    <tbody>
                        ${cluster.biConnector.enabled !== undefined ? `<tr><th>Enabled</th><td>${cluster.biConnector.enabled ? 'Yes' : 'No'}</td></tr>` : ''}
                        ${cluster.biConnector.readPreference ? `<tr><th>Read Preference</th><td>${cluster.biConnector.readPreference}</td></tr>` : ''}
                    </tbody>
                </table>
            </div>
        `;
    }

    // Labels/Tags
    if (cluster.labels && cluster.labels.length > 0) {
        html += `
            <div class="mb-3">
                <h6 class="text-muted">Labels</h6>
                ${cluster.labels.map(label =>
                    `<span class="badge bg-secondary me-1">${label.key}: ${label.value}</span>`
                ).join('')}
            </div>
        `;
    }

    if (cluster.tags && cluster.tags.length > 0) {
        html += `
            <div class="mb-3">
                <h6 class="text-muted">Tags</h6>
                ${cluster.tags.map(tag => `<span class="badge bg-secondary me-1">${tag}</span>`).join('')}
            </div>
        `;
    }

    // Connection strings
    if (cluster.connectionStrings) {
        html += `
            <div class="mb-3">
                <h6 class="text-muted">Connection Strings</h6>
                <div class="small">
        `;

        if (cluster.connectionStrings.standardSrv) {
            html += `
                <div class="mb-2">
                    <strong>Standard SRV:</strong><br>
                    <code class="small text-break">${formatConnectionString(cluster.connectionStrings.standardSrv)}</code>
                </div>
            `;
        }

        if (cluster.connectionStrings.standard) {
            html += `
                <div class="mb-2">
                    <strong>Standard:</strong><br>
                    <code class="small text-break">${formatConnectionString(cluster.connectionStrings.standard)}</code>
                </div>
            `;
        }

        if (cluster.connectionStrings.private) {
            html += `
                <div class="mb-2">
                    <strong>Private:</strong><br>
                    <code class="small text-break">${formatConnectionString(cluster.connectionStrings.private)}</code>
                </div>
            `;
        }

        if (cluster.connectionStrings.privateSrv) {
            html += `
                <div class="mb-2">
                    <strong>Private SRV:</strong><br>
                    <code class="small text-break">${formatConnectionString(cluster.connectionStrings.privateSrv)}</code>
                </div>
            `;
        }

        html += `</div></div>`;
    }

    // Snapshots/Backups
    if (snapshots.length > 0) {
        html += `
            <div class="mb-3">
                <h6 class="text-muted">Recent Snapshots (${snapshots.length})</h6>
                <div class="list-group list-group-flush">
                    ${snapshots.slice(0, 5).map(snapshot => `
                        <div class="list-group-item py-2 px-2">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <div class="d-flex align-items-center">
                                        <i class="bi bi-archive-fill text-info me-2"></i>
                                        <strong>${snapshot.id || 'Snapshot'}</strong>
                                    </div>
                                    <div class="small text-muted mt-1">
                                        ${snapshot.snapshotType ? `Type: ${snapshot.snapshotType}` : ''}
                                        ${snapshot.createdAt ? ` • Created: ${new Date(snapshot.createdAt).toLocaleString()}` : ''}
                                    </div>
                                    ${snapshot.storageSizeBytes ? `<div class="small">Size: ${formatBytes(snapshot.storageSizeBytes)}</div>` : ''}
                                    ${snapshot.description ? `<div class="small text-muted">${snapshot.description}</div>` : ''}
                                </div>
                                <span class="badge ${snapshot.status === 'completed' ? 'bg-success' : 'bg-secondary'} ms-2">${snapshot.status || 'N/A'}</span>
                            </div>
                        </div>
                    `).join('')}
                    ${snapshots.length > 5 ? `<div class="list-group-item small text-muted text-center">...and ${snapshots.length - 5} more snapshots</div>` : ''}
                </div>
            </div>
        `;
    }

    // Active Alerts
    if (alerts.length > 0) {
        html += `
            <div class="mb-3">
                <h6 class="text-muted">Active Alerts (${alerts.length})</h6>
                <div class="list-group list-group-flush">
                    ${alerts.slice(0, 5).map(alert => `
                        <div class="list-group-item py-2 px-2">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <div class="d-flex align-items-center">
                                        <i class="bi bi-exclamation-triangle-fill text-warning me-2"></i>
                                        <strong>${alert.typeName || alert.eventTypeName || 'Alert'}</strong>
                                    </div>
                                    <div class="small text-muted mt-1">
                                        ${alert.metricName ? `Metric: ${alert.metricName}` : ''}
                                    </div>
                                    ${alert.currentValue ? `<div class="small">Current: ${JSON.stringify(alert.currentValue)}</div>` : ''}
                                    <div class="small text-muted">
                                        ${alert.created ? new Date(alert.created).toLocaleString() : ''}
                                    </div>
                                </div>
                                <span class="badge ${alert.status === 'OPEN' ? 'bg-warning' : 'bg-secondary'} ms-2">${alert.status || 'OPEN'}</span>
                            </div>
                        </div>
                    `).join('')}
                    ${alerts.length > 5 ? `<div class="list-group-item small text-muted text-center">...and ${alerts.length - 5} more alerts</div>` : ''}
                </div>
            </div>
        `;
    }

    // Database users
    if (users.length > 0) {
        html += `
            <div class="mb-3">
                <h6 class="text-muted">Database Users (${users.length})</h6>
                <div class="table-responsive">
                    <table class="table table-sm table-bordered mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Username</th>
                                <th>Database</th>
                                <th>Roles</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${users.map(user => `
                                <tr>
                                    <td><strong>${user.username}</strong></td>
                                    <td><code class="small">${user.databaseName || 'admin'}</code></td>
                                    <td>
                                        ${user.roles && user.roles.length > 0 ?
                                            user.roles.map(role => `<span class="badge bg-secondary me-1">${role.roleName}</span>`).join('') :
                                            '<span class="text-muted">No roles</span>'
                                        }
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
    } else {
        html += `
            <div class="mb-3">
                <h6 class="text-muted">Database Users</h6>
                <p class="small text-muted">No database users in this project</p>
            </div>
        `;
    }

        detailsContent.innerHTML = html;

    } catch (err) {
        console.error('Error loading cluster details:', err);
        detailsContent.innerHTML = `
            <div class="alert alert-danger">
                <i class="bi bi-exclamation-triangle"></i>
                Failed to load cluster details: ${err.message}
            </div>
        `;
    }
}

function showLoginModal(connectionString, clusterName) {
    // Reset the form and hide messages
    document.getElementById('loginForm').reset();
    document.getElementById('loginError').classList.add('d-none');
    document.getElementById('loginSuccess').classList.add('d-none');
    document.getElementById('databasesList').classList.add('d-none');

    // Set the connection string and cluster name
    document.getElementById('clusterConnectionString').value = connectionString;
    document.getElementById('clusterName').value = clusterName;

    // Update modal title
    document.getElementById('loginModalLabel').innerHTML = `<i class="bi bi-key"></i> Login to ${clusterName}`;

    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('loginModal'));
    modal.show();
}

async function loginToCluster() {
    const loginBtn = document.getElementById('loginBtn');
    const loginError = document.getElementById('loginError');
    const loginSuccess = document.getElementById('loginSuccess');
    const databasesList = document.getElementById('databasesList');

    const connectionString = document.getElementById('clusterConnectionString').value;
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    if (!username || !password) {
        loginError.textContent = 'Please enter username and password';
        loginError.classList.remove('d-none');
        return;
    }

    // Hide previous messages
    loginError.classList.add('d-none');
    loginSuccess.classList.add('d-none');
    databasesList.classList.add('d-none');

    // Show loading state
    loginBtn.disabled = true;
    loginBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Connecting...';

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

        const data = await response.json();

        if (response.ok) {
            // Show success message
            loginSuccess.textContent = `Successfully connected! Found ${data.total} database(s)`;
            loginSuccess.classList.remove('d-none');

            // Populate databases table
            const tbody = document.getElementById('databasesTableBody');
            tbody.innerHTML = '';

            data.databases.forEach(db => {
                const row = document.createElement('tr');
                if (db.error) {
                    row.innerHTML = `
                        <td>${db.name}</td>
                        <td colspan="3" class="text-danger small">${db.error}</td>
                    `;
                } else {
                    row.innerHTML = `
                        <td><strong>${db.name}</strong></td>
                        <td>${db.collections || 0}</td>
                        <td>${db.indexes || 0}</td>
                        <td>${formatBytes(db.sizeOnDisk || 0)}</td>
                    `;
                }
                tbody.appendChild(row);
            });

            // Show databases list
            databasesList.classList.remove('d-none');

        } else {
            loginError.textContent = data.detail || 'Failed to connect to cluster';
            loginError.classList.remove('d-none');
        }

    } catch (err) {
        console.error('Login error:', err);
        loginError.textContent = 'Failed to connect to cluster: ' + err.message;
        loginError.classList.remove('d-none');
    } finally {
        // Reset button state
        loginBtn.disabled = false;
        loginBtn.innerHTML = '<i class="bi bi-box-arrow-in-right"></i> Login';
    }
}

function formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}

function showAddUserModal(projectId, projectName) {
    // Reset the form and hide messages
    document.getElementById('addUserForm').reset();
    document.getElementById('addUserError').classList.add('d-none');
    document.getElementById('addUserSuccess').classList.add('d-none');

    // Set the project ID
    document.getElementById('addUserProjectId').value = projectId;

    // Update modal title
    document.getElementById('addUserModalLabel').innerHTML =
        `<i class="bi bi-person-plus"></i> Add Database User to ${projectName}`;

    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('addUserModal'));
    modal.show();
}

async function addDatabaseUser() {
    const addUserBtn = document.getElementById('addUserBtn');
    const addUserError = document.getElementById('addUserError');
    const addUserSuccess = document.getElementById('addUserSuccess');

    const projectId = document.getElementById('addUserProjectId').value;
    const username = document.getElementById('newUsername').value;
    const password = document.getElementById('newPassword').value;
    const roleName = document.getElementById('userRole').value;
    const databaseName = document.getElementById('targetDatabase').value;

    if (!username || !password || !roleName) {
        addUserError.textContent = 'Please fill in all required fields';
        addUserError.classList.remove('d-none');
        return;
    }

    // Hide previous messages
    addUserError.classList.add('d-none');
    addUserSuccess.classList.add('d-none');

    // Show loading state
    addUserBtn.disabled = true;
    addUserBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Adding...';

    try {
        const response = await fetch(`/api/users/${projectId}/database-users`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: username,
                password: password,
                databaseName: databaseName,
                roles: [
                    {
                        roleName: roleName,
                        databaseName: databaseName
                    }
                ]
            })
        });

        const data = await response.json();

        if (response.ok) {
            // Show success message
            addUserSuccess.textContent = `User "${username}" added successfully!`;
            addUserSuccess.classList.remove('d-none');

            // Reload clusters after a short delay to show updated users
            setTimeout(() => {
                bootstrap.Modal.getInstance(document.getElementById('addUserModal')).hide();
                loadClusters();
            }, 1500);

        } else {
            addUserError.textContent = data.detail || 'Failed to add user';
            addUserError.classList.remove('d-none');
        }

    } catch (err) {
        console.error('Add user error:', err);
        addUserError.textContent = 'Failed to add user: ' + err.message;
        addUserError.classList.remove('d-none');
    } finally {
        // Reset button state
        addUserBtn.disabled = false;
        addUserBtn.innerHTML = '<i class="bi bi-person-plus"></i> Add User';
    }
}

// Handle cluster login/logout button action
let currentLogoutCluster = null;

function handleClusterAction(clusterName) {
    const button = document.querySelector(`button[data-cluster="${clusterName}"]`);
    const isLoggedIn = button.classList.contains('btn-outline-danger');

    if (isLoggedIn) {
        // Show logout confirmation
        showLogoutConfirmation(clusterName);
    } else {
        // Navigate to databases page for login
        window.location.href = `/clusters/${encodeURIComponent(clusterName)}/databases`;
    }
}

function showLogoutConfirmation(clusterName) {
    currentLogoutCluster = clusterName;
    document.getElementById('logoutClusterName').textContent = clusterName;

    const logoutModal = new bootstrap.Modal(document.getElementById('logoutModal'));
    logoutModal.show();
}

async function performLogout() {
    if (!currentLogoutCluster) return;

    const button = document.querySelector(`button[data-cluster="${currentLogoutCluster}"]`);

    try {
        // Call logout API
        const response = await fetch('/api/clusters/session/logout', {
            method: 'POST'
        });

        if (response.ok) {
            // Update button to login state
            button.classList.remove('btn-outline-danger');
            button.classList.add('btn-outline-primary');
            button.innerHTML = '<i class="bi bi-box-arrow-in-right"></i> Login';

            // Close modal
            bootstrap.Modal.getInstance(document.getElementById('logoutModal')).hide();

            // Show success message
            console.log(`Logged out from ${currentLogoutCluster}`);
        } else {
            console.error('Logout failed');
        }
    } catch (err) {
        console.error('Logout error:', err);
    }

    currentLogoutCluster = null;
}

async function checkSessionStatus() {
    try {
        const response = await fetch('/api/clusters/session/status');
        const data = await response.json();

        if (data.active && data.cluster_name) {
            // Update the button for the logged-in cluster
            const button = document.querySelector(`button[data-cluster="${data.cluster_name}"]`);
            if (button) {
                button.classList.remove('btn-outline-primary');
                button.classList.add('btn-outline-danger');
                button.innerHTML = '<i class="bi bi-box-arrow-right"></i> Logout';
            }
        }
    } catch (err) {
        console.log('No active session or error checking session');
    }
}

// Create Cluster functionality
function showCreateClusterModal() {
    // Use the resolved project ID (not the name)
    const projectId = RESOLVED_PROJECT_ID || PROJECT_ID_OR_NAME;

    if (!projectId) {
        alert('Unable to determine project ID. Please refresh the page.');
        return;
    }

    // Reset form and messages
    document.getElementById('createClusterForm').reset();
    document.getElementById('createClusterError').classList.add('d-none');
    document.getElementById('createClusterSuccess').classList.add('d-none');
    document.getElementById('createClusterProjectId').value = projectId;

    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('createClusterModal'));
    modal.show();
}

async function createCluster() {
    const submitBtn = document.getElementById('submitCreateClusterBtn');
    const errorDiv = document.getElementById('createClusterError');
    const successDiv = document.getElementById('createClusterSuccess');

    // Get form values
    const projectId = document.getElementById('createClusterProjectId').value;
    const clusterName = document.getElementById('clusterNameInput').value.trim();
    const providerName = document.getElementById('providerName').value;
    const regionName = document.getElementById('regionName').value;
    const instanceSize = document.getElementById('instanceSize').value;
    const mongoDBVersion = document.getElementById('mongoDBVersion').value;
    const clusterType = document.getElementById('clusterType').value;
    const enableBackup = document.getElementById('enableBackup').checked;

    // Validate
    if (!clusterName || !providerName || !regionName || !instanceSize || !clusterType) {
        errorDiv.textContent = 'Please fill in all required fields';
        errorDiv.classList.remove('d-none');
        return;
    }

    // Hide messages
    errorDiv.classList.add('d-none');
    successDiv.classList.add('d-none');

    // Disable button and show loading
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Creating...';

    try {
        // Build cluster configuration based on instance type
        let clusterConfig;

        if (instanceSize === 'FLEX') {
            // Flex cluster configuration (replaces Serverless)
            // Note: Flex clusters don't use clusterType field
            clusterConfig = {
                name: clusterName,
                providerSettings: {
                    providerName: "FLEX",  // FLEX provider for new Flex clusters
                    backingProviderName: providerName,  // AWS, GCP, or AZURE
                    regionName: regionName
                }
            };
        } else if (instanceSize === 'M0') {
            // Free tier cluster configuration
            clusterConfig = {
                name: clusterName,
                clusterType: clusterType,
                providerSettings: {
                    providerName: "TENANT",
                    backingProviderName: providerName,
                    regionName: regionName,
                    instanceSizeName: instanceSize
                }
            };
        } else {
            // Dedicated cluster configuration (M10+)
            clusterConfig = {
                name: clusterName,
                clusterType: clusterType,
                providerSettings: {
                    providerName: providerName,
                    regionName: regionName,
                    instanceSizeName: instanceSize
                }
            };

            // Add backup settings for dedicated clusters
            if (enableBackup) {
                clusterConfig.providerBackupEnabled = true;
            }
        }

        // Add MongoDB version if specified (not for Flex)
        if (mongoDBVersion && instanceSize !== 'FLEX') {
            clusterConfig.mongoDBMajorVersion = mongoDBVersion;
        }

        // Log the configuration being sent (for debugging)
        console.log('Creating cluster with config:', JSON.stringify(clusterConfig, null, 2));

        // Use different endpoint for Flex clusters (as of January 2025)
        const endpoint = instanceSize === 'FLEX'
            ? `/api/clusters/${projectId}/flex`
            : `/api/clusters/${projectId}`;

        console.log('Using endpoint:', endpoint);

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

        if (!response.ok) {
            let errorMessage = `Failed to create cluster (${response.status})`;
            try {
                const errorData = await response.json();
                console.error('Cluster creation error:', errorData);

                // Extract detailed error message
                if (errorData.detail) {
                    errorMessage = errorData.detail;
                } else if (errorData.error) {
                    errorMessage = errorData.error;
                } else if (errorData.message) {
                    errorMessage = errorData.message;
                }
            } catch (e) {
                console.error('Error parsing error response:', e);
            }
            throw new Error(errorMessage);
        }

        const newCluster = await response.json();
        console.log('Cluster creation response:', newCluster);
        console.log(`New cluster ${clusterName} initial state: ${newCluster.stateName || 'UNKNOWN'}`);

        // Hide the form and show success message with progress tracking
        document.getElementById('createClusterForm').style.display = 'none';
        errorDiv.classList.add('d-none');

        successDiv.innerHTML = `
            <div class="text-center">
                <div class="cluster-creation-animation mb-3">
                    <div class="spinner-grow text-success" style="width: 3rem; height: 3rem; animation-duration: 1s;" role="status">
                        <span class="visually-hidden">Creating...</span>
                    </div>
                    <div class="spinner-grow text-warning" style="width: 3rem; height: 3rem; animation-delay: 0.2s; animation-duration: 1s;" role="status">
                        <span class="visually-hidden">Creating...</span>
                    </div>
                    <div class="spinner-grow text-info" style="width: 3rem; height: 3rem; animation-delay: 0.4s; animation-duration: 1s;" role="status">
                        <span class="visually-hidden">Creating...</span>
                    </div>
                </div>

                <h5 class="mb-3">
                    <i class="bi bi-cloud-upload pulse-icon"></i>
                    Creating Cluster: <strong>${clusterName}</strong>
                </h5>

                <div class="mb-3">
                    <span class="badge bg-warning text-dark fs-6 py-2 px-3" id="clusterCreationStatus">
                        <i class="bi bi-gear-fill spinning-gear"></i> CREATING
                    </span>
                </div>

                <div class="progress mb-3" style="height: 20px;">
                    <div class="progress-bar progress-bar-striped progress-bar-animated bg-success"
                         role="progressbar"
                         id="clusterCreationProgress"
                         style="width: 10%">
                        <span class="fw-bold">Setting up...</span>
                    </div>
                </div>

                <div id="clusterStatusMessage" class="small text-muted fade-in">
                    <i class="bi bi-hourglass-split"></i>
                    Provisioning cloud resources... This typically takes 5-10 minutes.
                </div>

                <div class="mt-3 p-3 bg-light rounded">
                    <div class="small">
                        <div class="mb-1"><i class="bi bi-check-circle text-success"></i> Request submitted</div>
                        <div class="mb-1" id="step-provisioning"><i class="bi bi-circle text-muted"></i> Provisioning resources</div>
                        <div class="mb-1" id="step-configuring"><i class="bi bi-circle text-muted"></i> Configuring MongoDB</div>
                        <div id="step-ready"><i class="bi bi-circle text-muted"></i> Finalizing deployment</div>
                    </div>
                </div>
            </div>
        `;
        successDiv.classList.remove('d-none');

        // Start polling cluster status (pass instance size to know which endpoint to poll)
        pollClusterCreationStatus(projectId, clusterName, instanceSize);

    } catch (err) {
        console.error('Error creating cluster:', err);

        // Show the form again if it was hidden
        document.getElementById('createClusterForm').style.display = 'block';

        // Display error message
        errorDiv.textContent = err.message;
        errorDiv.classList.remove('d-none');

        // Hide success message if it was shown
        successDiv.classList.add('d-none');
    } finally {
        // Re-enable button
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="bi bi-plus-circle"></i> Create Cluster';
    }
}

// Poll cluster creation status
async function pollClusterCreationStatus(projectId, clusterName, instanceSize) {
    const maxAttempts = 60; // Poll for up to 10 minutes (60 * 10 seconds)
    let attempts = 0;

    const pollInterval = setInterval(async () => {
        attempts++;

        try {
            // Fetch cluster status from the correct endpoint
            // Flex clusters are in a separate endpoint
            const endpoint = instanceSize === 'FLEX'
                ? `/api/clusters/${projectId}/flex/list`
                : `/api/clusters/${projectId}`;

            console.log(`Polling cluster status from: ${endpoint}`);

            const response = await fetch(endpoint);
            if (!response.ok) {
                throw new Error('Failed to fetch cluster status');
            }

            const data = await response.json();
            console.log(`Polling response for ${clusterName}:`, data);

            const cluster = (data.results || []).find(c => c.name === clusterName);

            if (!cluster) {
                console.warn(`Cluster ${clusterName} not found in response. Stopping polling.`);
                clearInterval(pollInterval);
                return;
            }

            console.log(`Cluster ${clusterName} status: ${cluster.stateName}`);

            // Update progress bar based on time elapsed
            const progressBar = document.getElementById('clusterCreationProgress');
            const progressPercent = Math.min(10 + (attempts * 1.5), 95);
            if (progressBar) {
                progressBar.style.width = `${progressPercent}%`;

                // Update progress text based on percentage
                if (progressPercent < 30) {
                    progressBar.innerHTML = '<span class="fw-bold">Setting up...</span>';
                } else if (progressPercent < 60) {
                    progressBar.innerHTML = '<span class="fw-bold">Provisioning...</span>';
                } else if (progressPercent < 90) {
                    progressBar.innerHTML = '<span class="fw-bold">Configuring...</span>';
                } else {
                    progressBar.innerHTML = '<span class="fw-bold">Almost ready...</span>';
                }
            }

            // Animate step indicators
            if (attempts > 5) {
                const step1 = document.getElementById('step-provisioning');
                if (step1) step1.innerHTML = '<i class="bi bi-arrow-right-circle-fill text-primary"></i> Provisioning resources';
            }
            if (attempts > 15) {
                const step2 = document.getElementById('step-configuring');
                if (step2) step2.innerHTML = '<i class="bi bi-arrow-right-circle-fill text-primary"></i> Configuring MongoDB';
            }
            if (attempts > 30) {
                const step3 = document.getElementById('step-ready');
                if (step3) step3.innerHTML = '<i class="bi bi-arrow-right-circle-fill text-primary"></i> Finalizing deployment';
            }

            const statusBadge = document.getElementById('clusterCreationStatus');
            if (statusBadge) {
                // Update badge color and icon based on status
                statusBadge.className = 'badge fs-6 py-2 px-3';
                switch (cluster.stateName) {
                    case 'IDLE':
                        statusBadge.classList.add('bg-success');
                        statusBadge.innerHTML = '<i class="bi bi-check-circle-fill"></i> IDLE';
                        break;
                    case 'CREATING':
                    case 'UPDATING':
                        statusBadge.classList.add('bg-warning', 'text-dark');
                        statusBadge.innerHTML = '<i class="bi bi-gear-fill spinning-gear"></i> ' + cluster.stateName;
                        break;
                    case 'DELETING':
                    case 'DELETED':
                        statusBadge.classList.add('bg-danger');
                        statusBadge.innerHTML = '<i class="bi bi-x-circle-fill"></i> ' + cluster.stateName;
                        break;
                    default:
                        statusBadge.classList.add('bg-secondary');
                        statusBadge.innerHTML = '<i class="bi bi-question-circle-fill"></i> ' + (cluster.stateName || 'UNKNOWN');
                }
            }

            // Check if cluster is ready
            if (cluster.stateName === 'IDLE') {
                clearInterval(pollInterval);

                // Complete all steps
                document.getElementById('step-provisioning').innerHTML = '<i class="bi bi-check-circle-fill text-success"></i> Provisioning resources';
                document.getElementById('step-configuring').innerHTML = '<i class="bi bi-check-circle-fill text-success"></i> Configuring MongoDB';
                document.getElementById('step-ready').innerHTML = '<i class="bi bi-check-circle-fill text-success"></i> Finalizing deployment';

                // Update progress bar to 100%
                if (progressBar) {
                    progressBar.style.width = '100%';
                    progressBar.innerHTML = '<span class="fw-bold">Complete!</span>';
                    progressBar.classList.remove('bg-success');
                    progressBar.classList.add('bg-success');
                }

                // Update success message with celebration
                const successDiv = document.getElementById('createClusterSuccess');
                successDiv.innerHTML = `
                    <div class="text-center">
                        <div class="mb-3">
                            <i class="bi bi-check-circle-fill text-success" style="font-size: 4rem;"></i>
                        </div>
                        <h4 class="text-success mb-3">
                            <i class="bi bi-party-popper"></i>
                            Cluster Created Successfully!
                        </h4>
                        <p class="mb-3">
                            <strong>${clusterName}</strong> is now ready to use
                        </p>
                        <div class="mb-3">
                            <span class="badge bg-success fs-6 py-2 px-3">
                                <i class="bi bi-check-circle-fill"></i> IDLE
                            </span>
                        </div>
                        <div class="alert alert-success mb-0">
                            <i class="bi bi-info-circle"></i>
                            The cluster is fully operational and ready for connections.
                            <br>
                            <small class="text-muted">Refreshing cluster list...</small>
                        </div>
                    </div>
                `;

                // Close modal and refresh after a short delay
                setTimeout(() => {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('createClusterModal'));
                    if (modal) modal.hide();
                    loadClusters();
                }, 3000);
            }

            // Stop polling after max attempts
            if (attempts >= maxAttempts) {
                clearInterval(pollInterval);

                const successDiv = document.getElementById('createClusterSuccess');
                successDiv.innerHTML = `
                    <i class="bi bi-exclamation-triangle-fill"></i>
                    Cluster creation is taking longer than expected.
                    <div class="mt-2">
                        <span class="badge bg-warning">${cluster.stateName || 'UNKNOWN'}</span>
                        <small class="d-block mt-2">The cluster is still being created. You can close this dialog and check back later.</small>
                    </div>
                `;
            }

        } catch (err) {
            console.error('Error polling cluster status:', err);
            clearInterval(pollInterval);
        }

    }, 10000); // Poll every 10 seconds
}

// Delete Cluster functionality
let deleteClusterData = { name: '', projectId: '', providerName: '', instanceSizeName: '' };

function showDeleteClusterConfirmation(clusterName, projectId, providerName, instanceSizeName) {
    deleteClusterData = {
        name: clusterName,
        projectId: projectId,
        providerName: providerName || '',
        instanceSizeName: instanceSizeName || ''
    };

    console.log('Showing delete confirmation for cluster:', deleteClusterData);

    // Set cluster name in modal
    document.getElementById('deleteClusterName').textContent = clusterName;
    document.getElementById('confirmClusterName').value = '';
    document.getElementById('deleteClusterError').classList.add('d-none');
    document.getElementById('confirmDeleteClusterBtn').disabled = true;

    // Reset modal state
    document.getElementById('deleteClusterForm').style.display = 'block';
    document.getElementById('deleteClusterProgress').classList.add('d-none');
    document.getElementById('deleteClusterSuccess').classList.add('d-none');
    document.getElementById('deleteClusterFooter').classList.remove('d-none');
    document.getElementById('deleteClusterCompleteFooter').classList.add('d-none');

    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('deleteClusterModal'));
    modal.show();
}

// Region data by cloud provider
const regionsByProvider = {
    'AWS': [
        { value: 'US_EAST_1', label: 'US East (N. Virginia)' },
        { value: 'US_EAST_2', label: 'US East (Ohio)' },
        { value: 'US_WEST_1', label: 'US West (N. California)' },
        { value: 'US_WEST_2', label: 'US West (Oregon)' },
        { value: 'CA_CENTRAL_1', label: 'Canada (Central)' },
        { value: 'EU_WEST_1', label: 'EU (Ireland)' },
        { value: 'EU_WEST_2', label: 'EU (London)' },
        { value: 'EU_CENTRAL_1', label: 'EU (Frankfurt)' },
        { value: 'EU_NORTH_1', label: 'EU (Stockholm)' },
        { value: 'AP_SOUTH_1', label: 'Asia Pacific (Mumbai)' },
        { value: 'AP_SOUTHEAST_1', label: 'Asia Pacific (Singapore)' },
        { value: 'AP_SOUTHEAST_2', label: 'Asia Pacific (Sydney)' },
        { value: 'AP_NORTHEAST_1', label: 'Asia Pacific (Tokyo)' },
        { value: 'SA_EAST_1', label: 'South America (São Paulo)' }
    ],
    'GCP': [
        { value: 'CENTRAL_US', label: 'Iowa (us-central1)' },
        { value: 'EASTERN_US', label: 'South Carolina (us-east4)' },
        { value: 'WESTERN_US', label: 'Oregon (us-west1)' },
        { value: 'WESTERN_EUROPE', label: 'Belgium (europe-west1)' },
        { value: 'EASTERN_ASIA_PACIFIC', label: 'Taiwan (asia-east1)' },
        { value: 'NORTHEASTERN_ASIA_PACIFIC', label: 'Tokyo (asia-northeast1)' },
        { value: 'SOUTHEASTERN_ASIA_PACIFIC', label: 'Singapore (asia-southeast1)' },
        { value: 'AUSTRALIA_SOUTHEAST_1', label: 'Sydney (australia-southeast1)' }
    ],
    'AZURE': [
        { value: 'EAST_US_2', label: 'East US 2 (Virginia)' },
        { value: 'WEST_US_2', label: 'West US 2 (Washington)' },
        { value: 'CENTRAL_US', label: 'Central US (Iowa)' },
        { value: 'NORTH_EUROPE', label: 'North Europe (Ireland)' },
        { value: 'WEST_EUROPE', label: 'West Europe (Netherlands)' },
        { value: 'EAST_ASIA', label: 'East Asia (Hong Kong)' },
        { value: 'SOUTHEAST_ASIA', label: 'Southeast Asia (Singapore)' },
        { value: 'AUSTRALIA_EAST', label: 'Australia East (Sydney)' },
        { value: 'UK_SOUTH', label: 'UK South (London)' }
    ]
};

function updateRegionOptions(provider) {
    const regionSelect = document.getElementById('regionName');

    // Clear existing options
    regionSelect.innerHTML = '<option value="">Select region...</option>';

    // Get regions for selected provider
    const regions = regionsByProvider[provider] || [];

    // Add region options
    regions.forEach(region => {
        const option = document.createElement('option');
        option.value = region.value;
        option.textContent = region.label;
        regionSelect.appendChild(option);
    });

    // Enable/disable based on whether provider is selected
    regionSelect.disabled = !provider;
}

// Enable delete button only when cluster name is correctly typed
document.addEventListener('DOMContentLoaded', function() {
    const confirmInput = document.getElementById('confirmClusterName');
    const deleteBtn = document.getElementById('confirmDeleteClusterBtn');

    if (confirmInput) {
        confirmInput.addEventListener('input', function() {
            if (this.value === deleteClusterData.name) {
                deleteBtn.disabled = false;
            } else {
                deleteBtn.disabled = true;
            }
        });
    }

    // Add event listener for provider selection
    const providerSelect = document.getElementById('providerName');
    if (providerSelect) {
        providerSelect.addEventListener('change', function() {
            updateRegionOptions(this.value);
        });

        // Initialize region dropdown as disabled
        document.getElementById('regionName').disabled = true;
    }
});

async function deleteCluster() {
    const deleteBtn = document.getElementById('confirmDeleteClusterBtn');
    const errorDiv = document.getElementById('deleteClusterError');
    const confirmInput = document.getElementById('confirmClusterName');

    // Validate cluster name matches
    if (confirmInput.value !== deleteClusterData.name) {
        errorDiv.textContent = 'Cluster name does not match. Please type the exact cluster name.';
        errorDiv.classList.remove('d-none');
        return;
    }

    // Hide error
    errorDiv.classList.add('d-none');

    // Disable button and show loading
    deleteBtn.disabled = true;
    deleteBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Deleting...';

    try {
        console.log('Initiating deletion for cluster:', deleteClusterData);

        const response = await fetch(`/api/clusters/${deleteClusterData.projectId}/${deleteClusterData.name}`, {
            method: 'DELETE'
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.detail || `Failed to delete cluster (${response.status})`);
        }

        console.log('Deletion request successful, starting to poll for completion');

        // Hide confirmation form and show progress
        document.getElementById('deleteClusterForm').style.display = 'none';
        document.getElementById('deleteClusterProgress').classList.remove('d-none');
        document.getElementById('deleteClusterFooter').classList.add('d-none');

        // Start polling for deletion completion
        pollClusterDeletionStatus(
            deleteClusterData.projectId,
            deleteClusterData.name,
            deleteClusterData.providerName,
            deleteClusterData.instanceSizeName
        );

    } catch (err) {
        console.error('Error deleting cluster:', err);
        errorDiv.textContent = err.message;
        errorDiv.classList.remove('d-none');

        // Re-enable button
        deleteBtn.disabled = false;
        deleteBtn.innerHTML = '<i class="bi bi-trash"></i> Delete Cluster';
    }
}

async function pollClusterDeletionStatus(projectId, clusterName, providerName, instanceSizeName) {
    const maxAttempts = 60; // Max 10 minutes (60 * 10 seconds)
    let attempts = 0;

    console.log(`Starting deletion polling for ${clusterName} (provider: ${providerName}, instanceSize: ${instanceSizeName})`);

    const pollInterval = setInterval(async () => {
        attempts++;

        try {
            // Determine if this is a Flex cluster based on provider name or instance size
            const isFlexCluster = providerName === 'FLEX' || instanceSizeName === 'FLEX';

            // Fetch cluster list from the correct endpoint
            const endpoint = isFlexCluster
                ? `/api/clusters/${projectId}/flex/list`
                : `/api/clusters/${projectId}`;

            console.log(`Polling deletion status (attempt ${attempts}) from: ${endpoint}`);

            const response = await fetch(endpoint);
            if (!response.ok) {
                console.warn('Failed to fetch cluster list during deletion polling');
                // If we can't fetch, assume it might be deleted
                if (attempts > 3) {
                    // After a few attempts, if we can't fetch, assume deletion completed
                    clearInterval(pollInterval);
                    showDeletionComplete(clusterName);
                }
                return;
            }

            const data = await response.json();
            console.log(`Polling response for ${clusterName}:`, data);

            // Look for the cluster in the results
            const cluster = (data.results || []).find(c => c.name === clusterName);

            if (!cluster) {
                // Cluster not found - deletion complete!
                console.log(`Cluster ${clusterName} not found in list - deletion complete!`);
                clearInterval(pollInterval);
                showDeletionComplete(clusterName);
                return;
            }

            console.log(`Cluster ${clusterName} status: ${cluster.stateName}`);

            // Update progress bar based on time elapsed
            const progressBar = document.getElementById('deleteClusterProgressBar');
            const progressPercent = Math.min(10 + (attempts * 1.5), 95);
            if (progressBar) {
                progressBar.style.width = `${progressPercent}%`;

                // Update progress text based on percentage
                if (progressPercent < 40) {
                    progressBar.innerHTML = '<span class="fw-bold">Shutting down...</span>';
                } else if (progressPercent < 70) {
                    progressBar.innerHTML = '<span class="fw-bold">Removing resources...</span>';
                } else {
                    progressBar.innerHTML = '<span class="fw-bold">Finalizing...</span>';
                }
            }

            // Animate step indicators
            if (attempts > 3) {
                const step1 = document.getElementById('deleteStep1');
                if (step1) step1.innerHTML = '<i class="bi bi-check-circle-fill text-success"></i> Shutting down cluster';
            }
            if (attempts > 10) {
                const step2 = document.getElementById('deleteStep2');
                if (step2) step2.innerHTML = '<i class="bi bi-arrow-right-circle-fill text-primary"></i> Removing resources';
            }

            // Update status badge
            const statusBadge = document.getElementById('deleteClusterStatus');
            if (statusBadge) {
                statusBadge.className = 'badge fs-6 py-2 px-3';
                switch (cluster.stateName) {
                    case 'DELETING':
                        statusBadge.classList.add('bg-warning', 'text-dark');
                        statusBadge.innerHTML = '<i class="bi bi-hourglass-split"></i> DELETING';
                        break;
                    case 'DELETED':
                        statusBadge.classList.add('bg-danger');
                        statusBadge.innerHTML = '<i class="bi bi-x-circle-fill"></i> DELETED';
                        break;
                    default:
                        statusBadge.classList.add('bg-secondary');
                        statusBadge.innerHTML = '<i class="bi bi-question-circle-fill"></i> ' + (cluster.stateName || 'UNKNOWN');
                }
            }

            // Check if deletion took too long
            if (attempts >= maxAttempts) {
                console.warn(`Deletion polling timeout after ${attempts} attempts`);
                clearInterval(pollInterval);

                // Show a warning but still mark as complete
                document.getElementById('deleteClusterProgressText').textContent =
                    'Deletion is taking longer than expected. The cluster may still be deleting in the background.';
                setTimeout(() => {
                    showDeletionComplete(clusterName);
                }, 3000);
            }

        } catch (err) {
            console.error('Error polling cluster deletion status:', err);

            // If we get an error after a few attempts, assume deletion completed
            if (attempts > 3) {
                clearInterval(pollInterval);
                showDeletionComplete(clusterName);
            }
        }

    }, 10000); // Poll every 10 seconds
}

function showDeletionComplete(clusterName) {
    console.log(`Showing deletion complete for ${clusterName}`);

    // Update all steps to complete
    document.getElementById('deleteStep1').innerHTML = '<i class="bi bi-check-circle-fill text-success"></i> Shutting down cluster';
    document.getElementById('deleteStep2').innerHTML = '<i class="bi bi-check-circle-fill text-success"></i> Removing resources';
    document.getElementById('deleteStep3').innerHTML = '<i class="bi bi-check-circle-fill text-success"></i> Finalizing deletion';

    // Update progress bar to 100%
    const progressBar = document.getElementById('deleteClusterProgressBar');
    if (progressBar) {
        progressBar.style.width = '100%';
        progressBar.innerHTML = '<span class="fw-bold">Complete!</span>';
        progressBar.classList.remove('progress-bar-animated');
    }

    // Hide progress, show success
    setTimeout(() => {
        document.getElementById('deleteClusterProgress').classList.add('d-none');
        document.getElementById('deleteClusterSuccess').classList.remove('d-none');
        document.getElementById('deleteClusterCompleteFooter').classList.remove('d-none');

        // Reload clusters list
        loadClusters();
    }, 1500);
}

// Add event listeners
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('loginBtn').addEventListener('click', loginToCluster);
    document.getElementById('addUserBtn').addEventListener('click', addDatabaseUser);
    document.getElementById('confirmLogoutBtn').addEventListener('click', performLogout);
    document.getElementById('createClusterBtn').addEventListener('click', showCreateClusterModal);
    document.getElementById('submitCreateClusterBtn').addEventListener('click', createCluster);
    document.getElementById('confirmDeleteClusterBtn').addEventListener('click', deleteCluster);

    // Check session status on page load
    checkSessionStatus();

    // Allow Enter key to submit login
    document.getElementById('loginForm').addEventListener('submit', function(e) {
        e.preventDefault();
        loginToCluster();
    });

    // Allow Enter key to submit add user
    document.getElementById('addUserForm').addEventListener('submit', function(e) {
        e.preventDefault();
        addDatabaseUser();
    });

    // Allow Enter key to submit create cluster
    document.getElementById('createClusterForm').addEventListener('submit', function(e) {
        e.preventDefault();
        createCluster();
    });

    // Reset create cluster modal when closed
    const createClusterModal = document.getElementById('createClusterModal');
    createClusterModal.addEventListener('hidden.bs.modal', function () {
        document.getElementById('createClusterForm').reset();
        document.getElementById('createClusterForm').style.display = 'block';
        document.getElementById('createClusterError').classList.add('d-none');
        document.getElementById('createClusterSuccess').classList.add('d-none');
    });

    // Reset delete cluster modal when closed
    const deleteClusterModal = document.getElementById('deleteClusterModal');
    deleteClusterModal.addEventListener('hidden.bs.modal', function () {
        document.getElementById('confirmClusterName').value = '';
        document.getElementById('deleteClusterError').classList.add('d-none');
        document.getElementById('confirmDeleteClusterBtn').disabled = true;
        document.getElementById('deleteClusterForm').style.display = 'block';
        document.getElementById('deleteClusterProgress').classList.add('d-none');
        document.getElementById('deleteClusterSuccess').classList.add('d-none');
        document.getElementById('deleteClusterFooter').classList.remove('d-none');
        document.getElementById('deleteClusterCompleteFooter').classList.add('d-none');
        deleteClusterData = { name: '', projectId: '', providerName: '', instanceSizeName: '' };
    });
});
</script>
{% endblock %}
