/* global React, Icons, AppContext, DB, SB */
const { useState, useEffect, useContext, useMemo, createElement: h, Fragment } = React;

// ==================== New Appointment ====================
function NewAppointment() {
  const { setScreen, toast, clinicId, setAppointments, appointments, screenParams, patients, doctors, services } = useContext(AppContext);
  const allPatientsForAppt = (patients && patients.length) ? patients : (window.PATIENTS || []);
  const allDoctorsForAppt  = (doctors  && doctors.length)  ? doctors  : (window.DOCTORS  || []);
  const allServices        = (services && services.length) ? services : (window.TREATMENT_TYPES || []);
  const [saving, setSaving] = useState(false);
  const today = new Date().toISOString().split('T')[0];
  // If coming from patient file, pre-fill patient and skip to step 2
  const initPatientId   = screenParams?.patientId   || null;
  const initPatientName = screenParams?.patientName || '';
  const [step, setStep] = useState(initPatientId ? 2 : 1);
  const [data, setData] = useState({ patient: initPatientName, patientId: initPatientId, doctor: '', doctorId: null, type: 'كشف وفحص', date: today, time: '10:00', room: 'غرفة 1', notes: '', reminder: true, duration: 30, price: 150 });
  const steps = ['المريض', 'الإجراء', 'الموعد', 'تأكيد'];

  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', { className: 'flex gap-12 ai-c' },
        h('button', { className: 'icon-btn', onClick: () => setScreen('appointments') }, h(Icons.ChevronRight, { size: 18 })),
        h('div', null,
          h('div', { className: 'page-title' }, 'حجز موعد جديد'),
          h('div', { className: 'page-subtitle' }, `الخطوة ${step} من ${steps.length}: ${steps[step-1]}`),
        ),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { style: { maxWidth: 800, margin: '0 auto' } },
        // Stepper
        h('div', { className: 'flex ai-c mb-24', style: { gap: 0 } },
          steps.map((s, i) => h(Fragment, { key: i },
            h('div', { className: 'flex ai-c gap-8' },
              h('div', {
                style: {
                  width: 32, height: 32, borderRadius: '50%', display: 'grid', placeItems: 'center',
                  background: i + 1 <= step ? 'var(--accent)' : 'var(--bg-subtle)',
                  color: i + 1 <= step ? '#fff' : 'var(--text-tertiary)',
                  fontWeight: 800, fontSize: 14,
                },
              }, i + 1 < step ? h(Icons.Check, { size: 16 }) : i + 1),
              h('div', { style: { fontSize: 13, fontWeight: 600, color: i + 1 <= step ? 'var(--text-primary)' : 'var(--text-tertiary)' } }, s),
            ),
            i < steps.length - 1 ? h('div', { style: { flex: 1, height: 2, background: i + 1 < step ? 'var(--accent)' : 'var(--border)', margin: '0 12px' } }) : null,
          )),
        ),

        h('div', { className: 'card p-24' },
          step === 1 && h('div', null,
            h('div', { className: 'label' }, 'ابحث عن مريض'),
            h('input', { className: 'input mb-16', placeholder: 'اسم، رقم هاتف، أو ID...', value: data.patient, onChange: (e) => setData({ ...data, patient: e.target.value }) }),
            h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 8 } }, 'مرضى مقترحون'),
            h('div', { className: 'grid', style: { gap: 8 } },
              allPatientsForAppt.filter(p => !data.patient || p.name.includes(data.patient) || (p.phone||'').includes(data.patient)).slice(0, 4).map(p => h('div', {
                key: p.id,
                onClick: () => setData({ ...data, patient: p.name, patientId: p.id }),
                style: {
                  padding: 12, border: '1px solid ' + (data.patient === p.name ? 'var(--accent)' : 'var(--border)'),
                  background: data.patient === p.name ? 'var(--accent-soft)' : 'transparent',
                  borderRadius: 'var(--radius)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12,
                },
              },
                h('div', { className: 'avatar sm' }, p.avatar),
                h('div', { style: { flex: 1 } },
                  h('div', { style: { fontWeight: 700, fontSize: 14 } }, p.name),
                  h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)' } }, `${p.phone} · ${p.id}`),
                ),
              )),
            ),
            h('button', { className: 'btn outline mt-16', style: { width: '100%' } }, h(Icons.UserPlus, { size: 16 }), 'إضافة مريض جديد'),
          ),
          step === 2 && h('div', null,
            h('div', { className: 'label' }, 'نوع الإجراء'),
            h('div', { className: 'grid cols-2 mb-16', style: { gap: 8 } },
              allServices.slice(0, 8).map(t => h('div', {
                key: t.id,
                onClick: () => setData({ ...data, type: t.name, price: t.price, duration: t.duration }),
                style: {
                  padding: 12, border: '1px solid ' + (data.type === t.name ? 'var(--accent)' : 'var(--border)'),
                  background: data.type === t.name ? 'var(--accent-soft)' : 'transparent',
                  borderRadius: 'var(--radius)', cursor: 'pointer',
                },
              },
                h('div', { style: { fontWeight: 700, fontSize: 13 } }, t.name),
                h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 4 } }, `${t.duration} د · ${window.fmtEGP(t.price)}`),
              )),
            ),
            h('div', { className: 'label' }, 'الطبيب'),
            h('div', { className: 'grid cols-2', style: { gap: 8 } },
              allDoctorsForAppt.map(d => h('div', {
                key: d.id,
                onClick: () => setData({ ...data, doctor: d.name, doctorId: d.id }),
                style: {
                  padding: 10, border: '1px solid ' + (data.doctor === d.name ? 'var(--accent)' : 'var(--border)'),
                  background: data.doctor === d.name ? 'var(--accent-soft)' : 'transparent',
                  borderRadius: 'var(--radius)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10,
                },
              },
                h('div', { className: 'avatar sm', style: { background: d.color } }, d.avatar),
                h('div', null,
                  h('div', { style: { fontWeight: 700, fontSize: 13 } }, d.name),
                  h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, d.specialty),
                ),
              )),
            ),
          ),
          step === 3 && h('div', null,
            h('div', { className: 'grid cols-2 mb-16', style: { gap: 12 } },
              h('div', null, h('div', { className: 'label' }, 'التاريخ'), h('input', { className: 'input', type: 'date', value: data.date, onChange: (e) => setData({ ...data, date: e.target.value }) })),
              h('div', null, h('div', { className: 'label' }, 'الوقت'), h('input', { className: 'input', type: 'time', value: data.time, onChange: (e) => setData({ ...data, time: e.target.value }) })),
            ),
            h('div', { className: 'label' }, 'الأوقات المتاحة'),
            h('div', { className: 'flex gap-8 wrap mb-16' },
              ['09:00', '09:30', '10:00', '10:30', '11:00', '13:00', '14:00', '15:30', '16:00'].map(t => h('button', {
                key: t,
                className: 'btn sm ' + (data.time === t ? 'primary' : 'outline'),
                onClick: () => setData({ ...data, time: t }),
              }, t)),
            ),
            h('div', { className: 'label' }, 'الغرفة'),
            h('div', { className: 'flex gap-8 mb-16' },
              ['غرفة 1', 'غرفة 2', 'غرفة 3'].map(r => h('button', {
                key: r,
                className: 'btn sm ' + (data.room === r ? 'primary' : 'outline'),
                onClick: () => setData({ ...data, room: r }),
              }, r)),
            ),
            h('div', { className: 'label' }, 'ملاحظات'),
            h('textarea', { className: 'textarea', rows: 3, placeholder: 'أي ملاحظات خاصة بالموعد...', value: data.notes, onChange: (e) => setData({ ...data, notes: e.target.value }) }),
            h('label', { className: 'flex ai-c gap-8 mt-16', style: { cursor: 'pointer' } },
              h('input', { type: 'checkbox', checked: data.reminder, onChange: (e) => setData({ ...data, reminder: e.target.checked }) }),
              h('span', { style: { fontSize: 13 } }, 'إرسال تذكير تلقائي عبر WhatsApp قبل الموعد بـ 24 ساعة'),
            ),
          ),
          step === 4 && h('div', null,
            h('div', { style: { textAlign: 'center', marginBottom: 20 } },
              h('div', { style: { width: 64, height: 64, borderRadius: '50%', background: 'var(--success-soft)', color: 'var(--success)', display: 'grid', placeItems: 'center', margin: '0 auto 12px' } },
                h(Icons.Check, { size: 32 })),
              h('div', { style: { fontSize: 18, fontWeight: 800 } }, 'تأكيد الموعد'),
              h('div', { style: { fontSize: 13, color: 'var(--text-tertiary)', marginTop: 4 } }, 'راجع التفاصيل قبل الحفظ'),
            ),
            h('div', { style: { padding: 16, background: 'var(--bg-subtle)', borderRadius: 'var(--radius)' } },
              [
                { label: 'المريض', value: data.patient || '—' },
                { label: 'الإجراء', value: data.type },
                { label: 'الطبيب', value: data.doctor },
                { label: 'التاريخ والوقت', value: `${data.date} · ${data.time}` },
                { label: 'الغرفة', value: data.room },
                { label: 'المدة التقديرية', value: (data.duration || 30) + ' دقيقة' },
                { label: 'التكلفة التقديرية', value: window.fmtEGP(data.price || 150) },
              ].map((r, i) => h('div', { key: i, style: { display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderBottom: i < 6 ? '1px solid var(--border)' : 'none' } },
                h('span', { style: { fontSize: 13, color: 'var(--text-tertiary)' } }, r.label),
                h('span', { style: { fontSize: 13, fontWeight: 700 } }, r.value),
              )),
            ),
          ),

          h('div', { className: 'flex jc-sb mt-24' },
            h('button', { className: 'btn outline', onClick: () => step > 1 ? setStep(step - 1) : setScreen('appointments') }, step === 1 ? 'إلغاء' : 'السابق'),
            h('button', {
              className: 'btn primary',
              disabled: saving,
              onClick: async () => {
                if (step < 4) { setStep(step + 1); return; }
                if (!data.patientId) { toast('اختر مريضاً أولاً'); return; }
                setSaving(true);
                try {
                  const appt = await DB.addAppointment(clinicId, {
                    patient_id: data.patientId,
                    doctor_id: data.doctorId || (window.DOCTORS[0] && window.DOCTORS[0].id),
                    date: data.date,
                    time: data.time + ':00',
                    duration: data.duration || 30,
                    type: data.type,
                    status: 'pending',
                    room: data.room,
                    notes: data.notes,
                  });
                  setAppointments([appt, ...appointments]);
                  toast('تم حجز الموعد بنجاح 🎉');
                  setScreen('appointments');
                } catch(e) {
                  console.error(e);
                  toast('حدث خطأ أثناء الحفظ');
                } finally { setSaving(false); }
              },
            }, saving ? 'جاري الحفظ...' : step === 4 ? 'تأكيد الحجز' : 'التالي'),
          ),
        ),
      ),
    ),
  );
}

