// Sidebar + Topbar — wired to real user data
const { useState: _us, useEffect: _ue } = React;

function Sidebar({ mode, setMode, route, setRoute, me }) {
  const [mobileOpen, setMobileOpen] = _us(false);

  // Close drawer when route changes (auto-dismiss after nav)
  _ue(() => { setMobileOpen(false); }, [route, mode]);

  // Close drawer when window resized to desktop
  _ue(() => {
    const onResize = () => { if (window.innerWidth > 900) setMobileOpen(false); };
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  // Listen for mobile menu open events (dispatched by Topbar hamburger)
  _ue(() => {
    const open = () => setMobileOpen(true);
    window.addEventListener('hdr:open-menu', open);
    return () => window.removeEventListener('hdr:open-menu', open);
  }, []);

  const userNav = [
    { key: 'overview',  label: 'Overview',  icon: <I.home/> },
    { key: 'playground',label: 'Playground',icon: <I.play/> },
    { key: 'agents',    label: 'My Agents', icon: <I.bot/> },
    { key: 'skills',    label: 'My Skills', icon: <I.star/> },
    { key: 'keys',      label: 'API Keys',  icon: <I.key/> },
    { key: 'billing',   label: 'Billing',   icon: <I.wallet/> },
    { key: 'logs',      label: 'Logs',      icon: <I.list/> },
    { key: 'docs',      label: 'Docs',      icon: <I.book/> },
  ];
  const adminNav = [
    { key: 'overview',  label: 'Overview',  icon: <I.home/> },
    { key: 'analytics', label: 'Analytics', icon: <I.chart/> },
    { key: 'users',     label: 'Users',     icon: <I.users/> },
    { key: 'alllogs',   label: 'All Logs',  icon: <I.list/> },
    { key: 'models',    label: 'Models',    icon: <I.cube/> },
    { key: 'skills',    label: 'Skills',    icon: <I.star/> },
    { key: 'tools',     label: 'Tools',     icon: <I.wrench/> },
    { key: 'settings',  label: 'Settings',  icon: <I.cog/> },
  ];
  const nav = mode === 'admin' ? adminNav : userNav;

  const logout = async () => {
    await window.HDR_API.logout();
    location.href = '/';
  };

  const initials = (me?.name || me?.email || 'U').split(/\s+/).map(p => p[0]).filter(Boolean).slice(0,2).join('').toUpperCase();

  return (
    <>
      {/* Backdrop — appears behind drawer */}
      <div className={'sidebar-backdrop' + (mobileOpen ? ' open' : '')}
           onClick={() => setMobileOpen(false)}/>

      <aside className={'sidebar' + (mobileOpen ? ' open' : '')}>
        <div className="sidebar-brand">
          <div className="brand-mark">H</div>
          <div style={{minWidth: 0, flex: 1, overflow: 'hidden'}}>
            <div className="brand-name">Hidrogen<span className="brand-suffix">.in</span></div>
            <div className="dim" style={{fontSize: 10, fontFamily: 'var(--font-mono)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>v2.4 · ap-south-1</div>
          </div>
          {/* Close button on mobile */}
          <button className="icon-btn show-mobile-close" onClick={() => setMobileOpen(false)} aria-label="Close menu"
                  style={{display: 'none'}}>
            <I.x/>
          </button>
        </div>

        {!!me?.is_admin && (
          <div className="mode-switcher">
            <button className={mode === 'user' ? 'active' : ''} onClick={() => { setMode('user'); setRoute('overview'); }}>
              <span className="dot"/> User
            </button>
            <button data-admin className={mode === 'admin' ? 'active' : ''} onClick={() => { setMode('admin'); setRoute('overview'); }}>
              <span className="dot"/> Admin
            </button>
          </div>
        )}

        <nav className="nav">
          <div className="nav-section-label">{mode === 'admin' ? 'Operations' : 'Workspace'}</div>
          {nav.map(item => (
            <div key={item.key}
                 className={'nav-item' + (route === item.key ? ' active' : '')}
                 onClick={() => setRoute(item.key)}>
              {item.icon}<span>{item.label}</span>
            </div>
          ))}
        </nav>

        <div className="sidebar-foot">
          <div className="avatar">{initials}</div>
          <div style={{minWidth: 0, flex: 1}}>
            <div className="name">{me?.name || me?.email?.split('@')[0] || 'User'}</div>
            <div className="sub">{me?.is_admin ? 'Admin' : me?.email}</div>
          </div>
          <button className="icon-btn" title="Log out" onClick={logout}><I.logout/></button>
        </div>
      </aside>
    </>
  );
}

// Hamburger button — rendered separately inside Topbar
function MobileMenuBtn({ onClick }) {
  return (
    <button className="mobile-menu-btn" onClick={onClick} aria-label="Open menu">
      <I.menu/>
    </button>
  );
}
window.MobileMenuBtn = MobileMenuBtn;

function Topbar({ mode, route, theme, setTheme, me }) {
  const titles = {
    user: {
      overview: 'Overview', playground: 'Playground', agents: 'My Agents',
      skills: 'My Skills', keys: 'API Keys', billing: 'Billing', logs: 'Logs', docs: 'Docs',
    },
    admin: {
      overview: 'Admin Overview', analytics: 'Analytics', users: 'Users',
      alllogs: 'All Logs', models: 'Models', skills: 'Skills',
      tools: 'Tools', settings: 'Settings',
    },
  };

  const [pulse, setPulse] = _us(null);

  // Admin: live pulse polling for "X req/min"
  _ue(() => {
    if (mode !== 'admin') return;
    const tick = async () => {
      try { const p = await window.HDR_API.adminPulse(); setPulse(p.summary); } catch {}
    };
    tick();
    const id = setInterval(tick, 15000);
    return () => clearInterval(id);
  }, [mode]);

  return (
    <div className="topbar">
      <button className="mobile-menu-btn" onClick={() => window.dispatchEvent(new Event('hdr:open-menu'))} aria-label="Open menu">
        <I.menu/>
      </button>
      <div className="crumb">
        <span>{mode === 'admin' ? 'Admin' : 'Dashboard'}</span>
        <span className="sep">/</span>
        <span className="curr">{titles[mode][route] || ''}</span>
      </div>
      <div className="topbar-spacer"/>

      {mode === 'admin' ? (
        <div className="live-pill">
          <span className="live-dot"/>
          <span>{pulse ? `Live · ${pulse.reqs_60min || 0} req/h` : 'Live'}</span>
        </div>
      ) : (
        <div className="wallet-pill">
          <I.wallet/>
          <span className="wp-amt">{window.HDR_UTIL.rupees(me?.wallet_paise || 0)}</span>
          <button className="add" onClick={() => {
            const ev = new CustomEvent('hdr:goto-billing'); window.dispatchEvent(ev);
          }}>+ Add</button>
        </div>
      )}

      <button className="icon-btn" title="Toggle theme" onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
        {theme === 'dark' ? <I.sun/> : <I.moon/>}
      </button>
    </div>
  );
}

window.Sidebar = Sidebar;
window.Topbar = Topbar;
