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

// Plausibility check for German (+49 / 0) and Austrian (+43 / 0) phone numbers.
const isValidDEATPhone = (raw) => {
  const s = (raw || "").replace(/[\s/().\-]/g, "");
  const de = /^(\+49|0049|0)[1-9]\d{6,11}$/;
  const at = /^(\+43|0043|0)[1-9]\d{3,12}$/;
  return de.test(s) || at.test(s);
};

// Pickup time as one-hour windows (06:00–07:00 … 20:00–21:00) instead of a
// free minute-precision input — easier to dispatch and to choose on mobile.
const pad2 = (n) => String(n).padStart(2, "0");
const TIME_SLOTS = Array.from({ length: 15 }, (_, i) => `${pad2(6 + i)}:00 – ${pad2(7 + i)}:00`);

const initialData = {
  vorname: "", nachname: "", telefon: "", email: "",
  abhol: "", ziel: "", datum: "", uhrzeit: "",
  type: "", rolliEigen: null, rolliBenoetigt: null, rollator: null,
  begleitung: null, schein: null, pflegegrad: "", kasse: "",
  wiederkehrend: null, notes: "",
};

const RequestForm = ({ open, onClose }) => {
  const STEPS = t("form.steps");
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState(initialData);
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendError, setSendError] = React.useState(false);
  const [touched, setTouched] = React.useState({});
  // Async deliverability check of the e-mail domain (MX/A lookup via DNS-over-HTTPS).
  const [emailCheck, setEmailCheck] = React.useState({ status: "idle", email: "" });
  // Per-open lead session id, used to track form progress on the backend.
  const sessionIdRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      document.body.style.overflow = "hidden";
      // New session per open; record that the form was started (step 0).
      sessionIdRef.current = (window.crypto && crypto.randomUUID)
        ? crypto.randomUUID()
        : "sid-" + Date.now() + "-" + Math.random().toString(36).slice(2);
      track(0, false, initialData);
    } else {
      document.body.style.overflow = "";
    }
  }, [open]);

  React.useEffect(() => {
    const email = data.email.trim();
    if (!email || !EMAIL_RE.test(email)) {
      setEmailCheck({ status: "idle", email });
      return;
    }
    const domain = email.split("@")[1];
    let cancelled = false;
    setEmailCheck({ status: "checking", email });
    const dns = (type) => fetch("https://dns.google/resolve?name=" + encodeURIComponent(domain) + "&type=" + type)
      .then(r => r.json())
      .then(j => Array.isArray(j.Answer) && j.Answer.some(a => a.type === (type === "MX" ? 15 : 1)));
    const tid = setTimeout(() => {
      dns("MX")
        .then(hasMX => hasMX ? true : dns("A"))
        .then(deliverable => { if (!cancelled) setEmailCheck({ status: deliverable ? "valid" : "invalid", email }); })
        .catch(() => { if (!cancelled) setEmailCheck({ status: "unknown", email }); });
    }, 500);
    return () => { cancelled = true; clearTimeout(tid); };
  }, [data.email]);

  if (!open) return null;

  const set = (k, v) => setData(d => ({ ...d, [k]: v }));

  const emailVal = data.email.trim();
  const emailFormatOk = !emailVal || EMAIL_RE.test(emailVal);
  const emailDeliverable = !emailVal || (emailFormatOk && emailCheck.status !== "invalid");

  const errs = {};
  if (step === 0) {
    if (touched.vorname && !data.vorname.trim()) errs.vorname = t("form.err.vorname");
    if (touched.nachname && !data.nachname.trim()) errs.nachname = t("form.err.nachname");
    if (touched.telefon) {
      if (!data.telefon.trim()) errs.telefon = t("form.err.telefon");
      else if (!isValidDEATPhone(data.telefon)) errs.telefon = t("form.err.telefonInvalid");
    }
    if (touched.email && emailVal) {
      if (!emailFormatOk) errs.email = t("form.err.emailInvalid");
      else if (emailCheck.status === "invalid") errs.email = t("form.err.emailUnknown");
    }
  }
  if (step === 1) {
    if (touched.abhol && !data.abhol.trim()) errs.abhol = t("form.err.abhol");
    if (touched.ziel && !data.ziel.trim()) errs.ziel = t("form.err.ziel");
    if (touched.datum && !data.datum) errs.datum = t("form.err.datum");
  }

  const canNext = (() => {
    if (step === 0) return data.vorname && data.nachname && data.telefon && isValidDEATPhone(data.telefon) && emailFormatOk && emailDeliverable;
    if (step === 1) return data.abhol && data.ziel && data.datum;
    if (step === 2) return !!data.type;
    return true;
  })();

  // Fire-and-forget progress ping to the Django tracker. Stores how far each
  // visitor got (funnel) under a per-open session id. Never blocks the UI.
  const track = (step, completed, dataArg) => {
    if (!sessionIdRef.current) return;
    try {
      fetch("/api/lead/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        keepalive: true,
        body: JSON.stringify({
          session_id: sessionIdRef.current,
          step,
          completed: !!completed,
          lang: window.LANG || "de",
          data: dataArg || data,
        }),
      }).catch(() => {});
    } catch (e) { /* ignore */ }
  };

  const next = () => {
    if (step === 0) setTouched(t => ({ ...t, vorname: true, nachname: true, telefon: true }));
    if (step === 1) setTouched(t => ({ ...t, abhol: true, ziel: true, datum: true }));
    if (!canNext) return;
    if (step < STEPS.length - 1) {
      const ns = step + 1;
      setStep(ns);
      track(ns, false);        // record advance to the next step
    } else {
      submit();
    }
  };
  const back = () => step > 0 && setStep(step - 1);

  // Final submit: mark the lead completed (this is what triggers the brief
  // Telegram notification on the server) and show the success view.
  const submit = async () => {
    if (sending) return;
    setSending(true);
    setSendError(false);
    try {
      const res = await fetch("/api/lead/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          session_id: sessionIdRef.current,
          step: STEPS.length - 1,
          completed: true,
          lang: window.LANG || "de",
          data,
        }),
      });
      if (!res.ok) throw new Error("bad status " + res.status);
      setSubmitted(true);
    } catch (e) {
      setSendError(true);
    } finally {
      setSending(false);
    }
  };

  const close = () => {
    onClose();
    setTimeout(() => {
      setStep(0); setData(initialData); setSubmitted(false); setTouched({});
      setSending(false); setSendError(false);
    }, 200);
  };

  return (
    <div
      role="dialog" aria-modal="true" aria-label={t("form.dialogAria")}
      className="form-overlay"
      style={{
        position: "fixed", inset: 0, zIndex: 80,
        background: "rgba(11,42,74,.45)", backdropFilter: "blur(8px)",
        display: "flex", alignItems: "stretch", justifyContent: "center",
        padding: "clamp(12px, 4vw, 32px) 12px", overflow: "auto",
      }}
      onClick={(e) => { if (e.target === e.currentTarget) close(); }}
    >
      <div style={{
        background: "var(--surface)", borderRadius: 28, width: "100%", maxWidth: 840,
        boxShadow: "var(--shadow-lg)", overflow: "hidden", display: "grid",
        gridTemplateColumns: "260px 1fr", alignSelf: "flex-start",
      }} className="form-modal">

        {/* Sidebar */}
        <aside style={{
          background: "var(--bg-slate)", color: "#fff", padding: 32,
          display: "grid", alignContent: "space-between", gap: 32,
          position: "relative", overflow: "hidden",
        }} className="form-side">
          <div aria-hidden style={{ position: "absolute", right: -50, bottom: -30, opacity: .14 }}>
            <CraneMark size={200} color="#fff" accent="#fff"/>
          </div>
          <div style={{ position: "relative" }}>
            <Wordmark size="sm" invert/>
            <div style={{ fontSize: "calc(11px * var(--scale))", color: "rgba(255,255,255,.7)", letterSpacing: ".14em", textTransform: "uppercase", fontWeight: 700, margin: "32px 0 16px" }}>
              {window.tf("form.stepsHeading", { n: STEPS.length })}
            </div>
            <ol style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 4 }}>
              {STEPS.map((s, i) => {
                const C = Icon[s.icon];
                const active = i === step;
                const done = i < step || submitted;
                return (
                  <li key={s.id} style={{
                    display: "flex", gap: 14, alignItems: "center",
                    padding: "12px 10px", borderRadius: 12,
                    background: active ? "rgba(255,255,255,.14)" : "transparent",
                  }}>
                    <div style={{
                      width: 32, height: 32, borderRadius: 999,
                      background: done ? "var(--accent)" : active ? "#fff" : "rgba(255,255,255,.14)",
                      color: done ? "var(--ink)" : active ? "var(--ink)" : "#fff",
                      display: "flex", alignItems: "center", justifyContent: "center",
                      flexShrink: 0, fontWeight: 700, fontSize: 13,
                    }}>
                      {done ? <Icon.check size={16}/> : i + 1}
                    </div>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: "calc(14px * var(--scale))" }}>{s.label}</div>
                      <div style={{ fontSize: "calc(12px * var(--scale))", color: "rgba(255,255,255,.72)" }}>{s.sub}</div>
                    </div>
                  </li>
                );
              })}
            </ol>
          </div>

          <div style={{ fontSize: "calc(13px * var(--scale))", color: "rgba(255,255,255,.85)", lineHeight: 1.5, position: "relative" }}>
            {t("form.help")}<br/>
            <a href="tel:+4961511234567" style={{ color: "#fff", fontWeight: 700 }}>{t("common.phone")}</a>
          </div>
        </aside>

        {/* Main */}
        <main style={{ padding: 36, position: "relative", minHeight: 540 }}>
          <button onClick={close} aria-label={t("form.closeAria")} style={{
            position: "absolute", top: 20, right: 20,
            width: 40, height: 40, borderRadius: 999,
            background: "var(--bg)", color: "var(--ink-2)",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <Icon.close size={20}/>
          </button>

          {/* Mobile progress dots */}
          <div className="mobile-progress" style={{ display: "none", gap: 6, marginBottom: 16 }}>
            {STEPS.map((s, i) => (
              <div key={s.id} style={{
                height: 4, flex: 1, borderRadius: 4,
                background: i <= step ? "var(--accent)" : "var(--line)",
              }}/>
            ))}
          </div>

          {submitted ? (
            <SuccessView data={data} onClose={close}/>
          ) : (
            <>
              <div style={{ marginBottom: "clamp(14px, 4vw, 28px)" }}>
                <div style={{ fontSize: "calc(12px * var(--scale))", color: "var(--accent-2)", marginBottom: 6, fontWeight: 700, letterSpacing: ".14em", textTransform: "uppercase" }}>
                  {window.tf("form.stepCounter", { n: step + 1, total: STEPS.length })}
                </div>
                <h2 style={{ fontSize: "clamp(22px, 5.5vw, 30px)", fontWeight: 800, lineHeight: 1.05, letterSpacing: "-0.03em" }}>
                  {t("form.stepTitles")[step]}
                </h2>
              </div>

              {step === 0 && <StepPersonal data={data} set={set} errs={errs} setTouched={setTouched} emailCheck={emailCheck}/>}
              {step === 1 && <StepTrip data={data} set={set} errs={errs} setTouched={setTouched}/>}
              {step === 2 && <StepType data={data} set={set}/>}
              {step === 3 && <StepExtras data={data} set={set}/>}
              {step === 4 && <StepConfirm data={data} set={set}/>}

              {sendError && (
                <div style={{
                  marginTop: 20, padding: 14, borderRadius: 12,
                  background: "rgba(181,72,72,.1)", color: "#b54848",
                  fontSize: "calc(14px * var(--scale))", lineHeight: 1.5,
                }}>
                  {(window.LANG === "ru")
                    ? "Не удалось отправить заявку. Попробуйте ещё раз или позвоните нам."
                    : "Anfrage konnte nicht gesendet werden. Bitte erneut versuchen oder rufen Sie uns an."}
                </div>
              )}

              <div style={{
                display: "flex", justifyContent: "space-between", marginTop: "clamp(18px, 4vw, 36px)", gap: 12,
              }}>
                <button className="btn btn-secondary" onClick={back} disabled={step === 0 || sending} style={{ opacity: step === 0 ? .4 : 1 }}>
                  {t("form.back")}
                </button>
                <button className="btn btn-mint" onClick={next} disabled={sending} style={{ opacity: sending ? .6 : 1 }}>
                  {sending
                    ? ((window.LANG === "ru") ? "Отправка…" : "Senden…")
                    : (step === STEPS.length - 1 ? t("form.submit") : t("form.next"))} <Icon.arrow size={18}/>
                </button>
              </div>
            </>
          )}
        </main>

        <style>{`
          @media (max-width: 720px) {
            /* Full-screen modal on mobile — uses the whole working area */
            .form-overlay { padding: 0 !important; overflow: hidden !important; }
            .form-modal {
              /* minmax(0,1fr) lets the column shrink below content width;
                 min-width:0 lets the modal (a flex item) shrink to the screen */
              grid-template-columns: minmax(0, 1fr) !important;
              max-width: 100vw !important; width: 100vw !important; min-width: 0 !important;
              border-radius: 0 !important; align-self: stretch !important;
              min-height: 100vh; min-height: 100dvh;
              overflow-x: hidden !important;
            }
            .form-side { display: none !important; }
            .mobile-progress { display: flex !important; }
            /* Step content scrolls inside; never overflows horizontally */
            .form-modal > main {
              overflow-y: auto; max-height: 100dvh;
              min-width: 0; max-width: 100vw; overflow-x: hidden;
            }
            .form-modal main > div { min-width: 0; }
            .form-modal .row2 { min-width: 0; }
          }
        `}</style>
      </div>
    </div>
  );
};

