// App shell — sidebar, topbar, tweaks panel

const NAV_BY_ROLE = {
  reception: [
    { section: 'Asosiy', items: [
      { id: 'dashboard',  label: "Boshqaruv paneli", icon: 'house' },
      { id: 'new-visit',  label: "Yangi rentgen",     icon: 'plus-circle', highlight: true },
      { id: 'patients',   label: 'Bemorlar',          icon: 'users-three' },
    ]},
    { section: 'Kassa', items: [
      { id: 'kassa',      label: 'Yozuvlar',          icon: 'list-bullets' },
      { id: 'debts',      label: 'Qarzlar',           icon: 'warning' },
    ]},
  ],
  doctor: [
    { section: 'Asosiy', items: [
      { id: 'doctor-dashboard', label: "Boshqaruv paneli", icon: 'house' },
      { id: 'doctor-patients',  label: 'Bemorlarim',  icon: 'users-three' },
    ]},
  ],
  admin: [
    { section: 'Asosiy', items: [
      { id: 'dashboard',  label: "Boshqaruv paneli", icon: 'house' },
      { id: 'new-visit',  label: "Yangi rentgen",     icon: 'plus-circle' },
      { id: 'patients',   label: 'Bemorlar',          icon: 'users-three' },
    ]},
    { section: 'Kassa', items: [
      { id: 'kassa',      label: 'Yozuvlar',          icon: 'list-bullets' },
      { id: 'debts',      label: 'Qarzlar',           icon: 'warning' },
      { id: 'reports',    label: 'Hisobotlar',        icon: 'chart-line-up' },
    ]},
    { section: 'Boshqaruv', items: [
      { id: 'services',   label: 'Xizmatlar',         icon: 'package' },
      { id: 'doctors',    label: 'Shifokorlar',       icon: 'stethoscope' },
    ]},
  ],
  super_admin: [
    { section: 'Asosiy', items: [
      { id: 'dashboard',  label: "Boshqaruv paneli", icon: 'house' },
      { id: 'new-visit',  label: "Yangi rentgen",     icon: 'plus-circle' },
      { id: 'patients',   label: 'Bemorlar',          icon: 'users-three' },
    ]},
    { section: 'Kassa', items: [
      { id: 'kassa',      label: 'Yozuvlar',          icon: 'list-bullets' },
      { id: 'debts',      label: 'Qarzlar',           icon: 'warning' },
      { id: 'reports',    label: 'Hisobotlar',        icon: 'chart-line-up' },
    ]},
    { section: 'Boshqaruv', items: [
      { id: 'services',   label: 'Xizmatlar',         icon: 'package' },
      { id: 'doctors',    label: 'Shifokorlar',       icon: 'stethoscope' },
      { id: 'users',      label: 'Foydalanuvchilar',  icon: 'user-gear' },
      { id: 'audit',      label: 'Audit log',         icon: 'shield-check' },
      { id: 'settings',   label: 'Sozlamalar',        icon: 'gear' },
    ]},
  ],
};

function Sidebar({ role, page, onNav, collapsed, activeUser }) {
  const sections = NAV_BY_ROLE[role] || NAV_BY_ROLE.reception;
  return (
    <aside className="sidebar">
      <div className="sidebar__brand">
        <LogoMark size={32} />
        <div className="sidebar__title" style={{ lineHeight: 1.1 }}>
          Your <span style={{ color: 'var(--brand-secondary)' }}>Smile</span>
          <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.16em', color: 'var(--fg-3)', textTransform: 'uppercase', marginTop: 1 }}>Rentgen</div>
        </div>
      </div>

      <nav className="sidebar__nav">
        {sections.map(section => (
          <div key={section.section} className="nav-section">
            <div className="nav-section__label">{section.section}</div>
            {section.items.map(item => (
              <div
                key={item.id}
                className={`nav-item ${page === item.id ? 'is-active' : ''}`}
                onClick={() => onNav(item.id)}
                title={collapsed ? item.label : undefined}
              >
                <Icon name={item.icon} className="nav-item__icon" />
                <span className="nav-item__label">{item.label}</span>
                {item.highlight && <Icon name="sparkle" weight="fill" className="nav-item__badge" style={{ background: 'transparent', color: 'var(--brand-secondary)', fontSize: 14, padding: 0 }} />}
              </div>
            ))}
          </div>
        ))}
      </nav>

      <div className="sidebar__footer">
        <Avatar name={activeUser.full_name || activeUser.name || '?'} />
        <div className="sidebar__footer-text">
          <div className="sidebar__footer-name">{activeUser.full_name || activeUser.name || '—'}</div>
          <div className="sidebar__footer-role">{ROLE_LABELS[role]}</div>
        </div>
        <button className="icon-btn" title="Chiqish" onClick={() => onNav('login')}><Icon name="sign-out" /></button>
      </div>
    </aside>
  );
}

