/* global React, TREATMENTS, CATEGORIES, CLINIC, IconClose, IconArrow, IconArrowLeft, IconCheck, IconSparkle, IconAligner, IconImplant, IconLeaf, IconTooth, IconCalendar */

const TX_GROUPS = [
  { id: "Cosmetic",     icon: IconSparkle, label: "Cosmetic", desc: "Veneers, whitening, smile makeover" },
  { id: "Orthodontics", icon: IconAligner, label: "Orthodontics", desc: "Invisalign, braces, retainers" },
  { id: "Implants",     icon: IconImplant, label: "Implants & Restoration", desc: "Implants, crowns, dentures" },
  { id: "General",      icon: IconLeaf,    label: "General & Preventive", desc: "Check-up, cleaning, root canal" }
];

// generate a synthetic next-7-days set, excluding Friday (likely closed)
function nextDays(n = 7) {
  const out = [];
  const today = new Date(2026, 4, 22); // anchored to keep prototype deterministic
  let cursor = new Date(today);
  while (out.length < n) {
    cursor.setDate(cursor.getDate() + 1);
    if (cursor.getDay() === 5) continue; // skip Friday
    out.push(new Date(cursor));
  }
  return out;
}
const DAYS = nextDays(5);
const WEEKDAY = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
const MONTH = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
const TIME_SLOTS = ["10:00","10:30","11:00","11:30","12:00","12:30","14:30","15:00","15:30","16:00","16:30","17:00","17:30","18:00"];
// pretend some are taken
const TAKEN = new Set(["11:00","12:30","15:30","18:00"]);

