/* global React, Icon */

const THEME_KEY = 'was-theme';
window.THEME_KEY = THEME_KEY;

window.Sidebar = function Sidebar({ page, setPage, open, onClose }) {
  const [pinned, setPinned] = React.useState(false);
  function togglePin() {
    setPinned(next => !next);
  }
  const data = window.MOCK || {};
  const counts = {
    agents: (data.agents || []).length,
    conversations: (data.conversations || []).length,
    tickets: (data.tickets || []).length,
    channels: (data.channels || []).length,
    tables: (data.tables || []).length,
    kb: (data.knowledge || []).length,
    tools: (data.tools || []).length,
    squads: (data.squads || []).length,
    attendants: (data.attendants || []).length,
    tags: (data.tags || []).length,
  };
  const setupPending = (data.agents || []).filter(agent => !agent.isPublished).length;
  const sections = [
    { label: 'Início', items: [
      { id: 'dashboard', label: 'Dashboard', icon: 'dashboard' },
      { id: 'ecosystem', label: 'Mapa do Ecossistema', icon: 'ecosystem' },
      { id: 'assistants', label: 'Assistentes de IA', icon: 'assistants' },
    ]},
    { label: 'Fundação', items: [
      { id: 'tables', label: 'Tabelas', icon: 'tables', count: counts.tables },
      { id: 'kb', label: 'Conhecimento', icon: 'kb', count: counts.kb },
    ]},
    { label: 'Agentes', items: [
      { id: 'agents', label: 'Agentes', icon: 'agents', count: counts.agents },
    ]},
    { label: 'Orquestração', items: [
      { id: 'squads', label: 'Squads', icon: 'squads', count: counts.squads },
      { id: 'tools', label: 'Ferramentas', icon: 'tools', count: counts.tools },
      { id: 'channels', label: 'Canais', icon: 'channels', count: counts.channels },
    ]},
    { label: 'Atendimento', items: [
      { id: 'tickets', label: 'Tickets', icon: 'tickets', count: counts.tickets },
      { id: 'conversations', label: 'Conversas', icon: 'conversations', count: counts.conversations },
      { id: 'team', label: 'Atendentes & Times', icon: 'team', count: counts.attendants },
      { id: 'tags', label: 'Tags', icon: 'tags', count: counts.tags },
      { id: 'logs', label: 'Logs', icon: 'logs' },
    ]},
  ];

  return (
    <>
      <div className={`sidebar-backdrop ${open ? 'open' : ''}`} onClick={onClose}/>
      <aside className={`sidebar ${open ? 'open' : ''} ${pinned ? 'pinned' : ''}`}>
        <div className="sb-brand">
          <img className="sb-brand-mark" src="/static/system-manager-logo.png" alt="System Manager"/>
          <div>
            <div className="sb-brand-name">System Manager AI Studio</div>
            <div className="sb-brand-tag">v0.4.2</div>
          </div>
          <button className={`sb-pin-btn ${pinned ? 'active' : ''}`} onClick={togglePin} title={pinned ? 'Desafixar menu' : 'Fixar menu'}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2">
              {pinned
                ? <path d="M18 6L6 18M6 6l12 12"/>
                : <><path d="M12 2L8 8H2l5 5-2 7 7-4 7 4-2-7 5-5h-6z"/></>}
            </svg>
          </button>
        </div>

        {setupPending > 0 && (
          <button className="sb-item setup-cta agent-only-nav" data-page="setup" data-tooltip="Setup dos bots" title="Setup dos bots" onClick={() => { setPage('agents'); onClose && onClose(); }}>
            <Icon name="agents" size={15}/>
            <span>Setup dos bots</span>
            <span className="pill pill-warn pill-sm" id="setup-pending-count">{setupPending}</span>
          </button>
        )}

        {sections.map((section, i) => (
          <React.Fragment key={i}>
            <div className="sb-section-label">{section.label}</div>
            <nav className="sb-nav">
              {section.items.map(item => (
                <button
                  key={item.id}
                  className={`sb-item ${page === item.id ? 'active' : ''}`}
                  data-tooltip={item.label}
                  title={item.label}
                  onClick={() => { setPage(item.id); onClose && onClose(); }}>
                  <Icon name={item.icon} size={15}/>
                  <span>{item.label}</span>
                  {item.count != null && <span className="count">{item.count}</span>}
                </button>
              ))}
            </nav>
          </React.Fragment>
        ))}

        <div className="sb-foot">
          <div className="row"><span>API FastAPI</span><span className="ok">online</span></div>
          <div className="row"><span>WhatsApp</span><span>{(data.instances || []).length} conexões</span></div>
          <div className="row"><span>Runs</span><span>{(data.runs || []).length}</span></div>
        </div>
      </aside>
    </>
  );
};

