/* form.jsx — contact form, final CTA, footer */
const { I, Logo, track, PHONE, EMAIL, WHATSAPP } = window;

function Field({ label, children, error, htmlFor, full }) {
  return (
    <label className={`field ${full ? "field--full" : ""}`} htmlFor={htmlFor}>
      <span className="field__label">{label}</span>
      {children}
      <span className={`field__err ${error ? "on" : ""}`}>{error || ""}</span>
    </label>);

}

function ContactForm() {
  const SERVICE = [
  { k: "junk", label: "Junk removal", icon: I.truck },
  { k: "clean", label: "Cleaning", icon: I.sparkle },
  { k: "both", label: "Both", icon: I.box }];

  const [f, setF] = React.useState({ name: "", phone: "", email: "", service: "", date: "", message: "" });
  const [err, setErr] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [netErr, setNetErr] = React.useState("");
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));

  // Minimum selectable date for the preferred-date input: today (YYYY-MM-DD, local time)
  const today = React.useMemo(() => {
    const d = new Date();
    const tz = d.getTimezoneOffset() * 60000;
    return new Date(d.getTime() - tz).toISOString().slice(0, 10);
  }, []);

  const WEB3FORMS_KEY = "9b9bfe06-ee32-4eee-bf1b-4e043c41c0ab";
  // Google Apps Script webhook URL → syncs submissions to Google Sheets
  const ZAPIER_WEBHOOK = "https://script.google.com/macros/s/AKfycbw24P5pksKEstvI9bNtHqHBv5iRj9LFZn3kaBEnRR1oG4UPUOBYfVQ-MPg0UfxskI84/exec";
  // Cloudflare Turnstile site key. Leave empty to disable the CAPTCHA challenge.
  const TURNSTILE_SITE_KEY = "";

  const honeypot = React.useRef(null);          // Anti-spam: hidden decoy field
  const mountedAt = React.useRef(Date.now());    // Anti-spam: time-to-submit trap
  const captchaSlot = React.useRef(null);
  const captchaId = React.useRef(null);
  const [captchaToken, setCaptchaToken] = React.useState("");

  // Load and render Cloudflare Turnstile only when a site key is configured.
  React.useEffect(() => {
    if (!TURNSTILE_SITE_KEY) return;
    if (!document.getElementById("cf-turnstile-api")) {
      const s = document.createElement("script");
      s.id = "cf-turnstile-api";
      s.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
      s.async = true; s.defer = true;
      document.head.appendChild(s);
    }
    const render = () => {
      if (window.turnstile && window.turnstile.render && captchaSlot.current && captchaId.current === null) {
        try {
          captchaId.current = window.turnstile.render(captchaSlot.current, {
            sitekey: TURNSTILE_SITE_KEY,
            callback: (token) => setCaptchaToken(token),
            "expired-callback": () => setCaptchaToken(""),
            "error-callback": () => setCaptchaToken("")
          });
        } catch (e) {/* ya renderizado */}
      } else if (captchaId.current === null) {
        setTimeout(render, 300);
      }
    };
    render();
  }, []);

  const validate = () => {
    const e = {};
    if (!f.name.trim()) e.name = "Please tell us your name";
    const digits = f.phone.replace(/\D/g, "");
    if (!f.phone.trim()) e.phone = "We need a number to text your quote";else
    if (digits.length < 10) e.phone = "That doesn't look like a full phone number";
    if (!f.email.trim()) e.email = "We need your email to send the quote confirmation";
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.email)) e.email = "Check the email format";
    if (f.date && f.date < today) e.date = "Please pick a future date";
    if (!f.service) e.service = "Pick a service";
    setErr(e);
    return Object.keys(e).length === 0;
  };
  const submit = async (e) => {
    e.preventDefault();
    if (!validate()) return;

    // Layer 1 — Honeypot: a filled hidden field indicates a bot. Fake success, skip send.
    if (honeypot.current && honeypot.current.value) { setSent(true); return; }
    // Layer 2 — Time trap: submissions under 3s are almost always automated.
    if (Date.now() - mountedAt.current < 3000) { setSent(true); return; }

    // Layer 3 — Cloudflare Turnstile (when configured)
    if (TURNSTILE_SITE_KEY && !captchaToken) {
      setNetErr("Please complete the verification below.");
      return;
    }

    setNetErr("");
    setSending(true);
    const serviceLabel = SERVICE.find((s) => s.k === f.service)?.label || f.service;
    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: `New quote request — ${f.name} (${serviceLabel})`,
          from_name: "AfterMoving Website",
          replyto: f.email || undefined,
          botcheck: "",
          "cf-turnstile-response": captchaToken || undefined,
          "Name": f.name,
          "Phone": f.phone,
          "Email": f.email || "—",
          "Service requested": serviceLabel,
          "Preferred date": f.date || "Not specified",
          "Message": f.message || "—"
        })
      });
      const data = await res.json();
      if (data.success) {
        track("generate_lead", { service: serviceLabel, method: "form" });
        // Also send to Zapier → Google Sheets (fire-and-forget, non-blocking)
        if (ZAPIER_WEBHOOK) {
          fetch(ZAPIER_WEBHOOK, {
            method: "POST",
            mode: "no-cors",
            body: JSON.stringify({
              timestamp: new Date().toISOString(),
              name: f.name, phone: f.phone, email: f.email || "",
              service: serviceLabel, preferred_date: f.date || "",
              message: f.message || "", source: "Landing Page Form"
            })
          }).catch(() => {});
        }
        setSent(true);
      } else {
        setNetErr("Something went wrong sending your request. Please call us instead.");
      }
    } catch (_) {
      setNetErr("We couldn't reach our server. Check your connection or call us instead.");
    } finally {
      setSending(false);
      if (TURNSTILE_SITE_KEY && window.turnstile) { window.turnstile.reset(captchaId.current); setCaptchaToken(""); }
    }
  };

  if (sent) {
    return (
      <div className="form-done card">
        <span className="form-done__tick"><I.check /></span>
        <h3>Thank you, {f.name.split(" ")[0]}! Your request has been received.</h3>
        <p>We've sent a confirmation to <b>{f.email}</b>. A member of our team will review the details and reach out to <b>{f.phone}</b> shortly to confirm your personalized quote.</p>
        <div className="form__or"><span>Speed up your quote — send us photos</span></div>
        <div className="form-done__photo-options">
          <div className="photo-option photo-option--highlight">
            <span className="photo-option__icon" style={{background:"var(--accent)"}}>✉️</span>
            <div>
              <strong>Reply to your confirmation email</strong>
              <span>We sent a confirmation to <b>{f.email}</b> — just reply with your photos attached and we'll get your quote faster.</span>
            </div>
          </div>
          <div className="photo-option">
            <span className="photo-option__icon" style={{background:"var(--navy)"}}>
              <I.phone style={{width:17,height:17,color:"#fff"}} />
            </span>
            <div>
              <strong>Text photos to {PHONE}</strong>
              <span>Open your messages app and send photos to this number</span>
            </div>
          </div>
          <div className="photo-option">
            <a className="photo-option__wa" href={`https://wa.me/${WHATSAPP}?text=${encodeURIComponent("Hi AfterMoving! Sending photos for my quote:")}`} target="_blank" rel="noopener">
              <I.whatsapp style={{width:19,height:19}} />
              <div>
                <strong>Send photos on WhatsApp</strong>
                <span>Tap to open a chat with us</span>
              </div>
            </a>
          </div>
          <a className="photo-option photo-option--call" href={`tel:${PHONE}`}>
            <span className="photo-option__icon" style={{background:"var(--accent)"}}>
              <I.phone style={{width:17,height:17,color:"#fff"}} />
            </span>
            <div>
              <strong>Call us directly</strong>
              <span>{PHONE} · Mon–Sat 8am–6pm, Sun 9am–4pm</span>
            </div>
          </a>
        </div>
      </div>);

  }

  return (
    <form className="form card" onSubmit={submit} noValidate>
      <div className="form-grid">
        <Field label="Full name" htmlFor="f-name" error={err.name}>
          <input id="f-name" className={`inp ${err.name ? "inp--err" : ""}`} value={f.name} onChange={set("name")} placeholder="John Smith" autoComplete="name" />
        </Field>
        <Field label="Phone" htmlFor="f-phone" error={err.phone}>
          <input id="f-phone" className={`inp ${err.phone ? "inp--err" : ""}`} value={f.phone} onChange={set("phone")} placeholder="(415) 555-0142" inputMode="tel" autoComplete="tel" />
        </Field>
        <Field label="Email" htmlFor="f-email" error={err.email}>
          <input id="f-email" className={`inp ${err.email ? "inp--err" : ""}`} value={f.email} onChange={set("email")} placeholder="you@email.com" inputMode="email" autoComplete="email" required />
        </Field>
        <Field label="Preferred date" htmlFor="f-date" error={err.date}>
          <input id="f-date" className={`inp ${err.date ? "inp--err" : ""}`} type="date" min={today} value={f.date} onChange={set("date")} />
        </Field>
        <div className="field field--full">
          <span className="field__label">Service requested</span>
          <div className="seg" role="radiogroup">
            {SERVICE.map((s) =>
            <button type="button" key={s.k} role="radio" aria-checked={f.service === s.k}
            className={`seg__btn ${f.service === s.k ? "on" : ""}`}
            onClick={() => setF((v) => ({ ...v, service: s.k }))}>
                <s.icon />{s.label}
              </button>
            )}
          </div>
          <span className={`field__err ${err.service ? "on" : ""}`}>{err.service || ""}</span>
        </div>
        <Field label="Anything we should know?" htmlFor="f-msg" full>
          <textarea id="f-msg" className="inp inp--area" rows="3" value={f.message} onChange={set("message")} placeholder="3-bed move-out, garage full of furniture, need it cleaned by Friday…" />
        </Field>
      </div>
      {/* Anti-spam honeypot — invisible to users, auto-filled by bots */}
      <input ref={honeypot} type="text" name="botcheck" tabIndex="-1" autoComplete="off"
        aria-hidden="true" style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} />
      {TURNSTILE_SITE_KEY && <div ref={captchaSlot} className="form__captcha"></div>}
      <button className="btn btn--lg btn--block form__submit" type="submit" disabled={sending}>
        {sending ? "Sending…" : <React.Fragment>Get my free quote<I.arrow /></React.Fragment>}
      </button>
      {netErr && <p className="form__neterr">{netErr}</p>}
      <p className="form__fine"><I.shield style={{ width: 15, height: 15, color: "var(--ok)" }} /> No spam, no obligation. We only use your info to send your quote.</p>
      <a href="/get-a-quote" style={{
        display:"flex", alignItems:"center", justifyContent:"space-between",
        gap:"12px", marginTop:"16px", padding:"16px 20px",
        background:"#fff", borderRadius:"14px", textDecoration:"none",
        boxShadow:"0 2px 12px rgba(0,0,0,.18)",
        transition:"box-shadow .15s"
      }}>
        <span style={{fontSize:"14.5px", fontWeight:600, color:"#14253A"}}>Need to share more details?</span>
        <span style={{fontSize:"14px", fontWeight:700, color:"var(--accent)", whiteSpace:"nowrap"}}>Fill out our full request form →</span>
      </a>
    </form>);

}

