---
import type { HTMLAttributes } from "astro/types";
import { tv } from "tailwind-variants";

import { Button } from "@/components/starwind/button";
import { Card, CardContent } from "@/components/starwind/card";
import { Input } from "@/components/starwind/input";
import { Label } from "@/components/starwind/label";
import { Textarea } from "@/components/starwind/textarea";

interface Props extends HTMLAttributes<"section"> {
  badge: string;
  heading: string;
  description: string;
}

const sectionStyles = tv({
  base: "@container mx-auto w-full max-w-3xl px-4 py-24",
});

const {
  badge,
  heading,
  description,
  class: className,
  ...rest
} = Astro.props;
---

<section class={sectionStyles({ class: className })} {...rest}>
  <div class="text-center">
    <span
      class="bg-foreground/10 text-foreground inline-block rounded-full px-4 py-1.5 text-sm font-medium"
    >
      {badge}
    </span>
    <h2 class="font-heading mt-6 text-3xl font-bold tracking-tight @xl:text-4xl @3xl:text-5xl">
      {heading}
    </h2>
    <p class="text-muted-foreground mx-auto mt-4 max-w-xl text-lg">
      {description}
    </p>
  </div>

  <Card class="mt-10">
    <CardContent>
      <form
        class="space-y-6"
        id="contact-form-02"
        name="contact-form"
        method="post"
        action="/api/contact"
      >
        <div class="grid gap-6 @xl:grid-cols-2">
          <div class="flex flex-col gap-1">
            <Label for="contact-name-02">Nombre</Label>
            <Input id="contact-name-02" name="name" type="text" placeholder="Tu nombre" required />
          </div>
          <div class="flex flex-col gap-1">
            <Label for="contact-email-02">Correo</Label>
            <Input
              id="contact-email-02"
              name="email"
              type="email"
              placeholder="tu@correo.com"
              required
            />
          </div>
        </div>

        <div class="flex flex-col gap-1">
          <Label for="contact-subject-02">Asunto</Label>
          <Input
            id="contact-subject-02"
            name="subject"
            type="text"
            placeholder="¿En qué te ayudamos?"
            required
          />
        </div>

        <div class="flex flex-col gap-1">
          <Label for="contact-message-02">Mensaje</Label>
          <Textarea
            id="contact-message-02"
            name="message"
            placeholder="Cuéntanos un poco más..."
            rows={5}
            required
          />
        </div>

        <Button variant="default" type="submit" class="w-full @xl:w-auto">Enviar mensaje</Button>
      </form>
    </CardContent>
  </Card>

  <p class="text-muted-foreground mt-6 text-center text-sm" aria-live="polite" data-contact-status>
    Te respondemos por correo lo antes posible.
  </p>
</section>

<script>
  function handleFormSubmit() {
    const form = document.querySelector("#contact-form-02") as HTMLFormElement;
    const status = document.querySelector("[data-contact-status]") as HTMLElement | null;

    const updateStatus = (nextText: string) => {
      if (status) status.textContent = nextText;
    };

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

        updateStatus("Enviando...");

        try {
          const formData = new FormData(form);
          const response = await fetch(form.action, {
            method: "POST",
            body: formData,
            headers: {
              "Accept": "application/json",
            },
          });

          const contentType = response.headers.get("content-type") ?? "";
          const body: unknown = contentType.includes("application/json")
            ? await response.json()
            : await response.text();

          if (!response.ok) {
            const message =
              typeof body === "object" && body !== null && "error" in body
                ? "No se pudo enviar. Intenta de nuevo en un rato."
                : "No se pudo enviar. Intenta de nuevo en un rato.";
            updateStatus(message);
            return;
          }

          updateStatus("Listo. Recibimos tu mensaje. Gracias.");
          form.reset();
        } catch {
          updateStatus("No se pudo enviar. Revisa tu conexión e inténtalo de nuevo.");
        }
      });
    }
  }

  handleFormSubmit();

  document.addEventListener("astro:after-swap", handleFormSubmit);
</script>
