// App shell: sidebar + topbar + routing
const { useState, useEffect, useMemo, useRef, createContext, useContext } = React;

const AppCtx = createContext(null);
const useApp = () => useContext(AppCtx);

const NAV = [
  { id: 'dashboard', label: 'Dashboard', icon: 'dashboard' },
  { id: 'cabinet', label: 'Cabinet', icon: 'cabinet', section: 'Medicines', badge: 2 },
  { id: 'schedule', label: 'Schedule & Log', icon: 'clock', section: 'Medicines' },
  { id: 'regimens', label: 'Regimens', icon: 'list', section: 'Medicines' },
  { id: 'organizer', label: 'Pill Organizer', icon: 'calendar', section: 'Medicines' },
  { id: 'library', label: 'Library', icon: 'pill', section: 'Medicines' },
  { id: 'refills', label: 'Shopping list', icon: 'refresh', section: 'Medicines', badge: 1 },
  { id: 'purchases', label: 'Purchases', icon: 'truck', section: 'Medicines' },
  { id: 'prices', label: 'Prices', icon: 'tag', section: 'Medicines' },
  { id: 'stores', label: 'Stores', icon: 'store', section: 'Medicines' },
  { id: 'activity', label: 'Activity & Spend', icon: 'trend', section: 'Medicines' },
  { id: 'settings', label: 'Settings', icon: 'settings' },
];

const Sidebar = ({ route, onNav }) => {
  const grouped = useMemo(() => {
    const g = {};
    NAV.forEach(n => { (g[n.section] = g[n.section] || []).push(n); });
    return g;
  }, []);
  return (
    <aside className="mt-side">
      <div className="mt-side__brand">
        <div className="mt-side__logo">
          <svg width="22" height="22" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="5" fill="var(--brand)"/><path d="M7 15l3-6 2 4 2-3 3 5" stroke="var(--brand-ink)" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
        <div className="mt-side__wordmark">
          <div className="mt-side__title">MeshiTrack</div>
          <div className="mt-side__sub">Red Panda Den</div>
        </div>
      </div>

      <nav className="mt-side__nav">
        {Object.entries(grouped).map(([section, items]) => (
          <div key={section} className="mt-side__group">
            <div className="mt-side__section">{section}</div>
            {items.map(item => (
              <button
                key={item.id}
                className={'mt-side__item' + (route === item.id ? ' is-active' : '') + (item.soon ? ' is-soon' : '')}
                onClick={() => !item.soon && onNav(item.id)}
                disabled={item.soon}
              >
                <Icon name={item.icon} size={16} />
                <span>{item.label}</span>
                {item.badge ? <span className="mt-side__badge">{item.badge}</span> : null}
                {item.soon ? <span className="mt-side__soon">Soon</span> : null}
              </button>
            ))}
          </div>
        ))}
      </nav>

      <div className="mt-side__foot">
        <div className="mt-side__avatar">A</div>
        <div className="mt-side__who">
          <div className="mt-side__whoName">aerimagne</div>
          <div className="mt-side__whoRole">Household owner</div>
        </div>
      </div>
    </aside>
  );
};

const Topbar = ({ title, subtitle, crumbs, onSearch, actions, theme, onToggleTheme }) => {
  return (
    <header className="mt-top">
      <div className="mt-top__left">
        {crumbs && crumbs.length > 1 && (
          <div className="mt-top__crumbs">
            {crumbs.map((c, i) => (
              <React.Fragment key={i}>
                {i > 0 && <Icon name="chev" size={12} style={{ opacity: 0.4 }} />}
                <span className={i === crumbs.length - 1 ? 'is-current' : ''}>{c}</span>
              </React.Fragment>
            ))}
          </div>
        )}
        <div className="mt-top__titles">
          <h1 className="mt-top__title">{title}</h1>
          {subtitle && <div className="mt-top__sub">{subtitle}</div>}
        </div>
      </div>
      <div className="mt-top__right">
        <div className="mt-top__search">
          <Icon name="search" size={14} />
          <input placeholder="Search medicines, regimens, stores…" />
          <kbd>⌘K</kbd>
        </div>
        <button className="mt-iconbtn" title="Notifications">
          <Icon name="bell" size={16} />
          <span className="mt-iconbtn__dot"></span>
        </button>
        <button className="mt-iconbtn" onClick={onToggleTheme} title="Toggle theme">
          <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={16} />
        </button>
        {actions}
      </div>
    </header>
  );
};

window.Shell = { Sidebar, Topbar, AppCtx, useApp, NAV };
