// Reusable RodaiClientes components
const { useState, useEffect, useRef, useMemo, useCallback } = React;

function Btn({ children, kind = 'ghost', size = 'md', icon, iconRight, onClick, disabled, title, type = 'button' }) {
  const cls = ['btn', `btn-${kind}`, size === 'sm' ? 'btn-sm' : ''].join(' ');
  return (
    <button type={type} className={cls} onClick={onClick} disabled={disabled} title={title}>
      {icon ? <Icon name={icon} size={size === 'sm' ? 12 : 14} /> : null}
      {children}
      {iconRight ? <Icon name={iconRight} size={size === 'sm' ? 12 : 14} /> : null}
    </button>
  );
}

function IconBtn({ name, onClick, title, size = 'md', kind = 'ghost' }) {
  const cls = ['btn', `btn-${kind}`, 'btn-icon', size === 'sm' ? 'btn-sm' : ''].join(' ');
  return (
    <button type="button" className={cls} onClick={onClick} title={title} aria-label={title}>
      <Icon name={name} size={size === 'sm' ? 12 : 14} />
    </button>
  );
}

function Chip({ children, kind = 'default', icon }) {
  const cls = ['chip', kind !== 'default' ? `chip-${kind}` : ''].join(' ');
  return (
    <span className={cls}>
      {icon ? <Icon name={icon} size={10} /> : null}
      {children}
    </span>
  );
}

function StatusDot({ kind = 'mut', pulse = false }) {
  return <span className={`dot dot-${kind} ${pulse ? 'pulse-dot' : ''}`} />;
}

// Mini bars showing 4 servers' sync status for a client
function MiniBars({ status }) {
  // status is array of 0=ok 1=syncing 2=diverged 3=missing
  const cls = (s) => {
    if (s === 0) return 's-ok';
    if (s === 1) return 's-syncing';
    if (s === 2) return 's-diverged';
    if (s === 3) return 's-missing';
    return 's-unknown';
  };
  return (
    <span className="minibars" aria-label="status por servidor">
      {status.map((s, i) => <i key={i} className={cls(s)} />)}
    </span>
  );
}

function Input({ value, onChange, placeholder, icon, kbd, autoFocus, onKeyDown, type='text', style={}, maxLength }) {
  return (
    <label className="input" style={style}>
      {icon ? <Icon name={icon} size={13} /> : null}
      <input
        type={type}
        value={value || ''}
        onChange={(e) => onChange?.(e.target.value)}
        placeholder={placeholder}
        autoFocus={autoFocus}
        onKeyDown={onKeyDown}
        maxLength={maxLength}
      />
      {kbd ? <span className="kbd">{kbd}</span> : null}
    </label>
  );
}

function Segmented({ value, onChange, options }) {
  return (
    <div className="seg" role="tablist">
      {options.map(o => (
        <button
          key={o.value}
          className={value === o.value ? 'on' : ''}
          onClick={() => onChange(o.value)}
          role="tab"
          aria-selected={value === o.value}
        >
          {o.label}
        </button>
      ))}
    </div>
  );
}

