{% extends 'base.html' %}

{% block title %}AVS Migration Risks Analysis{% endblock %}

{% block content %}
<div class="container">
<h1 class="text-center">AVS Migration Risks Analysis</h1>
<p class="text-center lead">This page will display potential migration risks for the uploaded file: <code>{{ filename }}</code></p>

{% if risk_results and risk_results.risks %}
<!-- Summary Cards Section -->
<div class="d-flex flex-wrap justify-content-start" id="summary-cards">
    {% set risk_order = ['emergency', 'blocking', 'danger', 'warning', 'info'] %}
    {% for risk_level in risk_order %}
        {% for risk_name, risk_data in risk_results.risks.items() %}
            {% if risk_data.count > 0 and risk_data.risk_level == risk_level %}
                <a href="#{{ risk_name }}-card" class="card m-2 text-decoration-none" style="width: 18rem;" title="Click to view more details about {{ risk_data.function_name }}">
                    <div class="card-body">
                        <h5 class="card-title">{{ risk_name.replace('detect_', '').replace('_', ' ').title() }}</h5>
                        <p class="card-text">Count: {{ risk_data.count }}</p>
                    </div>
                    <div class="card-footer">
                        <span class="badge rounded-pill {{ get_risk_badge_class(risk_data.risk_level) }}">
                            Sev: {{ get_risk_display_name(risk_data.risk_level) }}
                        </span>
                    </div>
                </a>
            {% endif %}
        {% endfor %}
    {% endfor %}
</div>

<!-- Filter Buttons -->
<div class="d-flex justify-content-end mb-3">
    <div class="btn-group" role="group" aria-label="Filter Severity">
        <button type="button" class="btn btn-outline-primary" onclick="filterCards('all')">All</button>
        <button type="button" class="btn btn-outline-dark filter-outline-dark" onclick="filterCards('emergency')">Emergency</button>
        <button type="button" class="btn btn-outline-danger" onclick="filterCards('blocking')">Blocking</button>
        <button type="button" class="btn btn-outline-warning" onclick="filterCards('warning')">Warning</button>
        <button type="button" class="btn btn-outline-info" onclick="filterCards('info')">Info</button>
    </div>
</div>

