// PRLX Gear Hire — floating quote button, slide-in cart drawer with per-item tier select, and enquiry form.
// The enquiry posts to Formspree → info@prlx.com.au (endpoint in window.PRLX_FORM.hireEndpoint).
// Spam is handled by Formspree's built-in protection plus a honeypot field.
function QuoteCart({ cart, items, onAdd, onRemove, onClear, open, setOpen }) {
  const { Button, Input } = window.PRLXDesignSystem_b1b8b9;
  const { Icon, useViewport } = window;
  const { isMobile } = useViewport();
  const ENDPOINT = window.PRLX_FORM.hireEndpoint;
  const [tier, setTier] = React.useState("day");      // global tier toggle for the estimate
  const [status, setStatus] = React.useState("idle");  // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = React.useState("");
  const [fieldErrors, setFieldErrors] = React.useState({ email: "", phone: "" });
  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) }));
  };

  const lines = items.filter((i) => (cart[i.id] || 0) > 0);
  const totalUnits = lines.reduce((s, i) => s + cart[i.id], 0);
  const tierKey = { day: "day", weekend: "weekend", week: "week" }[tier];
  const estimate = lines.reduce((s, i) => s + i.rates[tierKey] * cart[i.id], 0);
  const tierLabel = { day: "day", weekend: "weekend", week: "week" }[tier];

  const formVisible = lines.length > 0 && status !== "sent";

  // Inject pulse keyframe once (shared with Contact.jsx)
  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);
    const senderName = (fd.get("name") || "").toString().trim();
    const fmtDate = (iso) => { if (!iso) return ""; const [y,m,d] = iso.split("-"); return `${d}/${m}/${y.slice(2)}`; };
    const dateFrom = fmtDate((fd.get("date_from") || "").toString().trim());
    const dateTo = fmtDate((fd.get("date_to") || "").toString().trim());
    const hireDates = dateFrom && dateTo ? `${dateFrom} → ${dateTo}` : dateFrom || dateTo || "—";
    const notes = (fd.get("notes") || "").toString().trim();
    const summary = lines.map((i) => `${cart[i.id]}× ${i.name} — $${i.rates[tierKey]}/${tierLabel}`).join("\n");
    // Remove raw form fields — replace with a single clean message
    fd.delete("date_from");
    fd.delete("date_to");
    fd.delete("notes");
    fd.set("_subject", senderName ? `Gear hire enquiry from ${senderName} — PRLX website` : "Gear hire enquiry — PRLX website");
    fd.set("message",
      `GEAR HIRE ENQUIRY\n` +
      `${"-".repeat(40)}\n` +
      `Hire dates: ${hireDates}\n\n` +
      `Items (${tierLabel} rate):\n${summary}\n\n` +
      `Estimated ${tierLabel} total: $${estimate.toLocaleString()} (indicative, ex GST)` +
      (notes ? `\n\nNotes:\n${notes}` : "")
    );
    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: "" });
  };

  return (
    <React.Fragment>
      {/* floating launcher */}
      {totalUnits > 0 && !open && (
        <button onClick={() => setOpen(true)}
          style={{ position: "fixed", right: isMobile ? 16 : 28, bottom: isMobile ? 16 : 28, zIndex: 900,
            display: "flex", alignItems: "center", gap: 12, padding: "14px 20px", background: "var(--accent)", color: "#fff", border: 0, cursor: "pointer",
            boxShadow: "0 12px 40px rgba(0,0,0,0.5)", fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 12, textTransform: "uppercase", letterSpacing: "0.12em" }}>
          <Icon name="ClipboardList" size={18} />
          Quote
          <span style={{ minWidth: 22, height: 22, padding: "0 6px", display: "inline-flex", alignItems: "center", justifyContent: "center", background: "#fff", color: "var(--accent)", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 12 }}>{totalUnits}</span>
        </button>
      )}

      {/* scrim */}
      <div onClick={() => setOpen(false)}
        style={{ position: "fixed", inset: 0, zIndex: 950, background: "rgba(5,5,5,0.6)", backdropFilter: "blur(3px)",
          opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity 240ms" }} />

      {/* drawer */}
      <aside style={{ position: "fixed", top: 0, right: 0, bottom: 0, zIndex: 960,
        width: isMobile ? "100%" : 460, maxWidth: "100%", background: "#0d0e10", borderLeft: "1px solid rgba(255,255,255,0.10)",
        transform: open ? "translateX(0)" : "translateX(100%)", transition: "transform 320ms cubic-bezier(0.22,1,0.36,1)",
        display: "flex", flexDirection: "column" }}>

        {/* header */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 22px", borderBottom: "1px solid rgba(255,255,255,0.10)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
            <Icon name="ClipboardList" size={20} style={{ color: "#fff" }} />
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, textTransform: "uppercase", letterSpacing: "-0.01em", fontSize: 20, color: "#fff" }}>Your quote</span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--prlx-graphite-500)" }}>{totalUnits}</span>
          </div>
          <button onClick={() => setOpen(false)} aria-label="Close"
            style={{ width: 38, height: 38, background: "transparent", border: 0, color: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="X" size={20} />
          </button>
        </div>

        {/* body + footer live inside one form so the submit button sends the fields */}
        <form ref={formRef} onSubmit={handleSubmit} noValidate style={{ flex: 1, display: "flex", flexDirection: "column", minHeight: 0 }}>
          {/* 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" }} />

          {/* body */}
          <div style={{ flex: 1, overflowY: "auto", padding: "18px 22px" }}>
          {status === "sent" ? (
            <div role="status" style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", height: "100%", textAlign: "center", gap: 20, padding: "24px 8px" }}>
              <span style={{ display: "inline-flex", width: 112, height: 112, 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)" }}>
                <Icon name="Check" size={56} />
              </span>
              <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 800, textTransform: "uppercase", letterSpacing: "-0.02em", fontSize: 34, lineHeight: 0.95, margin: 0, color: "#fff" }}>Quote sent.</h3>
              <p style={{ fontWeight: 300, fontSize: 15, lineHeight: 1.6, color: "var(--prlx-graphite-300)", margin: 0, maxWidth: "30ch" }}>
                Thanks — your gear list is with us and we'll confirm availability and final pricing shortly. For anything urgent, email <a href="mailto:info@prlx.com.au" style={{ color: "#fff", textDecoration: "underline" }}>info@prlx.com.au</a>.
              </p>
              <button type="button" onClick={() => { resetForm(); onClear(); setOpen(false); }} 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)" }}>
                Back to the kit →
              </button>
            </div>
          ) : lines.length === 0 ? (
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", height: "100%", gap: 14, textAlign: "center", color: "var(--prlx-graphite-500)" }}>
              <Icon name="PackageOpen" size={34} />
              <p style={{ fontFamily: "var(--font-body)", fontSize: 14, maxWidth: "24ch", margin: 0 }}>Nothing here yet. Add gear from the catalogue to build a quote.</p>
            </div>
          ) : (
            <React.Fragment>
              {/* tier toggle */}
              <div style={{ display: "flex", gap: 0, border: "1px solid rgba(255,255,255,0.16)", marginBottom: 18 }}>
                {["day", "weekend", "week"].map((tk) => (
                  <button key={tk} type="button" onClick={() => setTier(tk)}
                    style={{ flex: 1, padding: "9px 0", background: tier === tk ? "#fff" : "transparent", color: tier === tk ? "var(--prlx-ink)" : "var(--prlx-graphite-300)", border: 0, cursor: "pointer",
                      fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em" }}>
                    {tk === "weekend" ? "Weekend" : tk}
                  </button>
                ))}
              </div>

              {/* line items */}
              <div style={{ display: "flex", flexDirection: "column" }}>
                {lines.map((i) => (
                  <div key={i.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 0", borderBottom: "1px solid rgba(255,255,255,0.07)" }}>
                    <div style={{ width: 46, height: 46, flexShrink: 0, background: "#0a0a0b", overflow: "hidden", border: "1px solid rgba(255,255,255,0.08)" }}>
                      {i.images && i.images[0] ? <img src={`../../${i.images[0]}`} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                        : <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--prlx-graphite-600)" }}><Icon name="Box" size={18} /></div>}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 13.5, color: "#fff", lineHeight: 1.25 }}>{i.name}</div>
                      <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--prlx-graphite-500)", marginTop: 3 }}>${i.rates[tierKey]} / {tierLabel}</div>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", border: "1px solid rgba(255,255,255,0.18)" }}>
                      <button type="button" onClick={() => onRemove(i)} aria-label="Remove one" style={{ width: 28, height: 28, background: "transparent", border: 0, color: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="Minus" size={12} /></button>
                      <span style={{ minWidth: 20, textAlign: "center", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 13, color: "#fff" }}>{cart[i.id]}</span>
                      <button type="button" onClick={() => onAdd(i)} disabled={cart[i.id] >= i.qty} aria-label="Add one" style={{ width: 28, height: 28, background: "transparent", border: 0, color: cart[i.id] >= i.qty ? "var(--prlx-graphite-600)" : "#fff", cursor: cart[i.id] >= i.qty ? "not-allowed" : "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="Plus" size={12} /></button>
                    </div>
                  </div>
                ))}
              </div>

              <button type="button" onClick={onClear} style={{ marginTop: 14, background: "transparent", border: 0, cursor: "pointer", color: "var(--prlx-graphite-500)", fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em" }}>
                Clear all
              </button>

              {/* enquiry form */}
              <div style={{ marginTop: 26, paddingTop: 22, borderTop: "1px solid rgba(255,255,255,0.10)" }}>
                <div style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.2em", color: "var(--prlx-graphite-400)", marginBottom: 14 }}>↳ Send enquiry</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                  <Input label="Name" name="name" required placeholder="Jordan Reyes" icon={<Icon name="User" size={15} />} />
                  <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
                    <Input label="Email" name="email" type="email" required placeholder="you@studio.com" icon={<Icon name="Mail" size={15} />} error={!!fieldErrors.email} onChange={handleEmailChange} />
                    {fieldErrors.email && <span role="alert" style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: "var(--accent)" }}>{fieldErrors.email}</span>}
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
                    <Input label="Phone" name="phone" type="tel" required placeholder="04xx xxx xxx" icon={<Icon name="Phone" size={15} />} error={!!fieldErrors.phone} onChange={handlePhoneChange} />
                    {fieldErrors.phone && <span role="alert" style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: "var(--accent)" }}>{fieldErrors.phone}</span>}
                  </div>
                  <div>
                    <label style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 10, textTransform: "uppercase", letterSpacing: "0.14em", color: "var(--prlx-graphite-400)", marginBottom: 6 }}>Hire dates</label>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                      {[{name:"date_from",label:"From"},{name:"date_to",label:"To"}].map(({name,label}) => (
                        <div key={name}>
                          <label style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 9, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--prlx-graphite-500)", marginBottom: 4 }}>{label}</label>
                          <input type="date" name={name}
                            style={{ width: "100%", background: "#0d0e10", color: "#fff", border: "1px solid rgba(255,255,255,0.14)", padding: "9px 11px", fontFamily: "var(--font-body)", fontSize: 13, outline: "none", colorScheme: "dark", boxSizing: "border-box" }}
                            onFocus={(e) => e.target.style.borderColor = "var(--accent)"}
                            onBlur={(e) => e.target.style.borderColor = "rgba(255,255,255,0.14)"} />
                        </div>
                      ))}
                    </div>
                  </div>
                  <Input label="Notes" name="notes" multiline rows={3} placeholder="Any additional details, special requirements, etc" icon={<Icon name="AlignLeft" size={15} />} />
                  {status === "error" && errorMsg && (
                    <p role="alert" style={{ margin: 0, fontFamily: "var(--font-body)", fontSize: 12.5, lineHeight: 1.5, color: "var(--accent)" }}>{errorMsg}</p>
                  )}
                </div>
              </div>
            </React.Fragment>
          )}
          </div>

        {/* footer / total + submit */}
        {formVisible && (
          <div style={{ padding: "18px 22px", borderTop: "1px solid rgba(255,255,255,0.10)", background: "#0a0b0d" }}>
            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 14 }}>
              <span style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--prlx-graphite-400)" }}>Est. {tierLabel} total</span>
              <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 28, color: "#fff" }}>
                <span style={{ fontSize: 16, color: "var(--prlx-graphite-400)" }}>$</span>{estimate.toLocaleString()}
              </span>
            </div>
            <Button type="submit" variant="signal" size="lg" fullWidth disabled={status === "sending"} iconRight={status === "sending" ? null : <Icon name="ArrowUpRight" size={18} />}>
              {status === "sending" ? "Sending…" : "Request this quote"}
            </Button>
            <p style={{ fontFamily: "var(--font-body)", fontSize: 11, lineHeight: 1.5, color: "var(--prlx-graphite-500)", margin: "12px 0 0", textAlign: "center" }}>
              Indicative only · ex GST. We'll confirm availability + final pricing.
            </p>
          </div>
        )}
        </form>
      </aside>
    </React.Fragment>
  );
}
Object.assign(window, { QuoteCart });
