/* global React, ReactDOM, AnnouncementBar, Nav, Newsletter, Footer, useState */
/* TORI STONE — Contact page app */

function ContactSection() {
  const [status, setStatus] = useState("idle"); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus("sending");
    setErrorMsg("");

    const form = e.currentTarget;
    const data = new FormData(form);
    // Plain object for JSON
    const payload = {};
    for (const [k, v] of data.entries()) payload[k] = v;

    try {
      const res = await fetch("https://formsubmit.co/ajax/tori@toristonebooks.com", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json"
        },
        body: JSON.stringify(payload)
      });
      const json = await res.json().catch(() => ({}));
      if (res.ok && (json.success === "true" || json.success === true)) {
        setStatus("sent");
        form.reset();
      } else {
        setStatus("error");
        setErrorMsg(json.message || "Something went wrong. Please email tori@toristonebooks.com directly.");
      }
    } catch (err) {
      setStatus("error");
      setErrorMsg("Network error. Please email tori@toristonebooks.com directly.");
    }
  };

  return (
    <section id="contact" className="section">
      <div className="frame frame--narrow">
        <div className="section__head">
          <div className="section__eyebrow">Get in Touch</div>
          <h2 className="section__title">Say <span className="ital">hello</span></h2>
          <p className="section__sub">For press, rights, collaborations, or just to tell me a book ruined you in the best way.</p>
        </div>

        {status === "sent" ? (
          <div className="contact__success">
            <p className="contact__success-heading">Message sent.</p>
            <p className="contact__success-body">I read every note. I'll reply when I can.</p>
            <a href="index.html" className="btn btn--ghost">Back home <span className="arrow"></span></a>
          </div>
        ) : (
          <form className="contact-form" onSubmit={handleSubmit}>
            <input type="hidden" name="_subject" value="New message from toristonebooks.com" />
            <input type="hidden" name="_template" value="table" />
            {/* honeypot — humans leave blank, bots fill it */}
            <input type="text" name="_honey" style={{display:"none"}} tabIndex="-1" autoComplete="off" />

            <label className="contact-form__row">
              <span className="contact-form__label">Name</span>
              <input type="text" name="name" required autoComplete="name" placeholder="Your name" />
            </label>
            <label className="contact-form__row">
              <span className="contact-form__label">Email</span>
              <input type="email" name="email" required autoComplete="email" placeholder="your@email.com" />
            </label>
            <label className="contact-form__row">
              <span className="contact-form__label">Reason</span>
              <select name="reason" defaultValue="reader">
                <option value="reader">Reader note</option>
                <option value="press">Press / Media</option>
                <option value="rights">Rights / Foreign / Film</option>
                <option value="collab">Collaboration</option>
                <option value="other">Something else</option>
              </select>
            </label>
            <label className="contact-form__row">
              <span className="contact-form__label">Message</span>
              <textarea name="message" required rows="6" placeholder="Tell me what's on your mind..."></textarea>
            </label>

            <button type="submit" className="btn contact-form__submit" disabled={status === "sending"}>
              {status === "sending" ? "Sending..." : "Send message"} <span className="arrow"></span>
            </button>

            {status === "error" && (
              <p className="contact-form__error">{errorMsg}</p>
            )}

            <p className="contact-form__note">First-time setup note: formsubmit may ask Tori to confirm her inbox on the very first submission. After that, every message lands at tori@toristonebooks.com directly.</p>
          </form>
        )}
      </div>
    </section>
  );
}

function ContactApp() {
  React.useEffect(() => {
    document.documentElement.setAttribute("data-variation", "luxe");
    document.documentElement.setAttribute("data-density", "regular");
    document.body.setAttribute("data-atmosphere", "on");
  }, []);

  return (
    <>
      <AnnouncementBar />
      <Nav />
      <ContactSection />
      <Footer />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<ContactApp />);
