/* modals.jsx — enquire / request-price / book-viewing flow */

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

const INTENT_LABELS = {
  enquire: { title: "Enquire", sub: "Tell us what you're looking for. We'll respond within 4 working hours." },
  price: { title: "Request price", sub: "Prices are shared privately. We'll be in touch shortly with figures and current availability." },
  viewing: { title: "Book a private viewing", sub: "Schedule a one-to-one at our Sheikh Zayed Road showroom." },
  tradein: { title: "Sell or trade-in your car", sub: "Send us the details and photos. We'll come back with an indicative offer." },
  export: { title: "Export enquiry", sub: "International buyer? We'll outline logistics — pending confirmation of our export service." },
};

function Modal({ open, onClose, intent = "enquire", vehicle = null }) {
  const [step, setStep] = useStateM(0);
  const [form, setForm] = useStateM({
    name: "", email: "", phone: "", country: "United Arab Emirates",
    when: "", message: "",
    sellMake: "", sellModel: "", sellYear: "",
  });
  const meta = INTENT_LABELS[intent] || INTENT_LABELS.enquire;

  useEffectM(() => { if (open) setStep(0); }, [open, intent]);
  useEffectM(() => {
    if (!open) return;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", onKey); };
  }, [open, onClose]);

  if (!open) return null;

  const setF = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const slots = [
    "Tomorrow · 14:00", "Tomorrow · 16:30", "Sat · 11:00", "Sat · 15:00", "Sun · 12:30", "Mon · 18:00",
  ];

  return (
    <div className="modal-bg" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal-card">
        {/* Header */}
        <div style={{ padding: "28px 36px 0", display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16 }}>
          <div>
            <div className="kbd-eyebrow" style={{ color: "#7a7e85", marginBottom: 10 }}>
              {step === 0 ? "Step 01 of 02" : "Step 02 of 02 · Confirmation"}
            </div>
            <h3 className="display" style={{ fontSize: 36, margin: 0, color: "var(--ink-on-paper)" }}>{meta.title}</h3>
            {vehicle && (
              <div className="mono" style={{ fontSize: 11, marginTop: 8, color: "#6a6e75", letterSpacing: "0.08em", textTransform: "uppercase" }}>
                Re: {vehicle.year} {vehicle.brand} {vehicle.model}
              </div>
            )}
          </div>
          <button onClick={onClose} aria-label="Close"
            style={{ background: "transparent", border: "1px solid rgba(0,0,0,0.18)", borderRadius: 999, width: 36, height: 36, cursor: "pointer", color: "var(--ink-on-paper)", display: "grid", placeItems: "center" }}>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 1L13 13M13 1L1 13" stroke="currentColor" strokeWidth="1.4"/></svg>
          </button>
        </div>

        {step === 0 && (
          <form onSubmit={(e) => { e.preventDefault(); setStep(1); }} style={{ padding: "24px 36px 36px" }}>
            <p style={{ marginTop: 0, color: "#54585f", fontSize: 15, maxWidth: 540 }}>{meta.sub}</p>

            {intent === "viewing" && (
              <div style={{ marginTop: 24 }}>
                <div className="kbd-eyebrow" style={{ color: "#7a7e85", marginBottom: 12 }}>Pick a time</div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(160px, 1fr))", gap: 8 }}>
                  {slots.map((s) => (
                    <button type="button" key={s}
                      onClick={() => setForm({ ...form, when: s })}
                      style={{
                        padding: "12px 14px",
                        border: form.when === s ? "1px solid var(--accent)" : "1px solid rgba(0,0,0,0.16)",
                        background: form.when === s ? "rgba(225,29,42,0.06)" : "transparent",
                        color: "var(--ink-on-paper)",
                        borderRadius: 8, cursor: "pointer",
                        fontSize: 13, textAlign: "left",
                        fontFamily: "var(--mono)",
                      }}>{s}</button>
                  ))}
                </div>
                <div className="mono" style={{ fontSize: 10, color: "#9aa0a6", marginTop: 12, letterSpacing: "0.08em", textTransform: "uppercase" }}>Slots illustrative · real calendar in production</div>
              </div>
            )}

            {intent === "tradein" && (
              <div style={{ marginTop: 24, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 24 }}>
                <div className="field"><label>Make</label><input required value={form.sellMake} onChange={setF("sellMake")} placeholder="e.g. Ferrari" /></div>
                <div className="field"><label>Model</label><input required value={form.sellModel} onChange={setF("sellModel")} placeholder="e.g. 488 Pista" /></div>
                <div className="field"><label>Year</label><input required value={form.sellYear} onChange={setF("sellYear")} placeholder="2021" /></div>
              </div>
            )}

            <div style={{ marginTop: 24, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
              <div className="field"><label>Full name</label><input required value={form.name} onChange={setF("name")} placeholder="—" /></div>
              <div className="field"><label>Email</label><input required type="email" value={form.email} onChange={setF("email")} placeholder="—" /></div>
              <div className="field"><label>Phone (with country code)</label><input required value={form.phone} onChange={setF("phone")} placeholder="+971 …" /></div>
              <div className="field"><label>Country / market</label>
                <select value={form.country} onChange={setF("country")}>
                  <option>United Arab Emirates</option>
                  <option>Saudi Arabia</option>
                  <option>Qatar</option>
                  <option>Kuwait</option>
                  <option>United Kingdom</option>
                  <option>Switzerland</option>
                  <option>Germany</option>
                  <option>Russia / CIS</option>
                  <option>China</option>
                  <option>United States</option>
                  <option>Other</option>
                </select>
              </div>
            </div>

            <div className="field" style={{ marginTop: 24 }}>
              <label>{intent === "tradein" ? "Anything else (condition, mileage, photos)" : "Notes (optional)"}</label>
              <textarea rows={4} value={form.message} onChange={setF("message")}
                placeholder={intent === "tradein" ? "Condition, mileage, options, where the car is stored…" : "Specific car, colour, configuration, timing…"} />
            </div>

            {intent === "tradein" && (
              <div style={{ marginTop: 20, padding: 16, border: "1px dashed rgba(0,0,0,0.18)", borderRadius: 10, background: "rgba(0,0,0,0.02)" }}>
                <div className="kbd-eyebrow" style={{ color: "#7a7e85", marginBottom: 6 }}>Photos</div>
                <div style={{ color: "#54585f", fontSize: 13 }}>Drag images here · or click to upload (placeholder)</div>
              </div>
            )}

            <div style={{ marginTop: 28, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
              <div style={{ fontSize: 12, color: "#7a7e85", maxWidth: 380 }}>
                We respond within 4 working hours. By submitting you accept our privacy notice.
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                <button type="button" className="btn btn-ghost-dark" onClick={onClose}>Cancel</button>
                <button type="submit" className="btn btn-primary">{intent === "viewing" ? "Confirm booking" : "Submit enquiry"}</button>
              </div>
            </div>
          </form>
        )}

        {step === 1 && (
          <div style={{ padding: "12px 36px 44px" }}>
            <div style={{ marginTop: 24, padding: 24, borderRadius: 12, background: "rgba(225,29,42,0.06)", border: "1px solid rgba(225,29,42,0.2)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                <span style={{ width: 8, height: 8, borderRadius: 99, background: "var(--accent)" }} />
                <div className="mono" style={{ fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--accent)" }}>Sent · Ref&nbsp;FM-{Math.random().toString(36).slice(2,7).toUpperCase()}</div>
              </div>
              <h4 className="display" style={{ fontSize: 28, margin: "12px 0 6px", color: "var(--ink-on-paper)" }}>
                Thank you, {form.name.split(" ")[0] || "—"}.
              </h4>
              <p style={{ margin: 0, color: "#54585f", maxWidth: 520, fontSize: 15 }}>
                Your {meta.title.toLowerCase()} is logged. A specialist will be in touch via {form.email || "email"} and {form.phone || "phone"}.
                {intent === "viewing" && form.when && <> Your slot is held for <strong>{form.when}</strong>.</>}
              </p>
            </div>

            <div style={{ marginTop: 24, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <a className="btn btn-ghost-dark" href="tel:+97143201030">Call us +971 4 320 1030</a>
              <a className="btn btn-ghost-dark" href="mailto:info@f1rstmotors.com">Email info@f1rstmotors.com</a>
            </div>

            <div className="mono" style={{ fontSize: 10, color: "#9aa0a6", marginTop: 24, letterSpacing: "0.08em", textTransform: "uppercase" }}>
              Demo prototype — no enquiry was actually sent · in production this posts to Formspree/CRM
            </div>

            <div style={{ marginTop: 24, display: "flex", justifyContent: "flex-end" }}>
              <button className="btn btn-primary" onClick={onClose}>Close</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Modal });
