// Shell: Sidebar + Topbar + page-routing host

const { useState, useEffect, useRef } = React;

const NAV_RAW = [
  { id: 'dashboard',     label: 'Dashboard',      icon: 'Dashboard' },
  { id: 'conversations', label: 'Conversaciones', icon: 'Chat' },
  { id: 'tickets',       label: 'Tickets',        icon: 'Ticket' },
  { id: 'technicians',   label: 'Técnicos',       icon: 'Wrench' },
  { id: 'agents',        label: 'Agentes IA',     icon: 'Bot' },
  { id: 'reporting',     label: 'Reporting',      icon: 'Chart' },
  { id: '__sep__' },
  { id: 'billing',       label: 'Facturación',    icon: 'Card' },
  { id: 'admin',         label: 'Administración', icon: 'Settings' },
];

const computeNavCounts = () => {
  const D = window.BW_DATA || {};
  const total      = (D.PM_TICKETS || []).length;
  const active     = (D.PM_TICKETS || []).filter(t => t.state !== 'resolved').length;
  const pendingTec = (D.PM_TICKETS || []).filter(t => t.state === 'open').length;
  return {
    dashboard:     active,
    conversations: total,
    tickets:       active,
    technicians:   pendingTec || null,
  };
};

const NAV = NAV_RAW.map(n => {
  const counts = computeNavCounts();
  return counts[n.id] != null ? { ...n, count: counts[n.id] } : n;
});

function Sidebar({ page, onNav }) {
  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <img src="assets/blueways-logo-black.png" className="brand-logo" alt="Blueways" />
        <div className="brand-name">Blueways</div>
      </div>
      <div className="sidebar-search">
        <I.Search size={14} />
        <input placeholder="Buscar leads, conversaciones…" />
      </div>
      <div className="nav-section" style={{ flex: 1, overflow: 'auto' }}>
        {NAV.map((n, i) => {
          if (n.id === '__sep__') return <div key={i} style={{ height: 1, background: 'var(--color-border)', margin: '10px 12px' }} />;
          const Ic = I[n.icon];
          const active = page === n.id;
          return (
            <div key={n.id} className={'nav-item' + (active ? ' active' : '')} onClick={() => onNav(n.id)}>
              <Ic className="nav-icon" size={16} />
              <span style={{ flex: 1 }}>{n.label}</span>
              {n.count != null && <span className="badge" style={{ background: active ? 'rgba(37,99,235,.15)' : 'var(--color-surface-2)', color: active ? 'var(--color-accent)' : 'var(--color-text-secondary)', fontSize: 11, padding: '1px 8px' }}>{n.count}</span>}
            </div>
          );
        })}
      </div>
      <div className="sidebar-footer">
        <div className="avatar" style={{ background: 'linear-gradient(135deg,#60A5FA,#2563EB)' }}>AN</div>
        <div className="footer-meta">
          <div className="name">Adrián Núñez</div>
          <div className="tenant">Ementil Grupo Inmobiliario S.L.</div>
        </div>
        <button className="icon-btn" title="Salir"><I.Logout size={16} /></button>
      </div>
    </aside>
  );
}

const PAGE_TITLES = {
  dashboard:     { title: 'Dashboard',                crumb: ['Ementil Grupo Inmobiliario', 'Dashboard'] },
  conversations: { title: 'Conversaciones',           crumb: ['Ementil Grupo Inmobiliario', 'Conversaciones'] },
  tickets:       { title: 'Tickets',                  crumb: ['Ementil Grupo Inmobiliario', 'Tickets'] },
  ticket_detail: { title: 'Ficha de ticket',          crumb: ['Ementil Grupo Inmobiliario', 'Tickets', 'Detalle'] },
  technicians:   { title: 'Técnicos',                 crumb: ['Ementil Grupo Inmobiliario', 'Técnicos'] },
  agents:        { title: 'Agentes IA',               crumb: ['Ementil Grupo Inmobiliario', 'Agentes IA'] },
  agent_detail:  { title: 'Configuración de agente',  crumb: ['Ementil Grupo Inmobiliario', 'Agentes IA', 'Recepción WhatsApp'] },
  reporting:     { title: 'Reporting',                crumb: ['Ementil Grupo Inmobiliario', 'Reporting'] },
  billing:       { title: 'Facturación',              crumb: ['Ementil Grupo Inmobiliario', 'Facturación'] },
  admin:         { title: 'Administración',           crumb: ['Ementil Grupo Inmobiliario', 'Administración'] },
};

