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

// ==================== Add Patient Modal ====================
function AddPatientModal({ onClose, onSaved }) {
  const { clinicId, toast, patients } = useContext(AppContext);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({ name: '', age: '', gender: 'ذكر', phone: '', location: '', email: '', notes: '' });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // مناطق موجودة من المرضى السابقين للاقتراح التلقائي
  const knownLocations = [...new Set(
    ((patients && patients.length) ? patients : (window.PATIENTS || []))
      .map(p => (p.location || '').trim())
      .filter(Boolean)
  )].sort();

  const handleSave = async () => {
    if (!form.name.trim()) { toast('الاسم مطلوب'); return; }
    setSaving(true);
    try {
      const newPatient = await DB.addPatient(clinicId, {
        name: form.name.trim(),
        age: parseInt(form.age) || null,
        gender: form.gender,
        phone: form.phone,
        location: form.location,
        email: form.email,
        notes: form.notes,
        status: 'active',
      });
      toast('تم إضافة المريض بنجاح ✅');
      onSaved(newPatient);
      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: 480, zIndex: 201, boxShadow: 'var(--shadow-lg)',
      },
    },
      h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 } },
        h('div', { style: { fontWeight: 800, fontSize: 18 } }, 'مريض جديد'),
        h('button', { className: 'icon-btn', onClick: onClose }, h(Icons.X, { size: 18 })),
      ),
      h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 } },
        h('div', { style: { gridColumn: '1/-1' } },
          h('div', { className: 'label' }, 'الاسم الكامل *'),
          h('input', { className: 'input', placeholder: 'محمد أحمد...', value: form.name, onChange: e => set('name', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'العمر'),
          h('input', { className: 'input', type: 'number', placeholder: '30', value: form.age, onChange: e => set('age', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'الجنس'),
          h('select', { className: 'select', value: form.gender, onChange: e => set('gender', e.target.value) },
            h('option', { value: 'ذكر' }, 'ذكر'),
            h('option', { value: 'أنثى' }, 'أنثى'),
          ),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'الهاتف'),
          h('input', { className: 'input', placeholder: '01xxxxxxxxx', value: form.phone, onChange: e => set('phone', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'المنطقة'),
          h('input', {
            className: 'input',
            placeholder: 'الرحمانية، دسوق...',
            value: form.location,
            onChange: e => set('location', e.target.value),
            list: 'known-locations-list',
          }),
          h('datalist', { id: 'known-locations-list' },
            knownLocations.map(loc => h('option', { key: loc, value: loc })),
          ),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'البريد الإلكتروني'),
          h('input', { className: 'input', type: 'email', placeholder: 'email@...', value: form.email, onChange: e => set('email', e.target.value) }),
        ),
        h('div', { style: { gridColumn: '1/-1' } },
          h('div', { className: 'label' }, 'ملاحظات'),
          h('textarea', { className: 'textarea', rows: 2, placeholder: 'أي ملاحظات...', value: form.notes, onChange: e => set('notes', e.target.value) }),
        ),
      ),
      h('div', { style: { display: 'flex', gap: 8, marginTop: 20, justifyContent: 'flex-end' } },
        h('button', { className: 'btn outline', onClick: onClose }, 'إلغاء'),
        h('button', { className: 'btn primary', disabled: saving, onClick: handleSave },
          saving ? 'جاري الحفظ...' : 'حفظ المريض',
        ),
      ),
    ),
  );
}

