// Maison Yeya — Appointments multi-step modal

function AppointmentModal({ open, onClose, savedItems, onRemoveSaved }) {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    occasion: "",
    fullName: "",
    email: "",
    phone: "",
    eventDate: "",
    preferredDate: "",
    preferredTime: "Morning",
    notes: "",
    ack: false
  });
  const [done, setDone] = useState(false);

  useEffect(() => {
    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]);

  // Reset state when re-opened after completion
  useEffect(() => {
    if (open && done) {
      setTimeout(() => { setDone(false); setStep(0); }, 200);
    }
  }, [open]);

  if (!open) return null;

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

  const steps = [
    { id: "occasion",  label: "Occasion",   valid: () => !!data.occasion },
    { id: "details",   label: "Details",    valid: () => data.fullName.trim() && data.email.trim() && data.phone.trim() },
    { id: "schedule",  label: "Schedule",   valid: () => !!data.preferredDate },
    { id: "review",    label: "Review",     valid: () => data.ack }
  ];

  const next = () => {
    if (!steps[step].valid()) return;
    if (step === steps.length - 1) {
      setDone(true);
      return;
    }
    setStep(s => s + 1);
  };
  const back = () => setStep(s => Math.max(0, s - 1));

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 300 }}>
      <div onClick={onClose}
           style={{ position: "absolute", inset: 0, background: "rgba(20,17,15,0.62)", animation: "fadeIn 240ms ease both" }}></div>
      <div style={{
        position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center",
        padding: 24, pointerEvents: "none"
      }}>
        <div className="scroll-pretty" style={{
          background: "var(--paper)", width: "min(1080px, 100%)", maxHeight: "92vh", overflowY: "auto",
          pointerEvents: "auto", display: "grid", gridTemplateColumns: "1fr 1.1fr",
          animation: "modalIn 360ms cubic-bezier(0.22, 1, 0.36, 1) both"
        }}>
          <style>{`@keyframes modalIn { from { transform: translateY(20px); opacity: 0; } to { transform: none; opacity: 1; } }`}</style>

          {/* Left: image rail */}
          <aside style={{ position: "relative", minHeight: 600, background: "#14110f" }}>
            <img src="media/media-11-front-pg-cover-copy.webp" alt=""
                 style={{ width: "100%", height: "100%", objectFit: "cover", opacity: 0.85 }}/>
            <div style={{ position: "absolute", inset: 0,
                          background: "linear-gradient(to bottom, rgba(20,17,15,0.4), rgba(20,17,15,0.6))",
                          color: "#fff", display: "flex", flexDirection: "column",
                          padding: "40px 36px", justifyContent: "space-between" }}>
              <div>
                <YeyaMark size={26} color="#fff"/>
                <div className="wordmark-W" style={{ marginTop: 14, fontSize: 14, color: "#fff" }}>Maison Yeya</div>
              </div>

              <div>
                <div className="micro" style={{ color: "rgba(255,255,255,0.7)", marginBottom: 14 }}>
                  Step {done ? steps.length : step + 1} of {steps.length}
                </div>
                <div className="display" style={{ fontSize: 44, color: "#fff", lineHeight: 1.04, margin: "0 0 16px" }}>
                  {done ? "Thank you." : "Request a Private Appointment."}
                </div>
                <p className="editorial" style={{ fontSize: 16, color: "rgba(255,255,255,0.78)", lineHeight: 1.5, fontStyle: "italic" }}>
                  {done
                    ? "Your enquiry has been received. A concierge will respond within one working day."
                    : "We respond within one working day. All appointments take place at the atelier in Dubai Design District."}
                </p>

                <div className="hair-dark" style={{ margin: "32px 0" }}></div>

                <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                  {steps.map((s, i) => (
                    <div key={s.id} style={{ display: "grid", gridTemplateColumns: "32px 1fr", gap: 14, alignItems: "center",
                                              opacity: i === step ? 1 : 0.6, transition: "opacity 200ms ease" }}>
                      <div style={{
                        width: 26, height: 26, borderRadius: "50%",
                        border: `1px solid ${i <= step ? "#fff" : "rgba(255,255,255,0.4)"}`,
                        background: i < step || done ? "#fff" : "transparent",
                        color: i < step || done ? "var(--ink)" : "#fff",
                        display: "flex", alignItems: "center", justifyContent: "center",
                        fontFamily: "var(--sans-ui)", fontSize: 11
                      }}>
                        {(i < step || done) ? "✓" : i + 1}
                      </div>
                      <div className="label" style={{ color: "#fff" }}>{s.label}</div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </aside>

          {/* Right: form */}
          <section style={{ padding: "40px 48px 36px", display: "flex", flexDirection: "column", position: "relative" }}>
            <div style={{ position: "absolute", top: 24, right: 24 }}>
              <button className="label" onClick={onClose}>Close ✕</button>
            </div>

            {done ? (
              <ThankYou data={data} savedItems={savedItems} onClose={onClose}/>
            ) : (
              <>
                {step === 0 && <StepOccasion data={data} set={set} savedItems={savedItems}/>}
                {step === 1 && <StepDetails data={data} set={set}/>}
                {step === 2 && <StepSchedule data={data} set={set}/>}
                {step === 3 && <StepReview data={data} set={set} savedItems={savedItems} onRemoveSaved={onRemoveSaved}/>}

                <div style={{ marginTop: "auto", paddingTop: 36,
                              display: "flex", justifyContent: "space-between", alignItems: "center",
                              borderTop: "1px solid var(--hair)" }}>
                  <div className="micro" style={{ color: "var(--ink-mute)" }}>
                    {steps[step].valid() ? "Looks good." : "Complete the fields above to continue."}
                  </div>
                  <div style={{ display: "flex", gap: 12, paddingTop: 32 }}>
                    {step > 0 && <button className="btn ghost" onClick={back}>← Back</button>}
                    <button className="btn solid" disabled={!steps[step].valid()} onClick={next}
                            style={{ opacity: steps[step].valid() ? 1 : 0.4,
                                     cursor: steps[step].valid() ? "pointer" : "not-allowed",
                                     pointerEvents: steps[step].valid() ? "auto" : "none" }}>
                      {step === steps.length - 1 ? "Send Enquiry" : "Continue →"}
                    </button>
                  </div>
                </div>
              </>
            )}
          </section>
        </div>
      </div>
    </div>
  );
}

// ─── Step 1: Occasion ───
function StepOccasion({ data, set, savedItems }) {
  const opts = [
    { id: "bridal",       label: "Bridal Couture", note: "Wedding gown, second look, full bridal couture privée." },
    { id: "couture",      label: "Couture · Evening", note: "Eveningwear, red-carpet, premiere or gala." },
    { id: "made-to-meas", label: "Made-to-Measure", note: "A bespoke commission outside scheduled collections." },
    { id: "press",        label: "Press / Styling", note: "Editorial, red-carpet, or stylist enquiry." }
  ];
  return (
    <div className="fade-in">
      <div className="micro" style={{ marginBottom: 14 }}>01 · Occasion</div>
      <h3 className="display" style={{ fontSize: 38, margin: "0 0 32px" }}>What brings you to the Maison?</h3>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        {opts.map(o => (
          <button key={o.id} onClick={() => set("occasion", o.id)}
                  style={{
                    textAlign: "left", padding: 22, cursor: "pointer",
                    border: `1px solid ${data.occasion === o.id ? "var(--ink)" : "var(--hair)"}`,
                    background: data.occasion === o.id ? "var(--paper-2)" : "transparent",
                    transition: "all 200ms ease"
                  }}>
            <div className="display" style={{ fontSize: 22, marginBottom: 8 }}>{o.label}</div>
            <div className="editorial" style={{ fontSize: 14, color: "var(--ink-soft)", lineHeight: 1.45 }}>{o.note}</div>
          </button>
        ))}
      </div>

      {savedItems.length > 0 && (
        <div style={{ marginTop: 28, padding: "18px 22px", background: "var(--paper-2)", display: "flex", gap: 12, alignItems: "center" }}>
          <Heart filled size={14}/>
          <div className="editorial" style={{ fontSize: 15, color: "var(--ink-soft)", margin: 0 }}>
            {savedItems.length} saved look{savedItems.length > 1 ? "s" : ""} will accompany your enquiry.
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Step 2: Details ───
function StepDetails({ data, set }) {
  return (
    <div className="fade-in">
      <div className="micro" style={{ marginBottom: 14 }}>02 · Your Details</div>
      <h3 className="display" style={{ fontSize: 38, margin: "0 0 32px" }}>Tell us who is enquiring.</h3>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32 }}>
        <div className="field" style={{ gridColumn: "1 / -1" }}>
          <label>Full Name</label>
          <input type="text" value={data.fullName} onChange={e => set("fullName", e.target.value)} placeholder="Mrs. ..."/>
        </div>
        <div className="field">
          <label>Email</label>
          <input type="email" value={data.email} onChange={e => set("email", e.target.value)} placeholder="you@example.com"/>
        </div>
        <div className="field">
          <label>Phone / WhatsApp</label>
          <input type="tel" value={data.phone} onChange={e => set("phone", e.target.value)} placeholder="+971 ..."/>
        </div>
        <div className="field" style={{ gridColumn: "1 / -1" }}>
          <label>Event Date (optional)</label>
          <input type="date" value={data.eventDate} onChange={e => set("eventDate", e.target.value)}/>
        </div>
      </div>
    </div>
  );
}

// ─── Step 3: Schedule ───
function StepSchedule({ data, set }) {
  // Generate next 21 days, skip Fridays (Dubai closure)
  const days = useMemo(() => {
    const out = [];
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    for (let i = 1; i < 30 && out.length < 14; i++) {
      const d = new Date(today);
      d.setDate(today.getDate() + i);
      if (d.getDay() === 5) continue; // Friday closed
      out.push(d);
    }
    return out;
  }, []);

  const timeSlots = ["Morning · 10:00 – 12:00", "Midday · 12:00 – 14:00", "Afternoon · 14:00 – 16:00", "Evening · 16:00 – 18:00"];

  return (
    <div className="fade-in">
      <div className="micro" style={{ marginBottom: 14 }}>03 · Schedule</div>
      <h3 className="display" style={{ fontSize: 38, margin: "0 0 12px" }}>Choose a preferred date.</h3>
      <p className="editorial" style={{ fontSize: 14, color: "var(--ink-mute)", margin: "0 0 28px" }}>
        Showroom hours: 10:00 – 18:00. Closed Fridays and UAE public holidays.
      </p>

      <div className="scroll-pretty" style={{
        display: "grid", gridTemplateColumns: "repeat(7, minmax(0, 1fr))", gap: 8, marginBottom: 32
      }}>
        {days.map(d => {
          const iso = d.toISOString().slice(0, 10);
          const sel = data.preferredDate === iso;
          return (
            <button key={iso}
                    onClick={() => set("preferredDate", iso)}
                    style={{
                      padding: "16px 10px", textAlign: "center", cursor: "pointer",
                      border: `1px solid ${sel ? "var(--ink)" : "var(--hair)"}`,
                      background: sel ? "var(--ink)" : "transparent",
                      color: sel ? "var(--paper)" : "var(--ink)",
                      transition: "all 200ms ease"
                    }}>
              <div className="micro" style={{ marginBottom: 6, color: sel ? "rgba(244,239,231,0.6)" : "var(--ink-mute)" }}>
                {d.toLocaleDateString("en-US", { weekday: "short" })}
              </div>
              <div className="display" style={{ fontSize: 24, lineHeight: 1, color: "inherit" }}>
                {d.getDate()}
              </div>
              <div className="micro" style={{ marginTop: 4, color: sel ? "rgba(244,239,231,0.6)" : "var(--ink-mute)" }}>
                {d.toLocaleDateString("en-US", { month: "short" })}
              </div>
            </button>
          );
        })}
      </div>

      <div className="micro" style={{ marginBottom: 14 }}>Preferred Time</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        {timeSlots.map(t => (
          <button key={t} onClick={() => set("preferredTime", t.split(" ")[0])}
                  className="editorial"
                  style={{
                    padding: "14px 18px", textAlign: "left", cursor: "pointer", fontSize: 15,
                    border: `1px solid ${data.preferredTime === t.split(" ")[0] ? "var(--ink)" : "var(--hair)"}`,
                    background: data.preferredTime === t.split(" ")[0] ? "var(--paper-2)" : "transparent"
                  }}>
            {t}
          </button>
        ))}
      </div>
    </div>
  );
}

// ─── Step 4: Review ───
function StepReview({ data, set, savedItems, onRemoveSaved }) {
  const occasionLabels = {
    bridal: "Bridal Couture",
    couture: "Couture · Evening",
    "made-to-meas": "Made-to-Measure",
    press: "Press / Styling"
  };
  const dateLabel = data.preferredDate
    ? new Date(data.preferredDate).toLocaleDateString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric" })
    : "—";
  return (
    <div className="fade-in">
      <div className="micro" style={{ marginBottom: 14 }}>04 · Review</div>
      <h3 className="display" style={{ fontSize: 38, margin: "0 0 28px" }}>Confirm and send.</h3>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28, marginBottom: 28 }}>
        <ReviewRow label="Occasion" value={occasionLabels[data.occasion] || "—"}/>
        <ReviewRow label="Name" value={data.fullName || "—"}/>
        <ReviewRow label="Email" value={data.email || "—"}/>
        <ReviewRow label="Phone" value={data.phone || "—"}/>
        <ReviewRow label="Preferred Date" value={dateLabel}/>
        <ReviewRow label="Preferred Time" value={data.preferredTime}/>
        {data.eventDate && <ReviewRow label="Event Date" value={new Date(data.eventDate).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" })}/>}
      </div>

      <div className="field">
        <label>Notes for the atelier (optional)</label>
        <textarea value={data.notes} onChange={e => set("notes", e.target.value)} rows={3}
                  placeholder="A line about your event, your style, or anything we should know."/>
      </div>

      {savedItems.length > 0 && (
        <div style={{ marginTop: 24, padding: "18px 22px", background: "var(--paper-2)" }}>
          <div className="micro" style={{ marginBottom: 12 }}>Saved Looks · {savedItems.length}</div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            {savedItems.map(it => (
              <div key={it.id} className="chip on" style={{ paddingRight: 10 }}>
                {it.name}
                <button onClick={() => onRemoveSaved(it)}
                        style={{ marginLeft: 6, color: "var(--ink-mute)", cursor: "pointer", border: 0, background: "none" }}>
                  ✕
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      <label style={{ display: "flex", gap: 12, marginTop: 24, cursor: "pointer", alignItems: "flex-start" }}>
        <input type="checkbox" checked={data.ack} onChange={e => set("ack", e.target.checked)}
               style={{ marginTop: 4 }}/>
        <span className="editorial" style={{ fontSize: 14, color: "var(--ink-soft)", lineHeight: 1.5 }}>
          I understand Maison Yeya works by quotation and consultation, and that all appointments take place at the atelier in Dubai Design District. I consent to being contacted by the Maison.
        </span>
      </label>
    </div>
  );
}

function ReviewRow({ label, value }) {
  return (
    <div style={{ borderTop: "1px solid var(--hair)", paddingTop: 14 }}>
      <div className="micro" style={{ marginBottom: 6 }}>{label}</div>
      <div className="editorial" style={{ fontSize: 17 }}>{value}</div>
    </div>
  );
}

// ─── Confirmation ───
function ThankYou({ data, savedItems, onClose }) {
  return (
    <div className="fade-in" style={{ paddingTop: 12 }}>
      <div className="display" style={{ fontSize: 30, color: "var(--ink-mute)", marginBottom: 14 }}>✦</div>
      <h3 className="display" style={{ fontSize: 48, margin: "0 0 24px", lineHeight: 1.04 }}>
        Your enquiry is with the atelier.
      </h3>
      <p className="editorial" style={{ fontSize: 18, lineHeight: 1.55, color: "var(--ink-soft)", margin: "0 0 36px", fontStyle: "italic" }}>
        A concierge will respond to <strong style={{ fontStyle: "normal" }}>{data.email || "your email"}</strong> within one working day to confirm your appointment and answer any questions ahead of your visit.
      </p>

      <div className="hair" style={{ marginBottom: 28 }}></div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28, marginBottom: 36 }}>
        <ReviewRow label="Reference" value={`MY-${Math.floor(Math.random() * 90000 + 10000)}`}/>
        <ReviewRow label="Saved Looks" value={String(savedItems.length).padStart(2, "0")}/>
      </div>

      <p className="micro" style={{ color: "var(--ink-mute)", marginBottom: 28 }}>
        For urgent enquiries, the atelier is reachable on {CONTACT.mobile}.
      </p>

      <button className="btn" onClick={onClose}>Close</button>
    </div>
  );
}

window.AppointmentModal = AppointmentModal;
