// tr-form.jsx — shared contact form used by every skin.
// The form markup (.field / .two / .robot / .btn) is identical across skins and
// scoped by the parent .trs/.trc wrapper, so one component serves both.
//
// • Spam protection: a honeypot field ("company"), a minimum render→submit time,
//   and (in remote mode) the server's per-IP throttle. No third-party/captcha.
// • Submits to {apiBase}/contact when remote; in local/preview it just simulates
//   success (there is no server to email).
// • On success the button is replaced by a thank-you panel.
//
// Load AFTER React + tr-icons.js, BEFORE the skin files. Exposes window.TRContactForm.

(function () {
  if (typeof document === "undefined" || document.getElementById("tr-form-css")) return;
  var st = document.createElement("style");
  st.id = "tr-form-css";
  st.textContent = [
    ".form-fail{ background:#fff6ec; border:1px solid #f3d9b5; border-radius:14px; padding:16px 18px; margin:2px 0 4px; }",
    ".form-fail-lead{ color:#7a4a12; font-size:14.5px; line-height:1.5; margin:0 0 13px; }",
    ".form-fail-lead b{ color:#5f3a0e; }",
    ".form-fail-actions{ display:flex; flex-wrap:wrap; gap:10px; }",
    ".form-fail .ff-item{ display:inline-flex; align-items:center; gap:8px; background:#fff; border:1px solid #eecfa0; border-radius:999px; padding:10px 17px; font-size:14.5px; color:#7a4a12; text-decoration:none; white-space:nowrap; transition:border-color .15s ease, box-shadow .15s ease; }",
    ".form-fail a.ff-item:hover{ border-color:#d99a4e; box-shadow:0 8px 18px -10px rgba(150,90,20,.5); }",
    ".form-fail .ff-item svg{ color:#c2772a; flex:none; }",
    ".form-fail .ff-lbl{ font-weight:600; white-space:nowrap; }",
    ".form-fail .ff-val{ font-weight:700; color:#5f3a0e; margin-left:3px; }",
    ".form-fail .ff-phone{ display:inline-flex; flex-direction:row-reverse; }",
    "@media(max-width:520px){ .form-fail-actions{ flex-direction:column; align-items:stretch; } .form-fail .ff-item{ justify-content:center; } }",
  ].join("");
  document.head.appendChild(st);
})();