function ContactSection() {
  return (
    <section className="section section--navy" id="contact">
      <div className="wrap contact">
        <div className="contact__copy">
          <span className="eyebrow">Get started</span>
          <h2 className="h-sec">Tell us about your move</h2>
          <p className="lead">Send a few details and our team will get back to you with a flat, all-in price. No walkthroughs, no pressure, no surprise fees.</p>
          <ul className="contact__list">
            <li><I.check />Free, fast, flat-rate quote</li>
            <li><I.check />Same-day & next-day slots</li>
            <li><I.check />Licensed, insured, background-checked crews</li>
          </ul>
          <div className="contact__or">
            <span>Prefer to talk?</span>
            <a className="contact__tel" href={`tel:${PHONE}`}><I.phone />{PHONE}</a>
          </div>
        </div>
        <ContactForm />
      </div>
    </section>);

}

/* -------------------- FINAL CTA + FOOTER -------------------- */
function Footer({ onQuote }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="final card reveal">
          <img className="final__bg" src="https://images.unsplash.com/photo-1567767292278-a4f21aa2d36e?auto=format&fit=crop&w=1500&q=70" alt="" aria-hidden="true" onError={(e) => {e.currentTarget.style.display = "none";}} />
          <div className="final__copy">
            <h2 className="final__h">Don't let junk and mess delay your move.</h2>
            <p>Your moving day is stressful enough. Book the crew that hauls it all and leaves it spotless — so you can hand over the keys with zero loose ends.</p>
          </div>
          <div className="final__cta">
            <button className="btn btn--lg" onClick={onQuote}>Book your cleanup<I.arrow /></button>
            <a className="btn btn--ghost btn--lg" href={`tel:${PHONE}`}><I.phone />Call {PHONE}</a>
          </div>
        </div>

        <div className="foot-grid">
          <div className="foot-brand">
            <img className="foot-logo" src="assets/logo-on-dark.png" alt="AfterMoving" />
            <p>Atlanta & Georgia junk removal & post-move cleaning. We make empty, spotless, and stress-free happen in a single day.</p>
            <div className="foot-contact">
              <a href={`tel:${PHONE}`}><I.phone />{PHONE}</a>
              <a href={`mailto:${EMAIL}`}><I.mail />{EMAIL}</a>
            </div>
          </div>
          <div className="foot-col">
            <h4>Services</h4>
            <a href="#services">Junk removal</a>
            <a href="#services">Post-move cleaning</a>
            <a href="#services">Donation drop-off</a>
            <a href="#services">Appliance removal</a>
          </div>
          <div className="foot-col">
            <h4>Company</h4>
            <a href="#how">How it works</a>
            <a href="#reviews">Reviews</a>
            <a href="#areas">Service areas</a>
            <a href="#contact">Get a quote</a>
          </div>
          <div className="foot-col">
            <h4>Hours</h4>
            <span>Mon–Sat · 8am–6pm</span>
            <span>Sun · 9am–4pm</span>
          </div>
        </div>
        <div className="foot-base">
          <span>© 2026 AfterMoving. Serving Atlanta & Georgia.</span>
          <span className="foot-base__links"><a href="privacy.html">Privacy</a><a href="terms.html">Terms</a><a href="careers.html">Careers</a></span>
        </div>
      </div>
    </footer>);

}

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