{% extends "base.html" %}

{% block title %}Projects - 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 active" aria-current="page"><span id="orgNameBreadcrumb">...</span></li>
            </ol>
        </nav>

        <div class="d-flex justify-content-between align-items-center mb-2">
            <h1><i class="bi bi-folder"></i> Projects</h1>
            <div>
                <button class="btn btn-primary btn-sm me-2" data-bs-toggle="modal" data-bs-target="#createProjectModal">
                    <i class="bi bi-plus-circle"></i> Create Project
                </button>
                <button class="btn btn-outline-success btn-sm" id="refreshBtn">
                    <i class="bi bi-arrow-clockwise"></i> Refresh
                </button>
            </div>
        </div>

        <script>
            const ORG_ID_OR_NAME = "{{ org_id_or_name }}";
        </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 projects...</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>

        <!-- Projects grouped by organization -->
        <div id="projectsTable" class="d-none">
            <div id="projectsContainer">
            </div>
        </div>
    </div>
</div>

<!-- Project 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> Project 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 project name to view its details</p>
        </div>
    </div>
</div>

<!-- Cluster Details Panel (Offcanvas) -->
<div class="offcanvas offcanvas-end offcanvas-wide" tabindex="-1" id="clusterDetailsPanel" aria-labelledby="clusterDetailsPanelLabel">
    <div class="offcanvas-header border-bottom">
        <h5 class="offcanvas-title" id="clusterDetailsPanelLabel">
            <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="clusterDetailsContent">
            <p class="text-muted">Click on a cluster name to view its details</p>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteConfirmModalLabel">
                    <i class="bi bi-exclamation-triangle"></i> Confirm Project Deletion
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger mb-3">
                    <strong>Warning!</strong> This action cannot be undone. Deleting this project will permanently remove:
                </div>

                <h6>Project: <strong id="deleteProjectName"></strong></h6>

                <div id="deleteResourcesLoading" class="text-center my-3">
                    <div class="spinner-border spinner-border-sm text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="small mt-2">Loading project resources...</p>
                </div>

                <div id="deleteResourcesList" class="d-none">
                    <h6 class="mt-3">Clusters to be deleted:</h6>
                    <div id="deleteClustersContainer"></div>

                    <div class="mt-3 p-3 bg-light border rounded">
                        <p class="mb-2"><strong>To confirm deletion, type the project name exactly as shown above:</strong></p>
                        <input type="text" class="form-control" id="deleteConfirmInput" placeholder="Type project name here">
                        <div id="deleteConfirmError" class="text-danger small mt-1 d-none">Project name does not match</div>
                    </div>
                </div>
            </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="deleteConfirmBtn" disabled onclick="executeDeleteProject()">
                    <i class="bi bi-trash"></i> Delete Project
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Create Project Modal -->
<div class="modal fade" id="createProjectModal" tabindex="-1" aria-labelledby="createProjectModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createProjectModalLabel">
                    <i class="bi bi-plus-circle"></i> Create New Project
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="createProjectForm">
                    <div class="mb-3">
                        <label for="projectName" class="form-label">Project Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="projectName" name="projectName" required
                               placeholder="Enter project name" maxlength="64">
                        <div class="form-text">Choose a unique name for your project (2-64 characters)</div>
                    </div>
                    <div id="createProjectError" class="alert alert-danger d-none" role="alert"></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="createProjectBtn" onclick="executeCreateProject()">
                    <i class="bi bi-plus-circle"></i> Create Project
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

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

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

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

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

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

    .cluster-name-link:hover {
        text-decoration: underline;
    }
</style>

