// MissionChef — App Shell (Sidebar + Topbar + Router + Theme toggle)

function useStore() {
  const [, force] = React.useState(0);
  React.useEffect(() => mcApi.subscribe(() => force(n => n + 1)), []);
  return mcStore;
}

function useTheme() {
  const [theme, setTheme] = React.useState(() => localStorage.getItem('mc-theme') || 'light');
  React.useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('mc-theme', theme);
  }, [theme]);
  return [theme, setTheme];
}

const MODULES = [
  { id: 'dashboard',   label: 'Dashboard',       icon: 'dashboard' },
  { id: 'reservations',label: 'Reservierungen',  icon: 'calendar' },
  { id: 'pos',         label: 'Kasse',           icon: 'cart' },
  { id: 'kds',         label: 'Küche · KDS',     icon: 'flame' },
  { id: 'roster',      label: 'Dienstplan',      icon: 'clock' },
  { id: 'inventory',   label: 'Warenwirtschaft', icon: 'stock' },
  { id: 'catering',    label: 'Catering',        icon: 'truck' },
  { id: 'staff',       label: 'Mitarbeiter',     icon: 'team' },
  { id: 'marketing',   label: 'Marketing',       icon: 'megaphone' },
  { id: 'reports',     label: 'Berichte',        icon: 'chart' },
  { id: 'settings',    label: 'Einstellungen',   icon: 'settings' },
];

function Sidebar({ current, onNav, collapsed, onCollapse }) {
  return (
    <aside style={{
      width: collapsed ? 72 : 232,
      background: 'var(--mc-surface)',
      borderRight: '1px solid var(--mc-rule)',
      display: 'flex', flexDirection: 'column',
      transition: 'width .2s ease',
      flexShrink: 0,
    }}>
      <div style={{ padding: collapsed ? '22px 0' : '22px 20px', display: 'flex', alignItems: 'center', gap: 10, justifyContent: collapsed ? 'center' : 'flex-start', borderBottom: '1px solid var(--mc-rule)' }}>
        <McLogoTile size={28} />
        {!collapsed && <McWordmark size={17} />}
      </div>

      <nav style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 2, flex: 1 }}>
        {MODULES.map(m => {
          const active = current === m.id;
          return (
            <button key={m.id} onClick={() => onNav(m.id)} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: collapsed ? '11px 0' : '10px 12px',
              justifyContent: collapsed ? 'center' : 'flex-start',
              background: active ? 'var(--mc-surface-2)' : 'transparent',
              color: active ? 'var(--mc-ink)' : 'var(--mc-ink-muted)',
              border: 'none',
              borderLeft: active ? '2px solid var(--mc-leaf)' : '2px solid transparent',
              fontFamily: "'Space Grotesk', sans-serif", fontSize: 14, fontWeight: active ? 500 : 400,
              cursor: 'pointer', textAlign: 'left',
              letterSpacing: '-0.005em',
            }}>
              <McIcon2 name={m.icon} size={18} />
              {!collapsed && <span>{m.label}</span>}
            </button>
          );
        })}
      </nav>

      <div style={{ padding: 12, borderTop: '1px solid var(--mc-rule)' }}>
        <button onClick={onCollapse} style={{
          width: '100%', border: 'none', background: 'transparent',
          color: 'var(--mc-ink-dim)', cursor: 'pointer',
          padding: 8, display: 'flex', alignItems: 'center', gap: 10, justifyContent: collapsed ? 'center' : 'flex-start',
          fontFamily: "'Space Grotesk', sans-serif", fontSize: 12,
        }}>
          <McIcon2 name="menu" size={16} />
          {!collapsed && <span>Einklappen</span>}
        </button>
      </div>
    </aside>
  );
}

