/* Contact — message form with Turnstile + sent confirmation (refs #552 / #557). */
function Contact({ go }) {
  const DS = window.OcaInteriorsDesignSystem_2c041d;
  const { NavBar, SectionHeading, Field, Input, Textarea, Button, Divider } = DS;
  const [sent, setSent] = React.useState(false);
  const [error, setError] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const turnstileRef = React.useRef(null);
  const formRef = React.useRef(null);
  const engageRef = React.useRef(null);

  // Bind Turnstile only when the user focuses / types in a text field (refs #557)
  React.useEffect(() => {
    if (sent) {
      if (engageRef.current && engageRef.current.dispose) engageRef.current.dispose();
      engageRef.current = null;
      return;
    }
    if (!window.LLTurnstile || !formRef.current || !turnstileRef.current) return undefined;
    engageRef.current = LLTurnstile.prepareOnEngage({
      form: formRef.current,
      container: turnstileRef.current,
      theme: "light",
    });
    return () => {
      if (engageRef.current && engageRef.current.dispose) engageRef.current.dispose();
      engageRef.current = null;
    };
  }, [sent]);

  return (
    <div style={{ background: "var(--surface-page)", minHeight: "100%", display: "flex", flexDirection: "column" }}>
      <NavBar active="Contact" items={window.ocaNavItems(go)} />

      <div style={{
        maxWidth: "var(--max-content)", margin: "0 auto", padding: "56px 40px 72px",
        display: "grid", gridTemplateColumns: "1fr 1.25fr", gap: 80, flex: 1, width: "100%", boxSizing: "border-box",
      }}>
        <div>
          <SectionHeading title="Contact Us" size="md" />
          <p data-edit="contact.tagline" data-edit-html="true" style={{
            margin: "28px 0 0", fontFamily: "var(--font-display)", fontWeight: 400,
            fontSize: 27, lineHeight: 1.32, color: "var(--text-heading)", maxWidth: 360,
          }}>
            Our website's under construction.<br />Your new oasis could be too!
          </p>
        </div>

        <div>
          {sent ? (
            <div style={{
              background: "var(--oca-white)", borderRadius: "var(--radius-lg)", padding: "44px 40px",
              boxShadow: "var(--shadow-sm)",
            }}>
              <h3 data-edit="contact.thanksTitle" style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 400, fontSize: 30, color: "var(--text-heading)" }}>
                Thank you — we'll be in touch.
              </h3>
              <p data-edit="contact.thanksBody" style={{ margin: "14px 0 24px", fontFamily: "var(--font-body)", fontSize: 18, color: "var(--text-body)" }}>
                We read every note personally and usually reply within a couple of days.
              </p>
              <Button variant="secondary" onClick={() => setSent(false)}>Send another</Button>
            </div>
          ) : (
            <form ref={formRef} onSubmit={async (e) => {
                e.preventDefault();
                setError('');
                setBusy(true);
                try {
                  const fd = new FormData(e.currentTarget);
                  const first = String(fd.get('first') || '').trim();
                  const last = String(fd.get('last') || '').trim();
                  const name = [first, last].filter(Boolean).join(' ').trim();
                  const email = String(fd.get('email') || '').trim();
                  const message = String(fd.get('message') || '').trim();
                  let turnstileToken = '';
                  if (window.LLTurnstile && turnstileRef.current) {
                    turnstileToken = LLTurnstile.readPreparedToken(turnstileRef.current) || '';
                    if (!turnstileToken) {
                      turnstileToken = await LLTurnstile.getToken({ container: turnstileRef.current, theme: 'light' }) || '';
                    }
                  }
                  const res = await fetch('/api/ocainteriors/contact', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                    body: JSON.stringify({
                      name, email, message,
                      page: 'ocainteriors.com/contact',
                      cf_turnstile_response: turnstileToken,
                      turnstileToken,
                    }),
                  });
                  const data = await res.json().catch(() => ({}));
                  if (!res.ok || data.ok === false) {
                    throw new Error(data.error || data.message || 'Could not send right now. Please try again or call us.');
                  }
                  setSent(true);
                } catch (err) {
                  setError(err && err.message ? err.message : 'Could not send right now.');
                  if (window.LLTurnstile && turnstileRef.current) {
                    try {
                      LLTurnstile.reset(turnstileRef.current);
                      await LLTurnstile.prepare({ container: turnstileRef.current, theme: 'light' });
                    } catch (e) {}
                  }
                } finally {
                  setBusy(false);
                }
              }}>
              {error ? (
                <p role="alert" style={{ margin: "0 0 18px", fontFamily: "var(--font-body)", fontSize: 16, color: "#8b2e2e" }}>{error}</p>
              ) : null}
              <div style={{ marginBottom: 22 }}>
                <span style={{ fontFamily: "var(--font-body)", fontSize: 19, color: "var(--text-body)" }}>Name</span>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 22, marginBottom: 26 }}>
                <Field label="First Name" required htmlFor="fn"><Input id="fn" name="first" required /></Field>
                <Field label="Last Name" required htmlFor="ln"><Input id="ln" name="last" required /></Field>
              </div>
              <Field label="Email" required htmlFor="em" style={{ marginBottom: 26 }}><Input id="em" name="email" type="email" required /></Field>
              <Field label="Message" required htmlFor="msg" style={{ marginBottom: 28 }}><Textarea id="msg" name="message" rows={5} required /></Field>
              <div ref={turnstileRef} aria-label="Security check" style={{ marginBottom: 20, minHeight: 0 }} />
              <Button type="submit" variant="secondary" size="md" disabled={busy}>{busy ? 'Sending…' : 'Send'}</Button>
            </form>
          )}
        </div>
      </div>

      <Divider />
      <window.Footer />
    </div>
  );
}
window.Contact = Contact;