<script>
let projects = [];

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

    // Listen for operation completion events and reload projects list
    // Poll for operationQueueUI to be initialized
    let pollAttempts = 0;
    const maxPollAttempts = 20; // 10 seconds max
    const pollInterval = setInterval(() => {
        pollAttempts++;
        console.log(`[Projects] Polling for operationQueueUI (attempt ${pollAttempts}/${maxPollAttempts})`);

        if (window.operationQueueUI && window.operationQueueUI.manager) {
            clearInterval(pollInterval);
            console.log('[Projects] operationQueueUI found, registering listener');

            window.operationQueueUI.manager.addListener((event, operation) => {
                console.log('[Projects] SSE event received:', event, 'type:', operation.type);

                // Only reload for create_project (delete already removes the item optimistically)
                if (event === 'completed' && operation.type === 'create_project') {
                    console.log(`[Projects] ${operation.type} completed, reloading projects list`);
                    loadProjects();
                }
            });

            console.log('[Projects] Event listener registered successfully');
        } else if (pollAttempts >= maxPollAttempts) {
            clearInterval(pollInterval);
            console.error('[Projects] Failed to find operationQueueUI after', maxPollAttempts, 'attempts');
        }
    }, 500);
});

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

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

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

        // Find organization by ID or name (case-sensitive)
        const org = (orgsData.results || []).find(o =>
            o.id === ORG_ID_OR_NAME || o.name === ORG_ID_OR_NAME
        );

        if (!org) {
            throw new Error(`Organization "${ORG_ID_OR_NAME}" not found`);
        }

        // Update breadcrumb with organization name
        const breadcrumb = document.getElementById('orgNameBreadcrumb');
        breadcrumb.textContent = org.name;

        // Fetch projects for this organization
        const projectsResponse = await fetch(`/api/organizations/${org.id}/projects?itemsPerPage=500`);
        if (!projectsResponse.ok) throw new Error('Failed to fetch projects');
        const projectsData = await projectsResponse.json();

        projects = projectsData.results || [];

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

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

