// sidebar.jsx — hibank Design System tokens
function Sidebar({ activeNav, setActiveNav, sidebarOpen, setSidebarOpen, onLogout, pendingApproval = 0, primary, secondary, sidebarBg, role = 'super', user }) {
  const TEAL = primary || '#0056D2';
  const DARK_BG = sidebarBg || '#001F5B';
  const [expandedNavs, setExpandedNavs] = React.useState({ '4eyes': true, 'fds': false, 'refund_management': false });

  const toggleExpand = (e, id) => {
    e.stopPropagation();
    if (!sidebarOpen) setSidebarOpen(true);
    setExpandedNavs(prev => ({ ...prev, [id]: !prev[id] }));
  };

  // ── Menu item registry ──
  const ITEM = {
    dashboard:           { id: 'dashboard', label: 'Dashboard', icon: 'bx-home-alt-2' },
    onboarding_monitor:  { id: 'onboarding_monitor', label: 'Onboarding Monitor', icon: 'bx-desktop' },
    merchant_management: { id: 'merchant_management', label: 'Merchant Management', icon: 'bx-store' },
    merchant_business:   { id: 'merchant_business', label: 'Merchant Business', icon: 'bx-briefcase' },
    transaction_monitor: { id: 'transaction_monitor', label: 'Transaction Monitor', icon: 'bx-transfer' },
    recon_settlement:    { id: 'recon_settlement', label: 'Recon & Settlement', icon: 'bx-receipt' },
    disbursement:        { id: 'disbursement', label: 'Disbursement', icon: 'bx-money-withdraw' },
    refund:              { id: 'refund', label: 'Refund', icon: 'bx-undo' },
    report_generator:    { id: 'report_generator', label: 'Report Generator', icon: 'bx-file' },
    fourEyes: {
      id: '4eyes', label: '4 Eyes', icon: 'bx-group', subItems: [
        { id: '4eyes_checker', label: 'Checker', icon: 'bx-check-double' },
        { id: 'approval', label: 'Approver', icon: 'bx-check-shield' }
      ]
    },
    fds: {
      id: 'fds', label: 'FDS', icon: 'bx-shield-quarter', subItems: [
        { id: 'fds_dashboard', label: 'Dashboard', icon: 'bx-tachometer' },
        { id: 'fds_monitoring', label: 'Monitoring FDS', icon: 'bx-search-alt' },
        { id: 'fds_parameter', label: 'Parameters', icon: 'bx-slider-alt' },
        { id: 'fds_suspect', label: 'Suspect Management', icon: 'bx-user-x' }
      ]
    },
    refund_management_admin: {
      id: 'refund_management', label: 'Refund Management', icon: 'bx-history', subItems: [
        { id: 'refund_monitor', label: 'Refund Monitor', icon: 'bx-desktop' }
      ]
    },
    refund_management_full: {
      id: 'refund_management', label: 'Refund Management', icon: 'bx-history', subItems: [
        { id: 'refund_request', label: 'Refund Request', icon: 'bx-git-pull-request' },
        { id: 'refund_monitor', label: 'Refund Monitor', icon: 'bx-desktop' }
      ]
    }
  };

  // ── Menus per role ──
  const NAV_BY_ROLE = {
    // Hibank Admin
    admin: [
      ITEM.dashboard, ITEM.onboarding_monitor, ITEM.merchant_management, ITEM.transaction_monitor,
      ITEM.fourEyes, ITEM.recon_settlement, ITEM.disbursement, ITEM.fds,
      ITEM.refund_management_admin, ITEM.report_generator
    ],
    // Super Admin — all menus
    super: [
      ITEM.dashboard, ITEM.onboarding_monitor, ITEM.merchant_management, ITEM.merchant_business,
      ITEM.transaction_monitor, ITEM.fourEyes, ITEM.recon_settlement, ITEM.disbursement, ITEM.refund,
      ITEM.fds, ITEM.refund_management_full, ITEM.report_generator
    ],
    // Merchant
    merchant: [
      ITEM.dashboard, ITEM.merchant_business, ITEM.transaction_monitor,
      ITEM.recon_settlement, ITEM.disbursement, ITEM.refund, ITEM.report_generator
    ]
  };

  const navItems = NAV_BY_ROLE[role] || NAV_BY_ROLE.super;


  return (
    <div style={{
      width: sidebarOpen ? 240 : 68,
      flexShrink: 0,
      background: DARK_BG,
      display: 'flex', flexDirection: 'column',
      transition: 'width 250ms cubic-bezier(0.22,0.61,0.36,1)',
      overflow: 'hidden',
      boxShadow: '4px 0 20px rgba(0,50,56,0.35)'
    }}>

      {/* Logo */}
      <div style={{ padding: '24px 16px 20px', borderBottom: '1px solid rgba(255,255,255,0.08)', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 12 }}>
        <img
          src="assets/hiro-mark.svg"
          alt="hibank"
          style={{ width: 36, height: 36, flexShrink: 0, cursor: 'pointer', borderRadius: '50%' }}
          onClick={() => setSidebarOpen(!sidebarOpen)} />

        {sidebarOpen &&
          <div>
            <img src="assets/logo-hibank-white.svg" alt="hibank" style={{ height: 22, display: 'block' }} />
            <div style={{ fontSize: 10, fontWeight: 600, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: 3 }}>Back Office</div>
          </div>
        }
      </div>

      {/* Nav */}
      <nav style={{ flex: 1, padding: '12px 8px', display: 'flex', flexDirection: 'column', gap: 2, overflowY: 'auto' }}>
        {navItems.map((item) => {
          const hasSub = item.subItems && item.subItems.length > 0;
          const isExpanded = expandedNavs[item.id];
          const active = activeNav === item.id || (hasSub && item.subItems.some(sub => activeNav === sub.id));

          return (
            <div key={item.id} style={{ display: 'flex', flexDirection: 'column' }}>
              <button
                onClick={(e) => hasSub ? toggleExpand(e, item.id) : setActiveNav(item.id)}
                style={{
                  display: 'flex', alignItems: 'center',
                  gap: 10, position: 'relative',
                  padding: sidebarOpen ? '10px 12px' : '10px',
                  justifyContent: sidebarOpen ? 'flex-start' : 'center',
                  borderRadius: 8,
                  border: 'none', cursor: 'pointer',
                  fontFamily: "'Open Sans', sans-serif", fontSize: 14,
                  background: active && !hasSub ? TEAL : 'transparent',
                  color: active ? '#fff' : 'rgba(255,255,255,0.55)',
                  fontWeight: active ? 600 : 400,
                  whiteSpace: 'nowrap', transition: 'all 150ms'
                }}
                onMouseEnter={(e) => { if (!active || hasSub) e.currentTarget.style.background = 'rgba(255,255,255,0.07)'; }}
                onMouseLeave={(e) => { if (!active || hasSub) e.currentTarget.style.background = 'transparent'; }}>

                <i className={`bx ${item.icon}`} style={{ fontSize: 18, flexShrink: 0 }} />
                {sidebarOpen && <span style={{ flex: 1, textAlign: "left" }}>{item.label}</span>}

                {sidebarOpen && hasSub && (
                  <i className={`bx bx-chevron-${isExpanded ? 'down' : 'right'}`} style={{ fontSize: 16 }} />
                )}

                {sidebarOpen && item.badge > 0 &&
                  <span style={{ background: active && !hasSub ? 'rgba(255,255,255,0.25)' : '#cf5a27', color: '#fff', fontSize: 11, fontWeight: 700, borderRadius: 100, padding: '1px 7px', minWidth: 20, textAlign: 'center' }}>{item.badge}</span>
                }
                {!sidebarOpen && item.badge > 0 &&
                  <span style={{ position: 'absolute', top: 6, right: 8, width: 8, height: 8, borderRadius: '50%', background: '#cf5a27', border: '2px solid ' + DARK_BG }} />
                }
              </button>

              {/* Sub-items */}
              {hasSub && isExpanded && sidebarOpen && (
                <div style={{ display: 'flex', flexDirection: 'column', paddingLeft: 28, marginTop: 2, gap: 2 }}>
                  {item.subItems.map(sub => {
                    const subActive = activeNav === sub.id;
                    return (
                      <button
                        key={sub.id}
                        onClick={() => setActiveNav(sub.id)}
                        style={{
                          display: 'flex', alignItems: 'center',
                          gap: 8, position: 'relative',
                          padding: '8px 12px',
                          justifyContent: 'flex-start',
                          borderRadius: 8,
                          border: 'none', cursor: 'pointer',
                          fontFamily: "'Open Sans', sans-serif", fontSize: 13,
                          background: subActive ? TEAL : 'transparent',
                          color: subActive ? '#fff' : 'rgba(255,255,255,0.45)',
                          fontWeight: subActive ? 600 : 400,
                          whiteSpace: 'nowrap', transition: 'all 150ms'
                        }}
                        onMouseEnter={(e) => { if (!subActive) e.currentTarget.style.background = 'rgba(255,255,255,0.07)'; }}
                        onMouseLeave={(e) => { if (!subActive) e.currentTarget.style.background = 'transparent'; }}>

                        <i className={`bx ${sub.icon}`} style={{ fontSize: 16, flexShrink: 0 }} />
                        <span style={{ flex: 1, textAlign: "left" }}>{sub.label}</span>

                        {sub.badge > 0 &&
                          <span style={{ background: subActive ? 'rgba(255,255,255,0.25)' : '#cf5a27', color: '#fff', fontSize: 11, fontWeight: 700, borderRadius: 100, padding: '1px 7px', minWidth: 20, textAlign: 'center' }}>{sub.badge}</span>
                        }
                      </button>
                    )
                  })}
                </div>
              )}
            </div>
          );
        })}
      </nav>

      {/* User footer */}
      <div style={{ padding: '12px 8px', borderTop: '1px solid rgba(255,255,255,0.08)', flexShrink: 0 }}>
        {sidebarOpen ?
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px' }}>
            <div style={{ width: 34, height: 34, borderRadius: '50%', background: `linear-gradient(135deg, ${TEAL}, #0041A8)`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <span style={{ color: '#fff', fontWeight: 700, fontSize: 13 }}>{(user && user.initials) || 'AB'}</span>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ color: '#fff', fontWeight: 600, fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{(user && user.name) || 'Arief Budiman'}</div>
              <div style={{ color: 'rgba(255,255,255,0.4)', fontSize: 11, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{(user && user.roleLabel) || 'Super Admin'}</div>
            </div>
            <button onClick={onLogout} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'rgba(255,255,255,0.4)', padding: 4, display: 'flex' }}
              onMouseEnter={(e) => e.currentTarget.style.color = '#ed3151'}
              onMouseLeave={(e) => e.currentTarget.style.color = 'rgba(255,255,255,0.4)'}>

              <i className="bx bx-log-out" style={{ fontSize: 18 }} />
            </button>
          </div> :

          <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0' }}>
            <div style={{ width: 34, height: 34, borderRadius: '50%', background: `linear-gradient(135deg, ${TEAL}, #0041A8)`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <span style={{ color: '#fff', fontWeight: 700, fontSize: 13 }}>{(user && user.initials) || 'AB'}</span>
            </div>
          </div>
        }
      </div>
    </div>);

}

Object.assign(window, { Sidebar });