// ==================== Billing ====================
function PayModal({ inv, onClose, onPaid }) {
  const { toast } = useContext(AppContext);
  const remaining = inv.total - inv.paid;
  const [amount, setAmount] = useState(remaining);
  const [saving, setSaving] = useState(false);
  const handlePay = async () => {
    if (!amount || amount <= 0) { toast('أدخل مبلغ صحيح'); return; }
    setSaving(true);
    try {
      const newPaid = Math.min(inv.paid + parseFloat(amount), inv.total);
      const updated = await DB.updateInvoicePaid(inv.id, newPaid);
      toast('تم تسجيل الدفع ✅');
      onPaid(updated);
      onClose();
    } catch(e) { console.error(e); toast('حدث خطأ'); }
    finally { setSaving(false); }
  };
  return h(Fragment, null,
    h('div', { onClick: onClose, style: { position:'fixed',inset:0,background:'rgba(0,0,0,0.4)',zIndex:200 } }),
    h('div', { style: { position:'fixed',top:'50%',left:'50%',transform:'translate(-50%,-50%)',background:'var(--bg-elevated)',borderRadius:'var(--radius-lg)',padding:28,width:380,zIndex:201,boxShadow:'var(--shadow-lg)' } },
      h('div', { style:{fontWeight:800,fontSize:17,marginBottom:16} }, 'تسجيل دفعة'),
      h('div', { style:{fontSize:13,color:'var(--text-tertiary)',marginBottom:4} }, 'المريض: ' + inv.patient),
      h('div', { style:{fontSize:13,color:'var(--text-tertiary)',marginBottom:16} }, `الإجمالي: ${window.fmtEGP(inv.total)} · مدفوع: ${window.fmtEGP(inv.paid)} · متبقي: ${window.fmtEGP(remaining)}`),
      h('div', { className:'label' }, 'المبلغ المدفوع'),
      h('input', { className:'input mb-16', type:'number', value:amount, onChange:e=>setAmount(e.target.value) }),
      h('div', { className:'flex gap-8 jc-sb' },
        h('button', { className:'btn outline', onClick:onClose }, 'إلغاء'),
        h('button', { className:'btn primary', disabled:saving, onClick:handlePay }, saving?'جاري الحفظ...':'تأكيد الدفع'),
      ),
    ),
  );
}

function Billing() {
  const { setScreen, invoices, setInvoices } = useContext(AppContext);
  const [payInv, setPayInv] = useState(null);
  const [tabFilter, setTabFilter] = useState('all');
  const allInvoices = (invoices && invoices.length) ? invoices : (window.INVOICES || []);
  const filtered = tabFilter === 'all' ? allInvoices : allInvoices.filter(i => i.status === tabFilter);
  const total = allInvoices.reduce((s, i) => s + i.total, 0);
  const paid  = allInvoices.reduce((s, i) => s + i.paid,  0);
  const outstanding = total - paid;

  return h('div', { className: 'fade-in' },
    payInv ? h(PayModal, { inv: payInv, onClose: ()=>setPayInv(null), onPaid: (updated)=>setInvoices(prev=>(prev||[]).map(i=>i.id===updated.id?updated:i)) }) : null,
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'الفواتير والمدفوعات'),
        h('div', { className: 'page-subtitle' }, `${allInvoices.length} فاتورة · ${window.fmtEGP(outstanding)} مستحقة`),
      ),
      h('div', { className: 'flex gap-8' },
        h('button', { className: 'btn outline' }, h(Icons.Download, { size: 16 }), 'تصدير'),
        h('button', { className: 'btn primary', onClick: () => setScreen('new-invoice') }, h(Icons.Plus, { size: 16 }), 'فاتورة جديدة'),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'grid cols-3 mb-16' },
        [
          { label: 'إجمالي الفواتير', value: total, icon: Icons.CreditCard, color: 'var(--accent)', soft: 'var(--accent-soft)' },
          { label: 'مدفوع', value: paid, icon: Icons.Check, color: 'var(--success)', soft: 'var(--success-soft)' },
          { label: 'مستحق', value: outstanding, icon: Icons.AlertTriangle, color: 'var(--danger)', soft: 'var(--danger-soft)' },
        ].map((k, i) => h('div', { key: i, className: 'card kpi' },
          h('div', { className: 'flex jc-sb ai-c' },
            h('div', null,
              h('div', { className: 'label' }, k.label),
              h('div', { className: 'value' }, window.fmtEGP(k.value)),
            ),
            h('div', { className: 'kpi-icon', style: { background: k.soft, color: k.color } }, h(k.icon, { size: 20 })),
          ),
        )),
      ),
      h('div', { className: 'card', style: { overflow: 'hidden' } },
        h('div', { className: 'tabs', style: { padding: '0 16px', marginBottom: 0 } },
          [['all','الكل'],['paid','مدفوعة'],['partial','جزئية'],['unpaid','غير مدفوعة']].map(([v,l]) => h('button', {
            key: v, className: 'tab' + (tabFilter===v?' active':''), onClick:()=>setTabFilter(v),
          }, l)),
        ),
        h('table', { className: 'data-table' },
          h('thead', null, h('tr', null, ['رقم الفاتورة', 'المريض', 'التاريخ', 'الإجمالي', 'المدفوع', 'المتبقي', 'الحالة', ''].map((t, i) => h('th', { key: i }, t)))),
          h('tbody', null,
            filtered.length ? filtered.map(inv => h('tr', { key: inv.id, style: { cursor: 'pointer' } },
              h('td', { style: { fontFamily: 'monospace', fontSize: 12, fontWeight: 700 } }, typeof inv.id === 'string' && inv.id.startsWith('INV') ? inv.id : 'INV-' + String(inv.id).slice(-6)),
              h('td', null, inv.patient),
              h('td', { style: { fontSize: 13, color: 'var(--text-secondary)' } }, inv.date),
              h('td', { style: { fontWeight: 700 } }, window.fmtEGP(inv.total)),
              h('td', { style: { color: 'var(--success)', fontWeight: 600 } }, window.fmtEGP(inv.paid)),
              h('td', { style: { color: inv.total - inv.paid > 0 ? 'var(--danger)' : 'var(--text-muted)', fontWeight: 700 } }, window.fmtEGP(inv.total - inv.paid)),
              h('td', null, h('span', { className: 'chip ' + (inv.status === 'paid' ? 'success' : inv.status === 'partial' ? 'warning' : 'danger') },
                inv.status === 'paid' ? 'مدفوعة' : inv.status === 'partial' ? 'جزئية' : 'غير مدفوعة')),
              h('td', null,
                h('div', { className: 'flex gap-4' },
                  inv.status !== 'paid' ? h('button', { className:'btn sm primary', onClick:e=>{e.stopPropagation();setPayInv(inv);} }, 'دفع') : null,
                  h('button', { className: 'icon-btn', title: 'طباعة' }, h(Icons.Printer, { size: 14 })),
                  h('button', {
                    className: 'icon-btn',
                    title: 'حذف الفاتورة',
                    style: { color: 'var(--danger)' },
                    onClick: async (e) => {
                      e.stopPropagation();
                      if (!confirm(`حذف الفاتورة ${inv.id}؟`)) return;
                      try {
                        await SB.from('invoice_items').delete().eq('invoice_id', inv.id);
                        await SB.from('invoices').delete().eq('id', inv.id);
                        setInvoices(prev => prev.filter(i => i.id !== inv.id));
                        toast('تم حذف الفاتورة');
                      } catch(e) { console.error(e); toast('خطأ في الحذف'); }
                    },
                  }, h(Icons.Trash, { size: 14 })),
                ),
              ),
            )) : h('tr', null, h('td', { colSpan:8, style:{textAlign:'center',padding:32,color:'var(--text-tertiary)'} }, 'لا توجد فواتير')),
          ),
        ),
      ),
    ),
  );
}