function renderProjects() {
    const container = document.getElementById('projectsContainer');
    container.innerHTML = '';

    if (projects.length === 0) {
        container.innerHTML = '<div class="alert alert-info">No projects found in this organization</div>';
        return;
    }

    // Create table for projects
    const tableDiv = document.createElement('div');
    tableDiv.className = 'table-responsive';
    tableDiv.innerHTML = `
        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Clusters</th>
                    <th>Created</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    `;

    const tbody = tableDiv.querySelector('tbody');

    projects.forEach(project => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>
                <a href="javascript:void(0)" class="project-name-link" onclick="showProjectDetails('${project.id}')">
                    <strong>${project.name}</strong>
                </a>
            </td>
            <td>
                <a href="/clusters" class="text-decoration-none">
                    <span class="badge bg-primary">${project.clusterCount || 0}</span>
                </a>
            </td>
            <td>${new Date(project.created).toLocaleDateString()}</td>
            <td>
                <button class="btn btn-sm btn-outline-danger" onclick="confirmDeleteProject('${project.id}', '${project.name.replace(/'/g, "\\'")}')">
                    <i class="bi bi-trash"></i> Delete
                </button>
            </td>
        `;

        tbody.appendChild(row);
    });

    container.appendChild(tableDiv);
}

async function showProjectDetails(projectId) {
    // Find project in the projects array
    const project = projects.find(p => p.id === projectId);
    if (!project) return;

    const detailsContent = document.getElementById('detailsContent');

    // 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 project details...</p>
        </div>
    `;

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

    try {
        // Fetch all related data in parallel
        const [clustersData, usersData, alertsData, projectDetailsData] = await Promise.all([
            fetch(`/api/clusters/${project.id}`).then(r => r.ok ? r.json() : { results: [] }).catch(() => ({ results: [] })),
            fetch(`/api/users/${project.id}`).then(r => r.ok ? r.json() : { results: [] }).catch(() => ({ results: [] })),
            fetch(`/api/alerts/${project.id}`).then(r => r.ok ? r.json() : { results: [] }).catch(() => ({ results: [] })),
            fetch(`/api/projects/${project.id}`).then(r => r.ok ? r.json() : {}).catch(() => ({}))
        ]);

        const clusters = clustersData.results || [];
        const users = usersData.results || [];
        const alerts = alertsData.results || [];
        const projectDetails = projectDetailsData;

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

            <div class="mb-3">
                <h6 class="text-muted">Basic Information</h6>
                <table class="table table-sm">
                    <tbody>
                        <tr><th width="40%">Name</th><td>${project.name}</td></tr>
                        <tr><th>ID</th><td><code class="small">${project.id}</code></td></tr>
                        <tr><th>Organization ID</th><td><code class="small">${project.orgId}</code></td></tr>
                        <tr><th>Cluster Count</th><td>${project.clusterCount || 0}</td></tr>
                        <tr><th>Database Users</th><td>${users.length}</td></tr>
                        <tr><th>Active Alerts</th><td><span class="badge ${alerts.length > 0 ? 'bg-warning' : 'bg-success'}">${alerts.length}</span></td></tr>
                        <tr><th>Created</th><td>${new Date(project.created).toLocaleString()}</td></tr>
                    </tbody>
                </table>
            </div>

            <div class="mb-3">
                <h6 class="text-muted">Project Settings</h6>
                <table class="table table-sm">
                    <tbody>
                        <tr><th width="40%">Default Alerts</th><td>${project.withDefaultAlertsSettings ? '<span class="badge bg-success">Enabled</span>' : '<span class="badge bg-secondary">Disabled</span>'}</td></tr>
                        ${projectDetails.regionUsageRestrictions ? `<tr><th>Region Restrictions</th><td>${projectDetails.regionUsageRestrictions}</td></tr>` : ''}
                        ${projectDetails.limits ? `
                            <tr><th>Project Limits</th><td>
                                ${projectDetails.limits.map(limit => `
                                    <div class="small">${limit.name}: ${limit.value}${limit.currentUsage !== undefined ? ` (used: ${limit.currentUsage})` : ''}</div>
                                `).join('')}
                            </td></tr>
                        ` : ''}
                    </tbody>
                </table>
            </div>
        `;

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

        // Add clusters section
        if (clusters.length > 0) {
            const clusterAlerts = alerts.filter(alert => alert.clusterName);

            html += `
                <div class="mb-3">
                    <h6 class="text-muted">Clusters (${clusters.length})</h6>
                    <div class="list-group list-group-flush">
                        ${clusters.map(cluster => {
                            const clusterSpecificAlerts = clusterAlerts.filter(a => a.clusterName === cluster.name);
                            // Store cluster data for sidebar access
                            cluster.projectId = project.id;
                            cluster.projectName = project.name;
                            return `
                            <div class="list-group-item py-2 px-2">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <a href="javascript:void(0)" class="cluster-name-link" onclick="showClusterDetails('${cluster.id || cluster.name}', '${project.id}')">
                                            <strong><i class="bi bi-hdd-rack"></i> ${cluster.name}</strong>
                                        </a>
                                        ${cluster.paused ? '<span class="badge bg-warning text-dark ms-2">PAUSED</span>' : ''}
                                        ${clusterSpecificAlerts.length > 0 ? `<span class="badge bg-danger ms-1">${clusterSpecificAlerts.length} Alert${clusterSpecificAlerts.length > 1 ? 's' : ''}</span>` : ''}
                                        <div class="small text-muted mt-1">
                                            ${cluster.clusterType || 'N/A'} • ${cluster.mongoDBVersion || 'N/A'} • ${cluster.providerSettings?.instanceSizeName || 'N/A'}
                                        </div>
                                    </div>
                                    <div class="text-end">
                                        <span class="badge ${getStatusBadgeClass(cluster.stateName)}">${cluster.stateName || 'UNKNOWN'}</span>
                                    </div>
                                </div>
                            </div>
                        `}).join('')}
                    </div>
                </div>
            `;
        } else {
            html += `
                <div class="mb-3">
                    <h6 class="text-muted">Clusters</h6>
                    <p class="small text-muted">No clusters in this project</p>
                </div>
            `;
        }

        // Add database users section
        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>
            `;
        }

        // Add alerts section
        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, 10).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.clusterName ? `Cluster: ${alert.clusterName}` : 'Project-level'}
                                            ${alert.metricName ? ` • ${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 > 10 ? `<div class="list-group-item small text-muted text-center">...and ${alerts.length - 10} more alerts</div>` : ''}
                    </div>
                </div>
            `;
        } else {
            html += `
                <div class="mb-3">
                    <h6 class="text-muted">Active Alerts</h6>
                    <p class="small text-muted">No active alerts</p>
                </div>
            `;
        }

        detailsContent.innerHTML = html;

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

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';
    }
}

function formatConnectionString(connectionString) {
    // Insert username:password@ placeholder after the protocol
    if (!connectionString) return connectionString;
    const match = connectionString.match(/^(mongodb(?:\+srv)?:\/\/)(.*)/);
    if (match) {
        return `${match[1]}<strong>username:password@</strong>${match[2]}`;
    }
    return connectionString;
}

