function ContactModal() {
  const [open, setOpen] = React.useState(false);
  const [status, setStatus] = React.useState("idle"); // idle | submitting | success | error
  const [form, setForm] = React.useState({
    name: "", email: "", phone: "",
    boatType: "", boatName: "", message: "",
  });

  React.useEffect(() => {
    const onOpen = () => { setOpen(true); setStatus("idle"); };
    window.addEventListener('open-contact', onOpen);
    return () => window.removeEventListener('open-contact', onOpen);
  }, []);

  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = prev; window.removeEventListener('keydown', onKey); };
  }, [open]);

  function update(k) { return (e) => setForm(f => ({ ...f, [k]: e.target.value })); }

  async function submit(e) {
    e.preventDefault();
    setStatus("submitting");
    const fd = new FormData();
    fd.append("Name", form.name);
    fd.append("E-Mail", form.email);
    fd.append("Telefon", form.phone);
    fd.append("Bootstyp", form.boatType);
    fd.append("Bootsname", form.boatName);
    fd.append("Nachricht", form.message);
    // honey-pot
    if (e.target._honey && e.target._honey.value) { setStatus("idle"); return; }
    fd.append("_honey", "");
    try {
      const res = await fetch("kontakt.php", {
        method: "POST",
        headers: { Accept: "application/json" },
        body: fd,
      });
      const data = await res.json().catch(()=>({}));
      if (res.ok && data.ok) setStatus("success");
      else setStatus("error");
    } catch (err) {
      setStatus("error");
    }
  }

  if (!open) return null;

  const inputStyle = {
    width:"100%", padding:"14px 16px", border:"1px solid var(--line)",
    background:"var(--paper)", color:"var(--ink)",
    fontFamily:"'Cormorant Garamond', serif", fontSize: 17, lineHeight: 1.3,
    outline:"none", borderRadius: 0,
  };
  const labelStyle = {
    fontFamily:"'Inter', sans-serif", fontSize: 10, letterSpacing:"0.28em",
    textTransform:"uppercase", color:"var(--gold)", fontWeight: 600,
    marginBottom: 8, display:"block",
  };

  return (
    <div onClick={(e)=>{ if (e.target === e.currentTarget) setOpen(false); }} style={{
      position:"fixed", inset:0, zIndex: 200,
      background:"rgba(10,24,40,0.66)", backdropFilter:"blur(6px)",
      display:"flex", alignItems:"center", justifyContent:"center",
      padding: "24px",
      overflowY:"auto",
    }}>
      <div className="contact-modal" style={{
        background:"var(--paper)", maxWidth: 640, width:"100%",
        border:"1px solid var(--gold)",
        boxShadow:"0 40px 100px -30px rgba(10,24,40,0.5)",
        position:"relative",
        maxHeight: "92vh",
        display:"flex", flexDirection:"column",
      }}>
        <button onClick={()=>setOpen(false)} aria-label="Schließen" style={{
          position:"absolute", top: 16, right: 16, zIndex: 2,
          width: 38, height: 38, border:"1px solid var(--navy)", color:"var(--navy)",
          background:"var(--paper)", cursor:"pointer", padding: 0,
          display:"flex", alignItems:"center", justifyContent:"center",
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14">
            <g stroke="currentColor" strokeWidth="1.5">
              <line x1="2.5" y1="2.5" x2="11.5" y2="11.5"/>
              <line x1="11.5" y1="2.5" x2="2.5" y2="11.5"/>
            </g>
          </svg>
        </button>

        <div style={{padding:"36px 40px 28px", borderBottom:"1px solid var(--line)"}}>
          <div className="sans" style={{fontSize:10, letterSpacing:"0.4em", textTransform:"uppercase", color:"var(--gold)", fontWeight:600, marginBottom:12}}>
            ⚓ Anfrage
          </div>
          <h2 className="serif" style={{fontSize: 36, lineHeight: 1, fontWeight: 500, color:"var(--navy)", letterSpacing:"-0.015em"}}>
            Werfen Sie <span style={{fontStyle:"italic", color:"var(--gold)"}}>die Leinen los.</span>
          </h2>
          <p className="serif" style={{fontSize: 15.5, lineHeight: 1.55, color:"rgba(10,24,40,0.7)", marginTop: 12, fontStyle:"italic"}}>
            Wir melden uns innerhalb eines Werktages.
          </p>
        </div>

        <div style={{padding:"28px 40px 36px", overflowY:"auto", flex: 1}}>
        {status === "success" ? (
          <div style={{textAlign:"center", padding:"30px 0"}}>
            <div className="serif" style={{fontSize: 56, color:"var(--gold)", lineHeight:1, marginBottom: 16}}>⚓</div>
            <h3 className="serif" style={{fontSize: 28, color:"var(--navy)", fontWeight:500, marginBottom: 14, lineHeight:1.15}}>
              Danke — Ihre Anfrage ist <span style={{fontStyle:"italic", color:"var(--gold)"}}>auf See.</span>
            </h3>
            <p className="serif" style={{fontSize: 16, lineHeight:1.55, color:"rgba(10,24,40,0.7)", maxWidth:440, margin:"0 auto"}}>
              Wir antworten in der Regel innerhalb eines Werktages auf
              <strong style={{color:"var(--navy)", fontWeight: 500}}> {form.email}</strong>.
            </p>
            <button onClick={()=>setOpen(false)} className="sans" style={{
              marginTop: 28, padding:"14px 28px",
              background:"var(--navy)", color:"var(--paper)",
              fontSize: 12, letterSpacing:"0.16em", textTransform:"uppercase", fontWeight: 600,
              border:"none", cursor:"pointer",
            }}>Schließen</button>
          </div>
        ) : (
        <form onSubmit={submit} noValidate>
          <input type="text" name="_honey" tabIndex="-1" autoComplete="off" style={{position:"absolute", left:-9999, opacity:0}} />

          <div className="contact-row" style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap: 18, marginBottom: 18}}>
            <div>
              <label style={labelStyle}>Name<span style={{color:"var(--gold)"}}> *</span></label>
              <input required type="text" value={form.name} onChange={update("name")} style={inputStyle} />
            </div>
            <div>
              <label style={labelStyle}>Telefon</label>
              <input type="tel" value={form.phone} onChange={update("phone")} style={inputStyle} />
            </div>
          </div>

          <div style={{marginBottom: 18}}>
            <label style={labelStyle}>E-Mail<span style={{color:"var(--gold)"}}> *</span></label>
            <input required type="email" value={form.email} onChange={update("email")} style={inputStyle} />
          </div>

          <div className="contact-row" style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap: 18, marginBottom: 18}}>
            <div>
              <label style={labelStyle}>Bootstyp</label>
              <select value={form.boatType} onChange={update("boatType")} style={{...inputStyle, appearance:"none", backgroundImage:"linear-gradient(45deg, transparent 50%, var(--gold) 50%), linear-gradient(135deg, var(--gold) 50%, transparent 50%)", backgroundPosition:"calc(100% - 18px) 50%, calc(100% - 13px) 50%", backgroundSize:"5px 5px, 5px 5px", backgroundRepeat:"no-repeat", paddingRight: 32}}>
                <option value="">— bitte wählen —</option>
                <option value="Segelboot">Segelboot</option>
                <option value="Motorboot">Motorboot</option>
                <option value="Yacht">Yacht</option>
                <option value="Jetski">Jetski / PWC</option>
                <option value="Hausboot">Hausboot</option>
                <option value="Trailer / Charter">Trailer / Charter</option>
                <option value="Sonstiges">Sonstiges</option>
              </select>
            </div>
            <div>
              <label style={labelStyle}>Bootsname</label>
              <input type="text" value={form.boatName} onChange={update("boatName")} style={inputStyle} />
            </div>
          </div>

          <div style={{marginBottom: 22}}>
            <label style={labelStyle}>Ihre Nachricht<span style={{color:"var(--gold)"}}> *</span></label>
            <textarea required rows="4" value={form.message} onChange={update("message")}
              placeholder="Worum geht es — Neuabschluss, Vergleich, Schadenfall …"
              style={{...inputStyle, resize:"vertical", lineHeight:1.5, fontSize: 16}} />
          </div>

          {status === "error" && (
            <div className="serif" style={{
              fontSize: 14, color: "#b13e3e", fontStyle:"italic", marginBottom: 16,
              padding: "12px 14px", border:"1px solid rgba(177,62,62,0.3)", background:"rgba(177,62,62,0.05)",
            }}>
              Die Anfrage konnte nicht abgesendet werden. Bitte versuchen Sie es erneut oder
              schreiben Sie direkt an <a href="mailto:ahoi@bootsversicherung-makler.de" style={{color:"var(--navy)", textDecoration:"underline"}}>ahoi@bootsversicherung-makler.de</a>.
            </div>
          )}

          <div style={{display:"flex", gap: 14, alignItems:"center", flexWrap:"wrap"}}>
            <button type="submit" disabled={status==="submitting"} className="sans" style={{
              padding:"16px 32px", background:"var(--navy)", color:"var(--paper)",
              fontSize: 12, letterSpacing:"0.16em", textTransform:"uppercase", fontWeight: 600,
              border:"none", cursor: status==="submitting" ? "wait" : "pointer",
              display:"inline-flex", alignItems:"center", gap: 10,
              opacity: status==="submitting" ? 0.6 : 1,
            }}>
              {status === "submitting" ? "Wird gesendet …" : "Anfrage absenden"}
              <span style={{fontSize: 16}}>→</span>
            </button>
            <span className="serif" style={{fontSize: 12.5, color:"rgba(10,24,40,0.55)", fontStyle:"italic"}}>
              oder direkt an <a href="mailto:ahoi@bootsversicherung-makler.de" style={{color:"var(--navy)"}}>ahoi@bootsversicherung-makler.de</a>
            </span>
          </div>

          <p className="serif" style={{fontSize: 11.5, color:"rgba(10,24,40,0.5)", marginTop: 22, fontStyle:"italic", lineHeight:1.5}}>
            Mit Absenden stimmen Sie der Verarbeitung Ihrer Angaben gemäß unserer
            <a href="datenschutz.html" target="_blank" rel="noopener" style={{color:"var(--navy)"}}> Datenschutzerklärung</a> zu.
          </p>
        </form>
        )}
        </div>
      </div>
    </div>
  );
}

window.ContactModal = ContactModal;
