/* New Sidebar — perfis › seções › ferramentas */
const { useState: useSS, useEffect: useSE, useMemo: useSM } = React;

function ToolButton({ t, active, onChange }) {
  const isSoon = !!t.comingSoon;
  const isActive = active === `tool:${t.id}`;
  const cls = `side-tool${isActive ? ' is-active' : ''}${isSoon ? ' is-coming-soon' : ''}`;
  const handle = () => {
    if (isSoon) {
      if (window.CCAlert) window.CCAlert({ title: 'Em breve', message: 'Esta ferramenta ainda está em desenvolvimento.' });
      return;
    }
    onChange(`tool:${t.id}`);
  };
  return (
    <button className={cls} onClick={handle}
            style={isSoon ? { opacity: 0.55, cursor: 'not-allowed' } : undefined}>
      <div className={`side-tool-ic kind-${t.kind || 'safe'}`}><Icon name={t.icon} size={11} /></div>
      <span className="side-tool-label">{t.title}</span>
      {isSoon && (
        <span className="mono" style={{ fontSize: 8.5, color: 'rgba(255,255,255,0.45)', letterSpacing: '0.22em' }}>
          EM BREVE
        </span>
      )}
    </button>
  );
}

function Sidebar({ active, onChange, identity }) {
  const isAdmin = identity?.ticketRole === 'administrator';
  const isDev = !!identity?.isSuperAdmin;
  const tools = window.TOOLS.filter(t => !t.devOnly || isDev);
  const sections = window.SECTIONS;
  // Filter roles based on access. Liderança fica oculta — possivelmente vira app próprio.
  const roles = window.ROLES.filter(r => {
    if (r.id === 'lideranca') return false;
    if (r.id === 'gestor') return isAdmin;
    return true;
  });
  const isRoleLocked = () => false;

  // Determine which role/section is currently selected via tool
  const activeRole = useSM(() => {
    if (active.startsWith('tool:')) {
      const t = tools.find(x => x.id === active.slice(5));
      return t?.role;
    }
    return null;
  }, [active]);

  const activeSection = useSM(() => {
    if (active.startsWith('tool:')) {
      const t = tools.find(x => x.id === active.slice(5));
      return t ? `${t.role}:${t.section}` : null;
    }
    return null;
  }, [active]);

  // Persist expansion: which roles/sections are open. Default open = perfil ativo.
  const [openRoles, setOpenRoles] = useSS(() => {
    const init = {};
    roles.forEach(r => { init[r.id] = false; });
    return init;
  });
  const [openSections, setOpenSections] = useSS({});

  // Auto-open active role/section
  useSE(() => {
    if (activeRole) setOpenRoles(o => ({ ...o, [activeRole]: true }));
    if (activeSection) setOpenSections(o => ({ ...o, [activeSection]: true }));
  }, [activeRole, activeSection]);

  return (
    <aside className="sidebar-shell rise">
      <div className="sidebar-eyebrow mono">/ NAVEGAÇÃO</div>

      <div className="sidebar-scroll">
      <button className={`side-tool ${active === 'home' ? 'is-active' : ''}`}
              onClick={() => onChange('home')}>
        <div className="side-tool-ic kind-safe"><Icon name="layers" size={12} /></div>
        <span className="side-tool-label">Início</span>
        <span className="badge mono" style={{ fontSize: 9, letterSpacing: '0.18em', color: 'rgba(255,255,255,0.4)' }}>{tools.length}</span>
      </button>

      {(() => {
        const gestorTools = tools.filter(t => t.role === 'gestor' && !t.devOnly);
        const gestorSecs = (sections['gestor'] ?? []).filter(s => s.id !== 'tarefas');
        return gestorSecs.map(s => {
          const secKey = `gestor:${s.id}`;
          const secOpen = openSections[secKey] !== false;
          const secTools = gestorTools.filter(t => t.section === s.id);
          if (secTools.length === 0) return null;
          return (
            <div key={s.id} className="side-section">
              <button className="side-section-head"
                      onClick={() => setOpenSections(o => ({ ...o, [secKey]: !secOpen }))}>
                <span className="side-section-bullet">{secOpen ? '▾' : '▸'}</span>
                <span style={{ flex: 1 }}>{s.label}</span>
                <span className="badge mono" style={{ fontSize: 9, letterSpacing: '0.18em', color: 'rgba(255,255,255,0.35)' }}>{secTools.length}</span>
              </button>
              {secOpen && (
                <div className="side-section-body">
                  {secTools.map(t => <ToolButton key={t.id} t={t} active={active} onChange={onChange} />)}
                </div>
              )}
            </div>
          );
        });
      })()}

      {isDev && (() => {
        const devTools = tools.filter(t => t.devOnly);
        if (devTools.length === 0) return null;
        const isDevOpen = openRoles['tasksdev'];
        return (
          <div className="side-role">
            <button className="side-role-head" onClick={() => setOpenRoles(o => ({ ...o, tasksdev: !o.tasksdev }))}>
              <span style={{ display: 'inline-flex', width: 14, color: 'var(--warning)' }}><Icon name="terminal" size={13} /></span>
              <span style={{ flex: 1 }}>tasks.dev</span>
              <span className="badge">{devTools.length}</span>
              <span style={{ color: 'rgba(255,255,255,0.35)', transform: isDevOpen ? 'rotate(90deg)' : 'rotate(0deg)', transition: 'transform 180ms ease', fontSize: 11 }}>›</span>
            </button>
            {isDevOpen && (
              <div className="side-role-body" style={{ marginLeft: 8, paddingLeft: 16 }}>
                {devTools.map(t => <ToolButton key={t.id} t={t} active={active} onChange={onChange} />)}
              </div>
            )}
          </div>
        );
      })()}

      </div>{/* end sidebar-scroll */}

      <div className="sidebar-fixed-bottom">
      <div className="sidebar-divider" />

      {/* Special: Time Tech & IA (expandable section) */}
      {(() => {
        const r = roles.find(x => x.special);
        if (!r) return null;
        const ticketTools = tools.filter(t => t.role === 'tickets');
        const ticketSecs = sections['tickets'] ?? [];
        const isOpen = openRoles['tickets'];
        const active2 = active.startsWith('tool:tk-');
        return (
          <div>
            <button className={`side-ticket ${active2 ? 'is-active' : ''}`}
                    onClick={() => setOpenRoles(o => ({ ...o, tickets: !o.tickets }))}>
              <div className="side-ticket-ic"><Icon name={r.icon} size={14} /></div>
              <div className="side-ticket-text">
                <div className="side-ticket-title">Time Tech &amp; IA</div>
                <div className="side-ticket-sub mono">SUPORTE</div>
              </div>
              <span style={{
                color: 'rgba(255,255,255,0.35)',
                transform: isOpen ? 'rotate(90deg)' : 'rotate(0deg)',
                transition: 'transform 180ms ease',
                fontSize: 11,
              }}>›</span>
            </button>
            <div className={`side-ticket-expanded ${isOpen ? 'is-open' : ''}`}>
              {ticketSecs.length <= 1 ? (
                ticketTools.map(t => <ToolButton key={t.id} t={t} active={active} onChange={onChange} />)
                ) : (
                  ticketSecs.map(s => {
                    const secKey = `tickets:${s.id}`;
                    const secOpen = openSections[secKey] === true;
                    const secTools = ticketTools.filter(t => t.section === s.id);
                    return (
                      <div key={s.id} className="side-section">
                        <button className="side-section-head"
                                onClick={() => setOpenSections(o => ({ ...o, [secKey]: !secOpen }))}>
                          <span className="side-section-bullet">{secOpen ? '▾' : '▸'}</span>
                          <span style={{ flex: 1 }}>{s.label}</span>
                          <span className="badge mono" style={{ fontSize: 9, letterSpacing: '0.18em', color: 'rgba(255,255,255,0.35)' }}>{secTools.length}</span>
                        </button>
                        {secOpen && (
                          <div className="side-section-body">
                            {secTools.map(t => <ToolButton key={t.id} t={t} active={active} onChange={onChange} />)}
                          </div>
                        )}
                      </div>
                    );
                  })
                )}
              </div>
          </div>
        );
      })()}

      <div className="sidebar-divider" />

      {/* Auditoria — só super admin (dev). Cobre o antigo Histórico + Auditoria juntos. */}
      {identity?.isSuperAdmin && (
        <button className={`side-tool ${active === 'auditoria' ? 'is-active' : ''}`}
                onClick={() => onChange('auditoria')}>
          <div className="side-tool-ic"><Icon name="fileText" size={11} /></div>
          <span className="side-tool-label">Auditoria</span>
        </button>
      )}
      </div>{/* end sidebar-fixed-bottom */}

    </aside>
  );
}

window.Sidebar = Sidebar;
