/* global React, useReveal, SectionHeader, useState, fireConfetti, Logo, FooterCol */

/*
  KONTAKTFORMULAR — Formspree Backend
  ------------------------------------
  Damit das Formular wirklich eine E-Mail schickt, musst du einmal:
  1. Auf https://formspree.io/register kostenlosen Account anlegen
  2. Ein neues Formular für "hilfe@paulfaller.me" erstellen
  3. Deine persönliche Form-ID (sieht so aus: "xpzgqdnv") unten eintragen

  Ersetze: FORMSPREE_FORM_ID
  durch z.B.: xpzgqdnv
*/
const FORMSPREE_ENDPOINT = "https://formspree.io/f/FORMSPREE_FORM_ID";

function Contact() {
  const [submitted, setSubmitted] = useState(false);
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({ name: "", phone: "", email: "", problem: "" });

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.problem || !form.email) return;

    setLoading(true);
    try {
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: "POST",
        headers: {
          "Accept": "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          phone: form.phone || undefined,
          message: form.problem,
          _replyto: form.email,
          _subject: "Neue Anfrage – Paul.Tech von " + form.name,
        }),
      });

      if (res.ok) {
        setSubmitted(true);
        fireConfetti();
      } else {
        const data = await res.json().catch(() => ({}));
        if (data.errors) {
          alert("Fehler: " + data.errors.map((e) => e.message).join(", "));
        } else {
          alert("Etwas hat nicht geklappt — bitte schreiben Sie mir direkt per WhatsApp oder E-Mail.");
        }
      }
    } catch {
      alert("Netzwerkfehler — bitte schreiben Sie mir per WhatsApp oder E-Mail.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <section id="kontakt" className="section" style={{ background: "var(--bg-soft)", position: "relative", overflow: "hidden" }}>
      <div className="blob" style={{ width: 500, height: 500, background: "#c4b5fd", top: -100, left: -200, opacity: 0.25 }} />
      <div className="blob" style={{ width: 500, height: 500, background: "#f9a8d4", bottom: -200, right: -200, opacity: 0.25 }} />

      <div className="wrap" style={{ position: "relative" }}>
        <SectionHeader
          eyebrow="Kontakt"
          title={<>Problem? <span className="ital grad-text">Schreiben Sie mir.</span></>}
          sub="Am schnellsten geht es per WhatsApp — meist antworte ich innerhalb weniger Stunden."
        />

        <div className="contact-grid">
          <div className="contact-methods">
            <ContactCard
              type="whatsapp"
              title="WhatsApp"
              sub="Schnellste Antwort, oft minutenschnell"
              href="https://wa.me/4915122202137?text=Hallo%20Paul,%20ich%20brauche%20Hilfe%20mit..."
              cta="Chat öffnen"
            />
            <ContactCard
              type="mail"
              title="hilfe@paulfaller.me"
              sub="Antwort innerhalb von Stunden"
              href="mailto:hilfe@paulfaller.me"
              cta="E-Mail schreiben"
            />
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <InfoTile k="Antwortzeit" v="< 24 Stunden" />
              <InfoTile k="Gebiet" v="Radolfzell & Bodensee" />
            </div>
          </div>

          <form onSubmit={onSubmit} className="contact-form">
            {submitted ? (
              <div className="contact-success">
                <div style={{ fontSize: 64, marginBottom: 18 }}>✨</div>
                <h3 style={{ fontSize: 28, fontWeight: 600, letterSpacing: "-0.02em", marginBottom: 12 }}>Danke!</h3>
                <p style={{ color: "var(--muted)", fontSize: 16, lineHeight: 1.5, marginBottom: 24, maxWidth: 360 }}>
                  Ihre Anfrage ist angekommen. Ich melde mich so schnell wie möglich zurück.
                </p>
                <button type="button" onClick={() => { setSubmitted(false); setForm({ name: "", phone: "", email: "", problem: "" }); }} className="btn btn-ghost">
                  Neue Anfrage
                </button>
              </div>
            ) : (
              <>
                <h3 style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em", marginBottom: 6 }}>Anfrage senden</h3>
                <p style={{ fontSize: 14, color: "var(--muted)", marginBottom: 24 }}>Beschreiben Sie kurz Ihr Problem — ein Satz reicht oft schon.</p>

                <Field label="Name" id="name" value={form.name} onChange={(v) => setForm({ ...form, name: v })} required />
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  <Field label="E-Mail" id="email" type="email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} required />
                  <Field label="Telefon (optional)" id="phone" type="tel" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} />
                </div>
                <Field label="Was ist das Problem?" id="problem" textarea value={form.problem} onChange={(v) => setForm({ ...form, problem: v })} required placeholder="z.B. Mein WLAN funktioniert nicht im Schlafzimmer..." />

                <button
                  type="submit"
                  className="btn btn-grad btn-lg"
                  disabled={loading}
                  style={{ marginTop: 8, width: "100%", justifyContent: "center", opacity: loading ? 0.75 : 1, cursor: loading ? "wait" : "pointer" }}
                >
                  {loading ? "Wird gesendet…" : "Anfrage abschicken"}
                  {!loading && (
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                      <path d="M3 8h10m0 0L8.5 3.5M13 8l-4.5 4.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  )}
                </button>
                <p style={{ fontSize: 12, color: "var(--muted)", marginTop: 14, textAlign: "center" }}>
                  Ihre Daten werden nur verwendet um Ihre Anfrage zu beantworten.
                </p>
              </>
            )}
          </form>
        </div>
      </div>

      <style>{`
        .contact-grid {
          display: grid;
          grid-template-columns: 1fr 1.2fr;
          gap: 24px;
          align-items: stretch;
        }
        @media (max-width: 900px) { .contact-grid { grid-template-columns: 1fr; } }
        .contact-methods { display: flex; flex-direction: column; gap: 12px; }
        .contact-form {
          background: #fff;
          border: 1px solid var(--line);
          border-radius: 24px;
          padding: 36px;
          box-shadow: 0 12px 40px rgba(10,10,10,0.04);
        }
        @media (max-width: 600px) { .contact-form { padding: 24px; } }
        .contact-success { text-align: center; padding: 40px 20px; }
      `}</style>
    </section>
  );
}

function ContactCard({ type, title, sub, href }) {
  const isWhatsApp = type === "whatsapp";
  const icon = isWhatsApp ? (
    <svg width="28" height="28" viewBox="0 0 32 32" fill="#fff">
      <path d="M16 3C8.8 3 3 8.8 3 16c0 2.3.6 4.5 1.7 6.4L3 29l6.8-1.7c1.8 1 3.9 1.5 6.2 1.5 7.2 0 13-5.8 13-13S23.2 3 16 3Zm7.5 18.4c-.3.9-1.8 1.7-2.5 1.8-.7.1-1.5.4-5.2-1-4.4-1.7-7.2-6.2-7.4-6.5-.2-.3-1.7-2.3-1.7-4.4 0-2.1 1.1-3.1 1.5-3.5.4-.4.8-.5 1.1-.5h.8c.3 0 .6 0 .9.7l1.4 3.4c.1.2.1.5-.1.7l-.6.7-.4.5c-.2.3-.4.5-.2.9.2.4.9 1.5 1.9 2.5 1.4 1.2 2.5 1.6 2.9 1.8.4.2.6.2.8-.1l1.2-1.4c.3-.3.6-.3.9-.2l3.1 1.5c.4.2.6.3.7.4.1.3.1 1 0 1.8Z" />
    </svg>
  ) : (
    <svg width="28" height="28" viewBox="0 0 32 32" fill="none">
      <rect x="3" y="6" width="26" height="20" rx="2" fill="#fff" />
      <path d="M3 8l13 9 13-9" stroke="#7c3aed" strokeWidth="2" strokeLinejoin="round" />
    </svg>
  );
  return (
    <a
      href={href}
      target={isWhatsApp ? "_blank" : undefined}
      rel="noopener"
      style={{
        display: "flex", gap: 16, alignItems: "center",
        padding: 24, background: "#fff",
        border: "1px solid var(--line)", borderRadius: 20,
        transition: "all .3s ease",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 12px 32px rgba(10,10,10,0.06)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = "none"; }}
    >
      <div style={{
        width: 56, height: 56, borderRadius: 16, flexShrink: 0,
        background: isWhatsApp ? "#25D366" : "var(--grad)",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        {icon}
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 600, fontSize: 17, letterSpacing: "-0.01em" }}>{title}</div>
        <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 2 }}>{sub}</div>
      </div>
      <svg width="20" height="20" viewBox="0 0 16 16" fill="none">
        <path d="M3 8h10m0 0L8.5 3.5M13 8l-4.5 4.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    </a>
  );
}

