/* global React */
// =======================================================================
// BlazeConnector Admin v3 — AppShell (Sidebar + Topbar)
// =======================================================================
const { useState: _useState, useEffect: _useEffect, useRef: _useRef, useMemo: _useMemo } = React;

const NAV_GROUPS = [
  { label: 'Operaciones', items: [
    { id: 'dashboard',  label: 'Dashboard',  icon: 'gauge',         path: '/dashboard',  perms: ['view:dashboard'] },
    { id: 'messaging',  label: 'Mensajería', icon: 'message-square',path: '/messaging',  perms: ['view:messaging'] },
    { id: 'queues',     label: 'Colas',      icon: 'layers',        path: '/queues',     perms: ['view:queues'] },
    { id: 'logs',       label: 'Logs',       icon: 'terminal',      path: '/logs',       perms: ['view:logs'] },
    { id: 'alerts',     label: 'Alertas',    icon: 'bell-ring',     path: '/alerts',     perms: ['view:alerts'] }
  ]},
  { label: 'Administración', items: [
    { id: 'tenants',    label: 'Tenants',    icon: 'building-2',    path: '/tenants',    perms: ['view:tenants'] },
    { id: 'apikeys',    label: 'API Keys',   icon: 'key-round',     path: '/apikeys',    perms: ['view:apikeys'] },
    { id: 'templates',  label: 'Templates',  icon: 'file-text',     path: '/templates',  perms: ['view:templates'] },
    { id: 'audit',      label: 'Auditoría',  icon: 'shield-check',  path: '/audit',      perms: ['view:audit'] }
  ]},
  { label: 'Integraciones', items: [
    { id: 'isps',       label: 'ISP Providers', icon: 'router',     path: '/isps',       perms: ['view:integrations'] },
    { id: 'pagos',      label: 'Pagos',         icon: 'credit-card',path: '/pagos',      perms: ['view:integrations'] }
  ]}
];

const ROLE_DEFS = {
  superadmin:  { label: 'Superadmin',  perms: '*', desc: 'Acceso total al sistema' },
  operaciones: { label: 'Operaciones', desc: 'CRUD operacional, retries, configuración',
    perms: ['view:dashboard','view:messaging','view:queues','view:logs','view:alerts','view:tenants','view:apikeys','view:templates','view:audit','view:integrations','retry:execute','tenant:edit','apikey:create','apikey:revoke','template:sync','alert:ack','config:edit'] },
  soporte:     { label: 'Soporte', desc: 'Lectura + retries + lookups operacionales',
    perms: ['view:dashboard','view:messaging','view:queues','view:logs','view:alerts','view:tenants','view:audit','retry:execute','alert:ack'] },
  readonly:    { label: 'Read-only', desc: 'Solo lectura, sin acciones',
    perms: ['view:dashboard','view:messaging','view:queues','view:logs','view:alerts','view:tenants','view:apikeys','view:templates','view:audit','view:integrations'] }
};

function hasPerm(role, perm) {
  const def = ROLE_DEFS[role];
  if (!def) return false;
  if (def.perms === '*') return true;
  return def.perms.includes(perm);
}

const TENANT_GRAD = (id) => {
  const grads = ['linear-gradient(135deg,#FF5A1F,#F000D8)', 'linear-gradient(135deg,#1E7BFF,#7A3CFF)', 'linear-gradient(135deg,#2ECC5A,#16C6B9)', 'linear-gradient(135deg,#F000D8,#7A3CFF)', 'linear-gradient(135deg,#FF5A1F,#F2A900)', 'linear-gradient(135deg,#16C6B9,#1E7BFF)'];
  return grads[(id || '').charCodeAt(4) % grads.length];
};

