// Inquiry modal — shows when a customer clicks Reserve / Inquire on a car.
//
// Two paths:
//  - WhatsApp: fires an anonymous lead (via window.fireAutoLead) and opens
//    wa.me in a new tab. Same end result as the old direct flow, but the
//    explicit click in this modal is a more reliable trigger for the lead
//    POST than a passive <a onClick> (no race with browser nav, gives the
//    fetch a synchronous start before the new tab opens).
//  - Email: collects real name + email + optional phone + message, posts
//    the lead to Odoo with the REAL contact info (no sentinel email), and
//    shows a "✓ got it" confirmation. No mailto open — the form IS the
//    submission, and the team replies from their inbox.
//
// Exposed as window.InquiryModal so receipts.jsx (which loads after this
// file) can grab it and render it.

const { useState: useStateM, useEffect: useEffectM, useRef: useRefM } = React;

const _IM_STYLES = {
  fieldLabel: {
    display: "block", fontSize: 11, fontWeight: 600, marginBottom: 6, marginTop: 14,
    color: "var(--mute, rgba(239,233,221,0.58))", letterSpacing: "0.04em",
    textTransform: "uppercase", fontFamily: "var(--mono, monospace)",
  },
  input: {
    width: "100%", padding: "11px 13px",
    background: "rgba(255,255,255,0.04)",
    border: "1px solid var(--line-2, rgba(255,255,255,0.14))",
    borderRadius: 4, color: "var(--bone, #efe9dd)", fontSize: 14,
    boxSizing: "border-box", outline: "none",
    fontFamily: "var(--sans, sans-serif)",
  },
  primaryBtn: {
    flex: "1 1 auto",
    background: "var(--amber, #e8732e)", color: "var(--ink-0, #0a0a0b)",
    border: "none", padding: "13px 18px", borderRadius: 4,
    fontSize: 14, fontWeight: 700, cursor: "pointer",
    letterSpacing: "0.02em",
  },
  ghostBtn: {
    background: "transparent", color: "var(--mute, rgba(239,233,221,0.58))",
    border: "1px solid var(--line-2, rgba(255,255,255,0.14))",
    padding: "13px 18px", borderRadius: 4, fontSize: 13,
    cursor: "pointer", fontFamily: "var(--sans, sans-serif)",
  },
  waBtn: {
    flex: "1 1 180px",
    background: "#25D366", color: "#fff",
    border: "none", padding: "14px 18px", borderRadius: 4,
    fontSize: 14, fontWeight: 700, cursor: "pointer",
    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
    letterSpacing: "0.02em",
  },
  emailBtn: {
    flex: "1 1 180px",
    background: "var(--amber, #e8732e)", color: "var(--ink-0, #0a0a0b)",
    border: "none", padding: "14px 18px", borderRadius: 4,
    fontSize: 14, fontWeight: 700, cursor: "pointer",
    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
    letterSpacing: "0.02em",
  },
};