// ==================== New Invoice ====================
function NewInvoice() {
  const { setScreen, toast, clinicId, setInvoices, invoices, patients } = useContext(AppContext);
  const allPts = (patients && patients.length) ? patients : (window.PATIENTS || []);
  const [items, setItems] = useState([{ id: 1, name: 'كشف وفحص', qty: 1, price: 150 }]);
  const [patient, setPatient] = useState(null);
  const nextInvNum = `INV-${new Date().getFullYear()}-${String((invoices ? invoices.length : 0) + 1).padStart(4, '0')}`;
  const [payMethod, setPayMethod] = useState('نقدي');
  useEffect(() => { if (!patient && allPts.length) setPatient(allPts[0]); }, [allPts.length]);
  const [saving, setSaving] = useState(false);
  const [discount, setDiscount] = useState(0);
  const [tax, setTax] = useState(14);
  const subtotal = items.reduce((s, i) => s + i.qty * i.price, 0);
  const discountAmt = subtotal * (discount / 100);
  const taxAmt = (subtotal - discountAmt) * (tax / 100);
  const total = subtotal - discountAmt + taxAmt;

  const addItem = () => setItems([...items, { id: Date.now(), name: '', qty: 1, price: 0 }]);
  const removeItem = (id) => setItems(items.filter(i => i.id !== id));
  const updateItem = (id, field, val) => setItems(items.map(i => i.id === id ? { ...i, [field]: val } : i));

  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', { className: 'flex gap-12 ai-c' },
        h('button', { className: 'icon-btn', onClick: () => setScreen('billing') }, h(Icons.ChevronRight, { size: 18 })),
        h('div', null,
          h('div', { className: 'page-title' }, 'فاتورة جديدة'),
          h('div', { className: 'page-subtitle' }, nextInvNum),
        ),
      ),
      h('div', { className: 'flex gap-8' },
        h('button', { className: 'btn outline', onClick: () => setScreen('billing') }, 'إلغاء'),
        h('button', {
          className: 'btn primary',
          disabled: saving,
          onClick: async () => {
            if (!patient) { toast('اختر مريضاً أولاً'); return; }
            setSaving(true);
            try {
              const inv = await DB.addInvoice(clinicId,
                { patient_id: patient.id, date: new Date().toISOString().split('T')[0], notes: payMethod },
                items.map(it => ({ name: it.name, qty: it.qty, price: it.price, discount: 0 }))
              );
              setInvoices([inv, ...invoices]);
              toast('تم إنشاء الفاتورة بنجاح ✅');
              setScreen('billing');
            } catch(e) {
              console.error(e);
              toast('حدث خطأ أثناء الحفظ');
            } finally { setSaving(false); }
          },
        }, h(Icons.Check, { size: 16 }), saving ? 'جاري الحفظ...' : 'حفظ الفاتورة'),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { style: { display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 20 } },
        h('div', { className: 'card p-20' },
          h('div', { className: 'label' }, 'المريض'),
          h('select', {
            className: 'select mb-16',
            value: patient ? patient.id : '',
            onChange: (e) => setPatient(allPts.find(p => p.id === e.target.value) || null),
          },
            !patient ? h('option', { value: '' }, '— اختر مريضاً —') : null,
            allPts.map(p => h('option', { key: p.id, value: p.id }, `${p.name} — ${p.phone || p.id}`)),
          ),
          h('div', { className: 'label' }, 'البنود'),
          h('div', { className: 'card', style: { overflow: 'hidden', marginBottom: 8 } },
            h('table', { className: 'data-table', style: { fontSize: 13 } },
              h('thead', null, h('tr', null, ['الإجراء', 'الكمية', 'السعر', 'الإجمالي', ''].map((t, i) => h('th', { key: i }, t)))),
              h('tbody', null,
                items.map(it => h('tr', { key: it.id },
                  h('td', null, h('input', { className: 'input', style: { padding: 6, fontSize: 13 }, value: it.name, onChange: (e) => updateItem(it.id, 'name', e.target.value) })),
                  h('td', { style: { width: 70 } }, h('input', { className: 'input', type: 'number', style: { padding: 6, fontSize: 13 }, value: it.qty, onChange: (e) => updateItem(it.id, 'qty', +e.target.value) })),
                  h('td', { style: { width: 100 } }, h('input', { className: 'input', type: 'number', style: { padding: 6, fontSize: 13 }, value: it.price, onChange: (e) => updateItem(it.id, 'price', +e.target.value) })),
                  h('td', { style: { fontWeight: 700, width: 100 } }, window.fmtEGP(it.qty * it.price)),
                  h('td', { style: { width: 40 } }, h('button', { className: 'icon-btn', onClick: () => removeItem(it.id) }, h(Icons.Trash, { size: 14 }))),
                )),
              ),
            ),
          ),
          h('button', { className: 'btn outline sm', onClick: addItem }, h(Icons.Plus, { size: 14 }), 'إضافة بند'),
          h('div', { className: 'mt-16' },
            h('div', { className: 'label' }, 'ملاحظات'),
            h('textarea', { className: 'textarea', rows: 2, placeholder: 'أي ملاحظات على الفاتورة...' }),
          ),
        ),
        h('div', { className: 'card p-20' },
          h('div', { style: { fontWeight: 800, fontSize: 15, marginBottom: 16 } }, 'الملخص'),
          h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
            h('div', { className: 'flex jc-sb', style: { fontSize: 13 } },
              h('span', { style: { color: 'var(--text-tertiary)' } }, 'المجموع الفرعي'), h('span', { style: { fontWeight: 600 } }, window.fmtEGP(subtotal)),
            ),
            h('div', { className: 'flex jc-sb ai-c' },
              h('span', { style: { fontSize: 13, color: 'var(--text-tertiary)' } }, 'خصم %'),
              h('input', { type: 'number', className: 'input', style: { width: 70, padding: 6, fontSize: 13 }, value: discount, onChange: (e) => setDiscount(+e.target.value) }),
            ),
            h('div', { className: 'flex jc-sb', style: { fontSize: 13, color: 'var(--danger)' } },
              h('span', null, 'قيمة الخصم'), h('span', null, '- ' + window.fmtEGP(discountAmt)),
            ),
            h('div', { className: 'flex jc-sb ai-c' },
              h('span', { style: { fontSize: 13, color: 'var(--text-tertiary)' } }, 'ضريبة %'),
              h('input', { type: 'number', className: 'input', style: { width: 70, padding: 6, fontSize: 13 }, value: tax, onChange: (e) => setTax(+e.target.value) }),
            ),
            h('div', { className: 'flex jc-sb', style: { fontSize: 13 } },
              h('span', { style: { color: 'var(--text-tertiary)' } }, 'قيمة الضريبة'), h('span', null, window.fmtEGP(taxAmt)),
            ),
            h('div', { className: 'divider' }),
            h('div', { className: 'flex jc-sb', style: { fontSize: 20, fontWeight: 800 } },
              h('span', null, 'الإجمالي'), h('span', { style: { color: 'var(--accent)' } }, window.fmtEGP(total)),
            ),
          ),
          h('div', { className: 'label mt-16' }, 'طريقة الدفع'),
          h('div', { className: 'grid cols-2', style: { gap: 6 } },
            ['نقدي', 'فيزا', 'تحويل', 'تأمين'].map(m => h('button', {
              key: m,
              className: 'btn sm ' + (payMethod === m ? 'primary' : 'outline'),
              onClick: () => setPayMethod(m),
            }, m)),
          ),
        ),
      ),
    ),
  );
}

// ==================== Treatments (plans) ====================
function Treatments() {
  const { setScreen } = useContext(AppContext);
  const plans = [
    { id: 'TP1', patient: 'أحمد محمد السيد', doctor: 'د. سارة', status: 'جارية', progress: 60, procedures: 6, startDate: '2026-02-15', total: 8500, paid: 5000 },
    { id: 'TP2', patient: 'فاطمة علي حسن', doctor: 'د. منى', status: 'جارية', progress: 35, procedures: 18, startDate: '2026-01-10', total: 35000, paid: 12000 },
    { id: 'TP3', patient: 'محمد عبد الرحمن', doctor: 'د. سارة', status: 'جارية', progress: 85, procedures: 4, startDate: '2026-03-20', total: 4500, paid: 1100 },
    { id: 'TP4', patient: 'رنا أشرف', doctor: 'د. منى', status: 'مسودة', progress: 0, procedures: 8, startDate: '2026-04-18', total: 12000, paid: 0 },
    { id: 'TP5', patient: 'سلمى حسام', doctor: 'د. خالد', status: 'مكتملة', progress: 100, procedures: 3, startDate: '2025-11-15', total: 6000, paid: 6000 },
  ];

  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'خطط العلاج'),
        h('div', { className: 'page-subtitle' }, `${plans.filter(p => p.status === 'جارية').length} خطة جارية · ${plans.length} خطة إجمالاً`),
      ),
      h('div', { className: 'flex gap-8' },
        h('button', { className: 'btn primary', onClick: () => setScreen('new-treatment') }, h(Icons.Plus, { size: 16 }), 'خطة جديدة'),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'grid', style: { gap: 12 } },
        plans.map(p => h('div', { key: p.id, className: 'card p-20', style: { cursor: 'pointer' }, onClick: () => setScreen('patients') },
          h('div', { style: { display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1.5fr 80px', gap: 20, alignItems: 'center' } },
            h('div', null,
              h('div', { style: { fontWeight: 800, fontSize: 15 } }, p.patient),
              h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 } }, `${p.id} · ${p.doctor} · ${p.procedures} إجراءات`),
            ),
            h('div', null,
              h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, 'التاريخ'),
              h('div', { style: { fontSize: 13, fontWeight: 600, marginTop: 2 } }, p.startDate),
            ),
            h('div', null,
              h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, 'الإجمالي'),
              h('div', { style: { fontSize: 14, fontWeight: 800, marginTop: 2 } }, window.fmtEGP(p.total)),
              h('div', { style: { fontSize: 11, color: 'var(--success)' } }, 'مدفوع: ' + window.fmtEGP(p.paid)),
            ),
            h('div', null,
              h('div', { className: 'flex jc-sb ai-c mb-4' },
                h('span', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, 'التقدم'),
                h('span', { style: { fontSize: 12, fontWeight: 700 } }, p.progress + '%'),
              ),
              h('div', { className: 'progress' },
                h('div', { className: 'progress-bar', style: { width: p.progress + '%', background: p.status === 'مكتملة' ? 'var(--success)' : 'var(--accent)' } }),
              ),
            ),
            h('span', { className: 'chip ' + (p.status === 'مكتملة' ? 'success' : p.status === 'جارية' ? 'info' : '') }, p.status),
          ),
        )),
      ),
    ),
  );
}

