// Astrail — App Shell: Sidebar + Routing + Tweaks

// ── Palette Token Maps ────────────────────────────────────────────
const PALETTE_TOKENS = {
  stone: {
    light: {
      '--col-bg': '#F3F4F7', '--col-surface': '#FFFFFF', '--col-surface-2': '#EDEEF2',
      '--col-border-s': '#E4E6EB', '--col-border': '#D4D7DE', '--col-border-str': '#B9BDC7',
      '--col-text': '#0A0B0F', '--col-text-2': '#5B5F6B', '--col-text-3': '#7A7E8A', '--col-text-dis': '#A4A7B0',
      '--col-accent': '#4571F2', '--col-accent-50': '#EBF0FE', '--col-accent-100': '#CFDBFC',
      '--col-accent-600': '#2F56D0', '--col-accent-hover': 'rgba(69,113,242,0.07)',
      '--shadow-xs': '0 1px 2px rgba(10,11,15,0.06)',
      '--shadow-sm': '0 2px 8px rgba(10,11,15,0.06),0 1px 3px rgba(10,11,15,0.04)',
      '--shadow-md': '0 4px 16px rgba(10,11,15,0.08),0 2px 6px rgba(10,11,15,0.05)',
      '--shadow-lg': '0 8px 32px rgba(10,11,15,0.10),0 2px 8px rgba(10,11,15,0.06)'
    },
    dark: {
      '--col-bg': '#0A0B0F', '--col-surface': '#14161B', '--col-surface-2': '#1C1E24',
      '--col-border-s': '#24262B', '--col-border': '#30333A', '--col-border-str': '#41444C',
      '--col-text': '#F4F1EC', '--col-text-2': '#B4B1AC', '--col-text-3': '#8B8985', '--col-text-dis': '#6A6864',
      '--col-accent': '#7EA0FF', '--col-accent-50': 'rgba(95,138,255,0.16)', '--col-accent-100': 'rgba(95,138,255,0.28)',
      '--col-accent-600': '#5F8AFF', '--col-accent-hover': 'rgba(126,160,255,0.10)',
      '--shadow-xs': '0 1px 2px rgba(0,0,0,0.30)',
      '--shadow-sm': '0 2px 8px rgba(0,0,0,0.30),0 1px 3px rgba(0,0,0,0.20)',
      '--shadow-md': '0 4px 16px rgba(0,0,0,0.36),0 2px 6px rgba(0,0,0,0.22)',
      '--shadow-lg': '0 8px 32px rgba(0,0,0,0.42),0 2px 8px rgba(0,0,0,0.28)'
    }
  },
  aurora: {
    light: {
      '--col-bg': '#EEF9F7', '--col-surface': '#FFFFFF', '--col-surface-2': '#E0F5F0',
      '--col-border-s': '#C8ECE7', '--col-border': '#A8DAD4', '--col-border-str': '#80C0B8',
      '--col-text': '#080E14', '--col-text-2': '#1E6860', '--col-text-3': '#3A8880', '--col-text-dis': '#5CA8A0',
      '--col-accent': '#009B8A', '--col-accent-50': '#E0FDF8', '--col-accent-100': '#B0F4E8',
      '--col-accent-600': '#006860', '--col-accent-hover': 'rgba(0,155,138,0.07)',
      '--shadow-xs': '0 1px 2px rgba(0,0,0,0.05)',
      '--shadow-sm': '0 2px 8px rgba(0,0,0,0.05),0 1px 3px rgba(0,0,0,0.03)',
      '--shadow-md': '0 4px 16px rgba(0,0,0,0.07),0 2px 6px rgba(0,0,0,0.04)',
      '--shadow-lg': '0 8px 32px rgba(0,0,0,0.09),0 2px 8px rgba(0,0,0,0.05)'
    },
    dark: {
      '--col-bg': '#080E14', '--col-surface': '#0E1C2C', '--col-surface-2': '#142438',
      '--col-border-s': '#1C3048', '--col-border': '#243C5A', '--col-border-str': '#2E4E70',
      '--col-text': '#D0EEE8', '--col-text-2': '#90B8C8', '--col-text-3': '#5A8AA0', '--col-text-dis': '#3E6888',
      '--col-accent': '#00C5A8', '--col-accent-50': 'rgba(95,138,255,0.16)', '--col-accent-100': 'rgba(95,138,255,0.28)',
      '--col-accent-600': '#00C5A8', '--col-accent-hover': 'rgba(95,138,255,0.10)',
      '--shadow-xs': '0 1px 2px rgba(0,0,0,0.30)',
      '--shadow-sm': '0 2px 8px rgba(0,0,0,0.30),0 1px 3px rgba(0,0,0,0.20)',
      '--shadow-md': '0 4px 16px rgba(0,0,0,0.35),0 2px 6px rgba(0,0,0,0.22)',
      '--shadow-lg': '0 8px 32px rgba(0,0,0,0.42),0 2px 8px rgba(0,0,0,0.28)'
    }
  },
  onyx: {
    light: {
      '--col-bg': '#FAF8F4', '--col-surface': '#FFFFFF', '--col-surface-2': '#F4F0E8',
      '--col-border-s': '#EDE8DC', '--col-border': '#E0D8C8', '--col-border-str': '#C8BEA8',
      '--col-text': '#0A0908', '--col-text-2': '#6A6054', '--col-text-3': '#8A8070', '--col-text-dis': '#A89E90',
      '--col-accent': '#8B6B30', '--col-accent-50': '#FDF8EE', '--col-accent-100': '#FAF0D8',
      '--col-accent-600': '#5A4218', '--col-accent-hover': 'rgba(139,107,48,0.07)',
      '--shadow-xs': '0 1px 2px rgba(0,0,0,0.06)',
      '--shadow-sm': '0 2px 8px rgba(0,0,0,0.06),0 1px 3px rgba(0,0,0,0.04)',
      '--shadow-md': '0 4px 16px rgba(0,0,0,0.08),0 2px 6px rgba(0,0,0,0.05)',
      '--shadow-lg': '0 8px 32px rgba(0,0,0,0.10),0 2px 8px rgba(0,0,0,0.06)'
    },
    dark: {
      '--col-bg': '#0A0908', '--col-surface': '#161310', '--col-surface-2': '#201D18',
      '--col-border-s': '#2C2822', '--col-border': '#3A3530', '--col-border-str': '#4E4840',
      '--col-text': '#F4EEE4', '--col-text-2': '#B0A8A0', '--col-text-3': '#8C8480', '--col-text-dis': '#6A6460',
      '--col-accent': '#C8A876', '--col-accent-50': 'rgba(200,168,118,0.16)', '--col-accent-100': 'rgba(200,168,118,0.28)',
      '--col-accent-600': '#C8A876', '--col-accent-hover': 'rgba(200,168,118,0.10)',
      '--shadow-xs': '0 1px 2px rgba(0,0,0,0.26)',
      '--shadow-sm': '0 2px 8px rgba(0,0,0,0.26),0 1px 3px rgba(0,0,0,0.18)',
      '--shadow-md': '0 4px 16px rgba(0,0,0,0.32),0 2px 6px rgba(0,0,0,0.20)',
      '--shadow-lg': '0 8px 32px rgba(0,0,0,0.38),0 2px 8px rgba(0,0,0,0.24)'
    }
  },
  dusk: {
    light: {
      '--col-bg': '#F6F5FF', '--col-surface': '#FFFFFF', '--col-surface-2': '#EFEDFF',
      '--col-border-s': '#E5E2FF', '--col-border': '#D5D0FF', '--col-border-str': '#BCBAF0',
      '--col-text': '#100F1C', '--col-text-2': '#5C5A88', '--col-text-3': '#7A78AA', '--col-text-dis': '#9A98CC',
      '--col-accent': '#5A5AF0', '--col-accent-50': '#F0F0FF', '--col-accent-100': '#E0E0FF',
      '--col-accent-600': '#4848C0', '--col-accent-hover': 'rgba(90,90,240,0.07)',
      '--shadow-xs': '0 1px 2px rgba(16,15,28,0.06)',
      '--shadow-sm': '0 2px 8px rgba(16,15,28,0.06),0 1px 3px rgba(16,15,28,0.04)',
      '--shadow-md': '0 4px 16px rgba(16,15,28,0.08),0 2px 6px rgba(16,15,28,0.05)',
      '--shadow-lg': '0 8px 32px rgba(16,15,28,0.10),0 2px 8px rgba(16,15,28,0.06)'
    },
    dark: {
      '--col-bg': '#100F1C', '--col-surface': '#181628', '--col-surface-2': '#222036',
      '--col-border-s': '#2E2B48', '--col-border': '#3C3A5A', '--col-border-str': '#504E70',
      '--col-text': '#EEEEFF', '--col-text-2': '#AAA8C8', '--col-text-3': '#8A88A8', '--col-text-dis': '#6A6888',
      '--col-accent': '#7B7CF8', '--col-accent-50': 'rgba(123,124,248,0.16)', '--col-accent-100': 'rgba(123,124,248,0.28)',
      '--col-accent-600': '#7B7CF8', '--col-accent-hover': 'rgba(123,124,248,0.10)',
      '--shadow-xs': '0 1px 2px rgba(0,0,0,0.30)',
      '--shadow-sm': '0 2px 8px rgba(0,0,0,0.30),0 1px 3px rgba(0,0,0,0.20)',
      '--shadow-md': '0 4px 16px rgba(0,0,0,0.36),0 2px 6px rgba(0,0,0,0.22)',
      '--shadow-lg': '0 8px 32px rgba(0,0,0,0.44),0 2px 8px rgba(0,0,0,0.28)'
    }
  }
};

