// Multi-Dept Scheduler wizard, Detail drawers, Modals

function parseApptTime(str) {
  const m = str.match(/(\d+):(\d+)\s*(AM|PM)/i);
  if (!m) return 0;
  let h = parseInt(m[1]), mn = parseInt(m[2]);
  const ap = m[3].toUpperCase();
  if (ap === 'PM' && h !== 12) h += 12;
  if (ap === 'AM' && h === 12) h = 0;
  return h * 60 + mn;
}

const MultiDeptWizard = ({ onClose, onComplete }) => {
  const { PATIENTS, DEPARTMENTS, DOCTORS, ROOMS } = window.MOCK;
  const [step, setStep] = useState(0);
  const [patientId, setPatientId] = useState('p5');
  const [services, setServices] = useState([
    { id: 's1', dept: 'lab', type: 'Lab — CBC + metabolic panel', dur: 15 },
    { id: 's2', dept: 'radio', type: 'MRI lumbar spine', dur: 60 },
    { id: 's3', dept: 'ortho', type: 'Orthopedic consult', dur: 30 },
  ]);
  const [confirmed, setConfirmed] = useState(false);

  const patient = PATIENTS.find(p => p.id === patientId);
  const itinerary = [
    { step: 1, time: '8:30 AM', end: '8:45 AM', service: services[0], room: 'Phlebotomy A', provider: 'Dr. Vassilakis', dep: null },
    { step: 2, time: '9:00 AM', end: '10:00 AM', service: services[1], room: 'MRI Suite A', provider: 'Dr. Chen', dep: 'Waits for lab draw' },
    { step: 3, time: '10:30 AM', end: '11:00 AM', service: services[2], room: 'Ortho Clinic 1', provider: 'Dr. Haidari', dep: 'Waits for MRI read' },
  ];

  return (
    <div className="modal-backdrop open" onClick={onClose}>
      <div className="modal modal-wide" onClick={e => e.stopPropagation()} style={{ width: 880 }}>
        <div className="modal-head">
          <div className="row-space">
            <div>
              <div className="serif" style={{ fontSize: 20, fontWeight: 500 }}>Multi-department scheduler</div>
              <div className="muted" style={{ fontSize: 13 }}>Sequence appointments across services with automatic dependency resolution.</div>
            </div>
            <button className="close-btn" onClick={onClose} style={{ position: 'static' }}><Icon name="x" size={14} /></button>
          </div>
        </div>
        <div className="wizard-steps">
          {['Patient', 'Services', 'Optimize', 'Confirm'].map((s, i) => (
            <div key={s} className={`wstep ${step === i ? 'active' : step > i ? 'done' : ''}`}>
              <div className="num">{step > i ? '✓' : i + 1}</div> {s}
            </div>
          ))}
        </div>
        <div className="modal-body" style={{ minHeight: 320 }}>
          {step === 0 && (
            <div>
              <div className="label">Select patient</div>
              <div className="search-box" style={{ width: '100%', marginBottom: 14 }}>
                <Icon name="search" size={14} />
                <input placeholder="Search by name or MRN…" defaultValue={patient.name} />
              </div>
              <div className="stack">
                {PATIENTS.slice(0, 5).map(p => (
                  <div key={p.id}
                    onClick={() => setPatientId(p.id)}
                    style={{ padding: 12, border: `1px solid ${patientId === p.id ? 'var(--accent)' : 'var(--border)'}`, background: patientId === p.id ? 'var(--accent-soft)' : 'var(--bg-elev)', borderRadius: 8, display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer' }}>
                    <Avatar name={p.name} size={32} />
                    <div style={{ flex: 1 }}>
                      <div className="prow-name">{p.name}</div>
                      <div className="prow-sub">{p.mrn} · {p.age}{p.sex} · {p.primaryCondition}</div>
                    </div>
                    <PriorityPill priority={p.priority} />
                  </div>
                ))}
              </div>
            </div>
          )}
          {step === 1 && (
            <div>
              <div className="label">Required services</div>
              <div className="muted" style={{ fontSize: 12, marginBottom: 12 }}>Add all needed services; dependencies are detected automatically.</div>
              <div className="stack">
                {services.map((s, i) => (
                  <div key={s.id} style={{ padding: 12, border: '1px solid var(--border)', borderRadius: 8, display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{ width: 26, height: 26, borderRadius: 99, background: 'var(--accent-soft)', color: 'var(--accent-text)', display: 'grid', placeItems: 'center', fontWeight: 600, fontSize: 12 }}>{i + 1}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 500, fontSize: 13 }}>{s.type}</div>
                      <div className="muted" style={{ fontSize: 12 }}>{DEPARTMENTS.find(d => d.id === s.dept)?.name} · {s.dur}m</div>
                    </div>
                    <button className="btn sm ghost" onClick={() => setServices(services.filter(x => x.id !== s.id))}><Icon name="x" size={12} /></button>
                  </div>
                ))}
              </div>
              <button className="btn" style={{ marginTop: 12 }} onClick={() => setServices([...services, { id: `s${Date.now()}`, dept: 'gen', type: 'Follow-up consult', dur: 30 }])}>
                <Icon name="plus" size={12} /> Add service
              </button>
            </div>
          )}
          {step === 2 && (
            <div>
              <div className="row-space" style={{ marginBottom: 14 }}>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>Optimized itinerary for {patient.name}</div>
                  <div className="muted" style={{ fontSize: 12 }}>Dependencies respected · Total in-building time: 2h 30m · Idle gaps: 30m</div>
                </div>
                <button className="btn sm"><Icon name="wand" size={12} /> Re-optimize</button>
              </div>
              <div>
                {itinerary.map((it, i) => (
                  <div key={i} className={`timeline-step ${i === 0 ? 'active' : ''}`}>
                    <div className="timeline-num">{it.step}</div>
                    <div style={{ flex: 1 }}>
                      <div className="row-space">
                        <div>
                          <div style={{ fontWeight: 500, fontSize: 13 }}>{it.service.type}</div>
                          <div className="muted" style={{ fontSize: 12 }}>{it.provider} · {it.room}</div>
                        </div>
                        <div style={{ textAlign: 'right' }}>
                          <div className="mono" style={{ fontSize: 12 }}>{it.time} – {it.end}</div>
                          {it.dep && <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>↳ {it.dep}</div>}
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 14, padding: 12, background: 'var(--accent-soft)', borderRadius: 8, color: 'var(--accent-text)', fontSize: 12, display: 'flex', gap: 10 }}>
                <Icon name="zap" size={14} />
                <div>The system sequenced 3 services across 3 departments in a single 2.5 hr window — saving approximately 2 patient trips.</div>
              </div>
            </div>
          )}
          {step === 3 && !confirmed && (
            <div style={{ textAlign: 'center', padding: '30px 20px' }}>
              <div style={{ width: 56, height: 56, borderRadius: 99, background: 'var(--accent-soft)', color: 'var(--accent-text)', display: 'grid', placeItems: 'center', margin: '0 auto 14px' }}>
                <Icon name="check" size={24} />
              </div>
              <div className="serif" style={{ fontSize: 22, fontWeight: 500 }}>Ready to confirm</div>
              <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>3 appointments will be created for {patient.name}. Patient will receive full itinerary via SMS and email.</div>
            </div>
          )}
          {step === 3 && confirmed && (
            <div style={{ textAlign: 'center', padding: '40px 20px' }}>
              <div style={{ width: 64, height: 64, borderRadius: 99, background: 'var(--ok-soft)', color: 'var(--ok-text)', display: 'grid', placeItems: 'center', margin: '0 auto 14px' }}>
                <Icon name="check" size={28} />
              </div>
              <div className="serif" style={{ fontSize: 24, fontWeight: 500 }}>Itinerary booked</div>
              <div className="muted" style={{ fontSize: 13, marginTop: 6 }}>3 appointments created · Confirmation sent to {patient.name}</div>
            </div>
          )}
        </div>
        <div className="modal-foot">
          {step > 0 && !confirmed && <button className="btn" onClick={() => setStep(step - 1)}><Icon name="chevronLeft" size={12} /> Back</button>}
          <div style={{ flex: 1 }} />
          {step < 3 && <button className="btn accent" onClick={() => setStep(step + 1)}>Next <Icon name="chevronRight" size={12} /></button>}
          {step === 3 && !confirmed && <button className="btn accent" onClick={() => {
            setConfirmed(true);
            // Build lightweight appointment objects from the itinerary steps
            const PROVIDER_DOC = { 'Dr. Vassilakis': 'd5', 'Dr. Chen': 'd4', 'Dr. Haidari': 'd6' };
            const PROVIDER_ROOM = { 'Dr. Vassilakis': 'r8', 'Dr. Chen': 'r4', 'Dr. Haidari': 'r10' };
            const chainId = `chain-w${Date.now()}`;
            const appts = itinerary.map((it, i) => {
              const start = parseApptTime(it.time), end = parseApptTime(it.end);
              return {
                id: `w${Date.now()}-${i}`, patientId: patient.id,
                typeId: it.service.dept === 'lab' ? 'lab' : it.service.dept === 'radio' ? 'mri' : 'consult',
                docId: PROVIDER_DOC[it.provider] || 'd6',
                roomId: PROVIDER_ROOM[it.provider] || 'r10',
                dayId: 'wed', dept: it.service.dept,
                start, end, startLabel: it.time, endLabel: it.end,
                duration: end - start, typeLabel: it.service.type,
                status: 'scheduled', notes: '',
                chain: { id: chainId, step: i + 1, of: itinerary.length },
              };
            });
            const serviceChain = services.map(s => s.type.split(/[\s—]/)[0]).join(' → ');
            setTimeout(() => {
              onComplete({ patient, services, serviceChain, appointments: appts, dayId: 'wed', date: 'Wed · Apr 15' });
              onClose();
            }, 1400);
          }}>Confirm & book <Icon name="check" size={12} /></button>}
          {step === 3 && confirmed && <button className="btn" onClick={onClose}>Close</button>}
        </div>
      </div>
    </div>
  );
};

const ApptDrawer = ({ appt, onClose }) => {
  if (!appt) return null;
  const { PATIENTS, DOCTORS, ROOMS, DEPARTMENTS, DAYS } = window.MOCK;
  const p = PATIENTS.find(x => x.id === appt.patientId);
  const d = DOCTORS.find(x => x.id === appt.docId);
  const r = ROOMS.find(x => x.id === appt.roomId);
  const dept = DEPARTMENTS.find(x => x.id === appt.dept);
  const day = DAYS.find(x => x.id === appt.dayId);

  return (
    <>
      <div className={`drawer-backdrop ${appt ? 'open' : ''}`} onClick={onClose} />
      <div className={`drawer ${appt ? 'open' : ''}`}>
        <div className="drawer-head" style={{ position: 'relative' }}>
          <button className="close-btn" onClick={onClose}><Icon name="x" size={14} /></button>
          <div className="row" style={{ gap: 8, marginBottom: 10 }}>
            <Pill><span style={{ width: 6, height: 6, borderRadius: 99, background: dept.color, display: 'inline-block' }} /> {dept.name}</Pill>
            <StatusPill status={appt.status} />
            {appt.chain && <Pill tone="accent">Chain {appt.chain.step}/{appt.chain.of}</Pill>}
          </div>
          <div className="serif" style={{ fontSize: 22, fontWeight: 500 }}>{appt.typeLabel}</div>
          <div className="muted" style={{ fontSize: 13, marginTop: 2 }}>{day.label} {day.date} · {appt.startLabel} – {appt.endLabel}</div>
        </div>
        <div className="drawer-body">
          <div className="card" style={{ marginBottom: 14 }}>
            <div className="card-body">
              <div className="row" style={{ gap: 12 }}>
                <Avatar name={p.name} size={42} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 15 }}>{p.name}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{p.mrn} · {p.age}{p.sex} · {p.insurance}</div>
                </div>
                <PriorityPill priority={p.priority} />
              </div>
              <div className="kv"><span className="k">Condition</span><span>{p.primaryCondition}</span></div>
              <div className="kv"><span className="k">Phone</span><span className="mono">{p.phone}</span></div>
              <div className="kv"><span className="k">No-show risk</span>
                <span>
                  <span className="mono" style={{ fontSize: 12 }}>{p.noShowRisk}%</span>
                  <Pill tone={p.noShowRisk > 60 ? 'err' : p.noShowRisk > 35 ? 'warn' : 'ok'} style={{ marginLeft: 8 }}>{p.noShowRisk > 60 ? 'High' : p.noShowRisk > 35 ? 'Medium' : 'Low'}</Pill>
                </span>
              </div>
            </div>
          </div>

          <div className="card" style={{ marginBottom: 14 }}>
            <div className="card-head"><div className="card-title">Appointment details</div></div>
            <div className="card-body">
              <div className="kv"><span className="k">Provider</span><span>{d.name} · {d.title}</span></div>
              <div className="kv"><span className="k">Room</span><span>{r.name}</span></div>
              <div className="kv"><span className="k">Duration</span><span className="mono">{appt.duration} min</span></div>
              <div className="kv"><span className="k">Appointment ID</span><span className="mono muted">{appt.id.toUpperCase()}</span></div>
            </div>
          </div>

          {appt.chain && (
            <div className="card" style={{ marginBottom: 14 }}>
              <div className="card-head"><div className="card-title">Dependency chain</div><div className="card-sub">Multi-dept itinerary</div></div>
              <div className="card-body">
                <div className="timeline-step done"><div className="timeline-num">1</div><div style={{ flex: 1, fontSize: 13 }}>Lab draw <div className="muted" style={{ fontSize: 11 }}>8:00 AM · Completed</div></div></div>
                <div className="timeline-step done"><div className="timeline-num">2</div><div style={{ flex: 1, fontSize: 13 }}>Imaging <div className="muted" style={{ fontSize: 11 }}>8:45 AM · Completed</div></div></div>
                <div className="timeline-step active"><div className="timeline-num">3</div><div style={{ flex: 1, fontSize: 13 }}>Consultation <div className="muted" style={{ fontSize: 11 }}>10:00 AM · Waiting on lab results (cleared)</div></div></div>
              </div>
            </div>
          )}

          <div className="card">
            <div className="card-head"><div className="card-title">Recent patient history</div></div>
            <div>
              {p.history.map((h, i) => (
                <div key={i} style={{ padding: '12px 18px', borderBottom: i < p.history.length - 1 ? '1px solid var(--border)' : 0 }}>
                  <div className="row-space">
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{h.type} · {h.provider}</div>
                    <div className="mono muted" style={{ fontSize: 11 }}>{h.date}</div>
                  </div>
                  <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>{h.note}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="drawer-foot">
          <button className="btn"><Icon name="phone" size={12} /> Call patient</button>
          <button className="btn"><Icon name="edit" size={12} /> Reschedule</button>
          <div style={{ flex: 1 }} />
          <button className="btn danger"><Icon name="trash" size={12} /> Cancel</button>
          <button className="btn primary"><Icon name="check" size={12} /> Check in</button>
        </div>
      </div>
    </>
  );
};

const PatientDrawer = ({ patient, onClose, onOpenAppt }) => {
  if (!patient) return null;
  const { APPOINTMENTS, DEPARTMENTS, DOCTORS, DAYS } = window.MOCK;
  const allAppts = APPOINTMENTS.filter(a => a.patientId === patient.id);
  return (
    <>
      <div className={`drawer-backdrop ${patient ? 'open' : ''}`} onClick={onClose} />
      <div className={`drawer ${patient ? 'open' : ''}`}>
        <div className="drawer-head" style={{ position: 'relative' }}>
          <button className="close-btn" onClick={onClose}><Icon name="x" size={14} /></button>
          <div className="row" style={{ gap: 14 }}>
            <Avatar name={patient.name} size={52} />
            <div>
              <div className="serif" style={{ fontSize: 22, fontWeight: 500 }}>{patient.name}</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{patient.mrn} · {patient.age}{patient.sex} · {patient.insurance}</div>
              <div style={{ marginTop: 8 }}>
                <PriorityPill priority={patient.priority} />
                {patient.tags.map(t => <Pill key={t} tone={t === 'Urgent' ? 'err' : t === 'High no-show' ? 'warn' : 'default'} style={{ marginLeft: 4 }}>{t}</Pill>)}
              </div>
            </div>
          </div>
        </div>
        <div className="drawer-body">
          <div className="grid-2" style={{ marginBottom: 14 }}>
            <div className="card"><div className="card-body">
              <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>No-show risk</div>
              <div className="serif" style={{ fontSize: 28, fontWeight: 500, marginTop: 4 }}>{patient.noShowRisk}%</div>
            </div></div>
            <div className="card"><div className="card-body">
              <div className="muted" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Upcoming</div>
              <div className="serif" style={{ fontSize: 28, fontWeight: 500, marginTop: 4 }}>{patient.upcoming.length}</div>
            </div></div>
          </div>

          <div className="card" style={{ marginBottom: 14 }}>
            <div className="card-head"><div className="card-title">Contact & basics</div></div>
            <div className="card-body">
              <div className="kv"><span className="k">Phone</span><span className="mono">{patient.phone}</span></div>
              <div className="kv"><span className="k">Condition</span><span>{patient.primaryCondition}</span></div>
              <div className="kv"><span className="k">Last visit</span><span className="mono">{patient.lastVisit}</span></div>
            </div>
          </div>

          <div className="card" style={{ marginBottom: 14 }}>
            <div className="card-head"><div className="card-title">Appointments</div><div className="card-sub">{allAppts.length} total</div></div>
            <div>
              {allAppts.map(a => {
                const d = DOCTORS.find(x => x.id === a.docId);
                const dept = DEPARTMENTS.find(x => x.id === a.dept);
                const day = DAYS.find(x => x.id === a.dayId);
                return (
                  <div key={a.id} onClick={() => onOpenAppt(a)} style={{ padding: '12px 18px', borderBottom: '1px solid var(--border)', cursor: 'pointer' }}>
                    <div className="row-space">
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 500 }}>{a.typeLabel}</div>
                        <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>{d.name} · {dept.name}</div>
                      </div>
                      <div style={{ textAlign: 'right' }}>
                        <div className="mono" style={{ fontSize: 12 }}>{day.label} {a.startLabel}</div>
                        <StatusPill status={a.status} />
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="card">
            <div className="card-head"><div className="card-title">History</div></div>
            <div>
              {patient.history.map((h, i) => (
                <div key={i} style={{ padding: '12px 18px', borderBottom: i < patient.history.length - 1 ? '1px solid var(--border)' : 0 }}>
                  <div className="row-space">
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{h.type} · {h.provider}</div>
                    <div className="mono muted" style={{ fontSize: 11 }}>{h.date}</div>
                  </div>
                  <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>{h.note}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="drawer-foot">
          <button className="btn"><Icon name="phone" size={12} /> Call</button>
          <button className="btn"><Icon name="bell" size={12} /> Send reminder</button>
          <div style={{ flex: 1 }} />
          <button className="btn accent"><Icon name="plus" size={12} /> New appt</button>
        </div>
      </div>
    </>
  );
};

const NewApptModal = ({ open, onClose, onBook }) => {
  if (!open) return null;
  const { PATIENTS, DEPARTMENTS, DOCTORS, DAYS, APPOINTMENTS, APPT_TYPES, fmt } = window.MOCK;
  const [dept, setDept] = useState('cardio');
  const [patientId, setPatientId] = useState(PATIENTS[0].id);
  const [docId, setDocId] = useState('');
  const [dayId, setDayId] = useState('wed');
  const [timeStr, setTimeStr] = useState(fmt(9 * 60));
  const [serviceType, setServiceType] = useState('consult');
  const [notes, setNotes] = useState('');

  const deptDocs = DOCTORS.filter(d => d.dept === dept);
  const effectiveDocId = docId || deptDocs[0]?.id || '';
  const typeInfo = APPT_TYPES[serviceType] || { dur: 30, label: 'Consultation' };
  const dur = typeInfo.dur;
  const startMin = parseApptTime(timeStr);

  // Real conflict detection against APPOINTMENTS
  const conflict = APPOINTMENTS.some(a =>
    a.docId === effectiveDocId && a.dayId === dayId &&
    a.start < startMin + dur && a.end > startMin
  );

  // Closest free slots for same doctor, + other free doctors at the same time
  const { sameDocAlts, altDocAlts } = useMemo(() => {
    if (!conflict) return { sameDocAlts: [], altDocAlts: [] };
    const taken = APPOINTMENTS.filter(a => a.docId === effectiveDocId && a.dayId === dayId);
    const freeTimes = [];
    for (let t = 0; t < 1440; t += 15) {
      if (t === startMin) continue;
      if (!taken.some(a => a.start < t + dur && a.end > t)) freeTimes.push(t);
    }
    freeTimes.sort((a, b) => Math.abs(a - startMin) - Math.abs(b - startMin));
    const altDocs = deptDocs
      .filter(d => d.id !== effectiveDocId)
      .filter(d => !APPOINTMENTS.some(a =>
        a.docId === d.id && a.dayId === dayId && a.start < startMin + dur && a.end > startMin
      ));
    return { sameDocAlts: freeTimes.slice(0, 3), altDocAlts: altDocs.slice(0, 3) };
  }, [conflict, effectiveDocId, dayId, startMin, dur, deptDocs]);

  const timeOptions = useMemo(() =>
    Array.from({ length: 96 }, (_, i) => fmt(i * 15)), []);

  const DEPT_DEFAULT_ROOM = {
    cardio: 'r1', radio: 'r4', lab: 'r8', ortho: 'r10',
    neuro: 'r12', onco: 'r14', gen: 'r16', derm: 'r18',
  };

  const handleBook = () => {
    if (conflict) return;
    const newAppt = {
      id: `user-${Date.now()}`,
      patientId, typeId: serviceType,
      docId: effectiveDocId,
      roomId: DEPT_DEFAULT_ROOM[dept] || 'r16',
      dayId, dept,
      start: startMin, end: startMin + dur,
      startLabel: fmt(startMin), endLabel: fmt(startMin + dur),
      duration: dur, typeLabel: typeInfo.label,
      status: 'scheduled', notes,
    };
    onBook && onBook(newAppt);
    onClose();
  };

  return (
    <div className="modal-backdrop open" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div className="serif" style={{ fontSize: 20, fontWeight: 500 }}>New appointment</div>
          <div className="muted" style={{ fontSize: 12 }}>Conflict detection runs live as you fill the form.</div>
        </div>
        <div className="modal-body">
          <div className="grid-2">
            <div className="field">
              <label className="label">Patient</label>
              <select className="select" value={patientId} onChange={e => setPatientId(e.target.value)}>
                {PATIENTS.map(p => <option key={p.id} value={p.id}>{p.name} · {p.mrn}</option>)}
              </select>
            </div>
            <div className="field">
              <label className="label">Department</label>
              <select className="select" value={dept} onChange={e => { setDept(e.target.value); setDocId(''); }}>
                {DEPARTMENTS.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
              </select>
            </div>
            <div className="field">
              <label className="label">Service</label>
              <select className="select" value={serviceType} onChange={e => setServiceType(e.target.value)}>
                {Object.entries(APPT_TYPES).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
              </select>
            </div>
            <div className="field">
              <label className="label">Provider</label>
              <select className="select" value={effectiveDocId} onChange={e => setDocId(e.target.value)}>
                {deptDocs.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
              </select>
            </div>
            <div className="field">
              <label className="label">Day</label>
              <select className="select" value={dayId} onChange={e => setDayId(e.target.value)}>
                {DAYS.map(d => <option key={d.id} value={d.id}>{d.label} · {d.date}</option>)}
              </select>
            </div>
            <div className="field">
              <label className="label">Time</label>
              <select className="select" value={timeStr} onChange={e => setTimeStr(e.target.value)}>
                {timeOptions.map(t => <option key={t} value={t}>{t}</option>)}
              </select>
            </div>
          </div>
          <div className="field">
            <label className="label">Notes</label>
            <textarea className="textarea" rows={3} placeholder="Any notes for this appointment…" value={notes} onChange={e => setNotes(e.target.value)} />
          </div>

          {conflict && (
            <div style={{ padding: 12, background: 'var(--err-soft)', color: 'var(--err-text)', borderRadius: 8, fontSize: 13 }}>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 10 }}>
                <Icon name="alert" size={15} />
                <b>Conflict:</b> {DOCTORS.find(d => d.id === effectiveDocId)?.name} is booked at {timeStr}.
              </div>
              {sameDocAlts.length > 0 && (
                <div style={{ marginBottom: 8 }}>
                  <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', opacity: 0.7, marginBottom: 5 }}>
                    Same provider · closest times
                  </div>
                  <div className="row" style={{ gap: 6, flexWrap: 'wrap' }}>
                    {sameDocAlts.map(alt => (
                      <button key={alt} className="btn sm primary" onClick={() => setTimeStr(fmt(alt))}>
                        {fmt(alt)}
                      </button>
                    ))}
                  </div>
                </div>
              )}
              {altDocAlts.length > 0 && (
                <div>
                  <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', opacity: 0.7, marginBottom: 5 }}>
                    Other providers · {timeStr}
                  </div>
                  <div className="row" style={{ gap: 6, flexWrap: 'wrap' }}>
                    {altDocAlts.map(d => (
                      <button key={d.id} className="btn sm" style={{ background: 'var(--bg-elev)', color: 'var(--err-text)', border: '1px solid var(--err)' }} onClick={() => setDocId(d.id)}>
                        {d.name}
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button
            className="btn accent"
            onClick={handleBook}
            disabled={conflict}
            style={{ opacity: conflict ? 0.45 : 1, cursor: conflict ? 'not-allowed' : 'pointer' }}
          >
            Book appointment
          </button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { MultiDeptWizard, ApptDrawer, PatientDrawer, NewApptModal });