// ==================== Inventory ====================
function Inventory() {
  const { toast, inventory } = useContext(AppContext);
  const [query, setQuery] = useState('');
  const allInv = (inventory && inventory.length) ? inventory : (window.INVENTORY || []);
  const filtered = allInv.filter(i => i.name.includes(query) || i.category.includes(query));

  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'المخزون'),
        h('div', { className: 'page-subtitle' }, `${allInv.length} صنف · ${allInv.filter(i => i.stock < i.minStock).length} صنف تحت الحد الأدنى`),
      ),
      h('div', { className: 'flex gap-8' },
        h('button', { className: 'btn outline' }, h(Icons.Download, { size: 16 }), 'تصدير'),
        h('button', { className: 'btn primary' }, h(Icons.Plus, { size: 16 }), 'صنف جديد'),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'card p-16 mb-16 flex gap-8 ai-c' },
        h('div', { style: { flex: 1, position: 'relative' } },
          h('input', { className: 'input', placeholder: 'بحث...', value: query, onChange: (e) => setQuery(e.target.value), style: { paddingInlineEnd: 40 } }),
          h('span', { style: { position: 'absolute', insetInlineEnd: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-tertiary)' } }, h(Icons.Search, { size: 16 })),
        ),
        h('button', { className: 'btn outline' }, h(Icons.Filter, { size: 16 }), 'الفئة'),
      ),
      h('div', { className: 'card', style: { overflow: 'hidden' } },
        h('table', { className: 'data-table' },
          h('thead', null, h('tr', null, ['الصنف', 'الفئة', 'المخزون', 'الحد الأدنى', 'السعر', 'المورد', 'الصلاحية', 'الحالة', ''].map((t, i) => h('th', { key: i }, t)))),
          h('tbody', null,
            filtered.map(it => {
              const low = it.stock < it.minStock;
              const critical = it.stock < it.minStock / 2;
              return h('tr', { key: it.id },
                h('td', { style: { fontWeight: 600 } }, it.name),
                h('td', null, h('span', { className: 'chip' }, it.category)),
                h('td', null,
                  h('div', { className: 'flex ai-c gap-8' },
                    h('span', { style: { fontWeight: 800, color: critical ? 'var(--danger)' : low ? 'var(--warning)' : 'var(--text-primary)' } }, window.fmtNum(it.stock)),
                    h('span', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, it.unit),
                  ),
                ),
                h('td', { style: { fontSize: 12, color: 'var(--text-tertiary)' } }, window.fmtNum(it.minStock) + ' ' + it.unit),
                h('td', { style: { fontWeight: 600 } }, window.fmtEGP(it.price)),
                h('td', { style: { fontSize: 12 } }, it.supplier),
                h('td', { style: { fontSize: 12, color: 'var(--text-secondary)' } }, it.expiry),
                h('td', null, h('span', { className: 'chip ' + (critical ? 'danger' : low ? 'warning' : 'success') },
                  critical ? 'حرج' : low ? 'منخفض' : 'متاح')),
                h('td', null,
                  h('button', { className: 'btn sm outline', onClick: () => toast('تم طلب الصنف') }, 'طلب'),
                ),
              );
            }),
          ),
        ),
      ),
    ),
  );
}

// ==================== Staff ====================
function Staff() {
  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'الموظفين'),
        h('div', { className: 'page-subtitle' }, `${window.DOCTORS.length} أطباء · ${window.STAFF.length} موظفين مساعدين`),
      ),
      h('button', { className: 'btn primary' }, h(Icons.UserPlus, { size: 16 }), 'موظف جديد'),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'mb-16', style: { fontWeight: 800, fontSize: 15 } }, 'الأطباء'),
      h('div', { className: 'grid cols-4 mb-24' },
        window.DOCTORS.map(d => h('div', { key: d.id, className: 'card p-20', style: { textAlign: 'center' } },
          h('div', { className: 'avatar lg', style: { background: d.color, margin: '0 auto 12px' } }, d.avatar),
          h('div', { style: { fontWeight: 800, fontSize: 15 } }, d.name),
          h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 } }, d.specialty),
          h('div', { className: 'flex jc-sb ai-c mt-16' },
            h('div', null,
              h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, 'المرضى'),
              h('div', { style: { fontWeight: 800, fontSize: 18 } }, window.fmtNum(d.patients)),
            ),
            h('div', null,
              h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, 'التقييم'),
              h('div', { style: { fontWeight: 800, fontSize: 18 } },
                h(Icons.Star, { size: 14, style: { display: 'inline-block', verticalAlign: 'text-bottom', color: '#f59e0b', marginLeft: 4 } }),
                d.rating,
              ),
            ),
          ),
          h('span', { className: 'chip ' + (d.status === 'متاحة' ? 'success' : d.status === 'مع مريض' ? 'warning' : ''), style: { marginTop: 12 } }, d.status),
        )),
      ),
      h('div', { className: 'mb-16', style: { fontWeight: 800, fontSize: 15 } }, 'الموظفون المساعدون'),
      h('div', { className: 'card', style: { overflow: 'hidden' } },
        h('table', { className: 'data-table' },
          h('thead', null, h('tr', null, ['الاسم', 'الدور', 'الهاتف', 'الوردية', ''].map((t, i) => h('th', { key: i }, t)))),
          h('tbody', null,
            window.STAFF.map(s => h('tr', { key: s.id },
              h('td', null, h('div', { className: 'flex ai-c gap-12' },
                h('div', { className: 'avatar sm' }, s.avatar),
                h('div', { style: { fontWeight: 700 } }, s.name),
              )),
              h('td', null, s.role),
              h('td', { style: { direction: 'ltr', textAlign: 'right' } }, s.phone),
              h('td', null, h('span', { className: 'chip' }, s.shift)),
              h('td', null, h('button', { className: 'btn ghost sm' }, 'عرض')),
            )),
          ),
        ),
      ),
    ),
  );
}

// ==================== Reports ====================
function Reports() {
  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'التقارير والإحصائيات'),
        h('div', { className: 'page-subtitle' }, 'نظرة شاملة على أداء العيادة'),
      ),
      h('div', { className: 'flex gap-8' },
        h('select', { className: 'select', style: { width: 180 } },
          ['آخر 7 أيام', 'هذا الشهر', 'آخر 3 شهور', 'هذه السنة'].map((t, i) => h('option', { key: i }, t)),
        ),
        h('button', { className: 'btn outline' }, h(Icons.Download, { size: 16 }), 'تصدير PDF'),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'grid cols-4 mb-16' },
        [
          { label: 'إيرادات الشهر', value: '342,500 ج.م', trend: '+18.4%', up: true, icon: Icons.DollarSign, color: 'var(--success)' },
          { label: 'مرضى جدد', value: '47', trend: '+12', up: true, icon: Icons.UserPlus, color: 'var(--accent)' },
          { label: 'مواعيد مكتملة', value: '284', trend: '+8%', up: true, icon: Icons.Check, color: 'var(--info)' },
          { label: 'معدل الإلغاء', value: '4.2%', trend: '-1.1%', up: false, icon: Icons.X, color: 'var(--warning)' },
        ].map((k, i) => h('div', { key: i, className: 'card kpi' },
          h('div', { className: 'flex jc-sb ai-c' },
            h('div', null,
              h('div', { className: 'label' }, k.label),
              h('div', { className: 'value' }, k.value),
              h('div', { className: 'trend ' + (k.up ? 'up' : 'down') },
                h(k.up ? Icons.TrendingUp : Icons.TrendingDown, { size: 14 }), k.trend,
              ),
            ),
            h('div', { className: 'kpi-icon', style: { background: 'var(--bg-subtle)', color: k.color } }, h(k.icon, { size: 20 })),
          ),
        )),
      ),
      h('div', { style: { display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 20 } },
        h('div', { className: 'card p-20' },
          h('div', { className: 'flex jc-sb ai-c mb-16' },
            h('div', { style: { fontWeight: 800, fontSize: 15 } }, 'الإيرادات الشهرية'),
            h('div', { className: 'flex gap-8' },
              h('span', { className: 'chip', style: { background: 'var(--accent-soft)', color: 'var(--accent)' } }, '● إيرادات'),
              h('span', { className: 'chip' }, '● مصروفات'),
            ),
          ),
          h(LineChart, { data: [120, 145, 180, 165, 210, 195, 240, 260, 285, 305, 325, 342], expenses: [80, 95, 110, 100, 130, 120, 150, 160, 175, 185, 195, 210] }),
        ),
        h('div', { className: 'card p-20' },
          h('div', { style: { fontWeight: 800, fontSize: 15, marginBottom: 16 } }, 'أكثر الإجراءات طلباً'),
          [
            { name: 'كشف وفحص', count: 142, color: 'var(--accent)' },
            { name: 'تنظيف وتلميع', count: 98, color: 'var(--info)' },
            { name: 'حشو كومبوزيت', count: 76, color: 'var(--success)' },
            { name: 'حشو عصب', count: 45, color: 'var(--warning)' },
            { name: 'تبييض', count: 28, color: 'var(--purple)' },
          ].map((p, i) => h('div', { key: i, style: { marginBottom: 12 } },
            h('div', { className: 'flex jc-sb ai-c mb-4' },
              h('span', { style: { fontSize: 13, fontWeight: 600 } }, p.name),
              h('span', { style: { fontSize: 13, fontWeight: 800 } }, p.count),
            ),
            h('div', { className: 'progress' }, h('div', { className: 'progress-bar', style: { width: (p.count / 142 * 100) + '%', background: p.color } })),
          )),
        ),
      ),
      h('div', { className: 'grid cols-3 mt-16' },
        h('div', { className: 'card p-20' },
          h('div', { style: { fontWeight: 800, fontSize: 14, marginBottom: 12 } }, 'توزيع المرضى حسب العمر'),
          h(DonutChart, {
            data: [
              { label: 'أطفال', value: 18, color: 'var(--accent)' },
              { label: 'شباب', value: 42, color: 'var(--info)' },
              { label: 'كبار', value: 30, color: 'var(--success)' },
              { label: 'مسنون', value: 10, color: 'var(--warning)' },
            ],
          }),
        ),
        h('div', { className: 'card p-20' },
          h('div', { style: { fontWeight: 800, fontSize: 14, marginBottom: 12 } }, 'أفضل الأطباء'),
          window.DOCTORS.map((d, i) => h('div', { key: d.id, className: 'flex ai-c gap-10', style: { padding: '8px 0', borderBottom: i < 3 ? '1px solid var(--border)' : 'none' } },
            h('div', { style: { width: 20, fontSize: 14, fontWeight: 800, color: 'var(--text-tertiary)' } }, '#' + (i + 1)),
            h('div', { className: 'avatar sm', style: { background: d.color } }, d.avatar),
            h('div', { style: { flex: 1 } },
              h('div', { style: { fontSize: 13, fontWeight: 700 } }, d.name),
              h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, d.patients + ' مريض'),
            ),
            h('div', { style: { fontSize: 13, fontWeight: 800 } }, '★ ' + d.rating),
          )),
        ),
        h('div', { className: 'card p-20' },
          h('div', { style: { fontWeight: 800, fontSize: 14, marginBottom: 12 } }, 'مقارنة التأمين'),
          [
            { name: 'مصر للتأمين', amount: 125000, pct: 42 },
            { name: 'بوبا العربية', amount: 98000, pct: 33 },
            { name: 'أكسا', amount: 48000, pct: 16 },
            { name: 'الأهلي', amount: 27000, pct: 9 },
          ].map((t, i) => h('div', { key: i, style: { marginBottom: 12 } },
            h('div', { className: 'flex jc-sb ai-c', style: { fontSize: 12 } },
              h('span', { style: { fontWeight: 600 } }, t.name),
              h('span', { style: { color: 'var(--text-tertiary)' } }, t.pct + '%'),
            ),
            h('div', { className: 'progress', style: { marginTop: 4 } }, h('div', { className: 'progress-bar', style: { width: t.pct + '%' } })),
          )),
        ),
      ),
    ),
  );
}