function InfoTile({ k, v }) {
  return (
    <div style={{ padding: 18, background: "#fff", border: "1px solid var(--line)", borderRadius: 16 }}>
      <div style={{ fontSize: 12, color: "var(--muted)", letterSpacing: "0.04em", textTransform: "uppercase", fontWeight: 500 }}>{k}</div>
      <div style={{ fontSize: 16, fontWeight: 600, marginTop: 4, letterSpacing: "-0.01em" }}>{v}</div>
    </div>
  );
}

function Field({ label, id, value, onChange, type = "text", textarea, required, placeholder }) {
  const [focused, setFocused] = useState(false);
  const filled = value && value.length > 0;
  const active = focused || filled;
  return (
    <div style={{ marginBottom: 14, position: "relative" }}>
      <label htmlFor={id} style={{
        position: "absolute",
        left: 16,
        top: active ? 8 : (textarea ? 16 : 18),
        fontSize: active ? 11 : 14,
        color: focused ? "var(--violet-deep)" : "var(--muted)",
        fontWeight: active ? 600 : 400,
        letterSpacing: active ? "0.02em" : "0",
        textTransform: active ? "uppercase" : "none",
        transition: "all .2s cubic-bezier(.22,.61,.36,1)",
        pointerEvents: "none",
      }}>{label}{required && " *"}</label>
      {textarea ? (
        <textarea
          id={id}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          required={required}
          rows={4}
          placeholder={active ? placeholder : ""}
          style={fieldStyle(focused, true)}
        />
      ) : (
        <input
          id={id}
          type={type}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          required={required}
          style={fieldStyle(focused, false)}
        />
      )}
    </div>
  );
}

