// Sidebar + Topbar + Layout shell
const { useState: useStateL, useEffect: useEffectL } = React;

const NAV = [
  { id: 'dashboard', label: 'Dashboard', icon: 'Dashboard' },
  // { id: 'agent', label: 'AI Agent', icon: 'Bot' },
  { id: 'sleep', label: 'Sleep', icon: 'Moon' },
  { id: 'activity', label: 'Activity', icon: 'Activity' },
  // { id: 'nutrition', label: 'Nutrition', icon: 'Apple' },
  // { id: 'mind', label: 'Mind & Body', icon: 'Heart' },
  // { id: 'rewards', label: 'Rewards', icon: 'Gift' },
  // { id: 'marketplace', label: 'Marketplace', icon: 'Store' },
  // { id: 'community', label: 'Community', icon: 'Users' },
];

const doLogout = async () => {
  try {
    if (window.AuthService) await window.AuthService.logout();
  } catch (e) {
    console.error('Logout error:', e);
  } finally {
    window.location.href = '/';
  }
};

const Sidebar = ({ active, onNav, onLogout }) => {
  const I = window.Icons;
  const handleLogout = onLogout || doLogout;
  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark"></div>
        <div className="brand-name">
          <b>sleepagotchi</b>
          <span>Sleep · Health · Web3</span>
        </div>
      </div>
      <nav className="nav">
        {NAV.map(n => {
          const IconC = I[n.icon];
          return (
            <button key={n.id} className={`nav-item ${active === n.id ? 'active' : ''}`} onClick={() => onNav(n.id)}>
              <IconC className="ico" />
              {n.label}
            </button>
          );
        })}
      </nav>
      <div className="sidebar-spacer"></div>
      {/*<div className="stake-card">*/}
      {/*  <div className="row" style={{ justifyContent: 'space-between' }}>*/}
      {/*    <div className="row" style={{ gap: 8 }}>*/}
      {/*      <div style={{ width: 26, height: 26, borderRadius: '50%', background: 'radial-gradient(circle at 30% 30%, var(--primary), var(--primary-2))', display: 'grid', placeItems: 'center', color: 'white', fontWeight: 700, fontSize: 11 }}>S</div>*/}
      {/*      <div className="label">SLEEP Balance</div>*/}
      {/*    </div>*/}
      {/*  </div>*/}
      {/*  <div className="balance">1,250 <b>SLEEP</b></div>*/}
      {/*  <button className="btn primary sm" style={{ justifyContent: 'center' }} onClick={() => onNav('rewards')}>Stake SLEEP</button>*/}
      {/*</div>*/}
      <button
        className="nav-item sidebar-logout"
        onClick={handleLogout}
        style={{ marginTop: 8, color: '#ff6b6b' }}
      >
        <I.Power className="ico" />
        Logout
      </button>
    </aside>
  );
};

const UserMenu = ({ onLogout }) => {
  const I = window.Icons;
  const [open, setOpen] = useStateL(false);
  const handleLogout = onLogout || doLogout;
  const initial = (window.USER_DATA?.name || 'U').trim().charAt(0).toUpperCase();

  return (
    <div style={{ position: 'relative' }}>
      <button className="icon-btn" title="User menu" onClick={() => setOpen(!open)}>
        <div className="avatar">{initial}</div>
      </button>
      {open && (
        <>
          <div style={{ position: 'fixed', inset: 0, zIndex: 999 }} onClick={() => setOpen(false)}/>
          <div style={{
            position: 'absolute', top: '100%', right: 0, marginTop: 8, zIndex: 1000,
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderRadius: 12, minWidth: 200, boxShadow: '0 10px 40px rgba(0,0,0,0.2)'
          }}>
            <button style={{
              width: '100%', padding: '12px 16px', textAlign: 'left', border: 'none',
              background: 'transparent', cursor: 'pointer', color: 'var(--text)',
              fontSize: 13, display: 'flex', alignItems: 'center', gap: 10,
              borderBottom: '1px solid var(--border)', fontFamily: 'inherit'
            }} onClick={() => {}}>
              <I.Users size={14}/> Profile
            </button>
            <button style={{
              width: '100%', padding: '12px 16px', textAlign: 'left', border: 'none',
              background: 'transparent', cursor: 'pointer', color: 'var(--text)',
              fontSize: 13, display: 'flex', alignItems: 'center', gap: 10,
              borderBottom: '1px solid var(--border)', fontFamily: 'inherit'
            }} onClick={() => {}}>
              <I.Settings size={14}/> Settings
            </button>
            <button style={{
              width: '100%', padding: '12px 16px', textAlign: 'left', border: 'none',
              background: 'transparent', cursor: 'pointer', color: '#ff6b6b',
              fontSize: 13, display: 'flex', alignItems: 'center', gap: 10, fontFamily: 'inherit'
            }} onClick={() => { setOpen(false); handleLogout(); }}>
              <I.Power size={14}/> Logout
            </button>
          </div>
        </>
      )}
    </div>
  );
};

const Topbar = ({ title, subtitle, right, balance = 2845, onLogout }) => {
  const I = window.Icons;
  return (
    <div className="topbar">
      <div className="title-block">
        <h1>{title}</h1>
        {subtitle && <p>{subtitle}</p>}
      </div>
      <div className="top-actions">
        {right}
        <div className="token-pill">
          <div className="coin">S</div>
          <div>
            <div className="amt tnum">{balance.toLocaleString()} SLEEP</div>
            <div className="sub">Staked 1,250</div>
          </div>
        </div>
        <button className="icon-btn" title="Notifications">
          <I.Bell size={16} />
          <span className="dot"></span>
        </button>
        <UserMenu onLogout={onLogout}/>
      </div>
    </div>
  );
};

Object.assign(window, { Sidebar, Topbar, UserMenu, NAV });