// ==================== Edit Patient Modal ====================
function EditPatientModal({ patient, onClose, onSaved }) {
  const { toast, patients } = useContext(AppContext);
  const [saving, setSaving] = useState(false);
  const knownLocations = [...new Set(
    ((patients && patients.length) ? patients : (window.PATIENTS || []))
      .map(p => (p.location || '').trim())
      .filter(Boolean)
  )].sort();
  const [form, setForm] = useState({
    name: patient.name || '',
    age: patient.age || '',
    gender: patient.gender || 'ذكر',
    phone: patient.phone || '',
    location: patient.location || '',
    email: patient.email || '',
    notes: patient.notes || '',
    status: patient.status || 'active',
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSave = async () => {
    if (!form.name.trim()) { toast('الاسم مطلوب'); return; }
    setSaving(true);
    try {
      const updated = await DB.updatePatient(patient.id, {
        name: form.name.trim(),
        age: parseInt(form.age) || null,
        gender: form.gender,
        phone: form.phone,
        location: form.location,
        email: form.email,
        notes: form.notes,
        status: form.status,
        avatar: window.initials(form.name.trim()),
      });
      toast('تم تحديث بيانات المريض ✅');
      onSaved(updated);
      onClose();
    } catch(e) {
      console.error(e);
      toast('حدث خطأ أثناء التحديث');
    } finally { setSaving(false); }
  };

  return h(React.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: 480, zIndex: 201, boxShadow: 'var(--shadow-lg)',
      },
    },
      h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 } },
        h('div', { style: { fontWeight: 800, fontSize: 18 } }, 'تعديل بيانات المريض'),
        h('button', { className: 'icon-btn', onClick: onClose }, h(Icons.X, { size: 18 })),
      ),
      h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 } },
        h('div', { style: { gridColumn: '1/-1' } },
          h('div', { className: 'label' }, 'الاسم الكامل *'),
          h('input', { className: 'input', value: form.name, onChange: e => set('name', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'العمر'),
          h('input', { className: 'input', type: 'number', value: form.age, onChange: e => set('age', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'الجنس'),
          h('select', { className: 'select', value: form.gender, onChange: e => set('gender', e.target.value) },
            h('option', { value: 'ذكر' }, 'ذكر'),
            h('option', { value: 'أنثى' }, 'أنثى'),
          ),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'الهاتف'),
          h('input', { className: 'input', value: form.phone, onChange: e => set('phone', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'المنطقة'),
          h('input', {
            className: 'input',
            placeholder: 'الرحمانية، دسوق...',
            value: form.location,
            onChange: e => set('location', e.target.value),
            list: 'known-locations-list-edit',
          }),
          h('datalist', { id: 'known-locations-list-edit' },
            knownLocations.map(loc => h('option', { key: loc, value: loc })),
          ),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'البريد الإلكتروني'),
          h('input', { className: 'input', type: 'email', value: form.email, onChange: e => set('email', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'الحالة'),
          h('select', { className: 'select', value: form.status, onChange: e => set('status', e.target.value) },
            h('option', { value: 'active' }, 'نشط'),
            h('option', { value: 'pending' }, 'معلق'),
            h('option', { value: 'inactive' }, 'غير نشط'),
          ),
        ),
        h('div', { style: { gridColumn: '1/-1' } },
          h('div', { className: 'label' }, 'ملاحظات'),
          h('textarea', { className: 'textarea', rows: 2, value: form.notes, onChange: e => set('notes', e.target.value) }),
        ),
      ),
      h('div', { style: { display: 'flex', gap: 8, marginTop: 20, justifyContent: 'space-between' } },
        h('button', {
          className: 'btn danger',
          disabled: saving,
          onClick: async () => {
            if (!confirm(`هل أنت متأكد من حذف المريض "${patient.name}"؟ لا يمكن التراجع عن هذا الإجراء.`)) return;
            setSaving(true);
            try {
              await DB.deletePatient(patient.id);
              toast('تم حذف المريض ✅');
              onSaved({ _deleted: true, id: patient.id });
              onClose();
            } catch(e) { console.error(e); toast('حدث خطأ أثناء الحذف'); }
            finally { setSaving(false); }
          },
        }, h(Icons.Trash, { size: 14 }), 'حذف المريض'),
        h('div', { className: 'flex gap-8' },
          h('button', { className: 'btn outline', onClick: onClose }, 'إلغاء'),
          h('button', { className: 'btn primary', disabled: saving, onClick: handleSave },
            saving ? 'جاري الحفظ...' : 'حفظ التغييرات',
          ),
        ),
      ),
    ),
  );
}

// ==================== Patients List ====================
function Patients() {
  const { setScreen, patients, setPatients, doctors, invoices, dataLoading } = useContext(AppContext);

  const LoadingIndicator = () => h('div', {
    style: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      padding: 40,
      color: 'var(--text-tertiary)',
    },
  },
    h('div', {
      style: {
        width: 40,
        height: 40,
        border: '3px solid var(--border)',
        borderTopColor: 'var(--accent)',
        borderRadius: '50%',
        animation: 'spin 0.8s linear infinite',
        marginBottom: 16,
      },
    }),
    h('div', null, 'جاري تحميل البيانات...'),
  );
  const [query, setQuery] = useState('');
  const [view, setView] = useState('table');
  const [showAdd, setShowAdd] = useState(false);
  const [editPatient, setEditPatient] = useState(null);
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [showDateFilter, setShowDateFilter] = useState(false);
  const [activeDatePreset, setActiveDatePreset] = useState('all');
  const [showFilterPanel, setShowFilterPanel] = useState(false);
  const [advFilters, setAdvFilters] = useState({ status: '', gender: '', doctor: '', location: '', ageGroup: '' });
  const setAdv = (k, v) => setAdvFilters(f => ({ ...f, [k]: f[k] === v ? '' : v }));
  const advActiveCount = Object.values(advFilters).filter(Boolean).length;
  const setPatientDateRange = (fromValue, toValue, presetKey = 'custom') => {
    setDateFrom(fromValue || '');
    setDateTo(toValue || '');
    setActiveDatePreset(presetKey);
  };
  const applyPatientDatePreset = (presetKey) => {
    const { fromValue, toValue } = window.resolveDateRangePreset
      ? window.resolveDateRangePreset(presetKey)
      : { fromValue: '', toValue: '' };
    setPatientDateRange(fromValue, toValue, presetKey);
    setShowDateFilter(false);
  };
  const clearPatientDateRange = () => {
    setPatientDateRange('', '', 'all');
    setShowDateFilter(false);
  };
  const selectedRangeLabel = window.getDateRangeLabel
    ? window.getDateRangeLabel(dateFrom, dateTo)
    : 'كل التواريخ';
  const allDoctors = (doctors && doctors.length) ? doctors : (window.DOCTORS || []);
  const allInvoices = (invoices && invoices.length) ? invoices : (window.INVOICES || []);

  const allPatients = (patients && patients.length) ? patients : (window.PATIENTS || []);
  const normalizeText = (value) => String(value || '').trim().toLowerCase();
  const getPatientRegistrationDate = (patient) => String(
    patient.created_at ||
    patient.createdAt ||
    patient.registrationDate ||
    patient.date ||
    ''
  ).slice(0, 10);
  const getPatientDoctorNames = (patient) => {
    const names = new Set();
    const patientId = normalizeText(patient.id);
    const patientName = normalizeText(patient.name);

    allInvoices.forEach(inv => {
      const invoicePatientId = normalizeText(inv.patientId || inv.patient_id);
      const invoicePatientName = normalizeText(inv.patient || '');
      const matchesPatient = (patientId && invoicePatientId === patientId) ||
        (patientName && invoicePatientName === patientName);
      if (!matchesPatient) return;

      const doctorName = String(
        inv.doctorName ||
        allDoctors.find(d => normalizeText(d.id) === normalizeText(inv.doctorId))?.name ||
        ''
      ).trim();
      if (doctorName) names.add(doctorName);
    });

    const fallbackDoctor = String(patient.doctor || '').trim();
    if (fallbackDoctor) names.add(fallbackDoctor);

    return [...names];
  };
  const getPatientDoctorLabel = (patient) => {
    const names = getPatientDoctorNames(patient);
    return names.length ? names.join('، ') : (patient.doctor || '—');
  };
  const knownLocations = [...new Set(
    allPatients
      .map(p => (p.location || '').trim())
      .filter(Boolean)
  )].sort();
  const totalPatientsCount = allPatients.length;
  const dateFilteredPatients = allPatients.filter(p => {
    const registeredAt = getPatientRegistrationDate(p);
    if (dateFrom && (!registeredAt || registeredAt < dateFrom)) return false;
    if (dateTo && (!registeredAt || registeredAt > dateTo)) return false;
    return true;
  });
  const debtPatientsCount = dateFilteredPatients.filter(p => (parseFloat(p.balance) || 0) > 0).length;
  const newPatientsCount = dateFilteredPatients.length;

  const handleExport = () => {
    const rows = [['#', 'الاسم', 'العمر', 'الهاتف', 'المنطقة', 'الطبيب', 'آخر زيارة', 'الرصيد', 'الحالة']];
    filtered.forEach(p => rows.push([
      p.id || '',
      p.name || '',
      p.age || '',
      p.phone || '',
      p.location || '',
      getPatientDoctorLabel(p),
      p.lastVisit || '',
      p.balance || 0,
      p.status || '',
    ]));
    const csv = rows.map(row => row.map(value => '"' + String(value).replace(/"/g, '""') + '"').join(',')).join('\n');
    const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = `patients-${new Date().toISOString().split('T')[0]}.csv`;
    anchor.click();
    URL.revokeObjectURL(url);
  };

  const filtered = dateFilteredPatients.filter(p => {
    if (query && !p.name.includes(query) && !(p.phone||'').includes(query) && !(p.id||'').includes(query)) return false;
    if (advFilters.status === 'active' && p.status !== 'active') return false;
    if (advFilters.status === 'debt' && (!p.balance || p.balance === 0)) return false;
    if (advFilters.gender && p.gender !== advFilters.gender) return false;
    if (advFilters.doctor) {
      const doctorNames = getPatientDoctorNames(p);
      const doctorMatch = doctorNames.some(name => normalizeText(name) === normalizeText(advFilters.doctor));
      if (!doctorMatch) return false;
    }
    if (advFilters.location && (p.location || '').trim() !== advFilters.location) return false;
    if (advFilters.ageGroup) {
      const age = p.age || 0;
      if (advFilters.ageGroup === 'child' && age >= 18) return false;
      if (advFilters.ageGroup === 'young' && (age < 18 || age > 40)) return false;
      if (advFilters.ageGroup === 'adult' && (age < 40 || age > 60)) return false;
      if (advFilters.ageGroup === 'senior' && age < 60) return false;
    }
    return true;
  });

  const handlePatientUpdated = (updated) => {
    if (updated?._deleted) {
      setPatients(prev => prev.filter(p => p.id !== updated.id));
      setEditPatient(null);
    } else {
      setPatients(prev => prev.map(p => p.id === updated.id ? updated : p));
    }
  };

  return h('div', { className: 'fade-in' },
    showAdd ? h(AddPatientModal, {
      onClose: () => setShowAdd(false),
      onSaved: (newP) => setPatients(prev => [newP, ...prev]),
    }) : null,
    editPatient ? h(EditPatientModal, {
      patient: editPatient,
      onClose: () => setEditPatient(null),
      onSaved: handlePatientUpdated,
    }) : null,
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'المرضى'),
        h('div', { className: 'page-subtitle' }, `${totalPatientsCount} مريض في قاعدة البيانات`),
      ),
      h('div', { className: 'flex gap-8' },
        h('button', { className: 'btn outline', onClick: handleExport }, h(Icons.Download, { size: 16 }), 'تصدير'),
        h('button', { className: 'btn primary', onClick: () => setShowAdd(true) }, h(Icons.UserPlus, { size: 16 }), 'مريض جديد'),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'grid cols-3 mb-16' },
        h('div', { className: 'card p-20' },
          h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
            h('div', null,
              h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 6 } }, 'إجمالي المرضى'),
              h('div', { style: { fontWeight: 900, fontSize: 32, lineHeight: 1.1 } }, window.fmtNum(totalPatientsCount)),
            ),
            h('div', {
              style: {
                width: 52, height: 52, borderRadius: 16, background: 'var(--accent-soft)',
                display: 'grid', placeItems: 'center', color: 'var(--accent)',
              },
            }, h(Icons.Users, { size: 22 })),
          ),
        ),
        h('div', { className: 'card p-20' },
          h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
            h('div', null,
              h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 6 } }, 'مرضى جدد'),
              h('div', { style: { fontWeight: 900, fontSize: 32, lineHeight: 1.1, color: 'var(--accent)' } }, window.fmtNum(newPatientsCount)),
              h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 6 } }, selectedRangeLabel),
            ),
            h('div', {
              style: {
                width: 52, height: 52, borderRadius: 16, background: 'rgba(8,145,178,.12)',
                display: 'grid', placeItems: 'center', color: 'var(--accent)',
              },
            }, h(Icons.UserPlus, { size: 22 })),
          ),
        ),
        h('div', { className: 'card p-20' },
          h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
            h('div', null,
              h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 6 } }, 'عليهم مستحقات'),
              h('div', { style: { fontWeight: 900, fontSize: 32, lineHeight: 1.1, color: 'var(--danger)' } }, window.fmtNum(debtPatientsCount)),
              h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 6 } }, 'داخل فترة التسجيل المختارة'),
            ),
            h('div', {
              style: {
                width: 52, height: 52, borderRadius: 16, background: 'var(--danger-soft)',
                display: 'grid', placeItems: 'center', color: 'var(--danger)',
              },
            }, h(Icons.AlertTriangle, { size: 22 })),
          ),
        ),
      ),
      h(Shell.DateRangeFilter, {
        title: 'فلتر تاريخ التسجيل',
        subtitle: 'اختر فترة جاهزة أو حدد من يوم إلى يوم',
        dateFrom,
        dateTo,
        open: showDateFilter,
        onToggle: () => setShowDateFilter(prev => !prev),
        onClose: () => setShowDateFilter(false),
        onPresetSelect: applyPatientDatePreset,
        activePreset: activeDatePreset,
        onFromChange: (value) => {
          setDateFrom(value);
          setActiveDatePreset('custom');
        },
        onToChange: (value) => {
          setDateTo(value);
          setActiveDatePreset('custom');
        },
        onClear: clearPatientDateRange,
        onApply: () => setShowDateFilter(false),
      }),
      h('div', { className: 'card p-16 mb-16' },
        h('div', { className: 'flex gap-12 ai-c wrap' },
          h('div', { style: { flex: 1, position: 'relative', minWidth: 240 } },
            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 sm ' + (showFilterPanel || advActiveCount > 0 ? 'primary' : 'outline'),
            onClick: () => setShowFilterPanel(v => !v),
            style: { position: 'relative', gap: 6 },
          },
            h(Icons.Filter, { size: 14 }), 'تصفية',
            advActiveCount > 0 ? h('span', {
              style: {
                background: 'var(--danger)', color: '#fff', borderRadius: 10,
                padding: '1px 6px', fontSize: 10, fontWeight: 800, marginInlineStart: 4,
              },
            }, String(advActiveCount)) : null,
          ),
          h('button', {
            type: 'button',
            onClick: () => setAdv('status', 'debt'),
            className: 'btn sm',
            style: {
              gap: 6,
              borderColor: advFilters.status === 'debt' ? 'var(--danger)' : 'var(--border)',
              background: advFilters.status === 'debt' ? 'var(--danger-soft)' : 'var(--bg-elevated)',
              color: advFilters.status === 'debt' ? 'var(--danger)' : 'var(--text-primary)',
              boxShadow: advFilters.status === 'debt' ? 'var(--shadow-sm)' : 'none',
            },
          },
            h(Icons.AlertTriangle, { size: 14 }),
            `عليهم فلوس (${debtPatientsCount})`,
          ),
          h('div', { style: { display: 'flex', gap: 2, background: 'var(--bg-subtle)', padding: 4, borderRadius: 'var(--radius-sm)' } },
            ['table', 'grid'].map((v, i) => h('button', {
              key: v,
              onClick: () => setView(v),
              style: {
                padding: '6px 10px', border: 'none', background: view === v ? 'var(--bg-elevated)' : 'transparent',
                borderRadius: 4, cursor: 'pointer', color: view === v ? 'var(--text-primary)' : 'var(--text-tertiary)',
              },
            }, h(i === 0 ? Icons.List : Icons.Grid, { size: 14 }))),
          ),
        ),
      ),

      showFilterPanel ? h('div', { className: 'card p-16 mb-16', style: { borderTop: '3px solid var(--accent)' } },
        h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 } },
          h('div', { style: { fontWeight: 700, fontSize: 13 } }, 'فلاتر متقدمة'),
          advActiveCount > 0 ? h('button', {
            className: 'btn sm danger outline',
            onClick: () => setAdvFilters({ status: '', gender: '', doctor: '', location: '', ageGroup: '' }),
          }, h(Icons.X, { size: 12 }), 'مسح الكل (' + advActiveCount + ')') : null,
        ),
        h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 } },
          h('div', null,
            h('div', { className: 'label' }, 'الجنس'),
            h('div', { className: 'flex gap-4' },
              [['', 'الكل'], ['ذكر', 'ذكر'], ['أنثى', 'أنثى']].map(([v, l]) => h('button', {
                key: v,
                className: 'btn sm ' + (advFilters.gender === v ? 'primary' : 'outline'),
                onClick: () => setAdv('gender', v),
              }, l)),
            ),
          ),
          h('div', null,
            h('div', { className: 'label' }, 'الطبيب'),
            h('select', {
              className: 'select',
              value: advFilters.doctor,
              onChange: e => setAdvFilters(f => ({ ...f, doctor: e.target.value })),
            },
              h('option', { value: '' }, 'جميع الأطباء'),
              allDoctors.map(d => h('option', { key: d.id || d.name, value: d.name }, d.name)),
            ),
          ),
          h('div', null,
            h('div', { className: 'label' }, 'المنطقة'),
            h('select', {
              className: 'input',
              value: advFilters.location,
              onChange: e => setAdvFilters(f => ({ ...f, location: e.target.value })),
            },
              h('option', { value: '' }, 'كل المناطق'),
              knownLocations.map(loc => h('option', { key: loc, value: loc }, loc)),
            ),
          ),
          h('div', null,
            h('div', { className: 'label' }, 'الفئة العمرية'),
            h('div', { className: 'flex gap-4', style: { flexWrap: 'wrap' } },
              [['', 'الكل'], ['child', 'أقل من 18'], ['young', '18-40'], ['adult', '40-60'], ['senior', '+60']].map(([v, l]) => h('button', {
                key: v,
                className: 'btn sm ' + (advFilters.ageGroup === v ? 'primary' : 'outline'),
                onClick: () => setAdv('ageGroup', v),
              }, l)),
            ),
          ),
        ),
      ) : null,

      dataLoading ? h('div', { className: 'card', style: { textAlign: 'center', padding: 40 } }, h(LoadingIndicator)) : (view === 'table' ? 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(p => h('tr', { key: p.id, style: { cursor: 'pointer' }, onClick: () => setScreen('patient-file', { patientId: p.id }) },
              h('td', null, h('div', { className: 'flex ai-c gap-10' },
                h('div', {
                  className: 'avatar sm',
                  style: { fontSize: 11, fontWeight: 700 },
                }, String((p.name || '').trim().slice(0, 1) || '•')),
                h('div', null,
                  h('div', { style: { fontWeight: 700 } }, p.name),
                  h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, p.gender),
                ),
              )),
              h('td', null, p.age),
              h('td', { style: { direction: 'ltr', textAlign: 'right', fontSize: 13 } }, p.phone),
              h('td', { style: { fontSize: 12, color: 'var(--text-secondary)' } }, p.location || '—'),
              h('td', { style: { fontSize: 13, color: 'var(--text-secondary)' } }, p.lastVisit),
              h('td', { style: { fontWeight: 700, color: p.balance > 0 ? 'var(--danger)' : 'var(--text-muted)' } }, window.fmtEGP(p.balance)),
              h('td', null, h('span', { className: 'chip ' + (p.status === 'active' ? 'success' : p.status === 'pending' ? 'warning' : '') },
                p.status === 'active' ? 'نشط' : p.status === 'pending' ? 'معلق' : 'غير نشط')),
              h('td', null,
                h('div', { className: 'flex gap-4' },
                  h('button', { className: 'icon-btn', title: 'تعديل', onClick: (e) => { e.stopPropagation(); setEditPatient(p); } }, h(Icons.Edit2, { size: 14 })),
                  h('button', { className: 'icon-btn', title: 'اتصال', onClick: (e) => { e.stopPropagation(); if(p.phone) window.open('tel:' + p.phone); } }, h(Icons.Phone, { size: 14 })),
                ),
              ),
            )),
          ),
        ),
      ) : h('div', { className: 'grid cols-3' },
        filtered.map(p => h('div', {
          key: p.id,
          className: 'card p-20',
          style: { cursor: 'pointer' },
          onClick: () => setScreen('patient-file', { patientId: p.id }),
        },
          h('div', { className: 'flex ai-c gap-12 mb-12' },
            h('div', { className: 'avatar lg' }, p.avatar),
            h('div', { style: { flex: 1 } },
              h('div', { style: { fontWeight: 800, fontSize: 15 } }, p.name),
              h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)' } }, `${p.id} · ${p.age} سنة`),
            ),
            h('span', { className: 'chip ' + (p.status === 'active' ? 'success' : '') }, p.status === 'active' ? 'نشط' : 'غير نشط'),
            h('button', {
              className: 'icon-btn', title: 'تعديل',
              onClick: (e) => { e.stopPropagation(); setEditPatient(p); },
            }, h(Icons.Edit2, { size: 14 })),
          ),
          h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 12 } },
            h('div', null,
              h('div', { style: { color: 'var(--text-tertiary)', fontSize: 11 } }, 'الهاتف'),
              h('div', { style: { fontWeight: 600, marginTop: 2, direction: 'ltr', textAlign: 'right' } }, p.phone),
            ),
            h('div', null,
              h('div', { style: { color: 'var(--text-tertiary)', fontSize: 11 } }, 'المنطقة'),
              h('div', { style: { fontWeight: 600, marginTop: 2 } }, p.location || '—'),
            ),
            h('div', null,
              h('div', { style: { color: 'var(--text-tertiary)', fontSize: 11 } }, 'الطبيب'),
              h('div', { style: { fontWeight: 600, marginTop: 2 } }, getPatientDoctorLabel(p)),
            ),
            h('div', null,
              h('div', { style: { color: 'var(--text-tertiary)', fontSize: 11 } }, 'آخر زيارة'),
              h('div', { style: { fontWeight: 600, marginTop: 2 } }, p.lastVisit),
            ),
            h('div', null,
              h('div', { style: { color: 'var(--text-tertiary)', fontSize: 11 } }, 'الرصيد'),
              h('div', { style: { fontWeight: 700, marginTop: 2, color: p.balance > 0 ? 'var(--danger)' : 'var(--text-muted)' } }, window.fmtEGP(p.balance)),
            ),
          ),
        )),
      )),
    ),
  );
}

