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

// ==================== Patient File ====================
function PatientFile() {
  const { screenParams, setScreen, toast, patients, setPatients, invoices, appointments } = useContext(AppContext);

  // Get real data with fallback to window globals
  const allPatients = (patients && patients.length) ? patients : (window.PATIENTS || []);
  const allInvoices = (invoices && invoices.length) ? invoices : (window.INVOICES || []);
  const allAppts    = (appointments && appointments.length) ? appointments : (window.APPOINTMENTS || []);

  const patientId = screenParams?.patientId;
  const patient = allPatients.find(p => p.id === patientId) || allPatients[0];
  const [tab, setTab] = useState('overview');
  const [showEdit, setShowEdit] = useState(false);

  if (!patient) return h('div', { className: 'page-content', style: { padding: 40, textAlign: 'center' } },
    h('div', { style: { color: 'var(--text-tertiary)' } }, 'لم يتم العثور على المريض'),
    h('button', { className: 'btn primary mt-16', onClick: () => setScreen('patients') }, 'العودة للمرضى'),
  );

  const patientInvoices = allInvoices.filter(i => i.patientId === patient.id);
  const patientAppts    = allAppts.filter(a => a.patientId === patient.id);
  const patientRx = (window.PRESCRIPTIONS || []).filter(r => r.patient === patient.name);

  return h('div', { className: 'fade-in' },
    showEdit ? h(EditPatientModal, {
      patient,
      onClose: () => setShowEdit(false),
      onSaved: (updated) => { setPatients(prev => prev.map(p => p.id === updated.id ? updated : p)); setShowEdit(false); },
    }) : null,
    h('div', { className: 'page-header' },
      h('div', { className: 'flex gap-12 ai-c' },
        h('button', { className: 'icon-btn', onClick: () => setScreen('patients') },
          h(Icons.ChevronRight, { size: 18 }),
        ),
        h('div', { className: 'avatar lg' }, patient.avatar),
        h('div', null,
          h('div', { className: 'page-title', style: { display: 'flex', alignItems: 'center', gap: 8 } },
            patient.name,
            h('span', { className: 'chip success' }, 'نشط'),
          ),
          h('div', { className: 'page-subtitle' },
            `${patient.id} · ${patient.age} سنة · ${patient.gender} · ${patient.phone}`,
          ),
        ),
      ),
      h('div', { className: 'flex gap-8' },
        h('button', { className: 'btn outline', onClick: () => setShowEdit(true) }, h(Icons.Edit2, { size: 16 }), 'تعديل'),
        h('button', { className: 'btn outline' }, h(Icons.Printer, { size: 16 }), 'طباعة'),
        h('button', { className: 'btn primary', onClick: () => setScreen('new-appointment', { patientId: patient.id, patientName: patient.name }) }, h(Icons.Plus, { size: 16 }), 'موعد جديد'),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'tabs' },
        [
          { id: 'overview', label: 'نظرة عامة' },
          { id: 'chart', label: 'مخطط الأسنان' },
          { id: 'treatments', label: 'العلاجات' },
          { id: 'appointments', label: 'المواعيد' },
          { id: 'invoices', label: 'الفواتير' },
          { id: 'prescriptions', label: 'الوصفات' },
          { id: 'xrays', label: 'الأشعة' },
          { id: 'notes', label: 'الملاحظات' },
        ].map(t => h('button', {
          key: t.id,
          className: 'tab' + (tab === t.id ? ' active' : ''),
          onClick: () => setTab(t.id),
        }, t.label)),
      ),

      tab === 'overview' && h(PatientOverview, { patient, patientInvoices, patientAppts }),
      tab === 'chart' && h(DentalChart, { patient }),
      tab === 'treatments' && h(TreatmentsList, { patient }),
      tab === 'appointments' && h(PatientAppts, { appts: patientAppts }),
      tab === 'invoices' && h(PatientInvoices, { invoices: patientInvoices }),
      tab === 'prescriptions' && h(PatientRx, { rxs: patientRx }),
      tab === 'xrays' && h(XrayGallery),
      tab === 'notes' && h(PatientNotes, { patient }),
    ),
  );
}

