/* global React, Icon, LogoMark */
// ===== Books In The Loop — Contact + Footer =====
const { useState: useCS } = React;

const SERVICE_CHIPS = [
  "Monthly bookkeeping", "Catch-up / clean-up", "Payroll", "Reconciliation",
  "Reports", "1099s", "Software setup", "Not sure yet",
];

// Contact form endpoint (booksintheloop-form worker). Same-origin via the
// booksintheloop.com/api/* worker route (see form-worker/wrangler.toml).
const FORM_ENDPOINT = "/api/contact";

function Contact({ onNav }) {
  const [data, setData] = useCS({ name: "", email: "", company: "", message: "", how: "Book a free consultation" });
  const [chips, setChips] = useCS([]);
  const [errors, setErrors] = useCS({});
  const [sent, setSent] = useCS(false);
  const [sending, setSending] = useCS(false);
  const [sendError, setSendError] = useCS("");
  const [hp, setHp] = useCS(""); // honeypot — must stay empty

  const set = (k) => (e) => setData((d) => ({ ...d, [k]: e.target.value }));
  const toggleChip = (c) => setChips((arr) => (arr.includes(c) ? arr.filter((x) => x !== c) : [...arr, c]));

  const validate = () => {
    const er = {};
    if (!data.name.trim()) er.name = "Please enter your name";
    if (!data.email.trim()) er.email = "Please enter your email";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) er.email = "That email looks off";
    if (!data.message.trim()) er.message = "Tell us a little about your needs";
    setErrors(er);
    return Object.keys(er).length === 0;
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    setSending(true);
    setSendError("");
    try {
      const res = await fetch(FORM_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: data.name,
          email: data.email,
          company: data.company,
          how: data.how,
          message: data.message,
          services: chips,
          website: hp,
        }),
      });
      if (!res.ok) throw new Error("Request failed");
      setSent(true);
    } catch (err) {
      setSendError("Something went wrong sending your message. Please email hello@booksintheloop.com directly.");
    } finally {
      setSending(false);
    }
  };

  return (
    <section className="section section--paper" id="contact">
      <div className="wrap contact__grid">
        <div className="contact__info reveal">
          <div className="sec-head" style={{ gap: 18 }}>
            <div className="eyebrow">Let's talk</div>
            <h2 className="display h-md">Book your free<br />consultation.</h2>
            <p className="lede" style={{ fontSize: 17 }}>
              Thirty minutes, no pressure. We'll look at where your books are and map out exactly
              how we'd help. Prefer to reach out directly? We're easy to find.
            </p>
          </div>
          <div style={{ display: "grid", gap: 18, marginTop: 6 }}>
            <a className="cinfo" href="mailto:hello@booksintheloop.com">
              <span className="cinfo__ic"><Icon name="mail" size={20} /></span>
              <span><h4>Email</h4><span style={{ fontSize: 18, fontWeight: 500 }}>hello@booksintheloop.com</span></span>
            </a>
            <div className="cinfo">
              <span className="cinfo__ic"><Icon name="pin" size={20} /></span>
              <span><h4>Based in</h4><p>Monson, Massachusetts</p><span className="sub">Working with local &amp; remote clients</span></span>
            </div>
            <div className="cinfo">
              <span className="cinfo__ic"><Icon name="clock" size={20} /></span>
              <span><h4>Hours</h4><p>Mon–Fri · 9am–5pm ET</p><span className="sub">Replies within one business day</span></span>
            </div>
          </div>
        </div>

        <div className="reveal d2">
          {!sent ? (
            <form className="form" onSubmit={submit} noValidate>
              <input
                type="text"
                name="website"
                value={hp}
                onChange={(e) => setHp(e.target.value)}
                tabIndex={-1}
                autoComplete="off"
                aria-hidden="true"
                style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }}
              />
              <div className="form__row">
                <div className={"field" + (errors.name ? " invalid" : "")}>
                  <label>Name <span className="req">*</span></label>
                  <input value={data.name} onChange={set("name")} placeholder="Jane Doe" />
                  <span className="field__err">{errors.name}</span>
                </div>
                <div className={"field" + (errors.email ? " invalid" : "")}>
                  <label>Email <span className="req">*</span></label>
                  <input value={data.email} onChange={set("email")} placeholder="jane@business.com" />
                  <span className="field__err">{errors.email}</span>
                </div>
              </div>
              <div className="form__row">
                <div className="field">
                  <label>Business name</label>
                  <input value={data.company} onChange={set("company")} placeholder="Your company" />
                </div>
                <div className="field">
                  <label>I'd like to…</label>
                  <select value={data.how} onChange={set("how")}>
                    <option>Book a free consultation</option>
                    <option>Request a quote</option>
                    <option>Ask a quick question</option>
                  </select>
                </div>
              </div>
              <div className="field">
                <label>What do you need help with?</label>
                <div className="chip-row" style={{ marginBottom: 4 }}>
                  {SERVICE_CHIPS.map((c) => (
                    <span key={c} className={"chip" + (chips.includes(c) ? " is-on" : "")} onClick={() => toggleChip(c)}>{c}</span>
                  ))}
                </div>
              </div>
              <div className={"field" + (errors.message ? " invalid" : "")}>
                <label>A little about your business <span className="req">*</span></label>
                <textarea value={data.message} onChange={set("message")} placeholder="What you do, what software you use, and where your books are today…" />
                <span className="field__err">{errors.message}</span>
              </div>
              {sendError && (
                <p className="field__err" style={{ display: "block", marginBottom: 8 }}>{sendError}</p>
              )}
              <div className="form__submit">
                <span className="note">No commitment — just a friendly conversation.</span>
                <button className="btn btn--ink" type="submit" disabled={sending}>
                  {sending ? "Sending…" : "Send message"} <Icon name="arrow" size={17} stroke="#f7f3ea" />
                </button>
              </div>
            </form>
          ) : (
            <div className="form">
              <div className="form__success">
                <div className="ok"><Icon name="check" size={30} stroke="#b8843a" sw={2} /></div>
                <h3>Thanks, {data.name.split(" ")[0] || "there"} — you're in the loop.</h3>
                <p>We've got your note and will get back to you within one business day to set up your free consultation.</p>
                <button className="btn btn--outline-ink" onClick={() => { setSent(false); setData({ name: "", email: "", company: "", message: "", how: "Book a free consultation" }); setChips([]); }}>Send another</button>
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function Footer({ onNav }) {
  const go = (id) => (e) => { e.preventDefault(); onNav(id); };
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer__top">
          <div className="footer__brand">
            <div className="name"><LogoMark size={34} dot="#d3a253" stroke="#e3b566" />Books in the Loop</div>
            <p>Business bookkeeping that keeps small businesses accurate, organized, and always in the loop.</p>
          </div>
          <div className="footer__col">
            <h5>Explore</h5>
            <a href="#services" onClick={go("services")}>Services</a>
            <a href="#process" onClick={go("process")}>How it works</a>
            <a href="#why" onClick={go("why")}>Why us</a>
            <a href="#about" onClick={go("about")}>About</a>
          </div>
          <div className="footer__col">
            <h5>Get in touch</h5>
            <a href="mailto:hello@booksintheloop.com">hello@booksintheloop.com</a>
            <p>Monson, Massachusetts</p>
            <p>Mon–Fri · 9am–5pm ET</p>
          </div>
        </div>
        <div className="footer__bottom">
          <p>© {new Date().getFullYear()} Books in the Loop · Business Bookkeeping. All rights reserved.</p>
          <div className="legal">
            <span style={{ fontSize: 13, color: "rgba(247,243,234,.45)" }}>Bookkeeping services · not a CPA firm</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Contact, Footer });
