/* global React */
const { useState } = React;

/* ── Form delivery ──────────────────────────────────────────────
   Paste your free Web3Forms access key below to receive booking
   requests automatically at yaro@pausa.pt (sign up at web3forms.com
   with that address — takes 1 minute). While this is empty the form
   gracefully falls back to opening a pre-filled email instead.        */
const WEB3FORMS_KEY = "e1f43f3f-17b9-4164-a588-cc235cdb160d";

function BookingModal({ open, onClose }) {
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [errs, setErrs] = useState({});
  const [vals, setVals] = useState({ name: "", email: "", company: "", size: "", note: "" });

  function set(k, v) { setVals((s) => ({ ...s, [k]: v })); }

  function validate() {
    const e = {};
    if (!vals.name.trim()) e.name = "Please tell us your name.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(vals.email)) e.email = "Enter a valid work email.";
    if (!vals.company.trim()) e.company = "Your company, please.";
    if (!vals.size) e.size = "Select a team size.";
    setErrs(e);
    return Object.keys(e).length === 0;
  }

  function mailtoFallback() {
    const subject = `Discovery call request — ${vals.company || vals.name}`;
    const body = [
      `Name: ${vals.name}`,
      `Work email: ${vals.email}`,
      `Company: ${vals.company}`,
      `Leadership team size: ${vals.size}`,
      vals.note ? `Notes: ${vals.note}` : null,
      "",
      "— Sent from the Pausa landing page.",
    ].filter((l) => l !== null).join("\n");
    window.location.href = `mailto:yaro@pausa.pt?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
  }

  async function submit(ev) {
    ev.preventDefault();
    if (!validate()) return;

    // No key configured → open a pre-filled email instead.
    if (!WEB3FORMS_KEY) { mailtoFallback(); setSent(true); return; }

    setSending(true);
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          access_key: WEB3FORMS_KEY,
          subject: `Discovery call request — ${vals.company || vals.name}`,
          from_name: "Pausa landing page",
          name: vals.name,
          email: vals.email,
          company: vals.company,
          team_size: vals.size,
          message: vals.note || "(no extra notes)",
        }),
      });
      const data = await res.json();
      if (data.success) { setSent(true); }
      else { mailtoFallback(); setSent(true); }
    } catch (err) {
      mailtoFallback(); setSent(true);
    } finally {
      setSending(false);
    }
  }

  function close() {
    onClose();
    // reset shortly after the close transition
    setTimeout(() => { setSent(false); setErrs({}); setVals({ name: "", email: "", company: "", size: "", note: "" }); }, 400);
  }

  return (
    <div className={"modal-overlay" + (open ? " open" : "")} onMouseDown={(e) => { if (e.target === e.currentTarget) close(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        <button className="close" onClick={close} aria-label="Close">×</button>

        {sent ? (
          <div className="modal-success">
            <div className="check">
              <svg width="26" height="26" viewBox="0 0 26 26" fill="none"><path d="M6 13.5l4.6 4.5L20 7.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </div>
            <h3 className="h3">Thank you, {vals.name.split(" ")[0]}.</h3>
            <p className="modal-sub" style={{ marginBottom: 8 }}>
              We've got your details and will reply within one working day. If an email draft opened instead, just hit send. You can also write us directly at <a href="mailto:yaro@pausa.pt" style={{ color: "var(--moss)" }}>yaro@pausa.pt</a>.
            </p>
            <button className="btn btn-ghost" style={{ margin: "12px auto 0" }} onClick={close}>Close</button>
          </div>
        ) : (
          <form onSubmit={submit} noValidate>
            <span className="kicker">Discovery call</span>
            <h3 className="h3">Book a 30-minute conversation.</h3>
            <p className="modal-sub">Tell us a little about your team and we'll find a time. No high-pressure sales.</p>

            <div className={"field" + (errs.name ? " invalid" : "")}>
              <label>Full name</label>
              <input type="text" value={vals.name} onChange={(e) => set("name", e.target.value)} placeholder="Maria Silva" />
              <span className="err">{errs.name}</span>
            </div>

            <div className="field-row">
              <div className={"field" + (errs.email ? " invalid" : "")}>
                <label>Work email</label>
                <input type="email" value={vals.email} onChange={(e) => set("email", e.target.value)} placeholder="maria@company.com" />
                <span className="err">{errs.email}</span>
              </div>
              <div className={"field" + (errs.company ? " invalid" : "")}>
                <label>Company</label>
                <input type="text" value={vals.company} onChange={(e) => set("company", e.target.value)} placeholder="Your company" />
                <span className="err">{errs.company}</span>
              </div>
            </div>

            <div className={"field" + (errs.size ? " invalid" : "")}>
              <label>Leadership team size</label>
              <select value={vals.size} onChange={(e) => set("size", e.target.value)}>
                <option value="" disabled>Select…</option>
                <option>2–5 leaders</option>
                <option>6–9 leaders</option>
                <option>10–12 leaders</option>
                <option>More than 12</option>
              </select>
              <span className="err">{errs.size}</span>
            </div>

            <div className="field">
              <label>Anything we should know? <span style={{ color: "var(--stone)", fontWeight: 400 }}>(optional)</span></label>
              <textarea rows="2" value={vals.note} onChange={(e) => set("note", e.target.value)} placeholder="Context about your team's baseline…"></textarea>
            </div>

            <button type="submit" className="btn btn-primary" disabled={sending}>{sending ? "Sending…" : "Request my call"}<span className="dot"></span></button>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { BookingModal });
