<script>
  import { goto } from "$app/navigation";
  import { error } from "@sveltejs/kit";

  let formData = { title: "", content: "" };

  async function submitNote(event) {
    const payload = {
      title: formData.title,
      content: formData.content,
    };

    const response = await fetch(
      "http://no08g0o48sc8w0woowwsskos.134.255.231.190.sslip.io/api/note",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      },
    );

    if (response.ok) {
      goto("/");
    } else {
      error(500, "Bad Request");
    }
  }
</script>

<div class="container">
  <h1 class="title">Erstelle eine Neue Notiz</h1>

  <form on:submit|preventDefault={submitNote}>
    <fieldset>
      <label>
        Titel
        <input name="title" placeholder="Titel" bind:value={formData.title} />
      </label>
      <label>
        Inhalt
        <textarea
          name="content"
          placeholder="Inhalt"
          bind:value={formData.content}
        >
        </textarea>
      </label>
    </fieldset>

    <input type="submit" value="Erstellen" />
  </form>
</div>
