/* CrickAI marketing — "Send us a message" form (inline section + pop-up)
   Sends through Web3Forms (web3forms.com), which emails each message to the recipient
   set for this form on app.web3forms.com. Key: window.CRICKAI_WEB3FORMS_KEY.
   If no endpoint is set, runs in demo mode: shows success without sending. */

const CONTACT_ROLES = ["Player", "Coach", "Academy", "Local league", "Tournament organizer", "Sponsor", "Other"];
const CONTACT_TOPICS = {
  general: { label: "General enquiry", subject: "Website message — CrickAI" },
  pilot: { label: "Book a pilot", subject: "Pilot program — CrickAI",
    placeholder: "Tell us about your organization, roughly how many matches you play a month, and what you'd like to achieve." },
  partnership: { label: "Partnership", subject: "Partnership enquiry — CrickAI",
    placeholder: "What kind of partnership do you have in mind?" },
  early: { label: "Early-bird beta", subject: "Early-bird beta — CrickAI",
    placeholder: "Anything you'd like us to know? (optional)" },
};

/* Anywhere on the page: window.openContact("pilot") opens the pop-up. */
window.openContact = function (topic) {
  window.dispatchEvent(new CustomEvent("crickai:contact", { detail: { topic: topic || "general" } }));
};

function ContactForm({ initialTopic = "general", compact = false, onDone }) {
  const [topic, setTopic] = React.useState(initialTopic);
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error
  const [error, setError] = React.useState("");
  const t = CONTACT_TOPICS[topic] || CONTACT_TOPICS.general;
  const messageRequired = topic !== "early";

  React.useEffect(() => { setTopic(initialTopic); }, [initialTopic]);

  async function submit(e) {
    e.preventDefault();
    const form = e.currentTarget;
    const data = new FormData(form);
    if (data.get("_gotcha")) { setStatus("sent"); return; } // bot filled the hidden field
    const key = window.CRICKAI_WEB3FORMS_KEY;
    data.delete("_gotcha");
    data.set("topic", t.label);
    data.set("access_key", key || "");
    data.set("subject", "[crickai.com] " + t.label + " — " + (data.get("name") || "").toString().trim());
    data.set("from_name", "CrickAI website");
    data.set("replyto", data.get("email") || ""); // reply goes straight to the visitor
    setStatus("sending"); setError("");

    const endpoint = "https://api.web3forms.com/submit";
    if (!key) { // demo mode
      await new Promise((r) => setTimeout(r, 700));
      setStatus("sent"); form.reset(); return;
    }
    try {
      const res = await fetch(endpoint, { method: "POST", body: data, headers: { Accept: "application/json" } });
      let body = {};
      try { body = await res.json(); } catch (_) { /* non-JSON reply */ }
      if (!res.ok || body.success === false) {
        const err = new Error("Server responded " + res.status);
        if (res.status === 429) err.userMessage = "Too many messages just now — please wait a minute.";
        throw err;
      }
      setStatus("sent"); form.reset();
    } catch (err) {
      setStatus("error");
      setError(err.userMessage || "We couldn't send your message just now.");
    }
  }

  if (status === "sent") {
    return (
      <div className="cform__done" role="status">
        <div className="cform__done-ic"><Icon name="check" size={26} /></div>
        <h3>Message sent — thank you.</h3>
        <p>We read every message and usually reply within one business day.</p>
        {!window.CRICKAI_WEB3FORMS_KEY ? <p className="cform__demo">Demo mode: no form address is set yet, so nothing was actually sent.</p> : null}
        <div className="cform__done-actions">
          <button type="button" className="btn btn--ghost btn--sm" onClick={() => setStatus("idle")}>Send another</button>
          {onDone ? <button type="button" className="btn btn--primary btn--sm" onClick={onDone}>Close</button> : null}
        </div>
      </div>
    );
  }

  const mailHref = "mailto:" + window.CRICKAI_EMAIL + "?subject=" + encodeURIComponent(t.subject);

  return (
    <form className={"cform" + (compact ? " cform--compact" : "")} onSubmit={submit} noValidate={false}>
      <div className="cform__topics" role="radiogroup" aria-label="What's this about?">
        {Object.entries(CONTACT_TOPICS).map(([k, v]) => (
          <button type="button" key={k} role="radio" aria-checked={topic === k}
            className={"cform__topic" + (topic === k ? " is-on" : "")} onClick={() => setTopic(k)}>{v.label}</button>
        ))}
      </div>

      <div className="cform__grid">
        <label className="cform__field">
          <span>Name</span>
          <input name="name" type="text" autoComplete="name" required placeholder="Your name" />
        </label>
        <label className="cform__field">
          <span>Email</span>
          <input name="email" type="email" autoComplete="email" required placeholder="you@club.com" />
        </label>
        <label className="cform__field">
          <span>I am a…</span>
          <select name="role" required defaultValue="">
            <option value="" disabled>Choose one</option>
            {CONTACT_ROLES.map((r) => <option key={r} value={r}>{r}</option>)}
          </select>
        </label>
        <label className="cform__field">
          <span>Club / organization <em>optional</em></span>
          <input name="organization" type="text" autoComplete="organization" placeholder="e.g. Coastal Cricket Academy" />
        </label>
        <label className="cform__field cform__field--full">
          <span>Location <em>optional</em></span>
          <input name="location" type="text" placeholder="City, country" />
        </label>
        <label className="cform__field cform__field--full">
          <span>Message{messageRequired ? "" : <em> optional</em>}</span>
          <textarea name="message" rows={compact ? 4 : 5} required={messageRequired} maxLength={4000}
            placeholder={t.placeholder || "How can we help?"}></textarea>
        </label>
      </div>

      {/* Honeypot — hidden from people, bots fill it in */}
      <input type="text" name="_gotcha" tabIndex={-1} autoComplete="off" className="cform__hp" aria-hidden="true" />

      {status === "error" ? (
        <p className="cform__err" role="alert">{error} Please try again, or <a href={mailHref}>email us at {window.CRICKAI_EMAIL}</a>.</p>
      ) : null}

      <div className="cform__foot">
        <button type="submit" className="btn btn--primary btn--lg" disabled={status === "sending"}>
          {status === "sending" ? "Sending…" : <React.Fragment><Icon name="mail" size={18} />Send message</React.Fragment>}
        </button>
        <span className="cform__fine">Prefer email? <a href={mailHref}>{window.CRICKAI_EMAIL}</a></span>
      </div>
    </form>
  );
}

