---
import Layout from "../layouts/Layout.astro";
import PageHeader from "../components/PageHeader.astro";
import { getSettings } from "../lib/directus";

const settings = await getSettings();
// Öffentliche CMS-URL für den Browser-Fetch — NICHT import.meta.env.DIRECTUS_URL,
// das ist beim Build (im Rebuild-Container) die interne Docker-Adresse.
const cmsPublicUrl = "https://cms.kitafreunde-regenbogen.de";
const contactEmail = settings?.contact_email ?? "info@kitafreunde-regenbogen.de";
---

<Layout title="Kontakt" description="Kontakt zum Kitafreunde Regenbogen e.V. — schreib uns, werde Mitglied oder bring eine Idee ein.">
  <PageHeader eyebrow="Kontakt">
    Schreib <span class="squiggle rainbow-text">uns.</span>
    <Fragment slot="lead">Fragen, Ideen, Mitmachen — wir freuen uns über jede Nachricht.</Fragment>
  </PageHeader>

  <section class="section pt-6">
    <div class="grid grid-cols-1 md:grid-cols-2 gap-12">
      <!-- Kontaktinfos -->
      <div class="space-y-6">
        <div class="card">
          <h2 class="font-bold mb-3">Kitafreunde Regenbogen e.V.</h2>
          <p class="text-sm text-[var(--color-text-muted)] leading-relaxed">
            c/o Kita Regenbogen<br>
            Keilerstraße 23<br>
            13503 Berlin
          </p>
        </div>
        {settings?.contact_email && (
          <div class="card">
            <h3 class="font-bold mb-2 text-sm uppercase tracking-wide text-[var(--color-text-muted)]">E-Mail</h3>
            <a href={`mailto:${settings.contact_email}`} class="text-[var(--color-primary)] font-medium text-lg">
              {settings.contact_email}
            </a>
          </div>
        )}
        <div class="card">
          <h3 class="font-bold mb-3">Mitglied werden?</h3>
          <p class="text-sm text-[var(--color-text-muted)] mb-3">
            Beitrittserklärung herunterladen und ausgefüllt im Kitabüro abgeben oder per Mail schicken.
          </p>
          <a href="/mitglied-werden" class="btn-primary text-sm">Zur Mitgliedschaftsseite →</a>
        </div>
        {(settings?.social_instagram || settings?.social_facebook) && (
          <div class="card">
            <h3 class="font-bold mb-3">Social Media</h3>
            <div class="flex gap-3">
              {settings.social_instagram && (
                <a href={`https://instagram.com/${settings.social_instagram}`} target="_blank" rel="noopener" class="btn-secondary text-sm">Instagram</a>
              )}
              {settings.social_facebook && (
                <a href={settings.social_facebook} target="_blank" rel="noopener" class="btn-secondary text-sm">Facebook</a>
              )}
            </div>
          </div>
        )}
      </div>

      <!-- Formular: sendet an Directus → Flow benachrichtigt den Verein per Mail -->
      <div class="card">
        <h2 class="font-bold mb-4">Direkte Nachricht</h2>
        <form
          id="contact-form"
          class="space-y-4"
          data-endpoint={`${cmsPublicUrl}/items/contact_messages`}
          data-fallback={contactEmail}
        >
          <div class="grid sm:grid-cols-2 gap-4">
            <div>
              <label for="cf-name" class="block text-sm font-medium mb-1">Name</label>
              <input id="cf-name" name="name" type="text" required autocomplete="name"
                class="w-full border border-[var(--color-border)] rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:border-[var(--color-primary)]" />
            </div>
            <div>
              <label for="cf-email" class="block text-sm font-medium mb-1">E-Mail</label>
              <input id="cf-email" name="email" type="email" required autocomplete="email"
                class="w-full border border-[var(--color-border)] rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:border-[var(--color-primary)]" />
            </div>
          </div>
          <div>
            <label for="cf-subject" class="block text-sm font-medium mb-1">Betreff</label>
            <select id="cf-subject" name="subject"
              class="w-full border border-[var(--color-border)] rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:border-[var(--color-primary)]">
              <option value="Mitgliedschaft">Mitgliedschaft</option>
              <option value="Projektidee">Projektidee einbringen</option>
              <option value="Spende / Kooperation">Spende / Kooperation</option>
              <option value="Presseanfrage">Presseanfrage</option>
              <option value="Allgemeine Anfrage">Allgemeine Anfrage</option>
            </select>
          </div>
          <div>
            <label for="cf-message" class="block text-sm font-medium mb-1">Nachricht</label>
            <textarea id="cf-message" name="message" rows="5" required
              class="w-full border border-[var(--color-border)] rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:border-[var(--color-primary)] resize-none"
              placeholder="Deine Nachricht..."></textarea>
          </div>
          <!-- Honeypot gegen Spam: für Menschen unsichtbar, bitte leer lassen -->
          <div aria-hidden="true" style="position:absolute; left:-9999px; width:1px; height:1px; overflow:hidden;">
            <label>Website<input type="text" name="website" tabindex="-1" autocomplete="off" /></label>
          </div>
          <button type="submit" id="cf-submit" class="btn-primary w-full justify-center">
            <span aria-hidden="true">✉</span> Nachricht senden
          </button>
          <p id="cf-status" class="text-sm hidden" role="status" aria-live="polite"></p>
        </form>
      </div>
    </div>
  </section>

  <script>
    const form = document.getElementById("contact-form");
    if (form) {
      const statusEl = document.getElementById("cf-status");
      const btn = document.getElementById("cf-submit");
      const setStatus = (msg, color) => {
        statusEl.innerHTML = msg;
        statusEl.style.color = color;
        statusEl.classList.remove("hidden");
      };
      form.addEventListener("submit", async (e) => {
        e.preventDefault();
        const data = new FormData(form);
        if (data.get("website")) return; // Honeypot: stiller Bot-Abbruch
        const endpoint = form.dataset.endpoint;
        const fallback = form.dataset.fallback;
        const payload = {
          name: (data.get("name") || "").toString().trim(),
          email: (data.get("email") || "").toString().trim(),
          subject: (data.get("subject") || "").toString(),
          message: (data.get("message") || "").toString().trim(),
        };
        btn.disabled = true;
        setStatus("Senden…", "var(--color-text-muted)");
        try {
          const res = await fetch(endpoint, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
          });
          if (!res.ok) throw new Error("HTTP " + res.status);
          form.reset();
          setStatus("Danke! Deine Nachricht ist angekommen — wir melden uns bald.", "var(--color-rb-green)");
        } catch (err) {
          setStatus(
            `Senden hat gerade nicht geklappt. Schreib uns gern direkt: <a class="underline font-medium" href="mailto:${fallback}">${fallback}</a>`,
            "var(--color-rb-red)",
          );
        } finally {
          btn.disabled = false;
        }
      });
    }
  </script>
</Layout>