function PatientOverview({ patient, patientInvoices, patientAppts }) {
  const totalBilled = patientInvoices.reduce((s, i) => s + i.total, 0);
  const totalPaid = patientInvoices.reduce((s, i) => s + i.paid, 0);
  return h('div', { style: { display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 20 } },
    h('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },
      h('div', { className: 'card p-20' },
        h('div', { className: 'mb-16', style: { fontWeight: 800, fontSize: 15 } }, 'معلومات الاتصال'),
        h('div', { className: 'grid cols-2', style: { gap: 16 } },
          [
            { label: 'البريد الإلكتروني', value: patient.email, icon: Icons.Mail },
            { label: 'رقم الهاتف', value: patient.phone, icon: Icons.Phone, ltr: true },
            { label: 'الطبيب المعالج', value: patient.doctor, icon: Icons.Stethoscope },
            { label: 'شركة التأمين', value: patient.insurance, icon: Icons.Shield },
          ].map((f, i) => h('div', { key: i, className: 'flex gap-12 ai-c' },
            h('div', { style: { width: 36, height: 36, borderRadius: 10, background: 'var(--bg-subtle)', display: 'grid', placeItems: 'center', color: 'var(--accent)' } }, h(f.icon, { size: 16 })),
            h('div', null,
              h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, f.label),
              h('div', { style: { fontSize: 14, fontWeight: 600, direction: f.ltr ? 'ltr' : 'rtl', textAlign: 'right' } }, f.value),
            ),
          )),
        ),
      ),
      h('div', { className: 'card p-20' },
        h('div', { className: 'flex jc-sb ai-c mb-16' },
          h('div', { style: { fontWeight: 800, fontSize: 15 } }, 'السجل الطبي'),
          h('button', { className: 'btn ghost sm' }, h(Icons.Edit, { size: 14 }), 'تعديل'),
        ),
        h('div', { className: 'grid cols-3', style: { gap: 12 } },
          [
            { label: 'الحساسية', value: (patient.notes || '').includes('حساسية') ? 'البنسلين' : 'لا يوجد', color: (patient.notes || '').includes('حساسية') ? 'var(--danger)' : 'var(--success)' },
            { label: 'ضغط الدم', value: patient.age > 40 ? 'مرتفع' : 'طبيعي', color: patient.age > 40 ? 'var(--warning)' : 'var(--success)' },
            { label: 'فصيلة الدم', value: 'O+', color: 'var(--text-primary)' },
            { label: 'الحالة العامة', value: 'مستقرة', color: 'var(--success)' },
            { label: 'التدخين', value: 'لا', color: 'var(--success)' },
            { label: 'الحمل', value: patient.gender === 'أنثى' ? 'لا' : '—', color: 'var(--text-tertiary)' },
          ].map((f, i) => h('div', { key: i, style: { padding: 12, background: 'var(--bg-subtle)', borderRadius: 'var(--radius)' } },
            h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', fontWeight: 600 } }, f.label),
            h('div', { style: { fontSize: 14, fontWeight: 800, color: f.color, marginTop: 4 } }, f.value),
          )),
        ),
        patient.notes ? h('div', { style: { marginTop: 16, padding: 12, background: 'var(--warning-soft)', borderRadius: 'var(--radius)', color: 'var(--warning)', fontSize: 13, fontWeight: 600 } },
          h(Icons.AlertTriangle, { size: 14, style: { display: 'inline-block', verticalAlign: 'text-bottom', marginLeft: 6 } }),
          patient.notes,
        ) : null,
      ),
      h('div', { className: 'card p-20' },
        h('div', { className: 'flex jc-sb ai-c mb-16' },
          h('div', { style: { fontWeight: 800, fontSize: 15 } }, 'آخر الأنشطة'),
          h('button', { className: 'btn ghost sm' }, 'عرض الكل'),
        ),
        h('div', { className: 'timeline' },
          [
            { time: 'اليوم 10:24', title: 'تم تحديث خطة العلاج', desc: 'إضافة حشو عصب للضرس 36', icon: Icons.Edit },
            { time: 'أمس', title: 'تم إنشاء فاتورة', desc: 'INV-2026-0142 بقيمة 2,500 ج.م', icon: Icons.CreditCard },
            { time: 'منذ 3 أيام', title: 'زيارة مكتملة', desc: 'كشف وفحص دوري مع د. سارة', icon: Icons.Check },
            { time: 'منذ أسبوع', title: 'أشعة بانوراما', desc: 'تم رفع صورة أشعة جديدة', icon: Icons.Image },
          ].map((e, i) => h('div', { key: i, className: 'timeline-item' },
            h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginBottom: 2 } }, e.time),
            h('div', { style: { fontSize: 14, fontWeight: 700, marginBottom: 2 } }, e.title),
            h('div', { style: { fontSize: 12, color: 'var(--text-secondary)' } }, e.desc),
          )),
        ),
      ),
    ),
    h('div', { style: { display: 'flex', flexDirection: 'column', gap: 16 } },
      h('div', { className: 'card p-20' },
        h('div', { style: { fontWeight: 800, fontSize: 14, marginBottom: 14 } }, 'الملخص المالي'),
        h('div', { style: { padding: 14, background: 'var(--bg-subtle)', borderRadius: 'var(--radius)', marginBottom: 10 } },
          h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, 'الرصيد المستحق'),
          h('div', { style: { fontSize: 24, fontWeight: 800, color: 'var(--danger)', marginTop: 4 } }, window.fmtEGP(patient.balance)),
        ),
        h('div', { style: { display: 'flex', gap: 8 } },
          h('div', { style: { flex: 1, padding: 12, borderRadius: 'var(--radius)', border: '1px solid var(--border)' } },
            h('div', { style: { fontSize: 10, color: 'var(--text-tertiary)' } }, 'مفوتر'),
            h('div', { style: { fontWeight: 800, fontSize: 15, marginTop: 2 } }, window.fmtEGP(totalBilled)),
          ),
          h('div', { style: { flex: 1, padding: 12, borderRadius: 'var(--radius)', border: '1px solid var(--border)' } },
            h('div', { style: { fontSize: 10, color: 'var(--text-tertiary)' } }, 'مدفوع'),
            h('div', { style: { fontWeight: 800, fontSize: 15, color: 'var(--success)', marginTop: 2 } }, window.fmtEGP(totalPaid)),
          ),
        ),
        h('button', { className: 'btn primary w-full mt-16', style: { width: '100%' } },
          h(Icons.DollarSign, { size: 16 }), 'تسجيل دفعة',
        ),
      ),
      h('div', { className: 'card p-20' },
        h('div', { style: { fontWeight: 800, fontSize: 14, marginBottom: 14 } }, 'المواعيد القادمة'),
        patient.nextVisit ? h('div', null,
          h('div', { style: { padding: 14, background: 'var(--accent-soft)', borderRadius: 'var(--radius)', color: 'var(--accent-text)' } },
            h('div', { style: { fontSize: 11, fontWeight: 600 } }, 'القادم'),
            h('div', { style: { fontSize: 16, fontWeight: 800, marginTop: 4 } }, patient.nextVisit),
            h('div', { style: { fontSize: 12, marginTop: 6 } }, 'كشف دوري · الساعة 15:00'),
          ),
        ) : h('div', { className: 'empty-state', style: { padding: 20 } },
          h('div', { style: { fontSize: 13 } }, 'لا مواعيد قادمة'),
        ),
      ),
      h('div', { className: 'card p-20' },
        h('div', { style: { fontWeight: 800, fontSize: 14, marginBottom: 14 } }, 'الوثائق'),
        h('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
          [
            { name: 'نموذج الموافقة.pdf', size: '245 KB' },
            { name: 'شهادة التأمين.pdf', size: '180 KB' },
            { name: 'أشعة بانوراما.jpg', size: '2.4 MB' },
          ].map((f, i) => h('div', {
            key: i,
            style: { padding: 10, border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' },
          },
            h('div', { style: { color: 'var(--accent)' } }, h(Icons.File, { size: 16 })),
            h('div', { style: { flex: 1, minWidth: 0, fontSize: 12 } },
              h('div', { style: { fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, f.name),
              h('div', { style: { color: 'var(--text-tertiary)', fontSize: 10 } }, f.size),
            ),
            h(Icons.Download, { size: 14, style: { color: 'var(--text-tertiary)' } }),
          )),
        ),
      ),
    ),
  );
}

