// SkinJourney Dashboard — Appointments (pending / confirmed / cancellations)
//                          + BookAppointment modal
const { useState: useS_ap } = React;

function ApptCard({ appt, kind, onConfirm, onDecline, onCancel, onIcs, navigate }) {
  const patient = SJ_DATA.byId(appt.patient_id);
  const d = new Date(appt.scheduled_at);
  const isToday = new Date(SJ_DATA.NOW).toDateString() === d.toDateString();
  const isTomorrow = new Date(SJ_DATA.NOW.getTime() + 86400000).toDateString() === d.toDateString();

  const accent = kind === 'pending' ? 'var(--coral-500)' : kind === 'confirmed' ? 'var(--sage-500)' : 'var(--warning)';

  return (
    <div style={{
      display: 'flex', gap: 16, padding: '20px 22px',
      borderBottom: '1px solid var(--border-subtle)',
      alignItems: 'flex-start',
      position: 'relative',
    }}>
      <div style={{ position: 'absolute', insetInlineEnd: 0, top: 20, bottom: 20, width: 3, background: accent, borderRadius: 4 }} />

      <div style={{
        width: 78, padding: '12px 8px', textAlign: 'center',
        background: 'var(--surface-sunken)', borderRadius: 14, flexShrink: 0,
      }}>
        <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.6, textTransform: 'uppercase' }}>
          {isToday ? 'היום' : isTomorrow ? 'מחר' : SJ_DATA.HEB_DAYS_SHORT[d.getDay()]}
        </div>
        <div className="tabular" style={{ fontSize: 22, fontWeight: 700, color: 'var(--text-primary)', lineHeight: 1, margin: '2px 0' }}>
          {d.getDate()}
        </div>
        <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-tertiary)' }}>
          {SJ_DATA.HEB_MONTHS_SHORT[d.getMonth()]}
        </div>
        <div className="tabular ltr-run" style={{ marginTop: 6, fontSize: 13, fontWeight: 700, color: accent }}>
          {SJ_DATA.formatHebTime(d)}
        </div>
      </div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
          <Avatar name={patient.name} size="sm" />
          <button onClick={() => navigate({ name: 'patient', id: patient.id })}
                  style={{ background: 'none', border: 'none', fontSize: 16, fontWeight: 700, color: 'var(--text-primary)', cursor: 'pointer', padding: 0 }}>
            {patient.name}
          </button>
          <Chip kind="neutral">בת {patient.age}</Chip>
          <Chip>עור {patient.skin_label}</Chip>
        </div>
        {appt.patient_note && (
          <div style={{
            marginTop: 8, padding: '10px 14px',
            background: kind === 'pending' ? 'var(--coral-50)' : 'var(--sand-100)',
            border: '1px solid var(--border-subtle)', borderRadius: 12, fontSize: 13, lineHeight: 1.55,
            color: 'var(--text-secondary)',
          }}>
            <span style={{ fontWeight: 700, color: 'var(--text-primary)' }}>הערה מהמטופלת:</span> {appt.patient_note}
          </div>
        )}
        {appt.practitioner_note && (
          <div style={{ marginTop: 8, fontSize: 13, color: 'var(--text-secondary)' }}>
            <span style={{ fontWeight: 700 }}>הערה שלי:</span> {appt.practitioner_note}
          </div>
        )}
        {kind === 'cancelled' && (
          <div style={{ marginTop: 6, fontSize: 12, color: 'var(--coral-700)', fontWeight: 600 }}>
            בוטל על ידי המטופלת · {SJ_DATA.formatRelativeHe(appt.cancelled_at)}
          </div>
        )}
      </div>

      <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0 }}>
        {kind === 'pending' && (
          <>
            <Button kind="primary" size="sm" icon="check" onClick={onConfirm}>אשרי</Button>
            <Button kind="ghost" size="sm" icon="x" onClick={onDecline}>דחי</Button>
          </>
        )}
        {kind === 'confirmed' && (
          <>
            <IconButton icon="download" onClick={onIcs} title="הוספה ליומן" />
            <Button kind="ghost" size="sm" onClick={onCancel}>ביטול</Button>
          </>
        )}
        {kind === 'cancelled' && (
          <Button kind="secondary" size="sm" icon="plus">קבעי תור חדש</Button>
        )}
      </div>
    </div>
  );
}