function fieldStyle(focused, textarea) {
  return {
    width: "100%",
    padding: textarea ? "26px 16px 12px" : "24px 16px 10px",
    border: focused ? "1.5px solid var(--violet)" : "1.5px solid var(--line)",
    borderRadius: 12,
    fontSize: 15,
    background: "#fff",
    transition: "border-color .2s ease, box-shadow .2s ease",
    boxShadow: focused ? "0 0 0 4px rgba(124,58,237,0.12)" : "none",
    outline: "none",
    fontFamily: "inherit",
    resize: textarea ? "vertical" : "none",
    minHeight: textarea ? 120 : "auto",
  };
}

function Footer() {
  return (
    <footer style={{ padding: "48px 0 32px", borderTop: "1px solid var(--line)", background: "#fff" }}>
      <div className="wrap" style={{ display: "flex", flexWrap: "wrap", justifyContent: "space-between", alignItems: "flex-start", gap: 24 }}>
        <div style={{ maxWidth: 340 }}>
          <Logo size={20} />
          <p style={{ marginTop: 12, fontSize: 13, color: "var(--muted)", lineHeight: 1.5 }}>
            Tech-Hilfe per Video-Chat — von überall. Oder vor Ort am Bodensee. Ab 7,90 € pauschal, nur zahlen wenn gelöst.
          </p>
        </div>

        <div style={{ display: "flex", gap: 48, flexWrap: "wrap" }}>
          <FooterCol title="Hilfe">
            <a href="index.html#leistungen">Leistungen</a>
            <a href="index.html#problem">Problem-Finder</a>
            <a href="index.html#ablauf">So geht's</a>
            <a href="preise.html">Preise</a>
            <a href="index.html#faq">FAQ</a>
          </FooterCol>
          <FooterCol title="Kontakt">
            <a href="kontakt.html">Termin anfragen</a>
            <a href="https://wa.me/4915122202137" target="_blank" rel="noopener">WhatsApp</a>
            <a href="mailto:hilfe@paulfaller.me">hilfe@paulfaller.me</a>
            <span style={{ color: "var(--muted)", fontSize: 13 }}>Radolfzell · Bodensee</span>
          </FooterCol>
          <FooterCol title="Rechtliches">
            <a href="impressum.html">Impressum</a>
            <a href="datenschutz.html">Datenschutz</a>
          </FooterCol>
        </div>
      </div>

      <div className="wrap" style={{ marginTop: 32, paddingTop: 20, borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
        <span style={{ fontSize: 12, color: "var(--muted)" }}>© 2026 Paul Faller · Radolfzell am Bodensee</span>
        <span style={{ fontSize: 12, color: "var(--muted)" }}>Mit ❤️ am Bodensee gebaut</span>
      </div>

      <style>{`
        footer a { font-size: 13px; color: var(--ink-2); transition: color .2s; }
        footer a:hover { color: var(--violet-deep); }
      `}</style>
    </footer>
  );
}

function FooterCol({ title, children }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      <h4 style={{ fontSize: 13, fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 6 }}>{title}</h4>
      {children}
    </div>
  );
}

Object.assign(window, { Contact, Footer, FooterCol, ContactCard, InfoTile, Field, FORMSPREE_ENDPOINT });
