import { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Link, useLocation, useNavigate } from 'react-router-dom';
import {
  LayoutDashboard,
  Ticket,
  Users as UsersIconLucide,
  Settings as SettingsIcon,
  MessageSquare,
  LogOut,
  ExternalLink,
  ChevronRight,
  TrendingUp,
  DollarSign,
  Clock,
  Puzzle,
  ShieldCheck,
  Inbox,
  Webhook,
  ShoppingCart,
  Gift,
  Stethoscope,
  HeartPulse,
  BarChart2,
  Menu,
  X,
  Briefcase,
  Package2,
  Users2,
  QrCode,
  Landmark,
  UserCog,
} from 'lucide-react';
import {
  AreaChart,
  Area,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from 'recharts';

import UsersPage from './pages/Users';
import SettingsPage from './pages/Settings';
import RafflesPage from './pages/Raffles';
import PromotionsPage from './pages/Promotions';
import WhatsAppLogsPage from './pages/WhatsAppLogs';
import WhatsAppInboxPage from './pages/WhatsAppInbox';
import WhatsAppWebhooksPage from './pages/WhatsAppWebhooks';
import PluginsPage from './pages/Plugins';
import AdminUsersPage from './pages/AdminUsers';
import LoginPage from './pages/Login';
import OrdersPage from './pages/Orders';
import ClaimsPage from './pages/Claims';
import ClubOdontoPage from './pages/ClubOdonto';
import ClubMedicoPage from './pages/ClubMedico';
import ClubReportsPage from './pages/ClubReports';
import JobsPage        from './pages/JobsPage';
import CatalogPage     from './pages/CatalogPage';
import ClientesPage    from './pages/ClientesPage';
import PedidosPage     from './pages/PedidosPage';
import InboxPage       from './pages/InboxPage';
import RelatorioPage   from './pages/RelatorioPage';
import SeparadorPage   from './pages/SeparadorPage';
import FinanceiroPage  from './pages/FinanceiroPage';
import EquipePage      from './pages/EquipePage';
import NotificacoesBell from './components/NotificacoesBell';
import { AnalyticsService, AdminMeService, CotacaoService } from './services/api';

// ─── tipos ────────────────────────────────────────────────────────────────────

export interface TeamAccount {
  id: number;
  name: string;
  email: string;
  role: string;  // owner | manager | supervisor | secretary | agent | viewer
}

type AuthState = 'checking' | 'admin' | 'team' | 'login';

// ─── Sidebar (admin) ──────────────────────────────────────────────────────────

function SidebarItem({ icon: Icon, label, href, active, accentColor }: { icon: any; label: string; href: string; active?: boolean; accentColor?: string }) {
  const color = accentColor || '#06b6d4';
  return (
    <Link
      to={href}
      className={`flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 group ${
        active
          ? 'border'
          : 'text-slate-400 hover:bg-slate-800 hover:text-slate-200 border border-transparent'
      }`}
      style={active ? { background: `${color}15`, borderColor: `${color}30`, color } : {}}
    >
      <Icon size={20} style={active ? { color } : {}} className={active ? '' : 'text-slate-500 group-hover:text-slate-300'} />
      <span className="font-medium">{label}</span>
      {active && <div className="ml-auto w-1.5 h-1.5 rounded-full" style={{ background: color, boxShadow: `0 0 8px ${color}99` }} />}
    </Link>
  );
}

interface TenantInfo {
  id: number; slug: string; name: string;
  primary_color: string; secondary_color: string; logo_url: string | null;
}

function Sidebar({ tenant, adminInfo, isOpen, onClose, collapsed, onToggleCollapse }: {
  tenant: TenantInfo | null;
  adminInfo: { nome?: string | null; email?: string | null; username?: string } | null;
  isOpen: boolean;
  onClose: () => void;
  collapsed: boolean;
  onToggleCollapse: () => void;
}) {
  const location = useLocation();
  const path = location.pathname;
  const color = tenant?.primary_color || '#06b6d4';
  const w = collapsed ? 'w-16' : 'w-72';

  const navItems = [
    { icon: LayoutDashboard, label: 'Dashboard',        href: '/' },
    { icon: Ticket,          label: 'Sorteios',         href: '/raffles' },
    { icon: TrendingUp,      label: 'Promoções',        href: '/promotions' },
    { icon: Ticket,          label: 'Pedidos Sorteio',  href: '/orders' },
    { icon: Gift,            label: 'Resgates',         href: '/claims' },
    { icon: UsersIconLucide, label: 'Clientes',         href: '/users' },
    { icon: ShoppingCart,    label: 'Cotação — Pedidos',href: '/cotacao/pedidos' },
    { icon: Landmark,        label: 'Financeiro',       href: '/cotacao/financeiro' },
    { icon: Package2,        label: 'Catálogo',         href: '/cotacao/catalogo' },
    { icon: Users2,          label: 'Clientes Cotação', href: '/cotacao/clientes' },
    { icon: QrCode,          label: 'Separador PWA',    href: '/cotacao/separador' },
    { icon: MessageSquare,   label: 'Inbox Interno',    href: '/cotacao/inbox' },
    { icon: UserCog,         label: 'Equipe',           href: '/equipe' },
    { icon: BarChart2,       label: 'Relatórios Op.',   href: '/cotacao/relatorios' },
    { icon: Inbox,           label: 'WhatsApp Inbox',   href: '/wa-inbox' },
    { icon: Webhook,         label: 'WA Webhooks',      href: '/wa-webhooks' },
    { icon: MessageSquare,   label: 'WhatsApp (Logs)',  href: '/whatsapp' },
    { icon: Puzzle,          label: 'Integrações',      href: '/plugins' },
    { icon: Stethoscope,     label: 'Clube Odonto',     href: '/clubs/odonto' },
    { icon: HeartPulse,      label: 'Clube Médico',     href: '/clubs/medico' },
    { icon: BarChart2,       label: 'Relatórios Clube', href: '/clubs/reports' },
    { icon: Briefcase,       label: 'Vagas & Talentos', href: '/jobs' },
    { icon: ShieldCheck,     label: 'Administradores',  href: '/admins' },
    { icon: SettingsIcon,    label: 'Configurações',    href: '/settings' },
  ];

  const displayName = adminInfo?.nome || adminInfo?.username || adminInfo?.email || 'Admin';
  const initials = displayName.split(' ').map((n: string) => n[0]).slice(0, 2).join('').toUpperCase();

  return (
    <>
      {isOpen && (
        <div className="fixed inset-0 bg-black/60 z-30 md:hidden" onClick={onClose} />
      )}
      <aside className={`fixed md:sticky top-0 left-0 z-40 ${w} bg-slate-950 border-r border-slate-900 flex flex-col h-screen overflow-hidden transition-all duration-300 ease-in-out ${isOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'}`}>
        <div className="absolute top-0 left-0 w-full h-32 bg-gradient-to-b from-cyan-500/5 to-transparent pointer-events-none" />

        {/* Header da sidebar */}
        <div className={`relative z-10 border-b border-slate-900 flex items-center gap-3 ${collapsed ? 'p-2 justify-center h-16' : 'p-4'}`}>
          {!collapsed && (
            <>
              {tenant?.logo_url ? (
                <img src={tenant.logo_url} alt={tenant.name} className="h-9 object-contain shrink-0" />
              ) : (
                <div className="w-9 h-9 rounded-xl flex items-center justify-center shadow-lg shrink-0"
                  style={{ background: `linear-gradient(135deg, ${color}, ${color}88)` }}>
                  <LayoutDashboard className="text-white" size={18} />
                </div>
              )}
              <div className="flex-1 min-w-0">
                <h1 className="text-sm font-black text-white tracking-tight leading-tight truncate">
                  {tenant?.name || 'Admin'}
                </h1>
                <p className="text-[10px] font-black uppercase tracking-widest leading-none mt-0.5" style={{ color }}>
                  Cloud Admin v2
                </p>
              </div>
            </>
          )}
          {/* Botão colapsar/expandir (desktop) */}
          <button
            onClick={onToggleCollapse}
            className="hidden md:flex w-8 h-8 items-center justify-center rounded-lg text-slate-500 hover:text-white hover:bg-slate-800 transition-colors shrink-0"
            title={collapsed ? 'Expandir menu' : 'Recolher menu'}
          >
            <ChevronRight size={16} className={`transition-transform duration-300 ${collapsed ? '' : 'rotate-180'}`} />
          </button>
          {/* Fechar mobile */}
          <button onClick={onClose} className="md:hidden text-slate-500 hover:text-white transition-colors shrink-0">
            <X size={18} />
          </button>
        </div>

        {/* Nav */}
        <nav className={`flex-1 py-2 flex flex-col relative z-10 overflow-y-auto ${collapsed ? 'px-1 gap-1 items-center' : 'px-3 gap-0.5'}`}>
          {navItems.map(({ icon: Icon, label, href }) => {
            const active = path === href;
            if (collapsed) {
              return (
                <Link key={href} to={href} title={label}
                  className={`flex items-center justify-center w-10 h-10 rounded-xl transition-all shrink-0 ${active ? 'border' : 'text-slate-500 hover:bg-slate-800 hover:text-slate-200 border border-transparent'}`}
                  style={active ? { background: `${color}15`, borderColor: `${color}30`, color } : {}}>
                  <Icon size={18} style={active ? { color } : {}} />
                </Link>
              );
            }
            return (
              <SidebarItem key={href} icon={Icon} label={label} href={href} active={active} accentColor={color} />
            );
          })}
        </nav>

        {/* Footer — usuário logado + ações */}
        <div className={`mt-auto border-t border-slate-900 relative z-10 bg-slate-950/80 backdrop-blur-sm ${collapsed ? 'p-1 flex flex-col items-center gap-1' : 'p-3'}`}>
          {/* Info do usuário */}
          {!collapsed && adminInfo && (
            <div className="flex items-center gap-2.5 px-3 py-2.5 mb-2 bg-slate-900/60 rounded-xl border border-slate-800">
              <div className="w-8 h-8 rounded-lg flex items-center justify-center text-xs font-black text-white shrink-0"
                style={{ background: `linear-gradient(135deg, ${color}, ${color}88)` }}>
                {initials}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-xs font-bold text-white truncate leading-tight">{displayName}</p>
                {adminInfo.email && <p className="text-[10px] text-slate-500 truncate">{adminInfo.email}</p>}
              </div>
            </div>
          )}
          {collapsed && adminInfo && (
            <div className="w-10 h-10 rounded-xl flex items-center justify-center text-xs font-black text-white"
              style={{ background: `linear-gradient(135deg, ${color}, ${color}88)` }} title={displayName}>
              {initials}
            </div>
          )}

          {!collapsed && (
            <a href="/" target="_blank" className="flex items-center gap-3 px-3 py-2 text-slate-400 hover:text-white transition-colors group rounded-xl hover:bg-slate-800 mb-1">
              <ExternalLink size={16} className="group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition-transform shrink-0" />
              <span className="text-xs font-medium">Ver Site Público</span>
            </a>
          )}
          <button
            onClick={() => { window.location.href = '/admin/logout'; }}
            className={`flex items-center gap-3 text-rose-400 hover:bg-rose-500/10 rounded-xl transition-all group ${collapsed ? 'w-10 h-10 justify-center' : 'w-full px-3 py-2'}`}
            title="Encerrar Sessão"
          >
            <LogOut size={16} className="group-hover:-translate-x-0.5 transition-transform shrink-0" />
            {!collapsed && <span className="text-xs font-medium">Encerrar Sessão</span>}
          </button>
        </div>
      </aside>
    </>
  );
}

// ─── Dashboard ────────────────────────────────────────────────────────────────

function StatCard({ label, value, icon: Icon, trend, color }: { label: string; value: string; icon: any; trend?: string; color: string }) {
  return (
    <div className="bg-slate-900/40 backdrop-blur-sm border border-slate-800 p-6 rounded-3xl hover:border-slate-700 transition-all group">
      <div className="flex justify-between items-start mb-4">
        <div className={`p-3 rounded-2xl bg-slate-800 border border-white/5 text-${color}-400 group-hover:scale-110 transition-transform`}>
          <Icon size={24} />
        </div>
        {trend && (
          <span className="text-xs font-black text-emerald-400 bg-emerald-400/10 px-2 py-1 rounded-lg tracking-tighter">{trend}</span>
        )}
      </div>
      <div>
        <p className="text-slate-500 text-xs font-bold uppercase tracking-widest mb-1">{label}</p>
        <h3 className="text-3xl font-black text-white tabular-nums tracking-tighter">{value}</h3>
      </div>
    </div>
  );
}

const chartTooltipStyle = {
  contentStyle: { background: '#0f172a', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '12px', color: '#f1f5f9', fontSize: '12px' },
};

const formatBRL = (val: number) =>
  val.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });

