// Support.jsx — contact / support page with a "send us a message" form
// The form POSTs to the /api/support Worker route, which relays it to SendGrid
// (see worker/index.js). SUPPORT_EMAIL is only the public "email us directly"
// link shown to visitors — the real recipient lives in a Cloudflare binding.
const SUPPORT_EMAIL = "support@local-delivery.com";

// Modern themed dropdown (replaces native <select>); writes to a hidden input
// so the surrounding form's FormData still picks it up on submit.
function LDSelect({ name, options, placeholder = "Select…", defaultValue = "", invalid = false, onChange }) {
  const opts = options.map((o) => (typeof o === "string" ? { value: o, label: o } : o));
  const [open, setOpen] = React.useState(false);
  const [value, setValue] = React.useState(defaultValue);
  const ref = React.useRef(null);

  React.useEffect(() => {
    function onDoc(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    function onKey(e) { if (e.key === "Escape") setOpen(false); }
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("mousedown", onDoc); document.removeEventListener("keydown", onKey); };
  }, []);

  const selected = opts.find((o) => o.value === value);
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <input type="hidden" name={name} value={value} />
      <button type="button" onClick={() => setOpen((o) => !o)} aria-haspopup="listbox" aria-expanded={open} style={{
        width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8,
        padding: "12px 14px", fontSize: 15, fontFamily: "inherit", textAlign: "left",
        color: selected ? "var(--ld-ink)" : "var(--ld-ink-soft)",
        background: "#fff", border: `1.5px solid ${invalid ? "var(--ld-accent)" : (open ? "var(--ld-ink)" : "var(--ld-line)")}`,
        borderRadius: 10, cursor: "pointer", transition: "border-color 120ms ease",
      }}>
        <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{selected ? selected.label : placeholder}</span>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--ld-ink-mute)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform 150ms ease", flexShrink: 0 }}>
          <path d="M6 9l6 6 6-6"/>
        </svg>
      </button>
      {open && (
        <div role="listbox" style={{
          position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0, zIndex: 60,
          background: "#fff", border: "1.5px solid var(--ld-ink)", borderRadius: 12,
          boxShadow: "var(--ld-shadow-pop)", padding: 6, maxHeight: 260, overflowY: "auto",
        }}>
          {opts.map((o) => {
            const isSel = o.value === value;
            return (
              <div key={o.value} role="option" aria-selected={isSel}
                onClick={() => { setValue(o.value); setOpen(false); if (onChange) onChange(o.value); }}
                onMouseEnter={(e) => { if (!isSel) e.currentTarget.style.background = "var(--ld-yellow-tint)"; }}
                onMouseLeave={(e) => { if (!isSel) e.currentTarget.style.background = "transparent"; }}
                style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8,
                  padding: "9px 11px", fontSize: 14, borderRadius: 8, cursor: "pointer",
                  color: "var(--ld-ink)", background: isSel ? "var(--ld-yellow)" : "transparent",
                  fontWeight: isSel ? 700 : 500,
                }}>
                <span>{o.label}</span>
                {isSel && <window.LDIcon.Check size={14}/>}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

function LDSupport() {
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState("");
  const [topicError, setTopicError] = React.useState(false);
  const turnstileRef = React.useRef(null);
  const widgetIdRef = React.useRef(null);

  // Explicit render: the Turnstile script (loaded async in support.html) can't
  // auto-scan for the widget div because React mounts it after page load. Wait
  // for both the sitekey (served by the Worker) and window.turnstile.
  React.useEffect(() => {
    let cancelled = false;
    fetch("/api/turnstile-sitekey")
      .then((res) => res.json())
      .then(({ sitekey }) => {
        if (!sitekey) return;
        (function renderWidget() {
          if (cancelled || !turnstileRef.current) return;
          if (!window.turnstile) { setTimeout(renderWidget, 100); return; }
          widgetIdRef.current = window.turnstile.render(turnstileRef.current, {
            sitekey,
            action: "turnstile-spin-v1",
            theme: "light",
          });
        })();
      })
      .catch(() => {});
    return () => {
      cancelled = true;
      if (widgetIdRef.current !== null && window.turnstile) window.turnstile.remove(widgetIdRef.current);
    };
  }, []);

  async function handleSubmit(e) {
    e.preventDefault();
    const form = e.target;
    const f = new FormData(form);
    if (!f.get("topic")) { setTopicError(true); return; }

    // Turnstile drops a hidden cf-turnstile-response input inside the form.
    const turnstileToken =
      f.get("cf-turnstile-response") ||
      (window.turnstile && widgetIdRef.current !== null ? window.turnstile.getResponse(widgetIdRef.current) : "");
    if (!turnstileToken) { setError("Please complete the security check below."); return; }

    const payload = {
      name: f.get("name") || "",
      email: f.get("email") || "",
      company: f.get("company") || "",
      shopify_store: f.get("shopify_store") || "",
      cc: f.get("cc") || "",
      phone: f.get("phone") || "",
      topic: f.get("topic") || "",
      message: f.get("message") || "",
      pageUrl: window.location.href,
      turnstileToken,
    };

    setError("");
    setSending(true);
    try {
      const res = await fetch("/api/support", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || "Something went wrong. Please try again.");
      }
      setSent(true);
      form.reset();
    } catch (err) {
      setError(err.message || "Something went wrong. Please try again.");
    } finally {
      setSending(false);
      // Tokens are single-use — reset so a retry gets a fresh one.
      if (window.turnstile && widgetIdRef.current !== null) window.turnstile.reset(widgetIdRef.current);
    }
  }

  const label = { display: "block", fontSize: 13, fontWeight: 700, color: "var(--ld-ink)", marginBottom: 7 };
  const field = {
    width: "100%", padding: "12px 14px", fontSize: 15, fontFamily: "inherit",
    color: "var(--ld-ink)", background: "#fff",
    border: "1.5px solid var(--ld-line)", borderRadius: 10, outline: "none",
  };

  return (
    <section style={{ background: "var(--ld-cream)", padding: "72px 0 96px" }}>
      <div className="ld-container" style={{ maxWidth: 760 }}>
        <div style={{ marginBottom: 36 }}>
          <span className="ld-eyebrow ld-eyebrow-dot">Support</span>
          <h1 className="ld-h2" style={{ marginTop: 16 }}>How can we help?</h1>
          <p className="ld-lead" style={{ marginTop: 16 }}>
            Send us a message and our team will get back to you during business hours. You can also email us directly at{" "}
            <a href={`mailto:${SUPPORT_EMAIL}`} style={{ color: "var(--ld-ink)", fontWeight: 700, borderBottom: "2px solid var(--ld-yellow)" }}>{SUPPORT_EMAIL}</a>.
          </p>
        </div>

        <div style={{
          background: "#fff", border: "2px solid var(--ld-ink)", borderRadius: 20,
          boxShadow: "8px 8px 0 var(--ld-ink)", padding: "32px 32px 36px",
        }}>
          <h2 className="ld-h4" style={{ marginBottom: 24 }}>Send us a message</h2>

          {sent && (
            <div style={{
              background: "var(--ld-ok-tint)", border: "1.5px solid var(--ld-ok)",
              borderRadius: 10, padding: "12px 14px", marginBottom: 20,
              fontSize: 14, color: "var(--ld-ink)",
            }}>
              Thanks — your message has been sent. Our team will get back to you during business hours.
            </div>
          )}

          {error && (
            <div style={{
              background: "var(--ld-accent-tint, #fdecec)", border: "1.5px solid var(--ld-accent)",
              borderRadius: 10, padding: "12px 14px", marginBottom: 20,
              fontSize: 14, color: "var(--ld-ink)",
            }}>
              {error} You can also email us at{" "}
              <a href={`mailto:${SUPPORT_EMAIL}`} style={{ fontWeight: 700 }}>{SUPPORT_EMAIL}</a>.
            </div>
          )}

          <form onSubmit={handleSubmit}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginBottom: 18 }}>
              <div>
                <label style={label}>Name</label>
                <input name="name" required placeholder="Your full name" style={field}/>
              </div>
              <div>
                <label style={label}>Email</label>
                <input name="email" type="email" required placeholder="you@email.com" style={field}/>
              </div>
            </div>

            <div style={{ marginBottom: 18 }}>
              <label style={label}>Store / Company name</label>
              <input name="company" required placeholder="Your store name" style={field}/>
            </div>

            <div style={{ marginBottom: 18 }}>
              <label style={label}>Shopify store link</label>
              <input name="shopify_store" required placeholder="store.myshopify.com" style={field}/>
            </div>

            <div style={{ marginBottom: 18 }}>
              <label style={label}>Phone</label>
              <div style={{ display: "grid", gridTemplateColumns: "170px 1fr", gap: 10 }}>
                <LDSelect name="cc" defaultValue="+61" options={[
                  { value: "+61", label: "+61 Australia" },
                  { value: "+55", label: "+55 Brazil" },
                  { value: "+86", label: "+86 China" },
                  { value: "+852", label: "+852 Hong Kong" },
                  { value: "+91", label: "+91 India" },
                  { value: "+81", label: "+81 Japan" },
                  { value: "+64", label: "+64 New Zealand" },
                  { value: "+63", label: "+63 Philippines" },
                  { value: "+65", label: "+65 Singapore" },
                  { value: "+82", label: "+82 South Korea" },
                  { value: "+34", label: "+34 Spain" },
                  { value: "+44", label: "+44 UK" },
                  { value: "+1", label: "+1 US / Canada" },
                ]}/>
                <input name="phone" required placeholder="400 000 000" style={field}/>
              </div>
            </div>

            <div style={{ marginBottom: 18 }}>
              <label style={label}>How can we help you?</label>
              <LDSelect name="topic" placeholder="Select an option" invalid={topicError} onChange={() => setTopicError(false)} options={[
                "General question",
                "Setup & onboarding",
                "Billing & plans",
                "Something else",
              ]}/>
              {topicError && <div style={{ marginTop: 7, fontSize: 13, fontWeight: 600, color: "var(--ld-accent)" }}>Please choose an option.</div>}
            </div>

            <div style={{ marginBottom: 24 }}>
              <label style={label}>Message</label>
              <textarea name="message" required rows={5} placeholder="Tell us what you need help with…" style={{ ...field, resize: "vertical", minHeight: 120 }}/>
            </div>

            <div ref={turnstileRef} style={{ marginBottom: 24 }}/>

            <button type="submit" disabled={sending} className="ld-btn ld-btn-primary ld-btn-lg" style={{ width: "100%", justifyContent: "center", opacity: sending ? 0.7 : 1, cursor: sending ? "wait" : "pointer" }}>
              {sending ? "Sending…" : <React.Fragment>Send message <window.LDIcon.Arrow size={15}/></React.Fragment>}
            </button>
          </form>
        </div>
      </div>
    </section>
  );
}
window.LDSupport = LDSupport;
