// Sidebar with grouped navigation.
// minRole opcional em cada item/sub controla visibilidade por role do user
// (lido de Auth.userRole, comparado via Auth.userCan()). Items sem minRole
// ficam visíveis pra todos. Default da hierarquia: viewer < editor < admin < owner.
const NAV_GROUPS = [
  {
    label: "Visão geral",
    items: [
      { key: "dashboard", icon: "fa-chart-line", label: "Dashboard" },
    ],
  },
  {
    label: "Chatbot",
    items: [
      { key: "chatbot", icon: "fa-robot", label: "Configuração", minRole: "editor", subs: [
        { key: "chatbot:persona", label: "Persona & Voz", minRole: "admin" },
        { key: "chatbot:chat", label: "Aparência do widget", minRole: "admin" },
        { key: "chatbot:prompt", label: "System prompt", minRole: "admin" },
        { key: "chatbot:handoff", label: "Atendimento humano", minRole: "admin" },
      ]},
    ],
  },
  {
    label: "Conhecimento",
    items: [
      { key: "knowledge", icon: "fa-brain", label: "Base de conhecimento", minRole: "editor", subs: [
        { key: "knowledge:context", label: "Contexto direto", minRole: "editor" },
        { key: "knowledge:docs", label: "Documentos", minRole: "editor" },
        { key: "knowledge:faqs", label: "FAQs (IA)", minRole: "editor" },
        { key: "knowledge:files", label: "Arquivos (site/CMS)", minRole: "editor" },
        { key: "knowledge:pages", label: "Páginas do site", minRole: "editor" },
      ]},
    ],
  },
  {
    label: "Operação",
    items: [
      { key: "learning", icon: "fa-lightbulb", label: "Central de Inteligência", minRole: "editor" },
      { key: "search", icon: "fa-magnifying-glass", label: "Buscar na base", minRole: "editor" },
      { key: "history", icon: "fa-history", label: "Histórico" },
      { key: "system", icon: "fa-sliders-h", label: "Sistema", subs: [
        { key: "system:config",  label: "Geral",             minRole: "admin" },
        { key: "system:acessos", label: "Acessos" },
        { key: "system:smtp",    label: "SMTP",              minRole: "admin" },
        { key: "system:terms",   label: "Termos de IA",      minRole: "admin" },
        { key: "system:diag",    label: "Diagnóstico",       minRole: "admin" },
        { key: "system:api",     label: "API & Integração",  minRole: "admin" },
      ]},
    ],
  },
];

// Helper: checa se um item nav deve aparecer pro user atual.
function navItemVisible(it) {
  if (!it.minRole) return true;
  return (typeof Auth !== 'undefined' && Auth.userCan) ? Auth.userCan(it.minRole) : true;
}

function Sidebar({ route, onRoute, collapsed, onLogout, version, theme, branding }) {
  const baseRoute = route.split(":")[0];
  const subRoute = route;
  const logoSrc = theme === 'light' ? 'assets/unbox-light.png' : 'assets/unbox-dark.png';
  // Branding configurável (lido de /api/branding em app.jsx). Fallback pros
  // valores legados quando ainda não carregou ou /api/branding falhou.
  const brand = branding || { brand_name: 'SINTRACON-SP', brand_initial: 'S', brand_logo_path: '' };
  const brandLogoSrc = brand.brand_logo_path
    ? (brand.brand_logo_path.startsWith('http') || brand.brand_logo_path.startsWith('/')
        ? brand.brand_logo_path
        : '/' + brand.brand_logo_path)
    : null;

  // Inject live badge counts from Data
  const counts = {
    "knowledge:context": (Data.directContexts || []).length,
    "knowledge:files":   (Data.files || []).length,
    "knowledge:pages":   (Data.sitePages || []).length,
    "history":           (Data.stats && Data.stats.conversations) || (Data.recentLogs || []).length,
  };

  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <div className={"sidebar-brand-mark" + (brandLogoSrc ? " has-logo" : "")}>
          {brandLogoSrc
            ? <img src={brandLogoSrc} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain', borderRadius: 'inherit' }} />
            : (brand.brand_initial || 'S').charAt(0).toUpperCase()}
        </div>
        <div className="sidebar-brand-text">
          <span className="b1">{brand.brand_name || 'SINTRACON-SP'}</span>
          <span className="b2">admin</span>
        </div>
      </div>

      <div style={{ overflowY: "auto", flex: 1, marginRight: -8, paddingRight: 8 }}>
        {NAV_GROUPS.map((g) => {
          const visibleItems = g.items.filter(navItemVisible);
          if (visibleItems.length === 0) return null;
          return (
          <div key={g.label}>
            <div className="sidebar-section-label">{g.label}</div>
            <div className="nav-group">
              {visibleItems.map((it) => {
                const isActive = baseRoute === it.key;
                const badge = counts[it.key];
                const visibleSubs = it.subs ? it.subs.filter(navItemVisible) : null;
                return (
                  <React.Fragment key={it.key}>
                    <div
                      className={"nav-item" + (isActive ? " active" : "")}
                      onClick={() => {
                        const target = visibleSubs && visibleSubs.length ? visibleSubs[0].key : it.key;
                        onRoute(target);
                      }}
                    >
                      <i className={"fas " + it.icon}></i>
                      <span className="nav-label">{it.label}</span>
                      {badge != null && badge !== 0 && <span className="nav-badge">{badge}</span>}
                    </div>
                    {visibleSubs && visibleSubs.length > 0 && isActive && !collapsed && (
                      <div className="nav-sub">
                        {visibleSubs.map((s) => {
                          const sb = counts[s.key];
                          return (
                            <div
                              key={s.key}
                              className={"nav-item" + (subRoute === s.key ? " active" : "")}
                              onClick={() => onRoute(s.key)}
                            >
                              <span className="nav-label">{s.label}</span>
                              {sb != null && sb !== 0 && <span className="nav-badge">{sb}</span>}
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </React.Fragment>
                );
              })}
            </div>
          </div>
          );
        })}
      </div>

      <div className="sidebar-footer">
        <div className="sidebar-credit credit-stack">
          <a href="https://unboxbr.com.br" target="_blank" rel="noopener" className="unbox-brand" title={'Desenvolvido pela Unbox' + (version ? ' · ' + version : '')}>
            <img src={logoSrc} alt="Unbox" />
          </a>
          {version && <span className="sidebar-version">v{version}</span>}
        </div>
      </div>
    </aside>
  );
}

window.Sidebar = Sidebar;
window.NAV_GROUPS = NAV_GROUPS;