function Topbar({ title, breadcrumbs, role, me, onNav, onToggleSidebar, theme, onToggleTheme, onShowNotif, onShowTweaks }) {
  const [showMenu, setShowMenu] = useState(false);
  const wrapRef = useRef(null);

  useEffect(() => {
    const h = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setShowMenu(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);

  const fullName = (me && (me.full_name || me.name)) || '—';

  return (
    <header className="topbar">
      <button className="topbar__toggle" onClick={onToggleSidebar} aria-label="Sidebar"><Icon name="sidebar-simple" /></button>
      <div style={{ minWidth: 0, flex: 1 }}>
        {breadcrumbs && (
          <div className="page-header__breadcrumbs" style={{ margin: 0, fontSize: 11 }}>
            {breadcrumbs.map((b, i) => (
              <React.Fragment key={i}>
                {i > 0 && <Icon name="caret-right" style={{ fontSize: 10 }} />}
                <span>{b}</span>
              </React.Fragment>
            ))}
          </div>
        )}
        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '-0.01em' }}>{title}</div>
      </div>

      <div className="topbar__actions">
        <span className="role-pill"><Icon name="user-circle" style={{ fontSize: 12 }} />{ROLE_LABELS[role]}</span>
        <button className="topbar__btn" onClick={onShowNotif} aria-label="Bildirishnomalar">
          <Icon name="bell" />
        </button>
        <button className="topbar__btn" onClick={onToggleTheme} aria-label="Mavzu" title={theme === 'dark' ? "Yorug' rejim" : "Tungi rejim"}>
          <Icon name={theme === 'dark' ? 'sun' : 'moon'} />
        </button>
        <div ref={wrapRef} style={{ position: 'relative' }}>
          <div className="topbar__user" onClick={() => setShowMenu(v => !v)}>
            <Avatar name={fullName} />
            <span className="topbar__user-name">{fullName}</span>
            <Icon name="caret-down" style={{ fontSize: 14, color: 'var(--fg-3)' }} />
          </div>
          {showMenu && (
            <div className="menu" style={{ position: 'absolute', top: '110%', right: 0, minWidth: 220, zIndex: 60 }}>
              <div className="menu__item" style={{ pointerEvents: 'none', opacity: 0.85 }}>
                <Icon name="user" />{fullName}
              </div>
              <div className="menu__item" onClick={() => { setShowMenu(false); onShowTweaks && onShowTweaks(); }}><Icon name="sliders-horizontal" />Ko'rinish sozlamalari</div>
              <div className="menu__sep"></div>
              <div className="menu__item menu__item--danger" onClick={() => { setShowMenu(false); onNav && onNav('login'); }}><Icon name="sign-out" />Chiqish</div>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}

/* ---------- Notifications panel (slide-in from right) — REAL API ---------- */
const NOTIF_ICONS = {
  new_xray: 'tooth', link_attached: 'link', link_requested: 'bell-ringing',
  payment_received: 'money', default: 'bell',
};
function NotifPanel({ open, onClose }) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);

  const load = useCallback(() => {
    if (!window.API) return;
    setLoading(true);
    window.API.listNotifications(false)
      .then(rows => setItems(Array.isArray(rows) ? rows : []))
      .catch(() => setItems([]))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => { if (open) load(); }, [open, load]);

  const unread = items.filter(n => !n.is_read).length;

  const markAll = () => {
    if (!window.API) return;
    window.API.markAllRead().then(() => load()).catch(() => {});
  };

  if (!open) return null;
  return (
    <div className="modal-scrim" onClick={onClose} style={{ alignItems: 'stretch', justifyContent: 'flex-end', padding: 0 }}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 380, maxWidth: '100%', height: '100vh', maxHeight: '100vh', borderRadius: 0, animation: 'slide-down 280ms var(--ease-out)' }}>
        <div className="modal__header">
          <h3 className="modal__title"><Icon name="bell" style={{ marginRight: 8 }} />Bildirishnomalar</h3>
          <button className="modal__close" onClick={onClose}><Icon name="x" /></button>
        </div>
        <div className="modal__body" style={{ padding: 0 }}>
          <div style={{ padding: '8px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid var(--border-2)' }}>
            <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>{unread > 0 ? `${unread} yangi` : "Yangi yo'q"}</span>
            <button className="btn btn--ghost btn--sm" onClick={markAll} disabled={unread === 0}>Hammasi o'qildi</button>
          </div>
          <div style={{ padding: '0 16px' }}>
            {loading && <div style={{ padding: 24, textAlign: 'center', color: 'var(--fg-4)', fontSize: 13 }}>Yuklanmoqda…</div>}
            {!loading && items.length === 0 && (
              <div style={{ padding: 32, textAlign: 'center', color: 'var(--fg-4)' }}>
                <Icon name="bell-slash" style={{ fontSize: 28, opacity: 0.5 }} />
                <p style={{ fontSize: 13, marginTop: 8 }}>Hozircha bildirishnoma yo'q</p>
              </div>
            )}
            {!loading && items.map(n => (
              <div key={n.id} className="activity-item" style={{ opacity: n.is_read ? 0.6 : 1 }}>
                <div className="activity-item__dot activity-item__dot--info"><Icon name={NOTIF_ICONS[n.type] || NOTIF_ICONS.default} /></div>
                <div className="activity-item__body">
                  <p className="activity-item__text"><strong>{n.title}</strong></p>
                  <p className="activity-item__text" style={{ color: 'var(--fg-3)' }}>{n.message}</p>
                  <span className="activity-item__meta">{window.uzDateTime ? window.uzDateTime(n.created_at) : n.created_at}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Ko'rinish sozlamalari paneli (rol-almashtirgich OLIB TASHLANDI — production) ---------- */
function TweaksPanel({ open, onClose, state, setState }) {
  if (!open) return null;
  return (
    <div className="modal-scrim" onClick={onClose} style={{ alignItems: 'stretch', justifyContent: 'flex-end', padding: 0 }}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 360, maxWidth: '100%', height: '100vh', maxHeight: '100vh', borderRadius: 0 }}>
        <div className="modal__header">
          <h3 className="modal__title"><Icon name="sliders-horizontal" style={{ marginRight: 8 }} />Ko'rinish sozlamalari</h3>
          <button className="modal__close" onClick={onClose}><Icon name="x" /></button>
        </div>
        <div className="modal__body" style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>

          <div>
            <div className="t-eyebrow" style={{ marginBottom: 10 }}>Mavzu</div>
            <div style={{ display: 'flex', gap: 8 }}>
              {['light', 'dark'].map(t => (
                <button key={t}
                  className={`chip ${state.theme === t ? 'is-active' : ''}`}
                  style={{ flex: 1, padding: '10px 14px' }}
                  onClick={() => setState({ ...state, theme: t })}>
                  <Icon name={t === 'dark' ? 'moon' : 'sun'} style={{ marginRight: 6, verticalAlign: 'text-bottom', fontSize: 14 }} />
                  {t === 'dark' ? "Tungi" : "Yorug'"}
                </button>
              ))}
            </div>
          </div>

          <div>
            <div className="t-eyebrow" style={{ marginBottom: 10 }}>Sidebar</div>
            <div style={{ display: 'flex', gap: 8 }}>
              {[{id:'expanded',l:"Kengaytirilgan"},{id:'collapsed',l:"Yig'ilgan"}].map(t => (
                <button key={t.id}
                  className={`chip ${state.sidebar === t.id ? 'is-active' : ''}`}
                  style={{ flex: 1, padding: '10px 14px' }}
                  onClick={() => setState({ ...state, sidebar: t.id })}>{t.l}</button>
              ))}
            </div>
          </div>

          <div>
            <div className="t-eyebrow" style={{ marginBottom: 10 }}>Zichlik</div>
            <div style={{ display: 'flex', gap: 8 }}>
              {[{id:'comfortable',l:'Bemalol'},{id:'compact',l:'Zich'}].map(t => (
                <button key={t.id}
                  className={`chip ${state.density === t.id ? 'is-active' : ''}`}
                  style={{ flex: 1, padding: '10px 14px' }}
                  onClick={() => setState({ ...state, density: t.id })}>{t.l}</button>
              ))}
            </div>
          </div>

          <div>
            <div className="t-eyebrow" style={{ marginBottom: 10 }}>Brend rang</div>
            <div style={{ display: 'flex', gap: 8 }}>
              {[
                { id: 'slate', name: 'Slate', c: '#0F172A' },
                { id: 'sky',   name: 'Sky',   c: '#0EA5E9' },
                { id: 'indigo', name: 'Indigo', c: '#4F46E5' },
                { id: 'teal',  name: 'Teal',  c: '#0D9488' },
              ].map(c => (
                <button key={c.id}
                  onClick={() => setState({ ...state, brand: c.id })}
                  title={c.name}
                  style={{
                    flex: 1, height: 40, borderRadius: 10,
                    background: c.c, border: state.brand === c.id ? '3px solid var(--surface-1)' : '1px solid var(--border-1)',
                    boxShadow: state.brand === c.id ? '0 0 0 2px ' + c.c : 'none',
                    cursor: 'pointer',
                  }} />
              ))}
            </div>
          </div>

          <div style={{ fontSize: 12, color: 'var(--fg-4)', borderTop: '1px solid var(--border-2)', paddingTop: 16 }}>
            <Icon name="info" style={{ marginRight: 6, verticalAlign: 'middle' }} />
            Bu sozlamalar faqat ko'rinishni o'zgartiradi.
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Page header ---------- */
function PageHeader({ title, sub, breadcrumbs, actions }) {
  return (
    <div className="page-header">
      <div style={{ minWidth: 0 }}>
        {breadcrumbs && (
          <div className="page-header__breadcrumbs">
            {breadcrumbs.map((b, i) => (
              <React.Fragment key={i}>
                {i > 0 && <Icon name="caret-right" style={{ fontSize: 10 }} />}
                <span>{b}</span>
              </React.Fragment>
            ))}
          </div>
        )}
        <h1 className="page-header__title t-h1" style={{ fontSize: 28 }}>{title}</h1>
        {sub && <p className="page-header__sub">{sub}</p>}
      </div>
      {actions && <div className="row row-3">{actions}</div>}
    </div>
  );
}

Object.assign(window, { Sidebar, Topbar, NotifPanel, TweaksPanel, PageHeader, NAV_BY_ROLE, NOTIF_ICONS });