function Sidebar({ view, setView, opsBadge }) {
  const items = [
    { id: 'dashboard', label: 'Dashboard', icon: 'dashboard', kbd: 'g d' },
    { id: 'clientes',  label: 'Clientes',  icon: 'users',     kbd: 'g c' },
    { id: 'times',     label: 'Times',     icon: 'tree',      kbd: 'g t' },
    { id: 'servidores',label: 'Servidores',icon: 'server',    kbd: 'g s' },
    { id: 'sync',      label: 'Sincronização', icon: 'refresh', kbd: 'g y' },
    { id: 'historico', label: 'Histórico', icon: 'history',   kbd: 'g h' },
  ];
  return (
    <aside className="sidebar" style={{
      width: 220, flex: '0 0 220px',
      borderRight: '1px solid var(--line)',
      background: 'var(--bg-1)',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* brand */}
      <div className="row sidebar-brand" style={{ padding: '12px 12px 10px', gap: 8 }}>
        <BrandMark size={20} />
        <div className="col" style={{ lineHeight: 1.1, gap: 1 }}>
          <span style={{ fontWeight: 600, fontSize: 13.5 }}>RodaiClientes</span>
          <span className="dim" style={{ fontSize: 10.5 }}>RodaiLAB · v0.5.0</span>
        </div>
      </div>

      <div className="sidebar-search" style={{ padding: '0 8px 8px' }}>
        <button
          className="row"
          onClick={() => window.dispatchEvent(new CustomEvent('rc-cmdk'))}
          style={{
            width: '100%', height: 28, padding: '0 8px',
            background: 'var(--bg-2)', color: 'var(--text-muted)',
            border: '1px solid var(--line)', borderRadius: 6,
            display: 'flex', alignItems: 'center', gap: 8,
            fontSize: 12, cursor: 'pointer'
          }}
        >
          <Icon name="search" size={13} />
          <span style={{ flex: 1, textAlign: 'left' }}>Pular para…</span>
          <span className="kbd">⌘K</span>
        </button>
      </div>

      <nav className="sidebar-nav" style={{ padding: '0 8px', display: 'flex', flexDirection: 'column', gap: 1 }}>
        {items.map(it => (
          <div
            key={it.id}
            className={`nav-item ${view === it.id ? 'active' : ''}`}
            onClick={() => setView(it.id)}
          >
            <Icon name={it.icon} size={14} className="icon" />
            <span style={{ flex: 1 }}>{it.label}</span>
            {it.id === 'sync' ? <span className="dot dot-warn" /> : null}
            {it.id === 'historico' && opsBadge ? <span className="chip chip-acc" style={{ height: 16, fontSize: 10 }}>{opsBadge}</span> : null}
          </div>
        ))}
      </nav>

      {window.RC?.clients && (
        <div className="sidebar-quick" style={{ marginTop: 16, padding: '0 12px' }}>
          <div className="uc" style={{ marginBottom: 6 }}>Acesso rápido</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
            {(() => {
              const active = window.RC.clients.filter(c => !c.archived);
              const divergentes = window.RC.syncDiff.length;
              const emTransicao = active.filter(c => c.running).length;
              const sincronizados = active.filter(c => c.status && c.status.every(s => s === 0)).length;
              return (
                <>
                  <div className="nav-item" onClick={() => setView('sync')} style={{ height: 24 }}>
                    <span className="dot dot-warn" /><span>Divergentes</span>
                    {divergentes > 0 && <span className="chip chip-warn" style={{ marginLeft: 'auto', height: 16, fontSize: 10 }}>{divergentes}</span>}
                  </div>
                  <div className="nav-item" onClick={() => setView('clientes')} style={{ height: 24 }}>
                    <span className="dot dot-acc pulse-dot" /><span>Em transição</span>
                    {emTransicao > 0 && <span className="chip chip-acc" style={{ marginLeft: 'auto', height: 16, fontSize: 10 }}>{emTransicao}</span>}
                  </div>
                  <div className="nav-item" onClick={() => setView('clientes')} style={{ height: 24 }}>
                    <span className="dot dot-ok" /><span>Sincronizados</span>
                    <span className="chip" style={{ marginLeft: 'auto', height: 16, fontSize: 10 }}>{sincronizados}</span>
                  </div>
                </>
              );
            })()}
          </div>
        </div>
      )}

      <div className="sidebar-spacer" style={{ flex: 1 }} />

      {/* footer */}
      <div
        className="sidebar-footer"
        style={{ padding: '8px 12px', borderTop: '1px solid var(--line)', cursor: 'pointer' }}
        onClick={() => window.postMessage({ type: '__activate_edit_mode' }, '*')}
        title="Configurações e sessão"
      >
        <div className="row" style={{ gap: 8 }}>
          <div style={{
            width: 24, height: 24, borderRadius: 4,
            background: 'var(--accent-soft)',
            display: 'grid', placeItems: 'center',
            fontSize: 10, fontWeight: 600, color: 'var(--accent)',
          }}>AD</div>
          <div className="col" style={{ lineHeight: 1.15, fontSize: 11.5 }}>
            <span>admin</span>
            <span className="dim" style={{ fontSize: 10 }}>operador principal</span>
          </div>
          <div style={{ marginLeft: 'auto' }}>
            <Icon name="cog" size={14} style={{ color: 'var(--text-dim)' }} />
          </div>
        </div>
      </div>
    </aside>
  );
}

function Topbar({ title, crumbs, actions, info }) {
  return (
    <header className="topbar" style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 16px',
      borderBottom: '1px solid var(--line)',
      background: 'var(--bg)',
      minHeight: 48,
    }}>
      <div className="col" style={{ gap: 2, minWidth: 0 }}>
        {crumbs ? (
          <div className="crumbs">
            {crumbs.map((c, i) => (
              <React.Fragment key={i}>
                {i > 0 ? <span className="sep">/</span> : null}
                {i === crumbs.length - 1
                  ? <span className="now">{c}</span>
                  : <a>{c}</a>}
              </React.Fragment>
            ))}
          </div>
        ) : null}
        <div className="row" style={{ gap: 8 }}>
          <h1 style={{ margin: 0, fontSize: 17, fontWeight: 600, letterSpacing: '-0.01em' }}>{title}</h1>
          {info}
        </div>
      </div>
      <div style={{ flex: 1 }} />
      <div className="topbar-actions">{actions}</div>
    </header>
  );
}

