/* --- Panos Melekkis · multi-step booking modal --- */

const D3 = window.PM_DATA;

const INTERESTS = [
  { id: "bespoke",  ti: "Bespoke",            sub: "Custom design" },
  { id: "bridal",   ti: "Engagement & Bridal", sub: "Rings, bands, sets" },
  { id: "collection", ti: "A collection piece", sub: "From the shop" },
  { id: "redesign", ti: "Redesign",           sub: "Heirloom stones" },
];

const LOCATIONS = [
  { id: "dubai",  ti: "Dubai d3",     sub: "By appointment" },
  { id: "cyprus", ti: "Limassol HQ",   sub: "Boutique hours" },
  { id: "video",  ti: "Video call",   sub: "International" },
];

function BookingModal({ open, onClose }) {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    interest: null,
    location: null,
    name: "",
    email: "",
    phone: "",
    date: null, // ISO date
    time: null,
    notes: "",
  });

  const TIMES = ["10:00", "11:30", "14:00", "15:30", "17:00"];

  // make a 14-day date grid starting today
  const dateGrid = React.useMemo(() => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return Array.from({ length: 14 }, (_, i) => {
      const d = new Date(today);
      d.setDate(today.getDate() + i);
      return d;
    });
  }, []);

  React.useEffect(() => {
    if (open) {
      document.body.classList.add("is-locked");
    } else {
      document.body.classList.remove("is-locked");
      // reset after exit animation
      const t = setTimeout(() => { setStep(0); }, 380);
      return () => clearTimeout(t);
    }
    return () => document.body.classList.remove("is-locked");
  }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));

  const steps = [
    { key: "interest", lab: "Interest"  },
    { key: "location", lab: "Where"     },
    { key: "datetime", lab: "When"      },
    { key: "contact",  lab: "Contact"   },
    { key: "review",   lab: "Confirm"   },
  ];

  const canNext = (() => {
    if (step === 0) return !!data.interest;
    if (step === 1) return !!data.location;
    if (step === 2) return !!data.date && !!data.time;
    if (step === 3) return !!data.name && (!!data.email || !!data.phone);
    if (step === 4) return true;
    return false;
  })();

  const isFinal = step === steps.length; // post-confirm state
  const next = () => {
    if (step === steps.length - 1) setStep(step + 1); // go to "submitted"
    else setStep(step + 1);
  };

  const back = () => setStep(Math.max(0, step - 1));

  const summary = (k) => {
    if (k === "interest")  return data.interest ? INTERESTS.find(i => i.id === data.interest).ti : "—";
    if (k === "location")  return data.location ? LOCATIONS.find(i => i.id === data.location).ti : "—";
    if (k === "datetime")  {
      if (!data.date) return "—";
      const d = new Date(data.date);
      return d.toLocaleDateString(undefined, { weekday: "short", day: "numeric", month: "long" }) + (data.time ? ` · ${data.time}` : "");
    }
    if (k === "contact")   return [data.name, data.email, data.phone].filter(Boolean).join(" · ");
    if (k === "notes")     return data.notes || "—";
    return "—";
  };

  const fmtDay = (d) => d.toLocaleDateString(undefined, { weekday: "short" }).slice(0, 2).toUpperCase();
  const fmtNum = (d) => d.getDate();
  const fmtMonth = (d) => d.toLocaleDateString(undefined, { month: "short" });

  const waMessage = () => {
    const lines = [
      `Hello — I'd like to book a consultation.`,
      `Interest: ${summary("interest")}.`,
      `Location: ${summary("location")}.`,
      `When: ${summary("datetime")}.`,
      `Name: ${data.name || ""}.`,
      data.notes ? `Notes: ${data.notes}` : null,
    ].filter(Boolean).join("\n");
    return encodeURIComponent(lines);
  };

  return (
    <div className={"modal-back " + (open ? "is-open" : "")} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true" aria-labelledby="bk-title">
        {/* SIDE */}
        <aside className="modal-side">
          <img className="mark" src="media/logo-panos-melekkis.svg" alt="Panos Melekkis" />
          <div className="lede">
            A private<br />consultation,<br />with the gemologist.
          </div>
          <div className="stepper">
            {steps.map((s, i) => (
              <div className={"step " + (i === step ? "is-active" : i < step ? "is-done" : "")} key={s.key}>
                <span className="ix">{i < step ? "✓" : i + 1}</span>
                <span>{s.lab}</span>
              </div>
            ))}
          </div>
          <div className="ftr">
            BG·045 · Dubai d3 · Limassol
            <br />
            +971 56 458 4432 · +357 25 310 912
          </div>
        </aside>

        {/* BODY */}
        <div className="modal-body">
          {!isFinal && (
            <button className="drawer-close" onClick={onClose} aria-label="Close" style={{ top: 14, right: 14, position: "absolute", background: "transparent", color: "var(--ink)", borderColor: "var(--line)" }}>
              <svg width="12" height="12" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M1 1l12 12M13 1L1 13"></path></svg>
            </button>
          )}

          {/* Step 0 — interest */}
          {step === 0 && (
            <React.Fragment>
              <span className="eyebrow">— Step 01 of 05</span>
              <h3 id="bk-title">What would you like to discuss?</h3>
              <p className="desc">A consultation is approximately 60 minutes. Tell us which conversation to prepare for.</p>
              <div className="choices">
                {INTERESTS.map((i) => (
                  <button
                    key={i.id}
                    className={"choice " + (data.interest === i.id ? "is-selected" : "")}
                    onClick={() => set("interest", i.id)}
                  >
                    <span className="ti">{i.ti}</span>
                    <span className="sub">{i.sub}</span>
                  </button>
                ))}
              </div>
            </React.Fragment>
          )}

          {/* Step 1 — location */}
          {step === 1 && (
            <React.Fragment>
              <span className="eyebrow">— Step 02 of 05</span>
              <h3>Where would you like to meet?</h3>
              <p className="desc">Both ateliers are private. The Dubai d3 studio is appointment-only; the Limassol boutique sees walk-ins during opening hours but consultations are reserved.</p>
              <div className="choices cols-3">
                {LOCATIONS.map((i) => (
                  <button
                    key={i.id}
                    className={"choice " + (data.location === i.id ? "is-selected" : "")}
                    onClick={() => set("location", i.id)}
                  >
                    <span className="ti">{i.ti}</span>
                    <span className="sub">{i.sub}</span>
                  </button>
                ))}
              </div>
            </React.Fragment>
          )}

          {/* Step 2 — date/time */}
          {step === 2 && (
            <React.Fragment>
              <span className="eyebrow">— Step 03 of 05</span>
              <h3>When suits you?</h3>
              <p className="desc">Pick any day in the next two weeks. We confirm the exact slot by WhatsApp within the same business day.</p>
              <div className="date-grid">
                {dateGrid.map((d) => {
                  const iso = d.toISOString().slice(0, 10);
                  const isSun = d.getDay() === 0 && data.location === "cyprus";
                  return (
                    <button
                      key={iso}
                      className={"date-cell " + (data.date === iso ? "is-selected" : "")}
                      onClick={() => set("date", iso)}
                      disabled={isSun}
                      title={isSun ? "Limassol boutique closed Sundays" : ""}
                    >
                      <span className="day">{fmtDay(d)}</span>
                      {fmtNum(d)}
                    </button>
                  );
                })}
              </div>

              {data.date && (
                <React.Fragment>
                  <div className="cap" style={{ marginTop: 18, opacity: 0.7 }}>— Time slot</div>
                  <div className="time-row">
                    {TIMES.map((t) => (
                      <button
                        key={t}
                        className={"time-pill " + (data.time === t ? "is-selected" : "")}
                        onClick={() => set("time", t)}
                      >
                        {t}
                      </button>
                    ))}
                  </div>
                </React.Fragment>
              )}
            </React.Fragment>
          )}

          {/* Step 3 — contact */}
          {step === 3 && (
            <React.Fragment>
              <span className="eyebrow">— Step 04 of 05</span>
              <h3>And how do we reach you?</h3>
              <p className="desc">We need one of email or phone. We use WhatsApp for confirmations — most clients prefer it.</p>
              <div className="field">
                <label htmlFor="bk-name">Name</label>
                <input id="bk-name" value={data.name} onChange={(e) => set("name", e.target.value)} placeholder="Full name" />
              </div>
              <div className="col-2" style={{ marginTop: 4 }}>
                <div className="field">
                  <label htmlFor="bk-email">Email</label>
                  <input id="bk-email" type="email" value={data.email} onChange={(e) => set("email", e.target.value)} placeholder="you@email.com" />
                </div>
                <div className="field">
                  <label htmlFor="bk-phone">Phone / WhatsApp</label>
                  <input id="bk-phone" value={data.phone} onChange={(e) => set("phone", e.target.value)} placeholder="+971 ..." />
                </div>
              </div>
              <div className="field">
                <label htmlFor="bk-notes">Notes (optional)</label>
                <textarea id="bk-notes" value={data.notes} onChange={(e) => set("notes", e.target.value)} placeholder="A specific piece, a stone you already own, an occasion in mind…" />
              </div>
            </React.Fragment>
          )}

          {/* Step 4 — review */}
          {step === 4 && (
            <React.Fragment>
              <span className="eyebrow">— Step 05 of 05</span>
              <h3>Confirm the consultation.</h3>
              <p className="desc">A WhatsApp confirmation goes to <b>+357 96060772</b> the moment you submit. You'll hear back from Panos personally within the same business day.</p>
              <div>
                <div className="review-row">
                  <div className="lab">Interest</div>
                  <div className="val">{summary("interest")}</div>
                </div>
                <div className="review-row">
                  <div className="lab">Where</div>
                  <div className="val">{summary("location")}</div>
                </div>
                <div className="review-row">
                  <div className="lab">When</div>
                  <div className="val">{summary("datetime")}</div>
                </div>
                <div className="review-row">
                  <div className="lab">Contact</div>
                  <div className="val">{summary("contact")}</div>
                </div>
                {data.notes && (
                  <div className="review-row">
                    <div className="lab">Notes</div>
                    <div className="val" style={{ whiteSpace: "pre-line" }}>{summary("notes")}</div>
                  </div>
                )}
              </div>
            </React.Fragment>
          )}

          {/* Final — confirmation */}
          {isFinal && (
            <div className="confirm-state">
              <div className="seal">PM</div>
              <span className="eyebrow">— Received</span>
              <div className="lede">
                Thank you, {data.name.split(" ")[0] || "—"}.
                <br />
                The consultation is held.
              </div>
              <p className="desc" style={{ maxWidth: "50ch" }}>
                A confirmation message has been sent. Panos will write back within the same business day to confirm your <b>{summary("datetime")}</b> {summary("location")} consultation — and to ask any preparation questions about your piece.
              </p>
              <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
                <a className="btn btn-house" href={`https://wa.me/${D3.contact.waNumber}?text=${waMessage()}`} target="_blank" rel="noreferrer">
                  Open WhatsApp confirmation
                  <Arrow d="up-right" />
                </a>
                <button className="btn btn-ghost-dark" onClick={onClose}>
                  Close
                </button>
              </div>
            </div>
          )}

          {!isFinal && (
            <div className="modal-actions">
              <button className="secondary" onClick={step === 0 ? onClose : back}>
                {step === 0 ? "Cancel" : "← Back"}
              </button>
              <button
                className={"btn btn-house"}
                onClick={next}
                disabled={!canNext}
                style={!canNext ? { opacity: 0.35, pointerEvents: "none" } : {}}
              >
                {step === steps.length - 1 ? "Confirm consultation" : "Continue"}
                <Arrow d={step === steps.length - 1 ? "up-right" : "right"} />
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
