// PRLX site — contact CTA + footer
//
// ── HOW THE FORM SENDS ───────────────────────────────────────────────────────
//  Submissions POST to Formspree (window.PRLX_FORM.contactEndpoint), which
//  forwards to info@prlx.com.au. Spam is blocked by Formspree's built-in
//  protection plus a honeypot field.
// ─────────────────────────────────────────────────────────────────────────────
function Contact() {
  const { Button, Input, Divider } = window.PRLXDesignSystem_b1b8b9;
  const { Icon, useViewport } = window;
  const ENDPOINT = window.PRLX_FORM.contactEndpoint;
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = React.useState("");
  const [fieldErrors, setFieldErrors] = React.useState({ email: "", phone: "" });
  const { isMobile, isTablet } = useViewport();
  const formRef = React.useRef(null);

  const validateEmail = (v) =>
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test((v || "").trim()) ? "" : "Enter a valid email address";

  const validatePhone = (v) => {
    const digits = (v || "").replace(/\D/g, "");
    return digits.length >= 8 && digits.length <= 15 ? "" : "Enter a valid phone number";
  };

  const handleEmailChange = (e) => {
    if (fieldErrors.email) setFieldErrors((p) => ({ ...p, email: validateEmail(e.target.value) }));
  };

  const handlePhoneChange = (e) => {
    const filtered = e.target.value.replace(/[^\d\s\+\-\(\)]/g, "");
    if (filtered !== e.target.value) e.target.value = filtered;
    if (fieldErrors.phone) setFieldErrors((p) => ({ ...p, phone: validatePhone(filtered) }));
  };

  // Inject pulse keyframe once
  React.useEffect(() => {
    if (document.getElementById("prlx-check-pulse-kf")) return;
    const s = document.createElement("style");
    s.id = "prlx-check-pulse-kf";
    s.textContent = "@keyframes prlxCheckPulse{0%,100%{box-shadow:0 0 0 10px rgba(255,59,48,0.14),0 0 0 22px rgba(255,59,48,0.06)}50%{box-shadow:0 0 0 18px rgba(255,59,48,0.18),0 0 0 34px rgba(255,59,48,0.08)}}";
    document.head.appendChild(s);
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (status === "sending") return;
    const fd0 = new FormData(formRef.current);
    const emailErr = validateEmail(fd0.get("email") || "");
    const phoneErr = validatePhone(fd0.get("phone") || "");
    if (emailErr || phoneErr) { setFieldErrors({ email: emailErr, phone: phoneErr }); return; }
    setStatus("sending");
    setErrorMsg("");
    const fd = new FormData(formRef.current);
    try {
      const res = await fetch(ENDPOINT, {
        method: "POST",
        headers: { Accept: "application/json" },
        body: fd,
      });
      const data = await res.json();
      if (res.ok) {
        setStatus("sent");
      } else {
        setStatus("error");
        setErrorMsg((data.errors && data.errors.map(e => e.message).join(", ")) || "Something went wrong — please email info@prlx.com.au directly.");
      }
    } catch (err) {
      setStatus("error");
      setErrorMsg("Couldn't reach the server — please email info@prlx.com.au directly.");
    }
  };

  const resetForm = () => {
    setStatus("idle");
    setErrorMsg("");
    setFieldErrors({ email: "", phone: "" });
    if (formRef.current) formRef.current.reset();
  };

  return (
    <section data-screen-label="Contact" id="contact" style={{ background: "var(--prlx-ink)", color: "#fff", padding: isMobile ? "64px 20px 0" : "96px 32px 0" }}>
      <div style={{ display: "grid", gridTemplateColumns: isTablet ? "1fr" : "1.1fr 0.9fr", gap: isTablet ? 40 : 64, alignItems: "center", paddingBottom: isMobile ? 56 : 80, borderBottom: "1px solid rgba(255,255,255,0.10)" }}>
        <div>
          <div style={{ fontWeight: 700, fontSize: 11, textTransform: "uppercase", letterSpacing: "0.32em", color: "var(--prlx-graphite-400)", marginBottom: 18 }}>
            ↳ Start a project
          </div>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 800, textTransform: "uppercase", letterSpacing: "-0.02em", fontSize: "clamp(40px, 6vw, 88px)", lineHeight: 0.9, margin: 0 }}>
            Let's roll camera.
          </h2>
          <p style={{ fontWeight: 300, fontSize: 17, lineHeight: 1.6, color: "var(--prlx-graphite-300)", maxWidth: "40ch", marginTop: 24 }}>
            Got a brief, a budget, or just a wild idea on a post-it? Drop us a line and let's make something bloody good!
          </p>

          {/* Contact details — kept consistent with the LocalBusiness schema (NAP). */}
          <div style={{ marginTop: 40, display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: isMobile ? 24 : 32, maxWidth: 460 }}>
            {[
              { city: "Darwin", lines: ["2/4 Berrimah Road", "Berrimah NT 0828"], tel: "+61400254208", telLabel: "0400 254 208" },
              { city: "Hobart", lines: ["Servicing Greater Hobart", "& southern Tasmania"], tel: "+61401216151", telLabel: "0401 216 151" },
            ].map((loc) => (
              <div key={loc.city}>
                <div style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 11, textTransform: "uppercase", letterSpacing: "0.2em", color: "var(--prlx-graphite-400)", marginBottom: 10 }}>{loc.city}</div>
                <p style={{ fontWeight: 300, fontSize: 14, lineHeight: 1.55, color: "var(--prlx-graphite-300)", margin: "0 0 8px" }}>
                  {loc.lines[0]}<br />{loc.lines[1]}
                </p>
                <a href={`tel:${loc.tel}`}
                   style={{ fontFamily: "var(--font-mono)", fontSize: 15, letterSpacing: "0.02em", color: "#fff", textDecoration: "none", cursor: "pointer" }}
                   onMouseEnter={(e) => (e.currentTarget.style.color = "var(--accent)")}
                   onMouseLeave={(e) => (e.currentTarget.style.color = "#fff")}>{loc.telLabel}</a>
              </div>
            ))}
          </div>
          <a href="mailto:info@prlx.com.au"
             style={{ display: "inline-block", marginTop: 24, fontFamily: "var(--font-mono)", fontSize: 15, letterSpacing: "0.02em", color: "#fff", textDecoration: "none", cursor: "pointer" }}
             onMouseEnter={(e) => (e.currentTarget.style.color = "var(--accent)")}
             onMouseLeave={(e) => (e.currentTarget.style.color = "#fff")}>info@prlx.com.au</a>
        </div>

        <div>
          {status === "sent" ? (
            <div role="status" style={{ border: "1px solid rgba(255,255,255,0.14)", background: "rgba(255,255,255,0.03)", padding: isMobile ? "48px 24px" : "72px 40px", display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", gap: 28 }}>
              <span style={{ position: "relative", display: "inline-flex", width: isMobile ? 96 : 120, height: isMobile ? 96 : 120, alignItems: "center", justifyContent: "center", borderRadius: "50%", background: "var(--accent)", color: "#fff", flexShrink: 0, animation: "prlxCheckPulse 2s ease-in-out infinite", boxShadow: "0 0 0 10px rgba(255,59,48,0.14), 0 0 0 22px rgba(255,59,48,0.06)", marginBottom: 8 }}>
                <Icon name="Check" size={isMobile ? 48 : 60} />
              </span>
              <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 800, textTransform: "uppercase", letterSpacing: "-0.02em", fontSize: isMobile ? 34 : 44, lineHeight: 0.95, margin: 0 }}>
                Message sent.
              </h3>
              <p style={{ fontWeight: 300, fontSize: 17, lineHeight: 1.6, color: "var(--prlx-graphite-300)", margin: 0, maxWidth: "38ch" }}>
                Thanks for reaching out — it's landed in our inbox and we'll be in touch shortly.
              </p>
              <button type="button" onClick={resetForm} style={{ marginTop: 4, background: "transparent", border: "none", padding: 0, cursor: "pointer", fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 12, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--prlx-graphite-400)" }}>
                Send another →
              </button>
            </div>
          ) : (
            <form ref={formRef} onSubmit={handleSubmit} noValidate style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              {/* honeypot — hidden from people, catches bots. Formspree silently drops the submission if `_gotcha` is filled. */}
              <input type="text" name="_gotcha" tabIndex={-1} autoComplete="off" aria-hidden="true" style={{ display: "none" }} />
              <Input label="Name" name="name" required placeholder="Jordan Reyes" icon={<Icon name="User" size={16} />} />
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                <Input label="Email" name="email" type="email" required placeholder="you@studio.com.au" icon={<Icon name="Mail" size={16} />} error={!!fieldErrors.email} onChange={handleEmailChange} />
                {fieldErrors.email && <span role="alert" style={{ fontFamily: "var(--font-body)", fontSize: 12, color: "var(--accent)" }}>{fieldErrors.email}</span>}
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                <Input label="Phone" name="phone" type="tel" required placeholder="04xx xxx xxx" icon={<Icon name="Phone" size={16} />} error={!!fieldErrors.phone} onChange={handlePhoneChange} />
                {fieldErrors.phone && <span role="alert" style={{ fontFamily: "var(--font-body)", fontSize: 12, color: "var(--accent)" }}>{fieldErrors.phone}</span>}
              </div>
              <Input label="The project" name="project" placeholder="60sec brand film, 15sec insta reel, corporate video, etc" icon={<Icon name="Clapperboard" size={16} />} />
              <Input label="Description" name="message" required multiline rows={4} placeholder="My company needs an ad for our new product" icon={<Icon name="AlignLeft" size={16} />} />

              {status === "error" && errorMsg && (
                <p role="alert" style={{ margin: 0, fontFamily: "var(--font-body)", fontSize: 13, color: "var(--accent)" }}>{errorMsg}</p>
              )}

              <Button type="submit" variant="signal" size="lg" fullWidth disabled={status === "sending"} iconRight={status === "sending" ? null : <Icon name="ArrowUpRight" size={18} />}>
                {status === "sending" ? "Sending…" : "Send the courier pigeon"}
              </Button>
            </form>
          )}
        </div>
      </div>

      {/* footer */}
      <footer style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: isMobile ? 20 : 24, padding: "40px 0" }}>
        <img src="../../assets/logos/prlx-horizontal-rev.png" alt="PRLX — Video Production, Hobart &amp; Darwin" style={{ height: 28 }} />
        <div style={{ display: "flex", gap: isMobile ? 18 : 26, flexWrap: "wrap" }}>
          {[
            { label: "Instagram", href: "https://www.instagram.com/prlx_production/" },
            { label: "Facebook",  href: "https://www.facebook.com/prlxproductions" },
            { label: "LinkedIn",  href: "https://au.linkedin.com/company/prlxproductions" },
            { label: "TikTok",    href: "https://www.tiktok.com/@prlx_productions" },
          ].map((s) => (
            <a key={s.label} href={s.href} target="_blank" rel="noopener noreferrer"
               style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 12, textTransform: "uppercase", letterSpacing: "0.14em", color: "var(--prlx-graphite-400)", textDecoration: "none", cursor: "pointer" }}
               onMouseEnter={(e) => (e.currentTarget.style.color = "#fff")}
               onMouseLeave={(e) => (e.currentTarget.style.color = "var(--prlx-graphite-400)")}>{s.label}</a>
          ))}
        </div>
        <a href="privacy.html"
           style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 12, textTransform: "uppercase", letterSpacing: "0.14em", color: "var(--prlx-graphite-400)", textDecoration: "none", cursor: "pointer" }}
           onMouseEnter={(e) => (e.currentTarget.style.color = "#fff")}
           onMouseLeave={(e) => (e.currentTarget.style.color = "var(--prlx-graphite-400)")}>
          Privacy Policy
        </a>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--prlx-graphite-500)", letterSpacing: "0.06em" }}>
          © 2025 PRLX CREATIVE PRODUCTION · ALL FRAMES RESERVED
        </span>
      </footer>
      <div style={{ paddingBottom: 28, marginTop: -8 }}>
        <a href="https://www.youtube.com/watch?v=A7IMBnMU5a4" target="_blank" rel="noopener noreferrer"
           style={{ fontFamily: "var(--font-body)", fontWeight: 400, fontSize: 12, fontStyle: "italic", color: "var(--prlx-graphite-600)", cursor: "pointer", transition: "color 120ms" }}
           onMouseEnter={(e) => (e.currentTarget.style.color = "var(--accent)")}
           onMouseLeave={(e) => (e.currentTarget.style.color = "var(--prlx-graphite-600)")}>
          Do you click weird links on the internet?
        </a>
      </div>
    </section>
  );
}
Object.assign(window, { Contact });
