// App Shell — dark mode v2 with purple-blue accents
const AppShell = ({ current, onNavigate, children, page }) => {
  // Full module tree for Automatiza (all waves registered; wave-1 screens are navigable, others show "em breve")
  const navGroups = [
    {
      id: 'dashboards', label: 'Dashboards',
      items: [
        { id: 'dashboard', icon: 'dashboard', label: 'Home' },
        { id: 'executivo', icon: 'trending-up', label: 'Executivo' },
        { id: 'kpis', icon: 'bar-chart', label: 'KPIs históricos' },
        { id: 'churn', icon: 'alert', label: 'Churn Monitor', counter: 3 },
        { id: 'relatorios', icon: 'file', label: 'Relatórios' },
      ]
    },
    {
      id: 'crm', label: 'Comercial',
      items: [
        { id: 'crm', icon: 'kanban', label: 'Pipeline', counter: 28 },
        { id: 'contatos', icon: 'users', label: 'Contatos', counter: 412 },
        { id: 'negocios', icon: 'briefcase', label: 'Negócios' },
        { id: 'prospeccao', icon: 'map', label: 'Prospecção Maps' },
        { id: 'orcamentos', icon: 'calc', label: 'Orçamentos' },
        { id: 'estimativas', icon: 'calc', label: 'Estimativas' },
        { id: 'propostas', icon: 'doc', label: 'Propostas' },
        { id: 'pedidos', icon: 'shopping', label: 'Pedidos' },
        { id: 'os', icon: 'wrench', label: 'Ordens de Serviço' },
      ]
    },
    {
      id: 'financeiro', label: 'Financeiro',
      items: [
        { id: 'fluxo', icon: 'trending-up', label: 'Fluxo de Caixa' },
        { id: 'lancamentos', icon: 'receipt', label: 'Lançamentos' },
        { id: 'bancos', icon: 'wallet', label: 'Contas Bancárias' },
        { id: 'conciliacao', icon: 'sync', label: 'Conciliação OFX' },
        { id: 'contratos', icon: 'doc', label: 'Contratos' },
        { id: 'assinaturas', icon: 'repeat', label: 'Assinaturas' },
        { id: 'faturas', icon: 'receipt', label: 'Faturas', counter: 16 },
        { id: 'despesas', icon: 'minus-circle', label: 'Despesas' },
        { id: 'dre', icon: 'bar-chart', label: 'DRE & Relatórios' },
      ]
    },
    {
      id: 'rh', label: 'RH & Folha CLT',
      items: [
        { id: 'funcionarios', icon: 'users', label: 'Funcionários', counter: 17 },
        { id: 'horarios', icon: 'clock', label: 'Horários' },
        { id: 'ponto', icon: 'check', label: 'Ponto Eletrônico' },
        { id: 'folha', icon: 'wallet', label: 'Folha CLT' },
        { id: 'ajustes', icon: 'edit', label: 'Ajustes Salariais' },
        { id: 'comissoes', icon: 'award', label: 'Comissões' },
        { id: 'ferias', icon: 'palm', label: 'Férias' },
        { id: 'licencas', icon: 'doc', label: 'Licenças' },
        { id: 'folgas-tipos', icon: 'tag', label: 'Tipos de Folga' },
        { id: 'alocacoes', icon: 'calendar', label: 'Alocações de Folga' },
        { id: 'rh-relatorios', icon: 'bar-chart', label: 'Relatórios RH' },
      ]
    },
    {
      id: 'marketing', label: 'Marketing',
      items: [
        { id: 'campanhas', icon: 'megaphone', label: 'Campanhas', counter: 4 },
        { id: 'criador', icon: 'sparkle', label: 'Criador' },
        { id: 'templates', icon: 'mail', label: 'Templates' },
        { id: 'listas', icon: 'users', label: 'Listas de envio' },
        { id: 'blacklist', icon: 'ban', label: 'Blacklist' },
        { id: 'ia-gen', icon: 'cpu', label: 'Gerador IA' },
        { id: 'scoring', icon: 'trending-up', label: 'Lead Scoring' },
        { id: 'mailing-rel', icon: 'bar-chart', label: 'Relatórios' },
      ]
    },
    {
      id: 'suporte', label: 'Suporte',
      items: [
        { id: 'tickets', icon: 'help', label: 'Tickets', counter: 12 },
        { id: 'kb-suporte', icon: 'book', label: 'Base de Conhecimento' },
      ]
    },
    {
      id: 'projetos', label: 'Projetos & Operacional',
      items: [
        { id: 'projetos', icon: 'folder', label: 'Projetos', counter: 6 },
        { id: 'calendario', icon: 'calendar', label: 'Calendário' },
        { id: 'arquivos', icon: 'file', label: 'Arquivos' },
        { id: 'documentos', icon: 'doc', label: 'Documentos' },
        { id: 'knowledge', icon: 'book', label: 'Knowledge' },
        { id: 'mensagens', icon: 'message', label: 'Mensagens', counter: 3 },
        { id: 'comunicados', icon: 'megaphone', label: 'Comunicados' },
        { id: 'notas', icon: 'edit', label: 'Notas pessoais' },
        { id: 'tarefas', icon: 'check', label: 'Tarefas pessoais' },
        { id: 'lembretes', icon: 'bell', label: 'Lembretes' },
        { id: 'whatsapp', icon: 'whatsapp', label: 'WhatsApp', counter: 8 },
      ]
    },
    {
      id: 'pdv', label: 'PDV Fiscal',
      items: [
        { id: 'terminal', icon: 'shopping', label: 'Terminal' },
        { id: 'produtos', icon: 'tag', label: 'Produtos' },
        { id: 'fiscais', icon: 'shield', label: 'Docs Fiscais' },
      ]
    },
    {
      id: 'admin', label: 'Admin',
      items: [
        { id: 'usuarios', icon: 'users', label: 'Usuários' },
        { id: 'gestao', icon: 'shield', label: 'Papéis & Permissões' },
        { id: 'config', icon: 'settings', label: 'Configurações' },
      ]
    },
  ];

  // Breadcrumb resolver
  const flat = navGroups.flatMap(g => g.items.map(i => ({ ...i, group: g.label })));
  const currentItem = flat.find(i => i.id === current) || { label: 'Dashboard', group: 'Home' };

  // Groups collapse state, persisted
  const [collapsed, setCollapsed] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('automatiza-nav-collapse') || '{}'); } catch { return {}; }
  });
  const toggleGroup = (id) => {
    const next = { ...collapsed, [id]: !collapsed[id] };
    setCollapsed(next);
    try { localStorage.setItem('automatiza-nav-collapse', JSON.stringify(next)); } catch {}
  };

  // Auto-expand the group that contains `current`
  const activeGroupId = navGroups.find(g => g.items.some(i => i.id === current))?.id;

  const handleClick = (id) => { onNavigate(id); };

  const [mobNav, setMobNav] = React.useState(false);
  const [isNarrow, setIsNarrow] = React.useState(() => typeof window !== 'undefined' && window.innerWidth <= 980);
  React.useEffect(() => {
    const onResize = () => setIsNarrow(window.innerWidth <= 980);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  return (
    <div className="fade-in shell-grid" style={{
      display: 'grid',
      gridTemplateColumns: isNarrow ? '1fr' : '260px 1fr',
      minHeight: '100vh', background: 'var(--bg-base)', color: 'var(--text-1)',
    }}>
      <style>{`
        @media (max-width: 980px) {
          .shell-grid { grid-template-columns: 1fr !important; }
          .shell-sidebar { display: none !important; }
          .shell-sidebar.mob-open { display: flex !important; position: fixed; inset: 0; z-index: 200; width: 280px; box-shadow: var(--shadow-lg); }
          .shell-mob-overlay { display: block !important; }
        }
        .shell-sidebar {
          background: linear-gradient(180deg, #0b0a1a 0%, #0a091c 100%);
          color: var(--text-2);
          padding: 18px 12px; display: flex; flex-direction: column; gap: 2px;
          position: sticky; top: 0; height: 100vh; overflow-y: auto;
          border-right: 1px solid var(--line-1);
        }
        .shell-brand-row {
          display: flex; align-items: center; gap: 10px;
          padding: 4px 10px; margin-bottom: 18px;
        }
        .shell-workspace {
          padding: 10px 12px; margin-bottom: 12px;
          background: rgba(139,92,246,.08);
          border-radius: 10px; border: 1px solid rgba(139,92,246,.18);
          display: flex; align-items: center; gap: 10px;
        }
        .shell-workspace-name { font-size: 12px; font-weight: 600; color: var(--text-0); }
        .shell-workspace-plan { font-size: 10.5px; color: #c4b5fd; text-transform: uppercase; letter-spacing: .06em; }
        .shell-nav-section {
          font-size: 10px; text-transform: uppercase; letter-spacing: .12em;
          color: var(--text-4); padding: 12px 12px 6px; font-weight: 600;
        }
        .shell-nav-item {
          display: flex; align-items: center; gap: 11px;
          padding: 9px 12px; border-radius: 8px; font-size: 13px; font-weight: 500;
          color: var(--text-2); transition: all .12s; cursor: pointer;
          width: 100%; text-align: left; background: none; border: none;
        }
        .shell-nav-item:hover { background: rgba(255,255,255,.04); color: var(--text-0); }
        .shell-nav-item.active {
          background: var(--brand-gradient); color: white;
          box-shadow: 0 6px 20px -6px rgba(99,102,241,.6), inset 0 1px 0 rgba(255,255,255,.15);
        }
        .shell-nav-item .counter {
          margin-left: auto; font-size: 10px; padding: 2px 7px; border-radius: 999px;
          background: rgba(255,255,255,.06); color: var(--text-2); font-weight: 600;
          border: 1px solid rgba(255,255,255,.08);
        }
        .shell-nav-item.active .counter { background: rgba(255,255,255,.2); color: white; border-color: rgba(255,255,255,.15); }
        .shell-user {
          margin-top: auto; display: flex; align-items: center; gap: 10px;
          padding: 10px; border-radius: 10px; background: rgba(255,255,255,.03);
          border: 1px solid var(--line-1);
        }
        .shell-user-name { color: var(--text-0); font-size: 13px; font-weight: 500; }
        .shell-user-role { font-size: 11px; color: var(--text-3); }

        .shell-main { display: flex; flex-direction: column; min-width: 0; }
        .shell-topbar {
          background: rgba(10,9,20,.85); backdrop-filter: blur(20px);
          border-bottom: 1px solid var(--line-1);
          padding: 14px 28px; display: flex; align-items: center; gap: 18px;
          position: sticky; top: 0; z-index: 30;
        }
        @media (max-width: 640px) { .shell-topbar { padding: 12px 16px; gap: 10px; } }
        .shell-breadcrumb { display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--text-3); }
        .shell-breadcrumb b { color: var(--text-0); font-weight: 600; }
        .shell-search {
          flex: 1; max-width: 440px; position: relative;
        }
        .shell-search input {
          width: 100%; padding: 10px 14px 10px 40px; border-radius: 10px;
          border: 1px solid var(--line-2); background: var(--bg-2);
          font-size: 13px; color: var(--text-0); transition: all .15s;
        }
        .shell-search input:focus { outline: none; border-color: rgba(139,92,246,.5); box-shadow: 0 0 0 3px rgba(139,92,246,.15); }
        .shell-search input::placeholder { color: var(--text-4); }
        .shell-search svg { position: absolute; left: 14px; top: 50%; transform: translateY(-50%); color: var(--text-3); }
        .shell-search kbd {
          position: absolute; right: 10px; top: 50%; transform: translateY(-50%);
          background: var(--bg-3); border: 1px solid var(--line-2); border-radius: 5px;
          padding: 2px 6px; font-size: 10px; color: var(--text-3); font-family: inherit;
        }
        .shell-topbar-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
        .shell-top-btn {
          width: 38px; height: 38px; border-radius: 10px;
          background: var(--bg-2); border: 1px solid var(--line-2);
          display: grid; place-items: center; position: relative;
          color: var(--text-2); transition: all .12s;
        }
        .shell-top-btn:hover { background: var(--bg-3); border-color: var(--line-3); color: var(--text-0); }
        .shell-top-btn .badge {
          position: absolute; top: 5px; right: 5px; width: 8px; height: 8px; border-radius: 50%;
          background: #ef4444; border: 2px solid var(--bg-2);
        }
        .shell-body { flex: 1; overflow-y: auto; background: var(--bg-base); position: relative; }
        .shell-mob-overlay {
          display: none;
          position: fixed; inset: 0; background: rgba(0,0,0,.6);
          z-index: 150; backdrop-filter: blur(4px);
        }
        .shell-mob-burger {
          display: none;
          width: 38px; height: 38px; border-radius: 10px;
          background: var(--bg-2); border: 1px solid var(--line-2); color: var(--text-1);
          place-items: center;
        }
        @media (max-width: 980px) { .shell-mob-burger { display: grid; } }
      `}</style>

      {mobNav && <div className="shell-mob-overlay" onClick={() => setMobNav(false)}/>}

      <aside className={`shell-sidebar ${mobNav ? 'mob-open' : ''}`}>
        <div className="shell-brand-row">
          <BrandMark size={30} textSize={17}/>
        </div>
        <div className="shell-workspace">
          <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--brand-gradient)', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700, color: 'white' }}>PS</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="shell-workspace-name">Padaria São João</div>
            <div className="shell-workspace-plan">Profissional</div>
          </div>
          <Icon name="chevronDown" size={14} color="var(--text-3)"/>
        </div>

        {navGroups.map(g => {
          const isCollapsed = collapsed[g.id] && g.id !== activeGroupId;
          return (
            <div key={g.id} style={{ marginBottom: 2 }}>
              <button
                onClick={() => toggleGroup(g.id)}
                className="shell-nav-section-btn"
                style={{
                  display: 'flex', alignItems: 'center', gap: 6, width: '100%',
                  padding: '10px 12px 6px', background: 'none', border: 'none',
                  fontSize: 10, textTransform: 'uppercase', letterSpacing: '.12em',
                  color: 'var(--text-4)', fontWeight: 600, cursor: 'pointer', textAlign: 'left',
                }}
              >
                <Icon name="chevronDown" size={10} style={{ transform: isCollapsed ? 'rotate(-90deg)' : 'none', transition: 'transform .15s' }}/>
                {g.label}
              </button>
              {!isCollapsed && g.items.map(m => (
                <button key={m.id} className={`shell-nav-item ${current === m.id ? 'active' : ''}`} onClick={() => handleClick(m.id)}>
                  <Icon name={m.icon} size={16}/>
                  <span style={{ flex: 1 }}>{m.label}</span>
                  {m.counter != null && <span className="counter">{m.counter}</span>}
                </button>
              ))}
            </div>
          );
        })}

        <div className="shell-user">
          <Avatar name="Rafael Admin" size={32}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="shell-user-name">Rafael Admin</div>
            <div className="shell-user-role">admin@padaria.com.br</div>
          </div>
          <button className="shell-nav-item" style={{ padding: 6, width: 'auto' }} onClick={() => onNavigate('landing')}>
            <Icon name="logout" size={14}/>
          </button>
        </div>
      </aside>

      <div className="shell-main">
        <header className="shell-topbar">
          <button className="shell-mob-burger" onClick={() => setMobNav(!mobNav)}>
            <Icon name="menu" size={18}/>
          </button>
          <div className="shell-breadcrumb">
            <Icon name="dashboard" size={14}/>
            <span>{currentItem.group}</span>
            <span style={{ color: 'var(--text-5)' }}>/</span>
            <b>{currentItem.label}</b>
          </div>
          <div className="shell-search hide-mobile">
            <Icon name="search" size={16}/>
            <input placeholder="Buscar clientes, faturas, tickets..."/>
            <kbd>⌘K</kbd>
          </div>
          <div className="shell-topbar-actions">
            <button className="shell-top-btn" title="IA Assistente"><Icon name="sparkle" size={16} color="#a78bfa"/></button>
            <button className="shell-top-btn hide-mobile" title="Ajuda"><Icon name="help" size={16}/></button>
            <button className="shell-top-btn" title="Notificações">
              <Icon name="bell" size={16}/>
              <span className="badge"/>
            </button>
            <button className="btn btn-primary" style={{ padding: '8px 14px', fontSize: 13 }}>
              <Icon name="plus" size={14}/>
              <span className="hide-mobile">Novo</span>
            </button>
          </div>
        </header>
        <div className="shell-body">
          {children}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AppShell });
