// Apply modal — reusable form with validation

const SERVICES_META = {
  "rehab": {
    title: "Rehab & Performance Coaching",
    sub: "1-on-1, in-person · Netherlands",
    icon: "heart",
    accent: "var(--cursor-primary)",
  },
  "pt": {
    title: "Personal Coaching",
    sub: "In-person · Strength & conditioning",
    icon: "dumbbell",
    accent: "var(--ink)",
  },
  "online": {
    title: "Online Coaching",
    sub: "Remote · Worldwide check-ins",
    icon: "globe",
    accent: "var(--cursor-primary)",
  },
  "ramadan": {
    title: "40-Day Reset Challenge",
    sub: "Discipline · Movement · Mindset",
    icon: "zap",
    accent: "var(--ink)",
  },
};

const useApplyModal = () => {
  const [open, setOpen] = React.useState(null);
  return {
    open,
    openApply: (key = "rehab") => setOpen(key),
    close: () => setOpen(null),
  };
};

const ApplyModal = ({ serviceKey, onClose }) => {
  const [service, setService] = React.useState(SERVICES_META[serviceKey] ? serviceKey : "rehab");
  const meta = SERVICES_META[service] || SERVICES_META.rehab;
  // The three core programs people can apply to; the Reset Challenge only
  // appears as an option when the modal was opened from its own button.
  const serviceOptions = serviceKey === "ramadan"
    ? ["ramadan", "rehab", "pt", "online"]
    : ["rehab", "pt", "online"];
  const [form, setForm] = React.useState({
    name: "", email: "", phone: "",
    location: "Netherlands",
    goal: "",
    experience: "Some training experience",
    when: "Within 2 weeks",
    notes: "",
  });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);

  // Close on escape
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose]);

  const set = (k, v) => {
    setForm((f) => ({ ...f, [k]: v }));
    if (errors[k]) setErrors((e) => ({ ...e, [k]: null }));
  };

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Your name, please.";
    if (!form.email.trim()) e.email = "Email is required.";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "That email looks off.";
    if (!form.goal.trim()) e.goal = "Tell us the goal in a sentence.";
    return e;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    if (submitting) return;
    setSubmitting(true);
    setSubmitError(null);
    try {
      const res = await fetch("https://formspree.io/f/mqeowyzr", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          program: meta.title,
          name: form.name,
          email: form.email,
          phone: form.phone || "—",
          location: form.location,
          goal: form.goal,
          experience: form.experience,
          ideal_start: form.when,
          notes: form.notes || "—",
          _subject: `New application — ${meta.title} — ${form.name}`,
        }),
      });
      if (res.ok) {
        setSubmitted(true);
      } else {
        const data = await res.json().catch(() => ({}));
        setSubmitError(
          (data.errors && data.errors.map((x) => x.message).join(", ")) ||
          "Something went wrong. Please try again, or email info@7araka.co directly."
        );
      }
    } catch (err) {
      setSubmitError("Network error — please check your connection and try again.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="modal-scrim" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true" aria-labelledby="apply-title">
        <div className="modal-head">
          <div>
            <div style={{
              display: "inline-flex", alignItems: "center", gap: 10,
              padding: "6px 10px", borderRadius: 999,
              background: meta.accent === "var(--cursor-primary)" ? "var(--cursor-primary)" : "var(--ink)",
              color: meta.accent === "var(--cursor-primary)" ? "var(--ink)" : "var(--canvas)",
              fontSize: 12, fontWeight: 500,
            }}>
              <Icon name={meta.icon} size={13} />
              Apply
            </div>
            <h3 id="apply-title" className="display-md" style={{ marginTop: 12 }}>{meta.title}</h3>
            <div className="text-body" style={{ fontSize: 14, marginTop: 4 }}>{meta.sub}</div>
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Close">
            <Icon name="x" size={16} />
          </button>
        </div>

        {submitted ? (
          <div style={{ padding: "32px 24px 28px", textAlign: "center" }}>
            <div style={{
              width: 56, height: 56, borderRadius: 999,
              background: "var(--cursor-primary)", color: "var(--ink)",
              display: "grid", placeItems: "center", margin: "0 auto 16px"
            }}>
              <Icon name="check" size={22} stroke={2} />
            </div>
            <h4 className="display-sm">Application received.</h4>
            <p className="text-body" style={{ marginTop: 8, maxWidth: 360, marginInline: "auto" }}>
              We'll be in touch within 48 hours to schedule your intake call.
              Check your inbox at <strong style={{ color: "var(--ink)" }}>{form.email}</strong>.
            </p>
            <div style={{ marginTop: 24 }}>
              <Button variant="primary" onClick={onClose}>Close</Button>
            </div>
          </div>
        ) : (
          <form onSubmit={submit}>
            <div className="modal-body">
              <div className="field">
                <label>Choose your program</label>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 8 }}>
                  {serviceOptions.map((key) => {
                    const m = SERVICES_META[key];
                    const active = key === service;
                    return (
                      <button
                        key={key}
                        type="button"
                        onClick={() => setService(key)}
                        aria-pressed={active}
                        style={{
                          display: "flex", alignItems: "center", gap: 8,
                          padding: "10px 12px", borderRadius: 10, cursor: "pointer",
                          font: "inherit", fontSize: 13, fontWeight: 500, textAlign: "left",
                          background: active ? "var(--ink)" : "transparent",
                          color: active ? "var(--canvas)" : "var(--body)",
                          border: active ? "1px solid var(--ink)" : "1px solid var(--hairline-strong)",
                          minHeight: 44,
                        }}
                      >
                        <Icon name={m.icon} size={14} />
                        {m.title}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="grid-2" style={{ gap: 14 }}>
                <div className={`field ${errors.name ? "error" : ""}`}>
                  <label>Full name</label>
                  <input value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="Your name" />
                  {errors.name && <span className="err">{errors.name}</span>}
                </div>
                <div className={`field ${errors.email ? "error" : ""}`}>
                  <label>Email</label>
                  <input value={form.email} onChange={(e) => set("email", e.target.value)} placeholder="you@example.com" />
                  {errors.email && <span className="err">{errors.email}</span>}
                </div>
              </div>

              <div className="grid-2" style={{ gap: 14 }}>
                <div className="field">
                  <label>Phone (optional)</label>
                  <input value={form.phone} onChange={(e) => set("phone", e.target.value)} placeholder="+31 ··· ··· ···" />
                </div>
                <div className="field">
                  <label>Location</label>
                  <select value={form.location} onChange={(e) => set("location", e.target.value)}>
                    <option>Netherlands</option>
                    <option>Belgium</option>
                    <option>Germany</option>
                    <option>UK</option>
                    <option>Elsewhere (online only)</option>
                  </select>
                </div>
              </div>

              <div className={`field ${errors.goal ? "error" : ""}`}>
                <label>What's the goal?</label>
                <input value={form.goal} onChange={(e) => set("goal", e.target.value)} placeholder="Recover from a lower-back injury, build strength, run a half-marathon…" />
                {errors.goal && <span className="err">{errors.goal}</span>}
              </div>

              <div className="grid-2" style={{ gap: 14 }}>
                <div className="field">
                  <label>Training experience</label>
                  <select value={form.experience} onChange={(e) => set("experience", e.target.value)}>
                    <option>New to training</option>
                    <option>Some training experience</option>
                    <option>Trained consistently for 1–3 years</option>
                    <option>3+ years, intermediate / advanced</option>
                  </select>
                </div>
                <div className="field">
                  <label>Ideal start</label>
                  <select value={form.when} onChange={(e) => set("when", e.target.value)}>
                    <option>This week</option>
                    <option>Within 2 weeks</option>
                    <option>Within a month</option>
                    <option>Just exploring</option>
                  </select>
                </div>
              </div>

              <div className="field">
                <label>Anything we should know?</label>
                <textarea value={form.notes} onChange={(e) => set("notes", e.target.value)} placeholder="Past injuries, schedule constraints, what you've tried before…" />
              </div>
            </div>
            <div className="modal-foot" style={{
              borderTop: "1px solid var(--hairline-soft)",
              justifyContent: "space-between",
              alignItems: "center",
            }}>
              <span className="text-body" style={{ fontSize: 12 }}>
                {submitError ? (
                  <span style={{ color: "#c0392b" }}>{submitError}</span>
                ) : (
                  <>
                    <Icon name="clock" size={12} style={{ verticalAlign: "-2px", marginRight: 4 }} />
                    We reply within 48 hours.
                  </>
                )}
              </span>
              <div style={{ display: "inline-flex", gap: 8 }}>
                <Button variant="ghost" onClick={onClose}>Cancel</Button>
                <Button type="submit" variant="accent" iconRight={submitting ? null : "arrow-right"} disabled={submitting}>{submitting ? "Sending…" : "Submit application"}</Button>
              </div>
            </div>
          </form>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { ApplyModal, useApplyModal, SERVICES_META });
