// Multi-step Bewerbungs-Funnel modal
const { useState: useStateF, useEffect: useEffectF } = React;

function Funnel({ open, onClose }) {
  const D = window.DATA;
  const choiceSteps = D.funnel.steps;
  const cfg = D.funnel;
  const total = choiceSteps.length + 1; // + contact step
  const [step, setStep] = useStateF(0);
  const [answers, setAnswers] = useStateF({});
  const [form, setForm] = useStateF({ name: "", email: "", phone: "", plz: "" });
  const [done, setDone] = useStateF(false);

  useEffectF(() => {
    if (open) { setStep(0); setAnswers({}); setForm({ name: "", email: "", phone: "", plz: "" }); setDone(false); }
  }, [open]);

  useEffectF(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  if (!open) return null;

  const pct = done ? 100 : Math.round(((step) / total) * 100);
  const onChoice = (key, v) => {
    setAnswers((a) => ({ ...a, [key]: v }));
    setTimeout(() => setStep((s) => s + 1), 180);
  };
  const isContact = step === choiceSteps.length;
  const emailOk = /.+@.+\..+/.test(form.email);
  const formOk = form.name.trim().length > 1 && emailOk && form.phone.replace(/\D/g, "").length >= 6 && form.plz.length >= 4;

  return (
    <div onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }} style={{
      position: "fixed", inset: 0, zIndex: 9000, background: "rgba(8,10,8,.55)",
      backdropFilter: "blur(6px)", display: "flex", alignItems: "center",
      justifyContent: "center", padding: 20,
    }}>
      <div style={{
        width: "min(560px, 100%)", background: "#fff", borderRadius: 28, overflow: "hidden",
        boxShadow: "0 30px 80px rgba(0,0,0,.35)", display: "flex", flexDirection: "column",
        maxHeight: "92vh",
      }}>
        {/* top bar */}
        <div style={{ padding: "18px 22px", display: "flex", alignItems: "center", gap: 14, borderBottom: "1px solid var(--line)" }}>
          <img src="logo.svg" alt="Marius Pop · Vertrieb" style={{ height: 30, display: "block", flex: "0 0 auto" }} />
          <div style={{ flex: 1, height: 6, background: "var(--bg-soft)", borderRadius: 6, overflow: "hidden" }}>
            <div style={{ width: `${pct}%`, height: "100%", background: "var(--accent-strong)", borderRadius: 6, transition: "width .35s ease" }} />
          </div>
          <button onClick={onClose} aria-label="Schließen" style={{
            width: 34, height: 34, borderRadius: 34, border: "1px solid var(--line)", background: "#fff",
            cursor: "pointer", fontSize: 18, lineHeight: 1, color: "var(--ink-soft)",
          }}>×</button>
        </div>

        <div style={{ padding: "34px 32px 36px", overflowY: "auto" }}>
          {done ? (
            <div style={{ textAlign: "center", padding: "10px 0 6px" }}>
              <div style={{
                width: 72, height: 72, borderRadius: 72, background: "var(--accent)", margin: "0 auto 22px",
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                <svg width="34" height="34" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" /></svg>
              </div>
              <h3 style={{ fontFamily: "var(--font-head)", fontSize: 26, fontWeight: 600, letterSpacing: "-0.03em", margin: "0 0 10px" }}>
                {cfg.successTitle || "Bewerbung eingegangen."}
              </h3>
              <p style={{ fontFamily: "var(--font-head)", color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.55, maxWidth: 400, margin: "0 auto 26px" }}>
                {cfg.successBody
                  ? cfg.successBody.replace("Stark.", `Stark, ${form.name.split(" ")[0] || "und danke"}.`)
                  : <span>Stark, {form.name.split(" ")[0] || "und danke"}. Wir melden uns innerhalb von <strong>24 Stunden</strong> bei dir. Halt dein Telefon bereit.</span>}
              </p>
              <PillButton onClick={onClose} mono={false}>Schließen</PillButton>
            </div>
          ) : isContact ? (
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-soft)", marginBottom: 10 }}>
                Schritt {step + 1} / {total}
              </div>
              <h3 style={{ fontFamily: "var(--font-head)", fontSize: 26, fontWeight: 600, letterSpacing: "-0.03em", margin: "0 0 6px" }}>
                Fast geschafft.
              </h3>
              <p style={{ fontFamily: "var(--font-head)", color: "var(--ink-soft)", fontSize: 15, margin: "0 0 24px" }}>
                Wohin dürfen wir uns zurückmelden?
              </p>
              <div style={{ display: "grid", gap: 14 }}>
                <Field label="Name" value={form.name} onChange={(v) => setForm({ ...form, name: v })} placeholder="Vor- und Nachname" />
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                  <Field label="E-Mail" value={form.email} onChange={(v) => setForm({ ...form, email: v })} placeholder="du@mail.de" type="email" />
                  <Field label="Telefon" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} placeholder="0151 …" type="tel" />
                </div>
                <Field label="PLZ deiner Region" value={form.plz} onChange={(v) => setForm({ ...form, plz: v.replace(/\D/g, "").slice(0, 5) })} placeholder="z. B. 29221" />
              </div>
              <div style={{ marginTop: 26, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
                <button onClick={() => setStep((s) => s - 1)} style={backBtn}>← Zurück</button>
                <button disabled={!formOk} onClick={() => setDone(true)} style={{
                  ...submitBtn, opacity: formOk ? 1 : 0.4, cursor: formOk ? "pointer" : "not-allowed",
                }}>{cfg.submitLabel || "Bewerbung absenden"} →</button>
              </div>
              <p style={{ fontFamily: "var(--font-head)", fontSize: 12, color: "var(--ink-soft)", marginTop: 16, textAlign: "center" }}>
                Unverbindlich & ohne Startkosten. Deine Daten bleiben bei uns.
              </p>
            </div>
          ) : (
            <Step s={choiceSteps[step]} idx={step} total={total} selected={answers[choiceSteps[step].key]} onChoice={onChoice}
              onBack={step > 0 ? () => setStep((s) => s - 1) : null} />
          )}
        </div>
      </div>
    </div>
  );
}

function Step({ s, idx, total, selected, onChoice, onBack }) {
  return (
    <div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-soft)", marginBottom: 10 }}>
        Schritt {idx + 1} / {total}
      </div>
      <h3 style={{ fontFamily: "var(--font-head)", fontSize: 26, fontWeight: 600, letterSpacing: "-0.03em", margin: "0 0 6px", textWrap: "balance" }}>{s.q}</h3>
      {s.sub && <p style={{ fontFamily: "var(--font-head)", color: "var(--ink-soft)", fontSize: 15, margin: "0 0 24px" }}>{s.sub}</p>}
      <div style={{ display: "grid", gap: 12, marginTop: s.sub ? 0 : 22 }}>
        {s.options.map((o) => {
          const on = selected === o.v;
          return (
            <button key={o.v} onClick={() => onChoice(s.key, o.v)} style={{
              textAlign: "left", padding: "18px 20px", borderRadius: 16, cursor: "pointer",
              border: on ? "2px solid var(--ink)" : "1.5px solid var(--line-strong)",
              background: on ? "var(--accent)" : "#fff", transition: "all .15s ease",
              display: "flex", alignItems: "center", gap: 14,
            }}>
              <span style={{ flex: 1 }}>
                <span style={{ display: "block", fontFamily: "var(--font-head)", fontWeight: 600, fontSize: 17, letterSpacing: "-0.02em", color: on ? "#fff" : "var(--ink)" }}>{o.label}</span>
                <span style={{ display: "block", fontFamily: "var(--font-head)", fontSize: 14, color: on ? "rgba(255,255,255,.82)" : "var(--ink-soft)", marginTop: 2 }}>{o.d}</span>
              </span>
              <ArrowGlyph size={34} bg={on ? "var(--ink)" : "var(--bg-soft)"} stroke={on ? "#fff" : "var(--ink)"} />
            </button>
          );
        })}
      </div>
      {onBack && <button onClick={onBack} style={{ ...backBtn, marginTop: 22 }}>← Zurück</button>}
    </div>
  );
}

function Field({ label, value, onChange, placeholder, type = "text" }) {
  return (
    <label style={{ display: "block" }}>
      <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-soft)", marginBottom: 7 }}>{label}</span>
      <input value={value} type={type} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} style={{
        width: "100%", boxSizing: "border-box", padding: "13px 15px", borderRadius: 12,
        border: "1.5px solid var(--line-strong)", fontFamily: "var(--font-head)", fontSize: 15.5,
        outline: "none", background: "#fff",
      }} onFocus={(e) => e.target.style.borderColor = "var(--ink)"} onBlur={(e) => e.target.style.borderColor = "var(--line-strong)"} />
    </label>
  );
}

const backBtn = { background: "none", border: "none", cursor: "pointer", fontFamily: "var(--font-mono)", fontSize: 12.5, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-soft)", padding: "8px 0" };
const submitBtn = { background: "var(--ink)", color: "#fff", border: "none", borderRadius: 999, padding: "14px 24px", fontFamily: "var(--font-mono)", fontSize: 13, letterSpacing: "0.08em", textTransform: "uppercase", fontWeight: 500, transition: "opacity .15s ease" };

Object.assign(window, { Funnel });
