/* Railo — Schnellformular (Bewerbung & Erstgespräch) als Modal.
   Eigene React-Root, unabhängig von der jeweiligen Seite (die Startseite hat
   eine eigene Navigation, die Unterseiten teilen sich Shared.jsx). Diese Datei
   wird von ALLEN Seiten via <script type="text/babel" src="apply-modal.jsx">
   geladen.

   Öffnen lässt sich das Formular auf drei Wegen:
     1. window.RailoApply.open("bewerbung" | "erstgespraech")
     2. Klick auf einen Link mit href="#bewerben" / "#erstgespraech" / "#kontakt"
     3. Klick auf ein Element mit [data-railo-apply="bewerbung|erstgespraech"]

   Versand über Web3Forms (https://web3forms.com): die eingegebenen Daten werden
   per E-Mail an das mit dem Access-Key verknüpfte Postfach (coo@railo-gmbh.com)
   zugestellt. Keine Cookies, kein Tracking. Honeypot gegen Spam-Bots. */

/* >>> NACH der Web3Forms-Registrierung hier den Access-Key eintragen: <<< */
const WEB3FORMS_KEY = "a0306e4b-9317-4dac-8a6d-649ac13b3763";

const RAILO_APPLY_PHONE = "+49 152 01436843";
const RAILO_APPLY_PHONE_HREF = "tel:+4915201436843";

/* ---------- kleiner externer Store, damit jeder Button öffnen kann ---------- */
const RailoApplyStore = (function () {
  let state = { open: false, intent: "bewerbung" };
  const subs = new Set();
  const emit = function () { subs.forEach(function (fn) { fn(state); }); };
  return {
    open: function (intent) {
      state = { open: true, intent: intent === "erstgespraech" ? "erstgespraech" : "bewerbung" };
      emit();
    },
    close: function () { state = { open: false, intent: state.intent }; emit(); },
    get: function () { return state; },
    subscribe: function (fn) { subs.add(fn); return function () { subs.delete(fn); }; },
  };
})();
window.RailoApply = {
  open: function (i) { RailoApplyStore.open(i); },
  close: function () { RailoApplyStore.close(); },
};

/* ---------- Texte je Anliegen (Du für Bewerber:innen, Sie für Unternehmen) ---------- */
const RAILO_APPLY_COPY = {
  bewerbung: {
    eyebrow: "Bewerbung",
    title: "Jetzt bei Railo bewerben",
    sub: "Lass uns kurz kennenlernen — wir melden uns bei dir.",
    name: "Dein Name",
    phone: "Deine Telefonnummer",
    email: "Deine E-Mail",
    message: "Kurz zu dir: Erfahrung, Führerschein-Klassen, was dir wichtig ist",
    submit: "Bewerbung absenden",
    subject: "Neue Bewerbung über railo-gmbh.com",
    anliegen: "Bewerbung (Lokführer:in)",
    success: "Danke! Deine Bewerbung ist raus — wir melden uns bei dir.",
  },
  erstgespraech: {
    eyebrow: "Erstgespräch",
    title: "Erstgespräch vereinbaren",
    sub: "Sagen Sie uns kurz, worum es geht — wir melden uns zeitnah.",
    name: "Ihr Name",
    phone: "Ihre Telefonnummer",
    email: "Ihre E-Mail",
    message: "Worum geht es? Bedarf, Strecke, Zeitraum",
    submit: "Anfrage absenden",
    subject: "Neue Anfrage (Erstgespräch) über railo-gmbh.com",
    anliegen: "Erstgespräch (Unternehmen / EVU)",
    success: "Danke! Ihre Anfrage ist eingegangen — wir melden uns zeitnah.",
  },
};

const railoFieldStyle = {
  width: "100%", boxSizing: "border-box",
  fontFamily: "var(--font-text)", fontSize: 16, color: "var(--text-primary)",
  background: "var(--surface-page)", border: "1px solid var(--border-hairline)",
  borderRadius: "var(--radius-md)", padding: "12px 14px", outline: "none",
  transition: "border-color var(--dur-fast) var(--ease-standard), box-shadow var(--dur-fast) var(--ease-standard)",
};
const railoLabelStyle = {
  display: "block", fontFamily: "var(--font-text)", fontSize: 13, fontWeight: 600,
  color: "var(--text-secondary)", margin: "0 0 6px",
};

function RailoApplyField({ inputRef, label, name, type, autoComplete, textarea }) {
  const [focus, setFocus] = React.useState(false);
  const style = focus
    ? { ...railoFieldStyle, borderColor: "var(--accent)", boxShadow: "var(--focus-ring)" }
    : railoFieldStyle;
  const common = {
    ref: inputRef, name: name, required: true, autoComplete: autoComplete,
    onFocus: function () { setFocus(true); }, onBlur: function () { setFocus(false); },
  };
  return (
    <label style={{ display: "block", marginBottom: 14 }}>
      <span style={railoLabelStyle}>{label}</span>
      {textarea
        ? <textarea {...common} rows={3} style={{ ...style, resize: "vertical", minHeight: 84 }}></textarea>
        : <input {...common} type={type || "text"} style={style} />}
    </label>);
}

