/* global React, SaoriIcons */
const { useState } = React;
const Ic = SaoriIcons;

/* ============================================================
   Sidebar
   ============================================================ */
function Sidebar({ current, onNavigate }) {
  const items = [
    { id: 'inicio', label: 'Inicio', icon: Ic.Home },
    { id: 'inbox', label: 'Inbox', icon: Ic.Inbox },
    { id: 'leads', label: 'Leads', icon: Ic.UserPlus },
    { id: 'agentes', label: 'Agentes', icon: Ic.Bot },
    { id: 'campanas', label: 'Campañas', icon: Ic.Megaphone },
    { id: 'clientes', label: 'Clientes', icon: Ic.UserCircle },
    { id: 'integraciones', label: 'Integraciones', icon: Ic.Puzzle },
    { id: 'reportes', label: 'Reportes', icon: Ic.BarChart },
    { id: 'configuracion', label: 'Configuración', icon: Ic.Settings },
  ];
  return (
    <aside className="sidebar">
      <div className="sidebar__brand">
        <div className="sidebar__brand-mark" aria-hidden="true">
          {/* Hub mark · Pulse · per brand/BRAND.md */}
          <svg width="22" height="22" viewBox="0 0 64 64" fill="none">
            <circle cx="32" cy="32" r="22" fill="none" stroke="#fff" strokeWidth="3" strokeOpacity="0.40"/>
            <circle cx="32" cy="32" r="14" fill="none" stroke="#fff" strokeWidth="3" strokeOpacity="0.75"/>
            <circle cx="32" cy="32" r="6" fill="#fff"/>
          </svg>
        </div>
        <div className="sidebar__brand-stack">
          <span className="sidebar__brand-name">Hub</span>
          <span className="sidebar__brand-byline">by <strong>Virtualia</strong></span>
        </div>
      </div>

      <nav className="sidebar__nav">
        {items.map(it => (
          <button
            key={it.id}
            type="button"
            className={'nav-item' + (current === it.id ? ' nav-item--active' : '')}
            onClick={() => onNavigate(it.id)}
          >
            <it.icon size={18} strokeWidth={current === it.id ? 2 : 1.7} />
            <span>{it.label}</span>
          </button>
        ))}
      </nav>

      <div className="sidebar__footer">
        <div className="user-card">
          <div className="user-card__avatar">AM</div>
          <div className="col">
            <span className="user-card__name">Ana Martínez</span>
            <span className="user-card__role">Administradora</span>
          </div>
          <Ic.ChevronUp size={16} className="user-card__chevron" />
        </div>
      </div>
    </aside>
  );
}

/* ============================================================
   Topbar
   ============================================================ */
function Topbar() {
  return (
    <header className="topbar">
      <button type="button" className="tenant-selector">
        <span className="tenant-selector__icon-wrap">
          <Ic.Building size={15} />
        </span>
        <span>Hotel Demo</span>
        <Ic.ChevronDown size={16} className="tenant-selector__chevron" />
      </button>

      <div className="search">
        <Ic.Search size={17} className="search__icon" />
        <input placeholder="Buscar conversaciones, contactos, reservas..." />
        <span className="search__kbd">⌘ K</span>
      </div>

      <div className="top-actions">
        <span className="demo-badge" aria-label="Demo visual">
          <span className="demo-badge__dot" /> Demo visual
        </span>
        <button type="button" className="icon-btn" aria-label="Notificaciones">
          <Ic.Bell size={18} />
          <span className="icon-btn__dot">3</span>
        </button>
        <button type="button" className="icon-btn" aria-label="Mensajes">
          <Ic.Mail size={18} />
          <span className="icon-btn__dot icon-btn__dot--rose">·</span>
        </button>
        <button type="button" className="icon-btn" aria-label="Ayuda">
          <Ic.Help size={18} />
        </button>
        <div className="top-avatar">AM</div>
      </div>
    </header>
  );
}

/* ============================================================
   Shared bits: KPI, IntegrationCard, StatusBadge, Sparkline
   ============================================================ */
