// Icons + shared UI atoms for BControl v0.5

const Icon = ({ name, size = 16, color = 'currentColor', strokeWidth = 1.75, style }) => {
  const common = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth, strokeLinecap: 'round', strokeLinejoin: 'round', style };
  switch (name) {
    case 'fire': return <svg {...common} fill={color} stroke="none"><path d="M12 2.5c.8 2.4 2.5 3.4 3.6 5.4a5.4 5.4 0 0 1-.3 5.8c1.3-.5 2.3-1.6 2.8-2.9 1.7 2.4 1.9 5.4.3 7.7a7.5 7.5 0 0 1-9.6 2.4C6 19.6 4.4 16.4 5 13.1c.5-2.6 2.5-3.7 3.4-6 .4-1 .5-2.1.3-3.1 1.4.3 2.6 1.3 3.3 2.7.3-1.5.3-3 0-4.2Z"/></svg>;
    case 'warning': return <svg {...common}><path d="M10.3 3.86 1.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" fill={color === 'currentColor' ? 'none' : color} fillOpacity=".15"/><path d="M12 9v4M12 17h.01"/></svg>;
    case 'shield': return <svg {...common}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z" fill={color === 'currentColor' ? 'none' : color} fillOpacity=".15"/></svg>;
    case 'settings': return <svg {...common}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.36.19.76.3 1.17.31a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.5 1Z"/></svg>;
    case 'refresh': return <svg {...common}><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/></svg>;
    case 'plus': return <svg {...common}><path d="M12 5v14M5 12h14"/></svg>;
    case 'close': return <svg {...common}><path d="M6 6l12 12M18 6 6 18"/></svg>;
    case 'check': return <svg {...common}><path d="M4 12l5 5 11-11"/></svg>;
    case 'trash': return <svg {...common}><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>;
    case 'search': return <svg {...common}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>;
    case 'filter': return <svg {...common}><path d="M3 4h18l-7 9v6l-4 2v-8L3 4Z"/></svg>;
    case 'bell': return <svg {...common}><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>;
    case 'logout': return <svg {...common}><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="m16 17 5-5-5-5M21 12H9"/></svg>;
    case 'user': return <svg {...common}><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>;
    case 'list': return <svg {...common}><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg>;
    case 'shield-admin': return <svg {...common}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z" fill={color} fillOpacity=".15"/><path d="m9 12 2 2 4-4"/></svg>;
    case 'eye': return <svg {...common}><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"/><circle cx="12" cy="12" r="3"/></svg>;
    case 'power': return <svg {...common}><path d="M18.36 6.64a9 9 0 1 1-12.73 0"/><path d="M12 2v10"/></svg>;
    case 'send': return <svg {...common}><path d="m22 2-7 20-4-9-9-4 20-7Z"/><path d="M22 2 11 13"/></svg>;
    case 'dot': return <svg {...common} fill={color} stroke="none"><circle cx="12" cy="12" r="4"/></svg>;
    case 'chev-down': return <svg {...common}><path d="m6 9 6 6 6-6"/></svg>;
    case 'chev-right': return <svg {...common}><path d="m9 6 6 6-6 6"/></svg>;
    case 'server': return <svg {...common}><rect x="2" y="3" width="20" height="7" rx="2"/><rect x="2" y="14" width="20" height="7" rx="2"/><path d="M6 7h.01M6 18h.01"/></svg>;
    case 'terminal': return <svg {...common}><path d="m7 9 3 3-3 3M12 15h5"/><rect x="2" y="4" width="20" height="16" rx="2"/></svg>;
    case 'clock': return <svg {...common}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
    default: return null;
  }
};

// ───────── Status pill ─────────
const StatusPill = ({ status }) => {
  // status: connected | disconnected | pending
  const map = {
    connected:    { bg: BC.ok.bg,     fg: BC.ok.fg,     dot: BC.ok.dot,    label: 'Conectado' },
    pending:      { bg: BC.pending.bg, fg: BC.pending.fg, dot: BC.pending.dot, label: 'Pendiente' },
    disconnected: { bg: BC.fire.bg,   fg: BC.fire.fg,   dot: BC.fire.dot,  label: 'Desconectado' },
  };
  const s = map[status] || map.disconnected;
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:6, padding:'2px 10px', borderRadius:999, background:s.bg, color:s.fg, fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'.06em' }}>
      <span style={{ width:6, height:6, borderRadius:6, background:s.dot }}/>
      {s.label}
    </span>
  );
};