// Shared cluster details display function - same code path for all cluster detail views
async function showClusterDetails(clusterId, projectId) {
    const detailsContent = document.getElementById('clusterDetailsContent');

    // 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('clusterDetailsPanel'));
    offcanvas.show();

    try {
        // Fetch cluster details
        const clusterResponse = await fetch(`/api/clusters/${projectId}`);
        if (!clusterResponse.ok) throw new Error('Failed to fetch cluster');
        const clustersData = await clusterResponse.json();
        const cluster = (clustersData.results || []).find(c => c.id === clusterId || c.name === clusterId);

        if (!cluster) throw new Error('Cluster not found');

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

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

        // 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 width="40%">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>
        `;
    }
}

// Delete project functionality
let deleteProjectId = null;
let deleteProjectNameExpected = null;
let deleteProjectClusters = [];

async function confirmDeleteProject(projectId, projectName) {
    deleteProjectId = projectId;
    deleteProjectNameExpected = projectName;
    deleteProjectClusters = [];

    // Reset modal state
    document.getElementById('deleteProjectName').textContent = projectName;
    document.getElementById('deleteConfirmInput').value = '';
    document.getElementById('deleteConfirmBtn').disabled = true;
    document.getElementById('deleteConfirmError').classList.add('d-none');
    document.getElementById('deleteResourcesLoading').classList.remove('d-none');
    document.getElementById('deleteResourcesList').classList.add('d-none');

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

    // Check with backend if confirmation is required (will return cluster list)
    try {
        const response = await fetch(`/api/projects/${projectId}`, {
            method: 'DELETE'
        });

        if (!response.ok) {
            throw new Error(`Failed to check project deletion requirements: ${response.statusText}`);
        }

        const data = await response.json();

        // Always show confirmation (backend always requires it now)
        if (data.confirmation_required) {
            const clusters = data.clusters || [];
            deleteProjectClusters = clusters;

            // Build clusters list
            const clustersContainer = document.getElementById('deleteClustersContainer');

            if (clusters.length === 0) {
                clustersContainer.innerHTML = '<div class="alert alert-info"><i class="bi bi-info-circle"></i> No clusters in this project</div>';
            } else {
                let html = '<div class="alert alert-warning mb-3">';
                html += `<i class="bi bi-exclamation-triangle"></i> <strong>Warning:</strong> ${data.message}`;
                html += '</div><ul class="list-group">';

                for (const cluster of clusters) {
                    html += `
                        <li class="list-group-item">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <strong><i class="bi bi-hdd-rack"></i> ${cluster.name}</strong>
                                    <div class="small text-muted">
                                        ${cluster.type || 'N/A'} • ${cluster.state || 'UNKNOWN'}
                                    </div>
                                    <div class="small text-muted mt-1">
                                        <strong>Note:</strong> All databases and collections in this cluster will be permanently deleted
                                    </div>
                                </div>
                                <span class="badge ${getStatusBadgeClass(cluster.state)}">${cluster.state || 'UNKNOWN'}</span>
                            </div>
                        </li>
                    `;
                }
                html += '</ul>';
                clustersContainer.innerHTML = html;
            }

            // Hide loading, show resources
            document.getElementById('deleteResourcesLoading').classList.add('d-none');
            document.getElementById('deleteResourcesList').classList.remove('d-none');
        }

    } catch (err) {
        console.error('Error checking project deletion:', err);
        document.getElementById('deleteResourcesLoading').innerHTML = `
            <div class="alert alert-warning">
                <i class="bi bi-exclamation-triangle"></i>
                Failed to load project resources. ${err.message}
            </div>
        `;
        document.getElementById('deleteResourcesList').classList.remove('d-none');
    }
}

// Validate project name input
document.addEventListener('DOMContentLoaded', function() {
    const input = document.getElementById('deleteConfirmInput');
    const btn = document.getElementById('deleteConfirmBtn');
    const error = document.getElementById('deleteConfirmError');

    input.addEventListener('input', function() {
        const value = input.value.trim();
        if (value === deleteProjectNameExpected) {
            btn.disabled = false;
            error.classList.add('d-none');
        } else {
            btn.disabled = true;
            if (value.length > 0) {
                error.classList.remove('d-none');
            } else {
                error.classList.add('d-none');
            }
        }
    });
});

async function executeDeleteProject() {
    if (!deleteProjectId) return;

    const projectId = deleteProjectId;
    const projectName = deleteProjectNameExpected;

    // Close the modal
    const modal = bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'));
    modal.hide();

    try {
        console.log('executeDeleteProject called for:', projectId, projectName);

        // Call DELETE endpoint with confirmed=true
        const response = await fetch(`/api/projects/${projectId}?confirmed=true`, {
            method: 'DELETE'
        });

        console.log('Delete response status:', response.status, response.ok);

        if (!response.ok) {
            const error = await response.json();
            console.error('Delete failed:', error);
            alert(`Failed to delete project: ${error.detail || response.statusText}`);
            return;
        }

        const data = await response.json();
        console.log('Delete response data:', data);

        if (data.success) {
            const clusterCount = deleteProjectClusters.length;
            const message = clusterCount > 0
                ? `Project "${projectName}" and ${clusterCount} cluster(s) deletion queued`
                : `Project "${projectName}" deletion queued`;

            console.log(message);

            // Immediately remove project from the list to prevent duplicate deletion attempts
            console.log('Removing project from list:', projectId);
            console.log('Projects before removal:', projects.length);
            const projectIndex = projects.findIndex(p => p.id === projectId);
            console.log('Project index found:', projectIndex);
            if (projectIndex !== -1) {
                projects.splice(projectIndex, 1);
                console.log('Projects after removal:', projects.length);
                renderProjects();
                console.log('Projects re-rendered');
            } else {
                console.warn('Project not found in projects array:', projectId);
            }
        }

    } catch (err) {
        console.error('Error deleting project:', err);
        alert(`Error deleting project: ${err.message}`);
    }
}

// Create project functionality
let currentOrgId = null;

async function executeCreateProject() {
    const projectName = document.getElementById('projectName').value.trim();
    const errorDiv = document.getElementById('createProjectError');
    const btn = document.getElementById('createProjectBtn');
    const originalHtml = btn.innerHTML;

    // Clear previous errors
    errorDiv.classList.add('d-none');

    // Validate
    if (!projectName || projectName.length < 2) {
        errorDiv.textContent = 'Project name must be at least 2 characters long';
        errorDiv.classList.remove('d-none');
        return;
    }

    // Get current organization ID
    if (!currentOrgId) {
        try {
            const orgsResponse = await fetch('/api/organizations/');
            if (!orgsResponse.ok) throw new Error('Failed to fetch organizations');
            const orgsData = await orgsResponse.json();

            const org = (orgsData.results || []).find(o =>
                o.id === ORG_ID_OR_NAME || o.name === ORG_ID_OR_NAME
            );

            if (!org) {
                throw new Error(`Organization "${ORG_ID_OR_NAME}" not found`);
            }

            currentOrgId = org.id;
        } catch (err) {
            errorDiv.textContent = `Failed to get organization: ${err.message}`;
            errorDiv.classList.remove('d-none');
            return;
        }
    }

    // Show loading state
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Creating...';

    try {
        const response = await fetch('/api/projects/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name: projectName,
                orgId: currentOrgId
            })
        });

        if (!response.ok) {
            let errorMessage = 'Failed to create project';
            try {
                const error = await response.json();
                errorMessage = error.detail || errorMessage;
            } catch (parseError) {
                errorMessage = `${errorMessage}: ${response.statusText || response.status}`;
            }
            throw new Error(errorMessage);
        }

        const result = await response.json();

        console.log('Create project response:', result);

        // Close modal
        const modal = bootstrap.Modal.getInstance(document.getElementById('createProjectModal'));
        modal.hide();

        // Clear form
        document.getElementById('projectName').value = '';

        // Show success message
        const successAlert = document.createElement('div');
        successAlert.className = 'alert alert-success alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3';
        successAlert.style.zIndex = '9999';
        successAlert.innerHTML = `
            <i class="bi bi-check-circle"></i> Project "${projectName}" creation queued - check Operations panel for progress
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.body.appendChild(successAlert);
        setTimeout(() => successAlert.remove(), 5000);

        // Don't reload immediately - wait for operation completion
        // The project list will auto-refresh when the create operation completes

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

        // Re-enable button
        btn.disabled = false;
        btn.innerHTML = originalHtml;
    }
}

// Helper function to format bytes
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];
}

// Reset form when modal is closed
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('createProjectModal');
    modal.addEventListener('hidden.bs.modal', function() {
        document.getElementById('projectName').value = '';
        document.getElementById('createProjectError').classList.add('d-none');
        document.getElementById('createProjectBtn').disabled = false;
        document.getElementById('createProjectBtn').innerHTML = '<i class="bi bi-plus-circle"></i> Create Project';
    });
});
</script>
{% endblock %}
