// Topbar — breadcrumb, search, notifications, portal, user menu
const Topbar = ({ activeLabel, openNotif, setOpenNotif, openUser, setOpenUser, onBurger, currentRole, setCurrentRole }) => {
  // SIDEBAR_USER_META vive en sidebar.jsx, que carga antes que este archivo.
  const usuarioActivo = (SIDEBAR_USER_META[currentRole] || SIDEBAR_USER_META.admin);
  return (
    <header className="topbar">
      <button className="tb-burger" onClick={onBurger} aria-label="Menú">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M4 6h16M4 12h16M4 18h16" /></svg>
      </button>
      <div className="crumbs">
        <span>Inicio</span>
        <span className="sep">/</span>
        <span className="current">{activeLabel}</span>
      </div>

      <div className="top-actions">
        <RoleSwitcher currentRole={currentRole} setCurrentRole={setCurrentRole} />

        <div style={{ position: 'relative' }}>
          <button
            className="icon-btn"
            onClick={() => { setOpenNotif(!openNotif); setOpenUser(false); }}
          >
            <IconBell size={19} />
            <span className="bell-badge">8</span>
          </button>
          {openNotif && <NotifDropdown />}
        </div>

        <div style={{ position: 'relative' }}>
          <button
            className="user-pill"
            onClick={() => { setOpenUser(!openUser); setOpenNotif(false); }}
          >
            <div className="avatar">{usuarioActivo.initials}</div>
            <div style={{ textAlign: 'left' }}>
              <div className="name">{usuarioActivo.name.split(' ').slice(0, 2).join(' ')}</div>
            </div>
            <IconChevronDown size={14} style={{ color: 'var(--text-muted)' }} />
          </button>
          {openUser && <UserDropdown usuarioActivo={usuarioActivo} />}
        </div>
      </div>
    </header>
  );
};

const NOTIFS = [
  { type: 'auto', icon: 'IconZap', title: 'Motor activado para Andrés Mejía', sub: 'Cargo: Operario de Clasificación · 12 tareas generadas', time: 'hace 2 min', unread: true, color: 'navy' },
  { type: 'sst', icon: 'IconAlert', title: '3 exámenes médicos vencidos', sub: 'Línea de aprovechamiento · Sede Cali', time: 'hace 18 min', unread: true, color: 'rose' },
  { type: 'doc', icon: 'IconDoc', title: 'Contrato firmado por Juan David Ruiz', sub: 'Onboarding paso 4 de 7 completado', time: 'hace 1 h', unread: true, color: 'green' },
  { type: 'time', icon: 'IconCalendar', title: '7 solicitudes de vacaciones pendientes', sub: 'Esperando aprobación de líderes', time: 'hace 3 h', unread: false, color: 'amber' },
  { type: 'epp', icon: 'IconShirt', title: 'Entrega de dotación 2026-Q2', sub: '142 colaboradores · cierre 15/05', time: 'ayer', unread: false, color: 'blue' },
];

const NotifDropdown = () => {
  const ICONS = { IconZap, IconAlert, IconDoc, IconCalendar, IconShirt };
  return (
    <div style={{
      position: 'absolute', top: 'calc(100% + 8px)', right: 0,
      width: 380, background: 'white', border: '1px solid var(--border)',
      borderRadius: 12, boxShadow: 'var(--shadow-pop)', zIndex: 50, overflow: 'hidden',
    }}>
      <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontWeight: 600, fontSize: 14 }}>Notificaciones</div>
        <button style={{ background: 'transparent', border: 'none', color: 'var(--navy-800)', fontSize: 12, fontWeight: 500 }}>Marcar todas como leídas</button>
      </div>
      <div style={{ maxHeight: 420, overflowY: 'auto' }}>
        {NOTIFS.map((n, i) => {
          const Ico = ICONS[n.icon];
          return (
            <div key={i} style={{
              display: 'flex', gap: 12, padding: '12px 16px',
              borderBottom: '1px solid var(--border)',
              background: n.unread ? 'var(--navy-50)' : 'white',
              cursor: 'pointer',
            }}>
              <div className={`task-icon ${n.color}`}><Ico size={16} /></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>{n.title}</div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>{n.sub}</div>
                <div style={{ fontSize: 11, color: 'var(--text-subtle)', marginTop: 4 }}>{n.time}</div>
              </div>
              {n.unread && <div style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--aguila-600)', marginTop: 6, flexShrink: 0 }} />}
            </div>
          );
        })}
      </div>
      <div style={{ padding: 10, borderTop: '1px solid var(--border)', textAlign: 'center' }}>
        <button style={{ background: 'transparent', border: 'none', color: 'var(--navy-800)', fontSize: 13, fontWeight: 500 }}>Ver todas</button>
      </div>
    </div>
  );
};

const _emailDe = (nombre) => `${nombre.toLowerCase().split(' ')[0]}.${nombre.toLowerCase().split(' ').slice(-1)[0][0]}@atica.co`;

const UserDropdown = ({ usuarioActivo }) => (
  <div style={{
    position: 'absolute', top: 'calc(100% + 8px)', right: 0,
    width: 240, background: 'white', border: '1px solid var(--border)',
    borderRadius: 12, boxShadow: 'var(--shadow-pop)', zIndex: 50, overflow: 'hidden',
  }}>
    <div style={{ padding: '14px 14px 12px', borderBottom: '1px solid var(--border)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div className="avatar" style={{ width: 36, height: 36, fontSize: 13 }}>{usuarioActivo.initials}</div>
        <div>
          <div style={{ fontSize: 13.5, fontWeight: 600 }}>{usuarioActivo.name}</div>
          <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{_emailDe(usuarioActivo.name)}</div>
        </div>
      </div>
    </div>
    {[
      ['Mi perfil', 'IconUsers'],
      ['Cambiar de rol', 'IconCircle'],
      ['Configuración', 'IconSettings'],
      ['Centro de ayuda', 'IconBook'],
    ].map(([label]) => (
      <div key={label} style={{
        padding: '10px 14px', fontSize: 13.5, cursor: 'pointer',
      }}
      onMouseEnter={(e)=>e.currentTarget.style.background='var(--surface)'}
      onMouseLeave={(e)=>e.currentTarget.style.background='white'}>
        {label}
      </div>
    ))}
    <div style={{ borderTop: '1px solid var(--border)' }} />
    <div style={{ padding: '10px 14px', fontSize: 13.5, color: 'var(--aguila-600)', fontWeight: 500, cursor: 'pointer' }}>Cerrar sesión</div>
  </div>
);

window.Topbar = Topbar;