// Live operation banner for top of any screen when an op is running
function LiveOpBanner({ op, onOpen }) {
  if (!op) return null;
  const total = op.servers.length;
  const done = op.servers.filter(s => s.state === 'done').length;
  const failed = op.servers.filter(s => s.state === 'fail').length;
  const running = op.servers.filter(s => s.state === 'running').length;
  return (
    <div className="row" style={{
      gap: 12, padding: '8px 12px',
      background: 'var(--accent-soft)',
      borderBottom: '1px solid var(--accent-line)',
      fontSize: 12,
    }}>
      <Icon name="bolt" size={13} style={{ color: 'var(--accent)' }} />
      <span>
        <strong style={{ fontWeight: 600 }}>{op.kind}</strong>{' '}
        <span className="muted">·</span>{' '}
        <span className="font-mono">{op.target}</span>{' '}
        <span className="muted">em andamento — {done}/{total} servidores prontos · {running} rodando · {failed > 0 ? <span style={{ color: 'var(--err)' }}>{failed} falhou</span> : '0 falhou'}</span>
      </span>
      <div style={{ flex: 1 }} />
      <Btn kind="secondary" size="sm" iconRight="arrowR" onClick={onOpen}>Ver progresso</Btn>
    </div>
  );
}

// Floating toast manager
function Toast({ toast, onClose }) {
  if (!toast) return null;
  return (
    <div className="toast" role="status">
      <Icon name={toast.kind === 'err' ? 'alert' : 'check'} size={14}
            style={{ color: toast.kind === 'err' ? 'var(--err)' : 'var(--ok)', marginTop: 2 }} />
      <div className="col" style={{ flex: 1, gap: 2 }}>
        <span style={{ fontWeight: 500 }}>{toast.title}</span>
        {toast.body ? <span className="muted" style={{ fontSize: 12 }}>{toast.body}</span> : null}
      </div>
      <IconBtn name="x" size="sm" onClick={onClose} title="Fechar" />
    </div>
  );
}

function ConfirmModal({ open, title, body, danger, confirmLabel = 'Confirmar', onConfirm, onCancel, children }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onCancel?.(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onCancel]);
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onCancel}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line)' }}>
          <div className="row" style={{ gap: 8 }}>
            {danger ? <Icon name="alert" size={15} style={{ color: 'var(--err)' }} /> : null}
            <strong style={{ fontSize: 14 }}>{title}</strong>
          </div>
          {body ? <p className="muted" style={{ margin: '6px 0 0', fontSize: 12.5 }}>{body}</p> : null}
        </div>
        {children ? <div style={{ padding: '12px 16px' }}>{children}</div> : null}
        <div style={{ padding: '10px 12px', borderTop: '1px solid var(--line)', display: 'flex', gap: 8, justifyContent: 'flex-end', background: 'var(--bg-2)' }}>
          <Btn kind="secondary" size="sm" onClick={onCancel}>Cancelar</Btn>
          <Btn kind={danger ? 'danger' : 'primary'} size="sm" onClick={onConfirm}>{confirmLabel}</Btn>
        </div>
      </div>
    </div>
  );
}