// ==================== Dental Chart ====================
function DentalChart({ patient }) {
  const [selectedTooth, setSelectedTooth] = useState(null);
  const [states, setStates] = useState({ ...window.TOOTH_STATES });
  const [tool, setTool] = useState('view'); // view | cavity | filled | crown | treated | missing

  const legend = [
    { key: 'healthy', label: 'سليم', color: 'var(--bg-elevated)', border: 'var(--border-strong)' },
    { key: 'cavity', label: 'تسوس', color: 'var(--danger-soft)', border: 'var(--danger)' },
    { key: 'filled', label: 'حشو', color: 'var(--info-soft)', border: 'var(--info)' },
    { key: 'crown', label: 'تاج', color: 'var(--warning-soft)', border: 'var(--warning)' },
    { key: 'treated', label: 'علاج عصب', color: 'var(--success-soft)', border: 'var(--success)' },
    { key: 'missing', label: 'مفقود', color: 'var(--bg-subtle)', border: 'var(--text-muted)' },
  ];

  const toggleTooth = (num) => {
    if (tool === 'view') { setSelectedTooth(num); return; }
    setStates(prev => {
      const copy = { ...prev };
      if (copy[num] === tool) delete copy[num]; else copy[num] = tool;
      return copy;
    });
    setSelectedTooth(num);
  };

  const renderTooth = (num, isLower) => h('div', {
    key: num,
    className: 'tooth' + (isLower ? ' lower' : '') + (selectedTooth === num ? ' selected' : '') + (states[num] ? ' ' + states[num] : ''),
    onClick: () => toggleTooth(num),
    title: `سن رقم ${num}`,
  },
    h('div', { style: { fontSize: 16, lineHeight: 1 } }, toothEmoji(states[num])),
    h('span', null, num),
  );

  return h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20 } },
    h('div', { className: 'card p-20' },
      h('div', { className: 'flex jc-sb ai-c mb-16' },
        h('div', null,
          h('div', { style: { fontWeight: 800, fontSize: 15 } }, 'مخطط الأسنان التفاعلي (FDI)'),
          h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 } }, 'اضغط على سن لتحديد حالته'),
        ),
        h('div', { className: 'flex gap-4' },
          legend.slice(1).map(l => h('button', {
            key: l.key,
            className: 'btn sm ' + (tool === l.key ? 'primary' : 'outline'),
            onClick: () => setTool(tool === l.key ? 'view' : l.key),
            style: { fontSize: 11 },
          }, l.label)),
        ),
      ),
      h('div', { style: { background: 'var(--bg-subtle)', padding: 16, borderRadius: 'var(--radius-lg)' } },
        h('div', { style: { textAlign: 'center', fontSize: 11, color: 'var(--text-tertiary)', fontWeight: 700, marginBottom: 8 } }, 'الفك العلوي'),
        h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(16, 1fr)', gap: 4 } },
          window.TOOTH_NUMBERS_UPPER.map(n => renderTooth(n, false)),
        ),
        h('div', { style: { height: 16 } }),
        h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(16, 1fr)', gap: 4 } },
          window.TOOTH_NUMBERS_LOWER.map(n => renderTooth(n, true)),
        ),
        h('div', { style: { textAlign: 'center', fontSize: 11, color: 'var(--text-tertiary)', fontWeight: 700, marginTop: 8 } }, 'الفك السفلي'),
      ),
      h('div', { className: 'flex gap-12 wrap mt-16' },
        legend.map(l => h('div', { key: l.key, className: 'flex ai-c gap-8' },
          h('div', { style: { width: 18, height: 18, borderRadius: 4, background: l.color, border: `2px solid ${l.border}` } }),
          h('span', { style: { fontSize: 12, color: 'var(--text-secondary)' } }, l.label),
        )),
      ),
    ),
    h('div', { className: 'card p-20' },
      h('div', { style: { fontWeight: 800, fontSize: 15, marginBottom: 14 } }, 'تفاصيل السن'),
      selectedTooth
        ? h(Fragment, null,
            h('div', { style: { textAlign: 'center', padding: '20px 0', borderBottom: '1px solid var(--border)', marginBottom: 16 } },
              h('div', { style: { fontSize: 48, lineHeight: 1 } }, toothEmoji(states[selectedTooth]) || '🦷'),
              h('div', { style: { fontSize: 32, fontWeight: 800, marginTop: 8 } }, selectedTooth),
              h('div', { style: { fontSize: 13, color: 'var(--text-tertiary)' } }, toothName(selectedTooth)),
              h('span', { className: 'chip accent mt-8', style: { marginTop: 10 } }, toothStateLabel(states[selectedTooth])),
            ),
            h('div', { className: 'label' }, 'ملاحظات'),
            h('textarea', { className: 'textarea', rows: 3, placeholder: 'أضف ملاحظة على هذا السن...' }),
            h('div', { style: { marginTop: 16 } },
              h('div', { className: 'label' }, 'التاريخ العلاجي'),
              h('div', { style: { fontSize: 12, color: 'var(--text-secondary)', padding: 12, background: 'var(--bg-subtle)', borderRadius: 'var(--radius-sm)' } },
                selectedTooth === 16 ? 'فحص: 2026-04-10 — وُجد تسوس على السطح الإطباقي'
                : selectedTooth === 26 ? 'حشو كومبوزيت: 2026-03-15'
                : selectedTooth === 36 ? 'تاج زيركون: 2025-11-20'
                : 'لا يوجد سجل سابق',
              ),
            ),
            h('button', { className: 'btn primary w-full mt-16', style: { width: '100%' } },
              h(Icons.Plus, { size: 16 }), 'إضافة إجراء',
            ),
          )
        : h('div', { className: 'empty-state' },
            h('div', { className: 'empty-state-icon' }, h(Icons.Smile, { size: 24 })),
            h('div', { style: { fontSize: 13 } }, 'اضغط على سن لعرض تفاصيله'),
          ),
    ),
  );
}