/* ---------------- Sidebar ------------------------------------------ */
function Sidebar({ activePath, onNav, role, badges }) {
  return (
    <aside className="app-sidebar">
      <div className="sb-brand">
        <div className="sb-mark"><span>BLAZE</span></div>
        <div className="sb-brand-text">
          <span className="sb-brand-name">Connector</span>
          <span className="sb-brand-sub">v3.4.2 · admin</span>
        </div>
      </div>

      <button className="sb-env" title="Cambiar environment">
        <span className="sb-env-dot"></span>
        <span className="sb-env-lbl">prod</span>
        <span className="sb-env-name">sdq-1.blaze.do</span>
        <window.Icon name="chevrons-up-down" size={11} className="sb-env-caret" />
      </button>

      <nav className="sb-nav">
        {NAV_GROUPS.map((g) => (
          <React.Fragment key={g.label}>
            <div className="sb-group-head">{g.label}</div>
            {g.items.map((it) => {
              const allowed = it.perms.every((p) => hasPerm(role, p));
              const active = activePath === it.path;
              const badge = badges && badges[it.id];
              return (
                <button key={it.id} className={'sb-item ' + (active ? 'is-active' : '') + (!allowed ? ' is-disabled' : '')} onClick={() => allowed && onNav(it.path)} disabled={!allowed}>
                  <window.Icon name={it.icon} size={15} className="sb-item-ico" />
                  <span className="sb-item-label">{it.label}</span>
                  {badge && <span className={'sb-item-count ' + (badge.tone || '')}>{badge.value}</span>}
                </button>
              );
            })}
          </React.Fragment>
        ))}
      </nav>

      <div className="sb-footer">
        <div className="sb-footer-row">
          <window.Icon name="book-open" size={11} />
          <span>Docs</span>
          <span style={{ marginLeft: 'auto' }} className="sb-footer-ver">/docs/connector</span>
        </div>
        <div className="sb-footer-row">
          <window.Icon name="git-commit-horizontal" size={11} />
          <span className="sb-footer-ver">sha 8f4a2c9 · go1.22</span>
        </div>
      </div>
    </aside>
  );
}