function RailoApplyModal() {
  const [st, setSt] = React.useState(RailoApplyStore.get());
  const [status, setStatus] = React.useState("idle"); // idle | sending | done | error
  const [errMsg, setErrMsg] = React.useState("");
  const firstRef = React.useRef(null);
  const formRef = React.useRef(null);

  React.useEffect(function () { return RailoApplyStore.subscribe(setSt); }, []);

  const open = st.open;
  const copy = RAILO_APPLY_COPY[st.intent] || RAILO_APPLY_COPY.bewerbung;

  React.useEffect(function () {
    if (open) { setStatus("idle"); setErrMsg(""); }
  }, [open, st.intent]);

  React.useEffect(function () {
    if (!open) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = function (e) { if (e.key === "Escape") RailoApplyStore.close(); };
    document.addEventListener("keydown", onKey);
    const tid = setTimeout(function () { if (firstRef.current) firstRef.current.focus(); }, 70);
    return function () {
      document.body.style.overflow = prevOverflow;
      document.removeEventListener("keydown", onKey);
      clearTimeout(tid);
    };
  }, [open]);

  if (!open) return null;

  const close = function () { RailoApplyStore.close(); };

  const onSubmit = async function (e) {
    e.preventDefault();
    if (status === "sending") return;
    const form = formRef.current;
    const fd = new FormData(form);
    if (fd.get("botcheck")) { close(); return; } // Honeypot ausgelöst → still verwerfen
    if (!WEB3FORMS_KEY || WEB3FORMS_KEY.indexOf("REPLACE_") === 0) {
      setStatus("error");
      setErrMsg("Das Formular wird gerade freigeschaltet. Bitte ruf uns solange kurz an: " + RAILO_APPLY_PHONE + ".");
      return;
    }
    setStatus("sending");
    setErrMsg("");
    const payload = {
      access_key: WEB3FORMS_KEY,
      subject: copy.subject,
      from_name: "Railo Website",
      Anliegen: copy.anliegen,
      Name: fd.get("name"),
      Telefon: fd.get("phone"),
      "E-Mail": fd.get("email"),
      Nachricht: fd.get("message"),
    };
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (data && data.success) {
        setStatus("done");
      } else {
        setStatus("error");
        setErrMsg(data && data.message ? data.message : "Senden fehlgeschlagen. Bitte versuch es erneut.");
      }
    } catch (err) {
      setStatus("error");
      setErrMsg("Verbindung fehlgeschlagen. Bitte ruf uns an: " + RAILO_APPLY_PHONE + ".");
    }
  };

  return (
    <div
      role="dialog" aria-modal="true" aria-label={copy.title}
      onMouseDown={function (e) { if (e.target === e.currentTarget) close(); }}
      style={{
        position: "fixed", inset: 0, zIndex: 1000,
        display: "flex", alignItems: "flex-start", justifyContent: "center",
        padding: "max(16px, env(safe-area-inset-top, 0px)) 16px 32px",
        overflowY: "auto",
        background: "rgba(5,7,15,0.55)",
        backdropFilter: "blur(6px)", WebkitBackdropFilter: "blur(6px)",
        animation: "railoApplyFade 200ms var(--ease-out) both",
      }}>
      <div style={{
        position: "relative", width: "100%", maxWidth: 460, marginTop: "6vh",
        background: "var(--surface-card)", borderRadius: "var(--radius-xl)",
        border: "1px solid var(--border-subtle)", boxShadow: "0 24px 80px rgba(0,0,0,0.42)",
        padding: "30px 28px 26px",
        animation: "railoApplyPop 240ms var(--ease-out) both",
      }}>
        <button onClick={close} aria-label="Schließen" style={{
          position: "absolute", top: 14, right: 14, width: 38, height: 38,
          appearance: "none", border: "none", cursor: "pointer", borderRadius: 980,
          background: "var(--surface-section)", color: "var(--text-secondary)",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
            <path d="M6 6 L18 18 M18 6 L6 18"></path>
          </svg>
        </button>

        {status === "done" ? (
          <div style={{ textAlign: "center", padding: "18px 6px 8px" }}>
            <div style={{
              width: 64, height: 64, margin: "0 auto 20px", borderRadius: 980,
              background: "var(--green-50)", color: "var(--green-500)",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
            }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20 6 L9 17 L4 12"></path>
              </svg>
            </div>
            <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 24, letterSpacing: "var(--tracking-title)", color: "var(--text-primary)", margin: "0 0 10px" }}>
              Geschafft.
            </h2>
            <p style={{ fontFamily: "var(--font-text)", fontSize: 16, lineHeight: 1.5, color: "var(--text-secondary)", margin: "0 0 24px" }}>
              {copy.success}
            </p>
            <button onClick={close} style={{
              appearance: "none", border: "none", cursor: "pointer",
              fontFamily: "var(--font-text)", fontSize: 16, fontWeight: 600,
              color: "var(--text-on-accent)", background: "var(--accent)",
              padding: "13px 28px", borderRadius: 980, boxShadow: "0 8px 28px rgba(10,92,255,0.28)",
            }}>Schließen</button>
          </div>
        ) : (
          <React.Fragment>
            <div style={{ fontFamily: "var(--font-text)", fontSize: 12, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--accent)", marginBottom: 10 }}>
              {copy.eyebrow}
            </div>
            <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "clamp(24px, 4vw, 30px)", letterSpacing: "var(--tracking-title)", lineHeight: 1.12, color: "var(--text-primary)", margin: "0 0 8px", paddingRight: 28 }}>
              {copy.title}
            </h2>
            <p style={{ fontFamily: "var(--font-text)", fontSize: 15.5, lineHeight: 1.5, color: "var(--text-secondary)", margin: "0 0 22px" }}>
              {copy.sub}
            </p>

            <form ref={formRef} onSubmit={onSubmit} noValidate={false}>
              <RailoApplyField inputRef={firstRef} label={copy.name} name="name" autoComplete="name" />
              <RailoApplyField label={copy.phone} name="phone" type="tel" autoComplete="tel" />
              <RailoApplyField label={copy.email} name="email" type="email" autoComplete="email" />
              <RailoApplyField label={copy.message} name="message" textarea />

              {/* Honeypot — für Menschen unsichtbar, fängt Bots ab */}
              <input type="checkbox" name="botcheck" tabIndex={-1} autoComplete="off"
                style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} aria-hidden="true" />

              <label style={{ display: "flex", alignItems: "flex-start", gap: 10, margin: "4px 0 20px", cursor: "pointer" }}>
                <input type="checkbox" name="consent" required style={{ width: 18, height: 18, marginTop: 2, flexShrink: 0, accentColor: "var(--accent)" }} />
                <span style={{ fontFamily: "var(--font-text)", fontSize: 13.5, lineHeight: 1.45, color: "var(--text-secondary)" }}>
                  Ich habe die <a href="Datenschutz.html" target="_blank" rel="noopener" style={{ color: "var(--accent)", textDecoration: "none" }}>Datenschutzerklärung</a> gelesen und bin mit der Verarbeitung meiner Daten zur Bearbeitung meiner Anfrage einverstanden.
                </span>
              </label>

              {status === "error" && errMsg &&
                <div role="alert" style={{
                  fontFamily: "var(--font-text)", fontSize: 14, lineHeight: 1.45, color: "var(--red-500)",
                  background: "var(--red-50)", border: "1px solid color-mix(in srgb, var(--red-500) 24%, transparent)",
                  borderRadius: "var(--radius-md)", padding: "10px 13px", margin: "0 0 16px",
                }}>{errMsg}</div>}

              <button type="submit" disabled={status === "sending"} style={{
                width: "100%", appearance: "none", border: "none",
                cursor: status === "sending" ? "default" : "pointer",
                fontFamily: "var(--font-text)", fontSize: 16.5, fontWeight: 600,
                color: "var(--text-on-accent)", background: "var(--accent)",
                padding: "15px 24px", borderRadius: 980,
                boxShadow: "0 8px 28px rgba(10,92,255,0.28)",
                opacity: status === "sending" ? 0.7 : 1,
                transition: "opacity var(--dur-fast) var(--ease-standard)",
              }}>{status === "sending" ? "Wird gesendet…" : copy.submit}</button>

              <p style={{ fontFamily: "var(--font-text)", fontSize: 13, color: "var(--text-tertiary)", textAlign: "center", margin: "16px 0 0" }}>
                Lieber direkt? <a href={RAILO_APPLY_PHONE_HREF} style={{ color: "var(--accent)", textDecoration: "none", fontWeight: 600 }}>{RAILO_APPLY_PHONE}</a>
              </p>
            </form>
          </React.Fragment>
        )}
      </div>
    </div>);
}