const Field = ({ label, hint, error, children }) => (
  <div className="field">
    <label>{label}</label>
    {children}
    {error ? (
      <span style={{ color: "#b54848", fontSize: "calc(13px * var(--scale))" }}>{error}</span>
    ) : hint ? (
      <span className="hint">{hint}</span>
    ) : null}
  </div>
);

const StepPersonal = ({ data, set, errs, setTouched, emailCheck }) => (
  <div style={{ display: "grid", gap: 18 }}>
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }} className="row2">
      <Field label={t("form.personal.vorname")} error={errs.vorname}>
        <input className="input" value={data.vorname}
          onChange={e => set("vorname", e.target.value)}
          onBlur={() => setTouched(t => ({ ...t, vorname: true }))}
          placeholder={t("form.personal.vornamePh")} />
      </Field>
      <Field label={t("form.personal.nachname")} error={errs.nachname}>
        <input className="input" value={data.nachname}
          onChange={e => set("nachname", e.target.value)}
          onBlur={() => setTouched(t => ({ ...t, nachname: true }))}
          placeholder={t("form.personal.nachnamePh")} />
      </Field>
    </div>
    <Field label={t("form.personal.telefon")} hint={t("form.personal.telefonHint")} error={errs.telefon}>
      <input className="input" type="tel" value={data.telefon}
        onChange={e => set("telefon", e.target.value)}
        onBlur={() => setTouched(t => ({ ...t, telefon: true }))}
        placeholder={t("form.personal.telefonPh")} />
    </Field>
    <Field
      label={t("form.personal.email")}
      error={errs.email}
      hint={emailCheck && emailCheck.status === "checking" ? t("form.personal.emailChecking") : t("form.personal.emailHint")}>
      <input className="input" type="email" value={data.email}
        onChange={e => set("email", e.target.value)}
        onBlur={() => setTouched(t => ({ ...t, email: true }))}
        placeholder={t("form.personal.emailPh")} />
    </Field>
    <style>{`
      @media (max-width: 540px) { .row2 { grid-template-columns: 1fr !important; } }
    `}</style>
  </div>
);