function toothEmoji(state) {
  if (state === 'cavity') return '⚠';
  if (state === 'filled') return '▣';
  if (state === 'crown') return '♛';
  if (state === 'treated') return '✓';
  if (state === 'missing') return '✕';
  return '';
}
function toothStateLabel(state) {
  return { cavity: 'تسوس', filled: 'حشو', crown: 'تاج', treated: 'علاج عصب', missing: 'مفقود' }[state] || 'سليم';
}
function toothName(num) {
  const n = num % 10;
  if (n === 1) return 'قاطع أوسط';
  if (n === 2) return 'قاطع جانبي';
  if (n === 3) return 'ناب';
  if (n === 4 || n === 5) return 'ضاحك';
  return 'طاحن';
}

function TreatmentsList({ patient }) {
  const treatments = [
    { id: 'TR1', name: 'علاج شامل للفك السفلي', status: 'in-progress', progress: 60, totalCost: 8500, paid: 5000, startDate: '2026-02-15', items: 6 },
    { id: 'TR2', name: 'تبييض أسنان', status: 'completed', progress: 100, totalCost: 3000, paid: 3000, startDate: '2025-11-20', items: 3 },
  ];
  return h('div', { className: 'grid', style: { gap: 16 } },
    h('div', { className: 'flex jc-sb ai-c' },
      h('div', { style: { fontWeight: 800, fontSize: 15 } }, 'خطط العلاج'),
      h('button', { className: 'btn primary' }, h(Icons.Plus, { size: 16 }), 'خطة جديدة'),
    ),
    treatments.map(t => h('div', { key: t.id, className: 'card p-20' },
      h('div', { className: 'flex jc-sb ai-c mb-12' },
        h('div', null,
          h('div', { style: { fontWeight: 800, fontSize: 16 } }, t.name),
          h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 } }, `بدأت: ${t.startDate} · ${t.items} إجراءات`),
        ),
        h('span', { className: 'chip ' + (t.status === 'completed' ? 'success' : 'info') }, t.status === 'completed' ? 'مكتملة' : 'جارية'),
      ),
      h('div', { className: 'flex jc-sb ai-c mb-8', style: { fontSize: 12, color: 'var(--text-secondary)' } },
        h('span', null, `التقدم ${t.progress}%`),
        h('span', null, `${window.fmtEGP(t.paid)} من ${window.fmtEGP(t.totalCost)}`),
      ),
      h('div', { className: 'progress' }, h('div', { className: 'progress-bar', style: { width: t.progress + '%' } })),
    )),
  );
}

