---
import WebsiteLayout from '@layouts/website/WebsiteLayout.astro';
import ConfirmPopup from '@components/popup/ConfirmPopup.svelte';
import Popup from '@components/popup/Popup.svelte';
import Select from '@components/input/Select.svelte';
import Textarea from '@components/input/Textarea.svelte';
import Input from '@components/input/Input.svelte';
---

<WebsiteLayout title="Feedback & Kontakt">
  <div class="flex justify-center items-center">
    <div class="mt-12 grid card w-11/12 xl:w-2/3 2xl:w-1/2 p-6 shadow-lg">
      <h2 class="text-3xl text-center">Kontakt</h2>
      <form id="feedback-contact">
        <div class="space-y-4 mt-6 mb-4">
          <Textarea id="content" label="Feedback" dynamicWidth required rows={10} />
          <Input id="email" type="email" label="Email" required />
        </div>
        <button id="send" class="btn">Senden</button>
      </form>
    </div>
  </div>
</WebsiteLayout>

<ConfirmPopup client:idle />
<Popup client:idle />

<script>
  import { actions } from 'astro:actions';
  import { confirmPopupState } from '@components/popup/ConfirmPopup';
  import { popupState } from '@components/popup/Popup';
  import { actionErrorPopup } from '../util/action';

  function setupForm() {
    const form = document.getElementById('feedback-contact') as HTMLFormElement;
    const content = document.getElementById('content') as HTMLTextAreaElement;
    const email = document.getElementById('email') as HTMLInputElement;

    // reset form on site (re-)load
    form.reset();

    form.addEventListener('submit', async (e) => {
      e.preventDefault();

      confirmPopupState.set({
        title: 'Kontaktanfrage abschicken',
        message: 'Soll die Kontaktanfrage abgeschickt werden?',
        onConfirm: () => sendContact().then(() => form.reset())
      });
    });

    const sendContact = async () => {
      const { error } = await actions.feedback.addWebsiteContact({
        content: content.value,
        email: email.value
      });

      if (error) {
        actionErrorPopup(error);
        throw null;
      }

      popupState.set({
        type: 'info',
        title: 'Kontaktanfrage abgeschickt',
        message:
          'Deine Kontaktanfrage wurde abgeschickt. Jemand aus dem Admin-Team wird sich nächstmöglich bei Dir melden.'
      });
    };
  }

  const pathname = document.location.pathname;
  document.addEventListener('astro:page-load', () => {
    if (document.location.pathname !== pathname) return;

    setupForm();
  });
</script>