function AppointmentsScreen({ navigate, onBookAppointment, dataset }) {
  const toast = useToast();
  const all = dataset === 'empty' ? [] : SJ_DATA.APPOINTMENTS;
  const [appts, setAppts] = useS_ap(all);

  const pending = appts.filter((a) => a.status === 'pending');
  const confirmed = appts.filter((a) => a.status === 'confirmed' && new Date(a.scheduled_at) >= new Date(SJ_DATA.NOW.getTime() - 86400000))
    .sort((a, b) => new Date(a.scheduled_at) - new Date(b.scheduled_at));
  const cancellations = appts.filter((a) => a.status === 'cancelled' && a.cancelled_by === 'patient');

  const confirm = (id) => {
    setAppts(appts.map((a) => a.id === id ? { ...a, status: 'confirmed' } : a));
    toast.push('התור אושר. הודעה נשלחה למטופלת', { icon: 'check' });
  };
  const decline = (id) => {
    setAppts(appts.filter((a) => a.id !== id));
    toast.push('הבקשה נדחתה');
  };
  const cancel = (id) => {
    setAppts(appts.map((a) => a.id === id ? { ...a, status: 'cancelled', cancelled_by: 'practitioner', cancelled_at: new Date().toISOString() } : a));
    toast.push('התור בוטל');
  };
  const ics = () => toast.push('קובץ .ics הורד', { icon: 'download' });

  return (
    <div className="screen content-scroll">
      <PageHeader
        title="תורים"
        subtitle="ניהול בקשות וקביעת פגישות"
        actions={<Button kind="primary" icon="plus" onClick={onBookAppointment}>קבע תור חדש</Button>}
      />

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 28 }}>
        <KPI label="ממתינות לאישור" value={pending.length} icon="appointments" />
        <KPI label="תורים השבוע" value={confirmed.filter((a) => new Date(a.scheduled_at) < new Date(SJ_DATA.NOW.getTime() + 7 * 86400000)).length} icon="calendar" />
        <KPI label="ביטולים (14 ימים)" value={cancellations.length} icon="x" />
      </div>

      {/* Pending */}
      <div style={{ marginBottom: 28 }}>
        <div className="section-header">
          <h2 style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--coral-400)' }} />
            ממתינות לאישור
            <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-tertiary)' }}>{pending.length}</span>
          </h2>
        </div>
        <Card flush>
          {pending.length === 0
            ? <Empty icon="check" title="אין בקשות פתוחות" body="כל הבקשות טופלו ✨" />
            : pending.map((a) => <ApptCard key={a.id} appt={a} kind="pending" navigate={navigate}
                onConfirm={() => confirm(a.id)} onDecline={() => decline(a.id)} />)}
        </Card>
      </div>

      {/* Confirmed */}
      <div style={{ marginBottom: 28 }}>
        <div className="section-header">
          <h2 style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--sage-500)' }} />
            תורים מאושרים
            <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-tertiary)' }}>{confirmed.length}</span>
          </h2>
        </div>
        <Card flush>
          {confirmed.length === 0
            ? <Empty icon="calendar" title="אין תורים קרובים" />
            : confirmed.map((a) => <ApptCard key={a.id} appt={a} kind="confirmed" navigate={navigate}
                onCancel={() => cancel(a.id)} onIcs={ics} />)}
        </Card>
      </div>

      {/* Cancellations */}
      {cancellations.length > 0 && (
        <div>
          <div className="section-header">
            <h2 style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--warning)' }} />
              בוטלו על ידי מטופלות
              <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-tertiary)' }}>14 ימים אחרונים</span>
            </h2>
          </div>
          <Card flush>
            {cancellations.map((a) => <ApptCard key={a.id} appt={a} kind="cancelled" navigate={navigate} />)}
          </Card>
        </div>
      )}
    </div>
  );
}

/* ── Book Appointment Modal ─────────────────────────────────────────── */
function BookAppointmentModal({ open, onClose, patientId }) {
  const toast = useToast();
  const [pid, setPid] = useS_ap('');
  const [dt, setDt] = useS_ap('');
  const [note, setNote] = useS_ap('');

  // Pre-fill patient when opened from a patient detail page
  React.useEffect(() => {
    if (open) setPid(patientId || '');
  }, [open, patientId]);

  const lockedPatient = patientId ? SJ_DATA.byId(patientId) : null;

  const submit = () => {
    if (!pid || !dt) { toast.push('יש לבחור מטופלת ושעה', { icon: 'x' }); return; }
    onClose();
    toast.push('התור נקבע. הודעה נשלחה למטופלת');
    setPid(''); setDt(''); setNote('');
  };

  return (
    <Modal open={open} onClose={onClose} title="קביעת תור חדש"
      footer={
        <>
          <Button kind="primary" icon="check" onClick={submit}>קבעי תור</Button>
          <Button kind="ghost" onClick={onClose}>ביטול</Button>
        </>
      }>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div className="field">
          <label className="field-label">מטופלת</label>
          {lockedPatient ? (
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '10px 14px',
              background: 'var(--sage-50)',
              border: '1px solid var(--sage-200)',
              borderRadius: 'var(--radius-md)',
            }}>
              <Avatar name={lockedPatient.name} size="sm" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-primary)' }}>{lockedPatient.name}</div>
                <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>בת {lockedPatient.age} · עור {lockedPatient.skin_label}</div>
              </div>
              <Chip kind="success" dot>נבחרה</Chip>
            </div>
          ) : (
            <select className="select" value={pid} onChange={(e) => setPid(e.target.value)}>
              <option value="">בחרי מטופלת…</option>
              {SJ_DATA.PATIENTS.map((p) => <option key={p.id} value={p.id}>{p.name} · בת {p.age}</option>)}
            </select>
          )}
        </div>
        <div className="field">
          <label className="field-label">תאריך ושעה</label>
          <input type="datetime-local" className="input" value={dt} onChange={(e) => setDt(e.target.value)} />
        </div>
        <div className="field">
          <label className="field-label">הערה למטופלת (אופציונלי)</label>
          <textarea className="textarea" value={note} onChange={(e) => setNote(e.target.value)}
                    placeholder="הוראות הכנה, מה להביא, או כל פרט אחר..." />
        </div>
        <div style={{
          padding: '12px 14px', background: 'var(--sage-50)',
          border: '1px solid var(--sage-100)', borderRadius: 12,
          display: 'flex', gap: 10, alignItems: 'flex-start',
        }}>
          <Icon name="bell" size={16} style={{ color: 'var(--sage-700)', marginTop: 2 }} />
          <span style={{ fontSize: 13, color: 'var(--sage-700)', lineHeight: 1.55 }}>
            המטופלת תקבל הודעה דחיפה לטלפון מיד עם הקביעה
          </span>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { AppointmentsScreen, BookAppointmentModal });