// ── Palette-matched glass gradients ─────────────────────────────
const GLASS_GRADIENTS = {
  default: {
    light: 'linear-gradient(135deg,oklch(0.86 0.08 250) 0%,oklch(0.91 0.05 290) 25%,oklch(0.88 0.07 200) 50%,oklch(0.85 0.09 240) 75%,oklch(0.89 0.06 270) 100%)',
    dark: 'linear-gradient(135deg,oklch(0.20 0.06 260) 0%,oklch(0.16 0.05 290) 25%,oklch(0.18 0.06 230) 50%,oklch(0.20 0.05 250) 75%,oklch(0.17 0.07 265) 100%)'
  },
  stone: {
    light: 'linear-gradient(135deg,oklch(0.91 0.04 230) 0%,oklch(0.94 0.02 270) 25%,oklch(0.89 0.05 195) 50%,oklch(0.93 0.03 250) 75%,oklch(0.90 0.04 215) 100%)',
    dark: 'linear-gradient(135deg,oklch(0.20 0.05 230) 0%,oklch(0.16 0.04 270) 25%,oklch(0.18 0.06 195) 50%,oklch(0.19 0.04 250) 75%,oklch(0.17 0.05 215) 100%)'
  },
  aurora: {
    light: 'linear-gradient(135deg,oklch(0.88 0.09 185) 0%,oklch(0.93 0.06 165) 25%,oklch(0.91 0.08 210) 50%,oklch(0.87 0.10 190) 75%,oklch(0.92 0.07 175) 100%)',
    dark: 'linear-gradient(135deg,oklch(0.18 0.11 185) 0%,oklch(0.13 0.09 165) 25%,oklch(0.16 0.10 210) 50%,oklch(0.14 0.12 190) 75%,oklch(0.17 0.10 175) 100%)'
  },
  onyx: {
    light: 'linear-gradient(135deg,oklch(0.93 0.05 75) 0%,oklch(0.96 0.03 50) 25%,oklch(0.91 0.06 95) 50%,oklch(0.94 0.04 60) 75%,oklch(0.95 0.04 80) 100%)',
    dark: 'linear-gradient(135deg,oklch(0.18 0.05 75) 0%,oklch(0.13 0.03 50) 25%,oklch(0.16 0.06 95) 50%,oklch(0.14 0.04 60) 75%,oklch(0.17 0.05 80) 100%)'
  },
  dusk: {
    light: 'linear-gradient(135deg,oklch(0.88 0.09 285) 0%,oklch(0.92 0.07 305) 25%,oklch(0.90 0.08 265) 50%,oklch(0.87 0.10 295) 75%,oklch(0.91 0.08 310) 100%)',
    dark: 'linear-gradient(135deg,oklch(0.20 0.09 285) 0%,oklch(0.16 0.07 305) 25%,oklch(0.18 0.08 265) 50%,oklch(0.15 0.10 295) 75%,oklch(0.19 0.08 310) 100%)'
  }
};

function getGlassGradient(palette, theme, usePalette) {
  const key = usePalette ? palette : 'default';
  return (GLASS_GRADIENTS[key] || GLASS_GRADIENTS.default)[theme] || GLASS_GRADIENTS.default.light;
}

function applyTokens(palette, theme) {
  const tokens = PALETTE_TOKENS[palette]?.[theme];
  if (!tokens) return;
  const root = document.documentElement;
  Object.entries(tokens).forEach(([k, v]) => root.style.setProperty(k, v));
  // H6: expose palette-matched dark gradient for auth brand panel
  const authGrad = (GLASS_GRADIENTS[palette] || GLASS_GRADIENTS.stone).dark;
  root.style.setProperty('--auth-brand-bg', authGrad);
  root.dataset.nvxPalette = palette;
  root.dataset.nvxTheme   = theme;
  if (theme === 'dark') {
    root.classList.add('sem-dark');
  } else {
    root.classList.remove('sem-dark');
  }
}

// ── Notification data ─────────────────────────────────────────────
const INIT_NOTIFS = [
{ id: 1, type: 'approval', title: 'Approval required', body: 'May 2026 Payroll needs your signature — $48,200 · 47 recipients', time: '2h ago', unread: true, screen: 'approvals' },
{ id: 2, type: 'approval', title: 'Approval required', body: 'Vendor Payments Q2 is awaiting your sign-off — $12,400 · 8 recipients', time: '3h ago', unread: true, screen: 'approvals' },
{ id: 3, type: 'success', title: 'Run broadcast', body: 'April 2026 Payroll was broadcast on Tron successfully', time: '1d ago', unread: false, screen: 'payroll' },
{ id: 4, type: 'warning', title: 'Low balance alert', body: 'Operations Safe balance is approaching $880,000 — review treasury', time: '2d ago', unread: false, screen: 'treasury' },
{ id: 5, type: 'info', title: 'Member joined', body: 'Carol Dubois accepted your invite and joined as Accountant', time: '3d ago', unread: false, screen: 'settings' }];