/* ---------- globale Klick-Delegation: Sentinel-Links + data-Attribut ---------- */
document.addEventListener("click", function (e) {
  const t = e.target;
  const a = t && t.closest ? t.closest("a[href], [data-railo-apply]") : null;
  if (!a) return;
  let intent = null;
  if (a.hasAttribute("data-railo-apply")) {
    intent = a.getAttribute("data-railo-apply");
  } else {
    const href = a.getAttribute("href");
    if (href === "#bewerben") intent = "bewerbung";
    else if (href === "#erstgespraech" || href === "#kontakt") intent = "erstgespraech";
  }
  if (!intent) return;
  e.preventDefault();
  RailoApplyStore.open(intent);
});

/* ---------- eigene React-Root anlegen & mounten ---------- */
(function () {
  const mount = document.createElement("div");
  mount.id = "railo-apply-root";
  document.body.appendChild(mount);
  const style = document.createElement("style");
  style.textContent =
    "@keyframes railoApplyFade { from { opacity: 0; } to { opacity: 1; } }" +
    "@keyframes railoApplyPop { from { opacity: 0; transform: translateY(14px) scale(0.985); } to { opacity: 1; transform: none; } }";
  document.head.appendChild(style);
  ReactDOM.createRoot(mount).render(<RailoApplyModal />);
})();