function DashboardSkeleton() {
  return (
    <div className="space-y-10 animate-pulse">
      <div className="flex flex-wrap justify-between items-start gap-4">
        <div className="space-y-2">
          <div className="h-9 w-56 bg-slate-800 rounded-xl" />
          <div className="h-4 w-80 bg-slate-800/60 rounded-lg" />
        </div>
        <div className="h-10 w-36 bg-slate-800 rounded-2xl" />
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {[...Array(4)].map((_, i) => (
          <div key={i} className="bg-slate-900/40 border border-slate-800 p-6 rounded-3xl space-y-4">
            <div className="h-10 w-10 bg-slate-800 rounded-2xl" />
            <div className="space-y-2">
              <div className="h-3 w-24 bg-slate-800 rounded" />
              <div className="h-8 w-20 bg-slate-800 rounded-lg" />
            </div>
          </div>
        ))}
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 bg-slate-900/40 border border-slate-800 rounded-[2.5rem] p-10 h-96" />
        <div className="bg-slate-900/40 border border-slate-800 rounded-[2.5rem] p-10 h-96" />
      </div>
    </div>
  );
}

function Dashboard() {
  const navigate = useNavigate();
  const [data, setData]         = useState<any>(null);
  const [cotacao, setCotacao]   = useState<any>(null);
  const [loading, setLoading]   = useState(true);

  useEffect(() => {
    Promise.all([
      AnalyticsService.getDashboard().catch(() => null),
      CotacaoService.contadores().catch(() => null),
    ]).then(([dash, cnt]) => {
      setData(dash);
      setCotacao(cnt);
    }).finally(() => setLoading(false));
  }, []);

  if (loading) return <DashboardSkeleton />;

  const salesByDay = (data?.salesByDay || []).map((d: any) => ({
    ...d,
    revenue: parseFloat(d.revenue || 0),
    label: d.date ? new Date(d.date).toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' }) : d.date,
  }));
  const salesByHour = (data?.salesByHour || []).map((d: any) => ({ ...d, tickets_sold: parseInt(d.tickets_sold || 0) }));

  return (
    <div className="space-y-10 animate-in fade-in slide-in-from-bottom-4 duration-700">
      <header className="flex flex-wrap justify-between items-start gap-4">
        <div>
          <h2 className="text-3xl md:text-4xl font-black text-white tracking-tighter">Resumo Geral</h2>
          <p className="text-slate-400 mt-1 font-medium">Monitoramento em tempo real do ecossistema Alemão.</p>
        </div>
        <div className="bg-slate-900 border border-slate-800 p-2 rounded-2xl flex items-center gap-2 shrink-0">
          <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
          <span className="text-[10px] font-black uppercase tracking-widest text-slate-400 pr-2">Sistema Online</span>
        </div>
      </header>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard label="Receita Total" value={formatBRL(parseFloat(data?.revenueStats?.total_revenue || 0))} icon={DollarSign} color="cyan" />
        <StatCard label="Tickets Vendidos" value={String(data?.revenueStats?.total_tickets_sold ?? 0)} icon={Ticket} color="blue" />
        <StatCard label="Base Clientes" value={String(data?.revenueStats?.total_users ?? 0)} icon={UsersIconLucide} color="purple" />
        <StatCard label="Tickets Ativos" value={String(data?.revenueStats?.active_tickets ?? 0)} icon={Clock} color="orange" />
      </div>

      {/* Cotação Online — PROMO-09 */}
      {cotacao && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {[
            { label: 'Pedidos Hoje',    value: cotacao.hoje ?? 0,          color: 'text-cyan-400',    href: '/cotacao/pedidos' },
            { label: 'Em Separação',    value: cotacao.em_separacao ?? 0,  color: 'text-blue-400',    href: '/cotacao/pedidos' },
            { label: 'Em Auditoria',    value: cotacao.em_auditoria ?? 0,  color: 'text-orange-400',  href: '/cotacao/pedidos' },
            { label: 'Promos Ativas',   value: cotacao.promocoes_ativas ?? 0, color: 'text-emerald-400', href: '/promotions' },
          ].map(c => (
            <button key={c.label} onClick={() => navigate(c.href)}
              className="bg-slate-900/40 border border-slate-800 hover:border-slate-700 rounded-2xl p-4 text-left transition-all group">
              <p className={`text-3xl font-black tabular-nums group-hover:scale-105 transition-transform inline-block ${c.color}`}>{c.value}</p>
              <p className="text-[10px] font-black uppercase tracking-widest text-slate-500 mt-1">{c.label}</p>
            </button>
          ))}
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 bg-slate-900/40 border border-slate-800 rounded-[2.5rem] p-5 md:p-10 relative overflow-hidden group">
          <div className="absolute top-0 right-0 w-64 h-64 bg-cyan-500/5 blur-3xl rounded-full" />
          <div className="flex items-center justify-between mb-8 relative z-10">
            <h3 className="text-2xl font-black text-white flex items-center gap-3 tracking-tight">
              <TrendingUp className="text-cyan-400" size={24} />
              Performance de Mercado
            </h3>
          </div>
          <div className="h-56 w-full mb-8 relative z-10">
            <p className="text-[10px] font-black uppercase tracking-widest text-slate-500 mb-3">Receita por Dia (Últimos 30 Dias)</p>
            {salesByDay.length > 0 ? (
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={salesByDay}>
                  <defs>
                    <linearGradient id="gradRevenue" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#06b6d4" stopOpacity={0.3} />
                      <stop offset="95%" stopColor="#06b6d4" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                  <XAxis dataKey="label" stroke="#475569" tick={{ fontSize: 10 }} />
                  <YAxis stroke="#475569" tick={{ fontSize: 10 }} tickFormatter={(v: number) => `R$${v}`} />
                  <Tooltip {...chartTooltipStyle} formatter={(v: any) => [formatBRL(Number(v)), 'Receita']} />
                  <Area type="monotone" dataKey="revenue" stroke="#06b6d4" strokeWidth={2} fill="url(#gradRevenue)" />
                </AreaChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-full flex items-center justify-center text-slate-600 text-sm italic">Sem dados disponíveis</div>
            )}
          </div>
          <div className="h-40 w-full relative z-10">
            <p className="text-[10px] font-black uppercase tracking-widest text-slate-500 mb-3">Picos de Venda por Horário</p>
            {salesByHour.length > 0 ? (
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={salesByHour}>
                  <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                  <XAxis dataKey="hour_of_day" stroke="#475569" tick={{ fontSize: 10 }} tickFormatter={(h: number) => `${h}h`} />
                  <YAxis stroke="#475569" tick={{ fontSize: 10 }} />
                  <Tooltip {...chartTooltipStyle} formatter={(v: any) => [v, 'Tickets']} />
                  <Bar dataKey="tickets_sold" fill="#10b981" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-full flex items-center justify-center text-slate-600 text-sm italic">Sem dados disponíveis</div>
            )}
          </div>
        </div>

        <div className="bg-slate-900/40 border border-slate-800 rounded-[2.5rem] p-5 md:p-10 flex flex-col relative overflow-hidden group">
          <h3 className="text-2xl font-black text-white mb-8 tracking-tight relative z-10">Sorteios Quentes</h3>
          <div className="space-y-4 relative z-10 flex-1">
            {data?.salesByRaffle?.slice(0, 4).map((r: any) => {
              const pct = r.total_numeros > 0 ? Math.min(100, Math.round((r.tickets_sold / r.total_numeros) * 100)) : 0;
              return (
                <div key={r.raffle_id} className="flex items-center gap-4 p-5 rounded-[1.5rem] bg-slate-800/40 border border-slate-800 hover:border-cyan-500/30 hover:bg-slate-800/60 transition-all cursor-pointer group/item"
                  onClick={() => navigate('/raffles')}>
                  <div className="w-12 h-12 bg-gradient-to-br from-slate-700 to-slate-800 rounded-2xl flex items-center justify-center text-xl font-bold border border-white/5 shadow-lg">🍀</div>
                  <div className="flex-1 min-w-0">
                    <h4 className="text-sm font-black text-white truncate uppercase tracking-tight">{r.raffle_name}</h4>
                    <div className="flex items-center gap-2 mt-1">
                      <div className="flex-1 h-1 bg-slate-700 rounded-full overflow-hidden">
                        <div className="h-full bg-cyan-400 transition-all duration-500" style={{ width: `${pct}%` }} />
                      </div>
                      <span className="text-[10px] text-slate-500 font-bold tabular-nums">{pct}%</span>
                    </div>
                    <p className="text-[10px] text-slate-600 mt-1 tabular-nums">{r.tickets_sold} / {r.total_numeros} bilhetes · {formatBRL(parseFloat(r.revenue || 0))}</p>
                  </div>
                  <ChevronRight className="text-slate-600 group-hover/item:text-cyan-400 group-hover/item:translate-x-1 transition-all" size={20} />
                </div>
              );
            })}
            {(!data?.salesByRaffle || data.salesByRaffle.length === 0) && (
              <p className="text-slate-600 text-sm italic text-center py-8">Nenhum sorteio ativo</p>
            )}
          </div>
          <button
            onClick={() => navigate('/raffles')}
            className="mt-6 w-full py-5 text-sm font-black text-slate-400 hover:text-cyan-400 hover:bg-cyan-500/5 rounded-2xl transition-all border border-slate-800 hover:border-cyan-500/20"
          >
            Auditagem de Bilhetes
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── AppContent ───────────────────────────────────────────────────────────────

function AppContent({
  authState, setAuthState, teamAccount, setTeamAccount,
}: {
  authState: AuthState;
  setAuthState: (s: AuthState) => void;
  teamAccount: TeamAccount | null;
  setTeamAccount: (a: TeamAccount | null) => void;
}) {
  const navigate   = useNavigate();
  const location   = useLocation();
  const [tenant, setTenant]             = useState<TenantInfo | null>(null);
  const [adminInfo, setAdminInfo]       = useState<any>(null);
  const [sidebarOpen, setSidebarOpen]   = useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);

  useEffect(() => {
    if (authState === 'admin') {
      AdminMeService.get().then(d => { setTenant(d.tenant); setAdminInfo(d.admin); }).catch(() => {});
    }
  }, [authState]);

  useEffect(() => { setSidebarOpen(false); }, [location.pathname]);

  // ── Tela de login ──────────────────────────────────────────────────────────
  if (authState === 'login') {
    return (
      <LoginPage
        onLogin={(type, accountData) => {
          if (type === 'team' && accountData) {
            setTeamAccount(accountData);
            setAuthState('team');
            navigate('/wa-inbox');
          } else {
            setTeamAccount(null);
            setAuthState('admin');
            navigate('/');
          }
        }}
      />
    );
  }

  // ── Funcionário: vai direto para a Inbox (full-screen) ─────────────────────
  if (authState === 'team') {
    return (
      <WhatsAppInboxPage
        teamAccount={teamAccount}
        onTeamLogout={async () => {
          await fetch('/api/team/logout', { method: 'POST', credentials: 'include' });
          setTeamAccount(null);
          setAuthState('login');
        }}
      />
    );
  }

  // ── Admin: rotas full-screen ───────────────────────────────────────────────
  if (location.pathname === '/wa-inbox')      return <WhatsAppInboxPage />;
  if (location.pathname === '/wa-webhooks')   return <WhatsAppWebhooksPage />;
  if (location.pathname === '/cotacao/inbox') return <InboxPage />;

  // ── Admin: layout com sidebar ──────────────────────────────────────────────
  return (
    <div className="flex min-h-screen bg-black font-sans text-slate-200 selection:bg-cyan-500/30 selection:text-cyan-200">
      <Sidebar
        tenant={tenant}
        adminInfo={adminInfo}
        isOpen={sidebarOpen}
        onClose={() => setSidebarOpen(false)}
        collapsed={sidebarCollapsed}
        onToggleCollapse={() => setSidebarCollapsed(c => !c)}
      />
      <div className="flex-1 flex flex-col min-w-0">
        <header className="md:hidden flex items-center gap-4 px-4 h-14 bg-slate-950 border-b border-slate-900 sticky top-0 z-20">
          <button onClick={() => setSidebarOpen(true)} className="text-slate-400 hover:text-white"><Menu size={22} /></button>
          <span className="font-black text-white text-sm truncate flex-1">{tenant?.name || 'Admin'}</span>
          <NotificacoesBell />
        </header>
        <main className="flex-1 p-4 sm:p-8 md:p-16 overflow-y-auto relative">
          <div className="fixed inset-0 opacity-[0.03] pointer-events-none bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')]" />
          <div className="max-w-7xl mx-auto">
            <Routes>
              <Route path="/"               element={<Dashboard />} />
              <Route path="/raffles"         element={<RafflesPage />} />
              <Route path="/promotions"      element={<PromotionsPage />} />
              <Route path="/orders"          element={<OrdersPage />} />
              <Route path="/claims"          element={<ClaimsPage />} />
              <Route path="/clubs/odonto"    element={<ClubOdontoPage />} />
              <Route path="/clubs/medico"    element={<ClubMedicoPage />} />
              <Route path="/clubs/reports"   element={<ClubReportsPage />} />
              <Route path="/jobs"            element={<JobsPage />} />
              <Route path="/users"           element={<UsersPage />} />
              <Route path="/whatsapp"        element={<WhatsAppLogsPage />} />
              <Route path="/plugins"         element={<PluginsPage />} />
              <Route path="/admins"              element={<AdminUsersPage />} />
              <Route path="/settings"            element={<SettingsPage />} />
              {/* Módulo Cotação Online */}
              <Route path="/cotacao/pedidos"     element={<PedidosPage />} />
              <Route path="/cotacao/financeiro"  element={<FinanceiroPage />} />
              <Route path="/cotacao/catalogo"    element={<CatalogPage />} />
              <Route path="/cotacao/clientes"    element={<ClientesPage />} />
              <Route path="/cotacao/inbox"       element={<InboxPage />} />
              <Route path="/cotacao/relatorios"  element={<RelatorioPage />} />
              <Route path="/cotacao/separador"   element={<SeparadorPage />} />
              <Route path="/equipe"              element={<EquipePage />} />
            </Routes>
          </div>
        </main>
      </div>
    </div>
  );
}

// ─── App root ─────────────────────────────────────────────────────────────────

function App() {
  const [authState,   setAuthState]   = useState<AuthState>('checking');
  const [teamAccount, setTeamAccount] = useState<TeamAccount | null>(null);

  useEffect(() => {
    // 1. Tenta admin — usa /api/admin/me que retorna 200 só com token válido
    fetch('/api/admin/me', { credentials: 'include', headers: { Accept: 'application/json' } })
      .then(async r => {
        if (r.ok) {
          setAuthState('admin');
          return;
        }
        // 2. Tenta team
        const r2 = await fetch('/api/team/me', { credentials: 'include', headers: { Accept: 'application/json' } });
        if (r2.ok) {
          const d = await r2.json();
          setTeamAccount(d.account);
          setAuthState('team');
        } else {
          setAuthState('login');
        }
      })
      .catch(() => setAuthState('login'));

    const handleLogout = () => setAuthState('login');
    window.addEventListener('auth:logout', handleLogout);
    return () => window.removeEventListener('auth:logout', handleLogout);
  }, []);

  if (authState === 'checking') {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <div className="w-8 h-8 border-2 border-cyan-500 border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <Router basename="/admin-v2">
      <AppContent
        authState={authState}
        setAuthState={setAuthState}
        teamAccount={teamAccount}
        setTeamAccount={setTeamAccount}
      />
    </Router>
  );
}

export default App;