function LineChart({ data, expenses }) {
  const max = Math.max(...data, ...expenses);
  const w = 100, h2 = 60;
  const path = (arr) => arr.map((v, i) => `${i === 0 ? 'M' : 'L'} ${(i / (arr.length - 1)) * w} ${h2 - (v / max) * h2}`).join(' ');
  const area = (arr) => `${path(arr)} L ${w} ${h2} L 0 ${h2} Z`;
  return h('div', null,
    h('svg', { viewBox: `0 0 ${w} ${h2}`, preserveAspectRatio: 'none', style: { width: '100%', height: 200 } },
      h('path', { d: area(data), fill: 'var(--accent)', fillOpacity: 0.15 }),
      h('path', { d: path(data), fill: 'none', stroke: 'var(--accent)', strokeWidth: 0.6, strokeLinecap: 'round' }),
      h('path', { d: path(expenses), fill: 'none', stroke: 'var(--text-tertiary)', strokeWidth: 0.5, strokeDasharray: '2 1' }),
    ),
    h('div', { className: 'flex jc-sb', style: { fontSize: 10, color: 'var(--text-tertiary)', marginTop: 8 } },
      ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'].map((m, i) => h('span', { key: i }, m.slice(0, 3))),
    ),
  );
}

function DonutChart({ data }) {
  const total = data.reduce((s, d) => s + d.value, 0);
  let offset = 0;
  const C = 2 * Math.PI * 40;
  return h('div', { style: { display: 'flex', alignItems: 'center', gap: 16 } },
    h('svg', { width: 120, height: 120, viewBox: '0 0 120 120' },
      data.map((d, i) => {
        const pct = d.value / total;
        const dash = pct * C;
        const seg = h('circle', {
          key: i, cx: 60, cy: 60, r: 40, fill: 'none', stroke: d.color, strokeWidth: 20,
          strokeDasharray: `${dash} ${C - dash}`, strokeDashoffset: -offset,
          transform: 'rotate(-90 60 60)',
        });
        offset += dash;
        return seg;
      }),
    ),
    h('div', { style: { flex: 1 } },
      data.map((d, i) => h('div', { key: i, className: 'flex ai-c gap-8', style: { padding: '4px 0', fontSize: 12 } },
        h('div', { style: { width: 10, height: 10, borderRadius: 2, background: d.color } }),
        h('span', { style: { flex: 1 } }, d.label),
        h('span', { style: { fontWeight: 700 } }, d.value + '%'),
      )),
    ),
  );
}

// ==================== Messages ====================
function Messages() {
  const [active, setActive] = useState('M1');
  const [text, setText] = useState('');
  const [thread, setThread] = useState([
    { id: 1, from: 'them', text: 'صباح الخير، هل أشعة المريض أحمد جاهزة؟', time: '10:22' },
    { id: 2, from: 'me', text: 'صباح النور، نعم تم رفعها منذ قليل على ملفه', time: '10:23' },
    { id: 3, from: 'them', text: 'ممتاز، سأراجعها الآن. شكراً!', time: '10:24' },
  ]);

  const activeThread = window.MESSAGES.find(m => m.id === active);

  return h('div', { className: 'fade-in', style: { height: '100%' } },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'الدردشة الداخلية'),
        h('div', { className: 'page-subtitle' }, 'تواصل سريع بين أعضاء الفريق'),
      ),
    ),
    h('div', { className: 'page-content', style: { height: 'calc(100% - 100px)' } },
      h('div', { className: 'card', style: { display: 'grid', gridTemplateColumns: '300px 1fr', height: 'calc(100vh - 180px)', overflow: 'hidden' } },
        h('div', { style: { borderInlineEnd: '1px solid var(--border)', overflow: 'auto' } },
          h('div', { style: { padding: 12, borderBottom: '1px solid var(--border)' } },
            h('input', { className: 'input', placeholder: 'بحث في المحادثات...', style: { padding: 8, fontSize: 13 } }),
          ),
          window.MESSAGES.map(m => h('div', {
            key: m.id,
            onClick: () => setActive(m.id),
            style: {
              padding: '12px 14px', borderBottom: '1px solid var(--border)', cursor: 'pointer',
              background: active === m.id ? 'var(--accent-soft)' : 'transparent',
              display: 'flex', gap: 10, alignItems: 'center',
            },
          },
            h('div', { style: { position: 'relative' } },
              h('div', { className: 'avatar sm' }, m.avatar),
              m.online ? h('div', { style: { position: 'absolute', bottom: -2, insetInlineEnd: -2, width: 10, height: 10, borderRadius: '50%', background: 'var(--success)', border: '2px solid var(--bg-elevated)' } }) : null,
            ),
            h('div', { style: { flex: 1, minWidth: 0 } },
              h('div', { className: 'flex jc-sb ai-c' },
                h('div', { style: { fontSize: 13, fontWeight: 700, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, m.from),
                h('div', { style: { fontSize: 10, color: 'var(--text-tertiary)' } }, m.time),
              ),
              h('div', { className: 'flex jc-sb ai-c' },
                h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 } }, m.preview),
                m.unread ? h('span', { style: { background: 'var(--accent)', color: '#fff', fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 999 } }, m.unread) : null,
              ),
            ),
          )),
        ),
        h('div', { style: { display: 'flex', flexDirection: 'column', overflow: 'hidden' } },
          h('div', { style: { padding: 14, borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12 } },
            h('div', { className: 'avatar sm' }, activeThread.avatar),
            h('div', { style: { flex: 1 } },
              h('div', { style: { fontWeight: 700 } }, activeThread.from),
              h('div', { style: { fontSize: 11, color: activeThread.online ? 'var(--success)' : 'var(--text-tertiary)' } }, activeThread.online ? 'متصل الآن' : 'غير متصل'),
            ),
            h('button', { className: 'icon-btn' }, h(Icons.Phone, { size: 16 })),
            h('button', { className: 'icon-btn' }, h(Icons.MoreHorizontal, { size: 16 })),
          ),
          h('div', { style: { flex: 1, overflowY: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 10 } },
            thread.map(m => h('div', {
              key: m.id,
              style: { display: 'flex', justifyContent: m.from === 'me' ? 'flex-start' : 'flex-end' },
            },
              h('div', {
                style: {
                  maxWidth: '70%', padding: '10px 14px',
                  background: m.from === 'me' ? 'var(--accent)' : 'var(--bg-subtle)',
                  color: m.from === 'me' ? '#fff' : 'var(--text-primary)',
                  borderRadius: m.from === 'me' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
                  fontSize: 13,
                },
              },
                h('div', null, m.text),
                h('div', { style: { fontSize: 10, opacity: 0.7, marginTop: 4, textAlign: 'end' } }, m.time),
              ),
            )),
          ),
          h('div', { style: { padding: 14, borderTop: '1px solid var(--border)', display: 'flex', gap: 8, alignItems: 'center' } },
            h('button', { className: 'icon-btn' }, h(Icons.Paperclip, { size: 18 })),
            h('input', {
              className: 'input', placeholder: 'اكتب رسالة...', value: text,
              onChange: (e) => setText(e.target.value),
              onKeyDown: (e) => {
                if (e.key === 'Enter' && text.trim()) {
                  setThread([...thread, { id: Date.now(), from: 'me', text, time: 'الآن' }]);
                  setText('');
                }
              },
            }),
            h('button', {
              className: 'btn primary',
              onClick: () => {
                if (!text.trim()) return;
                setThread([...thread, { id: Date.now(), from: 'me', text, time: 'الآن' }]);
                setText('');
              },
            }, h(Icons.Send, { size: 16 })),
          ),
        ),
      ),
    ),
  );
}