function TRContactForm({ content }) {
  const { useState, useRef } = React;
  const [sent, setSent] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const [failed, setFailed] = useState(false);
  const [robot, setRobot] = useState(false);
  const startRef = useRef(Date.now());
  const options = (content.supportOptions && content.supportOptions.length)
    ? content.supportOptions
    : ["Home tech support", "Business tech support", "Not sure yet"];
  const fbEmail = (content.fallbackEmail || content.recipientEmail || "").trim();
  const fbPhone = (content.fallbackPhone || "").trim();
  const phoneDial = fbPhone.replace(/[^\d+]/g, "");
  const armTel = (e) => { e.currentTarget.setAttribute("href", "tel:" + phoneDial); };
  const armMail = (e) => { e.currentTarget.setAttribute("href", "mailto:" + fbEmail); };
  const emailParts = (email) => {
    const s = String(email).trim(), at = s.indexOf("@");
    if (at < 0) return [React.createElement("span", { key: 0 }, s)];
    const user = s.slice(0, at), parts = s.slice(at + 1).split(".");
    const kids = [React.createElement("span", { key: "u" }, user), React.createElement("span", { key: "a", className: "at" })];
    parts.forEach((p, i) => { if (i > 0) kids.push(React.createElement("span", { key: "d" + i, className: "dot" })); kids.push(React.createElement("span", { key: "p" + i }, p)); });
    return kids;
  };

  const submit = async (e) => {
    e.preventDefault();
    const f = e.currentTarget;
    setFailed(false);
    if (f.company && f.company.value) { setSent(true); return; }              // honeypot tripped → bot
    if (!robot) { setErr("Please tick the box to confirm you're not a robot."); return; }
    if (Date.now() - startRef.current < 2500) { setErr("Just a moment, then try again."); return; }
    setErr(""); setBusy(true);
    const payload = {
      name: f.fullname.value, email: f.email.value, support: f.support.value,
      when: f.when.value, message: f.message.value, company: f.company.value,
      t: Math.round(startRef.current / 1000),
    };
    try {
      const remote = window.ContentBackend && window.ContentBackend.isRemote && window.ContentBackend.isRemote();
      if (remote) {
        const res = await fetch((window.CMS_CONFIG.apiBase || "/api") + "/contact", {
          method: "POST", headers: { "Content-Type": "application/json" },
          credentials: "same-origin", body: JSON.stringify(payload),
        });
        const j = await res.json().catch(() => ({}));
        if (!res.ok || !j.ok) throw new Error(j.error || "failed");
      } else {
        await new Promise((r) => setTimeout(r, 450));   // local/preview demo
      }
      setSent(true);
    } catch (_) {
      setFailed(true);
      setBusy(false);
    }
  };

  if (sent) {
    return (
      <form onSubmit={(e) => e.preventDefault()}>
        <div className="form-done">
          <span className="form-done-ico">{window.TRIcon ? window.TRIcon("check", 22, 3) : "\u2713"}</span>
          <p>{content.successText || "Thanks, we'll be in touch!"}</p>
        </div>
      </form>
    );
  }

  return (
    <form onSubmit={submit} noValidate>
      <div className="two">
        <div className="field"><label>Your name</label><input name="fullname" type="text" placeholder="Jane Smith" required /></div>
        <div className="field"><label>Email address</label><input name="email" type="email" placeholder="jane@email.com" required /></div>
      </div>
      <div className="two">
        <div className="field"><label>Type of support</label>
          <select name="support" defaultValue="" required>
            <option value="" disabled>Please select…</option>
            {options.map((o, i) => <option key={i} value={o}>{o}</option>)}
          </select>
        </div>
        <div className="field"><label>When works best?</label><input name="when" type="text" placeholder="e.g. Weekday mornings" /></div>
      </div>
      <div className="field"><label>How can we help?</label><textarea name="message" placeholder="Tell us a little about what's going on…" required /></div>
      <div className="hp" aria-hidden="true"><label>Company<input name="company" tabIndex={-1} autoComplete="off" /></label></div>
      <label className="robot"><input type="checkbox" checked={robot} onChange={(e) => { setRobot(e.target.checked); if (e.target.checked) setErr(""); }} />I'm not a robot</label>
      {err ? <div className="form-err">{err}</div> : null}
      {failed ? (
        <div className="form-fail" role="alert">
          <p className="form-fail-lead"><b>Sorry, that didn't send.</b> Please reach us directly and we'll sort it out right away.</p>
          {(fbPhone || fbEmail) && (
            <div className="form-fail-actions">
              {fbPhone ? (
                <a className="ff-item tr-obf" href="#" onMouseEnter={armTel} onFocus={armTel} onTouchStart={armTel} onMouseDown={armTel}>
                  {window.TRIcon("phoneCall", { size: 17, sw: 2.2 })}<span className="ff-lbl">Call us</span>
                  <span className="ff-val ff-phone">{fbPhone.split("").reverse().map((ch, i) => <span key={i}>{ch}</span>)}</span>
                </a>
              ) : null}
              {fbEmail ? (
                <a className="ff-item tr-obf" href="#" onMouseEnter={armMail} onFocus={armMail} onTouchStart={armMail} onMouseDown={armMail}>
                  {window.TRIcon("mail", { size: 17, sw: 2.2 })}<span className="ff-lbl">Email us</span>
                  <span className="ff-val">{emailParts(fbEmail)}</span>
                </a>
              ) : null}
            </div>
          )}
        </div>
      ) : null}
      <button className="btn btn-primary" type="submit" disabled={busy}>{busy ? "Sending…" : (failed ? "Try again" : (content.submitLabel || "Send message"))}</button>
    </form>
  );
}

window.TRContactForm = TRContactForm;