const StepTrip = ({ data, set, errs, setTouched }) => {
  const abholRef = React.useRef(null);
  const zielRef = React.useRef(null);

  React.useEffect(() => {
    if (typeof window.loadGoogleMaps !== "function") return;
    let autos = [];
    let cancelled = false;
    window.loadGoogleMaps().then((maps) => {
      if (cancelled) return;
      const opts = { componentRestrictions: { country: ["de", "at"] }, fields: ["formatted_address"], types: ["address"] };
      [[abholRef, "abhol"], [zielRef, "ziel"]].forEach(([ref, key]) => {
        if (!ref.current) return;
        const ac = new maps.places.Autocomplete(ref.current, opts);
        ac.addListener("place_changed", () => {
          const place = ac.getPlace();
          if (place && place.formatted_address) {
            set(key, place.formatted_address);
            setTouched(t => ({ ...t, [key]: true }));
          }
        });
        autos.push(ac);
      });
    }).catch(() => { /* no/invalid API key — fields stay plain text inputs */ });
    return () => {
      cancelled = true;
      if (window.google && window.google.maps) {
        autos.forEach(ac => window.google.maps.event.clearInstanceListeners(ac));
      }
    };
  }, []);

  return (
  <div style={{ display: "grid", gap: 18 }}>
    <Field label={t("form.trip.abhol")} hint={t("form.trip.abholHint")} error={errs.abhol}>
      <input ref={abholRef} className="input" value={data.abhol}
        onChange={e => set("abhol", e.target.value)}
        onBlur={() => setTouched(t => ({ ...t, abhol: true }))}
        placeholder={t("form.trip.abholPh")} />
    </Field>
    <Field label={t("form.trip.ziel")} hint={t("form.trip.zielHint")} error={errs.ziel}>
      <input ref={zielRef} className="input" value={data.ziel}
        onChange={e => set("ziel", e.target.value)}
        onBlur={() => setTouched(t => ({ ...t, ziel: true }))}
        placeholder={t("form.trip.zielPh")} />
    </Field>
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }} className="row2">
      <Field label={t("form.trip.datum")} error={errs.datum}>
        <input className="input" type="date" value={data.datum}
          onChange={e => set("datum", e.target.value)}
          onBlur={() => setTouched(t => ({ ...t, datum: true }))} />
      </Field>
      <Field label={t("form.trip.uhrzeit")} hint={t("form.trip.uhrzeitHint")}>
        <select className="select" value={data.uhrzeit} onChange={e => set("uhrzeit", e.target.value)}>
          <option value="">{(window.LANG === "ru") ? "Интервал выбрать" : "Zeitfenster wählen"}</option>
          {TIME_SLOTS.map(slot => <option key={slot} value={slot}>{slot}</option>)}
        </select>
      </Field>
    </div>
    <style>{`
      @media (max-width: 540px) { .row2 { grid-template-columns: 1fr !important; } }
    `}</style>
  </div>
  );
};

