
// Main App Shell — Sidebar, Topbar, Routing

function App() {
  const [session, setSession] = React.useState(null);
  const [authLoading, setAuthLoading] = React.useState(true);

  React.useEffect(() => {
    sb.auth.getSession().then(({ data: { session } }) => {
      setSession(session);
      setAuthLoading(false);
    });
    const { data: { subscription } } = sb.auth.onAuthStateChange((_event, session) => {
      setSession(session);
    });
    return () => subscription.unsubscribe();
  }, []);

  if (authLoading) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', background: '#F1F5F9' }}>
        <Spinner />
      </div>
    );
  }

  if (!session) {
    return <Login onLogin={setSession} />;
  }

  return <AppShell session={session} />;
}

function AppShell({ session }) {
  const [page, setPage]                   = React.useState(() => localStorage.getItem('ef_page') || 'dashboard');
  const [sidebarCollapsed, setSidebarCollapsed] = React.useState(false);
  const [mobileMenuOpen, setMobileMenuOpen]     = React.useState(false);
  const [isMobile, setIsMobile]           = React.useState(window.innerWidth < 768);
  const [notifOpen, setNotifOpen]         = React.useState(false);
  const [searchVal, setSearchVal]         = React.useState('');
  const [notifs, setNotifs]               = React.useState([]);

  React.useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  React.useEffect(() => {
    const today = new Date().toISOString().split('T')[0];
    const inWeek = new Date(Date.now() + 7 * 86400000).toISOString().split('T')[0];
    Promise.all([
      sb.from('events').select('id, name, event_date').gte('event_date', today).lte('event_date', inWeek).order('event_date'),
      sb.from('budgets').select('id').in('status', ['Pendente', 'Em análise']),
    ]).then(([evRes, budRes]) => {
      const items = [];
      (evRes.data || []).slice(0, 3).forEach(e => {
        const days = Math.ceil((new Date(e.event_date) - new Date(today)) / 86400000);
        items.push({ icon: 'calendar', color: '#3B82F6', text: `${e.name} em ${days === 0 ? 'hoje' : days + ' dia(s)'}`, time: 'Agenda' });
      });
      const pending = (budRes.data || []).length;
      if (pending > 0) items.push({ icon: 'budget', color: '#F59E0B', text: `${pending} orçamento(s) aguardando aprovação`, time: 'Orçamentos' });
      setNotifs(items);
    });
  }, []);

  const userName    = session?.user?.email?.split('@')[0] || 'Usuário';
  const displayName = userName.charAt(0).toUpperCase() + userName.slice(1);

  const navigate = (p) => {
    setPage(p);
    localStorage.setItem('ef_page', p);
    if (isMobile) setMobileMenuOpen(false); // auto-close no mobile
  };

  const handleLogout = async () => {
    await sb.auth.signOut();
  };

  const nav = [
    { id: 'dashboard',   label: 'Dashboard',      icon: 'dashboard' },
    { id: 'budgets',     label: 'Orçamentos',      icon: 'budget'   },
    { id: 'events',      label: 'Agenda',          icon: 'calendar' },
    { id: 'freelancers', label: 'Freelancers',     icon: 'users'    },
    { id: 'crm',         label: 'Clientes',        icon: 'crm'      },
    { id: 'financeiro',  label: 'Financeiro',      icon: 'wallet'   },
    { id: 'tasks',       label: 'Tarefas',         icon: 'tasks'    },
    { id: 'portal',      label: 'Portal Cliente',  icon: 'portal'   },
    { id: 'reports',     label: 'Relatórios',      icon: 'reports'  },
    { id: 'usuarios',    label: 'Usuários',         icon: 'users'    },
  ];


  const SIDEBAR_W = isMobile ? 260 : (sidebarCollapsed ? 60 : 200);

  // Safe area top (notch)
  const safeTop = 'env(safe-area-inset-top, 0px)';

  const SidebarItem = ({ item }) => {
    const active = page === item.id;
    const collapsed = !isMobile && sidebarCollapsed;
    const [hov, setHov] = React.useState(false);
    return (
      <div onClick={() => navigate(item.id)}
        onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
        style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: collapsed ? '10px 0' : '10px 14px',
          justifyContent: collapsed ? 'center' : 'flex-start',
          borderRadius: DS.radius.sm, cursor: 'pointer', transition: 'all 0.15s',
          background: active ? DS.colors.primary : hov ? DS.colors.sidebarHover : 'transparent',
          color: active ? '#fff' : hov ? '#CBD5E1' : '#94A3B8',
          position: 'relative',
          minHeight: 44,
        }}>
        <Icon name={item.icon} size={18} color={active ? '#fff' : hov ? '#CBD5E1' : '#94A3B8'} />
        {!collapsed && <span style={{ fontSize: 13, fontWeight: active ? 700 : 500 }}>{item.label}</span>}
        {active && !collapsed && <div style={{ width: 3, height: 20, background: '#fff', borderRadius: DS.radius.full, position: 'absolute', right: 0, top: '50%', transform: 'translateY(-50%)' }} />}
        {collapsed && hov && (
          <div style={{ position: 'absolute', left: '100%', marginLeft: 8, background: '#1C1280', color: '#fff', padding: '6px 10px', borderRadius: DS.radius.sm, fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap', zIndex: 100, boxShadow: DS.shadow.lg }}>
            {item.label}
          </div>
        )}
      </div>
    );
  };

  const pageMap = { dashboard: Dashboard, budgets: Budgets, events: Events, freelancers: Freelancers, crm: CRM, financeiro: Financeiro, tasks: Tasks, portal: ClientPortal, reports: Reports, usuarios: Usuarios };
  const PageComp = pageMap[page] || Dashboard;

  const collapsed = !isMobile && sidebarCollapsed;

  // ── Sidebar content (reutilizado em desktop e mobile) ──
  const SidebarContent = () => (
    <>
      {/* Logo */}
      <div style={{
        padding: collapsed ? '12px 0' : '14px 14px',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        borderBottom: '1px solid rgba(255,255,255,0.08)',
        paddingTop: isMobile ? safeTop : (collapsed ? '12px' : '14px'),
      }}>
        {collapsed ? (
          <img src="logo-icon.png" alt="Promoup" style={{ width: 36, height: 36, objectFit: 'contain', filter: 'drop-shadow(0 1px 4px rgba(0,0,0,0.4))' }} />
        ) : (
          <img src="logo.png" alt="Promoup 360°" style={{ height: 64, objectFit: 'contain', maxWidth: '100%', filter: 'drop-shadow(0 1px 8px rgba(0,0,0,0.35))' }} />
        )}
      </div>

      {/* Nav */}
      <div style={{ flex: 1, padding: '12px 10px', overflowY: 'auto', overflowX: 'hidden' }}>
        {!collapsed && <div style={{ fontSize: 10, fontWeight: 700, color: 'rgba(255,255,255,0.3)', textTransform: 'uppercase', letterSpacing: '0.1em', padding: '4px 6px 8px' }}>Principal</div>}
        {nav.slice(0, 3).map(item => <SidebarItem key={item.id} item={item} />)}
        {!collapsed && <div style={{ fontSize: 10, fontWeight: 700, color: 'rgba(255,255,255,0.3)', textTransform: 'uppercase', letterSpacing: '0.1em', padding: '14px 6px 8px' }}>Gestão</div>}
        {collapsed && <div style={{ height: 14 }} />}
        {nav.slice(3).map(item => <SidebarItem key={item.id} item={item} />)}
      </div>

      {/* Bottom */}
      <div style={{ padding: '12px 10px', borderTop: '1px solid rgba(255,255,255,0.08)', paddingBottom: isMobile ? 'max(12px, env(safe-area-inset-bottom))' : '12px' }}>
        {!isMobile && (
          <div onClick={() => setSidebarCollapsed(c => !c)}
            style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: DS.radius.sm, cursor: 'pointer', color: '#64748B', justifyContent: collapsed ? 'center' : 'flex-start', marginBottom: 4 }}
            onMouseEnter={e => e.currentTarget.style.color = '#94A3B8'}
            onMouseLeave={e => e.currentTarget.style.color = '#64748B'}>
            <Icon name={collapsed ? 'arrow' : 'logout'} size={16} color="currentColor" />
            {!collapsed && <span style={{ fontSize: 12, fontWeight: 600 }}>Recolher menu</span>}
          </div>
        )}

        {!collapsed && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 10px 2px' }}>
            <Avatar name={displayName} size={32} color="#EA6B00" />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: '#CBD5E1', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{displayName}</div>
              <div style={{ fontSize: 11, color: '#475569' }}>Administrador</div>
            </div>
            <button onClick={handleLogout} title="Sair"
              style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 4, borderRadius: 6, display: 'flex', color: '#475569' }}
              onMouseEnter={e => e.currentTarget.style.color = '#EF4444'}
              onMouseLeave={e => e.currentTarget.style.color = '#475569'}>
              <Icon name="logout" size={14} color="currentColor" />
            </button>
          </div>
        )}

        {collapsed && (
          <div onClick={handleLogout} title="Sair"
            style={{ display: 'flex', justifyContent: 'center', padding: '8px 0', cursor: 'pointer', color: '#475569', borderRadius: DS.radius.sm }}
            onMouseEnter={e => e.currentTarget.style.color = '#EF4444'}
            onMouseLeave={e => e.currentTarget.style.color = '#475569'}>
            <Icon name="logout" size={16} color="currentColor" />
          </div>
        )}
      </div>
    </>
  );

  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: DS.colors.bg, fontFamily: "'Inter', sans-serif" }}>

      {/* ── DESKTOP Sidebar ── */}
      {!isMobile && (
        <div style={{
          width: SIDEBAR_W, minHeight: '100vh', background: DS.colors.sidebar,
          display: 'flex', flexDirection: 'column', flexShrink: 0,
          transition: 'width 0.2s ease', overflow: 'hidden',
          position: 'sticky', top: 0, height: '100vh',
        }}>
          <SidebarContent />
        </div>
      )}

      {/* ── MOBILE Sidebar overlay ── */}
      {isMobile && mobileMenuOpen && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 999 }} onClick={() => setMobileMenuOpen(false)}>
          <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)' }} />
        </div>
      )}
      {isMobile && (
        <div style={{
          position: 'fixed', top: 0, left: 0, height: '100%', width: SIDEBAR_W,
          background: DS.colors.sidebar, display: 'flex', flexDirection: 'column',
          zIndex: 1000, overflow: 'hidden',
          transform: mobileMenuOpen ? 'translateX(0)' : 'translateX(-100%)',
          transition: 'transform 0.25s cubic-bezier(0.4,0,0.2,1)',
          boxShadow: mobileMenuOpen ? '4px 0 24px rgba(0,0,0,0.4)' : 'none',
        }}>
          <SidebarContent />
        </div>
      )}

      {/* ── Main ── */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, overflow: 'hidden' }}>

        {/* Topbar */}
        <div style={{
          background: '#fff', borderBottom: `1px solid ${DS.colors.border}`,
          display: 'flex', alignItems: 'flex-end', padding: '0 16px',
          gap: 12, position: 'sticky', top: 0, zIndex: 50,
          paddingTop: safeTop,
          minHeight: `calc(56px + env(safe-area-inset-top, 0px))`,
          paddingBottom: 8,
        }}>
          {/* Hamburguer mobile */}
          {isMobile && (
            <button onClick={() => setMobileMenuOpen(o => !o)}
              style={{ width: 36, height: 36, borderRadius: DS.radius.sm, border: `1px solid ${DS.colors.border}`, background: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <svg width="18" height="14" viewBox="0 0 18 14" fill="none">
                <rect y="0"  width="18" height="2" rx="1" fill={DS.colors.text}/>
                <rect y="6"  width="14" height="2" rx="1" fill={DS.colors.text}/>
                <rect y="12" width="10" height="2" rx="1" fill={DS.colors.text}/>
              </svg>
            </button>
          )}

          {/* Search — oculto no mobile pequeno */}
          {!isMobile && (
            <div style={{ flex: 1, maxWidth: 380, position: 'relative' }}>
              <div style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)' }}>
                <Icon name="search" size={15} color={DS.colors.textMuted} />
              </div>
              <input value={searchVal} onChange={e => setSearchVal(e.target.value)}
                placeholder="Buscar eventos, clientes, tarefas…"
                style={{ width: '100%', border: `1px solid ${DS.colors.border}`, borderRadius: DS.radius.sm, padding: '8px 12px 8px 36px', fontSize: 13, outline: 'none', background: '#F8FAFC', fontFamily: 'inherit', color: DS.colors.text, boxSizing: 'border-box' }} />
            </div>
          )}

          {isMobile && (
            <div style={{ flex: 1, fontSize: 15, fontWeight: 700, color: DS.colors.text }}>
              {nav.find(n => n.id === page)?.label || 'Dashboard'}
            </div>
          )}

          <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
            {!isMobile && <Btn size="sm" icon="plus" onClick={() => navigate('events')}>Novo evento</Btn>}

            {/* Notificações */}
            <div style={{ position: 'relative' }}>
              <button onClick={() => setNotifOpen(o => !o)} style={{ width: 36, height: 36, borderRadius: DS.radius.sm, border: `1px solid ${DS.colors.border}`, background: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
                <Icon name="bell" size={16} color={DS.colors.textSec} />
                {notifs.length > 0 && <div style={{ position: 'absolute', top: 6, right: 6, width: 7, height: 7, borderRadius: '50%', background: DS.colors.danger, border: '1.5px solid #fff' }} />}
              </button>
              {notifOpen && (
                <div style={{ position: 'absolute', right: 0, top: 44, width: isMobile ? 290 : 320, background: '#fff', borderRadius: DS.radius.md, boxShadow: DS.shadow.lg, border: `1px solid ${DS.colors.border}`, zIndex: 200 }}>
                  <div style={{ padding: '14px 16px', borderBottom: `1px solid ${DS.colors.border}`, display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ fontSize: 13, fontWeight: 700 }}>Notificações</span>
                    {notifs.length > 0 && <Badge variant="danger">{notifs.length} novas</Badge>}
                  </div>
                  {notifs.length === 0 ? (
                    <div style={{ padding: '24px 16px', textAlign: 'center', fontSize: 13, color: DS.colors.textMuted }}>Sem notificações no momento</div>
                  ) : notifs.map((n, i) => (
                    <div key={i} onClick={() => setNotifOpen(false)}
                      style={{ display: 'flex', gap: 12, padding: '12px 16px', borderBottom: i < notifs.length - 1 ? `1px solid ${DS.colors.border}` : 'none', cursor: 'pointer' }}
                      onMouseEnter={e => e.currentTarget.style.background = '#F8FAFC'}
                      onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
                      <div style={{ width: 32, height: 32, borderRadius: '50%', background: n.color + '18', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                        <Icon name={n.icon} size={14} color={n.color} />
                      </div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 12, color: DS.colors.text, lineHeight: 1.4 }}>{n.text}</div>
                        <div style={{ fontSize: 11, color: DS.colors.textMuted, marginTop: 2 }}>{n.time}</div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Usuário — só desktop */}
            {!isMobile && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 10px', borderRadius: DS.radius.sm, border: `1px solid ${DS.colors.border}`, cursor: 'pointer' }}>
                <Avatar name={displayName} size={26} color="#EA6B00" />
                <span style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{displayName}</span>
                <Icon name="chevronDown" size={13} color={DS.colors.textMuted} />
              </div>
            )}

            {/* Avatar mobile */}
            {isMobile && (
              <div style={{ width: 34, height: 34, borderRadius: '50%', overflow: 'hidden', flexShrink: 0 }}>
                <Avatar name={displayName} size={34} color="#EA6B00" />
              </div>
            )}
          </div>
        </div>

        {/* Page content */}
        <div style={{
          flex: 1,
          padding: isMobile ? '16px 14px' : '28px 28px',
          overflowY: 'auto',
          paddingBottom: isMobile ? 'max(20px, env(safe-area-inset-bottom))' : '28px',
        }}>
          <PageComp onNavigate={navigate} />
        </div>
      </div>

      {/* Overlay notificações */}
      {notifOpen && <div style={{ position: 'fixed', inset: 0, zIndex: 100 }} onClick={() => setNotifOpen(false)} />}
    </div>
  );
}

Object.assign(window, { App });
