<div class="mail_form" style="width:80%;margin:0 auto 0 auto">
    <form method="post" name="inputForm" id="inputForm">
        <input type="hidden" name="mode" value="post">
        お名前<br>
        <input type="text" class="p-input" name="name" class="flat_input" style="width:30em;max-width:90%;"><br>
        メールアドレス<br>
        <input type="email" class="p-input" name="email" id="email" class="flat_input" style="width:30em;max-width:90%;"><br>
        コメント<br>
        <textarea name="comment" class="p-textarea" id="comment" class="flat_input" style="height:10em;width:90%;"></textarea>
        <input type="hidden" name="return_message" value="コメントを受け付けました。">
        <div class="control" style="text-align:center">
            <input type="submit" value="送信" class="p-button" id="submit_message">
        </div>
        <input type="text" name="title" style="font-size:0.4em;border:none;width:1em;height:1em;">
        {PPP:csrf}
    </form>
</div>
<script>
    document.addEventListener("DOMContentLoaded", async () => {

        async function postMessage(form_data) {
            let url = `${BASE_URL}/api/v2/messages`;
            let method = "POST";
            try {
                const response = await fetch(url, {
                    method: method,
                    body: form_data
                });
                if (!response.ok) {
                    throw new Error("Network response was not ok");
                }
                return await response.json();
            } catch (error) {
                console.error("Error:", error);
                throw error;
            }
        }

        Q("#submit_message").addEventListener("click", async function(e) {
            e.preventDefault();
            if (Q("#comment").value.trim() == "") {
                await showDialog("コメントを入力してください", "OK");
                return
            }
            let form_data = new FormData(Q("#inputForm"));
            postResult = await postMessage(form_data);
            console.log(postResult);
            let dialogText = "<p>" + postResult.message + "</p>";
            await showDialog(dialogText, "OK");
            if (postResult.success) {
                Q("#comment").value = "";
            }
        });
    });
</script>