function PatientAppts({ appts }) {
  const history = [
    { date: '2026-04-12', type: 'كشف دوري', doctor: 'د. سارة', status: 'completed', duration: 30 },
    { date: '2026-03-28', type: 'حشو ضرس', doctor: 'د. سارة', status: 'completed', duration: 60 },
    { date: '2026-02-15', type: 'أشعة بانوراما', doctor: 'د. خالد', status: 'completed', duration: 15 },
    { date: '2026-01-20', type: 'تنظيف وتلميع', doctor: 'د. سارة', status: 'completed', duration: 45 },
  ];
  return 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,
        history.map((a, i) => h('tr', { key: i },
          h('td', { style: { fontWeight: 600 } }, a.date),
          h('td', null, a.type),
          h('td', null, a.doctor),
          h('td', null, a.duration + ' د'),
          h('td', null, h('span', { className: 'chip success' }, 'مكتمل')),
          h('td', null, h('button', { className: 'btn ghost sm' }, 'عرض')),
        )),
      ),
    ),
  );
}

function PatientInvoices({ invoices }) {
  return 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,
        invoices.map(inv => h('tr', { key: inv.id },
          h('td', { style: { fontFamily: 'monospace', fontSize: 12 } }, inv.id),
          h('td', null, inv.date),
          h('td', { style: { fontWeight: 700 } }, window.fmtEGP(inv.total)),
          h('td', { style: { color: 'var(--success)' } }, 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('button', { className: 'btn ghost sm' }, 'طباعة')),
        )),
      ),
    ),
  );
}