window.TopBar = function TopBar({ crumbs, onMenu, theme, toggleTheme, onNewAgent, loading, error, onSearch, onGuide, guideOpen }) {
  return (
    <header className="topbar">
      <button className="mobile-menu-btn" onClick={onMenu} aria-label="Abrir menu"><span></span></button>
      <div className="crumbs">
        {crumbs.map((crumb, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="sep">/</span>}
            <span className={i === crumbs.length - 1 ? 'here' : ''}>{crumb}</span>
          </React.Fragment>
        ))}
      </div>
      <div className="topbar-search">
        <Icon name="search" size={13}/>
        <input placeholder="Buscar agentes, conversas, tickets..." onKeyDown={onSearch}/>
        <span className="topbar-kbd">Ctrl K</span>
      </div>
      <div className="topbar-actions">
        {loading && <span className="sync-state">sincronizando</span>}
        {error && <span className="sync-state bad">offline</span>}
        <button className="theme-toggle" onClick={toggleTheme} aria-label="Alternar tema">
          <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={15}/>
        </button>
        <button className="tb-btn ghost" aria-label="Notificações" onClick={() => window.STUDIO?.toast?.('Sem notificações novas.')}>
          <Icon name="bell" size={14}/>
        </button>
        <button className={`tb-btn ghost guide-topbar-btn ${guideOpen ? 'active' : ''}`} onClick={onGuide} aria-label="Abrir Guia do Sistema">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2">
            <circle cx="12" cy="12" r="10"/>
            <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>
            <circle cx="12" cy="17" r=".5" fill="currentColor"/>
          </svg>
          Guia
        </button>
        <button className="tb-btn primary" onClick={onNewAgent}>
          <Icon name="plus" size={13}/> Novo bot de IA
        </button>
      </div>
    </header>
  );
};

window.Toast = function Toast({ message, type = '' }) {
  if (!message) return null;
  return <div className={`toast ${type === 'bad' ? 'bad' : ''}`}>{message}</div>;
};

window.Modal = function Modal({ open, title, children, onClose }) {
  if (!open) return null;
  return (
    <div className="modal-backdrop open" role="dialog" aria-modal="true">
      <div className="create-modal">
        <div className="create-head">
          <div className="create-title">{title}</div>
          <button className="tb-btn ghost" onClick={onClose}>Fechar</button>
        </div>
        {children}
      </div>
    </div>
  );
};

window.Drawer = function Drawer({ open, title, children, onClose }) {
  return (
    <div className={`drawer ${open ? 'open' : ''}`}>
      <div className="dh">
        <div className="dt">{title}</div>
        <button className="tb-btn ghost" onClick={onClose}>Fechar</button>
      </div>
      <div className="db">{children}</div>
    </div>
  );
};

window.Shell = function Shell({ page, setPage, menuOpen, setMenuOpen, children, topbarProps }) {
  return (
    <div className="shell">
      <Sidebar page={page === 'agent-profile' ? 'agents' : page} setPage={setPage} open={menuOpen} onClose={() => setMenuOpen(false)}/>
      <main className="main">
        <TopBar {...topbarProps} onMenu={() => setMenuOpen(true)}/>
        {children}
      </main>
    </div>
  );
};

window.WaShell = { Sidebar: window.Sidebar, Topbar: window.TopBar, TopBar: window.TopBar, Shell: window.Shell, Toast: window.Toast, Modal: window.Modal, Drawer: window.Drawer, THEME_KEY };