const StepType = ({ data, set }) => {
  const types = t("form.transportTypes");
  return (
    <div>
      <p style={{ color: "var(--ink-2)", marginBottom: 20 }}>
        {t("form.type.intro")}
      </p>
      <div className="choice-grid">
        {types.map(tt => {
          const C = Icon[tt.icon];
          const active = data.type === tt.id;
          return (
            <button key={tt.id} className="choice" data-active={active}
              onClick={() => set("type", tt.id)} type="button">
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 4 }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 12,
                  background: active ? "var(--primary)" : "var(--primary-soft)",
                  color: active ? "#fff" : "var(--primary)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}><C size={22}/></div>
                <span className="ti">{tt.t}</span>
              </div>
              <span className="ds">{tt.d}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
};

const YesNo = ({ label, sub, value, onChange }) => {
  const opts = [t("form.yes"), t("form.no")];
  return (
    <div className="toggle-row">
      <div>
        <div className="lbl">{label}</div>
        {sub && <div className="sub">{sub}</div>}
      </div>
      <div className="seg">
        {opts.map(v => (
          <button key={v} type="button"
            data-active={value === v}
            onClick={() => onChange(v)}>{v}</button>
        ))}
      </div>
    </div>
  );
};

const StepExtras = ({ data, set }) => (
  <div style={{ display: "grid", gap: 12 }}>
    {data.type === "rolli" && (
      <YesNo label={t("form.extras.rolliEigen")}
        sub={t("form.extras.rolliEigenSub")}
        value={data.rolliEigen} onChange={v => set("rolliEigen", v)} />
    )}
    <YesNo label={t("form.extras.rollator")}
      sub={t("form.extras.rollatorSub")}
      value={data.rollator} onChange={v => set("rollator", v)} />
    <YesNo label={t("form.extras.begleitung")}
      sub={t("form.extras.begleitungSub")}
      value={data.begleitung} onChange={v => set("begleitung", v)} />
    <YesNo label={t("form.extras.schein")}
      sub={t("form.extras.scheinSub")}
      value={data.schein} onChange={v => set("schein", v)} />

    <Field label={t("form.extras.pflegegrad")} hint={t("form.extras.pflegegradHint")}>
      <select className="select" value={data.pflegegrad} onChange={e => set("pflegegrad", e.target.value)}>
        <option value="">{t("form.extras.pflegegradPlaceholder")}</option>
        {t("form.pflegegrade").map(p => <option key={p} value={p}>{p}</option>)}
      </select>
    </Field>

    <Field label={t("form.extras.kasse")} hint={t("form.extras.kasseHint")}>
      <select className="select" value={data.kasse} onChange={e => set("kasse", e.target.value)}>
        <option value="">{t("form.extras.kassePlaceholder")}</option>
        {t("form.krankenkassen").map(k => <option key={k} value={k}>{k}</option>)}
      </select>
    </Field>

    <YesNo label={t("form.extras.wiederkehrend")}
      sub={t("form.extras.wiederkehrendSub")}
      value={data.wiederkehrend} onChange={v => set("wiederkehrend", v)} />

    <div style={{
      padding: 20, border: "1.5px dashed var(--line)",
      borderRadius: 16, background: "var(--bg-soft)",
      display: "flex", gap: 14, alignItems: "center",
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: 12,
        background: "var(--surface)", color: "var(--primary)",
        display: "flex", alignItems: "center", justifyContent: "center",
        border: "1px solid var(--line)", flexShrink: 0,
      }}><Icon.upload size={20}/></div>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 600, fontSize: "calc(15px * var(--scale))" }}>{t("form.extras.uploadTitle")}</div>
        <div style={{ color: "var(--ink-3)", fontSize: "calc(13px * var(--scale))" }}>{t("form.extras.uploadSub")}</div>
      </div>
      <button type="button" className="btn btn-secondary" style={{ padding: "10px 16px", fontSize: "calc(14px * var(--scale))" }}>
        {t("form.extras.uploadBtn")}
      </button>
    </div>
  </div>
);

const StepConfirm = ({ data, set }) => {
  const types = t("form.transportTypes");
  const typeLabel = types.find(tt => tt.id === data.type)?.t || "—";
  const c = t("form.confirm");
  const rows = [
    [c.kontakt, `${data.vorname} ${data.nachname} · ${data.telefon}${data.email ? " · " + data.email : ""}`],
    [c.abholung, data.abhol || "—"],
    [c.ziel, data.ziel || "—"],
    [c.datumZeit, `${data.datum || "—"}${data.uhrzeit ? " · " + data.uhrzeit : ""}`],
    [c.transportArt, typeLabel],
    ...(data.type === "rolli" ? [[c.eigenerRolli, data.rolliEigen || "—"]] : []),
    [c.rollator, data.rollator || "—"],
    [c.begleitung, data.begleitung || "—"],
    [c.transportschein, data.schein || "—"],
    [c.pflegegrad, data.pflegegrad || "—"],
    [c.krankenkasse, data.kasse || "—"],
    [c.wiederkehrend, data.wiederkehrend || "—"],
  ];
  return (
    <div style={{ display: "grid", gap: 20 }}>
      <div style={{
        border: "1px solid var(--line)", borderRadius: 18, overflow: "hidden",
      }}>
        {rows.map(([k, v], i) => (
          <div key={i} style={{
            display: "grid", gridTemplateColumns: "180px 1fr",
            borderBottom: i < rows.length - 1 ? "1px solid var(--line-soft)" : "none",
            padding: "14px 18px", gap: 16,
          }} className="confirm-row">
            <span style={{ color: "var(--ink-3)", fontSize: "calc(14px * var(--scale))" }}>{k}</span>
            <span style={{ fontWeight: 500, fontSize: "calc(15px * var(--scale))" }}>{v}</span>
          </div>
        ))}
      </div>
      <Field label={c.notesLabel} hint={c.notesHint}>
        <textarea className="textarea" value={data.notes} onChange={e => set("notes", e.target.value)}
          placeholder={c.notesPh}/>
      </Field>
      <div style={{
        padding: 16, background: "var(--accent-soft)", color: "var(--accent-ink)",
        borderRadius: 14, display: "flex", gap: 12, alignItems: "flex-start",
        fontSize: "calc(14px * var(--scale))",
      }}>
        <Icon.lock size={20}/>
        <span>{c.privacy}</span>
      </div>
      <style>{`
        @media (max-width: 540px) { .confirm-row { grid-template-columns: 1fr !important; gap: 4px !important; } }
      `}</style>
    </div>
  );
};

const SuccessView = ({ data, onClose }) => (
  <div style={{ textAlign: "center", padding: "20px 0", display: "grid", gap: 20, placeItems: "center" }}>
    <div style={{
      width: 96, height: 96, borderRadius: 999,
      background: "var(--accent)", color: "var(--ink)",
      display: "flex", alignItems: "center", justifyContent: "center",
    }}>
      <Icon.check size={48} strokeWidth={2.5}/>
    </div>
    <h2 style={{ fontSize: "calc(32px * var(--scale))", fontWeight: 800, lineHeight: 1.05, letterSpacing: "-0.03em" }}>
      {t("form.success.thanks")}, {data.vorname || t("form.success.fallbackName")}!
    </h2>
    <p style={{ color: "var(--ink-2)", fontSize: "calc(18px * var(--scale))", maxWidth: 480, lineHeight: 1.5 }}>
      {t("form.success.bodyPre")}<strong>{t("form.success.bodyTime")}</strong>{t("form.success.bodyMid")}<strong>{data.telefon || t("form.success.fallbackTel")}</strong>.
    </p>
    <div style={{
      background: "var(--bg-soft)", borderRadius: 16, padding: 18,
      display: "grid", gap: 8, fontSize: "calc(14px * var(--scale))",
      color: "var(--ink-2)", textAlign: "left", maxWidth: 480, width: "100%",
    }}>
      {t("form.success.checks").map((chk, i) => (
        <div key={i} style={{ display: "flex", gap: 10 }}>
          <Icon.check size={18} stroke="var(--accent-2)"/>
          <span>{chk}</span>
        </div>
      ))}
    </div>
    <div style={{ display: "flex", gap: 12, marginTop: 8, flexWrap: "wrap", justifyContent: "center" }}>
      <a href="tel:+4961511234567" className="btn btn-mint">
        <Icon.phone size={18}/> {t("common.phone")}
      </a>
      <button className="btn btn-secondary" onClick={onClose}>{t("form.success.close")}</button>
    </div>
  </div>
);

Object.assign(window, { RequestForm });
