<script>
    const ctx = document.getElementById('liveChart').getContext('2d');
    const nodeLabel = document.getElementById('selectedNodeLabel');
    const nodeSelector = document.getElementById('nodeSelector');

    let selectedNode = "5"; // Default node
    const historyLimit = 300; // Keep up to 300 points in memory (5 min if 1/s)
    const viewWindow = 60; // Show last 60 points on screen

    let allData = {
        labels: [],
        setpoint: [],
        feedback: [],
        flow: [],
        pressure: []
    };

    // Populate dropdown
    for (let i = 5; i <= 24; i++) {
        const option = document.createElement("option");
        option.value = i.toString();
        option.text = `Node ${i.toString().padStart(2, "0")}`;
        if (i === 5) option.selected = true;
        nodeSelector.appendChild(option);
    }

    nodeSelector.addEventListener("change", () => {
        selectedNode = nodeSelector.value;
        nodeLabel.textContent = selectedNode.padStart(2, "0");

        // Reset history for this new node
        allData = {
            labels: [],
            setpoint: [],
            feedback: [],
            flow: [],
            pressure: []
        };

        chart.data.labels = [];
        chart.data.datasets.forEach(ds => ds.data = []);
        chart.update();
    });

    const chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [
                { label: 'Setpoint', borderColor: 'blue', data: [], fill: false },
                { label: 'Feedback', borderColor: 'green', data: [], fill: false },
                { label: 'Flow (L/h)', borderColor: 'orange', data: [], fill: false },
                { label: 'Pressure (bar)', borderColor: 'red', data: [], fill: false }
            ]
        },
        options: {
            responsive: true,
            animation: false,
            scales: {
                x: { title: { display: true, text: 'Time' } },
                y: { title: { display: true, text: 'Value' } }
            }
        }
    });

    function fetchLiveData() {
        fetch("/data")
            .then(res => res.json())
            .then(data => {
                const now = new Date().toLocaleTimeString();
                const valve = data.valves?.[selectedNode] || {};
                const flow = data.flow?.["0x01"] || 0;
                const pressure = data.pressure?.["0x01"] || 0;

                // Append to history arrays
                allData.labels.push(now);
                allData.setpoint.push(valve.setpoint || 0);
                allData.feedback.push(valve.feedback || 0);
                allData.flow.push(flow);
                allData.pressure.push(pressure);

                // Trim history if needed
                if (allData.labels.length > historyLimit) {
                    allData.labels.shift();
                    allData.setpoint.shift();
                    allData.feedback.shift();
                    allData.flow.shift();
                    allData.pressure.shift();
                }

                // Extract last `viewWindow` points to show in graph
                const start = Math.max(0, allData.labels.length - viewWindow);

                chart.data.labels = allData.labels.slice(start);
                chart.data.datasets[0].data = allData.setpoint.slice(start);
                chart.data.datasets[1].data = allData.feedback.slice(start);
                chart.data.datasets[2].data = allData.flow.slice(start);
                chart.data.datasets[3].data = allData.pressure.slice(start);

                chart.update();
            });
    }

    setInterval(fetchLiveData, 1000);
</script>