function InquiryModal({ car, isOpen, onClose, waUrl }) {
  const [view, setView] = useStateM("choice"); // "choice" | "email" | "sent"
  const [name, setName] = useStateM("");
  const [email, setEmail] = useStateM("");
  const [phone, setPhone] = useStateM("");
  const [message, setMessage] = useStateM("");
  const [submitting, setSubmitting] = useStateM(false);
  const emailInputRef = useRefM(null);

  // Reset the form each time the modal opens fresh.
  useEffectM(() => {
    if (isOpen) {
      setView("choice");
      setName("");
      setEmail("");
      setPhone("");
      setMessage(
        "I'm interested in the " + car.brand + " " + car.model_en +
        ". Please send me the next steps for sourcing this from China."
      );
      setSubmitting(false);
    }
  }, [isOpen, car.brand, car.model_en]);

  // Auto-focus email input when entering the email view.
  useEffectM(() => {
    if (view === "email") {
      const id = setTimeout(() => {
        if (emailInputRef.current) emailInputRef.current.focus();
      }, 60);
      return () => clearTimeout(id);
    }
  }, [view]);

  // Esc closes.
  useEffectM(() => {
    if (!isOpen) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [isOpen, onClose]);

  // Lock body scroll while open.
  useEffectM(() => {
    if (!isOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prev; };
  }, [isOpen]);

  if (!isOpen) return null;

  const carSpecLines = [
    "Car: " + car.brand + " " + car.model_en + (car.model_cn ? " (" + car.model_cn + ")" : ""),
    "Tier: " + car.tier + " · Fuel: " + car.fuel,
    car.china_price_usd ? "China factory: $" + car.china_price_usd.toLocaleString("en-US") : null,
    car.icon_one_landed_usd ? "Landed estimate: $" + car.icon_one_landed_usd.toLocaleString("en-US") : null,
  ].filter(Boolean);

  const tierLabel =
    car.tier === "auto_electric" ? "Electric" :
    car.tier === "auto_exclusive" ? "Exclusive" : "Auto";

  const onWhatsApp = () => {
    if (typeof window !== "undefined" && window.fireAutoLead) {
      window.fireAutoLead({
        inquiry_source: "auto_reserve_wa",
        request_kind: car.china_price_usd ? "Reserve · WhatsApp" : "Inquiry · WhatsApp",
        subject: car.brand + " " + car.model_en,
        whatsapp: waUrl,
        cargo_type: car.tier + ": " + car.brand + " " + car.model_en + " (" + car.fuel + ")",
        details: carSpecLines.concat([
          "Channel: customer picked WhatsApp from inquiry modal",
        ]),
      });
    }
    if (waUrl) window.open(waUrl, "_blank", "noopener");
    onClose();
  };

  const onEmailSubmit = (e) => {
    e.preventDefault();
    if (!email.trim() || !name.trim()) return;
    setSubmitting(true);
    if (typeof window !== "undefined" && window.fireAutoLead) {
      window.fireAutoLead({
        inquiry_source: "auto_reserve_email",
        request_kind: car.china_price_usd ? "Reserve · Email" : "Inquiry · Email",
        subject: car.brand + " " + car.model_en,
        whatsapp: "", // no WA destination — email path
        email: email.trim(),
        phone: phone.trim(),
        cargo_type: car.tier + ": " + car.brand + " " + car.model_en + " (" + car.fuel + ")",
        details: carSpecLines.concat([
          "",
          "Customer: " + name.trim(),
          "Customer email: " + email.trim(),
          phone.trim() ? "Customer phone: " + phone.trim() : "Customer phone: not provided",
          "",
          "Customer message:",
          message.trim() || "(no message)",
          "",
          "Channel: customer picked Email from inquiry modal",
        ]),
      });
    }
    // Give the fetch a quarter-second to leave before flipping UI state.
    setTimeout(() => {
      setSubmitting(false);
      setView("sent");
    }, 250);
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 1000,
        background: "rgba(0,0,0,0.72)",
        backdropFilter: "blur(4px)", WebkitBackdropFilter: "blur(4px)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 16,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        role="dialog" aria-modal="true"
        style={{
          background: "var(--ink-1, #111113)", color: "var(--bone, #efe9dd)",
          border: "1px solid var(--line, rgba(255,255,255,0.08))",
          borderRadius: 8,
          width: "100%", maxWidth: 480, position: "relative",
          padding: "30px 28px 26px",
          maxHeight: "92vh", overflowY: "auto",
          boxShadow: "0 24px 80px rgba(0,0,0,0.5)",
          fontFamily: "var(--sans, sans-serif)",
        }}
      >
        <button
          type="button" onClick={onClose} aria-label="Close"
          style={{
            position: "absolute", top: 12, right: 14,
            background: "transparent", border: "none",
            color: "var(--mute, rgba(239,233,221,0.58))",
            fontSize: 24, cursor: "pointer", lineHeight: 1, padding: 4,
            fontFamily: "inherit",
          }}
        >×</button>

        {/* Header — car identity, always shown */}
        <div
          className="mono"
          style={{
            fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase",
            color: "var(--amber, #e8732e)", marginBottom: 6,
            fontFamily: "var(--mono, monospace)",
          }}
        >
          {tierLabel}
        </div>
        <h3
          className="serif"
          style={{
            fontSize: 26, margin: 0, marginBottom: 4, lineHeight: 1.1,
            fontFamily: "var(--serif, serif)",
            letterSpacing: "-0.01em",
          }}
        >
          {car.brand} {car.model_en}
        </h3>
        {car.icon_one_landed_usd && (
          <div style={{ fontSize: 13, color: "var(--mute, rgba(239,233,221,0.58))", marginBottom: 4 }}>
            Landed estimate:{" "}
            <span
              className="num"
              style={{
                color: "var(--amber, #e8732e)", fontWeight: 600,
                fontVariantNumeric: "tabular-nums",
              }}
            >
              ${car.icon_one_landed_usd.toLocaleString("en-US")}
            </span>
          </div>
        )}

        {/* View: choice */}
        {view === "choice" && (
          <div style={{ marginTop: 24 }}>
            <p style={{ margin: "0 0 16px 0", fontSize: 14, color: "var(--mute, rgba(239,233,221,0.58))" }}>
              How would you like to inquire?
            </p>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              <button type="button" onClick={onWhatsApp} style={_IM_STYLES.waBtn}>
                <span aria-hidden="true">💬</span> WhatsApp
              </button>
              <button type="button" onClick={() => setView("email")} style={_IM_STYLES.emailBtn}>
                <span aria-hidden="true">✉️</span> Email
              </button>
            </div>
            <p
              style={{
                marginTop: 16, marginBottom: 0,
                fontSize: 11, color: "var(--mute-2, rgba(239,233,221,0.42))",
                lineHeight: 1.5,
                fontFamily: "var(--mono, monospace)",
                letterSpacing: "0.04em",
              }}
            >
              Either way we reply within 24 hours with the China showroom price and an estimated landed cost to your door.
            </p>
          </div>
        )}

        {/* View: email form */}
        {view === "email" && (
          <form onSubmit={onEmailSubmit} style={{ marginTop: 18 }}>
            <label style={_IM_STYLES.fieldLabel}>Your name *</label>
            <input
              type="text" required value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Full name" autoComplete="name"
              style={_IM_STYLES.input}
            />

            <label style={_IM_STYLES.fieldLabel}>Email *</label>
            <input
              ref={emailInputRef}
              type="email" required value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@example.com" autoComplete="email"
              style={_IM_STYLES.input}
            />

            <label style={_IM_STYLES.fieldLabel}>Phone <span style={{ textTransform: "none", letterSpacing: 0 }}>(optional)</span></label>
            <input
              type="tel" value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="+961 …" autoComplete="tel"
              style={_IM_STYLES.input}
            />

            <label style={_IM_STYLES.fieldLabel}>Message</label>
            <textarea
              rows={3} value={message}
              onChange={(e) => setMessage(e.target.value)}
              style={{
                ..._IM_STYLES.input,
                fontFamily: "inherit", resize: "vertical", minHeight: 70,
              }}
            />

            <div style={{ display: "flex", gap: 10, marginTop: 18, flexWrap: "wrap" }}>
              <button type="button" onClick={() => setView("choice")} style={_IM_STYLES.ghostBtn}>
                ← Back
              </button>
              <button
                type="submit"
                disabled={submitting}
                style={{
                  ..._IM_STYLES.primaryBtn,
                  opacity: submitting ? 0.6 : 1,
                  cursor: submitting ? "wait" : "pointer",
                }}
              >
                {submitting ? "Sending…" : "Send inquiry"}
              </button>
            </div>
          </form>
        )}

        {/* View: sent */}
        {view === "sent" && (
          <div style={{ textAlign: "center", padding: "12px 0 4px" }}>
            <div
              aria-hidden="true"
              style={{
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                width: 56, height: 56, borderRadius: "50%",
                background: "rgba(232,115,46,0.15)",
                border: "1px solid rgba(232,115,46,0.4)",
                margin: "22px 0 18px",
              }}
            >
              <span style={{ fontSize: 28, color: "var(--amber, #e8732e)", lineHeight: 1 }}>✓</span>
            </div>
            <h4
              className="serif"
              style={{
                fontSize: 22, margin: 0, marginBottom: 10,
                fontFamily: "var(--serif, serif)",
              }}
            >
              Got it.
            </h4>
            <p
              style={{
                fontSize: 14, color: "var(--mute, rgba(239,233,221,0.58))",
                marginBottom: 22, lineHeight: 1.6,
              }}
            >
              Our team will reply to{" "}
              <strong style={{ color: "var(--bone, #efe9dd)" }}>{email}</strong>{" "}
              within 24 hours with the next steps for your{" "}
              <strong style={{ color: "var(--bone, #efe9dd)" }}>
                {car.brand} {car.model_en}
              </strong>.
            </p>
            <button type="button" onClick={onClose} style={_IM_STYLES.ghostBtn}>
              Close
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

window.InquiryModal = InquiryModal;