// ==================== Settings ====================
function Settings() {
  const { theme, setTheme, density, setDensity, clinicName, setClinicName } = useContext(AppContext);
  const [tab, setTab] = useState('general');

  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'الإعدادات'),
        h('div', { className: 'page-subtitle' }, 'إدارة إعدادات العيادة والنظام'),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { style: { display: 'grid', gridTemplateColumns: '240px 1fr', gap: 20 } },
        h('div', { className: 'card', style: { padding: 10, height: 'fit-content' } },
          [
            { id: 'general', label: 'عام', icon: Icons.Settings },
            { id: 'clinic', label: 'بيانات العيادة', icon: Icons.Building },
            { id: 'appearance', label: 'المظهر', icon: Icons.Sliders },
            { id: 'notifications', label: 'الإشعارات', icon: Icons.Bell },
            { id: 'billing-s', label: 'الفوترة والضرائب', icon: Icons.CreditCard },
            { id: 'integrations', label: 'التكاملات', icon: Icons.Zap },
            { id: 'security', label: 'الأمان', icon: Icons.Shield },
            { id: 'backup', label: 'النسخ الاحتياطي', icon: Icons.Database },
          ].map(s => h('button', {
            key: s.id,
            className: 'nav-item' + (tab === s.id ? ' active' : ''),
            onClick: () => setTab(s.id),
          },
            h('span', { className: 'icon-box' }, h(s.icon, { size: 16 })),
            h('span', null, s.label),
          )),
        ),
        h('div', { className: 'card p-24' },
          tab === 'general' && h('div', null,
            h('div', { style: { fontWeight: 800, fontSize: 16, marginBottom: 16 } }, 'الإعدادات العامة'),
            h('div', { className: 'grid', style: { gap: 16 } },
              h('div', null, h('div', { className: 'label' }, 'اللغة'), h('select', { className: 'select' }, h('option', null, 'العربية'), h('option', null, 'English'))),
              h('div', null, h('div', { className: 'label' }, 'المنطقة الزمنية'), h('select', { className: 'select' }, h('option', null, 'GMT+2 (القاهرة)'))),
              h('div', null, h('div', { className: 'label' }, 'العملة'), h('select', { className: 'select' }, h('option', null, 'الجنيه المصري (ج.م)'), h('option', null, 'الريال السعودي'))),
              h('div', null, h('div', { className: 'label' }, 'تنسيق التاريخ'), h('select', { className: 'select' }, h('option', null, 'DD-MM-YYYY'), h('option', null, 'YYYY-MM-DD'))),
            ),
          ),
          tab === 'clinic' && h('div', null,
            h('div', { style: { fontWeight: 800, fontSize: 16, marginBottom: 16 } }, 'بيانات العيادة'),
            h('div', { className: 'grid', style: { gap: 16 } },
              h('div', null, h('div', { className: 'label' }, 'اسم العيادة'), h('input', { className: 'input', value: clinicName, onChange: (e) => setClinicName(e.target.value) })),
              h('div', { className: 'grid cols-2', style: { gap: 12 } },
                h('div', null, h('div', { className: 'label' }, 'رقم الهاتف'), h('input', { className: 'input', defaultValue: '+20 2 2345 6789' })),
                h('div', null, h('div', { className: 'label' }, 'البريد الإلكتروني'), h('input', { className: 'input', defaultValue: 'info@senan.clinic' })),
              ),
              h('div', null, h('div', { className: 'label' }, 'العنوان'), h('input', { className: 'input', defaultValue: 'شارع التحرير، وسط البلد، القاهرة' })),
              h('div', null, h('div', { className: 'label' }, 'الرقم الضريبي'), h('input', { className: 'input', defaultValue: '123-456-789' })),
              h('div', null, h('div', { className: 'label' }, 'ساعات العمل'), h('input', { className: 'input', defaultValue: 'السبت - الخميس · 9 صباحاً - 9 مساءً' })),
            ),
            h('button', { className: 'btn primary mt-24' }, 'حفظ التغييرات'),
          ),
          tab === 'appearance' && h('div', null,
            h('div', { style: { fontWeight: 800, fontSize: 16, marginBottom: 16 } }, 'المظهر'),
            h('div', { className: 'label' }, 'الثيم'),
            h('div', { className: 'grid cols-3', style: { gap: 10, marginBottom: 20 } },
              [{ id: 'clean', name: 'طبي نظيف', desc: 'أبيض + تركواز هادئ' }, { id: 'luxe', name: 'فاخر داكن', desc: 'أسود + ذهبي' }, { id: 'warm', name: 'دافئ', desc: 'باستيل وأرضي' }].map(t => h('div', {
                key: t.id,
                onClick: () => setTheme(t.id),
                style: {
                  padding: 16, cursor: 'pointer', borderRadius: 'var(--radius)',
                  border: '2px solid ' + (theme === t.id ? 'var(--accent)' : 'var(--border)'),
                  background: theme === t.id ? 'var(--accent-soft)' : 'transparent',
                },
              },
                h('div', { className: 'theme-swatch', 'data-preview': t.id, style: { width: '100%', height: 50, marginBottom: 10, transform: 'none' } }),
                h('div', { style: { fontWeight: 700, fontSize: 14 } }, t.name),
                h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 } }, t.desc),
              )),
            ),
            h('div', { className: 'label' }, 'الكثافة'),
            h('div', { className: 'flex gap-8' },
              ['compact', 'comfortable'].map((d, i) => h('button', {
                key: d,
                className: 'btn ' + (density === d ? 'primary' : 'outline'),
                onClick: () => setDensity(d),
              }, i === 0 ? 'مدمجة' : 'مريحة')),
            ),
          ),
          tab === 'notifications' && h('div', null,
            h('div', { style: { fontWeight: 800, fontSize: 16, marginBottom: 16 } }, 'إعدادات الإشعارات'),
            h('div', { className: 'grid', style: { gap: 4 } },
              ['تذكيرات المواعيد (WhatsApp)', 'تذكيرات المواعيد (SMS)', 'تأكيد استلام المدفوعات', 'تنبيهات انخفاض المخزون', 'تنبيهات انتهاء الصلاحية', 'التقرير اليومي للمدير'].map((l, i) => h('label', {
                key: i,
                style: { padding: '14px 0', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer' },
              },
                h('span', { style: { fontSize: 14 } }, l),
                h(Toggle, { defaultChecked: i < 4 }),
              )),
            ),
          ),
          tab === 'billing-s' && h('div', null,
            h('div', { style: { fontWeight: 800, fontSize: 16, marginBottom: 16 } }, 'الفوترة والضرائب'),
            h('div', { className: 'grid cols-2', style: { gap: 16 } },
              h('div', null, h('div', { className: 'label' }, 'نسبة الضريبة (%)'), h('input', { className: 'input', defaultValue: '14' })),
              h('div', null, h('div', { className: 'label' }, 'بادئة الفواتير'), h('input', { className: 'input', defaultValue: 'INV-2026-' })),
              h('div', null, h('div', { className: 'label' }, 'شروط الدفع'), h('input', { className: 'input', defaultValue: 'صافي 30 يوم' })),
              h('div', null, h('div', { className: 'label' }, 'العملة الافتراضية'), h('input', { className: 'input', defaultValue: 'ج.م' })),
            ),
          ),
          tab === 'integrations' && h('div', null,
            h('div', { style: { fontWeight: 800, fontSize: 16, marginBottom: 16 } }, 'التكاملات'),
            [
              { name: 'WhatsApp Business', desc: 'إرسال التذكيرات والتأكيدات تلقائياً', on: true },
              { name: 'بوابة الدفع Fawry', desc: 'تحصيل المدفوعات أونلاين', on: true },
              { name: 'Google Calendar', desc: 'مزامنة المواعيد مع جوجل', on: false },
              { name: 'نظام التأمين الموحد', desc: 'الربط مع شركات التأمين', on: true },
              { name: 'SMS Gateway', desc: 'إرسال رسائل نصية', on: false },
            ].map((it, i) => h('div', { key: i, style: { padding: 16, border: '1px solid var(--border)', borderRadius: 'var(--radius)', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 12 } },
              h('div', { style: { width: 40, height: 40, borderRadius: 10, background: 'var(--bg-subtle)', display: 'grid', placeItems: 'center' } }, h(Icons.Zap, { size: 18 })),
              h('div', { style: { flex: 1 } },
                h('div', { style: { fontWeight: 700 } }, it.name),
                h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)' } }, it.desc),
              ),
              h(Toggle, { defaultChecked: it.on }),
            )),
          ),
          tab === 'security' && h('div', null,
            h('div', { style: { fontWeight: 800, fontSize: 16, marginBottom: 16 } }, 'الأمان'),
            h('div', { className: 'grid', style: { gap: 16 } },
              h('div', null, h('div', { className: 'label' }, 'كلمة المرور الحالية'), h('input', { className: 'input', type: 'password', defaultValue: '••••••••' })),
              h('div', null, h('div', { className: 'label' }, 'كلمة المرور الجديدة'), h('input', { className: 'input', type: 'password' })),
              h('label', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: 12, background: 'var(--bg-subtle)', borderRadius: 'var(--radius)' } },
                h('div', null,
                  h('div', { style: { fontWeight: 700 } }, 'التحقق بخطوتين'),
                  h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 } }, 'أمان إضافي لحسابك'),
                ),
                h(Toggle, { defaultChecked: true }),
              ),
            ),
          ),
          tab === 'backup' && h('div', null,
            h('div', { style: { fontWeight: 800, fontSize: 16, marginBottom: 16 } }, 'النسخ الاحتياطي'),
            h('div', { style: { padding: 16, background: 'var(--success-soft)', borderRadius: 'var(--radius)', color: 'var(--success)', fontWeight: 600, marginBottom: 16 } },
              h(Icons.Check, { size: 16, style: { display: 'inline-block', verticalAlign: 'text-bottom', marginLeft: 6 } }),
              'آخر نسخة احتياطية: اليوم 03:00 صباحاً',
            ),
            h('div', { className: 'grid cols-2', style: { gap: 12 } },
              h('button', { className: 'btn outline' }, h(Icons.Download, { size: 16 }), 'تصدير جميع البيانات'),
              h('button', { className: 'btn outline' }, h(Icons.Upload, { size: 16 }), 'استعادة من نسخة'),
            ),
          ),
        ),
      ),
    ),
  );
}

