/* @jsx React.createElement */
const { useState: useStateCta, useEffect: useEffectCta } = React;

const WHATSAPP_GROUP_URL = "https://chat.whatsapp.com/E1iQGAiwPYXBiyfRFrexgg";
const QR_IMG_URL = `https://api.qrserver.com/v1/create-qr-code/?size=440x440&margin=8&color=111111&bgcolor=FAF8F6&data=${encodeURIComponent(WHATSAPP_GROUP_URL)}`;

// Web3Forms access key. Free tier, 250 submissions/month. Public key,
// safe to commit (Web3Forms keys are designed for client-side use).
// Recipient address is configured in the Web3Forms dashboard.
const WEB3FORMS_ACCESS_KEY = "df1f8860-8191-4379-b4f8-1976bfbbecca";

// Web3Forms aggressively blocks browser fetch (CORS preflight 403 +
// Cross-Origin-Resource-Policy: same-origin). Only native HTML form
// submit works. We pass a redirect URL so the user comes back to
// /anfragen?sent=1 and sees an in-brand thank-you panel.

function readSentParam() {
  if (typeof window === "undefined") return false;
  return new URLSearchParams(window.location.search).has("sent");
}

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

function ContactCTA() {
  const [tab, setTab] = useStateCta(() => (readSentParam() ? "form" : "wa"));
  const [status, setStatus] = useStateCta(() => (readSentParam() ? "sent" : "idle"));
  const [errors, setErrors] = useStateCta({});

  // Strip the ?sent=1 from the URL so a reload does not keep showing
  // the thank-you panel.
  useEffectCta(() => {
    if (readSentParam() && typeof window !== "undefined") {
      const cleanUrl = window.location.pathname + window.location.hash;
      window.history.replaceState({}, "", cleanUrl);
    }
  }, []);

  const redirectUrl = typeof window !== "undefined"
    ? `${window.location.origin}/anfragen?sent=1`
    : "https://orientierungsstark.vercel.app/anfragen?sent=1";

  // The form-name attributes use deutsche Klartext-Labels because
  // Web3Forms renders them 1:1 as headings in the e-mail Corinne
  // receives. Internal error keys stay short so the JS stays readable.
  const FORM_NAMES = { name: "Name", email: "E-Mail", hund: "Dein Hund", message: "Anliegen" };

  // Inline validation. Returns true if the form is valid; otherwise
  // populates `errors` and prevents the native submit so the user
  // never sees the browser's default validation toast.
  const onSubmit = (e) => {
    const formEl = e.currentTarget;
    const get = (key) => (formEl.elements.namedItem(FORM_NAMES[key]).value || "").trim();
    const name = get("name");
    const email = get("email");
    const message = get("message");

    const next = {};
    if (!name) next.name = "Bitte gib deinen Namen an.";
    if (!email) next.email = "Bitte gib deine E-Mail-Adresse an.";
    else if (!EMAIL_RE.test(email)) next.email = "Diese E-Mail-Adresse sieht nicht gültig aus.";
    if (!message) next.message = "Schreib mir kurz, was bei euch los ist.";

    if (Object.keys(next).length > 0) {
      e.preventDefault();
      setErrors(next);
      // Scroll the first error field into view so mobile users see it
      const firstField = Object.keys(next)[0];
      const target = formEl.elements.namedItem(FORM_NAMES[firstField]);
      if (target && target.focus) target.focus();
      return;
    }
    // Valid: let the native form submit happen (no preventDefault).
  };

  const clearError = (field) => {
    if (!errors[field]) return;
    const next = { ...errors };
    delete next[field];
    setErrors(next);
  };

  return (
    <section id="kontakt" style={{ background: "var(--os-paper-2)", color: "var(--os-black)", borderBottom: "1px solid var(--border-1)" }}>
      <div style={{ maxWidth: 1240, margin: "0 auto", padding: "112px 32px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 80, alignItems: "start" }}>
        <div>
          <div style={{ fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 600, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--os-red-485)" }}>Anfragen</div>
          <h2 style={{ fontFamily: "var(--font-sans)", fontWeight: 300, fontSize: 56, lineHeight: 1.05, letterSpacing: "-0.015em", margin: "16px 0 0", color: "var(--os-black)" }}>
            Schreib mir.<br />
            <span style={{ fontWeight: 600 }}>Lass es uns angehen…</span>
          </h2>
          <div style={{ height: 2, width: 64, background: "var(--os-red-485)", margin: "32px 0 0" }} />
          <div style={{ marginTop: 32, display: "flex", flexDirection: "column", gap: 14, fontFamily: "var(--font-sans)", fontSize: 15, color: "var(--fg-1)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}><i data-lucide="map-pin" style={{ width: 18, height: 18, color: "var(--os-red-485)" }}></i>Widestrasse 3, 8580 Hefenhofen</div>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}><i data-lucide="mail" style={{ width: 18, height: 18, color: "var(--os-red-485)" }}></i>c.p.hundeschule@gmail.com</div>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}><i data-lucide="phone" style={{ width: 18, height: 18, color: "var(--os-red-485)" }}></i>079 / 843 61 83</div>
          </div>
        </div>
        <div style={{ background: "var(--os-white)", color: "var(--os-black)", padding: 36, border: "1px solid var(--border-1)" }}>
          <div style={{ display: "flex", gap: 0, marginBottom: 28, borderBottom: "1px solid var(--border-1)" }}>
            <button onClick={() => setTab("wa")} style={{
              flex: 1, padding: "14px 8px", background: "transparent", border: "none",
              borderBottom: tab === "wa" ? "2px solid var(--os-red-485)" : "2px solid transparent",
              fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 13, cursor: "pointer",
              color: tab === "wa" ? "var(--os-black)" : "var(--fg-3)", letterSpacing: "0.16em", textTransform: "uppercase",
            }}>WhatsApp</button>
            <button onClick={() => setTab("form")} style={{
              flex: 1, padding: "14px 8px", background: "transparent", border: "none",
              borderBottom: tab === "form" ? "2px solid var(--os-red-485)" : "2px solid transparent",
              fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 13, cursor: "pointer",
              color: tab === "form" ? "var(--os-black)" : "var(--fg-3)", letterSpacing: "0.16em", textTransform: "uppercase",
            }}>Kontaktformular</button>
          </div>
          <div key={tab + ":" + status} className="os-tab-fade">
          {tab === "form" ? (
            status === "sent" ? (
              <div style={{ padding: "48px 16px", textAlign: "center" }}>
                <div style={{ width: 56, height: 56, margin: "0 auto", borderRadius: "50%", background: "var(--os-red-485)", color: "var(--os-white)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <i data-lucide="check" style={{ width: 28, height: 28, strokeWidth: 2 }}></i>
                </div>
                <h3 style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 22, color: "var(--os-black)", margin: "20px 0 10px" }}>
                  Vielen Dank.
                </h3>
                <p style={{ fontFamily: "var(--font-serif)", fontSize: 16, lineHeight: 1.6, color: "var(--fg-2)", margin: 0, maxWidth: "30ch", marginLeft: "auto", marginRight: "auto" }}>
                  Deine Nachricht ist bei mir angekommen. Ich melde mich zeitnah.
                </p>
                <button onClick={() => setStatus("idle")} style={{
                  marginTop: 28, background: "transparent", border: "1px solid var(--os-black)",
                  padding: "12px 22px", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 13,
                  letterSpacing: "0.04em", textTransform: "uppercase", cursor: "pointer", borderRadius: 2,
                  color: "var(--os-black)",
                }}>Weitere Nachricht senden</button>
              </div>
            ) : (
              <form action="https://api.web3forms.com/submit" method="POST" noValidate onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                <input type="hidden" name="access_key" value={WEB3FORMS_ACCESS_KEY} />
                <input type="hidden" name="subject" value="Neue Anfrage · Orientierungsstark Webseite" />
                <input type="hidden" name="from_name" value="Orientierungsstark Webseite" />
                <input type="hidden" name="redirect" value={redirectUrl} />
                <Field label="Dein Name" name={FORM_NAMES.name} required error={errors.name} onInput={() => clearError("name")} />
                <Field label="E-Mail" name={FORM_NAMES.email} type="email" required error={errors.email} onInput={() => clearError("email")} />
                <Field label="Dein Hund (Name, Rasse, Alter)" name={FORM_NAMES.hund} />
                <div>
                  <label style={fieldLabel}>Worum geht es? *</label>
                  <textarea
                    name={FORM_NAMES.message}
                    rows="4"
                    onInput={() => clearError("message")}
                    style={{
                      ...fieldInput, resize: "none",
                      borderColor: errors.message ? "var(--os-red-485)" : "var(--border-1)",
                    }}
                    placeholder="Erzähl mir kurz, was bei euch los ist."
                  />
                  {errors.message && <FieldError text={errors.message} />}
                </div>
                {/* Honeypot: hidden from humans, often filled by bots */}
                <input type="checkbox" name="botcheck" tabIndex="-1" autoComplete="off" style={{ display: "none" }} />
                <button type="submit" className="os-cta-red" style={{
                  background: "var(--os-red-485)", color: "var(--os-white)", border: 0,
                  padding: "16px 22px", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 15,
                  borderRadius: 2, cursor: "pointer", marginTop: 8, letterSpacing: "0.02em",
                  display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
                }}>
                  Nachricht senden <i data-lucide="arrow-right" style={{ width: 16, height: 16 }}></i>
                </button>
              </form>
            )
          ) : (
            <div style={{ textAlign: "center", padding: "16px 0 4px" }}>
              <div style={{ width: 232, height: 232, margin: "0 auto", padding: 6, background: "var(--os-paper)", border: "1px solid var(--border-1)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <img src={QR_IMG_URL} alt="QR-Code WhatsApp-Gruppe Orientierungsstark" style={{ width: 220, height: 220, display: "block" }} />
              </div>
              <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--fg-2)", marginTop: 18, lineHeight: 1.6 }}>
                QR scannen für Zutritt zur<br /><strong style={{ color: "var(--os-black)" }}>WhatsApp-Gruppe</strong>
              </div>
              <a href={WHATSAPP_GROUP_URL} target="_blank" rel="noopener" className="os-cta-black" style={{ display: "inline-flex", alignItems: "center", gap: 10, marginTop: 22, background: "var(--os-black)", color: "var(--os-white)", padding: "14px 24px", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 14, textDecoration: "none", borderRadius: 2 }}>
                <i data-lucide="message-circle" style={{ width: 16, height: 16 }}></i>WhatsApp-Gruppe öffnen
              </a>
            </div>
          )}
          </div>
        </div>
      </div>
    </section>
  );
}

const fieldLabel = { display: "block", fontFamily: "var(--font-sans)", fontSize: 11, fontWeight: 600, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--fg-2)", marginBottom: 8 };
const fieldInput = { width: "100%", padding: "12px 14px", border: "1px solid var(--border-1)", borderRadius: 2, fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--os-black)", background: "var(--os-white)", boxSizing: "border-box", transition: "border-color 200ms var(--ease-standard)" };

function FieldError({ text }) {
  return (
    <div className="os-field-error" style={{
      display: "flex", alignItems: "center", gap: 6,
      marginTop: 8,
      fontFamily: "var(--font-sans)", fontSize: 12, color: "var(--os-red-485)",
      letterSpacing: "0.02em",
    }}>
      <i data-lucide="alert-circle" style={{ width: 13, height: 13, strokeWidth: 2 }}></i>
      {text}
    </div>
  );
}

function Field({ label, name, type = "text", required = false, error, onInput }) {
  return (
    <div>
      <label style={fieldLabel}>{label}{required && " *"}</label>
      <input
        type={type}
        name={name}
        onInput={onInput}
        style={{
          ...fieldInput,
          borderColor: error ? "var(--os-red-485)" : "var(--border-1)",
        }}
      />
      {error && <FieldError text={error} />}
    </div>
  );
}

window.ContactCTA = ContactCTA;