function ContactModal() {
  const [open, setOpen] = React.useState(false);
  const [topic, setTopic] = React.useState("general");
  const lastFocus = React.useRef(null);
  const panel = React.useRef(null);

  React.useEffect(() => {
    const onOpen = (e) => { lastFocus.current = document.activeElement; setTopic(e.detail.topic); setOpen(true); };
    window.addEventListener("crickai:contact", onOpen);
    return () => window.removeEventListener("crickai:contact", onOpen);
  }, []);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") close(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    setTimeout(() => { const f = panel.current && panel.current.querySelector("input[name=name]"); if (f) f.focus(); }, 30);
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [open]);

  function close() {
    setOpen(false);
    if (lastFocus.current && lastFocus.current.focus) lastFocus.current.focus();
  }

  if (!open) return null;
  return (
    <div className="cmodal" onMouseDown={(e) => { if (e.target === e.currentTarget) close(); }}>
      <div className="cmodal__panel" role="dialog" aria-modal="true" aria-labelledby="cmodal-title" ref={panel}>
        <button type="button" className="cmodal__x" aria-label="Close" onClick={close}>×</button>
        <Eyebrow>Send us a message</Eyebrow>
        <h2 id="cmodal-title">Let's talk cricket.</h2>
        <ContactForm initialTopic={topic} compact onDone={close} />
      </div>
    </div>
  );
}

function ContactSection() {
  return (
    <section className="contact" id="contact">
      <div className="wrap contact__inner">
        <div className="contact__intro">
          <Eyebrow>Contact</Eyebrow>
          <h2>Send us a message.</h2>
          <p>Questions about streaming, coaching analytics, or a pilot for your club?
            Drop us a line and a real person from the CrickAI team will get back to you.</p>
          <ul className="contact__points">
            <li><Icon name="clock" size={18} />Replies within one business day</li>
            <li><Icon name="handshake" size={18} />Pilots for academies, leagues and tournaments</li>
            <li><Icon name="mail" size={18} /><a href={"mailto:" + window.CRICKAI_EMAIL}>{window.CRICKAI_EMAIL}</a></li>
          </ul>
        </div>
        <div className="contact__card">
          <ContactForm />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { ContactForm, ContactModal, ContactSection });
