/* global React */
const { useState, useMemo, useEffect } = React;

function StepDots({ step }) {
  const labels = ["Service", "When", "Details", "Pay", "Done"];
  return (
    <div className="book-progress">
      {labels.map((l, i) => (
        <div key={l} className={"step " + (i < step ? "done" : "") + (i === step ? "active" : "")}>
          <span>0{i + 1} · {l}</span>
          <div className="bar" />
        </div>
      ))}
    </div>
  );
}

function StepService({ state, set }) {
  return (
    <div className="book-step">
      <h3>Choose your service</h3>
      <p className="sub">Onsen access can be added in step 3. Therapists are assigned on the day.</p>
      {window.NIK_SERVICES.map(s => (
        <div
          key={s.id}
          className={"svc-pick" + (state.serviceId === s.id ? " selected" : "")}
          onClick={() => set({ serviceId: s.id, duration: s.duration })}
        >
          <div className="name">
            {s.name}
            <small>{s.nameJp} · {s.category}</small>
          </div>
          <div className="duration">{s.duration} min</div>
          <div className="price">${s.price}</div>
        </div>
      ))}

      {state.serviceId && (() => {
        const svc = window.NIK_SERVICES.find(x => x.id === state.serviceId);
        if (svc.durations.length <= 1) return null;
        return (
          <div style={{ marginTop: 28 }}>
            <label style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.2em", color: "var(--stone)", textTransform: "uppercase", display: "block", marginBottom: 12 }}>
              Duration
            </label>
            <div className="tag-row">
              {svc.durations.map(d => (
                <div
                  key={d}
                  className={"tag" + (state.duration === d ? " on" : "")}
                  onClick={() => set({ duration: d })}
                >
                  {d} min · ${svc.pricing[d]}
                </div>
              ))}
            </div>
          </div>
        );
      })()}
    </div>
  );
}

