/**
 * MVGAL Web Dashboard
 *
 * SPDX-License-Identifier: MIT
 *
 * A web-based monitoring dashboard for MVGAL.
 * Compiled to JavaScript for browser use and WebAssembly for Emscripten.
 */

import js.html.CanvasElement;
import js.html.CanvasRenderingContext2D;
import js.html.DivElement;
import js.html.Element;

// GPU Metrics structure
typedef struct {
    index: Int;
    name: String;
    vendor: String;
    vram_mb: Float;
    utilization: Int;
    temperature_c: Int;
    power_w: Float;
    clock_mhz: Int;
}

// Main Dashboard class
class MvgalDashboard {
    var container: DivElement;
    var metrics: Map<String, Dynamic>;
    var refreshInterval: Int;

    public function new(containerId: String) {
        container = js.Browser.document.getElementById(containerId);
        metrics = new Map();
        refreshInterval = 1000; // ms

        this.init();
        this.startRefresh();
    }

    function init(): Void {
        this.renderHeader();
        this.renderGpuGrid();
        this.renderControls();
        this.renderChart_placeholder();
    }

    function renderHeader(): Void {
        var header = js.Browser.document.createDivElement();
        header.className = "header";
        header.innerHTML = '<h1>MVGAL Multi-GPU Dashboard</h1>';
        container.appendChild(header);
    }

    function renderGpuGrid(): Void {
        var grid = js.Browser.document.createDivElement();
        grid.className = "gpu-grid";
        grid.id = "gpu-grid";
        container.appendChild(grid);
    }

    function renderControls(): Void {
        var controls = js.Browser.document.createDivElement();
        controls.className = "controls";
        controls.innerHTML = '
            <div class="scheduler-control">
                <label>Scheduling Mode:</label>
                <select id="scheduler-mode">
                    <option value="afr">AFR</option>
                    <option value="sfr">SFR</option>
                    <option value="hybrid">Hybrid</option>
                    <option value="static">Static</option>
                </select>
            </div>
            <div class="power-control">
                <label>Power Profile:</label>
                <select id="power-profile">
                    <option value="gaming">Gaming</option>
                    <option value="performance">Performance</option>
                    <option value="power_save">Power Save</option>
                </select>
            </div>
        ';
        container.appendChild(controls);
    }

    function renderChart_placeholder(): Void {
        var chart = js.Browser.document.createDivElement();
        chart.className = "chart-placeholder";
        chart.innerHTML = '<canvas id="metrics-chart" width="400" height="200"></canvas>';
        container.appendChild(chart);
    }

    function startRefresh(): Void {
        haxe.Timer.interval(this.refresh.bind(this), refreshInterval);
    }

    function refresh(): Void {
        this.fetchMetrics();
        this.updateGpuDisplay();
        this.updateChart();
    }

    function fetchMetrics(): Void {
        // Fetch from REST API
        var xhr = new js.xml.HttpRequest();
        xhr.onLoad.add(function(_) {
            var response = xhr.responseText;
            this.parseMetrics(response);
        });
        xhr.onError.add(function(_) {
            trace("Failed to fetch metrics");
        });
        xhr.open("GET", "/api/v1/gpus");
        xhr.send();
    }

    function parseMetrics(jsonStr: String): Void {
        try {
            var data = haxe.Json.parse(jsonStr);
            for (gpu in data.gpus) {
                metrics.set(gpu.id, gpu);
            }
        } catch (e) {
            trace("Failed to parse metrics: " + e);
        }
    }

    function updateGpuDisplay(): Void {
        var grid = js.Browser.document.getElementById("gpu-grid");
        if (grid == null) return;

        grid.innerHTML = "";

        for (key in metrics.keys()) {
            var gpu = metrics.get(key);
            var card = this.createGpuCard(gpu);
            grid.appendChild(card);
        }
    }

    function createGpuCard(gpu: Dynamic): DivElement {
        var card = js.Browser.document.createDivElement();
        card.className = "gpu-card";

        var utilPercent = gpu.utilization;
        var vramPercent = (gpu.vram_used / gpu.vram_total) * 100;

        card.innerHTML = '
            <div class="gpu-header">
                <h3>' + gpu.name + '</h3>
                <span class="vendor">' + gpu.vendor + '</span>
            </div>
            <div class="gpu-metrics">
                <div class="metric">
                    <label>Utilization:</label>
                    <div class="bar-container">
                        <div class="bar" style="width: ' + utilPercent + '%"></div>
                    </div>
                    <span>' + utilPercent + '%</span>
                </div>
                <div class="metric">
                    <label>VRAM:</label>
                    <div class="bar-container">
                        <div class="bar" style="width: ' + vramPercent + '%"></div>
                    </div>
                    <span>' + gpu.vram_used + ' / ' + gpu.vram_total + ' MB</span>
                </div>
                <div class="metric">
                    <label>Temperature:</label>
                    <span>' + gpu.temperature + '°C</span>
                </div>
                <div class="metric">
                    <label>Power:</label>
                    <span>' + gpu.power + ' W</span>
                </div>
            </div>
        ';

        return card;
    }

    function updateChart(): Void {
        // Update chart with utilization history
    }
}