function PatientRx({ rxs }) {
  return h('div', { className: 'grid', style: { gap: 16 } },
    h('div', { className: 'flex jc-sb ai-c' },
      h('div', { style: { fontWeight: 800, fontSize: 15 } }, 'الوصفات الطبية'),
      h('button', { className: 'btn primary' }, h(Icons.Plus, { size: 16 }), 'وصفة جديدة'),
    ),
    rxs.length > 0 ? rxs.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 } }, r.id),
          h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)' } }, `${r.date} · ${r.doctor}`),
        ),
        h('div', { className: 'flex gap-8' },
          h('button', { className: 'btn ghost sm' }, h(Icons.Printer, { size: 14 })),
          h('button', { className: 'btn ghost sm' }, h(Icons.Send, { size: 14 })),
        ),
      ),
      r.meds.map((m, i) => h('div', { key: i, style: { padding: 12, background: 'var(--bg-subtle)', borderRadius: 'var(--radius)', marginBottom: 8 } },
        h('div', { style: { fontWeight: 700, fontSize: 14 } }, m.name),
        h('div', { style: { fontSize: 12, color: 'var(--text-secondary)', marginTop: 4 } },
          h('span', null, 'الجرعة: ', m.dose), ' · ',
          h('span', null, 'المدة: ', m.duration),
        ),
      )),
    )) : h('div', { className: 'card empty-state' },
      h('div', { className: 'empty-state-icon' }, h(Icons.Pill, { size: 24 })),
      h('div', null, 'لا توجد وصفات مسجلة'),
    ),
  );
}

