// live-booking.jsx — multi-step booking modal + lightbox + toast helpers

/* ─── Toast (top-right, auto-dismiss) ─────────────────────────────── */
function useToasts() {
  const [list, setList] = React.useState([]);
  const push = React.useCallback((text, kind = "info") => {
    const id = Date.now() + Math.random();
    setList(l => [...l, { id, text, kind }]);
    setTimeout(() => setList(l => l.filter(t => t.id !== id)), 3500);
  }, []);
  const node = (
    <div style={{ position: "fixed", top: 20, right: 20, zIndex: 200, display: "flex", flexDirection: "column", gap: 10, pointerEvents: "none" }}>
      {list.map(t => (
        <div key={t.id} style={{
          pointerEvents: "auto",
          padding: "14px 20px", borderRadius: 12,
          background: t.kind === "ok" ? "var(--c-navy)" : "var(--c-paper)",
          color: t.kind === "ok" ? "#fff" : "var(--c-ink)",
          border: t.kind === "ok" ? "1px solid var(--c-navy)" : "1px solid var(--c-line)",
          boxShadow: "0 10px 30px rgba(11,37,69,0.18)",
          fontSize: 14, fontWeight: 600, maxWidth: 360,
          display: "flex", alignItems: "center", gap: 12,
          animation: "toastIn .25s ease",
        }}>
          {t.kind === "ok" && <Ico.check className="ico" style={{ width: 18, height: 18, color: "var(--c-accent)" }}/>}
          {t.text}
        </div>
      ))}
    </div>
  );
  return [push, node];
}

