/* global React */

// Design partner modal — simple 4-field form, POSTs to Formspree.

const PARTNER_ENDPOINT = "https://formspree.io/f/xykoakag";

const PartnerModalCtx = React.createContext({ open: () => {} });

function usePartnerModal() {
  return React.useContext(PartnerModalCtx);
}

function PartnerModalProvider({ children }) {
  const [open, setOpen] = React.useState(false);
  const api = React.useMemo(() => ({ open: () => setOpen(true) }), []);
  return (
    <PartnerModalCtx.Provider value={api}>
      {children}
      {open && <PartnerModal onClose={() => setOpen(false)} />}
    </PartnerModalCtx.Provider>
  );
}

const EMPTY = {
  name: "",
  email: "",
  organisation: "",
  role: "",
  focus: "",
  timeline: "",
  message: "",
};

const ROLE_OPTIONS = [
  "Founder / CEO",
  "Product / Engineering leader",
  "Operator",
  "Investor",
  "Other",
];
const FOCUS_OPTIONS = [
  "Music & rights",
  "Capital markets",
  "Insurance",
  "Another regulated domain",
  "Just exploring",
];
const TIMELINE_OPTIONS = [
  "Exploring ideas",
  "Active project",
  "Within 6 months",
  "Already in flight",
];

function PartnerModal({ onClose }) {
  const [form, setForm] = React.useState(EMPTY);
  const [errors, setErrors] = React.useState({});
  const [state, setState] = React.useState("idle"); // idle | sending | success | error
  const [errorMsg, setErrorMsg] = React.useState("");
  const dialogRef = React.useRef(null);
  const firstFieldRef = React.useRef(null);

  // Lock scroll + escape to close + focus first field
  React.useEffect(() => {
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => {
      if (e.key === "Escape" && state !== "sending") onClose();
    };
    window.addEventListener("keydown", onKey);
    const t = setTimeout(() => firstFieldRef.current?.focus(), 60);
    return () => {
      document.body.style.overflow = prevOverflow;
      window.removeEventListener("keydown", onKey);
      clearTimeout(t);
    };
  }, [onClose, state]);

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

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Required";
    if (!form.email.trim()) e.email = "Required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(form.email.trim())) e.email = "Use a valid email";
    if (!form.organisation.trim()) e.organisation = "Required";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const onSubmit = async (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setState("sending");
    setErrorMsg("");

    // Client-side rate limit: ignore re-submits within 30s in the same session.
    // Bot mitigation only; real rate limiting lives server-side at Formspree.
    try {
      const lastSubmit = parseInt(sessionStorage.getItem("partner_last_submit") || "0", 10);
      const now = Date.now();
      if (now - lastSubmit < 30000) {
        // Silently pretend it worked — don't give bots feedback.
        setState("success");
        return;
      }
      sessionStorage.setItem("partner_last_submit", String(now));
    } catch (_) { /* sessionStorage unavailable; continue */ }

    try {
      const body = new FormData();
      body.append("name", form.name);
      body.append("email", form.email);
      body.append("organisation", form.organisation);
      body.append("role", form.role);
      body.append("focus", form.focus);
      body.append("timeline", form.timeline);
      body.append("message", form.message);
      body.append("_subject", "Tavyaan — new enquiry");
      body.append("_replyto", form.email);
      // Formspree honeypot — leave empty; if a bot fills it, Formspree drops the submission.
      body.append("_gotcha", "");

      const res = await fetch(PARTNER_ENDPOINT, {
        method: "POST",
        body,
        headers: { Accept: "application/json" },
      });
      if (res.ok) {
        setState("success");
      } else {
        const data = await res.json().catch(() => ({}));
        const msg =
          data && data.errors && data.errors[0] && data.errors[0].message
            ? data.errors[0].message
            : "Something went wrong. Try again or email enquiry@tavyaan.com.";
        setErrorMsg(msg);
        setState("error");
      }
    } catch (_) {
      setErrorMsg("Network error. Try again or email enquiry@tavyaan.com.");
      setState("error");
    }
  };

  const onBackdrop = (e) => {
    if (e.target === e.currentTarget && state !== "sending") onClose();
  };

  return (
    <div className="pm-backdrop" onMouseDown={onBackdrop} role="dialog" aria-modal="true" aria-labelledby="pm-title">
      <div className="pm-dialog" ref={dialogRef}>
        <button className="pm-close" onClick={onClose} aria-label="Close" disabled={state === "sending"}>
          <svg viewBox="0 0 14 14" aria-hidden="true">
            <path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
          </svg>
        </button>

        {state === "success" ? (
          <div className="pm-success">
            <div className="pm-success-mark" aria-hidden="true">
              <svg viewBox="0 0 32 32">
                <circle cx="16" cy="16" r="15" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.3" />
                <path d="M9 16.5l4.5 4.5L23 11" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <div className="pm-eyebrow"><span className="pm-dot"></span>Enquiry received</div>
            <h2 id="pm-title" className="pm-title">Thanks, {form.name.split(" ")[0] || "there"}. We&rsquo;ll be in touch.</h2>
            <p className="pm-sub">
              A founder will respond from <b>enquiry@tavyaan.com</b> inside two business days.
            </p>
            <div className="pm-actions">
              <button type="button" className="btn" onClick={onClose}>Close</button>
            </div>
          </div>
        ) : (
          <form className="pm-form" onSubmit={onSubmit} noValidate>
            {/* Honeypot — invisible to humans; Formspree drops submissions where it's filled */}
            <input
              type="text"
              name="_gotcha"
              style={{ display: 'none' }}
              tabIndex={-1}
              autoComplete="off"
              aria-hidden="true"
            />
            <div className="pm-head">
              <div className="pm-eyebrow"><span className="pm-dot"></span>Get in touch</div>
              <h2 id="pm-title" className="pm-title">Start a conversation.</h2>
              <p className="pm-sub">A founder responds personally inside two business days.</p>
            </div>

            <div className="pm-grid">
              <Field
                inputRef={firstFieldRef}
                label="Full name"
                name="name"
                value={form.name}
                onChange={(v) => set("name", v)}
                error={errors.name}
                autoComplete="name"
              />
              <Field
                label="Work email"
                name="email"
                type="email"
                value={form.email}
                onChange={(v) => set("email", v)}
                error={errors.email}
                autoComplete="email"
              />
              <Field
                label="Organisation"
                name="organisation"
                value={form.organisation}
                onChange={(v) => set("organisation", v)}
                error={errors.organisation}
                autoComplete="organization"
                full
              />
              <ChipField
                label="You are…"
                name="role"
                value={form.role}
                onChange={(v) => set("role", v)}
                options={ROLE_OPTIONS}
              />
              <ChipField
                label="Where you're focused"
                name="focus"
                value={form.focus}
                onChange={(v) => set("focus", v)}
                options={FOCUS_OPTIONS}
              />
              <ChipField
                label="Timeline"
                name="timeline"
                value={form.timeline}
                onChange={(v) => set("timeline", v)}
                options={TIMELINE_OPTIONS}
              />
              <div className="pm-field pm-field-full">
                <label htmlFor="pm-message" className="pm-label">
                  What would make this worth a call? <span className="pm-optional">optional</span>
                </label>
                <textarea
                  id="pm-message"
                  name="message"
                  rows={4}
                  value={form.message}
                  onChange={(e) => set("message", e.target.value)}
                  placeholder="A few lines is enough."
                  className="pm-input pm-textarea"
                />
              </div>
            </div>

            {state === "error" && (
              <div className="pm-error-banner">{errorMsg}</div>
            )}

            <div className="pm-foot">
              <div className="pm-foot-meta">
                <span className="pm-mono">enquiry@tavyaan.com</span>
              </div>
              <div className="pm-actions">
                <button type="button" className="btn ghost" onClick={onClose} disabled={state === "sending"}>Cancel</button>
                <button type="submit" className="btn" disabled={state === "sending"}>
                  {state === "sending" ? "Sending…" : "Submit"}
                  {state !== "sending" && (
                    <svg className="arr" viewBox="0 0 14 14" aria-hidden="true">
                      <path d="M2 7h10M8 3l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  )}
                </button>
              </div>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

function ChipField({ label, name, value, onChange, options }) {
  return (
    <div className="pm-field pm-field-full pm-chipfield">
      <label className="pm-label">
        {label} <span className="pm-optional">optional</span>
      </label>
      <div className="pm-chips" role="radiogroup" aria-label={label}>
        {options.map((opt) => {
          const active = value === opt;
          return (
            <button
              key={opt}
              type="button"
              role="radio"
              aria-checked={active}
              className={"pm-chip" + (active ? " is-active" : "")}
              onClick={() => onChange(active ? "" : opt)}
            >
              <span className="pm-chip-dot" aria-hidden="true"></span>
              <span className="pm-chip-label">{opt}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Field({ label, name, type = "text", value, onChange, error, inputRef, autoComplete, full }) {
  const id = "pm-" + name;
  return (
    <div className={"pm-field" + (full ? " pm-field-full" : "") + (error ? " pm-field-error" : "")}>
      <label htmlFor={id} className="pm-label">{label}</label>
      <input
        id={id}
        ref={inputRef}
        name={name}
        type={type}
        autoComplete={autoComplete}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="pm-input"
        spellCheck={type === "email" ? false : undefined}
      />
      {error && <span className="pm-error">{error}</span>}
    </div>
  );
}

// Export to window so app.jsx can use them.
Object.assign(window, { PartnerModalProvider, usePartnerModal });