/* ---------------- Tenant switcher popover -------------------------- */
function TenantSwitcher({ tenant, onSelect }) {
  const [open, setOpen] = _useState(false);
  const [q, setQ] = _useState('');
  const ref = _useRef(null);
  const bc = window.useBC();           // re-render cuando cambian los tenants (live)
  _useEffect(() => {
    if (!open) return;
    const fn = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', fn);
    return () => document.removeEventListener('mousedown', fn);
  }, [open]);
  const list = _useMemo(() => {
    const ql = q.toLowerCase();
    return [{ id: '*', name: 'Todos los tenants', uuid: 'global', status: 'active' }, ...bc.tenants].filter(t => !ql || t.name.toLowerCase().includes(ql) || (t.id || '').includes(ql));
  }, [q, bc.tenants]);
  return (
    <div style={{ position: 'relative' }} ref={ref}>
      <button className="tb-tenant" onClick={() => setOpen(o => !o)}>
        {tenant.id === '*'
          ? <span className="tb-tenant-ava" style={{ background: 'var(--grad-blaze)' }}>★</span>
          : <span className="tb-tenant-ava" style={{ background: TENANT_GRAD(tenant.id) }}>{tenant.name.split(' ').slice(0, 2).map(s => s[0]).join('')}</span>}
        <div className="tb-tenant-lbl">
          <span className="tb-tenant-name">{tenant.name}</span>
          <span className="tb-tenant-sub">{tenant.id === '*' ? 'global' : tenant.id}</span>
        </div>
        <window.Icon name="chevrons-up-down" size={11} className="tb-tenant-caret" />
      </button>
      {open && (
        <div className="popover" style={{ top: 38, left: 0, minWidth: 320 }}>
          <div style={{ padding: 6 }}>
            <div className="fb-search" style={{ height: 28 }}>
              <window.Icon name="search" size={12} style={{ color: 'var(--app-fg3)' }} />
              <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar tenant…" autoFocus />
            </div>
          </div>
          <div className="popover-section">Tenants ({list.length - 1})</div>
          <div style={{ maxHeight: 380, overflow: 'auto' }}>
            {list.map((t) => (
              <button key={t.id} className="popover-item" onClick={() => { onSelect(t); setOpen(false); }} style={{ background: 'none', border: 'none', width: '100%', textAlign: 'left' }}>
                {t.id === '*'
                  ? <span className="tb-tenant-ava" style={{ background: 'var(--grad-blaze)' }}>★</span>
                  : <span className="tb-tenant-ava" style={{ background: TENANT_GRAD(t.id) }}>{t.name.split(' ').slice(0, 2).map(s => s[0]).join('')}</span>}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--app-fg1)' }}>{t.name}</div>
                  <div className="mono" style={{ fontSize: 10.5, color: 'var(--app-fg3)' }}>{t.id === '*' ? '— mostrando todos —' : t.uuid.slice(0, 18) + '…'}</div>
                </div>
                {t.id !== '*' && <window.StatusBadge status={t.status} square />}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------------- User menu / role switcher ------------------------ */
function UserMenu({ role, onRoleChange, theme, onThemeToggle }) {
  const [open, setOpen] = _useState(false);
  const ref = _useRef(null);
  _useEffect(() => {
    if (!open) return;
    const fn = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', fn);
    return () => document.removeEventListener('mousedown', fn);
  }, [open]);
  return (
    <div style={{ position: 'relative' }} ref={ref}>
      <button className="tb-user" onClick={() => setOpen(o => !o)}>
        <span className="tb-user-ava">YR</span>
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.15, alignItems: 'flex-start' }}>
          <span className="tb-user-name">Yarisbel R.</span>
          <span className="tb-user-role">{ROLE_DEFS[role].label}</span>
        </div>
        <window.Icon name="chevron-down" size={11} style={{ color: 'var(--app-fg3)', marginLeft: 4 }} />
      </button>
      {open && (
        <div className="popover" style={{ top: 38, right: 0, minWidth: 260 }}>
          <div style={{ padding: '10px 12px 8px', borderBottom: '1px solid var(--app-divider)' }}>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <span className="tb-user-ava" style={{ width: 32, height: 32 }}>YR</span>
              <div>
                <div style={{ fontSize: 13, fontWeight: 700 }}>Yarisbel Rodríguez</div>
                <div style={{ fontSize: 11, color: 'var(--app-fg3)' }}>yarisbel@blaze.do</div>
              </div>
            </div>
          </div>
          <div className="popover-section">Cambiar rol (demo)</div>
          {Object.entries(ROLE_DEFS).map(([k, def]) => (
            <button key={k} className="popover-item" onClick={() => { onRoleChange(k); setOpen(false); }} style={{ background: 'none', border: 'none', width: '100%', textAlign: 'left' }}>
              <window.Icon name={k === role ? 'circle-dot' : 'circle'} size={13} style={{ color: k === role ? 'var(--blaze-orange)' : 'var(--app-fg3)' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600 }}>{def.label}</div>
                <div style={{ fontSize: 10.5, color: 'var(--app-fg3)' }}>{def.desc}</div>
              </div>
            </button>
          ))}
          <div className="popover-divider"></div>
          <button className="popover-item" onClick={() => { onThemeToggle(); setOpen(false); }} style={{ background: 'none', border: 'none', width: '100%', textAlign: 'left' }}>
            <window.Icon name={theme === 'dark' ? 'sun' : 'moon'} size={13} />
            <span style={{ flex: 1 }}>Tema {theme === 'dark' ? 'claro' : 'oscuro'}</span>
            <span className="kbd">⌘⇧L</span>
          </button>
          <button className="popover-item" style={{ background: 'none', border: 'none', width: '100%', textAlign: 'left' }}>
            <window.Icon name="settings" size={13} /> <span style={{ flex: 1 }}>Preferencias</span>
          </button>
          <button className="popover-item" style={{ background: 'none', border: 'none', width: '100%', textAlign: 'left' }}>
            <window.Icon name="key-round" size={13} /> <span style={{ flex: 1 }}>Mis API keys</span>
          </button>
          <div className="popover-divider"></div>
          <button className="popover-item" style={{ background: 'none', border: 'none', width: '100%', textAlign: 'left', color: 'var(--st-danger-fg)' }}>
            <window.Icon name="log-out" size={13} /> <span>Cerrar sesión</span>
          </button>
        </div>
      )}
    </div>
  );
}

/* ---------------- Realtime indicator ------------------------------- */
function RealtimeIndicator({ status, eventsPerSec }) {
  const tone = status === 'connected' ? '' : status === 'degraded' ? 'is-degraded' : 'is-down';
  const lbl = status === 'connected' ? 'live' : status === 'degraded' ? 'degraded' : 'down';
  return (
    <span className={'tb-realtime ' + tone} title={'SSE /events/stream — ' + status}>
      <span className="tb-realtime-dot"></span>
      <span style={{ fontWeight: 600 }}>{lbl}</span>
      <span className="tb-realtime-rate">{eventsPerSec.toFixed(1)}/s</span>
    </span>
  );
}

/* ---------------- Topbar ------------------------------------------- */
function Topbar({ tenant, onTenantChange, breadcrumb, role, onRoleChange, theme, onThemeToggle, realtime, onSidebarToggle, onOpenCmdK }) {
  return (
    <header className="app-topbar">
      <button className="tb-collapse" onClick={onSidebarToggle} title="Colapsar sidebar"><window.Icon name="panel-left" size={15} /></button>
      <div className="tb-breadcrumb">
        {breadcrumb.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="crumb-sep">/</span>}
            <span className={i === breadcrumb.length - 1 ? 'crumb-cur' : ''}>{c}</span>
          </React.Fragment>
        ))}
      </div>

      <div className="tb-search" onClick={onOpenCmdK} role="button" tabIndex={0}>
        <window.Icon name="search" size={12} />
        <input placeholder="Buscar tenant, mensaje, trace_id, log… (⌘K)" onFocus={onOpenCmdK} readOnly />
        <div className="tb-search-kbd">
          <span className="kbd">⌘</span>
          <span className="kbd">K</span>
        </div>
      </div>

      <div className="tb-right">
        <TenantSwitcher tenant={tenant} onSelect={onTenantChange} />
        <div className="tb-divider"></div>
        <window.ConnectionChip />
        <RealtimeIndicator status={realtime.status} eventsPerSec={realtime.rate} />
        <button className="tb-icon-btn has-badge" title="Alertas"><window.Icon name="bell" size={15} /></button>
        <button className="tb-icon-btn" title="Documentación"><window.Icon name="circle-help" size={15} /></button>
        <button className="tb-icon-btn" onClick={onThemeToggle} title="Cambiar tema"><window.Icon name={theme === 'dark' ? 'sun' : 'moon'} size={15} /></button>
        <div className="tb-divider"></div>
        <UserMenu role={role} onRoleChange={onRoleChange} theme={theme} onThemeToggle={onThemeToggle} />
      </div>
    </header>
  );
}

/* ---------------- Command palette (⌘K) ----------------------------- */
function CommandPalette({ open, onClose, onNav }) {
  const [q, setQ] = _useState('');
  _useEffect(() => { if (open) setQ(''); }, [open]);
  if (!open) return null;
  const items = [
    ...NAV_GROUPS.flatMap((g) => g.items.map(it => ({ type: 'Página', label: it.label, sub: g.label, ico: it.icon, action: () => onNav(it.path) }))),
    ...window.TENANTS.slice(0, 8).map((t) => ({ type: 'Tenant', label: t.name, sub: t.id + ' · ' + t.region, ico: 'building-2', action: () => onNav('/tenants/' + t.id) })),
    { type: 'Acción', label: 'Crear nuevo tenant', sub: 'tenants', ico: 'plus', action: () => onNav('/tenants?new=1') },
    { type: 'Acción', label: 'Emitir API key', sub: 'apikeys', ico: 'key-round', action: () => onNav('/apikeys?new=1') },
    { type: 'Acción', label: 'Ver mensajes fallidos', sub: 'messaging', ico: 'message-square-warning', action: () => onNav('/messaging?status=failed') }
  ];
  const ql = q.toLowerCase();
  const filtered = !ql ? items : items.filter(it => it.label.toLowerCase().includes(ql) || it.sub.toLowerCase().includes(ql));
  return (
    <div className="modal-mask" onClick={onClose} style={{ alignItems: 'flex-start', paddingTop: 80 }}>
      <div className="modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 560, padding: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '14px 16px', borderBottom: '1px solid var(--app-divider)' }}>
          <window.Icon name="search" size={14} style={{ color: 'var(--app-fg3)' }} />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar páginas, tenants, acciones, trace_ids…" autoFocus
            style={{ flex: 1, border: 'none', background: 'transparent', outline: 'none', color: 'var(--app-fg1)', fontSize: 14 }} />
          <span className="kbd">ESC</span>
        </div>
        <div style={{ maxHeight: 420, overflow: 'auto', padding: '6px 4px' }}>
          {filtered.length === 0 && <div className="empty"><div className="empty-title">Sin coincidencias</div><div className="empty-sub">Prueba con otro término o filtro.</div></div>}
          {filtered.map((it, i) => (
            <button key={i} onClick={() => { it.action(); onClose(); }} className="popover-item" style={{ width: '100%', background: 'none', border: 'none', textAlign: 'left', padding: '8px 12px', borderRadius: 6 }}>
              <window.Icon name={it.ico} size={14} style={{ color: 'var(--app-fg3)' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, color: 'var(--app-fg1)' }}>{it.label}</div>
                <div style={{ fontSize: 11, color: 'var(--app-fg3)' }}>{it.sub}</div>
              </div>
              <span style={{ fontSize: 10, color: 'var(--app-fg-faint)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{it.type}</span>
            </button>
          ))}
        </div>
        <div style={{ padding: '8px 14px', borderTop: '1px solid var(--app-divider)', display: 'flex', gap: 10, fontSize: 10.5, color: 'var(--app-fg3)' }}>
          <span><span className="kbd">↑↓</span> navegar</span>
          <span><span className="kbd">↵</span> abrir</span>
          <span style={{ marginLeft: 'auto' }}>{filtered.length} resultados</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, Topbar, CommandPalette, NAV_GROUPS, ROLE_DEFS, hasPerm, TENANT_GRAD });