function BookingModal({ open, onClose, prefillTreatment }) {
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({
    category: "Cosmetic", treatment: null, day: 1, time: "15:00",
    name: "", phone: "", email: "", message: "", consent: false
  });

  // Sync the category when a treatment is prefilled
  React.useEffect(() => {
    if (open && prefillTreatment) {
      const tx = TREATMENTS.find(t => t.id === prefillTreatment);
      if (tx) setForm(f => ({ ...f, category: tx.cat, treatment: tx.id }));
    }
  }, [open, prefillTreatment]);

  React.useEffect(() => {
    if (!open) {
      // tiny delay so the close animation finishes before resetting
      const t = setTimeout(() => { setStep(0); }, 240);
      return () => clearTimeout(t);
    }
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const set = (patch) => setForm(f => ({ ...f, ...patch }));

  const steps = [
    { id: 0, t: "What brings you in?", sub: "Pick a category — we'll match it to the right dentist." },
    { id: 1, t: "Choose a date & time", sub: "Provisional slots; the clinic will confirm by phone." },
    { id: 2, t: "Your details", sub: "We only need a phone number to confirm — the rest is optional." },
    { id: 3, t: "Confirm your booking", sub: "Last look. We’ll text and call to confirm." }
  ];

  const filteredTx = TREATMENTS.filter(t => t.cat === form.category);

  const canAdvance = (() => {
    if (step === 0) return !!form.category;
    if (step === 1) return form.day !== null && form.time;
    if (step === 2) return form.name.trim().length > 1 && /^[+\d\s()-]{7,}$/.test(form.phone) && form.consent;
    return true;
  })();

  const submit = () => setStep(4);

  return (
    <div className={"modal-overlay" + (open ? " is-open" : "")} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} role="dialog" aria-modal="true">

        <aside className="modal__aside">
          <div>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '.18em', textTransform: 'uppercase', opacity: .7 }}>Book a Consultation</div>
            <div className="serif" style={{ fontSize: 26, fontWeight: 600, marginTop: 8, lineHeight: 1.1 }}>
              From AED 200 — confirmed in under a minute.
            </div>
          </div>

          <div className="modal__steps">
            {steps.map((s, i) => (
              <div key={s.id} className={"step" + (i === step ? " is-active" : "") + (i < step ? " is-done" : "")}>
                <span className="n">{i < step ? <IconCheck size={14} /> : i + 1}</span>
                <span className="t">{s.t}</span>
              </div>
            ))}
          </div>

          <div className="modal__quote">
            One of the best dental clinics in Dubai. Especially Dr Ammar — makes you feel as if you know him for a long time.
            <span className="by">— Verified patient, Doctify</span>
          </div>
        </aside>

        <main className="modal__main">
          <div className="modal__head">
            <span className="num">Step {Math.min(step, 3) + 1} of 4</span>
            <button className="close" onClick={onClose} aria-label="Close"><IconClose /></button>
          </div>

          {step <= 3 && (
            <React.Fragment>
              <h3 className="modal__title">{steps[step].t}</h3>
              <p className="modal__sub">{steps[step].sub}</p>
            </React.Fragment>
          )}

          {/* STEP 0 — category & treatment */}
          {step === 0 && (
            <div>
              <div className="opt-grid">
                {TX_GROUPS.map(g => {
                  const Icon = g.icon;
                  return (
                    <button
                      key={g.id}
                      className={"opt" + (form.category === g.id ? " is-selected" : "")}
                      onClick={() => set({ category: g.id, treatment: null })}
                    >
                      <span className="ic"><Icon size={20} /></span>
                      <span>
                        <div className="t">{g.label}</div>
                        <div className="d">{g.desc}</div>
                      </span>
                    </button>
                  );
                })}
              </div>

              <div className="modal__field">
                <label>Specific treatment <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--slate-soft)', fontFamily: 'var(--sans)' }}>· optional</span></label>
                <select
                  value={form.treatment || ""}
                  onChange={e => set({ treatment: e.target.value || null })}
                >
                  <option value="">Not sure yet — recommend for me</option>
                  {filteredTx.map(t => (
                    <option key={t.id} value={t.id}>{t.title}</option>
                  ))}
                </select>
              </div>
            </div>
          )}

          {/* STEP 1 — calendar */}
          {step === 1 && (
            <div>
              <div className="daygrid">
                {DAYS.map((d, i) => (
                  <button
                    key={i}
                    className={form.day === i ? "is-selected" : ""}
                    onClick={() => set({ day: i })}
                  >
                    <span className="w">{WEEKDAY[d.getDay()]}</span>
                    <span className="d">{d.getDate()}</span>
                    <span className="m">{MONTH[d.getMonth()]}</span>
                  </button>
                ))}
              </div>

              <div className="mono" style={{ fontSize: 10, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--slate)', marginBottom: 10 }}>
                Available times — {WEEKDAY[DAYS[form.day].getDay()]} {DAYS[form.day].getDate()} {MONTH[DAYS[form.day].getMonth()]}
              </div>
              <div className="timegrid">
                {TIME_SLOTS.map(t => {
                  const taken = TAKEN.has(t);
                  return (
                    <button
                      key={t}
                      disabled={taken}
                      className={(taken ? "is-disabled " : "") + (form.time === t && !taken ? "is-selected" : "")}
                      onClick={() => !taken && set({ time: t })}
                    >{t}</button>
                  );
                })}
              </div>

              <div style={{ marginTop: 18, padding: '12px 16px', background: 'rgba(200,169,106,.14)', borderRadius: 10, fontSize: 13, color: '#6F5520' }}>
                <strong>Heads up:</strong> these are placeholder slots until the clinic confirms its working calendar — the team will phone you within 1 working day to lock the time.
              </div>
            </div>
          )}

          {/* STEP 2 — details */}
          {step === 2 && (
            <div>
              <div className="modal__row">
                <div className="modal__field">
                  <label>Full name</label>
                  <input type="text" value={form.name} onChange={e => set({ name: e.target.value })} placeholder="e.g. Sarah Ahmadi" />
                </div>
                <div className="modal__field">
                  <label>Mobile number</label>
                  <input type="tel" value={form.phone} onChange={e => set({ phone: e.target.value })} placeholder="+971 50 000 0000" />
                </div>
              </div>
              <div className="modal__field">
                <label>Email <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--slate-soft)', fontFamily: 'var(--sans)' }}>· optional</span></label>
                <input type="email" value={form.email} onChange={e => set({ email: e.target.value })} placeholder="you@example.com" />
              </div>
              <div className="modal__field">
                <label>Anything we should know? <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--slate-soft)', fontFamily: 'var(--sans)' }}>· optional</span></label>
                <textarea rows={3} value={form.message} onChange={e => set({ message: e.target.value })} placeholder="A recent issue, a preferred dentist, insurance details…" />
              </div>
              <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13, color: 'var(--slate)', cursor: 'pointer' }}>
                <input type="checkbox" checked={form.consent} onChange={e => set({ consent: e.target.checked })} style={{ marginTop: 3 }} />
                <span>I agree that Empire Dental Clinic may contact me by phone, SMS or WhatsApp to confirm this booking. We never share patient data.</span>
              </label>
            </div>
          )}

          {/* STEP 3 — confirm */}
          {step === 3 && (
            <div className="confirm">
              <div className="confirm__summary">
                <div className="r"><div className="l">Treatment</div><div className="v">
                  {form.category}{form.treatment ? ` · ${TREATMENTS.find(t => t.id === form.treatment)?.title}` : " · open consultation"}
                </div></div>
                <div className="r"><div className="l">When</div><div className="v">
                  {WEEKDAY[DAYS[form.day].getDay()]} {DAYS[form.day].getDate()} {MONTH[DAYS[form.day].getMonth()]} · {form.time}
                </div></div>
                <div className="r"><div className="l">Patient</div><div className="v">{form.name || "—"} · {form.phone || "—"}</div></div>
                {form.email && <div className="r"><div className="l">Email</div><div className="v">{form.email}</div></div>}
                <div className="r"><div className="l">Clinic</div><div className="v">Empire Heights, Tower B, Office 901 · Business Bay</div></div>
                <div className="r"><div className="l">Consultation</div><div className="v">From AED 200 · pay at the clinic</div></div>
              </div>
            </div>
          )}

          {/* STEP 4 — booked */}
          {step === 4 && (
            <div className="confirm" style={{ paddingTop: 12 }}>
              <div className="confirm__check"><IconCheck size={28} /></div>
              <h3 className="modal__title" style={{ marginTop: 0 }}>You’re on the list.</h3>
              <p className="modal__sub" style={{ marginBottom: 14 }}>
                A member of the Empire team will call <strong>{form.phone}</strong> within one working day to confirm your <strong>{WEEKDAY[DAYS[form.day].getDay()]} {DAYS[form.day].getDate()} {MONTH[DAYS[form.day].getMonth()]} · {form.time}</strong> consultation.
              </p>
              <div className="confirm__summary">
                <div className="r"><div className="l">Reference</div><div className="v mono" style={{ fontFamily: 'var(--mono)', fontSize: 13 }}>EMP-{Date.now().toString().slice(-6)}</div></div>
                <div className="r"><div className="l">Phone</div><div className="v"><a href={CLINIC.phoneHref}>{CLINIC.phone}</a></div></div>
                <div className="r"><div className="l">Map</div><div className="v">Tower B, 9th floor · Empire Heights, Marasi Dr</div></div>
              </div>
              <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
                <button className="btn btn--ghost" onClick={onClose}>Close</button>
              </div>
            </div>
          )}

          {step <= 3 && (
            <div className="modal__foot">
              {step > 0 ? (
                <button className="btn btn--ghost btn--sm" onClick={() => setStep(s => s - 1)}>
                  <IconArrowLeft size={14} /> Back
                </button>
              ) : (
                <span className="modal__pill">No payment now · pay at the clinic</span>
              )}
              <span className="spacer" />
              {step < 3 ? (
                <button className="btn btn--primary" disabled={!canAdvance} onClick={() => setStep(s => s + 1)} style={{ opacity: canAdvance ? 1 : .45 }}>
                  Continue <IconArrow size={14} />
                </button>
              ) : (
                <button className="btn btn--gold" onClick={submit}>
                  Confirm booking <IconCheck size={14} />
                </button>
              )}
            </div>
          )}
        </main>
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