// ───────── Role badge ─────────
const RoleBadge = ({ role }) => {
  const map = {
    admin:    { bg: '#F3E8FF', fg: '#6B21A8', label: 'ADMIN' },
    operator: { bg: BC.brandTint, fg: BC.brandDeep, label: 'OPERADOR' },
    viewer:   { bg: BC.bgAlt,   fg: BC.inkMuted, label: 'LECTOR' },
  };
  const s = map[role] || map.viewer;
  return (
    <span style={{ padding:'2px 8px', borderRadius:4, background:s.bg, color:s.fg, fontSize:10, fontWeight:700, letterSpacing:'.06em', fontFamily:BC.mono }}>{s.label}</span>
  );
};

// ───────── App Header ─────────
function AppHeader({ user, counts, animationGen, shouldAnimate, onLogout, onAdmin, onReconnect, onResetNotifications, liveState, onFilter, activeFilter, section, onSection, density, onDensity, onOpenSettings, onSidebarToggle }) {
  const [pillHover, setPillHover] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const menuRef = React.useRef(null);
  React.useEffect(() => {
    if (!menuOpen) return;
    const handler = (e) => { if (!menuRef.current?.contains(e.target)) setMenuOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [menuOpen]);
  const NotifIcon = ({ iconName, count, cat, severity }) => {
    const sel = activeFilter === cat;
    return (
      <button onClick={() => { console.log('[DEBUG] Badge click:', cat, 'sel:', sel, 'calling onFilter:', cat); onFilter && onFilter(cat); }} className="bc-btn bc-iconbtn"
        style={{ position:'relative', width:40, height:40, display:'flex', alignItems:'center', justifyContent:'center', border:'none', background: sel ? 'rgba(255,255,255,.18)' : 'transparent', borderRadius:6, color:'#fff', opacity: activeFilter && !sel ? .5 : 1 }}>
        <Icon name={iconName} size={20}/>
        {count > 0 && (
          <span key={`badge-${cat}-${animationGen}`} style={{ position:'absolute', top:3, right:3, minWidth:18, height:18, padding:'0 5px', borderRadius:9, background:severity.bar, color:'#fff', fontSize:10, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'0 0 0 2px '+BC.brand, animation: (cat==='alarm' && count>0 && shouldAnimate) ? 'bc-badge-pop .25s ease' : 'none' }}>
            {count >= 100 ? '99+' : count}
          </span>
        )}
      </button>
    );
  };
  const tabs = [
    { id: 'monitor', label: 'Monitor',    icon: 'server' },
    { id: 'stream',  label: 'Eventos',    icon: 'list' },
  ];
  if (user?.role === 'admin') tabs.push({ id: 'admin', label: 'Administración', icon: 'shield-admin' });
  return (
    <div className="bc-header" style={{ height:56, flex:'0 0 56px', background:BC.brand, display:'flex', alignItems:'center', paddingRight:12, color:'#fff', borderBottom:'1px solid '+BC.brandDeep, position:'relative' }}>
      <button className="bc-btn bc-hamburger" onClick={onSidebarToggle} aria-label="Paneles" title="Paneles"><Icon name="list" size={20}/></button>
      {/* Logo block — centered absolutely */}
      <div className="bc-header-logo" style={{ position:'absolute', left:'50%', transform:'translateX(-50%)', display:'flex', alignItems:'center', pointerEvents:'none' }}>
        <img src="/frontend/logo.png" alt="Logo" style={{ height:38, objectFit:'contain' }}/>
      </div>
      {/* Tabs */}
      <div style={{ display:'flex', alignItems:'center', height:'100%', minWidth:0 }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => onSection(t.id)} className="bc-btn" style={{ display:'flex', alignItems:'center', gap:7, height:56, padding:'0 14px', border:'none', background:'transparent', color:'#fff', fontSize:13, fontWeight: section===t.id ? 600 : 500, opacity: section===t.id ? 1 : .75, borderBottom:'3px solid '+(section===t.id ? '#fff' : 'transparent'), marginBottom:-1, whiteSpace:'nowrap' }}>
            <Icon name={t.icon} size={15}/>
            <span className="bc-tab-label">{t.label}</span>
          </button>
        ))}
      </div>
      <div style={{ flex:1 }}/>
      {/* Live pill */}
      <button onClick={onReconnect} onMouseEnter={() => setPillHover(true)} onMouseLeave={() => setPillHover(false)} className="bc-btn bc-livepill" style={{ display:'flex', alignItems:'center', gap:8, padding:'5px 12px', background:pillHover ? 'rgba(255,255,255,.2)' : 'rgba(255,255,255,.12)', border:'1px solid rgba(255,255,255,.18)', borderRadius:999, fontSize:12, fontWeight:500, marginRight:12, color:'#fff', transform: pillHover ? 'scale(1.05)' : 'scale(1)', transition:'transform .18s,background .18s' }} title="Reconectar">
        <span style={{ width:7, height:7, borderRadius:7, background: liveState==='live' ? '#86EFAC' : liveState==='reconnecting' ? '#FCD34D' : '#FCA5A5', animation: liveState==='live' ? 'bc-live-dot 1.8s ease-in-out infinite' : 'none' }}/>
        <span className="bc-livepill-text">{liveState==='reconnecting' ? 'Reconectando…' : (pillHover ? 'Reconectar' : (liveState==='live' ? 'En vivo' : 'Sin conexión'))}</span>
        <Icon name="refresh" size={12} style={liveState==='reconnecting' ? { animation:'bc-spin 0.7s linear infinite' } : null}/>
      </button>
      {/* Notification triad */}
      <div style={{ display:'flex', alignItems:'center', gap:2 }}>
        <NotifIcon iconName="fire"    count={counts.alarm}       cat="alarm"       severity={BC.fire}/>
        <NotifIcon iconName="warning" count={counts.trouble}     cat="trouble"     severity={BC.trouble}/>
        <NotifIcon iconName="shield"  count={counts.supervisory} cat="supervisory" severity={BC.supervisory}/>
      </div>
      <div style={{ width:1, height:24, background:'rgba(255,255,255,.2)', margin:'0 12px' }}/>
      {/* User chip with dropdown menu */}
      <div ref={menuRef} style={{ position:'relative', flex:'0 0 auto' }}>
        <button onClick={() => setMenuOpen(o => !o)} className="bc-btn"
          style={{ display:'flex', alignItems:'center', gap:6, padding:'3px 8px 3px 3px', background: menuOpen ? 'rgba(255,255,255,.22)' : 'rgba(255,255,255,.12)', border:'1px solid rgba(255,255,255,.18)', borderRadius:999, color:'#fff', fontFamily:'inherit' }}
          title={`${user?.username} · ${user?.role}`}>
          <div style={{ width:28, height:28, borderRadius:14, background:'#fff', color:BC.brand, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:12, flex:'0 0 28px' }}>
            {(user?.username || '?').slice(0,1).toUpperCase()}
          </div>
          <div className="bc-userchip-name" style={{ lineHeight:1.15, paddingRight:2, textAlign:'left' }}>
            <div style={{ fontSize:12, fontWeight:600 }}>{user?.username}</div>
            <div style={{ fontSize:10, color:'rgba(255,255,255,.75)', fontFamily:BC.mono, textTransform:'uppercase', letterSpacing:'.06em' }}>{user?.role}</div>
          </div>
          <Icon name="chev-down" size={13} style={{ transition:'transform .15s', transform: menuOpen ? 'rotate(180deg)' : 'rotate(0deg)' }}/>
        </button>
        {menuOpen && (
          <div className="bc-slide-up" style={{ position:'fixed', right:8, top:62, zIndex:200, background:BC.surface, border:'1px solid '+BC.border, borderRadius:8, boxShadow:BC.shadowLg, minWidth:264, maxWidth:'calc(100vw - 16px)', overflow:'hidden', color:BC.ink }}>
            {/* Header */}
            <div style={{ padding:'12px 14px', borderBottom:'1px solid '+BC.divider, background:BC.surfaceAlt, display:'flex', alignItems:'center', gap:10 }}>
              <div style={{ width:36, height:36, borderRadius:18, background:BC.brand, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:14 }}>{(user?.username || '?').slice(0,1).toUpperCase()}</div>
              <div style={{ minWidth:0, flex:1 }}>
                <div style={{ fontSize:13, fontWeight:600, color:BC.ink }}>{user?.username}</div>
                <div style={{ fontSize:11, color:BC.inkSubtle, fontFamily:BC.mono, textTransform:'uppercase', letterSpacing:'.06em' }}>{user?.role}</div>
              </div>
            </div>
            {/* Density settings */}
            <div style={{ padding:'10px 14px', borderBottom:'1px solid '+BC.divider }}>
              <div style={{ fontSize:11, fontWeight:600, color:BC.inkSubtle, textTransform:'uppercase', letterSpacing:'.06em', marginBottom:8 }}>Densidad</div>
              <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                {[{value:'compact',label:'Compacto'},{value:'comfortable',label:'Cómodo'},{value:'spacious',label:'Espacioso'}].map(opt => (
                  <button key={opt.value} onClick={() => { onDensity && onDensity(opt.value); setMenuOpen(false); }} className="bc-btn"
                    style={{ width:'100%', display:'flex', alignItems:'center', gap:8, padding:'6px 8px', border:'1px solid '+(density===opt.value ? BC.brand : BC.border), background: density===opt.value ? BC.brandTint : 'transparent', borderRadius:5, fontSize:12, color: density===opt.value ? BC.brand : BC.ink, textAlign:'left', fontFamily:'inherit', fontWeight: density===opt.value ? 600 : 400, cursor:'pointer' }}>
                    <span style={{ width:4, height:4, borderRadius:2, background: density===opt.value ? BC.brand : BC.inkFaint }}/>
                    {opt.label}
                  </button>
                ))}
              </div>
            </div>
            {/* Reset notifications */}
            <button onClick={() => { setMenuOpen(false); onResetNotifications && onResetNotifications(); }} className="bc-btn bc-nav-item"
              style={{ width:'100%', display:'flex', alignItems:'center', gap:10, padding:'10px 14px', border:'none', background:'transparent', fontSize:13, color:BC.ink, textAlign:'left', fontFamily:'inherit' }}>
              <Icon name="bell" size={15} color={BC.inkMuted}/> Limpiar notificaciones
              <div style={{ flex:1 }}/>
            </button>
            {/* Logout */}
            <button onClick={() => { setMenuOpen(false); onLogout(); }} className="bc-btn bc-nav-item"
              style={{ width:'100%', display:'flex', alignItems:'center', gap:10, padding:'10px 14px', border:'none', borderTop:'1px solid '+BC.divider, background:'transparent', fontSize:13, color:BC.fire.fg, textAlign:'left', fontFamily:'inherit', fontWeight:600 }}>
              <Icon name="logout" size={15}/> Cerrar sesión
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

// ───────── Status bar ─────────
function StatusBar({ panels, connected, events, filter, onClearFilter, lastUpdate }) {
  return (
    <div style={{ height:28, flex:'0 0 28px', background:BC.surfaceAlt, borderTop:'1px solid '+BC.border, display:'flex', alignItems:'center', padding:'0 14px', fontSize:11, fontFamily:BC.mono, color:BC.inkSubtle, gap:18 }}>
      <span style={{ display:'flex', alignItems:'center', gap:6 }}><span style={{ width:6, height:6, borderRadius:6, background:BC.ok.dot }}/>{panels} paneles</span>
      <span>{connected} conectados</span>
      <span>{panels - connected} sin conexión</span>
      <span>{events} eventos</span>
      {filter && (<>
        <div style={{ flex:1 }}/>
        <span style={{ display:'flex', alignItems:'center', gap:6, padding:'2px 8px', background:BC.brandTint, color:BC.brand, borderRadius:999, border:'1px solid '+BC.brand, fontSize:10, textTransform:'uppercase', fontWeight:700, letterSpacing:'.06em' }}>
          Filtro: {filter}
          <button onClick={onClearFilter} style={{ border:'none', background:'transparent', padding:0, display:'flex', cursor:'pointer', color:BC.brand }}><Icon name="close" size={12}/></button>
        </span>
      </>)}
      {!filter && <div style={{ flex:1 }}/>}
      <span className="bc-statusbar-extra">Última actualización {formatTs(lastUpdate)}</span>
      <span className="bc-statusbar-extra">BControl {APP_VERSION} · America/Santiago</span>
    </div>
  );
}

Object.assign(window, { Icon, StatusPill, RoleBadge, AppHeader, StatusBar });
