<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <title></title>
</head>

<body>

    <header class="bg-primary text-white text-center py-2">
        <h1 class="display-4">{{params.title}}</h1>
        <p class="lead">{{params.subtitle}}</p>
    </header>


    <div class="container p-3">
        <form id="userForm" name="form1" onChange="getFormValues('form1')">
            <div class="mb-3">
                <label for="dropdown" class="form-label lead">{{params.menu_label}}</label>
                <select class="form-select" id="dropdown" name="dropdown">
                    {% for opt in params.options %}
                    <option value="{{opt.code}}">{{opt.desc}}</option>
                    {% endfor %}
                </select>
            </div>
        </form>
        <div>
            <!-- Main Content Area -->
            <p class="lead">{{params.content}}</p>
            <div id="displayDiv"></div>
        </div>
        <div id="graph"></div>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>
    <script>

        function getFormValues(f) {
            const form = document.forms.namedItem(f);
            const formData = new FormData(form);
            const value = Object.fromEntries(formData.entries());
            postJSON(value);
        }

        async function postJSON(data) {
            try {
                const response = await fetch("/callback", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify(data),
                });

                const result = await response.json();
                console.log("Success:");//, result);

                drawGraph(result);
            }
            catch (error) {
                console.error("Error:", error);
            }
        }

        function drawGraph(graph) {
            var figure = JSON.parse(graph);
            console.log(figure);
            Plotly.newPlot('graph', figure, {});
        }

        getFormValues('form1');

    </script>
</body>

</html>