function StepWhen({ state, set }) {
  const days = useMemo(() => window.buildCalendar(), []);
  const slots = useMemo(() => state.date ? window.buildSlots(state.date) : [], [state.date]);
  return (
    <div className="book-step">
      <h3>Pick a day & time</h3>
      <p className="sub">All times Phnom Penh (ICT). Last seating 9:00 pm.</p>
      <div className="cal-grid">
        {["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map(d => (
          <div key={d} className="dh">{d}</div>
        ))}
        {days.map(d => (
          <div
            key={d.iso}
            className={"cal-day" + (d.isPast ? " disabled" : "") + (state.date === d.iso ? " selected" : "") + (d.isToday ? " today" : "")}
            onClick={() => !d.isPast && set({ date: d.iso, time: null })}
          >
            <div>{d.date}</div>
            <div className="dlbl">{d.month}</div>
          </div>
        ))}
      </div>

      {state.date && (
        <>
          <div className="divider">— time —</div>
          <div className="slots">
            {slots.map(s => (
              <div
                key={s.t}
                className={"slot" + (s.taken ? " disabled" : "") + (state.time === s.t ? " selected" : "")}
                onClick={() => !s.taken && set({ time: s.t })}
              >
                {window.formatTime(s.t)}
              </div>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function StepDetails({ state, set }) {
  const toggle = (key, val) => {
    const cur = state[key] || [];
    set({ [key]: cur.includes(val) ? cur.filter(x => x !== val) : [...cur, val] });
  };
  return (
    <div className="book-step">
      <h3>Your details</h3>
      <p className="sub">Pre-visit intake — your therapist will see this before you arrive. We do not share with anyone else.</p>

      <div className="field-group">
        <div className="field"><label>First name</label><input value={state.firstName||""} onChange={e=>set({firstName:e.target.value})} placeholder="Sothea" /></div>
        <div className="field"><label>Last name</label><input value={state.lastName||""} onChange={e=>set({lastName:e.target.value})} placeholder="Chan" /></div>
        <div className="field"><label>Email</label><input type="email" value={state.email||""} onChange={e=>set({email:e.target.value})} placeholder="you@example.com" /></div>
        <div className="field"><label>Phone</label><input value={state.phone||""} onChange={e=>set({phone:e.target.value})} placeholder="+855 12 345 678" /></div>
      </div>

      <div className="field full" style={{ marginBottom: 20 }}>
        <label>Preferred language with therapist</label>
        <div className="tag-row">
          {window.NIK_INTAKE_TAGS.language.map(l => (
            <div key={l} className={"tag" + (state.language === l ? " on" : "")} onClick={() => set({ language: l })}>{l}</div>
          ))}
        </div>
      </div>

      <div className="field full" style={{ marginBottom: 20 }}>
        <label>Pressure</label>
        <div className="tag-row">
          {window.NIK_INTAKE_TAGS.pressure.map(p => (
            <div key={p} className={"tag" + (state.pressure === p ? " on" : "")} onClick={() => set({ pressure: p })}>{p}</div>
          ))}
        </div>
      </div>

      <div className="field full" style={{ marginBottom: 20 }}>
        <label>Areas to focus</label>
        <div className="tag-row">
          {window.NIK_INTAKE_TAGS.focus.map(f => (
            <div key={f} className={"tag" + ((state.focus||[]).includes(f) ? " on" : "")} onClick={() => toggle("focus", f)}>{f}</div>
          ))}
        </div>
      </div>

      <div className="field full" style={{ marginBottom: 20 }}>
        <label>Areas to avoid</label>
        <div className="tag-row">
          {window.NIK_INTAKE_TAGS.avoid.map(f => (
            <div key={f} className={"tag" + ((state.avoid||[]).includes(f) ? " on" : "")} onClick={() => toggle("avoid", f)}>{f}</div>
          ))}
        </div>
      </div>

      <div className="field full">
        <label>Allergies, injuries, anything else we should know</label>
        <textarea value={state.notes||""} onChange={e=>set({notes:e.target.value})} placeholder="Optional" />
      </div>

      <div className="field full" style={{ marginTop: 20 }}>
        <label style={{ display: "flex", alignItems: "center", gap: 12, cursor: "pointer", textTransform: "none", letterSpacing: 0, fontFamily: "var(--font-body)", fontSize: 14, color: "var(--ink-soft)" }}>
          <input
            type="checkbox"
            checked={!!state.addOnsen}
            onChange={e => set({ addOnsen: e.target.checked })}
            style={{ width: 16, height: 16, accentColor: "var(--brand-red)" }}
          />
          Add 90-minute onsen access for $28 — recommended before your treatment
        </label>
      </div>
    </div>
  );
}

function StepPay({ state, set }) {
  const svc = window.NIK_SERVICES.find(x => x.id === state.serviceId);
  const total = (svc?.pricing?.[state.duration] || 0) + (state.addOnsen ? 28 : 0);
  const method = state.payMethod || "redbox";
  const setMethod = (m) => set({ payMethod: m });
  return (
    <div className="book-step">
      <h3>Payment</h3>
      <p className="sub">Choose how you'd like to pay. All methods are confirmed before your therapist is assigned.</p>

      <div className={"pay-card redbox" + (method === "redbox" ? " selected" : "")} onClick={() => setMethod("redbox")}>
        <div className="pay-mark">R</div>
        <div className="pay-info">
          <div className="pay-name">Redbox</div>
          <div className="pay-desc">Pay via Nik Onsen's Redbox menu — accepts ABA, Wing, AcledaXP, and Truemoney. You'll be taken to a secure Redbox page and returned here once paid.</div>
          <div className="pay-meta">Most common · Khmer Riel or USD</div>
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.15em", color: "var(--stone)", textTransform: "uppercase" }}>${total}</div>
      </div>

      <div className={"pay-card khqr" + (method === "khqr" ? " selected" : "")} onClick={() => setMethod("khqr")}>
        <div className="pay-mark">QR</div>
        <div className="pay-info">
          <div className="pay-name">KHQR — Bakong</div>
          <div className="pay-desc">Scan a single QR with any Cambodian banking app. Coming soon — currently in merchant onboarding.</div>
          <div className="pay-meta" style={{ color: "var(--brand-red)" }}>Phase 2 · Available July 2026</div>
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.15em", color: "var(--stone-light)", textTransform: "uppercase" }}>—</div>
      </div>

      <div className={"pay-card onsite" + (method === "onsite" ? " selected" : "")} onClick={() => setMethod("onsite")}>
        <div className="pay-mark">＄</div>
        <div className="pay-info">
          <div className="pay-name">Pay on arrival</div>
          <div className="pay-desc">Reserve now, settle at the front desk. Cash (USD or KHR) or any local card. Booking held until 15 min after your appointment time.</div>
          <div className="pay-meta">No deposit required</div>
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.15em", color: "var(--stone)", textTransform: "uppercase" }}>${total}</div>
      </div>

      {method === "redbox" && (
        <div className="pay-handoff">
          <div className="h-text">
            <strong>You'll continue on Redbox</strong>
            We'll bring you back to confirm once payment clears. Your booking is held for 10 minutes.
          </div>
          <svg width="20" height="14" viewBox="0 0 14 10" fill="none"><path d="M1 5h12m0 0L9 1m4 4L9 9" stroke="currentColor" strokeWidth="1.4" /></svg>
        </div>
      )}
    </div>
  );
}

function StepConfirm({ state }) {
  const svc = window.NIK_SERVICES.find(x => x.id === state.serviceId);
  const total = (svc?.pricing?.[state.duration] || 0) + (state.addOnsen ? 28 : 0);
  const dt = state.date ? new Date(state.date + "T00:00:00").toLocaleDateString("en", { weekday: "long", month: "long", day: "numeric" }) : "";
  return (
    <div className="book-step confirm">
      <div className="stamp-big">
        <img src="assets/logo.jpg" alt="Nik Onsen" />
      </div>
      <h3 className="serif">Booking received</h3>
      <p className="lede">A confirmation has been sent to <strong>{state.email}</strong>. Please arrive 15 minutes before your appointment to change.</p>

      <div className="confirm-card">
        <div className="row"><span className="k">Reference</span><span className="v">NIK-{Math.floor(Math.random()*9000+1000)}</span></div>
        <div className="row"><span className="k">Service</span><span className="v">{svc?.name}</span></div>
        <div className="row"><span className="k">Date</span><span className="v">{dt}</span></div>
        <div className="row"><span className="k">Time</span><span className="v">{state.time ? window.formatTime(state.time) : ""}</span></div>
        <div className="row"><span className="k">Duration</span><span className="v">{state.duration} min{state.addOnsen ? " + onsen" : ""}</span></div>
        <div className="row"><span className="k">Total</span><span className="v">${total}</span></div>
      </div>

      <p style={{ marginTop: 32, fontSize: 12, fontFamily: "var(--font-mono)", letterSpacing: "0.15em", color: "var(--stone)", textTransform: "uppercase" }}>
        #18, ST 566 · BOENG KAK 2 · TUOL KOUK
      </p>
    </div>
  );
}

function BookingDrawer({ open, onClose, prefilledServiceId }) {
  const [step, setStep] = useState(0);
  const [state, setState] = useState({ serviceId: null, payMethod: "redbox" });
  const set = (patch) => setState(s => ({ ...s, ...patch }));

  useEffect(() => {
    if (open && prefilledServiceId && !state.serviceId) {
      const svc = window.NIK_SERVICES.find(s => s.id === prefilledServiceId);
      if (svc) setState(s => ({ ...s, serviceId: prefilledServiceId, duration: svc.duration }));
    }
  }, [open, prefilledServiceId]);

  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const close = () => {
    onClose();
    // reset after exit anim
    setTimeout(() => { setStep(0); setState({ serviceId: null, payMethod: "redbox" }); }, 500);
  };

  const canAdvance = (() => {
    if (step === 0) return state.serviceId && state.duration;
    if (step === 1) return state.date && state.time;
    if (step === 2) return state.firstName && state.lastName && state.email && state.phone;
    if (step === 3) return (state.payMethod || "redbox") !== "khqr";
    return false;
  })();

  const svc = state.serviceId ? window.NIK_SERVICES.find(x => x.id === state.serviceId) : null;
  const total = svc ? (svc.pricing?.[state.duration] || svc.price) + (state.addOnsen ? 28 : 0) : 0;

  return (
    <div className={"book-overlay" + (open ? " open" : "")} onClick={(e) => { if (e.target.classList.contains("book-overlay")) close(); }}>
      <div className="book-drawer">
        <div className="book-head">
          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.25em", color: "var(--stone)", textTransform: "uppercase", marginBottom: 4 }}>Reservation</div>
            <div className="title">{step < 3 ? "Book your visit" : "御予約済み"}</div>
          </div>
          <button className="close" onClick={close} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="1.4" /></svg>
          </button>
        </div>
        <StepDots step={step} />
        <div className="book-body">
          {step === 0 && <StepService state={state} set={set} />}
          {step === 1 && <StepWhen state={state} set={set} />}
          {step === 2 && <StepDetails state={state} set={set} />}
          {step === 3 && <StepPay state={state} set={set} />}
          {step === 4 && <StepConfirm state={state} />}

          {step < 4 && (
            <div className="book-foot">
              <div className="book-summary">
                {svc ? <>
                  <span>{svc.name} · {state.duration}min{state.addOnsen ? " + onsen" : ""}</span>
                  <strong>${total}</strong>
                </> : <span style={{ color: "var(--stone)" }}>Choose a service to begin</span>}
              </div>
              <div style={{ display: "flex", gap: 12 }}>
                {step > 0 && <button className="btn btn-ghost" onClick={() => setStep(step - 1)}>Back</button>}
                <button
                  className="btn btn-primary"
                  disabled={!canAdvance}
                  style={{ opacity: canAdvance ? 1 : 0.4, cursor: canAdvance ? "pointer" : "not-allowed" }}
                  onClick={() => canAdvance && setStep(step + 1)}
                >
                  {step === 2 ? "Continue to payment" : step === 3 ? ((state.payMethod || "redbox") === "redbox" ? "Continue on Redbox" : "Confirm reservation") : "Continue"}
                  <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 5h12m0 0L9 1m4 4L9 9" stroke="currentColor" strokeWidth="1.4" /></svg>
                </button>
              </div>
            </div>
          )}

          {step === 4 && (
            <div style={{ textAlign: "center", marginTop: 32 }}>
              <button className="btn btn-ghost" onClick={close}>Close</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.BookingDrawer = BookingDrawer;