function Toggle({ defaultChecked }) {
  const [on, setOn] = useState(!!defaultChecked);
  return h('button', {
    onClick: () => setOn(!on),
    style: {
      width: 42, height: 24, borderRadius: 999, border: 'none',
      background: on ? 'var(--accent)' : 'var(--border-strong)',
      position: 'relative', cursor: 'pointer', transition: 'background 0.2s',
    },
  },
    h('div', {
      style: {
        width: 18, height: 18, borderRadius: '50%', background: '#fff',
        position: 'absolute', top: 3, insetInlineStart: on ? 21 : 3,
        transition: 'all 0.2s', boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
      },
    }),
  );
}

// ==================== Insurance ====================
function Insurance() {
  const providers = [
    { name: 'مصر للتأمين الصحي', patients: 42, claims: 18, approved: 15, pending: 3, amount: 125000, color: 'var(--accent)' },
    { name: 'بوبا العربية', patients: 28, claims: 12, approved: 11, pending: 1, amount: 98000, color: 'var(--info)' },
    { name: 'أكسا للتأمين', patients: 15, claims: 6, approved: 5, pending: 1, amount: 48000, color: 'var(--success)' },
    { name: 'الأهلي للتأمين', patients: 9, claims: 4, approved: 4, pending: 0, amount: 27000, color: 'var(--purple)' },
  ];
  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'التأمين الطبي'),
        h('div', { className: 'page-subtitle' }, '4 شركات تأمين · 40 مطالبة نشطة'),
      ),
      h('button', { className: 'btn primary' }, h(Icons.Plus, { size: 16 }), 'مطالبة جديدة'),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'grid cols-4 mb-24' },
        providers.map((p, i) => h('div', { key: i, className: 'card p-20' },
          h('div', { style: { width: 40, height: 40, borderRadius: 10, background: 'color-mix(in oklab, ' + p.color + ' 15%, var(--bg-elevated))', color: p.color, display: 'grid', placeItems: 'center', marginBottom: 12 } },
            h(Icons.Shield, { size: 20 }),
          ),
          h('div', { style: { fontWeight: 800, fontSize: 14 } }, p.name),
          h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 } }, p.patients + ' مريض'),
          h('div', { style: { fontSize: 20, fontWeight: 800, marginTop: 10 } }, window.fmtEGP(p.amount)),
          h('div', { className: 'flex gap-8 mt-8' },
            h('span', { className: 'chip success', style: { fontSize: 10 } }, p.approved + ' موافقة'),
            p.pending > 0 ? h('span', { className: 'chip warning', style: { fontSize: 10 } }, p.pending + ' معلقة') : null,
          ),
        )),
      ),
      h('div', { className: 'card', style: { overflow: 'hidden' } },
        h('div', { style: { padding: '16px 20px', borderBottom: '1px solid var(--border)', fontWeight: 800 } }, 'المطالبات الأخيرة'),
        h('table', { className: 'data-table' },
          h('thead', null, h('tr', null, ['رقم المطالبة', 'المريض', 'الشركة', 'التاريخ', 'المبلغ', 'المغطى', 'الحالة'].map((t, i) => h('th', { key: i }, t)))),
          h('tbody', null,
            [
              { id: 'CL-0142', patient: 'أحمد محمد', company: 'مصر للتأمين', date: '2026-04-12', amount: 2500, covered: 2000, status: 'approved' },
              { id: 'CL-0143', patient: 'فاطمة علي', company: 'أكسا', date: '2026-04-15', amount: 1500, covered: 1200, status: 'approved' },
              { id: 'CL-0144', patient: 'محمد عبد الرحمن', company: 'بوبا', date: '2026-04-10', amount: 4500, covered: 3600, status: 'pending' },
              { id: 'CL-0145', patient: 'نورهان إبراهيم', company: 'بوبا', date: '2026-03-28', amount: 500, covered: 0, status: 'rejected' },
            ].map(c => h('tr', { key: c.id },
              h('td', { style: { fontFamily: 'monospace', fontSize: 12, fontWeight: 700 } }, c.id),
              h('td', null, c.patient),
              h('td', null, c.company),
              h('td', { style: { fontSize: 13, color: 'var(--text-secondary)' } }, c.date),
              h('td', { style: { fontWeight: 700 } }, window.fmtEGP(c.amount)),
              h('td', { style: { fontWeight: 700, color: 'var(--success)' } }, window.fmtEGP(c.covered)),
              h('td', null, h('span', { className: 'chip ' + (c.status === 'approved' ? 'success' : c.status === 'pending' ? 'warning' : 'danger') },
                c.status === 'approved' ? 'موافق' : c.status === 'pending' ? 'قيد المراجعة' : 'مرفوض')),
            )),
          ),
        ),
      ),
    ),
  );
}

// ==================== Accounting ====================
function Accounting() {
  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'المحاسبة'),
        h('div', { className: 'page-subtitle' }, 'الإيرادات، المصروفات، والأرباح'),
      ),
      h('div', { className: 'flex gap-8' },
        h('button', { className: 'btn outline' }, h(Icons.Download, { size: 16 }), 'تقرير شهري'),
        h('button', { className: 'btn primary' }, h(Icons.Plus, { size: 16 }), 'مصروف جديد'),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'grid cols-4 mb-16' },
        [
          { label: 'الإيرادات', value: 342500, trend: '+18.4%', up: true, color: 'var(--success)' },
          { label: 'المصروفات', value: 128000, trend: '+5.2%', up: false, color: 'var(--danger)' },
          { label: 'صافي الربح', value: 214500, trend: '+22.1%', up: true, color: 'var(--accent)' },
          { label: 'هامش الربح', value: '62.6%', trend: '+2.4%', up: true, color: 'var(--purple)' },
        ].map((k, i) => h('div', { key: i, className: 'card kpi' },
          h('div', { className: 'label' }, k.label),
          h('div', { className: 'value' }, typeof k.value === 'number' ? window.fmtEGP(k.value) : k.value),
          h('div', { className: 'trend ' + (k.up ? 'up' : 'down') },
            h(k.up ? Icons.TrendingUp : Icons.TrendingDown, { size: 14 }), k.trend,
          ),
        )),
      ),
      h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 } },
        h('div', { className: 'card p-20' },
          h('div', { style: { fontWeight: 800, fontSize: 15, marginBottom: 16 } }, 'توزيع المصروفات'),
          [
            { cat: 'الرواتب', amt: 65000, pct: 50, color: 'var(--accent)' },
            { cat: 'المواد والمستلزمات', amt: 32000, pct: 25, color: 'var(--info)' },
            { cat: 'الإيجار والمرافق', amt: 18000, pct: 14, color: 'var(--warning)' },
            { cat: 'الصيانة والمعدات', amt: 8500, pct: 7, color: 'var(--success)' },
            { cat: 'أخرى', amt: 4500, pct: 4, color: 'var(--purple)' },
          ].map((e, i) => h('div', { key: i, style: { marginBottom: 12 } },
            h('div', { className: 'flex jc-sb ai-c mb-4' },
              h('span', { style: { fontSize: 13, fontWeight: 600 } }, e.cat),
              h('span', { style: { fontSize: 13, fontWeight: 800 } }, window.fmtEGP(e.amt)),
            ),
            h('div', { className: 'progress' }, h('div', { className: 'progress-bar', style: { width: e.pct + '%', background: e.color } })),
          )),
        ),
        h('div', { className: 'card p-20' },
          h('div', { style: { fontWeight: 800, fontSize: 15, marginBottom: 16 } }, 'آخر المعاملات'),
          [
            { type: 'in', desc: 'فاتورة #INV-0147', amt: 2100, date: 'اليوم 14:22' },
            { type: 'out', desc: 'راتب د. سارة', amt: 18000, date: 'اليوم 09:00' },
            { type: 'in', desc: 'فاتورة #INV-0146', amt: 800, date: 'أمس' },
            { type: 'out', desc: 'شراء مستلزمات', amt: 4500, date: 'أمس' },
            { type: 'in', desc: 'فاتورة #INV-0145', amt: 1500, date: '15 أبريل' },
            { type: 'out', desc: 'فاتورة الكهرباء', amt: 2200, date: '14 أبريل' },
          ].map((t, i) => h('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: i < 5 ? '1px solid var(--border)' : 'none' } },
            h('div', {
              style: {
                width: 32, height: 32, borderRadius: 8, display: 'grid', placeItems: 'center',
                background: t.type === 'in' ? 'var(--success-soft)' : 'var(--danger-soft)',
                color: t.type === 'in' ? 'var(--success)' : 'var(--danger)',
              },
            }, h(t.type === 'in' ? Icons.TrendingUp : Icons.TrendingDown, { size: 16 })),
            h('div', { style: { flex: 1 } },
              h('div', { style: { fontSize: 13, fontWeight: 600 } }, t.desc),
              h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, t.date),
            ),
            h('div', { style: { fontSize: 14, fontWeight: 800, color: t.type === 'in' ? 'var(--success)' : 'var(--danger)' } },
              (t.type === 'in' ? '+' : '-') + window.fmtEGP(t.amt),
            ),
          )),
        ),
      ),
    ),
  );
}