function Topbar({ title, subtitle, actions, theme, setTheme }) {
  const store = useStore();
  const [openNotifs, setOpenNotifs] = React.useState(false);
  return (
    <header style={{
      height: 68, borderBottom: '1px solid var(--mc-rule)',
      background: 'var(--mc-surface)',
      display: 'flex', alignItems: 'center', padding: '0 28px', gap: 20,
      flexShrink: 0,
    }}>
      <div style={{ flex: 1 }}>
        <div className="mc-eyebrow">{subtitle}</div>
        <div style={{ fontSize: 20, fontWeight: 500, letterSpacing: '-0.015em', marginTop: 2 }}>{title}</div>
      </div>

      {actions}

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginLeft: 'auto' }}>
        <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')} title="Theme" style={{
          width: 36, height: 36, border: '1px solid var(--mc-rule)', background: 'var(--mc-surface)',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--mc-ink)',
        }}>
          <McIcon2 name={theme === 'light' ? 'moon' : 'sun'} size={16} />
        </button>

        <div style={{ position: 'relative' }}>
          <button onClick={() => setOpenNotifs(v => !v)} style={{
            width: 36, height: 36, border: '1px solid var(--mc-rule)', background: 'var(--mc-surface)',
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--mc-ink)', position: 'relative',
          }}>
            <McIcon2 name="bell" size={16} />
            <span style={{ position: 'absolute', top: 6, right: 6, width: 7, height: 7, background: 'var(--mc-ember)', borderRadius: '50%' }} />
          </button>
          {openNotifs && <NotifsPanel onClose={() => setOpenNotifs(false)} />}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingLeft: 12, borderLeft: '1px solid var(--mc-rule)' }}>
          <div style={{ width: 32, height: 32, background: 'var(--mc-ink)', color: 'var(--mc-bg)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: 12, fontWeight: 600, borderRadius: 2 }}>
            PW
          </div>
          <div style={{ lineHeight: 1.2 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{store.session.name}</div>
            <div style={{ fontSize: 11, color: 'var(--mc-ink-dim)' }}>{store.biz.name}</div>
          </div>
        </div>
      </div>
    </header>
  );
}

function NotifsPanel({ onClose }) {
  const store = useStore();
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 10 }} />
      <div style={{
        position: 'absolute', right: 0, top: 44, width: 360,
        background: 'var(--mc-surface)', border: '1px solid var(--mc-rule)',
        boxShadow: 'var(--mc-shadow)', zIndex: 20,
      }}>
        <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--mc-rule)', display: 'flex', justifyContent: 'space-between' }}>
          <div style={{ fontWeight: 500, fontSize: 14 }}>Benachrichtigungen</div>
          <div className="mc-eyebrow">{store.notifs.length} neu</div>
        </div>
        {store.notifs.map(n => (
          <div key={n.id} style={{ padding: '12px 16px', borderBottom: '1px solid var(--mc-rule)', display: 'flex', gap: 10 }}>
            <StatusDot tone={n.tone === 'leaf' ? 'ok' : n.tone === 'ember' ? 'warn' : 'info'} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13 }}>{n.msg}</div>
              <div style={{ fontSize: 11, color: 'var(--mc-ink-dim)', marginTop: 2 }}>
                vor {Math.round((Date.now() - n.at) / 60000)} Min
              </div>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

function AppShell({ module, onNav }) {
  const [theme, setTheme] = useTheme();
  const [collapsed, setCollapsed] = React.useState(false);
  const modMeta = MODULES.find(m => m.id === module);

  const ModuleComponent = {
    dashboard: DashboardScreen,
    reservations: ReservationsScreen,
    pos: PosScreen,
    kds: KdsScreen,
    roster: RosterScreen,
    inventory: InventoryScreen,
    catering: CateringScreenV2,
    staff: StaffScreen,
    marketing: MarketingScreen,
    reports: ReportsScreen,
    settings: SettingsScreen,
  }[module] || DashboardScreen;

  return (
    <div className="mc-app" data-screen-label={modMeta?.label || module} style={{
      display: 'flex', height: '100vh', width: '100%',
      overflow: 'hidden',
    }}>
      <Sidebar current={module} onNav={onNav} collapsed={collapsed} onCollapse={() => setCollapsed(v => !v)} />
      <main style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        <ModuleComponent
          theme={theme} setTheme={setTheme}
          Topbar={(props) => <Topbar {...props} theme={theme} setTheme={setTheme} />}
        />
      </main>
    </div>
  );
}

Object.assign(window, { AppShell, useStore, useTheme, MODULES, Topbar, Sidebar });