<!-- Azure OpenAI Disclaimer - Visible when AI is configured via environment variables -->
<div class="alert alert-warning ai-disclaimer" role="alert" style="display: none;">
    <i class="fas fa-exclamation-triangle"></i> <strong>Disclaimer:</strong>
    AI-generated suggestions are for informational purposes only and should be thoroughly reviewed by qualified professionals.
    The tool maintainers cannot be held responsible for the accuracy or consequences of the provided suggestions.
    Always validate recommendations with your specific environment and requirements.
    <br><br>
    <i class="fas fa-leaf text-success"></i> <strong>Environmental Responsibility:</strong>
    Please be mindful when using AI features, as they require significant computational resources and contribute to carbon
    emissions. Consider the environmental impact and use AI suggestions thoughtfully.

    <!-- Cumulative AI Analysis Impact Tracker -->
    <div id="cumulative-ai-impact" class="mt-3 p-3 bg-light rounded border" style="display: none;">
        <div class="d-flex align-items-center mb-2">
            <i class="fas fa-chart-line text-primary me-2"></i>
            <strong>AI analysis impact for this session</strong>
        </div>
        <div class="row text-center">
            <div class="col-md-4">
                <div class="p-2 bg-info bg-opacity-10 rounded">
                    <i class="fas fa-microchip text-info mb-1"></i>
                    <div class="fw-bold text-info" id="cumulative-tokens">0</div>
                    <small class="text-muted">total tokens</small>
                </div>
            </div>
            <div class="col-md-4">
                <div class="p-2 bg-success bg-opacity-10 rounded">
                    <i class="fas fa-leaf text-success mb-1"></i>
                    <div class="fw-bold text-success" id="cumulative-carbon">0μg CO₂e</div>
                    <small class="text-muted">
                        carbon footprint 
                        <i class="fas fa-info-circle text-info ms-1" 
                           data-bs-toggle="popover" 
                           data-bs-placement="bottom" 
                           data-bs-html="true"
                           data-bs-trigger="click"
                           data-bs-title="<strong>Carbon Footprint Calculation</strong>"
                           data-bs-content="<strong>Method:</strong> ~0.0047 g CO₂e per 1000 tokens<br>
                           <strong>Formula:</strong> Energy (kWh) × Grid Intensity (gCO₂/kWh)<br>
                           <strong>Example:</strong> 0.01 Wh per 1000 tokens × 470 gCO₂/kWh<br><br>
                           <strong>Note:</strong> Approximate value. Actual footprint varies by GPU model, batching, model size, and infrastructure.<br><br>
                           <strong>Sources & Tools:</strong><br>
                           • <a href='https://arxiv.org/abs/1906.02243' target='_blank' class='text-primary'>Strubell et al. - Energy and Policy Considerations</a><br>
                           • <a href='https://arxiv.org/abs/1910.09700' target='_blank' class='text-primary'>Lacoste et al. - Quantifying ML Carbon Emissions</a><br>
                           • <a href='https://carbontracker.org/' target='_blank' class='text-primary'>CarbonTracker</a> | <a href='https://github.com/mlco2/codecarbon' target='_blank' class='text-primary'>CodeCarbon</a><br>
                           • <a href='https://ourworldindata.org/co2-intensity-electricity' target='_blank' class='text-primary'>Grid Carbon Intensities</a><br><br>
                           <small class='text-muted'>Click outside to close</small>"
                           style="cursor: pointer;"></i>
                    </small>
                </div>
            </div>
            <div class="col-md-4">
                <div class="p-2 bg-secondary bg-opacity-10 rounded">
                    <i class="fas fa-robot text-secondary mb-1"></i>
                    <div class="fw-bold text-secondary" id="cumulative-requests">0</div>
                    <small class="text-muted">AI requests</small>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Risk Detail Cards -->
{% set risk_order = ['emergency', 'blocking', 'danger', 'warning', 'info'] %}
{% for risk_level in risk_order %}
    {% for risk_name, risk_data in risk_results.risks.items() %}
        {% if risk_data.count > 0 and risk_data.risk_level == risk_level %}
            <div class="card mb-4" id="{{ risk_name }}-card" data-risk-level="{{ risk_data.risk_level }}">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h2>{{ risk_name.replace('detect_', '').replace('_', ' ').title() }}</h2>
                    <div class="d-flex gap-2">
                        <button class="btn btn-outline-success ai-suggestion-btn"
                                data-risk-name="{{ risk_name }}"
                                data-risk-description="{{ risk_data.risk_info.description if risk_data.risk_info else '' }}"
                                data-risk-level="{{ risk_data.risk_level }}"
                                onclick="getAISuggestion(this)"
                                style="display: none;">
                            <i class="fas fa-robot"></i> AI Suggestion
                        </button>
                        <button class="btn btn-primary" data-id="{{ risk_name }}-table" onclick="downloadTableAsCSV(this)">
                            <i class="fas fa-download"></i> Download CSV
                        </button>
                    </div>
                </div>
            <div class="card-body">
                {% if risk_data.risk_info %}
                    <p>{{ risk_data.risk_info.description }}</p>

                    {% if risk_data.risk_info.alert_message %}
                    <div class="alert alert-primary" role="alert">
                        <i class="fa-solid fa-circle-info"></i>
                        {{ risk_data.risk_info.alert_message | safe }}
                    </div>
                    {% endif %}

                    <!-- AI Suggestion Area -->
                    <div id="ai-suggestion-{{ risk_name }}" class="ai-suggestion-area" style="display: none;">
                        <div class="alert alert-info">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <h6 class="alert-heading"><i class="fas fa-robot"></i> AI Analysis & Recommendations</h6>
                                    <div id="ai-suggestion-content-{{ risk_name }}"></div>
                                </div>
                                <button type="button" class="btn-close" onclick="hideAISuggestion('{{ risk_name }}')" aria-label="Close"></button>
                            </div>
                        </div>
                    </div>
                {% endif %}                <!-- Generic table for all risk types -->
                {% if risk_data.data %}
                    <table class="table table-striped resizable-table" id="{{ risk_name }}-table">
                        <thead>
                            <tr>
                                <!-- Handle list of dictionaries -->
                                {% for key in risk_data.data[0].keys() %}
                                    <th>{{ key }}</th>
                                {% endfor %}
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Render list of dictionaries -->
                            {% for item in risk_data.data %}
                                <tr>
                                    {% for key, value in item.items() %}
                                        <td class="wrap">
                                            {% if key == 'Risk Level' %}
                                            <span class="badge rounded-pill {{ get_risk_badge_class(value) }}">
                                                {{ get_risk_display_name(value) }}
                                            </span>
                                            {% elif value is sameas true or value|string|lower in ['true', 'yes'] %}
                                                <span class="text-success"><strong>✓</strong></span>
                                            {% elif value is sameas false or value|string|lower in ['false', 'no'] %}
                                                <span class="text-danger">✘</span>
                                            {% elif 'MiB' in key and value|string|length > 0 %}
                                                {{ value | convert_mib_to_human_readable }}
                                            {% else %}
                                                {{ value }}
                                            {% endif %}
                                        </td>
                                    {% endfor %}
                                </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                {% endif %}
            </div>
            <div class="card-footer">
                <span class="badge rounded-pill {{ get_risk_badge_class(risk_data.risk_level) }}">
                    Sev: {{ get_risk_display_name(risk_data.risk_level) }}
                </span>
            </div>
        </div>
        {% endif %}
    {% endfor %}
{% endfor %}