function Topbar({ page, onNav }) {
  const meta = PAGE_TITLES[page] || PAGE_TITLES.dashboard;
  const [guideOpen, setGuideOpen] = useState(false);
  const [profileOpen, setProfileOpen] = useState(false);
  const [notifsOpen, setNotifsOpen] = useState(false);
  const [readIds, setReadIds] = useState(new Set());
  const profileRef = useRef(null);
  const notifsRef = useRef(null);

  // First-run: open guide automatically the first time
  useEffect(() => {
    if (!localStorage.getItem('bw_guide_seen')) {
      const t = setTimeout(() => setGuideOpen(true), 600);
      return () => clearTimeout(t);
    }
  }, []);

  // Close profile menu on outside click
  useEffect(() => {
    if (!profileOpen) return;
    const onDoc = (e) => {
      if (profileRef.current && !profileRef.current.contains(e.target)) setProfileOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [profileOpen]);

  // Close notifs on outside click
  useEffect(() => {
    if (!notifsOpen) return;
    const onDoc = (e) => {
      if (notifsRef.current && !notifsRef.current.contains(e.target)) setNotifsOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [notifsOpen]);

  const NOTIFS = [
    { id:'n1', t:'hace 2 min',  channel:'whatsapp', icon:'Chat',  color:'#22c55e', title:'Nueva solicitud',          sub:'Lucía Marín · Apt 4B · AC averiado',                       agent:'Echo · WhatsApp', score:'92%' },
    { id:'n2', t:'hace 8 min',  channel:'phone',    icon:'Phone', color:'#f59e0b', title:'Llamada de incidencia',    sub:'Pavel Krastev · Plaga · tercera reincidencia',             agent:'Vox · Teléfono',  score:'88%' },
    { id:'n3', t:'hace 14 min', channel:'whatsapp', icon:'Chat',  color:'#22c55e', title:'Técnico confirmado',         sub:'James Carter · Fontanería · mañana 10:00',                  agent:'Echo · WhatsApp', score:'95%' },
    { id:'n4', t:'hace 32 min', channel:'mail',     icon:'Mail',  color:'#6366f1', title:'Solicitud derivada a humano', sub:'Helena Vidal · Carpintería · fiscalidad arrendamiento',  agent:'Atlas · Email',   score:'—', warn: true },
    { id:'n5', t:'hace 1 h',    channel:'whatsapp', icon:'Chat',  color:'#22c55e', title:'Nueva solicitud',          sub:'Sofía Aragón · Apt 7D · horno no enciende',                  agent:'Echo · WhatsApp', score:'81%' },
    { id:'n6', t:'hace 2 h',    channel:'phone',    icon:'Phone', color:'#f59e0b', title:'Llamada de incidencia',    sub:'Tomás Ferré · sin agua caliente · termo cambiado',         agent:'Vox · Teléfono',  score:'77%' },
  ];
  const unreadCount = NOTIFS.filter(n => !readIds.has(n.id)).length;
  const markRead = (id) => setReadIds(s => new Set([...s, id]));
  const markAllRead = () => setReadIds(new Set(NOTIFS.map(n => n.id)));

  return (
    <header className="topbar">
      <div className="topbar-title">{meta.title}</div>
      <div className="crumb">
        {meta.crumb.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="sep"><I.ChevR size={12} /></span>}
            <span className={i === meta.crumb.length - 1 ? 'current' : ''}>{c}</span>
          </React.Fragment>
        ))}
      </div>
      <div className="topbar-actions">
        <button className="btn btn-sm" onClick={() => setGuideOpen(true)}>
          <I.Book size={14} /> Guía
        </button>
        <button className="icon-btn" title="Notificaciones" onClick={() => setNotifsOpen(o => !o)} style={{ position:'relative' }}>
          <I.Bell size={16} />
          {unreadCount > 0 && (
            <span style={{ position:'absolute', top: 4, right: 4, minWidth: 14, height: 14, padding:'0 3px', background: 'var(--color-danger)', color:'white', borderRadius: 999, fontSize: 9, fontWeight: 700, display:'grid', placeItems:'center', fontFamily:'var(--font-mono)' }}>
              {unreadCount}
            </span>
          )}
        </button>
        {notifsOpen && (
          <div ref={notifsRef} style={{
            position:'absolute', top: 52, right: 16, width: 380, zIndex: 50,
            background:'white', border:'1px solid var(--color-border)', borderRadius: 12,
            boxShadow:'0 12px 40px -12px rgba(15,23,42,.25)',
            display:'flex', flexDirection:'column', maxHeight: 'calc(100vh - 80px)',
            animation:'fadeDown .15s ease-out',
          }}>
            <div style={{ padding:'14px 16px 10px', display:'flex', alignItems:'center', justifyContent:'space-between', borderBottom:'1px solid var(--color-border)' }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Notificaciones</div>
                <div style={{ fontSize: 11, color:'var(--color-text-secondary)' }}>{unreadCount} sin leer · solicitudes y dispatches</div>
              </div>
              {unreadCount > 0 && (
                <button onClick={markAllRead} style={{ border: 0, background:'transparent', color:'var(--color-accent)', fontSize: 11.5, cursor:'pointer', fontWeight: 500 }}>
                  Marcar todas
                </button>
              )}
            </div>
            <div style={{ flex: 1, overflow:'auto' }}>
              {NOTIFS.map(n => {
                const NIc = I[n.icon];
                const unread = !readIds.has(n.id);
                return (
                  <button key={n.id} onClick={() => { markRead(n.id); onNav && onNav('tickets'); setNotifsOpen(false); }}
                    style={{
                      width:'100%', textAlign:'left', display:'flex', gap: 12,
                      padding:'12px 16px', border: 0, borderBottom:'1px solid var(--color-border)',
                      background: unread ? 'var(--color-accent-light)' : 'transparent',
                      cursor:'pointer',
                    }}>
                    <div style={{ width: 32, height: 32, borderRadius: 8, background: `${n.color}22`, color: n.color, display:'grid', placeItems:'center', flexShrink: 0 }}>
                      <NIc size={14} />
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display:'flex', alignItems:'baseline', gap: 6, marginBottom: 2 }}>
                        <div style={{ fontSize: 13, fontWeight: unread ? 600 : 500, color:'var(--color-text-primary)' }}>{n.title}</div>
                        {unread && <span style={{ width: 6, height: 6, borderRadius:'50%', background:'var(--color-accent)' }} />}
                        <span style={{ marginLeft:'auto', fontSize: 10.5, color:'var(--color-text-muted)', fontFamily:'var(--font-mono)', flexShrink: 0 }}>{n.t}</span>
                      </div>
                      <div style={{ fontSize: 12, color:'var(--color-text-secondary)', marginBottom: 4, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{n.sub}</div>
                      <div style={{ display:'flex', alignItems:'center', gap: 6 }}>
                        <span style={{ fontSize: 10.5, padding:'1px 7px', background:'var(--color-surface)', borderRadius: 999, color:'var(--color-text-secondary)' }}>{n.agent}</span>
                        {n.score !== '—' && (
                          <span style={{ fontSize: 10.5, padding:'1px 7px', background:'rgba(34,197,94,.1)', borderRadius: 999, color:'var(--color-success)', fontWeight: 600, fontFamily:'var(--font-mono)' }}>{n.score}</span>
                        )}
                        {n.warn && (
                          <span style={{ fontSize: 10.5, padding:'1px 7px', background:'rgba(245,158,11,.12)', borderRadius: 999, color:'var(--color-warning)', fontWeight: 600 }}>Requiere atención</span>
                        )}
                      </div>
                    </div>
                  </button>
                );
              })}
            </div>
            <div style={{ padding:'10px 16px', borderTop:'1px solid var(--color-border)', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <button onClick={() => { onNav && onNav('tickets'); setNotifsOpen(false); }} style={{ border: 0, background:'transparent', color:'var(--color-accent)', fontSize: 12, fontWeight: 500, cursor:'pointer' }}>
                Ver todos los tickets →
              </button>
              <button style={{ border: 0, background:'transparent', color:'var(--color-text-secondary)', fontSize: 12, cursor:'pointer' }}>
                Configurar alertas
              </button>
            </div>
          </div>
        )}
        <div style={{ width: 1, height: 24, background: 'var(--color-border)' }} />
        <div ref={profileRef} style={{ position:'relative' }}>
          <div
            className="avatar"
            style={{ background: 'linear-gradient(135deg,#60A5FA,#2563EB)', cursor:'pointer', outline: profileOpen ? '2px solid var(--color-accent)' : 'none', outlineOffset: 2 }}
            onClick={() => setProfileOpen(o => !o)}
          >
            AN
          </div>
          {profileOpen && <ProfileMenu onClose={() => setProfileOpen(false)} onNav={onNav} />}
        </div>
      </div>
      {window.Guide ? React.createElement(window.Guide, { open: guideOpen, onClose: () => setGuideOpen(false), onNav }) : null}
    </header>
  );
}

function ProfileMenu({ onClose, onNav }) {
  const items = [
    { label: 'Mi perfil',          icon: 'User',     section: 'Tu cuenta' },
    { label: 'Notificaciones',     icon: 'Bell' },
    { label: 'Atajos de teclado',  icon: 'Doc' },
    { label: 'Tema claro / oscuro',icon: 'Sun' },
    { label: 'Administración',     icon: 'Settings', go: 'admin', section: 'Empresa' },
    { label: 'Facturación',        icon: 'Card',     go: 'billing' },
    { label: 'Cerrar sesión',      icon: 'Logout',   section: '_', danger: true },
  ];
  return (
    <div style={{
      position:'absolute', top: 'calc(100% + 8px)', right: 0,
      width: 280, background:'white', border:'1px solid var(--color-border)', borderRadius: 12,
      boxShadow:'0 1px 3px rgba(15,23,42,.06), 0 24px 48px -16px rgba(15,23,42,.18)',
      zIndex: 80, overflow:'hidden',
      animation: 'fade .15s ease-out'
    }}>
      <div style={{ padding:'16px 16px 14px', borderBottom:'1px solid var(--color-border)', display:'flex', alignItems:'center', gap: 12 }}>
        <div className="avatar" style={{ background:'linear-gradient(135deg,#60A5FA,#2563EB)', width: 40, height: 40, fontSize: 14 }}>AN</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600 }}>Adrián Núñez</div>
          <div style={{ fontSize: 12, color:'var(--color-text-secondary)' }} className="truncate">adrian@blueways.es</div>
        </div>
      </div>
      <div style={{ padding: 6 }}>
        {items.map((it, i) => {
          const Ic = I[it.icon];
          const prevSection = i > 0 ? items[i-1].section : null;
          return (
            <React.Fragment key={i}>
              {it.section && it.section !== prevSection && it.section !== '_' && (
                <div style={{ padding:'8px 10px 4px', fontSize: 11, fontWeight: 600, color:'var(--color-text-muted)' }}>{it.section}</div>
              )}
              {it.section === '_' && <div style={{ height: 1, background:'var(--color-border)', margin:'4px 0' }} />}
              <button
                onClick={() => { if (it.go) onNav(it.go); onClose(); }}
                style={{
                  width:'100%', display:'flex', alignItems:'center', gap: 10,
                  padding:'8px 10px', border: 0, background:'transparent',
                  textAlign:'left', borderRadius: 6, cursor:'pointer',
                  fontSize: 13.5, color: it.danger ? 'var(--color-danger)' : 'var(--color-text-primary)'
                }}
                onMouseEnter={e => e.currentTarget.style.background='var(--color-surface)'}
                onMouseLeave={e => e.currentTarget.style.background='transparent'}
              >
                <Ic size={14} />
                <span style={{ flex: 1 }}>{it.label}</span>
              </button>
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

window.Shell = { Sidebar, Topbar, NAV, PAGE_TITLES };
