// Sidebar navigation.

const NAV_GROUPS = [
  {
    label: 'Overview',
    items: [
      { id: 'dashboard', label: 'Dashboard', Icon: IHome },
      { id: 'insights', label: 'Insights', Icon: ISparkle },
      { id: 'categories', label: 'Categories', Icon: ICat },
    ],
  },
  {
    label: 'Money',
    items: [
      { id: 'transactions', label: 'Transactions', Icon: IList },
      { id: 'debt', label: 'Debt tracker', Icon: IDebt },
      { id: 'savings', label: 'Savings goals', Icon: ITarget },
    ],
  },
  {
    label: 'Plan',
    items: [
      { id: 'calendar', label: 'Bill calendar', Icon: ICal },
      { id: 'networth', label: 'Net worth', Icon: ITrend },
      { id: 'household', label: 'Household', Icon: IUsers },
    ],
  },
];

const Sidebar = ({ page, setPage, mobileOpen, setMobileOpen }) => {
  const { state } = useAppState();
  const { user, signOut } = useAuth();
  const handleNav = (id) => {
    setPage(id);
    if (setMobileOpen) setMobileOpen(false);
  };
  return (
    <aside className={`sidebar ${mobileOpen ? 'open' : ''}`}>
      <div className="brand">
        <div className="brand-mark"></div>
        <div>
          <div className="brand-name serif" style={{fontSize:'19px'}}>{(() => {
          const meta = user?.user_metadata;
          if (meta?.full_name) return meta.full_name.split(' ')[0];
          if (meta?.name) return meta.name.split(' ')[0];
          const prefix = (user?.email || '').split('@')[0].split(/[._+\-]/)[0].replace(/\d+$/, '');
          return prefix ? prefix.charAt(0).toUpperCase() + prefix.slice(1).toLowerCase() : 'You';
        })()}</div>
          <div className="brand-sub">{(() => {
            const taglines = [
              'Your money, in plain sight',
              'Small wins, big future',
              'Your Rands, your rules',
            ];
            const idx = (today().getDate() + today().getMonth()) % taglines.length;
            return taglines[idx];
          })()}</div>
        </div>
      </div>

      {NAV_GROUPS.map(group => (
        <React.Fragment key={group.label}>
          <div className="nav-group-label">{group.label}</div>
          {group.items.map(item => {
            // Hide household nav in single mode
            if (item.id === 'household' && state.mode === 'single') return null;
            const Ico = item.Icon;
            return (
              <button
                key={item.id}
                className={`nav-item ${page === item.id ? 'active' : ''}`}
                onClick={() => handleNav(item.id)}
              >
                <Ico className="nav-icon" />
                <span>{item.label}</span>
              </button>
            );
          })}
        </React.Fragment>
      ))}

      <div style={{flex: 1}}></div>

      {/* User account + sign out */}
      <div style={{
        padding: '12px 14px',
        background: 'var(--card)',
        border: '1px solid var(--line)',
        borderRadius: 12,
        display: 'flex',
        alignItems: 'center',
        gap: 10,
      }}>
        <div style={{
          width: 30, height: 30, borderRadius: '50%',
          background: 'var(--ink)', color: 'white',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 12, fontWeight: 600, flexShrink: 0,
        }}>
          {(user?.email?.[0] || '?').toUpperCase()}
        </div>
        <div style={{flex: 1, minWidth: 0}}>
          <div style={{fontSize: 12, fontWeight: 500, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>
            {user?.email}
          </div>
        </div>
        <button
          onClick={signOut}
          title="Sign out"
          style={{
            background: 'none', border: 'none', cursor: 'pointer',
            color: 'var(--ink-3)', padding: 4, borderRadius: 6,
            display: 'flex', alignItems: 'center',
            transition: 'color 0.15s',
          }}
          onMouseOver={e => e.currentTarget.style.color = 'var(--ink)'}
          onMouseOut={e => e.currentTarget.style.color = 'var(--ink-3)'}
        >
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
            <polyline points="16 17 21 12 16 7"/>
            <line x1="21" y1="12" x2="9" y2="12"/>
          </svg>
        </button>
      </div>
    </aside>
  );
};

Object.assign(window, { Sidebar });