const NOTIF_TYPE_ICON = {
  approval: { d: ["M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z", "M9 12l2 2 4-4"], color: 'var(--col-accent)', bg: 'var(--col-accent-50)' },
  success: { d: ["M22 11.08V12a10 10 0 1 1-5.93-9.14", "M22 4L12 14.01l-3-3"], color: 'var(--col-success)', bg: 'var(--col-success-bg)' },
  warning: { d: ["M12 9v4", "M12 17h.01", "M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"], color: 'var(--col-warning)', bg: 'var(--col-warning-bg)' },
  info: { d: ["M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z", "M12 16v-4", "M12 8h.01"], color: 'var(--col-info)', bg: 'var(--col-info-bg)' }
};

// ── Notification panel (slide-over) ────────────────────────────────
const NotifPanel = ({ notifs, onClose, onMarkAll, onClickItem, onNavigate, onSettingsSection }) => {
  const [filter, setFilter] = React.useState('all');
  const FILTER_TYPES = ['all', 'approval', 'success', 'warning', 'info'];
  const visible = filter === 'all' ? notifs : notifs.filter((n) => n.type === filter);
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 350, display: 'flex', justifyContent: 'flex-end' }} onClick={onClose}>
    <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.28)' }} />
    <div onClick={(e) => e.stopPropagation()} className="notif-panel-inner" style={{ position: 'relative', width: 380, height: '100%', background: 'var(--col-surface)', borderLeft: '1px solid var(--col-border-s)', display: 'flex', flexDirection: 'column', boxShadow: 'var(--shadow-lg)', animation: 'slideInRight 220ms cubic-bezier(0.4,0,0.2,1)' }}>
      <style>{`@keyframes slideInRight{from{transform:translateX(32px);opacity:0}to{transform:none;opacity:1}}`}</style>
      {/* Header */}
      <div style={{ padding: '18px 20px', borderBottom: '1px solid var(--col-border-s)', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--col-text)', flex: 1 }}>Notifications</div>
          {notifs.some((n) => n.unread) &&
            <button onClick={onMarkAll} style={{ fontSize: 12, fontWeight: 500, color: 'var(--col-accent)', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', padding: '4px 8px', borderRadius: 6, transition: 'background 120ms' }}
            onMouseOver={(e) => e.currentTarget.style.background = 'var(--col-accent-50)'}
            onMouseOut={(e) => e.currentTarget.style.background = 'none'}>
              Mark all read
            </button>
            }
          <button onClick={onClose} style={{ width: 28, height: 28, borderRadius: 7, background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--col-text-3)', transition: 'background 120ms' }}
            onMouseOver={(e) => e.currentTarget.style.background = 'var(--col-surface-2)'}
            onMouseOut={(e) => e.currentTarget.style.background = 'none'}>
            <IcoX size={14} />
          </button>
        </div>
        {/* Type filter */}
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {FILTER_TYPES.map((f) =>
            <button key={f} onClick={() => setFilter(f)}
            style={{ padding: '3px 9px', borderRadius: 999, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
              fontSize: 11, fontWeight: 600, textTransform: 'capitalize', transition: 'all 120ms',
              background: filter === f ? 'var(--col-accent)' : 'var(--col-surface-2)',
              color: filter === f ? 'white' : 'var(--col-text-3)' }}>
              {f}
            </button>
            )}
        </div>
      </div>

      {/* List */}
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {visible.length === 0 ?
          <div style={{ padding: '48px 24px', textAlign: 'center' }}>
            <div style={{ fontSize: 13, color: 'var(--col-text-3)' }}>No notifications</div>
          </div> :
          notifs.map((n, i) => {
            const visIdx = visible.indexOf(n);
            if (visIdx === -1) return null;
            const meta = NOTIF_TYPE_ICON[n.type] || NOTIF_TYPE_ICON.info;
            return (
              <div key={n.id} onClick={() => {onClickItem(n.id);if (n.screen) {onNavigate(n.screen);onClose();}}}
              style={{ padding: '14px 20px', borderBottom: visIdx < visible.length - 1 ? '1px solid var(--col-border-s)' : 'none', background: n.unread ? 'var(--col-accent-50)' : 'transparent', display: 'flex', gap: 12, cursor: 'pointer', transition: 'background 120ms' }}
              onMouseOver={(e) => {if (!n.unread) e.currentTarget.style.background = 'var(--col-surface-2)';}}
              onMouseOut={(e) => {e.currentTarget.style.background = n.unread ? 'var(--col-accent-50)' : 'transparent';}}>
              {/* Icon */}
              <div style={{ width: 34, height: 34, borderRadius: 10, background: meta.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>
                <Icon d={meta.d} size={15} color={meta.color} strokeWidth={2} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 2 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--col-text)' }}>{n.title}</div>
                  {n.unread && <div style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--col-accent)', flexShrink: 0 }} />}
                </div>
                <div style={{ fontSize: 13, color: 'var(--col-text-2)', lineHeight: 1.4 }}>{n.body}</div>
                <div style={{ fontSize: 11, color: 'var(--col-text-3)', marginTop: 4 }}>{n.time}</div>
              </div>
            </div>);

          })}
      </div>

      {/* Footer */}
      <div style={{ padding: '12px 20px', borderTop: '1px solid var(--col-border-s)' }}>
        <button onClick={() => {onNavigate('settings');onSettingsSection && onSettingsSection('notifications');onClose();}} style={{ width: '100%', padding: '8px', borderRadius: 9, border: '1px solid var(--col-border-s)', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, color: 'var(--col-text-3)', transition: 'all 120ms' }}
          onMouseOver={(e) => {e.currentTarget.style.background = 'var(--col-surface-2)';e.currentTarget.style.color = 'var(--col-text)';}}
          onMouseOut={(e) => {e.currentTarget.style.background = 'none';e.currentTarget.style.color = 'var(--col-text-3)';}}>
          Notification settings →
        </button>
      </div>
    </div>
  </div>);
};


// ── Workspace Switcher ────────────────────────────────────────────
const WORKSPACES = [
{ id: 'acme', name: 'Acme Corp', role: 'Owner', initials: 'AC' },
{ id: 'demo', name: 'Demo Workspace', role: 'Viewer', initials: 'DW' }];


const WorkspaceSwitcher = ({ isCollapsed }) => {
  const [current, setCurrent] = React.useState('acme');
  const [open, setOpen] = React.useState(false);
  const ws = WORKSPACES.find((w) => w.id === current) || WORKSPACES[0];
  return (
    <div style={{ position: 'relative' }}>
      {isCollapsed ? (
        <div onClick={() => setOpen((o) => !o)}
          style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', height: 38, borderRadius: 9, transition: 'background 120ms' }}
          onMouseOver={(e) => e.currentTarget.style.background = 'var(--col-accent-hover)'}
          onMouseOut={(e) => e.currentTarget.style.background = 'transparent'}>
          <div className="user-avatar" style={{ background: 'var(--col-accent-50)', color: 'var(--col-accent)', fontSize: 11, fontWeight: 700, width: 28, height: 28, flexShrink: 0 }}>
            {ws.initials}
          </div>
        </div>
      ) : (
      <div className="sidebar-workspace"
      onClick={() => setOpen((o) => !o)} style={{ cursor: 'pointer' }}>
        <div className="user-avatar" style={{ background: 'var(--col-accent-50)', color: 'var(--col-accent)', fontSize: 11, fontWeight: 700, width: 24, height: 24 }}>
          {ws.initials}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="sidebar-workspace-name">{ws.name}</div>
          <div className="sidebar-workspace-role">{ws.role}</div>
        </div>
        <IcoChevronDown size={12} color="var(--col-text-3)" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 150ms' }} />
      </div>
      )}
      {open &&
      <div style={{ position: 'absolute', top: isCollapsed ? 0 : 'calc(100% + 4px)', left: isCollapsed ? 'calc(100% + 6px)' : 0, right: isCollapsed ? 'auto' : 0, minWidth: 200, zIndex: 50,
        background: 'var(--col-surface)', border: '1px solid var(--col-border-s)', borderRadius: 10,
        boxShadow: 'var(--shadow-md)', overflow: 'hidden' }}
      onClick={(e) => e.stopPropagation()}>
          {WORKSPACES.map((w) =>
        <div key={w.id} onClick={() => {setCurrent(w.id);setOpen(false);}}
        style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', cursor: 'pointer',
          background: w.id === current ? 'var(--col-accent-50)' : 'transparent',
          transition: 'background 100ms' }}
        onMouseOver={(e) => {if (w.id !== current) e.currentTarget.style.background = 'var(--col-surface-2)';}}
        onMouseOut={(e) => {if (w.id !== current) e.currentTarget.style.background = 'transparent';}}>
              <div className="user-avatar" style={{ background: 'var(--col-accent-50)', color: 'var(--col-accent)', fontSize: 10, fontWeight: 700, width: 22, height: 22, flexShrink: 0 }}>{w.initials}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--col-text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{w.name}</div>
                <div style={{ fontSize: 11, color: 'var(--col-text-3)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{w.role}</div>
              </div>
              {w.id === current && <IcoCheck size={13} color="var(--col-accent)" />}
            </div>
        )}
          <div style={{ borderTop: '1px solid var(--col-border-s)', padding: '8px 12px' }}>
            <button style={{ width: '100%', padding: '6px 8px', borderRadius: 7, border: '1px dashed var(--col-border)', background: 'none',
            cursor: 'pointer', fontSize: 12, fontWeight: 500, color: 'var(--col-text-3)', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5, transition: 'all 120ms' }}
          onMouseOver={(e) => {e.currentTarget.style.background = 'var(--col-surface-2)';e.currentTarget.style.color = 'var(--col-text)';}}
          onMouseOut={(e) => {e.currentTarget.style.background = 'none';e.currentTarget.style.color = 'var(--col-text-3)';}}>
              <IcoPlus size={12} /> New workspace
            </button>
          </div>
        </div>
      }
    </div>);

};

// ── Sidebar Component ─────────────────────────────────────────────
const Sidebar = ({ currentScreen, onNavigate, isOpen, onClose, unreadCount, onOpenNotifs, settingsSection, onSettingsSection, isCollapsed, onToggleCollapse, onOpenHelp, onHoverStart, onHoverEnd }) => {
  const NAV_ITEMS = [
  { id: 'dashboard', label: 'Dashboard', Icon: IcoDashboard, badge: null },
  { id: 'payroll', label: 'Payroll', Icon: IcoPayroll, badge: 3 },
  { id: 'treasury', label: 'Treasury', Icon: IcoTreasury, badge: null },
  { id: 'approvals', label: 'Approvals', Icon: IcoApprovals, badge: 3 },
  { id: 'addressbook', label: 'Recipients', Icon: IcoAddressBook, badge: null }];

  const isActive = (id) =>
  currentScreen === id ||
  id === 'payroll' && (currentScreen === 'payroll-detail' || currentScreen === 'payroll-new');

  return (
    <nav className={`sidebar ${isOpen ? 'is-open' : ''} ${isCollapsed ? 'is-collapsed' : ''}`}
    style={{ transition: 'width 240ms cubic-bezier(0.4,0,0.2,1)', overflowX: 'hidden', overflowY: 'auto' }}
    onMouseEnter={onHoverStart}
    onMouseLeave={onHoverEnd}>
      <style>{`
        .sidebar.is-collapsed { width: 62px !important; min-width: 62px !important; }
        .sidebar.is-collapsed .sidebar-workspace-name,
        .sidebar.is-collapsed .sidebar-workspace-role,
        .sidebar.is-collapsed .user-name,
        .sidebar.is-collapsed .user-role { display: none !important; }
        .sidebar.is-collapsed .sidebar-workspace { justify-content: center !important; padding: 6px !important; }
        .sidebar.is-collapsed .sidebar-footer { padding: 10px 6px !important; }
        .sidebar.is-collapsed .sidebar-user { justify-content: center !important; }
        .sidebar.is-collapsed .nav-item { justify-content: center !important; padding: 0 8px !important; }
        .sidebar.is-collapsed .settings-subnav { display: none !important; }
        .sidebar.is-collapsed .sidebar-nav { padding: 8px 4px !important; }
        .sidebar.is-collapsed .nav-badge { display: none !important; }
        .sidebar.is-collapsed .nav-divider { margin: 4px 6px !important; }
      `}</style>
      {/* Logo + collapse toggle */}
      <div className="sidebar-logo"
        style={{ justifyContent: isCollapsed ? 'center' : 'space-between', padding: isCollapsed ? '0 8px' : '0 20px' }}>
        {!isCollapsed && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div className="sidebar-logo-mark">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M3.6 13.4 8 2.6l4.4 10.8" stroke="#F4F1EC" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" fill="none" /><path d="M5.6 9.5h4.8" stroke="#5F8AFF" strokeWidth="1.9" strokeLinecap="round" />
              </svg>
            </div>
            <span className="sidebar-logo-text">Astrail</span>
          </div>
        )}
        <button onClick={onToggleCollapse}
        className="sidebar-collapse-btn"
        style={{ width: 26, height: 26, borderRadius: 7,
          background: 'var(--col-surface-2)', border: '1px solid var(--col-border-s)',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--col-text-3)', transition: 'all 150ms', flexShrink: 0 }}
        title={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}
        onMouseOver={(e) => {e.currentTarget.style.background = 'var(--col-accent-hover)';e.currentTarget.style.color = 'var(--col-text)';}}
        onMouseOut={(e) => {e.currentTarget.style.background = 'var(--col-surface-2)';e.currentTarget.style.color = 'var(--col-text-3)';}}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            {isCollapsed ?
            <><path d="M9 18l6-6-6-6" /></> :
            <><path d="M15 18l-6-6 6-6" /></>
            }
          </svg>
        </button>
      </div>

      {/* Workspace switcher */}
      <div style={{ padding: '8px 8px 4px' }}>
        <WorkspaceSwitcher isCollapsed={isCollapsed} />
      </div>

      {/* Navigation */}
      <div className="sidebar-nav">
        {NAV_ITEMS.map((item) =>
        <div key={item.id}
        className={`nav-item ${isActive(item.id) ? 'active' : ''}`}
        onClick={() => onNavigate(item.id)}
        title={item.label}>
            <item.Icon size={17} color="currentColor" />
            {!isCollapsed && <span>{item.label}</span>}
            {item.badge && !isActive(item.id) && !isCollapsed &&
          <span className="nav-badge">{item.badge}</span>
          }
          </div>
        )}

        <div className="nav-divider" />

        <div className={`nav-item ${currentScreen === 'settings' ? 'active' : ''}`} onClick={() => onNavigate('settings')} title={isCollapsed ? 'Settings' : ''}>
          <IcoSettings size={17} />
          {!isCollapsed && <span>Settings</span>}
        </div>
        {currentScreen === 'settings' && !isCollapsed &&
        <div className="settings-subnav" style={{ paddingLeft: 12, borderLeft: '2px solid var(--col-border-s)', marginLeft: 14, marginTop: 2, marginBottom: 4 }}>
            {(window.SETTINGS_SECTIONS || []).map((group) =>
          <React.Fragment key={group.group}>
                <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.09em', color: 'var(--col-text-3)', padding: '6px 8px 2px 6px' }}>
                  {group.group}
                </div>
                {group.items.map((item) =>
            <div key={item.id}
            className={`nav-item ${settingsSection === item.id ? 'active' : ''}`}
            style={{ height: 32, fontSize: 13 }}
            onClick={(e) => {e.stopPropagation();onSettingsSection && onSettingsSection(item.id);}}>
                    {window.SNIcon && React.createElement(window.SNIcon, { type: item.icon, size: 14 })}
                    <span>{item.label}</span>
                  </div>
            )}
              </React.Fragment>
          )}
          </div>
        }
        <div className="nav-item" onClick={onOpenHelp} title={isCollapsed ? 'Help' : ''}>
          <IcoHelp size={17} />
          {!isCollapsed && <span>Help</span>}
        </div>
      </div>

      {/* User footer */}
      <div className="sidebar-footer">
        {isCollapsed ? (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
            <button onClick={onOpenNotifs} style={{ position: 'relative', width: 46, height: 38, borderRadius: 9, background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--col-text-3)', transition: 'background 120ms ease' }}
              onMouseOver={(e) => {e.currentTarget.style.background = 'var(--col-accent-hover)';e.currentTarget.style.color = 'var(--col-text)';}}
              onMouseOut={(e) => {e.currentTarget.style.background = 'none';e.currentTarget.style.color = 'var(--col-text-3)';}}>
              <Icon d={["M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9", "M13.73 21a2 2 0 0 1-3.46 0"]} size={17} color="currentColor" strokeWidth={1.7} />
              {unreadCount > 0 &&
                <div style={{ position: 'absolute', top: 4, right: 6, minWidth: 14, height: 14, borderRadius: 999, background: 'var(--col-accent)', border: '2px solid var(--col-surface)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 8, fontWeight: 700, color: 'white', padding: '0 3px', lineHeight: 1 }}>
                  {unreadCount > 9 ? '9+' : unreadCount}
                </div>
              }
            </button>
            <div style={{ display: 'flex', justifyContent: 'center', paddingBottom: 4 }}>
              <Avatar name="Alice Johnson" size="sm" />
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <div className="sidebar-user" style={{ flex: 1, minWidth: 0 }}>
              <Avatar name="Alice Johnson" size="sm" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="user-name">Alice Johnson</div>
                <div className="user-role">Owner</div>
              </div>
            </div>
            {/* Notification bell */}
            <button onClick={onOpenNotifs} style={{ position: 'relative', width: 34, height: 34, borderRadius: 9, background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--col-text-3)', flexShrink: 0, transition: 'background 120ms ease' }}
            onMouseOver={(e) => {e.currentTarget.style.background = 'var(--col-accent-hover)';e.currentTarget.style.color = 'var(--col-text)';}}
            onMouseOut={(e) => {e.currentTarget.style.background = 'none';e.currentTarget.style.color = 'var(--col-text-3)';}}>  
              <Icon d={["M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9", "M13.73 21a2 2 0 0 1-3.46 0"]} size={17} color="currentColor" strokeWidth={1.7} />
              {unreadCount > 0 &&
                <div style={{ position: 'absolute', top: 5, right: 5, minWidth: 14, height: 14, borderRadius: 999, background: 'var(--col-accent)', border: '2px solid var(--col-surface)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 8, fontWeight: 700, color: 'white', padding: '0 3px', lineHeight: 1 }}>
                  {unreadCount > 9 ? '9+' : unreadCount}
                </div>
              }
            </button>
          </div>
        )}
      </div>
    </nav>);

};

// ── Bottom Tab Bar (mobile primary navigation) ───────────────────
const BottomTabBar = ({ currentScreen, onNavigate, unreadCount, onOpenMore }) => {
  const isActive = (id) =>
  currentScreen === id ||
  id === 'payroll' && (currentScreen === 'payroll-detail' || currentScreen === 'payroll-new');

  const TABS = [
  { id: 'dashboard', label: 'Dashboard', Icon: IcoDashboard },
  { id: 'payroll', label: 'Payroll', Icon: IcoPayroll },
  { id: 'approvals', label: 'Approvals', Icon: IcoApprovals, badge: unreadCount },
  { id: 'addressbook', label: 'Recipients', Icon: IcoAddressBook }];


  return (
    <div className="bottom-tab-bar">
      {TABS.map((tab) =>
      <div key={tab.id}
      className={`bottom-tab-item ${isActive(tab.id) ? 'active' : ''}`}
      onClick={() => onNavigate(tab.id)}>
          <div className="bottom-tab-icon">
            <tab.Icon size={22} color="currentColor" />
            {tab.badge > 0 &&
          <div className="bottom-tab-badge">{tab.badge > 9 ? '9+' : tab.badge}</div>
          }
          </div>
          <span className="bottom-tab-label">{tab.label}</span>
        </div>
      )}
      {/* More tab */}
      <div className="bottom-tab-item" onClick={onOpenMore}>
        <div className="bottom-tab-icon">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" stroke="none">
            <circle cx="5" cy="12" r="1.8" />
            <circle cx="12" cy="12" r="1.8" />
            <circle cx="19" cy="12" r="1.8" />
          </svg>
        </div>
        <span className="bottom-tab-label">More</span>
      </div>
    </div>);

};

// ── More Bottom Sheet (mobile secondary navigation) ───────────────
const MoreSheet = ({ onClose, onNavigate, onOpenNotifs, unreadCount }) =>
<>
    {/* Backdrop */}
    <div style={{ position: 'fixed', inset: 0, zIndex: 198, background: 'rgba(0,0,0,0.38)' }} onClick={onClose} />
    {/* Sheet */}
    <div style={{
    position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 199,
    background: 'var(--col-surface)',
    borderRadius: '20px 20px 0 0',
    paddingBottom: 'env(safe-area-inset-bottom, 0px)',
    boxShadow: '0 -4px 32px rgba(0,0,0,0.14)',
    animation: 'slideUpSheet 240ms cubic-bezier(0.4,0,0.2,1)'
  }}>
      <style>{`@keyframes slideUpSheet { from { transform:translateY(56px); opacity:0; } to { transform:none; opacity:1; } }`}</style>

      {/* Handle */}
      <div style={{ width: 36, height: 4, borderRadius: 2, background: 'var(--col-border)', margin: '12px auto 0' }} />

      {/* User card */}
      <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--col-border-s)', display: 'flex', alignItems: 'center', gap: 14 }}>
        <Avatar name="Alice Johnson" size="md" />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--col-text)', marginBottom: 2 }}>Alice Johnson</div>
          <div style={{ fontSize: 12, color: 'var(--col-text-3)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Owner · Acme Corp</div>
        </div>
        <div style={{ fontSize: 11, fontWeight: 600, padding: '3px 9px', borderRadius: 999, background: 'var(--col-accent-50)', color: 'var(--col-accent)', flexShrink: 0 }}>Owner</div>
      </div>

      {/* Nav items */}
      {[
    { id: 'treasury', label: 'Treasury', Icon: IcoTreasury },
    { id: 'settings', label: 'Settings', Icon: IcoSettings }].
    map((item) =>
    <div key={item.id} className="more-sheet-row" onClick={() => {onNavigate(item.id);onClose();}}>
          <div className="more-sheet-icon"><item.Icon size={18} color="var(--col-text-2)" /></div>
          <span style={{ fontSize: 15, fontWeight: 500, color: 'var(--col-text)', flex: 1 }}>{item.label}</span>
          <IcoChevronRight size={14} color="var(--col-text-3)" />
        </div>
    )}

      {/* Notifications */}
      <div className="more-sheet-row" onClick={() => {onOpenNotifs();onClose();}}>
        <div className="more-sheet-icon">
          <Icon d={["M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9", "M13.73 21a2 2 0 0 1-3.46 0"]} size={18} color="var(--col-text-2)" strokeWidth={1.8} />
        </div>
        <span style={{ fontSize: 15, fontWeight: 500, color: 'var(--col-text)', flex: 1 }}>Notifications</span>
        {unreadCount > 0 &&
      <div style={{ background: 'var(--col-accent)', color: 'white', borderRadius: 999, fontSize: 11, fontWeight: 700, padding: '2px 8px', minWidth: 20, textAlign: 'center' }}>
            {unreadCount}
          </div>
      }
      </div>

      {/* Help */}
      <div className="more-sheet-row" style={{ borderBottom: 'none' }}>
        <div className="more-sheet-icon"><IcoHelp size={18} color="var(--col-text-2)" /></div>
        <span style={{ fontSize: 15, fontWeight: 500, color: 'var(--col-text)', flex: 1 }}>Help & Support</span>
        <IcoChevronRight size={14} color="var(--col-text-3)" />
      </div>

      <div style={{ height: 8 }} />
    </div>
  </>;


// ── Main App ──────────────────────────────────────────────────────
const App = () => {
  // Auth stage: 'login' | 'register' | 'onboarding' | 'app'
  const [authStage, setAuthStage] = React.useState('loading');
  const [sidebarOpen, setSidebarOpen] = React.useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = React.useState(false);
  const [sidebarHovering, setSidebarHovering] = React.useState(false);
  const sidebarEffectiveCollapsed = sidebarCollapsed && !sidebarHovering;
  const [showHelp, setShowHelp] = React.useState(false);
  const [showMore, setShowMore] = React.useState(false);

  const [screen, setScreen] = React.useState('dashboard');
  const [screenData, setScreenData] = React.useState(null);
  const [settingsSection, setSettingsSection] = React.useState('general');
  const { toasts, addToast, dismiss } = useToasts();

  // Notifications state
  const [notifs, setNotifs] = React.useState(INIT_NOTIFS);
  const [showNotifs, setShowNotifs] = React.useState(false);
  const unreadCount = notifs.filter((n) => n.unread).length;

  const markAllRead = () => setNotifs((p) => p.map((n) => ({ ...n, unread: false })));
  const markOneRead = (id) => setNotifs((p) => p.map((n) => n.id === id ? { ...n, unread: false } : n));

  // Tweaks defaults
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "palette": "stone",
    "theme": "light",
    "density": "comfortable",
    "glass": false,
    "paletteGradient": false,
    "animatedGlass": false,
    "deviceSim": "desktop"
  } /*EDITMODE-END*/;

  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Expose to Settings Appearance panel
  React.useEffect(() => {
    window.__nvxTweaks = t;
    window.__nvxSetTweak = (key, val) => setTweak(key, val);
  }, [t]);

  // Apply tokens whenever palette/theme changes
  React.useEffect(() => {
    applyTokens(t.palette, t.theme);
    document.documentElement.classList.toggle('density-compact', t.density === 'compact');
    const root = document.getElementById('root');
    root.classList.toggle('glass-mode', !!t.glass);
    root.classList.toggle('sem-dark', !!t.glass && t.theme === 'dark');

    // Inject animation keyframes once
    if (!document.getElementById('nvx-glass-anim')) {
      const s = document.createElement('style');
      s.id = 'nvx-glass-anim';
      s.textContent = `
        @keyframes nvxGradFlow {
          0%   { background-position: 0% 0%; }
          25%  { background-position: 100% 0%; }
          50%  { background-position: 100% 100%; }
          75%  { background-position: 0% 100%; }
          100% { background-position: 0% 0%; }
        }
        body.nvx-anim {
          background-size: 400% 400% !important;
          animation: nvxGradFlow 26s cubic-bezier(0.45,0.05,0.55,0.95) infinite !important;
        }
      `;
      document.head.appendChild(s);
    }

    if (t.glass) {
      document.body.style.background = getGlassGradient(t.palette, t.theme, !!t.paletteGradient);
      document.body.style.backgroundAttachment = 'fixed';
      document.body.style.minHeight = '100vh';
      document.documentElement.style.background = 'transparent';
      document.body.classList.toggle('nvx-anim', !!t.animatedGlass);
      if (!t.animatedGlass) document.body.style.backgroundSize = '';
    } else {
      document.body.style.cssText = '';
      document.documentElement.style.background = '';
      document.body.classList.remove('nvx-anim');
    }
  }, [t.palette, t.theme, t.density, t.glass, t.paletteGradient, t.animatedGlass]);

  // Initial apply
  React.useEffect(() => {applyTokens(TWEAK_DEFAULTS.palette, TWEAK_DEFAULTS.theme);}, []);

  // (sidebar-width CSS var kept for legacy compatibility)
  React.useEffect(() => {
    document.documentElement.style.setProperty('--di-sidebar-w', sidebarEffectiveCollapsed ? '62px' : '220px');
  }, [sidebarEffectiveCollapsed]);

  // Apply device sim class to #root
  React.useEffect(() => {
    const root = document.getElementById('root');
    root.classList.remove('sim-phone', 'sim-tablet');
    if (t.deviceSim === 'phone') root.classList.add('sim-phone');
    if (t.deviceSim === 'tablet') root.classList.add('sim-tablet');
  }, [t.deviceSim]);

  const PAGE_TITLES = {
    dashboard: 'Dashboard',
    payroll: 'Payroll',
    'payroll-detail': 'Payroll Run',
    'payroll-new': 'New Run',
    treasury: 'Treasury',
    approvals: 'Approvals',
    addressbook: 'Recipients',
    settings: 'Settings'
  };const navigate = (target, data = null) => {
    setScreen(target);
    setScreenData(data);
    setSidebarOpen(false);
    window.scrollTo && window.scrollTo(0, 0);
  };

  // ── Loader ─────────────────────────────────────────────────────
  if (authStage === 'loading') {
    return <NvxLoader onDone={() => setAuthStage('login')} />;
  }

  // ── Auth screens (no sidebar / tweaks) ─────────────────────────
  if (authStage === 'login') {
    return (
      <>
        <LoginScreen
          onLogin={() => setAuthStage('app')}
          onGoToRegister={() => setAuthStage('register')} />
        
        <style>{`@keyframes spin { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }`}</style>
      </>);

  }
  if (authStage === 'register') {
    return (
      <>
        <RegisterScreen
          onComplete={() => setAuthStage('onboarding')}
          onGoToLogin={() => setAuthStage('login')} />
        
        <style>{`@keyframes spin { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }`}</style>
      </>);

  }
  if (authStage === 'onboarding') {
    return (
      <>
        <OnboardingScreen onComplete={() => setAuthStage('app')} />
        <style>{`@keyframes spin { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }`}</style>
      </>);

  }

  const PALETTE_OPTIONS = [
  ['#4571F2', '#F3F4F7', '#0A0B0F'],
  ['#009B8A', '#EEF9F7', '#080E14'],
  ['#8B6B30', '#FAF8F4', '#0A0908'],
  ['#5A5AF0', '#F6F5FF', '#100F1C']];

  const PALETTE_KEYS = ['stone', 'aurora', 'onyx', 'dusk'];

  return (
    <div className="app-shell">
      {/* Sidebar drawer overlay (mobile/tablet) */}
      <div className={`sidebar-overlay ${sidebarOpen ? 'is-open' : ''}`}
      onClick={() => setSidebarOpen(false)} />

      <Sidebar currentScreen={screen} onNavigate={navigate}
      isOpen={sidebarOpen} onClose={() => setSidebarOpen(false)}
      unreadCount={unreadCount} onOpenNotifs={() => setShowNotifs(true)}
      settingsSection={settingsSection} onSettingsSection={setSettingsSection}
      isCollapsed={sidebarEffectiveCollapsed}
      onToggleCollapse={() => { setSidebarCollapsed((c) => !c); setSidebarHovering(false); }}
      onHoverStart={() => { if (sidebarCollapsed) setSidebarHovering(true); }}
      onHoverEnd={() => setSidebarHovering(false)}
      onOpenHelp={() => setShowHelp(true)} />

      <div className="main-content">
        {/* Mobile top bar — logo · title · bell · avatar (phone only) */}
        <div className="mobile-topbar">
          <div className="mobile-topbar-mark" style={{ flexShrink: 0 }}>
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d="M3.6 13.4 8 2.6l4.4 10.8" stroke="#F4F1EC" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" fill="none" /><path d="M5.6 9.5h4.8" stroke="#5F8AFF" strokeWidth="1.9" strokeLinecap="round" />
            </svg>
          </div>
          <span className="mobile-topbar-title">{PAGE_TITLES[screen] || 'Astrail'}</span>
          <div className="mobile-topbar-actions">
            {/* Bell */}
            <button className="mobile-topbar-btn" onClick={() => setShowNotifs(true)} aria-label="Notifications">
              <Icon d={["M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9", "M13.73 21a2 2 0 0 1-3.46 0"]} size={18} color="currentColor" strokeWidth={1.7} />
              {unreadCount > 0 &&
              <div style={{ position: 'absolute', top: 7, right: 7, width: 7, height: 7, borderRadius: '50%', background: 'var(--col-accent)', border: '1.5px solid var(--col-surface)' }} />
              }
            </button>
            {/* Avatar */}
            <div style={{ marginLeft: 2 }}>
              <Avatar name="Alice Johnson" size="sm" />
            </div>
          </div>
        </div>
        {screen === 'dashboard' && <DashboardScreen onNavigate={navigate} addToast={addToast} />}
        {screen === 'payroll' && <PayrollScreen onNavigate={navigate} addToast={addToast} />}
        {screen === 'payroll-detail' && <PayrollDetailScreen run={screenData || window.MOCK.payrollRuns[0]} onNavigate={navigate} addToast={addToast} />}
        {screen === 'payroll-new' && <NewRunScreen onNavigate={navigate} addToast={addToast} />}
        {screen === 'treasury' && <TreasuryScreen onNavigate={navigate} addToast={addToast} />}
        {screen === 'approvals' && <ApprovalsScreen onNavigate={navigate} addToast={addToast} initialDetail={screenData} />}
        {screen === 'addressbook' && <AddressBookScreen onNavigate={navigate} addToast={addToast} />}
        {screen === 'settings' && <SettingsScreen onNavigate={navigate} addToast={addToast} activeSection={settingsSection} onSectionChange={setSettingsSection} />}
      </div>

      {showHelp &&
      <div className="modal-overlay" onClick={() => setShowHelp(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()} style={{ width: 480 }}>
            <div className="modal-header">
              <div className="modal-title">Help &amp; Resources</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, padding: '4px 0 16px' }}>
              {[
            { icon: 'docs',    d: ["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"],      title: 'Documentation',   desc: 'Guides, API reference, and tutorials',          href: '#' },
            { icon: 'chat',    d: ["M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"],                                title: 'Contact support',  desc: 'Reach the team — avg. response under 2 hours', href: '#' },
            { icon: 'status',  d: ["M22 12h-4l-3 9L9 3l-3 9H2"],                                                                  title: 'System status',   desc: 'Live uptime and incident history',              href: '#' },
            { icon: 'roadmap', d: ["M3 3h18","M3 9h18","M3 15h12","M3 21h8"],                                                   title: 'Product roadmap', desc: "See what's coming next",                         href: '#' }].
            map((item) =>
            <a key={item.title} href={item.href}
            style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 16px', borderRadius: 10,
              border: '1px solid var(--col-border-s)', background: 'var(--col-surface)',
              textDecoration: 'none', transition: 'background 120ms' }}
            onMouseOver={(e) => e.currentTarget.style.background = 'var(--col-surface-2)'}
            onMouseOut={(e) => e.currentTarget.style.background = 'var(--col-surface)'}>
                  <div style={{ width: 36, height: 36, borderRadius: 9, background: 'var(--col-accent-50)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Icon d={item.d} size={16} color="var(--col-accent)" strokeWidth={1.8} />
                  </div>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--col-text)', marginBottom: 2 }}>{item.title}</div>
                    <div style={{ fontSize: 12, color: 'var(--col-text-3)' }}>{item.desc}</div>
                  </div>
                  <svg style={{ marginLeft: 'auto', flexShrink: 0 }} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--col-text-3)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17L17 7M7 7h10v10" /></svg>
                </a>
            )}
            </div>
            <div className="modal-footer">
              <button className="btn btn-secondary btn-md" onClick={() => setShowHelp(false)}>Close</button>
            </div>
          </div>
        </div>
      }

      <ToastArea toasts={toasts} dismiss={dismiss} />

      {/* Bottom tab bar — shown on mobile via CSS */}
      <BottomTabBar
        currentScreen={screen}
        onNavigate={navigate}
        unreadCount={unreadCount}
        onOpenMore={() => setShowMore(true)} />

      {/* More bottom sheet — mobile secondary nav */}
      {showMore &&
      <MoreSheet
        onClose={() => setShowMore(false)}
        onNavigate={navigate}
        onOpenNotifs={() => setShowNotifs(true)}
        unreadCount={unreadCount} />
      }

      {showNotifs &&
      <NotifPanel
        notifs={notifs}
        onClose={() => setShowNotifs(false)}
        onMarkAll={markAllRead}
        onClickItem={markOneRead}
        onNavigate={navigate}
        onSettingsSection={setSettingsSection} />

      }

      <TweaksPanel>
        <TweakSection label="Palette" />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4, padding: '0 14px 8px' }}>
          {PALETTE_KEYS.map((k, i) =>
          <button key={k} onClick={() => setTweak('palette', k)}
          style={{
            padding: '6px 8px', borderRadius: 7, border: '1.5px solid',
            borderColor: t.palette === k ? '#4E8CDA' : 'rgba(0,0,0,0.12)',
            background: t.palette === k ? 'rgba(78,140,218,0.12)' : 'rgba(255,255,255,0.6)',
            color: t.palette === k ? '#4E8CDA' : '#555',
            fontSize: 12, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 6, transition: 'all 150ms'
          }}>
              <div style={{ width: 10, height: 10, borderRadius: 2, background: PALETTE_OPTIONS[i][0], flexShrink: 0 }} />
              {['Stone', 'Aurora', 'Onyx', 'Dusk'][i]}
            </button>
          )}
        </div>

        <TweakSection label="Theme" />
        <TweakRadio
          label="Mode"
          value={t.theme}
          options={['light', 'dark']}
          onChange={(v) => setTweak('theme', v)} />
        

        <TweakSection label="Density" />
        <TweakRadio
          label="Layout"
          value={t.density}
          options={['comfortable', 'compact']}
          onChange={(v) => setTweak('density', v)} />
        

        <TweakSection label="Effects" />
        <TweakToggle label="Glass mode" value={!!t.glass} onChange={(v) => setTweak('glass', v)} />

        {!!t.glass &&
        <>
            <TweakToggle label="Palette gradient" value={!!t.paletteGradient} onChange={(v) => setTweak('paletteGradient', v)} />
            <TweakToggle label="Animated gradient" value={!!t.animatedGlass} onChange={(v) => setTweak('animatedGlass', v)} />
          </>
        }

        <TweakSection label="Device" />
        <div style={{ display: 'flex', gap: 6, padding: '0 14px 8px' }}>
          {[
          { id: 'desktop', label: 'Desktop', svg: <svg width="18" height="16" viewBox="0 0 18 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="1" y="1" width="16" height="11" rx="2" /><path d="M5 15h8M9 12v3" /></svg> },
          { id: 'tablet', label: 'Tablet', svg: <svg width="14" height="18" viewBox="0 0 14 18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="1" y="1" width="12" height="16" rx="2.5" /><circle cx="7" cy="14.5" r="0.9" fill="currentColor" stroke="none" /></svg> },
          { id: 'phone', label: 'Phone', svg: <svg width="11" height="18" viewBox="0 0 11 18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="1" y="1" width="9" height="16" rx="2.5" /><circle cx="5.5" cy="14.5" r="0.9" fill="currentColor" stroke="none" /></svg> }].
          map((d) =>
          <button key={d.id} onClick={() => setTweak('deviceSim', d.id)} style={{
            flex: 1, padding: '8px 4px', borderRadius: 8,
            border: '1.5px solid',
            borderColor: t.deviceSim === d.id ? 'var(--col-accent)' : 'rgba(0,0,0,0.10)',
            background: t.deviceSim === d.id ? 'var(--col-accent-50)' : 'rgba(255,255,255,0.6)',
            color: t.deviceSim === d.id ? 'var(--col-accent)' : 'var(--col-text-3)',
            cursor: 'pointer', fontFamily: 'inherit', transition: 'all 150ms',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5
          }}>
              {d.svg}
              <span style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.02em' }}>{d.label}</span>
            </button>
          )}
        </div>

        <TweakSection label="Loader System" />
        <div style={{ padding: '0 14px 10px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          {[
          { label: 'Arc', note: 'buttons · inline', comp: React.createElement(LoaderArc, { size: 'md' }) },
          { label: 'Orbit', note: 'approvals · sig checks', comp: React.createElement(LoaderOrbit, { size: 'md' }) },
          { label: 'Chain', note: 'batch ops · wizards', comp: React.createElement(LoaderChain, { size: 'md' }) },
          { label: 'Pulse', note: 'tx confirm · ext waits', comp: React.createElement(LoaderPulse, { size: 'md' }) },
          { label: 'Signal', note: 'live sync · data feed', comp: React.createElement(LoaderSignal, { size: 'md' }) }].
          map(({ label, note, comp }) =>
          <div key={label} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 36, display: 'flex', justifyContent: 'center' }}>{comp}</div>
              <div>
                <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--col-text-2)' }}>{label}</div>
                <div style={{ fontSize: 11, color: 'var(--col-text-3)', marginTop: 1 }}>{note}</div>
              </div>
            </div>
          )}
        </div>

        <TweakSection label="Preview Auth" />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4, padding: '0 14px 8px' }}>
          {[
          { label: '⟳ Loader', stage: 'loading' },
          { label: 'Login', stage: 'login' },
          { label: 'Register', stage: 'register' },
          { label: 'Onboarding', stage: 'onboarding' },
          { label: '→ Dashboard', stage: 'app' }].
          map(({ label, stage }) =>
          <button key={stage}
          onClick={() => setAuthStage(stage)}
          style={{
            padding: '6px 10px', borderRadius: 7,
            border: '1.5px solid',
            borderColor: authStage === stage ? 'var(--col-accent)' : 'rgba(0,0,0,0.10)',
            background: authStage === stage ? 'var(--col-accent-50)' : 'rgba(255,255,255,0.6)',
            color: authStage === stage ? 'var(--col-accent)' : 'var(--col-text-2)',
            fontSize: 12, fontWeight: 500, cursor: 'pointer',
            fontFamily: 'inherit', textAlign: 'left',
            transition: 'all 150ms'
          }}>
              {label}
            </button>
          )}
        </div>
      </TweaksPanel>
    </div>);

};

// ── Placeholder Screens ───────────────────────────────────────────
const TreasuryPlaceholder = ({ onNavigate }) =>
<>
    <div className="content-header">
      <span className="page-title">Treasury</span>
    </div>
    <div className="content-body">
      <div className="card">
        <div className="empty-state">
          <IcoTreasury size={44} color="var(--col-text-3)" />
          <div className="empty-title">Treasury</div>
          <div className="empty-desc">Full treasury view with balance charts, per-chain breakdown, and transaction history is shown on the Dashboard.</div>
          <button className="btn btn-primary btn-md" style={{ marginTop: 8 }} onClick={() => onNavigate('dashboard')}>
            Go to Dashboard
          </button>
        </div>
      </div>
    </div>
  </>;


const ApprovalsPlaceholder = ({ onNavigate, addToast }) => {
  const { MOCK } = window;
  return (
    <>
      <div className="content-header">
        <span className="page-title">Approvals</span>
        <div className="content-header-right">
          <span style={{ fontSize: 13, color: 'var(--col-text-3)' }}>{MOCK.pendingApprovals.length} pending</span>
        </div>
      </div>
      <div className="content-body">
        <div className="card" style={{ overflow: 'hidden' }}>
          <table className="data-table">
            <thead>
              <tr>
                <th>Run</th>
                <th className="right">Recipients</th>
                <th className="right">Total</th>
                <th>Chain</th>
                <th>Signatures</th>
                <th style={{ width: 100 }}></th>
              </tr>
            </thead>
            <tbody>
              {MOCK.pendingApprovals.map((run) =>
              <tr key={run.id} onClick={() => onNavigate('payroll-detail', run)}>
                  <td className="cell-primary">{run.name}</td>
                  <td className="right cell-mono cell-secondary">{run.recipients}</td>
                  <td className="right cell-mono fw-5">{fmtFull(run.total)}</td>
                  <td><ChainBadge chain={run.chain} /></td>
                  <td><ApprovalDots signed={run.signed} required={run.required} /></td>
                  <td className="right">
                    <button className="btn btn-primary btn-sm"
                  onClick={(e) => {e.stopPropagation();onNavigate('payroll-detail', run);}}>
                      Review
                    </button>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>);

};

// ── Render ────────────────────────────────────────────────────────
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);