function Sparkline({ values = [3, 5, 4, 6, 5, 8, 7, 9, 6, 8, 10, 9], tone = 'violet' }) {
  const max = Math.max(...values);
  return (
    <div className="kpi__spark">
      {values.map((v, i) => (
        <span
          key={i}
          className={i >= values.length - 3 ? 'tall' : ''}
          style={{ height: `${(v / max) * 100}%` }}
        />
      ))}
    </div>
  );
}

function KpiCard({ label, value, delta, deltaTone = 'up', deltaSub = 'vs ayer', icon: Icon, iconTone = 'violet', spark }) {
  const arrow = deltaTone === 'up' ? <Ic.ArrowUp size={12} strokeWidth={2.4}/> : deltaTone === 'down' ? <Ic.ArrowDown size={12} strokeWidth={2.4}/> : <Ic.ArrowRight size={12} strokeWidth={2.4}/>;
  return (
    <div className="kpi">
      <div className="kpi__top">
        <div className="kpi__label">{label}</div>
        <div className={'kpi__icon icon-chip--' + iconTone} style={{ background: 'var(--' + iconTone + '-50)', color: 'var(--' + iconTone + '-600)' }}>
          <Icon size={16} />
        </div>
      </div>
      <div className="kpi__value">{value}</div>
      <div className="kpi__bottom">
        <div className={'kpi__delta kpi__delta--' + deltaTone}>
          {arrow}<span>{delta}</span>
          <span className="kpi__sub">{deltaSub}</span>
        </div>
        <Sparkline values={spark} />
      </div>
    </div>
  );
}

/* Estado canónico de integración/acción · vocabulario honesto per BRAND.md + DESIGN.md (Phase 4.1).
   Nunca usar "Conectado/Activo/Sincronizado" para algo sin runtime. */
function StatusChip({ state, label }) {
  const map = {
    'disenado':            { t: 'Diseñado',            cls: 'status-chip--design' },
    'proxima-fase':        { t: 'Próxima fase',        cls: 'status-chip--next'   },
    'pendiente':           { t: 'Pendiente',           cls: 'status-chip--pending'},
    'no-conectado':        { t: 'No conectado',        cls: 'status-chip--off'    },
    'requiere-aprobacion': { t: 'Requiere aprobación', cls: 'status-chip--pending'},
    'handoff':             { t: 'Handoff humano',      cls: 'status-chip--design' },
    'baja-confianza':      { t: 'Baja confianza',      cls: 'status-chip--pending'},
    'demo':                { t: 'Demo visual',         cls: 'status-chip--demo'   },
    'sugerido':            { t: 'Sugerido por IA',     cls: 'status-chip--design' },
    'verificado':          { t: 'Verificado',          cls: 'status-chip--ok'     },
  };
  const c = map[state] || { t: label || state, cls: 'status-chip--off' };
  return <span className={'status-chip ' + c.cls}>{label || c.t}</span>;
}

function IntegrationCard({ icon: Icon, iconTone = 'violet', title, sub, state }) {
  return (
    <div className="integration-card">
      <div className={'icon-chip icon-chip--lg icon-chip--' + iconTone}>
        <Icon size={18} />
      </div>
      <div className="col" style={{ flex: 1, minWidth: 0 }}>
        <div className="integration-card__title">{title}</div>
        {sub && <div className="integration-card__sub">{sub}</div>}
      </div>
      <StatusChip state={state} />
    </div>
  );
}

function ChannelDot({ kind, size = 16 }) {
  const map = {
    whatsapp: { Icon: Ic.ChWhatsapp, cls: 'channel-whatsapp' },
    messenger: { Icon: Ic.ChMessenger, cls: 'channel-messenger' },
    instagram: { Icon: Ic.ChInstagram, cls: 'channel-instagram' },
    email: { Icon: Ic.ChEmail, cls: 'channel-email' },
    webchat: { Icon: Ic.ChWebChat, cls: 'channel-webchat' },
  };
  const c = map[kind] || map.whatsapp;
  return (
    <span className={'avatar__channel ' + c.cls} style={{ width: size, height: size, color: '#fff' }}>
      <c.Icon size={size - 6} strokeWidth={2.2} />
    </span>
  );
}

window.SaoriShell = { Sidebar, Topbar, KpiCard, IntegrationCard, StatusChip, Sparkline, ChannelDot };
