<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
    <dialog layout:fragment="overlay" th:if="${@permissionService.canViewRequests()}" id="language-overlay" class="dialog" data-closable>
        <form class="flex vertical p-7" id="profile-update-form">
            <h2 class="font-500 underlined">Languages</h2>

            <p>Select the language(s) in which you wish to handle requests.</p>

            <div class="grid col-2 align-center gap-3" style="--col-1: minmax(0, 8rem)">
                <label for="languages">Language(s)</label>
                <select id="languages" name="language" class="textfield">
                    <option value="ENGLISH_ONLY" th:selected="not ${#profile.language.name() == 'ENGLISH_ONLY'}">English only</option>
                    <option value="ANY" th:selected="${#profile.language.name() == 'ANY'}">English and Dutch</option>
                </select>
            </div>

            <div class="flex space-between">
                <button type="button" class="button p-less" data-style="outlined" data-cancel>Close</button>
                <button type="submit" class="button p-less">Update</button>
            </div>
        </form>

        <script th:inline="javascript">
            //<![CDATA[
            const userLanguage = /*[[${#profile.language.name()}]]*/ "ENGLISH_ONLY";
            //]]>
        </script>
        <script>
            document.addEventListener("DOMContentLoaded", function () {
                const form = document.getElementById("profile-update-form");
                form.addEventListener("submit", function (event) {
                    event.preventDefault();
                    fetch("/profile/update", {
                        method: "POST",
                        headers: {
                            "X-CSRF-TOKEN": csrfToken,
                            "Content-Type": "application/json",
                        },
                        body: JSON.stringify(Object.fromEntries(new FormData(form).entries())),
                    })
                        .then(res => res.text())
                        .then(() => window.location.reload())
                        .catch(() => alert("Failed to update language preference"));
                });
            });
        </script>
    </dialog>
</html>