// ==================== Login Screen ====================
function Login() {
  const { refreshAuth } = useContext(AppContext);
  const [tab, setTab]             = useState('login');  // login | register
  const [email, setEmail]         = useState('');
  const [password, setPassword]   = useState('');
  const [clinicNameVal, setClinicNameVal] = useState('');
  const [loading, setLoading]     = useState(false);
  const [error, setError]         = useState('');

  const Spinner = () => h('div', {
    style: { width: 16, height: 16, border: '2px solid rgba(255,255,255,0.3)', borderTopColor: '#fff', borderRadius: '50%', animation: 'spin 0.8s linear infinite' },
  });

  const handleLogin = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    const { error: err } = await SB.auth.signInWithPassword({ email, password });
    if (err) {
      setLoading(false);
      setError(err.message === 'Invalid login credentials' ? 'البريد الإلكتروني أو كلمة المرور غير صحيحة' : err.message);
      return;
    }
    // Success: directly trigger app state update without relying on onAuthStateChange
    if (typeof refreshAuth === 'function') {
      await refreshAuth();
    } else {
      window.location.reload();
    }
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    setError('');
    if (!clinicNameVal.trim()) { setError('أدخل اسم العيادة'); return; }
    if (password.length < 6)   { setError('كلمة المرور يجب أن تكون 6 أحرف على الأقل'); return; }
    setLoading(true);

    // 1. إنشاء حساب المستخدم
    const { data: authData, error: signUpErr } = await SB.auth.signUp({ email, password });
    if (signUpErr) { setLoading(false); setError(signUpErr.message); return; }

    // 2. إنشاء سجل العيادة (المستخدم الآن مسجّل دخول)
    const userId = authData?.user?.id;
    if (userId) {
      const { error: clinicErr } = await SB.from('clinics').insert({
        owner_id: userId,
        name: clinicNameVal.trim(),
      });
      if (clinicErr) {
        setLoading(false);
        setError('تم إنشاء الحساب — خطأ في العيادة: ' + clinicErr.message);
        return;
      }
    }

    setLoading(false);
    // auth state change في index.html هيكمل الباقي تلقائياً
  };

  const Logo = () => h('div', { style: { textAlign: 'center', marginBottom: 24 } },
    h('div', {
      style: {
        width: 60, height: 60, borderRadius: 16,
        background: 'linear-gradient(135deg, var(--accent), var(--info))',
        color: '#fff', display: 'grid', placeItems: 'center', margin: '0 auto 16px',
        boxShadow: 'var(--shadow)',
      },
    }, h(Icons.Smile, { size: 28 })),
    h('div', { style: { fontSize: 24, fontWeight: 800 } }, 'سِنان كلينيك'),
    h('div', { style: { fontSize: 13, color: 'var(--text-tertiary)', marginTop: 4 } }, 'نظام إدارة عيادات الأسنان المتكامل'),
  );

  const TabBar = () => h('div', {
    style: { display: 'flex', gap: 4, background: 'var(--bg-subtle)', padding: 4, borderRadius: 'var(--radius)', marginBottom: 20 },
  },
    [['login', 'تسجيل الدخول'], ['register', 'عيادة جديدة']].map(([id, label]) =>
      h('button', {
        key: id, onClick: () => { setTab(id); setError(''); },
        style: {
          flex: 1, padding: '10px 12px', border: 'none', cursor: 'pointer',
          background: tab === id ? 'var(--bg-elevated)' : 'transparent',
          borderRadius: 'var(--radius-sm)',
          color: tab === id ? 'var(--text-primary)' : 'var(--text-tertiary)',
          fontWeight: 700, fontSize: 13, boxShadow: tab === id ? 'var(--shadow-sm)' : 'none',
          transition: 'all 0.15s',
        },
      }, label),
    ),
  );

  return h('div', { className: 'login-root' },
    h('div', { className: 'login-bg' }),
    h('div', { className: 'login-card card scale-in' },
      h(Logo),
      h(TabBar),

      tab === 'login'
        ? h('form', { onSubmit: handleLogin },
            h('div', { className: 'label' }, 'البريد الإلكتروني'),
            h('input', {
              className: 'input mb-16', type: 'email', required: true, autoFocus: true,
              placeholder: 'clinic@example.com',
              value: email, onChange: e => setEmail(e.target.value),
            }),
            h('div', { className: 'flex jc-sb ai-c', style: { marginBottom: 4 } },
              h('div', { className: 'label', style: { margin: 0 } }, 'كلمة المرور'),
            ),
            h('input', {
              className: 'input', type: 'password', required: true,
              placeholder: '••••••••',
              value: password, onChange: e => setPassword(e.target.value),
            }),
            error && h('div', { style: { marginTop: 12, fontSize: 12, color: error.startsWith('✅') ? 'var(--success)' : 'var(--danger)', fontWeight: 600 } }, error),
            h('button', {
              type: 'submit',
              className: 'btn primary mt-20',
              style: { width: '100%', justifyContent: 'center', padding: '12px 20px', fontSize: 14 },
              disabled: loading,
            }, loading ? h(Fragment, null, h(Spinner), 'جاري تسجيل الدخول...') : h(Fragment, null, h(Icons.LogIn, { size: 16 }), 'تسجيل الدخول')),
          )

        : h('form', { onSubmit: handleRegister },
            h('div', { className: 'label' }, 'اسم العيادة'),
            h('input', {
              className: 'input mb-16', required: true, autoFocus: true,
              placeholder: 'عيادة د. أحمد للأسنان',
              value: clinicNameVal, onChange: e => setClinicNameVal(e.target.value),
            }),
            h('div', { className: 'label' }, 'البريد الإلكتروني'),
            h('input', {
              className: 'input mb-16', type: 'email', required: true,
              placeholder: 'clinic@example.com',
              value: email, onChange: e => setEmail(e.target.value),
            }),
            h('div', { className: 'label' }, 'كلمة المرور'),
            h('input', {
              className: 'input', type: 'password', required: true,
              placeholder: '6 أحرف على الأقل',
              value: password, onChange: e => setPassword(e.target.value),
            }),
            error && h('div', { style: { marginTop: 12, fontSize: 12, color: error.startsWith('✅') ? 'var(--success)' : 'var(--danger)', fontWeight: 600 } }, error),
            h('button', {
              type: 'submit',
              className: 'btn primary mt-20',
              style: { width: '100%', justifyContent: 'center', padding: '12px 20px', fontSize: 14 },
              disabled: loading,
            }, loading ? h(Fragment, null, h(Spinner), 'جاري الإنشاء...') : h(Fragment, null, h(Icons.UserPlus, { size: 16 }), 'إنشاء الحساب')),
          ),
    ),
    h('style', null, `
      .login-root {
        position: fixed; inset: 0; display: grid; place-items: center;
        background: var(--bg); overflow: hidden; z-index: 1000;
      }
      .login-bg {
        position: absolute; inset: -10%;
        background:
          radial-gradient(ellipse at 20% 30%, color-mix(in oklab, var(--accent) 22%, transparent), transparent 55%),
          radial-gradient(ellipse at 80% 70%, color-mix(in oklab, var(--info) 22%, transparent), transparent 55%),
          radial-gradient(ellipse at 60% 20%, color-mix(in oklab, var(--purple) 14%, transparent), transparent 50%);
        filter: blur(60px); animation: drift 18s ease-in-out infinite alternate;
      }
      @keyframes drift { 0% { transform: translate(0,0) rotate(0); } 100% { transform: translate(3%, -2%) rotate(4deg); } }
      .login-card { width: 420px; max-width: 92vw; padding: 32px; position: relative; z-index: 1; }
      @keyframes spin { to { transform: rotate(360deg); } }
    `),
  );
}