function XrayGallery() {
  const imgs = [
    { date: '2026-04-10', type: 'بانوراما', label: 'فحص شامل' },
    { date: '2026-03-15', type: 'ديجيتال', label: 'ضرس 36' },
    { date: '2026-02-20', type: 'بانوراما', label: 'قبل التقويم' },
    { date: '2025-11-10', type: 'ديجيتال', label: 'قناة جذر 26' },
  ];
  return h('div', null,
    h('div', { className: 'flex jc-sb ai-c mb-16' },
      h('div', { style: { fontWeight: 800, fontSize: 15 } }, 'الأشعة والصور'),
      h('button', { className: 'btn primary' }, h(Icons.Upload, { size: 16 }), 'رفع صورة'),
    ),
    h('div', { className: 'grid cols-4', style: { gap: 16 } },
      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 8px, #3a3a4a 8px, #3a3a4a 16px)`,
            display: 'grid', placeItems: 'center', color: '#fff', position: 'relative',
          },
        },
          h('div', { style: { textAlign: 'center', opacity: 0.6 } },
            h(Icons.Image, { size: 32 }),
            h('div', { style: { fontFamily: 'monospace', fontSize: 10, marginTop: 8 } }, im.type.toUpperCase()),
          ),
        ),
        h('div', { className: 'p-16' },
          h('div', { style: { fontWeight: 700, fontSize: 14 } }, im.label),
          h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 } }, im.date),
        ),
      )),
    ),
  );
}

function PatientNotes({ patient }) {
  const [notes, setNotes] = useState([
    { id: 1, text: 'المريض يعاني من حساسية تجاه البنسلين — استخدام كلينداميسين كبديل.', date: '2026-04-12', author: 'د. سارة' },
    { id: 2, text: 'يفضل مواعيد المساء بسبب ظروف العمل.', date: '2026-03-28', author: 'استقبال' },
  ]);
  const [newNote, setNewNote] = useState('');
  return h('div', null,
    h('div', { className: 'card p-20 mb-16' },
      h('div', { className: 'label' }, 'إضافة ملاحظة جديدة'),
      h('textarea', {
        className: 'textarea', rows: 3,
        value: newNote,
        placeholder: 'اكتب ملاحظة...',
        onChange: (e) => setNewNote(e.target.value),
      }),
      h('div', { className: 'flex jc-sb ai-c mt-8' },
        h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, 'مرئية لجميع الأطباء'),
        h('button', {
          className: 'btn primary sm',
          onClick: () => {
            if (!newNote.trim()) return;
            setNotes([{ id: Date.now(), text: newNote, date: '2026-04-18', author: 'أنت' }, ...notes]);
            setNewNote('');
          },
        }, 'إضافة'),
      ),
    ),
    h('div', { className: 'grid', style: { gap: 10 } },
      notes.map(n => h('div', { key: n.id, className: 'card p-16' },
        h('div', { className: 'flex jc-sb ai-c mb-8' },
          h('div', { style: { fontSize: 12, fontWeight: 700 } }, n.author),
          h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, n.date),
        ),
        h('div', { style: { fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.7 } }, n.text),
      )),
    ),
  );
}

window.Screens = window.Screens || {};
window.Screens.PatientFile = PatientFile;
window.Screens.DentalChartPage = function() {
  const { patients, setScreen } = React.useContext(AppContext);
  const allPts = (patients && patients.length) ? patients : (window.PATIENTS || []);
  const [selId, setSel] = React.useState(allPts[0]?.id || null);
  const patient = allPts.find(p => p.id === selId) || allPts[0];

  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'مخطط الأسنان التفاعلي'),
        h('div', { className: 'page-subtitle' }, patient ? patient.name : 'اختر مريض'),
      ),
      h('div', { className: 'flex gap-8' },
        h('select', {
          className: 'select',
          value: selId || '',
          onChange: e => setSel(e.target.value),
          style: { minWidth: 200 },
        }, allPts.map(p => h('option', { key: p.id, value: p.id }, p.name))),
      ),
    ),
    patient
      ? h('div', { className: 'page-content' }, h(DentalChart, { patient }))
      : h('div', { className: 'page-content', style: { textAlign: 'center', padding: 40, color: 'var(--text-tertiary)' } }, 'لا يوجد مرضى'),
  );
};
