/**
 * AddressModal — "leave your address for the printed invitation" flow.
 *
 * PROTOTYPE ONLY: the submit is a simulated async call (setTimeout). The full
 * UX is built out — validation + inline errors, a submitting/loading state, a
 * network-error banner path, and a success screen — so it can be wired to a
 * real endpoint in the next step without touching the markup.
 *
 * Collects: Name, Adresse (Straße + Hausnummer), PLZ (4-digit Austrian postal
 * code). No country, by design.
 */
const { useState: useStateAM, useEffect: useEffectAM, useRef: useRefAM } = React;

function AddressModal() {
  const [open, setOpen] = useStateAM(false);
  const [form, setForm] = useStateAM({ name: "", address: "", plz: "" });
  const [errors, setErrors] = useStateAM({});
  const [status, setStatus] = useStateAM("idle"); // idle | submitting | error | success
  const firstFieldRef = useRefAM(null);

  useEffectAM(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") handleClose(); };
    document.addEventListener("keydown", onKey);
    const focusTimer = setTimeout(() => firstFieldRef.current && firstFieldRef.current.focus(), 60);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      clearTimeout(focusTimer);
      document.body.style.overflow = prevOverflow;
    };
  }, [open]);

  function handleClose() {
    setOpen(false);
    // Reset after the close transition so the form is fresh next open.
    setTimeout(() => {
      setForm({ name: "", address: "", plz: "" });
      setErrors({});
      setStatus("idle");
    }, 260);
  }

  function validate() {
    const e = {};
    if (!form.name.trim()) e.name = "Bitte gib deinen Namen an.";
    if (!form.address.trim()) e.address = "Bitte gib deine Adresse an.";
    if (!form.plz.trim()) e.plz = "Bitte gib deine PLZ an.";
    else if (!/^\d{4}$/.test(form.plz.trim())) e.plz = "Die PLZ besteht aus 4 Ziffern.";
    return e;
  }

  async function handleSubmit(ev) {
    ev.preventDefault();
    if (status === "submitting") return;
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length > 0) return;
    setStatus("submitting");
    try {
      // → Replace with the real POST in the code editor. Simulated latency here.
      await new Promise((res) => setTimeout(res, 1400));
      setStatus("success");
    } catch (err) {
      setStatus("error");
    }
  }

  const update = (key) => (ev) => {
    const v = ev.target.value;
    setForm((f) => ({ ...f, [key]: v }));
    if (errors[key]) setErrors((er) => ({ ...er, [key]: undefined }));
  };

  const submitting = status === "submitting";

  return (
    <>
      <button type="button" className="addr-trigger" onClick={() => setOpen(true)}>
        <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <rect x="3" y="5" width="18" height="14" rx="2" />
          <path d="m3 7 9 6 9-6" />
        </svg>
        Adresse für die Einladung hinterlegen
      </button>

      {open &&
        <div
          className="addr-overlay"
          onMouseDown={(e) => { if (e.target === e.currentTarget) handleClose(); }}>
          <div className="addr-modal" role="dialog" aria-modal="true" aria-labelledby="addr-title">
            <button className="addr-close" type="button" onClick={handleClose} aria-label="Schließen">×</button>

            {status === "success" ?
              <div className="addr-success">
                <span className="addr-check" aria-hidden="true">
                  <svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="m5 13 4 4L19 7" />
                  </svg>
                </span>
                <h3>Vielen Dank!</h3>
                <p>Deine Adresse ist hinterlegt — die gedruckte Einladung kommt zu dir.</p>
                <button type="button" className="addr-submit" onClick={handleClose}>Schließen</button>
              </div>
            :
              <form onSubmit={handleSubmit} noValidate>
                <h3 id="addr-title" className="addr-title">Adresse hinterlegen</h3>
                <p className="addr-sub">Damit die gedruckte Einladung sicher bei dir ankommt.</p>

                {status === "error" &&
                  <div className="addr-banner" role="alert">
                    Etwas ist schiefgelaufen. Bitte versuch es noch einmal.
                  </div>
                }

                <label className="addr-field">
                  <span>Name</span>
                  <input
                    ref={firstFieldRef}
                    type="text"
                    value={form.name}
                    onChange={update("name")}
                    className={errors.name ? "is-invalid" : ""}
                    placeholder="Vor- und Nachname"
                    autoComplete="name"
                    disabled={submitting} />
                  {errors.name && <em>{errors.name}</em>}
                </label>

                <label className="addr-field">
                  <span>Adresse</span>
                  <input
                    type="text"
                    value={form.address}
                    onChange={update("address")}
                    className={errors.address ? "is-invalid" : ""}
                    placeholder="Straße und Hausnummer"
                    autoComplete="street-address"
                    disabled={submitting} />
                  {errors.address && <em>{errors.address}</em>}
                </label>

                <label className="addr-field">
                  <span>PLZ</span>
                  <input
                    type="text"
                    inputMode="numeric"
                    maxLength={4}
                    value={form.plz}
                    onChange={update("plz")}
                    className={errors.plz ? "is-invalid" : ""}
                    placeholder="z. B. 7000"
                    autoComplete="postal-code"
                    disabled={submitting} />
                  {errors.plz && <em>{errors.plz}</em>}
                </label>

                <button type="submit" className="addr-submit" disabled={submitting}>
                  {submitting && <span className="addr-spinner" aria-hidden="true"></span>}
                  {submitting ? "Wird gesendet…" : "Absenden"}
                </button>
              </form>
            }
          </div>
        </div>
      }
    </>);
}

if (typeof window !== "undefined") window.AddressModal = AddressModal;