// ==================== Prescriptions (all) ====================
function Prescriptions() {
  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'الوصفات الطبية'),
        h('div', { className: 'page-subtitle' }, window.PRESCRIPTIONS.length + ' وصفة مسجلة'),
      ),
      h('button', { className: 'btn primary' }, h(Icons.Plus, { size: 16 }), 'وصفة جديدة'),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'grid', style: { gap: 12 } },
        window.PRESCRIPTIONS.map(r => h('div', { key: r.id, className: 'card p-20' },
          h('div', { className: 'flex jc-sb ai-c mb-12' },
            h('div', null,
              h('div', { style: { fontWeight: 800, fontSize: 15 } }, r.patient),
              h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)' } }, `${r.id} · ${r.date} · ${r.doctor}`),
            ),
            h('div', { className: 'flex gap-4' },
              h('button', { className: 'btn outline sm' }, h(Icons.Printer, { size: 14 }), 'طباعة'),
              h('button', { className: 'btn outline sm' }, h(Icons.Send, { size: 14 }), 'إرسال للصيدلية'),
            ),
          ),
          h('div', { className: 'grid cols-2', style: { gap: 8 } },
            r.meds.map((m, i) => h('div', { key: i, style: { padding: 12, background: 'var(--bg-subtle)', borderRadius: 'var(--radius)' } },
              h('div', { className: 'flex ai-c gap-8 mb-4' },
                h('div', { style: { color: 'var(--accent)' } }, h(Icons.Pill, { size: 16 })),
                h('div', { style: { fontWeight: 700, fontSize: 14 } }, m.name),
              ),
              h('div', { style: { fontSize: 12, color: 'var(--text-secondary)', marginTop: 6 } }, m.dose),
              h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 } }, 'المدة: ' + m.duration),
            )),
          ),
        )),
      ),
    ),
  );
}

// ==================== Xrays (all) ====================
function Xrays() {
  const imgs = [
    { patient: 'أحمد محمد', date: '2026-04-10', type: 'بانوراما', label: 'فحص شامل' },
    { patient: 'فاطمة علي', date: '2026-04-15', type: 'ديجيتال', label: 'ضرس 36' },
    { patient: 'محمد عبد الرحمن', date: '2026-04-12', type: 'بانوراما', label: 'قبل التقويم' },
    { patient: 'نورهان إبراهيم', date: '2026-03-28', type: 'ديجيتال', label: 'قناة جذر 26' },
    { patient: 'يوسف طارق', date: '2026-04-14', type: 'ديجيتال', label: 'لبنية' },
    { patient: 'سلمى حسام', date: '2026-04-16', type: 'بانوراما', label: 'تركيب تاج' },
    { patient: 'رنا أشرف', date: '2026-04-17', type: 'ديجيتال', label: 'تسوس أمامي' },
    { patient: 'عمر شريف', date: '2026-02-20', type: 'بانوراما', label: 'فحص دوري' },
  ];
  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'الأشعة والصور'),
        h('div', { className: 'page-subtitle' }, imgs.length + ' صورة · تصفح وإدارة الأشعة'),
      ),
      h('button', { className: 'btn primary' }, h(Icons.Upload, { size: 16 }), 'رفع صورة'),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'grid cols-4' },
        imgs.map((im, i) => h('div', { key: i, className: 'card', style: { overflow: 'hidden', cursor: 'pointer' } },
          h('div', {
            style: {
              aspectRatio: '4/3',
              background: 'repeating-linear-gradient(45deg, #2a2a3a, #2a2a3a 10px, #3a3a4a 10px, #3a3a4a 20px)',
              display: 'grid', placeItems: 'center', color: '#fff', position: 'relative',
            },
          },
            h('div', { style: { textAlign: 'center', opacity: 0.55 } },
              h(Icons.Image, { size: 36 }),
              h('div', { style: { fontFamily: 'monospace', fontSize: 10, marginTop: 6 } }, im.type.toUpperCase()),
            ),
            h('span', { className: 'chip', style: { position: 'absolute', top: 10, insetInlineEnd: 10, background: 'rgba(0,0,0,0.5)', color: '#fff', border: 'none' } }, im.type),
          ),
          h('div', { className: 'p-16' },
            h('div', { style: { fontWeight: 700, fontSize: 13 } }, im.label),
            h('div', { style: { fontSize: 12, color: 'var(--text-secondary)', marginTop: 2 } }, im.patient),
            h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 } }, im.date),
          ),
        )),
      ),
    ),
  );
}

// ==================== Patient Portal ====================
function PatientPortal() {
  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'بوابة المريض'),
        h('div', { className: 'page-subtitle' }, 'معاينة — هكذا يرى المريض بياناته على الموبايل'),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { style: { display: 'grid', gridTemplateColumns: '360px 1fr', gap: 24 } },
        // Phone preview
        h('div', { style: { display: 'flex', justifyContent: 'center' } },
          h('div', {
            style: {
              width: 340, height: 680, background: '#0b1020', borderRadius: 40, padding: 10,
              boxShadow: 'var(--shadow-lg)', position: 'relative',
            },
          },
            h('div', {
              style: {
                width: '100%', height: '100%', background: 'var(--bg)', borderRadius: 30,
                overflow: 'hidden', display: 'flex', flexDirection: 'column', direction: 'rtl',
              },
            },
              h('div', { style: { padding: '12px 20px 8px', background: 'linear-gradient(135deg, var(--accent), var(--info))', color: '#fff' } },
                h('div', { style: { fontSize: 11, opacity: 0.9 } }, 'مساء الخير'),
                h('div', { style: { fontSize: 18, fontWeight: 800, marginTop: 2 } }, 'أحمد محمد 👋'),
                h('div', {
                  style: {
                    marginTop: 12, padding: 12, background: 'rgba(255,255,255,0.15)',
                    borderRadius: 12, fontSize: 12,
                  },
                },
                  h('div', { style: { opacity: 0.9 } }, 'موعدك القادم'),
                  h('div', { style: { fontSize: 15, fontWeight: 800, marginTop: 4 } }, '22 أبريل · 14:30'),
                  h('div', { style: { opacity: 0.9, marginTop: 2 } }, 'متابعة حشو عصب — د. سارة'),
                ),
              ),
              h('div', { style: { padding: 16, overflow: 'auto', flex: 1 } },
                h('div', { style: { fontWeight: 800, fontSize: 13, marginBottom: 10 } }, 'الخدمات'),
                h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginBottom: 16 } },
                  [
                    { icon: Icons.Calendar, label: 'حجز' },
                    { icon: Icons.File, label: 'ملفي' },
                    { icon: Icons.CreditCard, label: 'فواتير' },
                    { icon: Icons.Image, label: 'أشعة' },
                  ].map((s, i) => h('div', {
                    key: i,
                    style: { background: 'var(--bg-elevated)', borderRadius: 10, padding: 8, textAlign: 'center', border: '1px solid var(--border)' },
                  },
                    h('div', { style: { color: 'var(--accent)', display: 'flex', justifyContent: 'center' } }, h(s.icon, { size: 18 })),
                    h('div', { style: { fontSize: 10, marginTop: 4, fontWeight: 600 } }, s.label),
                  )),
                ),
                h('div', { style: { fontWeight: 800, fontSize: 13, marginBottom: 10 } }, 'خطة العلاج الحالية'),
                h('div', { style: { background: 'var(--bg-elevated)', padding: 12, borderRadius: 10, border: '1px solid var(--border)', marginBottom: 12 } },
                  h('div', { style: { fontSize: 13, fontWeight: 700 } }, 'علاج شامل للفك السفلي'),
                  h('div', { className: 'flex jc-sb ai-c mt-8', style: { fontSize: 10, color: 'var(--text-tertiary)' } },
                    h('span', null, '60% مكتمل'),
                    h('span', null, '4 من 6 جلسات'),
                  ),
                  h('div', { className: 'progress mt-8' }, h('div', { className: 'progress-bar', style: { width: '60%' } })),
                ),
                h('div', { style: { fontWeight: 800, fontSize: 13, marginBottom: 10 } }, 'آخر الوصفات'),
                h('div', { style: { background: 'var(--bg-elevated)', padding: 12, borderRadius: 10, border: '1px solid var(--border)' } },
                  h('div', { style: { fontSize: 12, fontWeight: 700 } }, 'أموكسيسيلين 500mg'),
                  h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 } }, 'كبسولة كل 8 ساعات · 7 أيام'),
                ),
              ),
            ),
          ),
        ),
        // Features list
        h('div', null,
          h('div', { style: { fontWeight: 800, fontSize: 16, marginBottom: 16 } }, 'ما يستطيع المريض فعله'),
          h('div', { className: 'grid cols-2', style: { gap: 12 } },
            [
              { icon: Icons.Calendar, title: 'حجز وإدارة المواعيد', desc: 'حجز، تأجيل، أو إلغاء المواعيد أونلاين' },
              { icon: Icons.File, title: 'عرض الملف الطبي', desc: 'تاريخ العلاج، الأشعة، والملاحظات' },
              { icon: Icons.CreditCard, title: 'الفواتير والدفع', desc: 'سداد الفواتير عبر بوابة الدفع' },
              { icon: Icons.Pill, title: 'الوصفات الطبية', desc: 'عرض الوصفات وطلب إعادة صرفها' },
              { icon: Icons.Bell, title: 'التذكيرات', desc: 'تنبيهات قبل الموعد بيوم' },
              { icon: Icons.MessageCircle, title: 'التواصل مع العيادة', desc: 'رسائل مباشرة مع الاستقبال' },
            ].map((f, i) => h('div', { key: i, className: 'card p-16' },
              h('div', { style: { width: 40, height: 40, borderRadius: 10, background: 'var(--accent-soft)', color: 'var(--accent)', display: 'grid', placeItems: 'center', marginBottom: 10 } }, h(f.icon, { size: 18 })),
              h('div', { style: { fontWeight: 700, fontSize: 14, marginBottom: 2 } }, f.title),
              h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)' } }, f.desc),
            )),
          ),
        ),
      ),
    ),
  );
}

window.Screens = Object.assign(window.Screens || {}, {
  NewAppointment, Billing, NewInvoice, Treatments, Inventory, Staff, Reports,
  Messages, Settings, Insurance, Accounting, Prescriptions, Xrays, PatientPortal,
});
