// Booking modal — multi-step flow

const { useState } = React;

function BookingModal({ open, onClose }) {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    service: null,
    patientType: null,
    date: null,
    time: null,
    name: "", phone: "", email: "", notes: ""
  });

  if (!open) return null;

  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const close = () => { onClose(); setTimeout(() => { setStep(0); setData({ service:null, patientType:null, date:null, time:null, name:"", phone:"", email:"", notes:"" }); }, 250); };

  const services = [
    { id: "exam", ttl: "Comprehensive Eye Exam", sub: "30–45 min · Most common", price: "Bulk-billed (Medicare)" },
    { id: "child", ttl: "Children's Vision", sub: "Ages 3+ · 30 min", price: "Bulk-billed (Medicare)" },
    { id: "contact", ttl: "Contact Lens Fitting", sub: "45 min · Initial consult", price: "From $95" },
    { id: "specialty", ttl: "Specialty / Dry Eye", sub: "Myopia control, IPL, OCT", price: "From $120" },
    { id: "frames", ttl: "Frame Selection Only", sub: "30 min · Existing prescription", price: "No charge" },
    { id: "repair", ttl: "Repair / Adjustment", sub: "Walk-in or 15 min slot", price: "Free for our patients" }
  ];

  // generate next 14 weekdays
  const dates = [];
  const today = new Date();
  for (let i = 1; dates.length < 14; i++) {
    const d = new Date(today); d.setDate(today.getDate() + i);
    const dow = d.getDay();
    if (dow === 0) continue; // skip Sunday
    dates.push(d);
  }
  const dows = ["S","M","T","W","T","F","S"];
  const fmtDate = (d) => d ? d.toLocaleDateString("en-AU", { weekday:"long", day:"numeric", month:"long" }) : "";

  const times = ["9:00", "9:30", "10:00", "10:30", "11:00", "11:30", "1:30", "2:00", "2:30", "3:00", "3:30", "4:00", "4:30"];
  // pretend some are unavailable
  const unavailable = (d, t) => {
    if (!d) return true;
    const seed = (d.getDate() + times.indexOf(t)) % 5;
    return seed === 0;
  };

  const steps = ["Service", "Date", "Details", "Confirm"];
  const canNext = () => {
    if (step === 0) return data.service && data.patientType;
    if (step === 1) return data.date && data.time;
    if (step === 2) return data.name.trim() && data.phone.trim();
    return true;
  };

  return (
    <div className="modal-backdrop" onClick={(e) => { if (e.target === e.currentTarget) close(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        <header>
          <div>
            <div className="step">Step {Math.min(step+1,4)} of 4 · {steps[Math.min(step,3)]}</div>
            <h3>{step === 4 ? "Request received" : "Book an appointment"}</h3>
          </div>
          <button className="close-x" onClick={close} aria-label="Close">×</button>
        </header>

        <div className="body">
          {step === 0 && (
            <>
              <h4>What kind of appointment?</h4>
              <p className="help">We'll confirm by phone within one business day. New patients are very welcome.</p>
              <div className="option-grid">
                {services.map(s => (
                  <button key={s.id} className={"option" + (data.service===s.id ? " selected" : "")} onClick={() => set("service", s.id)}>
                    <div className="ttl">{s.ttl}</div>
                    <div className="sub">{s.sub}</div>
                    <div className="price">{s.price}</div>
                  </button>
                ))}
              </div>
              <h4 style={{ marginTop: 28 }}>Have you visited us before?</h4>
              <div className="option-grid">
                <button className={"option" + (data.patientType==="new" ? " selected" : "")} onClick={() => set("patientType","new")}>
                  <div className="ttl">New patient</div>
                  <div className="sub">First visit to Bill Cutler Optometrists</div>
                </button>
                <button className={"option" + (data.patientType==="returning" ? " selected" : "")} onClick={() => set("patientType","returning")}>
                  <div className="ttl">Returning patient</div>
                  <div className="sub">We have your records on file</div>
                </button>
              </div>
            </>
          )}

          {step === 1 && (
            <>
              <h4>Pick a day & time</h4>
              <p className="help">Showing the next two weeks. We'll confirm exact availability when we call.</p>
              <div className="date-grid">
                {dates.map((d, i) => (
                  <button key={i}
                    className={"date-cell" + (data.date && data.date.getTime()===d.getTime() ? " selected" : "")}
                    onClick={() => { set("date", d); set("time", null); }}>
                    <span className="dow">{dows[d.getDay()]}</span>
                    <span className="dnum">{d.getDate()}</span>
                    <span className="dow" style={{opacity:0.5,fontSize:9}}>{d.toLocaleDateString("en-AU",{month:"short"})}</span>
                  </button>
                ))}
              </div>
              {data.date && (
                <>
                  <div style={{ marginTop: 24, fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-muted)" }}>
                    {fmtDate(data.date)}
                  </div>
                  <div className="time-grid">
                    {times.map(t => {
                      const dis = unavailable(data.date, t);
                      return (
                        <button key={t} disabled={dis}
                          className={"time-cell" + (data.time===t ? " selected" : "")}
                          onClick={() => set("time", t)}>{t}</button>
                      );
                    })}
                  </div>
                </>
              )}
            </>
          )}

          {step === 2 && (
            <>
              <h4>Your details</h4>
              <p className="help">We only need the basics. We'll call to confirm and answer any questions.</p>
              <div className="contact-form">
                <div>
                  <label>Full name *</label>
                  <input value={data.name} onChange={e => set("name", e.target.value)} placeholder="Jane Smith" />
                </div>
                <div>
                  <label>Phone *</label>
                  <input value={data.phone} onChange={e => set("phone", e.target.value)} placeholder="0412 345 678" />
                </div>
                <div className="full">
                  <label>Email</label>
                  <input value={data.email} onChange={e => set("email", e.target.value)} placeholder="jane@example.com" />
                </div>
                <div className="full">
                  <label>Anything we should know?</label>
                  <textarea value={data.notes} onChange={e => set("notes", e.target.value)} placeholder="Health fund, accessibility needs, current concerns…" />
                </div>
              </div>
            </>
          )}

          {step === 3 && (
            <>
              <h4>Review your request</h4>
              <p className="help">We'll confirm by phone within one business day. Nothing's locked in yet.</p>
              <div>
                <div className="confirm-row"><div className="k">Appointment</div><div className="v">{services.find(s=>s.id===data.service)?.ttl}</div></div>
                <div className="confirm-row"><div className="k">Patient</div><div className="v">{data.patientType==="new" ? "New patient" : "Returning patient"}</div></div>
                <div className="confirm-row"><div className="k">When</div><div className="v">{fmtDate(data.date)} at {data.time}</div></div>
                <div className="confirm-row"><div className="k">Name</div><div className="v">{data.name}</div></div>
                <div className="confirm-row"><div className="k">Phone</div><div className="v">{data.phone}</div></div>
                {data.email && <div className="confirm-row"><div className="k">Email</div><div className="v">{data.email}</div></div>}
                {data.notes && <div className="confirm-row"><div className="k">Notes</div><div className="v">{data.notes}</div></div>}
              </div>
            </>
          )}

          {step === 4 && (
            <div className="success">
              <div className="check">✓</div>
              <h4>Thank you, {data.name.split(" ")[0]}.</h4>
              <p>We've received your request and will call you on <strong>{data.phone}</strong> within one business day to confirm your appointment on {fmtDate(data.date)} at {data.time}.</p>
            </div>
          )}
        </div>

        {step < 4 && (
          <footer>
            <div className="progress">
              {[0,1,2,3].map(i => (
                <div key={i} className={"pip " + (i < step ? "done" : i === step ? "cur" : "")}></div>
              ))}
            </div>
            <div style={{ display:"flex", gap:10 }}>
              {step > 0 && <button className="btn ghost" onClick={() => setStep(step-1)}>Back</button>}
              {step < 3 && <button className="btn" disabled={!canNext()} style={{ opacity: canNext() ? 1 : 0.4 }} onClick={() => canNext() && setStep(step+1)}>Continue <span className="arrow">→</span></button>}
              {step === 3 && <button className="btn" onClick={() => setStep(4)}>Submit request <span className="arrow">→</span></button>}
            </div>
          </footer>
        )}
        {step === 4 && (
          <footer>
            <div></div>
            <button className="btn" onClick={close}>Close</button>
          </footer>
        )}
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