function LoginPortal() {
  const { refreshAuth } = useContext(AppContext);
  const [tab, setTab] = useState('login');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loginForm, setLoginForm] = useState({ email: '', password: '' });
  const [registerForm, setRegisterForm] = useState({
    clinicName: '',
    adminName: '',
    email: '',
    password: '',
  });

  const Spinner = () => h('div', {
    style: { width: 16, height: 16, border: '2px solid rgba(255,255,255,0.3)', borderTopColor: '#fff', borderRadius: '50%', animation: 'spin 0.8s linear infinite' },
  });

  const setLogin = (key, value) => setLoginForm(prev => ({ ...prev, [key]: value }));
  const setRegister = (key, value) => setRegisterForm(prev => ({ ...prev, [key]: value }));

  const portalCopy = useMemo(() => (
    tab === 'login'
      ? {
          badge: 'بوابة العيادة',
          title: 'الدخول إلى لوحة تشغيل سِنان كلينيك',
          subtitle: 'وصول آمن إلى المواعيد والمرضى والفواتير والمخزون من شاشة واحدة.',
        }
      : {
          badge: 'ابدأ التجربة',
          title: 'أنشئ بوابة عيادتك خلال دقائق',
          subtitle: 'نسجل حساب المدير، ننشئ العيادة، ونجهز مساحة العمل للانطلاق في بيئة الـ Dev.',
        }
  ), [tab]);

  const featureCards = [
    { icon: Icons.Shield, title: 'دخول آمن', text: 'مصادقة Supabase وربط مباشر مع العيادة عبر owner_id.' },
    { icon: Icons.Stethoscope, title: 'Onboarding عملي', text: 'تهيئة سريعة للأطباء والخدمات والمخزون بعد أول دخول.' },
    { icon: Icons.Database, title: 'بيانات موحدة', text: 'كل شاشة تعمل على نفس قاعدة البيانات والـ realtime updates.' },
  ];

  function normalizeAuthError(message) {
    if (!message) return 'حدث خطأ غير متوقع. حاول مرة أخرى.';
    if (message === 'Invalid login credentials') return 'البريد الإلكتروني أو كلمة المرور غير صحيحة.';
    if (message.includes('Email not confirmed')) return 'يرجى تأكيد البريد الإلكتروني أولاً ثم تسجيل الدخول.';
    if (message.includes('User already registered')) return 'هذا البريد مستخدم بالفعل. جرّب تسجيل الدخول أو استخدم بريدًا آخر.';
    return message;
  }

  const handleLogin = async (e) => {
    e.preventDefault();
    setSuccess('');
    setError('');
    setLoading(true);

    try {
      await AuthAPI.loginClinicAccount(loginForm);
      if (typeof refreshAuth === 'function') {
        await refreshAuth();
      } else {
        window.location.reload();
      }
    } catch (err) {
      setError(normalizeAuthError(err.message));
      setLoading(false);
    }
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    setSuccess('');
    setError('');

    if (!registerForm.clinicName.trim()) { setError('أدخل اسم العيادة.'); return; }
    if (!registerForm.adminName.trim()) { setError('أدخل اسم المدير أو الطبيب المسؤول.'); return; }
    if (registerForm.password.length < 8) { setError('كلمة المرور يجب أن تكون 8 أحرف على الأقل.'); return; }

    setLoading(true);

    try {
      const result = await AuthAPI.registerClinicAccount(registerForm);
      if (result.requiresEmailConfirmation) {
        setSuccess('تم إنشاء الحساب وإرسال رسالة التفعيل إلى بريدك الإلكتروني. بعد التأكيد، سجّل الدخول للمتابعة.');
        setTab('login');
        setLoginForm({ email: registerForm.email, password: '' });
      } else {
        setSuccess('تم إنشاء حساب العيادة بنجاح. جاري تجهيز لوحة التحكم...');
        if (typeof refreshAuth === 'function') {
          await refreshAuth();
        } else {
          window.location.reload();
        }
      }
    } catch (err) {
      setError(normalizeAuthError(err.message));
    } finally {
      setLoading(false);
    }
  };

  const Logo = () => h('div', { className: 'portal-brand' },
    h('div', { className: 'portal-logo' }, h(Icons.Smile, { size: 28 })),
    h('div', null,
      h('div', { className: 'portal-name' }, 'سِنان كلينيك'),
      h('div', { className: 'portal-tagline' }, 'SaaS لإدارة وتشغيل عيادات الأسنان'),
    ),
  );

  const TabBar = () => h('div', { className: 'portal-tabs' },
    [['login', 'تسجيل الدخول'], ['register', 'عيادة جديدة']].map(([id, label]) =>
      h('button', {
        key: id,
        type: 'button',
        onClick: () => { setTab(id); setError(''); setSuccess(''); },
        className: 'portal-tab ' + (tab === id ? 'is-active' : ''),
      }, label),
    ),
  );

  const StatusMessage = () => (
    error ? h('div', { className: 'portal-status error' }, h(Icons.AlertTriangle, { size: 15 }), error) :
    success ? h('div', { className: 'portal-status success' }, h(Icons.Check, { size: 15 }), success) :
    null
  );

  return h('div', { className: 'portal-root' },
    h('div', { className: 'portal-orb portal-orb-a' }),
    h('div', { className: 'portal-orb portal-orb-b' }),
    h('div', { className: 'portal-shell scale-in' },
      h('section', { className: 'portal-hero' },
        h(Logo),
        h('span', { className: 'portal-badge' }, portalCopy.badge),
        h('h1', { className: 'portal-title' }, portalCopy.title),
        h('p', { className: 'portal-subtitle' }, portalCopy.subtitle),
        h('div', { className: 'portal-feature-list' },
          featureCards.map((item, index) => h('div', { key: index, className: 'portal-feature-card' },
            h('div', { className: 'portal-feature-icon' }, h(item.icon, { size: 18 })),
            h('div', null,
              h('div', { className: 'portal-feature-title' }, item.title),
              h('div', { className: 'portal-feature-text' }, item.text),
            ),
          )),
        ),
      ),

      h('section', { className: 'portal-form-side card' },
        h(TabBar),
        h('div', { className: 'portal-form-head' },
          h('div', { className: 'portal-form-title' }, tab === 'login' ? 'تسجيل الدخول' : 'إنشاء حساب عيادة'),
          h('div', { className: 'portal-form-subtitle' },
            tab === 'login'
              ? 'أدخل البريد الإلكتروني وكلمة المرور للوصول إلى لوحة التحكم.'
              : 'أنشئ حساب المدير واربطه بعيادتك الجديدة في خطوة واحدة.'),
        ),
        h(StatusMessage),

        tab === 'login'
          ? h('form', { onSubmit: handleLogin, className: 'portal-form-grid' },
              h('div', null,
                h('div', { className: 'label' }, 'البريد الإلكتروني'),
                h('div', { className: 'portal-field' },
                  h('span', { className: 'portal-field-icon' }, h(Icons.Mail, { size: 15 })),
                  h('input', {
                    className: 'input',
                    type: 'email',
                    required: true,
                    autoFocus: true,
                    placeholder: 'clinic@example.com',
                    value: loginForm.email,
                    onChange: e => setLogin('email', e.target.value),
                  }),
                ),
              ),
              h('div', null,
                h('div', { className: 'label' }, 'كلمة المرور'),
                h(PasswordField, {
                  value: loginForm.password,
                  onChange: e => setLogin('password', e.target.value),
                  placeholder: 'اكتب كلمة المرور',
                  visible: showPassword,
                  onToggle: () => setShowPassword(v => !v),
                  autoComplete: 'current-password',
                }),
              ),
              h('button', {
                type: 'submit',
                className: 'btn primary portal-submit',
                disabled: loading,
              }, loading ? h(Fragment, null, h(Spinner), 'جاري تسجيل الدخول...') : h(Fragment, null, h(Icons.LogIn, { size: 16 }), 'دخول إلى لوحة التحكم')),
            )
          : h('form', { onSubmit: handleRegister, className: 'portal-form-grid' },
              h('div', null,
                h('div', { className: 'label' }, 'اسم العيادة'),
                h('div', { className: 'portal-field' },
                  h('span', { className: 'portal-field-icon' }, h(Icons.Building, { size: 15 })),
                  h('input', {
                    className: 'input',
                    required: true,
                    autoFocus: true,
                    placeholder: 'مثال: عيادة سِنان للأسنان',
                    value: registerForm.clinicName,
                    onChange: e => setRegister('clinicName', e.target.value),
                  }),
                ),
              ),
              h('div', null,
                h('div', { className: 'label' }, 'اسم المدير أو الطبيب'),
                h('div', { className: 'portal-field' },
                  h('span', { className: 'portal-field-icon' }, h(Icons.User, { size: 15 })),
                  h('input', {
                    className: 'input',
                    required: true,
                    placeholder: 'د. أحمد محمد',
                    value: registerForm.adminName,
                    onChange: e => setRegister('adminName', e.target.value),
                  }),
                ),
              ),
              h('div', null,
                h('div', { className: 'label' }, 'البريد الإلكتروني'),
                h('div', { className: 'portal-field' },
                  h('span', { className: 'portal-field-icon' }, h(Icons.Mail, { size: 15 })),
                  h('input', {
                    className: 'input',
                    type: 'email',
                    required: true,
                    placeholder: 'admin@clinic.com',
                    value: registerForm.email,
                    onChange: e => setRegister('email', e.target.value),
                  }),
                ),
              ),
              h('div', null,
                h('div', { className: 'label' }, 'كلمة المرور'),
                h(PasswordField, {
                  value: registerForm.password,
                  onChange: e => setRegister('password', e.target.value),
                  placeholder: '8 أحرف على الأقل',
                  visible: showPassword,
                  onToggle: () => setShowPassword(v => !v),
                  autoComplete: 'new-password',
                }),
              ),
              h('div', { className: 'portal-hint' },
                h(Icons.Info, { size: 14 }),
                h('span', null, 'إذا كان المشروع يطلب تفعيل البريد، سنجهز الربط تلقائيًا بعد أول دخول ناجح.'),
              ),
              h('button', {
                type: 'submit',
                className: 'btn primary portal-submit',
                disabled: loading,
              }, loading ? h(Fragment, null, h(Spinner), 'جاري إنشاء الحساب...') : h(Fragment, null, h(Icons.UserPlus, { size: 16 }), 'إنشاء حساب العيادة')),
            ),
      ),
    ),
    h('style', null, `
      .portal-root {
        position: fixed;
        inset: 0;
        overflow: auto;
        background:
          radial-gradient(circle at top left, rgba(26, 127, 107, 0.16), transparent 30%),
          linear-gradient(135deg, #f3f7f6 0%, #eef4f8 55%, #f7fbfa 100%);
        z-index: 1000;
      }
      .portal-orb {
        position: fixed;
        width: 34rem;
        height: 34rem;
        border-radius: 999px;
        filter: blur(70px);
        opacity: 0.22;
        pointer-events: none;
      }
      .portal-orb-a {
        top: -8rem;
        inset-inline-start: -8rem;
        background: #0f766e;
      }
      .portal-orb-b {
        bottom: -10rem;
        inset-inline-end: -8rem;
        background: #0284c7;
      }
      .portal-shell {
        position: relative;
        z-index: 1;
        width: min(1180px, calc(100vw - 32px));
        min-height: calc(100vh - 32px);
        margin: 16px auto;
        display: grid;
        grid-template-columns: 1.08fr 0.92fr;
        gap: 18px;
        align-items: stretch;
      }
      .portal-hero {
        padding: 40px 38px;
        border-radius: 32px;
        background:
          linear-gradient(155deg, rgba(255,255,255,0.88), rgba(255,255,255,0.62)),
          linear-gradient(135deg, rgba(15,118,110,0.18), rgba(2,132,199,0.12));
        border: 1px solid rgba(255,255,255,0.7);
        box-shadow: 0 22px 60px rgba(15, 23, 42, 0.08);
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
      .portal-form-side {
        padding: 26px;
        border-radius: 32px;
        position: relative;
        overflow: hidden;
        border: 1px solid rgba(255,255,255,0.7);
        box-shadow: 0 22px 60px rgba(15, 23, 42, 0.08);
      }
      .portal-brand {
        display: flex;
        align-items: center;
        gap: 14px;
        margin-bottom: 22px;
      }
      .portal-logo {
        width: 58px;
        height: 58px;
        border-radius: 18px;
        display: grid;
        place-items: center;
        color: #fff;
        background: linear-gradient(135deg, #0f766e, #0284c7);
        box-shadow: 0 18px 36px rgba(15, 118, 110, 0.24);
      }
      .portal-name {
        font-size: 24px;
        font-weight: 900;
        color: #0f172a;
      }
      .portal-tagline {
        font-size: 13px;
        color: #4b5563;
        margin-top: 4px;
      }
      .portal-badge {
        display: inline-flex;
        align-items: center;
        width: fit-content;
        padding: 8px 12px;
        border-radius: 999px;
        font-size: 12px;
        font-weight: 800;
        color: #0f766e;
        background: rgba(15, 118, 110, 0.1);
        margin-bottom: 18px;
      }
      .portal-title {
        font-size: clamp(32px, 4vw, 48px);
        line-height: 1.1;
        margin: 0 0 14px;
        color: #0f172a;
      }
      .portal-subtitle {
        font-size: 15px;
        line-height: 1.9;
        color: #475569;
        margin: 0 0 28px;
        max-width: 52ch;
      }
      .portal-feature-list {
        display: grid;
        gap: 14px;
      }
      .portal-feature-card {
        display: grid;
        grid-template-columns: auto 1fr;
        gap: 12px;
        align-items: flex-start;
        padding: 16px 18px;
        border-radius: 20px;
        background: rgba(255,255,255,0.72);
        border: 1px solid rgba(255,255,255,0.6);
      }
      .portal-feature-icon {
        width: 42px;
        height: 42px;
        border-radius: 14px;
        display: grid;
        place-items: center;
        background: rgba(15, 118, 110, 0.12);
        color: #0f766e;
      }
      .portal-feature-title {
        font-size: 14px;
        font-weight: 800;
        color: #0f172a;
        margin-bottom: 4px;
      }
      .portal-feature-text {
        font-size: 13px;
        line-height: 1.8;
        color: #475569;
      }
      .portal-tabs {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 6px;
        background: #edf3f6;
        padding: 6px;
        border-radius: 16px;
        margin-bottom: 22px;
      }
      .portal-tab {
        border: none;
        cursor: pointer;
        padding: 12px 14px;
        border-radius: 12px;
        background: transparent;
        color: #64748b;
        font-size: 13px;
        font-weight: 800;
        transition: all 0.18s ease;
      }
      .portal-tab.is-active {
        background: #fff;
        color: #0f172a;
        box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
      }
      .portal-form-head {
        margin-bottom: 18px;
      }
      .portal-form-title {
        font-size: 24px;
        font-weight: 900;
        color: #0f172a;
        margin-bottom: 6px;
      }
      .portal-form-subtitle {
        font-size: 13px;
        line-height: 1.8;
        color: #64748b;
      }
      .portal-form-grid {
        display: grid;
        gap: 14px;
      }
      .portal-field {
        position: relative;
      }
      .portal-field .input {
        padding-inline-start: 42px;
      }
      .portal-field-icon {
        position: absolute;
        inset-inline-start: 14px;
        top: 50%;
        transform: translateY(-50%);
        color: #64748b;
        display: inline-flex;
      }
      .portal-password-wrap {
        position: relative;
      }
      .portal-password-wrap .input {
        padding-inline-end: 46px;
      }
      .portal-password-toggle {
        position: absolute;
        inset-inline-end: 8px;
        top: 50%;
        transform: translateY(-50%);
        color: #64748b;
      }
      .portal-status {
        display: flex;
        align-items: flex-start;
        gap: 8px;
        padding: 12px 14px;
        border-radius: 16px;
        font-size: 13px;
        line-height: 1.8;
        font-weight: 700;
        margin-bottom: 16px;
      }
      .portal-status.error {
        color: #b91c1c;
        background: #fef2f2;
        border: 1px solid #fecaca;
      }
      .portal-status.success {
        color: #166534;
        background: #f0fdf4;
        border: 1px solid #bbf7d0;
      }
      .portal-hint {
        display: flex;
        gap: 8px;
        align-items: flex-start;
        padding: 12px 14px;
        border-radius: 16px;
        background: #eff6ff;
        color: #1d4ed8;
        font-size: 12px;
        line-height: 1.8;
      }
      .portal-submit {
        width: 100%;
        justify-content: center;
        padding: 13px 20px;
        font-size: 14px;
        margin-top: 4px;
      }
      @keyframes spin { to { transform: rotate(360deg); } }
      @media (max-width: 980px) {
        .portal-shell {
          grid-template-columns: 1fr;
          width: min(680px, calc(100vw - 20px));
          min-height: auto;
          margin: 10px auto;
        }
        .portal-hero,
        .portal-form-side {
          padding: 24px;
          border-radius: 26px;
        }
        .portal-title {
          font-size: 32px;
        }
      }
      @media (max-width: 640px) {
        .portal-root {
          background: linear-gradient(180deg, #f3f7f6 0%, #eef4f8 100%);
        }
        .portal-shell {
          width: calc(100vw - 12px);
          margin: 6px auto;
          gap: 10px;
        }
        .portal-hero,
        .portal-form-side {
          padding: 18px;
          border-radius: 22px;
        }
        .portal-brand {
          gap: 10px;
          margin-bottom: 16px;
        }
        .portal-logo {
          width: 50px;
          height: 50px;
          border-radius: 15px;
        }
        .portal-title {
          font-size: 28px;
        }
        .portal-subtitle {
          font-size: 14px;
          margin-bottom: 20px;
        }
      }
    `),
  );
}