function CmdK({ open, onClose, gotoView }) {
  const [q, setQ] = useState('');
  const inputRef = useRef(null);
  useEffect(() => {
    if (open) {
      setQ('');
      setTimeout(() => inputRef.current?.focus(), 0);
    }
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (open) window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  const items = useMemo(() => {
    const navItems = [
      { id: 'go-dashboard', label: 'Ir para Dashboard',     icon: 'dashboard', section: 'Navegação', run: () => gotoView('dashboard') },
      { id: 'go-clientes',  label: 'Ir para Clientes',      icon: 'users',     section: 'Navegação', run: () => gotoView('clientes') },
      { id: 'go-times',     label: 'Ir para Times',         icon: 'tree',      section: 'Navegação', run: () => gotoView('times') },
      { id: 'go-servidores',label: 'Ir para Servidores',    icon: 'server',    section: 'Navegação', run: () => gotoView('servidores') },
      { id: 'go-sync',      label: 'Ir para Sincronização', icon: 'refresh',   section: 'Navegação', run: () => gotoView('sync') },
    ];
    const actions = [
      { id: 'a-new',  label: 'Criar cliente novo',           icon: 'plus',    section: 'Ações',  shortcut: 'N',  run: () => gotoView('criar') },
      { id: 'a-sync', label: 'Rodar verificação completa',   icon: 'refresh', section: 'Ações',  run: () => gotoView('sync') },
      { id: 'a-op',   label: 'Ver operação em andamento',    icon: 'bolt',    section: 'Ações',  run: () => gotoView('operacao') },
    ];
    const clientItems = window.RC.clients.slice(0, 12).map(c => ({
      id: 'c-' + c.id,
      label: c.name,
      sub: (window.RC.teamById(c.team)?.name || String(c.team)).toUpperCase(),
      icon: 'user',
      section: 'Clientes',
      run: () => gotoView('clientes', { selectId: c.id }),
    }));
    const all = [...navItems, ...actions, ...clientItems];
    if (!q) return all;
    const ql = q.toLowerCase();
    return all.filter(it => it.label.toLowerCase().includes(ql) || (it.sub || '').toLowerCase().includes(ql));
  }, [q, gotoView]);

  const [active, setActive] = useState(0);
  useEffect(() => { setActive(0); }, [q, open]);

  if (!open) return null;
  const onKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(items.length - 1, a + 1)); }
    if (e.key === 'ArrowUp')   { e.preventDefault(); setActive(a => Math.max(0, a - 1)); }
    if (e.key === 'Enter')     { e.preventDefault(); items[active]?.run(); onClose(); }
  };

  // group by section
  const groups = {};
  items.forEach((it, i) => { (groups[it.section] = groups[it.section] || []).push({ ...it, _i: i }); });

  return (
    <div className="cmdk-backdrop" onClick={onClose}>
      <div
        className="card"
        style={{ width: 560, maxWidth: '92vw', overflow: 'hidden', boxShadow: 'var(--shadow-pop)' }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="row" style={{ padding: '10px 12px', borderBottom: '1px solid var(--line)', gap: 8 }}>
          <Icon name="search" size={14} className="muted" />
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onKeyDown={onKey}
            placeholder="Buscar comandos, clientes, times…"
            style={{ all: 'unset', flex: 1, fontSize: 14, color: 'var(--text)' }}
          />
          <span className="kbd">esc</span>
        </div>
        <div style={{ maxHeight: 380, overflow: 'auto', padding: '4px 0' }}>
          {Object.keys(groups).length === 0 ? (
            <div className="muted" style={{ padding: 16, textAlign: 'center', fontSize: 12 }}>Sem resultados.</div>
          ) : Object.entries(groups).map(([sec, list]) => (
            <div key={sec}>
              <div className="uc" style={{ padding: '8px 12px 4px' }}>{sec}</div>
              {list.map(it => (
                <div
                  key={it.id}
                  onMouseEnter={() => setActive(it._i)}
                  onClick={() => { it.run(); onClose(); }}
                  className="row"
                  style={{
                    padding: '6px 12px', gap: 10, cursor: 'pointer', height: 30,
                    background: active === it._i ? 'var(--bg-active)' : 'transparent',
                  }}
                >
                  <Icon name={it.icon} size={13} className="muted" />
                  <span style={{ flex: 1, fontSize: 13 }}>{it.label}</span>
                  {it.sub ? <span className="dim font-mono" style={{ fontSize: 11 }}>{it.sub}</span> : null}
                  {it.shortcut ? <span className="kbd">{it.shortcut}</span> : null}
                </div>
              ))}
            </div>
          ))}
        </div>
        <div className="row" style={{ padding: '6px 12px', borderTop: '1px solid var(--line)', background: 'var(--bg-2)', fontSize: 11, gap: 12, color: 'var(--text-dim)' }}>
          <span><span className="kbd">↑</span> <span className="kbd">↓</span> navegar</span>
          <span><span className="kbd">↵</span> selecionar</span>
          <span><span className="kbd">esc</span> fechar</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Btn, IconBtn, Chip, StatusDot, MiniBars, Input, Segmented, Sidebar, Topbar, LiveOpBanner, Toast, ConfirmModal, CmdK });
