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

// ==================== Sidebar ====================
function Sidebar() {
  const { currentScreen, setScreen, unreadMessages, setLoggedIn, user, clinicName } = useContext(AppContext);

  const mainNav = [
    { id: 'dashboard', label: 'لوحة التحكم', icon: Icons.Home },
    { id: 'appointments', label: 'المواعيد', icon: Icons.Calendar, badge: 12 },
    { id: 'patients', label: 'المرضى', icon: Icons.Users },
    { id: 'dental-chart', label: 'مخطط الأسنان', icon: Icons.Smile },
    { id: 'treatments', label: 'خطط العلاج', icon: Icons.Activity },
    { id: 'prescriptions', label: 'الوصفات الطبية', icon: Icons.Pill },
    { id: 'xrays', label: 'الأشعة والصور', icon: Icons.Image },
  ];

  const adminNav = [
    { id: 'billing', label: 'الفواتير', icon: Icons.CreditCard },
    { id: 'accounting', label: 'المحاسبة', icon: Icons.Calculator },
    { id: 'insurance', label: 'التأمين الطبي', icon: Icons.Shield },
    { id: 'inventory', label: 'المخزون', icon: Icons.Package },
    { id: 'staff', label: 'الموظفين', icon: Icons.Briefcase },
  ];

  const systemNav = [
    { id: 'messages', label: 'الدردشة الداخلية', icon: Icons.MessageCircle, badge: unreadMessages },
    { id: 'reports', label: 'التقارير', icon: Icons.BarChart },
    { id: 'patient-portal', label: 'بوابة المريض', icon: Icons.User },
    { id: 'settings', label: 'الإعدادات', icon: Icons.Settings },
  ];

  const renderItem = (item) => h('button', {
    key: item.id,
    className: 'nav-item' + (currentScreen === item.id ? ' active' : ''),
    onClick: () => setScreen(item.id),
  },
    h('span', { className: 'icon-box' }, h(item.icon, { size: 18 })),
    h('span', null, item.label),
    item.badge ? h('span', { className: 'badge-count' }, item.badge) : null,
  );

  return h('aside', { className: 'sidebar' },
    h('div', { className: 'sidebar-logo' },
      h('div', { className: 'sidebar-logo-mark' }, h(Icons.Smile, { size: 22 })),
      h('div', null,
        h('div', { className: 'sidebar-logo-title' }, 'سِنان كلينيك'),
        h('div', { className: 'sidebar-logo-sub' }, 'إدارة عيادة متكاملة'),
      ),
    ),
    h('div', { className: 'sidebar-group-label' }, 'العيادة'),
    h('nav', { className: 'nav-items' }, mainNav.map(renderItem)),
    h('div', { className: 'sidebar-group-label' }, 'الإدارة'),
    h('nav', { className: 'nav-items' }, adminNav.map(renderItem)),
    h('div', { className: 'sidebar-group-label' }, 'النظام'),
    h('nav', { className: 'nav-items' }, systemNav.map(renderItem)),
    h('div', { style: { flex: '0 0 auto' } }),
    h('div', { className: 'sidebar-footer' },
      h('div', { className: 'avatar' }, (clinicName || 'ع').substring(0, 2)),
      h('div', { style: { flex: 1, minWidth: 0 } },
        h('div', { style: { fontSize: 13, fontWeight: 700, color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, clinicName || 'عيادتي'),
        h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, user?.email || ''),
      ),
      h('button', {
        className: 'icon-btn',
        title: 'تسجيل الخروج',
        style: { width: 32, height: 32 },
        onClick: () => { if (confirm('هل تريد تسجيل الخروج؟')) setLoggedIn(false); },
      },
        h(Icons.LogOut, { size: 16 }),
      ),
    ),
  );
}

// ==================== Topbar ====================
function Topbar({ title, subtitle, actions }) {
  const { setTheme, theme, toggleTweaks, showTweaks, dataLoading } = useContext(AppContext);
  const [showNotifs, setShowNotifs] = useState(false);

  return h('header', { className: 'topbar' },
    h('div', null,
      h('div', { style: { fontWeight: 800, fontSize: 18, color: 'var(--text-primary)', display: 'flex', alignItems: 'center', gap: 8 } },
        title,
        dataLoading ? h('div', { style: { width: 14, height: 14, border: '2px solid var(--border)', borderTopColor: 'var(--accent)', borderRadius: '50%', animation: 'spin 0.8s linear infinite', flexShrink: 0 } }) : null,
      ),
      subtitle ? h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 } }, subtitle) : null,
    ),
    h('div', { className: 'search' },
      h('input', { placeholder: 'بحث عن مريض، موعد، فاتورة...', type: 'text' }),
      h('span', { className: 'search-icon' }, h(Icons.Search, { size: 16 })),
    ),
    h('div', { className: 'topbar-actions' },
      actions || null,
      h('button', {
        className: 'icon-btn',
        title: 'تبديل الوضع',
        onClick: () => setTheme(theme === 'luxe' ? 'clean' : 'luxe'),
      }, h(theme === 'luxe' ? Icons.Sun : Icons.Moon, { size: 18 })),
      h('div', { style: { position: 'relative' } },
        h('button', {
          className: 'icon-btn',
          onClick: () => setShowNotifs(!showNotifs),
        },
          h(Icons.Bell, { size: 18 }),
          h('span', { className: 'pulse-dot' }),
        ),
        showNotifs ? h(NotificationsDropdown, { onClose: () => setShowNotifs(false) }) : null,
      ),
      h('button', { className: 'icon-btn' }, h(Icons.MessageCircle, { size: 18 })),
      h('div', { style: { width: 1, height: 24, background: 'var(--border)', margin: '0 4px' } }),
      h('div', { className: 'avatar sm' }, 'مد'),
    ),
  );
}