{% else %}
<div class="alert alert-info" role="alert">
    <i class="fa-solid fa-circle-info"></i>
    No risks detected in the uploaded file, or the file could not be processed.
</div>
{% endif %}
</div>

<!-- JavaScript for filtering and CSV download -->
<style>
    /* Resizable table styles */
    .resizable-table {
        table-layout: fixed;
        width: 100%;
    }

    .resizable-table th {
        position: relative;
        padding-right: 20px;
    }

    .resizable-table th:not(:last-child)::after {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 6px;
        height: 100%;
        cursor: col-resize;
        background: transparent;
        border-right: 2px solid transparent;
        transition: border-color 0.2s;
    }

    .resizable-table th:not(:last-child):hover::after {
        border-right-color: #007bff;
    }

    .resizable-table th.resizing::after {
        border-right-color: #007bff;
    }

    .resizable-table td {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .resizable-table td.wrap {
        white-space: normal;
        word-break: break-word;
    }

    /* Azure OpenAI Integration Styles */
    .ai-suggestion-area {
        margin-bottom: 1rem;
    }

    .ai-suggestion-btn {
        min-width: 140px;
    }

    #azure-openai-config .btn-link {
        text-decoration: none;
        color: #0d6efd;
        padding: 0;
    }

    #azure-openai-config .btn-link:hover {
        color: #0a58ca;
    }

    .ai-suggestion-area .alert {
        margin-bottom: 0;
    }

    .ai-suggestion-area .alert-heading {
        margin-bottom: 1rem;
    }

    /* Print styles */
    @media print {
        .ai-analysis-metrics {
            display: none !important;
        }
    }

    /* Custom popover styles for carbon footprint info */
    .popover {
        max-width: 400px;
        font-size: 0.85rem;
        background-color: #2d3748;
        border: 1px solid #4a5568;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    }
    
    .popover-header {
        background-color: #1a202c;
        border-bottom: 1px solid #4a5568;
        font-weight: 600;
        color: #e2e8f0;
    }
    
    .popover-body {
        line-height: 1.4;
        text-align: left;
        background-color: #2d3748;
        color: #e2e8f0;
    }
    
    .popover-body a {
        color: #63b3ed !important;
        text-decoration: underline;
    }
    
    .popover-body a:hover {
        color: #90cdf4 !important;
    }
    
    .popover-body strong {
        color: #f7fafc;
    }
    
    .popover-body .text-muted {
        color: #a0aec0 !important;
    }
    
    /* Dark theme popover arrow */
    .popover .popover-arrow::before {
        border-bottom-color: #2d3748;
    }
    
    .popover .popover-arrow::after {
        border-bottom-color: #2d3748;
    }
</style>

<script>
    // Store risk data globally to avoid HTML attribute size limits
    const riskDataStore = {
        {% for risk_name, risk_data in risk_results.risks.items() %}
        "{{ risk_name }}": {{ risk_data.data | tojson | safe }},
        {% endfor %}
    };

    function downloadTableAsCSV(button) {
        const tableId = button.getAttribute('data-id');
        const table = document.getElementById(tableId);
        if (!table) {
            alert('Table not found.');
            return;
        }

        const rows = Array.from(table.querySelectorAll('tr'));
        const csvContent = rows.map(row => {
            const cells = Array.from(row.querySelectorAll('th, td'));
            return cells.map(cell => `"${cell.textContent.trim()}"`).join(',');
        }).join('\n');

        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `${tableId}.csv`;
        link.click();
    }

    function filterCards(severity) {
        const cards = document.querySelectorAll('.card[data-risk-level]');
        const summaryCards = document.querySelectorAll('#summary-cards .card');

        cards.forEach(card => {
            const riskLevel = card.getAttribute('data-risk-level');
            if (severity === 'all' || riskLevel === severity ||
                (severity === 'blocking' && (riskLevel === 'danger' || riskLevel === 'blocking')) ||
                (severity === 'emergency' && riskLevel === 'emergency')) {
                card.style.display = '';
            } else {
                card.style.display = 'none';
            }
        });

        summaryCards.forEach(card => {
            const badge = card.querySelector('.badge');
            const badgeText = badge ? badge.textContent.toLowerCase() : '';
            if (severity === 'all' || badgeText.includes(severity) ||
                (severity === 'blocking' && badgeText.includes('blocking')) ||
                (severity === 'emergency' && badgeText.includes('emergency'))) {
                card.style.display = '';
            } else {
                card.style.display = 'none';
            }
        });
    }

    // Resizable columns functionality
    function makeTablesResizable() {
        const tables = document.querySelectorAll('.resizable-table');

        tables.forEach(table => {
            const headers = table.querySelectorAll('th');

            headers.forEach((header, index) => {
                if (index < headers.length - 1) { // Don't add resizer to last column
                    let isResizing = false;
                    let startX = 0;
                    let startWidth = 0;

                    const onMouseDown = (e) => {
                        // Check if click is on the resize area (right edge of header)
                        const rect = header.getBoundingClientRect();
                        if (e.clientX >= rect.right - 10) {
                            isResizing = true;
                            startX = e.clientX;
                            startWidth = header.offsetWidth;
                            header.classList.add('resizing');

                            document.addEventListener('mousemove', onMouseMove);
                            document.addEventListener('mouseup', onMouseUp);
                            e.preventDefault();
                        }
                    };

                    const onMouseMove = (e) => {
                        if (!isResizing) return;

                        const diff = e.clientX - startX;
                        const newWidth = Math.max(50, startWidth + diff); // Minimum width of 50px
                        header.style.width = newWidth + 'px';
                    };

                    const onMouseUp = () => {
                        if (isResizing) {
                            isResizing = false;
                            header.classList.remove('resizing');
                            document.removeEventListener('mousemove', onMouseMove);
                            document.removeEventListener('mouseup', onMouseUp);
                        }
                    };

                    header.addEventListener('mousedown', onMouseDown);
                }
            });
        });
    }

    // Initialize resizable tables when DOM is loaded
    document.addEventListener('DOMContentLoaded', function() {
        makeTablesResizable();

        // Initialize Bootstrap popovers for carbon footprint info
        var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
        var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
            return new bootstrap.Popover(popoverTriggerEl, {
                container: 'body',
                sanitize: false // Allow HTML content including links
            });
        });

        // Close popover when clicking outside
        document.addEventListener('click', function (e) {
            popoverTriggerList.forEach(function (popoverTriggerEl) {
                var popoverInstance = bootstrap.Popover.getInstance(popoverTriggerEl);
                if (popoverInstance && !popoverTriggerEl.contains(e.target)) {
                    // Check if click is not inside the popover content
                    var popover = document.querySelector('.popover');
                    if (!popover || !popover.contains(e.target)) {
                        popoverInstance.hide();
                    }
                }
            });
        });

        // Check Azure OpenAI configuration status
        checkAzureOpenAIStatus();

        // Check for emergency risks and show warning popup
        checkForEmergencyRisks();
    });

    function checkForEmergencyRisks() {
        const emergencyCards = document.querySelectorAll('.card[data-risk-level="emergency"]');
        if (emergencyCards.length > 0) {
            // Create and show emergency warning modal
            showEmergencyWarning();
        }
    }

    function showEmergencyWarning() {
        // Create modal HTML
        const modalHTML = `
            <div class="modal fade" id="emergencyWarningModal" tabindex="-1" aria-labelledby="emergencyWarningModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content border-danger">
                        <div class="modal-header bg-danger text-white">
                            <h5 class="modal-title" id="emergencyWarningModalLabel">
                                <i class="fas fa-exclamation-triangle"></i> CRITICAL SECURITY ALERT
                            </h5>
                        </div>
                        <div class="modal-body">
                            <div class="alert alert-danger" role="alert">
                                <h4 class="alert-heading"><i class="fas fa-shield-alt"></i> Password Exposure Detected!</h4>
                                <p><strong>Clear text passwords have been found in your VMware environment.</strong></p>
                                <hr>
                                <p class="mb-0">
                                    <strong>IMMEDIATE ACTION REQUIRED:</strong>
                                    <ul class="mt-2">
                                        <li>Review the detected items below</li>
                                        <li>Remove all clear text passwords from VM annotations and snapshot descriptions</li>
                                        <li>Rotate any exposed passwords immediately</li>
                                        <li>Implement secure password management practices</li>
                                    </ul>
                                </p>
                            </div>
                            <div class="alert alert-info" role="alert">
                                <strong><i class="fas fa-info-circle"></i> Privacy Notice:</strong>
                                This RVTools file was analyzed in memory only and has NOT been stored on our server.
                                However, the security risk remains in your VMware environment and in the file that was submitted.
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-danger" data-bs-dismiss="modal">
                                <i class="fas fa-check"></i> I Understand - Show Analysis
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // Add modal to page
        document.body.insertAdjacentHTML('beforeend', modalHTML);

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

        // Clean up modal after it's hidden
        document.getElementById('emergencyWarningModal').addEventListener('hidden.bs.modal', function () {
            this.remove();
        });
    }

    // Azure OpenAI Integration Functions
    let azureOpenAIConfigured = false;

    // Cumulative impact tracking
    let cumulativeImpact = {
        totalTokens: 0,
        inputTokens: 0,
        outputTokens: 0,
        totalCarbonGrams: 0,
        requests: 0
    };

    function checkAzureOpenAIStatus() {
        fetch('/api/azure-openai-status')
        .then(response => response.json())
        .then(data => {
            if (data.is_configured) {
                azureOpenAIConfigured = true;

                // Show disclaimer when AI is configured via environment variables
                document.querySelector('.ai-disclaimer').style.display = 'block';

                // Show AI suggestion buttons
                document.querySelectorAll('.ai-suggestion-btn').forEach(btn => {
                    btn.style.display = '';
                });

                console.log('Azure OpenAI configured via environment variables');
            }
        })
        .catch(error => {
            console.log('Azure OpenAI status check failed:', error);
            // Silently fail - this just means OpenAI is not available
        });
    }

    function updateCumulativeImpact(tokensUsed, inputTokens, outputTokens, carbonFootprint) {
        // Update cumulative values
        cumulativeImpact.totalTokens += tokensUsed || 0;
        cumulativeImpact.inputTokens += inputTokens || 0;
        cumulativeImpact.outputTokens += outputTokens || 0;
        cumulativeImpact.requests += 1;

        // Add carbon footprint to cumulative total (carbonFootprint is now just a float in grams)
        if (carbonFootprint && typeof carbonFootprint === 'number') {
            cumulativeImpact.totalCarbonGrams += carbonFootprint;
        }

        // Show the cumulative impact tracker
        const cumulativeDiv = document.getElementById('cumulative-ai-impact');
        if (cumulativeDiv) {
            cumulativeDiv.style.display = 'block';
        }

        // Update display values only if elements exist
        const cumulativeTokensEl = document.getElementById('cumulative-tokens');
        const cumulativeInputTokensEl = document.getElementById('cumulative-input-tokens');
        const cumulativeOutputTokensEl = document.getElementById('cumulative-output-tokens');
        const cumulativeRequestsEl = document.getElementById('cumulative-requests');
        const cumulativeCarbonEl = document.getElementById('cumulative-carbon');

        if (cumulativeTokensEl) {
            cumulativeTokensEl.textContent = cumulativeImpact.totalTokens.toLocaleString();
        }
        if (cumulativeInputTokensEl) {
            cumulativeInputTokensEl.textContent = cumulativeImpact.inputTokens.toLocaleString();
        }
        if (cumulativeOutputTokensEl) {
            cumulativeOutputTokensEl.textContent = cumulativeImpact.outputTokens.toLocaleString();
        }
        if (cumulativeRequestsEl) {
            cumulativeRequestsEl.textContent = cumulativeImpact.requests;
        }

        // Format cumulative carbon footprint
        if (cumulativeCarbonEl) {
            const formattedCarbon = formatCarbonFootprint(cumulativeImpact.totalCarbonGrams);
            cumulativeCarbonEl.textContent = formattedCarbon;
        }
    }

    function formatCarbonFootprint(totalGrams) {
        if (totalGrams < 0.001) {
            return Math.round(totalGrams * 1000000) + 'μg CO₂e';
        } else if (totalGrams < 1) {
            return (totalGrams * 1000).toFixed(2) + 'mg CO₂e';
        } else {
            return totalGrams.toFixed(3) + 'g CO₂e';
        }
    }

    function getAISuggestion(button) {
        if (!azureOpenAIConfigured) {
            showStatusMessage('Azure OpenAI is not configured via environment variables.', 'warning');
            return;
        }

        const riskName = button.getAttribute('data-risk-name');
        const riskDescription = button.getAttribute('data-risk-description');
        const riskLevel = button.getAttribute('data-risk-level');

        // Get risk data from global store instead of HTML attribute
        const riskData = riskDataStore[riskName] || [];

        // Show loading state
        button.disabled = true;
        button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating...';

        fetch('/api/ai-suggestion', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                risk_name: riskName,
                risk_description: riskDescription,
                risk_data: riskData,
                risk_level: riskLevel
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAISuggestion(riskName, data.suggestion, data.tokens_used, data.input_tokens, data.output_tokens, data.carbon_footprint);
            } else {
                showStatusMessage(`❌ Error generating AI suggestion: ${data.error}`, 'danger');
            }
        })
        .catch(error => {
            showStatusMessage(`❌ Error generating AI suggestion: ${error.message}`, 'danger');
        })
        .finally(() => {
            // Reset button state
            button.disabled = false;
            button.innerHTML = '<i class="fas fa-robot"></i> AI Suggestion';
        });
    }

    function showAISuggestion(riskName, suggestion, tokensUsed, inputTokens, outputTokens, carbonFootprint) {
        const suggestionArea = document.getElementById(`ai-suggestion-${riskName}`);
        const suggestionContent = document.getElementById(`ai-suggestion-content-${riskName}`);

        if (suggestionArea && suggestionContent) {
            // Update cumulative impact tracking
            updateCumulativeImpact(tokensUsed, inputTokens, outputTokens, carbonFootprint);

            // Clear previous content
            suggestionContent.innerHTML = '';

            // Add the AI suggestion content after the metrics
            const suggestionDiv = document.createElement('div');
            suggestionDiv.innerHTML = suggestion;
            suggestionContent.appendChild(suggestionDiv);

            suggestionArea.style.display = '';

            // Scroll to the suggestion
            suggestionArea.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    }

    function hideAISuggestion(riskName) {
        const suggestionArea = document.getElementById(`ai-suggestion-${riskName}`);
        if (suggestionArea) {
            suggestionArea.style.display = 'none';
        }
    }

    function showStatusMessage(message, type) {
        // Create a temporary alert div
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 1050; max-width: 400px;';
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;

        // Add to body
        document.body.appendChild(alertDiv);

        // Auto-remove after 5 seconds
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 5000);
    }
</script>

{% endblock %}