// ==================== Onboarding Wizard ====================
function OnboardingWizard({ onDone }) {
  const { clinicId, clinicName, setClinicName, setDoctors, setServices, setInventory, toast, user, setScreen } = useContext(AppContext);
  const [step, setStep] = useState(1);
  const totalSteps = 4;
  const pendingDraft = AuthAPI.getPendingSignupDraft(user?.email);
  const initialDoctorName = (pendingDraft?.adminName || user?.user_metadata?.admin_name || user?.user_metadata?.full_name || '').trim();

  // Step 1: بيانات العيادة
  const [cName, setCName] = useState(clinicName || '');
  const [cPhone, setCPhone] = useState('');
  const [cAddress, setCAddress] = useState('');

  // Step 2: الأطباء
  const [docRows, setDocRows] = useState([{ name: '', specialty: 'أسنان عامة', commission: 30 }]);
  const addDocRow = () => setDocRows(r => [...r, { name: '', specialty: 'أسنان عامة', commission: 30 }]);
  const setDoc = (i, k, v) => setDocRows(r => r.map((d, idx) => idx === i ? { ...d, [k]: v } : d));
  useEffect(() => {
    if (!initialDoctorName) return;
    setDocRows(rows => {
      if (!rows.length) return [{ name: initialDoctorName, specialty: 'أسنان عامة', commission: 30 }];
      if ((rows[0]?.name || '').trim()) return rows;
      return rows.map((row, index) => index === 0 ? { ...row, name: initialDoctorName } : row);
    });
  }, [initialDoctorName]);

  // Step 3: الخدمات
  const defaultSvcs = [
    { name: 'كشف وفحص', price: 150, duration: 30, category: 'فحص وتشخيص' },
    { name: 'تنظيف وتلميع', price: 300, duration: 45, category: 'تنظيف' },
    { name: 'حشو كومبوزيت', price: 500, duration: 60, category: 'حشو' },
  ];
  const [svcRows, setSvcRows] = useState(defaultSvcs);
  const addSvcRow = () => setSvcRows(r => [...r, { name: '', price: '', duration: 30, category: 'عام' }]);
  const setSvc = (i, k, v) => setSvcRows(r => r.map((s, idx) => idx === i ? { ...s, [k]: v } : s));

  // Step 4: مخزون أساسي
  const defaultInv = [
    { name: 'قفازات لاتكس S', category: 'قفازات ومستلزمات', stock: 100, min_stock: 20, unit: 'قطعة', price: 2 },
    { name: 'كمامات طبية', category: 'قفازات ومستلزمات', stock: 50, min_stock: 10, unit: 'قطعة', price: 3 },
  ];
  const [invRows, setInvRows] = useState(defaultInv);

  const [saving, setSaving] = useState(false);

  const handleFinish = async () => {
    setSaving(true);
    try {
      // حفظ اسم العيادة
      if (cName && setClinicName) setClinicName(cName);
      await SB.from('clinics').update({ name: cName, phone: cPhone, address: cAddress }).eq('id', clinicId);

      // حفظ الأطباء
      const validDocs = docRows.filter(d => d.name.trim());
      for (const d of validDocs) {
        const doc = await DB.addDoctor(clinicId, { name: d.name.trim(), specialty: d.specialty, color: '#0891b2', status: 'متاح' });
        if (setDoctors) setDoctors(prev => [doc, ...prev]);
      }

      // حفظ الخدمات
      const validSvcs = svcRows.filter(s => s.name.trim() && +s.price > 0);
      for (const s of validSvcs) {
        const svc = await DB.addService(clinicId, { name: s.name.trim(), price: +s.price, duration: +s.duration, category: s.category });
        if (setServices) setServices(prev => [svc, ...prev]);
      }

      // حفظ المخزون
      const validInv = invRows.filter(i => i.name.trim());
      for (const it of validInv) {
        const item = await DB.addInventoryItem(clinicId, it);
        if (setInventory) setInventory(prev => [item, ...prev]);
      }

      toast('🎉 تم إعداد العيادة بنجاح! مرحباً بك في سِنان كلينيك');
      if (typeof setScreen === 'function') setScreen('dashboard');
      onDone();
    } catch(e) { console.error(e); toast('حدث خطأ: ' + (e.message || 'غير متوقع')); }
    finally { setSaving(false); }
  };

  const stepTitles = ['بيانات العيادة', 'الأطباء', 'الخدمات والأسعار', 'المخزون الأساسي'];
  const specialties = ['أسنان عامة', 'تقويم', 'جراحة', 'أطفال', 'تركيبات', 'تجميل', 'أشعة'];

  return h('div', { style: { position:'fixed',inset:0,background:'var(--bg)',zIndex:1000,overflowY:'auto',display:'flex',alignItems:'center',justifyContent:'center',padding:20 } },
    h('div', { style: { maxWidth:640,width:'100%' } },
      // Header
      h('div', { style: { textAlign:'center',marginBottom:28 } },
        h('div', { style: { fontSize:28,fontWeight:900,color:'var(--accent)',marginBottom:8 } }, '🦷 سِنان كلينيك'),
        h('div', { style: { fontSize:16,color:'var(--text-secondary)' } }, 'إعداد العيادة — خطوة ' + step + ' من ' + totalSteps),
      ),

      // Stepper
      h('div', { className:'flex ai-c mb-24', style:{gap:0} },
        stepTitles.map((t, i) => h(Fragment, { key:i },
          h('div', { className:'flex ai-c gap-6', style:{flexDirection:'column',alignItems:'center'} },
            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:13 } },
              i+1 < step ? h(Icons.Check,{size:14}) : i+1),
            h('div', { style:{fontSize:11,color:i+1<=step?'var(--text-primary)':'var(--text-tertiary)',marginTop:4,whiteSpace:'nowrap'} }, t),
          ),
          i < stepTitles.length-1 ? h('div',{style:{flex:1,height:2,background:i+1<step?'var(--accent)':'var(--border)',margin:'0 4px',alignSelf:'flex-start',marginTop:16}}) : null,
        )),
      ),

      h('div', { className:'card p-24' },
        // Step 1
        step === 1 && h('div', { style:{display:'grid',gap:14} },
          h('div',{style:{fontWeight:800,fontSize:16,marginBottom:4}},'بيانات العيادة الأساسية'),
          h('div',null, h('div',{className:'label'},'اسم العيادة *'), h('input',{className:'input',placeholder:'مثال: عيادة سِنان',value:cName,onChange:e=>setCName(e.target.value)})),
          h('div',{style:{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}},
            h('div',null, h('div',{className:'label'},'رقم الهاتف'), h('input',{className:'input',placeholder:'01000000000',value:cPhone,onChange:e=>setCPhone(e.target.value)})),
            h('div',null, h('div',{className:'label'},'العنوان'), h('input',{className:'input',placeholder:'المدينة - الحي',value:cAddress,onChange:e=>setCAddress(e.target.value)})),
          ),
        ),

        // Step 2
        step === 2 && h('div',null,
          h('div',{style:{fontWeight:800,fontSize:16,marginBottom:12}},'أضف أطباء العيادة'),
          h('div',{style:{display:'flex',flexDirection:'column',gap:8}},
            docRows.map((d,i) => h('div',{key:i,style:{display:'grid',gridTemplateColumns:'2fr 2fr 1fr auto',gap:8,alignItems:'end'}},
              h('div',null, i===0&&h('div',{className:'label'},'الاسم'), h('input',{className:'input',placeholder:'د. محمد أحمد',value:d.name,onChange:e=>setDoc(i,'name',e.target.value)})),
              h('div',null, i===0&&h('div',{className:'label'},'التخصص'),
                h('select',{className:'select',value:d.specialty,onChange:e=>setDoc(i,'specialty',e.target.value)},
                  specialties.map(s=>h('option',{key:s,value:s},s)))),
              h('div',null, i===0&&h('div',{className:'label'},'العمولة %'), h('input',{className:'input',type:'number',min:0,max:100,value:d.commission,onChange:e=>setDoc(i,'commission',e.target.value)})),
              h('button',{className:'icon-btn',style:{color:'var(--danger)',marginBottom:docRows.length>1?0:0},onClick:()=>setDocRows(r=>r.filter((_,idx)=>idx!==i))}, h(Icons.Trash,{size:13})),
            )),
          ),
          h('button',{className:'btn sm outline mt-10',onClick:addDocRow}, h(Icons.Plus,{size:13}), 'إضافة طبيب'),
        ),

        // Step 3
        step === 3 && h('div',null,
          h('div',{style:{fontWeight:800,fontSize:16,marginBottom:12}},'الخدمات والأسعار'),
          h('div',{style:{display:'flex',flexDirection:'column',gap:8}},
            svcRows.map((s,i) => h('div',{key:i,style:{display:'grid',gridTemplateColumns:'2fr 1fr 1fr auto',gap:8,alignItems:'end'}},
              h('div',null, i===0&&h('div',{className:'label'},'اسم الخدمة'), h('input',{className:'input',placeholder:'كشف وفحص',value:s.name,onChange:e=>setSvc(i,'name',e.target.value)})),
              h('div',null, i===0&&h('div',{className:'label'},'السعر ج.م'), h('input',{className:'input',type:'number',placeholder:'150',value:s.price,onChange:e=>setSvc(i,'price',e.target.value)})),
              h('div',null, i===0&&h('div',{className:'label'},'المدة د'), h('input',{className:'input',type:'number',value:s.duration,onChange:e=>setSvc(i,'duration',e.target.value)})),
              h('button',{className:'icon-btn',style:{color:'var(--danger)'},onClick:()=>setSvcRows(r=>r.filter((_,idx)=>idx!==i))}, h(Icons.Trash,{size:13})),
            )),
          ),
          h('button',{className:'btn sm outline mt-10',onClick:addSvcRow}, h(Icons.Plus,{size:13}), 'إضافة خدمة'),
        ),

        // Step 4
        step === 4 && h('div',null,
          h('div',{style:{fontWeight:800,fontSize:16,marginBottom:4}},'مخزون أساسي (اختياري)'),
          h('div',{style:{fontSize:13,color:'var(--text-tertiary)',marginBottom:12}},'يمكن تعديله لاحقاً من صفحة المخزون'),
          h('div',{style:{display:'flex',flexDirection:'column',gap:8}},
            invRows.map((it,i) => h('div',{key:i,style:{display:'grid',gridTemplateColumns:'2fr 1fr 1fr auto',gap:8,alignItems:'end'}},
              h('div',null, i===0&&h('div',{className:'label'},'اسم الصنف'), h('input',{className:'input',placeholder:'قفازات...',value:it.name,onChange:e=>setInvRows(r=>r.map((row,idx)=>idx===i?{...row,name:e.target.value}:row))})),
              h('div',null, i===0&&h('div',{className:'label'},'الكمية'), h('input',{className:'input',type:'number',value:it.stock,onChange:e=>setInvRows(r=>r.map((row,idx)=>idx===i?{...row,stock:+e.target.value}:row))})),
              h('div',null, i===0&&h('div',{className:'label'},'الحد الأدنى'), h('input',{className:'input',type:'number',value:it.min_stock,onChange:e=>setInvRows(r=>r.map((row,idx)=>idx===i?{...row,min_stock:+e.target.value}:row))})),
              h('button',{className:'icon-btn',style:{color:'var(--danger)'},onClick:()=>setInvRows(r=>r.filter((_,idx)=>idx!==i))}, h(Icons.Trash,{size:13})),
            )),
          ),
          h('button',{className:'btn sm outline mt-10',onClick:()=>setInvRows(r=>[...r,{name:'',category:'عام',stock:0,min_stock:0,unit:'قطعة',price:0}])}, h(Icons.Plus,{size:13}), 'إضافة صنف'),
        ),

        h('div',{className:'flex gap-8 jc-sb mt-24'},
          step > 1 ? h('button',{className:'btn outline',onClick:()=>setStep(s=>s-1)},'السابق') : h('button',{className:'btn outline',onClick:onDone},'تخطي الإعداد'),
          step < totalSteps ?
            h('button',{className:'btn primary',onClick:()=>setStep(s=>s+1)}, 'التالي', h(Icons.ChevronLeft,{size:16})) :
            h('button',{className:'btn primary',disabled:saving,onClick:handleFinish},
              saving?'جاري الحفظ...':'🚀 ابدأ استخدام النظام'),
        ),
      ),
    ),
  );
}

function PasswordField({ value, onChange, placeholder, visible, onToggle, autoComplete }) {
  return h('div', { className: 'portal-password-wrap' },
    h('input', {
      className: 'input',
      type: visible ? 'text' : 'password',
      required: true,
      placeholder,
      value,
      onChange,
      autoComplete: autoComplete || 'current-password',
      spellCheck: false,
      autoCapitalize: 'none',
      autoCorrect: 'off',
    }),
    h('button', {
      type: 'button',
      className: 'icon-btn portal-password-toggle',
      title: visible ? 'إخفاء كلمة المرور' : 'إظهار كلمة المرور',
      onMouseDown: e => e.preventDefault(),
      onClick: onToggle,
    }, h(Icons.Eye, { size: 15 })),
  );
}

window.EditPatientModal = EditPatientModal;
window.AddPatientModal = AddPatientModal;
window.Screens = Object.assign(window.Screens || {}, { Patients, Login: LoginPortal, OnboardingWizard });