/* ─── Booking modal ──────────────────────────────────────────────── */
function BookingModal({ open, preset, onClose, onSubmit }) {
  const m = useIsMobile();
  const [step, setStep] = React.useState(0); // 0 route, 1 contact, 2 success
  const [data, setData] = React.useState({
    route: "", type: "", price: "",
    from: "Huế", to: "Đà Nẵng",
    date: "", time: "08:00", seats: 1,
    name: "", phone: "", note: "",
  });
  const [touched, setTouched] = React.useState({});

  // Reset when reopened or preset changes
  React.useEffect(() => {
    if (open) {
      setStep(0); setTouched({});
      const today = new Date();
      const tomorrow = new Date(today.getTime() + 24*60*60*1000);
      const iso = tomorrow.toISOString().slice(0, 10);
      setData(d => ({
        ...d,
        route: preset?.route || "",
        type:  preset?.type  || "Xe ghép Limousine",
        price: preset?.price || "",
        from:  preset?.from  || "Huế",
        to:    preset?.to    || "Đà Nẵng",
        date:  iso,
      }));
    }
  }, [open, preset]);

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

  if (!open) return null;

  const errs = {
    from: !data.from ? "Chọn điểm đón" : "",
    to:   !data.to ? "Chọn điểm đến" : (data.to === data.from ? "Điểm đến phải khác điểm đón" : ""),
    date: !data.date ? "Chọn ngày đi" : "",
    name: !data.name.trim() ? "Họ và tên không được trống" : "",
    phone: !/^0\d{9,10}$/.test(data.phone.replace(/\s/g, "")) ? "Số điện thoại không hợp lệ (10 số, bắt đầu 0)" : "",
  };
  const step0Valid = !errs.from && !errs.to && !errs.date;
  const step1Valid = !errs.name && !errs.phone;

  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const blur = (k) => setTouched(t => ({ ...t, [k]: true }));
  const showErr = (k) => touched[k] && errs[k];

  const submit = () => {
    setTouched({ name: true, phone: true, from: true, to: true, date: true });
    if (!step1Valid) return;
    onSubmit && onSubmit(data);
    setStep(2);
  };

  return (
    <div role="dialog" aria-modal="true"
      style={{ position: "fixed", inset: 0, background: "rgba(6,26,53,0.65)", backdropFilter: "blur(6px)", zIndex: 100, display: "flex", alignItems: m ? "flex-end" : "center", justifyContent: "center", padding: m ? 0 : 20, animation: "fadeIn .2s ease" }}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{
        width: "100%", maxWidth: 720, background: "var(--c-paper)",
        borderRadius: m ? "22px 22px 0 0" : 22, overflow: "hidden",
        boxShadow: "0 40px 80px rgba(0,0,0,0.4)", animation: "popIn .25s ease",
        maxHeight: m ? "94vh" : "auto", display: "flex", flexDirection: "column",
      }}>
        {/* Header */}
        <div style={{ position: "relative", padding: m ? "18px 18px 14px" : "26px 32px 20px", borderBottom: "1px solid var(--c-line)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div>
              <div style={{ fontSize: 11, fontWeight: 800, color: "var(--c-accent-deep)", letterSpacing: "0.14em", textTransform: "uppercase" }}>
                {step === 2 ? "Hoàn tất" : `Bước ${step+1} / 2`}
              </div>
              <h2 style={{ fontSize: m ? 18 : 24, fontWeight: 800, color: "var(--c-navy)", marginTop: 6, letterSpacing: "-0.02em", lineHeight: 1.2 }}>
                {step === 0 && (m ? "Đặt xe" : "Đặt xe — Hành trình của bạn")}
                {step === 1 && "Thông tin liên hệ"}
                {step === 2 && "Đặt xe thành công! 🎉"}
              </h2>
            </div>
            <button onClick={onClose} aria-label="Đóng" style={{ width: 36, height: 36, border: "1px solid var(--c-line)", background: "var(--c-cream)", color: "var(--c-ink)", borderRadius: 10, cursor: "pointer", fontSize: 18, fontWeight: 700, flex: "0 0 auto" }}>×</button>
          </div>
          {/* Progress bar */}
          {step < 2 && (
            <div style={{ marginTop: 14, display: "flex", gap: 6 }}>
              <div style={{ flex: 1, height: 4, borderRadius: 2, background: step >= 0 ? "var(--c-accent)" : "var(--c-line)" }}/>
              <div style={{ flex: 1, height: 4, borderRadius: 2, background: step >= 1 ? "var(--c-accent)" : "var(--c-line)" }}/>
            </div>
          )}
        </div>

        {/* Body */}
        <div style={{ padding: m ? "18px 18px 4px" : "26px 32px 4px", overflowY: "auto", flex: 1 }}>
          {step === 0 && <Step0 data={data} set={set} blur={blur} errs={errs} showErr={showErr}/>}
          {step === 1 && <Step1 data={data} set={set} blur={blur} errs={errs} showErr={showErr}/>}
          {step === 2 && <Step2 data={data}/>}
        </div>

        {/* Footer actions */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: m ? "14px 18px" : "22px 32px", borderTop: "1px solid var(--c-line)", background: "var(--c-cream)" }}>
          {step === 0 && (
            <>
              <button onClick={onClose} style={btnGhost()}>Huỷ</button>
              <button onClick={() => step0Valid ? setStep(1) : setTouched({ from: true, to: true, date: true })} style={btnPrimary()}>
                Tiếp tục <Ico.arrowR className="ico" style={{ width: 14, height: 14 }}/>
              </button>
            </>
          )}
          {step === 1 && (
            <>
              <button onClick={() => setStep(0)} style={btnGhost()}>← Quay lại</button>
              <button onClick={submit} style={btnPrimary()}>
                Xác nhận đặt xe <Ico.check className="ico" style={{ width: 14, height: 14 }}/>
              </button>
            </>
          )}
          {step === 2 && (
            <>
              <a href="tel:+84886075075" style={btnGhost()}>📞 Gọi xác nhận lại</a>
              <button onClick={onClose} style={btnPrimary()}>Hoàn tất</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function btnGhost() {
  return { background: "transparent", color: "var(--c-ink)", border: "1px solid var(--c-line-strong)", padding: "12px 20px", borderRadius: 10, fontSize: 14, fontWeight: 700, cursor: "pointer", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 8 };
}
function btnPrimary() {
  return { background: "var(--c-navy)", color: "#fff", border: 0, padding: "12px 22px", borderRadius: 10, fontSize: 14, fontWeight: 800, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8 };
}

/* ─── Step 0: route + date ─── */
function Step0({ data, set, blur, errs, showErr }) {
  const m = useIsMobile();
  const cities = ["Huế", "Đà Nẵng", "Hội An", "Sân bay Đà Nẵng"];
  const types = [
    { v: "Xe ghép Limousine", desc: "Ghế đơn, 9 chỗ" },
    { v: "Xe ghép 7 chỗ",     desc: "Fortuner, Innova" },
    { v: "Bao xe 4 chỗ",       desc: "Sedan riêng" },
    { v: "Bao xe 7 chỗ",       desc: "Đi nhóm, gia đình" },
    { v: "Bao Limousine 9 chỗ",desc: "VIP đoàn lớn" },
  ];
  return (
    <div style={{ display: "grid", gap: 16 }}>
      {/* Route row */}
      <div style={{ display: "grid", gridTemplateColumns: m ? "1fr" : "1fr 1fr", gap: 12 }}>
        <Field label="Điểm đón" icon="pin" err={showErr("from")}>
          <select value={data.from} onChange={(e) => set("from", e.target.value)} onBlur={() => blur("from")} style={selectStyle()}>
            {cities.map(c => <option key={c}>{c}</option>)}
          </select>
        </Field>
        <Field label="Điểm đến" icon="pin" err={showErr("to")}>
          <select value={data.to} onChange={(e) => set("to", e.target.value)} onBlur={() => blur("to")} style={selectStyle()}>
            {cities.map(c => <option key={c}>{c}</option>)}
          </select>
        </Field>
      </div>

      {/* Type — radio cards */}
      <div>
        <div style={fieldLabel()}>Loại dịch vụ</div>
        <div style={{ display: "grid", gridTemplateColumns: m ? "1fr" : "repeat(2, 1fr)", gap: 10, marginTop: 8 }}>
          {types.map(t => {
            const on = data.type === t.v;
            return (
              <button key={t.v} type="button" onClick={() => set("type", t.v)} style={{
                padding: "12px 14px", textAlign: "left",
                border: on ? "2px solid var(--c-accent)" : "1px solid var(--c-line)",
                background: on ? "rgba(232,155,74,0.08)" : "var(--c-paper)",
                borderRadius: 12, cursor: "pointer", font: "inherit"
              }}>
                <div style={{ fontSize: 13, fontWeight: 800, color: "var(--c-navy)", letterSpacing: "-0.01em" }}>{t.v}</div>
                <div style={{ fontSize: 11, color: "var(--c-mute)", marginTop: 2 }}>{t.desc}</div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Date + time + seats */}
      <div style={{ display: "grid", gridTemplateColumns: m ? "1fr 1fr" : "1.2fr 1fr 1fr", gap: 12 }}>
        <Field label="Ngày đi" icon="cal" err={showErr("date")}>
          <input type="date" value={data.date} onChange={(e) => set("date", e.target.value)} onBlur={() => blur("date")} style={inputStyle()}/>
        </Field>
        <Field label="Giờ đi" icon="clock">
          <select value={data.time} onChange={(e) => set("time", e.target.value)} style={selectStyle()}>
            {TIMES.map(t => <option key={t}>{t}</option>)}
          </select>
        </Field>
        <Field label="Số khách" icon="user">
          <select value={data.seats} onChange={(e) => set("seats", +e.target.value)} style={selectStyle()}>
            {[1,2,3,4,5,6,7,8,9].map(n => <option key={n} value={n}>{n} khách</option>)}
          </select>
        </Field>
      </div>
    </div>
  );
}

/* ─── Step 1: contact ─── */
function Step1({ data, set, blur, errs, showErr }) {
  return (
    <div style={{ display: "grid", gap: 18 }}>
      <Field label="Họ và tên" icon="user" err={showErr("name")}>
        <input type="text" value={data.name} onChange={(e) => set("name", e.target.value)} onBlur={() => blur("name")} placeholder="VD: Nguyễn Văn A" style={inputStyle()}/>
      </Field>
      <Field label="Số điện thoại" icon="phone" err={showErr("phone")}>
        <input type="tel" value={data.phone} onChange={(e) => set("phone", e.target.value)} onBlur={() => blur("phone")} placeholder="VD: 0905123456" style={inputStyle()}/>
      </Field>
      <Field label="Ghi chú (tuỳ chọn)">
        <textarea value={data.note} onChange={(e) => set("note", e.target.value)} placeholder="Địa chỉ đón cụ thể, yêu cầu đặc biệt..." rows="3" style={{ ...inputStyle(), resize: "vertical", paddingTop: 10 }}/>
      </Field>

      {/* Summary */}
      <div style={{ background: "var(--c-cream)", border: "1px solid var(--c-line)", borderRadius: 12, padding: 18 }}>
        <div style={{ fontSize: 11, fontWeight: 800, color: "var(--c-accent-deep)", letterSpacing: "0.12em", textTransform: "uppercase" }}>Tóm tắt chuyến đi</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 12, fontSize: 13 }}>
          <SumRow l="Tuyến" v={`${data.from} → ${data.to}`}/>
          <SumRow l="Loại xe" v={data.type || "—"}/>
          <SumRow l="Ngày, giờ" v={`${vnDate(data.date)} · ${data.time}`}/>
          <SumRow l="Số khách" v={`${data.seats} khách`}/>
        </div>
      </div>
    </div>
  );
}

function vnDate(iso) {
  if (!iso) return "—";
  const [y, m, d] = iso.split("-");
  return `${d}.${m}.${y}`;
}
function SumRow({ l, v }) {
  return (
    <div>
      <div style={{ fontSize: 10, fontWeight: 700, color: "var(--c-mute)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{l}</div>
      <div style={{ fontSize: 14, fontWeight: 700, color: "var(--c-navy)", marginTop: 2 }}>{v}</div>
    </div>
  );
}

/* ─── Step 2: success ─── */
function Step2({ data }) {
  return (
    <div style={{ textAlign: "center", padding: "20px 0 30px" }}>
      <div style={{ width: 80, height: 80, borderRadius: "50%", background: "var(--c-accent)", color: "var(--c-navy-deep)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto", boxShadow: "0 12px 28px rgba(232,155,74,0.4)" }}>
        <Ico.check className="ico" style={{ width: 38, height: 38 }}/>
      </div>
      <h3 style={{ fontSize: 22, fontWeight: 800, color: "var(--c-navy)", marginTop: 22, letterSpacing: "-0.02em" }}>Cảm ơn {data.name.split(" ").slice(-1)[0]}!</h3>
      <p style={{ fontSize: 15, color: "var(--c-ink-soft)", marginTop: 8, lineHeight: 1.6 }}>
        Bôn Lê đã nhận yêu cầu đặt xe của bạn. Tổng đài sẽ gọi xác nhận tại số <strong style={{ color: "var(--c-navy)" }}>{data.phone}</strong> trong vòng 5 phút.
      </p>
      <div style={{ marginTop: 22, display: "inline-grid", gap: 8, padding: 18, background: "var(--c-cream)", borderRadius: 12, border: "1px dashed var(--c-accent)", textAlign: "left" }}>
        <SumLine l="Mã đặt" v={`BL-${Date.now().toString().slice(-6)}`}/>
        <SumLine l="Tuyến" v={`${data.from} → ${data.to}`}/>
        <SumLine l="Loại xe" v={data.type}/>
        <SumLine l="Ngày, giờ" v={`${vnDate(data.date)} · ${data.time}`}/>
      </div>
    </div>
  );
}
function SumLine({ l, v }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "100px 1fr", gap: 14, fontSize: 13 }}>
      <span style={{ color: "var(--c-mute)", fontWeight: 600 }}>{l}</span>
      <span style={{ color: "var(--c-navy)", fontWeight: 700 }}>{v}</span>
    </div>
  );
}

/* ─── Field shell ─── */
function Field({ label, icon, err, children }) {
  const I = icon ? Ico[icon] : null;
  return (
    <div>
      <div style={{ ...fieldLabel(), display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
          {I && <I className="ico" style={{ width: 13, height: 13, color: "var(--c-accent-deep)" }}/>}{label}
        </span>
        {err && <span style={{ fontSize: 11, color: "#C13", fontWeight: 600, textTransform: "none", letterSpacing: 0 }}>{err}</span>}
      </div>
      <div style={{ marginTop: 6 }}>{children}</div>
    </div>
  );
}

function fieldLabel() {
  return { fontSize: 11, fontWeight: 700, color: "var(--c-mute)", letterSpacing: "0.1em", textTransform: "uppercase" };
}
function inputStyle() {
  return { width: "100%", padding: "12px 14px", border: "1px solid var(--c-line-strong)", borderRadius: 10, fontSize: 14, color: "var(--c-ink)", background: "var(--c-paper)", outline: "none", fontFamily: "inherit", fontWeight: 500 };
}
function selectStyle() {
  return { ...inputStyle(), cursor: "pointer", appearance: "menulist" };
}

/* ─── Lightbox ─────────────────────────────────────────────────── */
function Lightbox({ items, index, onClose, onPrev, onNext }) {
  React.useEffect(() => {
    if (index == null) return;
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") onPrev();
      if (e.key === "ArrowRight") onNext();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [index, onClose, onPrev, onNext]);

  if (index == null) return null;
  const item = items[index];
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.92)", zIndex: 110, display: "flex", alignItems: "center", justifyContent: "center", padding: 40 }}>
      <button onClick={(e) => { e.stopPropagation(); onPrev(); }} aria-label="Trước" style={navBtn("left")}>‹</button>
      <ImageSlot onClick={(e) => e.stopPropagation()} src={SITE_IMAGES.gallery[index]} alt={item} fallbackLabel={`ẢNH — ${item.toUpperCase()}`} dark style={{ width: "min(1000px, 88vw)", height: "min(620px, 70vh)", borderRadius: 14, fontSize: 13 }}/>
      <button onClick={(e) => { e.stopPropagation(); onNext(); }} aria-label="Tiếp" style={navBtn("right")}>›</button>
      <div style={{ position: "absolute", top: 24, right: 28, display: "flex", gap: 12, alignItems: "center", color: "#fff", fontSize: 13, fontWeight: 600 }}>
        <span style={{ background: "rgba(255,255,255,0.1)", padding: "6px 12px", borderRadius: 999 }}>{index+1} / {items.length}</span>
        <button onClick={onClose} aria-label="Đóng" style={{ width: 36, height: 36, borderRadius: 10, background: "rgba(255,255,255,0.1)", color: "#fff", border: 0, fontSize: 18, cursor: "pointer" }}>×</button>
      </div>
      <div style={{ position: "absolute", bottom: 24, left: 0, right: 0, textAlign: "center", color: "rgba(255,255,255,0.7)", fontSize: 12 }}>
        ← → để chuyển ảnh · Esc để đóng
      </div>
    </div>
  );
}
function navBtn(side) {
  return {
    position: "absolute", [side]: 24, top: "50%", transform: "translateY(-50%)",
    width: 56, height: 56, borderRadius: "50%",
    background: "rgba(255,255,255,0.1)", color: "#fff", border: "1px solid rgba(255,255,255,0.2)",
    fontSize: 28, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
  };
}

Object.assign(window, { BookingModal, Lightbox, useToasts });