function NotificationsDropdown({ onClose }) {
  return h(Fragment, null,
    h('div', { style: { position: 'fixed', inset: 0, zIndex: 40 }, onClick: onClose }),
    h('div', {
      className: 'card scale-in',
      style: {
        position: 'absolute', top: 'calc(100% + 8px)', insetInlineStart: 0,
        width: 340, zIndex: 50, boxShadow: 'var(--shadow-lg)', padding: 0, overflow: 'hidden',
      },
    },
      h('div', { style: { padding: '14px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' } },
        h('div', { style: { fontWeight: 800, fontSize: 14 } }, 'الإشعارات'),
        h('span', { className: 'chip accent' }, window.NOTIFICATIONS.length + ' جديد'),
      ),
      h('div', { style: { maxHeight: 360, overflowY: 'auto' } },
        window.NOTIFICATIONS.map(n => h('div', {
          key: n.id,
          style: { padding: '12px 16px', borderBottom: '1px solid var(--border)', display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer' },
        },
          h('div', {
            style: {
              width: 32, height: 32, borderRadius: 8, display: 'grid', placeItems: 'center', flexShrink: 0,
              background: `var(--${n.type}-soft)`, color: `var(--${n.type})`,
            },
          },
            h(n.type === 'warning' ? Icons.AlertTriangle : n.type === 'success' ? Icons.Check : Icons.Info, { size: 16 }),
          ),
          h('div', { style: { flex: 1, minWidth: 0 } },
            h('div', { style: { fontSize: 13, color: 'var(--text-primary)', fontWeight: 500 } }, n.text),
            h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 } }, n.time),
          ),
        )),
      ),
      h('div', { style: { padding: 10, textAlign: 'center' } },
        h('button', { className: 'btn ghost sm w-full' }, 'عرض الكل'),
      ),
    ),
  );
}

// ==================== Toast ====================
function Toast({ message, onDone }) {
  useEffect(() => {
    if (!message) return;
    const t = setTimeout(onDone, 2800);
    return () => clearTimeout(t);
  }, [message]);
  if (!message) return null;
  return h('div', { className: 'toast success' },
    h('div', { className: 'toast-icon' }, h(Icons.Check, { size: 16 })),
    h('div', null, message),
  );
}

// ==================== Modal ====================
function Modal({ open, onClose, title, children, footer, size = 'md' }) {
  useEffect(() => {
    if (!open) return;
    const onEsc = (e) => e.key === 'Escape' && onClose && onClose();
    window.addEventListener('keydown', onEsc);
    return () => window.removeEventListener('keydown', onEsc);
  }, [open, onClose]);
  if (!open) return null;
  return h('div', { className: 'modal-backdrop', onClick: onClose },
    h('div', {
      className: 'modal ' + (size === 'lg' ? 'lg' : size === 'xl' ? 'xl' : ''),
      onClick: (e) => e.stopPropagation(),
    },
      h('div', { className: 'modal-header' },
        h('div', { className: 'modal-title' }, title),
        h('button', { className: 'icon-btn', onClick: onClose }, h(Icons.X, { size: 18 })),
      ),
      h('div', { className: 'modal-body' }, children),
      footer ? h('div', { className: 'modal-footer' }, footer) : null,
    ),
  );
}

// ==================== Tweaks Panel ====================
function TweaksPanel() {
  const { theme, setTheme, density, setDensity, clinicName, setClinicName, showTweaks, toggleTweaks } = useContext(AppContext);
  if (!showTweaks) return null;

  return h('div', { className: 'tweaks-panel' },
    h('h4', null,
      h('span', null, '⚙  إعدادات التصميم'),
      h('button', { className: 'icon-btn', style: { width: 26, height: 26 }, onClick: toggleTweaks },
        h(Icons.X, { size: 14 }),
      ),
    ),
    h('div', { className: 'tweak-row' },
      h('span', { className: 'label-txt' }, 'المظهر'),
      h('div', { className: 'theme-swatches' },
        ['clean', 'luxe', 'warm'].map(t => h('div', {
          key: t,
          className: 'theme-swatch' + (theme === t ? ' active' : ''),
          'data-preview': t,
          onClick: () => setTheme(t),
          title: t === 'clean' ? 'طبي نظيف' : t === 'luxe' ? 'فاخر داكن' : 'دافئ',
        })),
      ),
    ),
    h('div', { className: 'tweak-row' },
      h('span', { className: 'label-txt' }, 'الكثافة'),
      h('div', { style: { display: 'flex', gap: 4 } },
        ['مدمجة', 'مريحة'].map((d, i) => h('button', {
          key: d,
          className: 'btn sm ' + (density === (i === 0 ? 'compact' : 'comfortable') ? 'primary' : 'outline'),
          onClick: () => setDensity(i === 0 ? 'compact' : 'comfortable'),
        }, d)),
      ),
    ),
    h('div', { className: 'tweak-row', style: { flexDirection: 'column', alignItems: 'stretch', gap: 6 } },
      h('span', { className: 'label-txt' }, 'اسم العيادة'),
      h('input', {
        className: 'input',
        style: { padding: '6px 10px', fontSize: 12 },
        value: clinicName,
        onChange: (e) => setClinicName(e.target.value),
      }),
    ),
    h('div', { style: { fontSize: 10, color: 'var(--text-muted)', marginTop: 8, textAlign: 'center' } },
      'استخدم زر Tweaks في الشريط العلوي للإخفاء',
    ),
  );
}

window.Shell = { Sidebar, Topbar, Toast, Modal, TweaksPanel };
