/* components.jsx — App shell: Sidebar, TopBar, Logo, ProfileMenu */

// ============================================================
// White-label brand mark — uses the real DashM cube logo
// ============================================================
function BrandMark({ collapsed = false }) {
  return (
    <div className="flex items-center gap-2.5">
      <div className="relative w-9 h-9 rounded-[8px] flex items-center justify-center shrink-0">
        <img src="assets/dashm-logo.png" alt="DashM" className="w-9 h-9 object-contain" style={{ filter: "drop-shadow(0 0 12px var(--accent-glow))" }} />
      </div>
      {!collapsed && (
        <div className="leading-tight">
          <div className="text-[15px] font-semibold tracking-tight">
            Dash<span style={{ background: "linear-gradient(135deg, #6c4ee8, #4cd3e8)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent", backgroundClip: "text" }}>M</span><span className="text-[var(--fg-faint)]">·OS</span>
          </div>
          <div className="text-[9px] uppercase tracking-[0.16em] text-[var(--fg-faint)]">White-label · seu ERP conectado</div>
        </div>
      )}
    </div>
  );
}

// ============================================================
// Sidebar
// ============================================================
const NAV = [
  { section: "Operação", items: [
    { id: "home",       label: "Home",                icon: "layout-dashboard" },
    { id: "fechamento", label: "Fechamento do Dia",   icon: "sun-medium" },
    { id: "visao",      label: "Visão Geral",         icon: "store" },
    { id: "produtos",   label: "Análise de Produtos", icon: "package" },
  ]},
  { section: "Inteligência", items: [
    { id: "comparativo",label: "Comparativo Lojas",   icon: "table-2", badge: "NOVO" },
    { id: "forecast",   label: "Previsão de Vendas",  icon: "line-chart", badge: "WOW" },
    { id: "ruptura",    label: "Ruptura & Cobertura", icon: "shield-alert", badge: "WOW" },
    { id: "alerts",     label: "Alertas Reposição",   icon: "bell" },
  ]},
  { section: "Comercial", items: [
    { id: "carteira",   label: "Carteira de Pedidos", icon: "clipboard-list" },
    { id: "pedidos",    label: "Cadastro de Pedidos", icon: "file-plus-2", badge: "NOVO" },
    { id: "otb",        label: "Open to Buy (OTB)",   icon: "shopping-cart" },
    { id: "campanhas",  label: "Campanhas",           icon: "megaphone", count: 4 },
    { id: "vendedores", label: "Perf. Vendedores",    icon: "users" },
  ]},
];

const ADMIN_NAV = [
  { id: "plano",        label: "Plano & Cobrança", icon: "credit-card",  desc: "Plano atual, faturas e uso" },
  { id: "planosCatalog",label: "Catálogo de planos", icon: "sparkles",   desc: "Planos fixos + simulador" },
  { id: "acessos",      label: "Dashboard de acessos", icon: "activity", desc: "Uso, mapa de calor e usuários" },
  { id: "integracoes",  label: "Integrações",      icon: "plug",         desc: "Seu ERP, conectores e webhooks" },
  { id: "branding",     label: "Branding",         icon: "palette",      desc: "Logo, paleta e domínio próprio" },
  { id: "usuarios",     label: "Usuários",         icon: "users",        desc: "Convites e permissões" },
  { id: "seguranca",    label: "Segurança",        icon: "shield-check", desc: "MFA, SSO e auditoria" },
];

function AdminSidebar({ active, onNavigate, onBack, collapsed, onToggleCollapsed }) {
  return (
    <aside
      className={`relative h-screen shrink-0 border-r border-[var(--border)] bg-[var(--panel)] flex flex-col transition-all duration-200 ${collapsed ? "w-[68px]" : "w-[264px]"}`}
    >
      {/* Top — Back to dashboard (destacado) */}
      <div className={`flex items-center ${collapsed ? "justify-center px-2" : "justify-between px-3"} h-[60px] border-b border-[var(--border)] gap-2`}>
        {collapsed ? (
          <button
            onClick={onBack}
            className="w-10 h-10 rounded-xl flex items-center justify-center bg-[var(--accent-soft)] border border-[var(--accent)] text-[var(--accent)] hover:scale-105 hover:bg-[color-mix(in_oklch,var(--accent)_18%,transparent)] transition-all"
            title="Voltar para dashboard"
          >
            <Icon name="arrow-left" className="w-4 h-4" />
          </button>
        ) : (
          <button
            onClick={onBack}
            className="flex items-center gap-2 px-3 py-2 text-[12.5px] font-semibold rounded-xl bg-[var(--accent-soft)] border border-[var(--accent)] text-[var(--accent)] hover:bg-[color-mix(in_oklch,var(--accent)_18%,transparent)] hover:gap-2.5 transition-all group flex-1 min-w-0"
            title="Voltar para dashboard"
          >
            <Icon name="arrow-left" className="w-4 h-4 group-hover:-translate-x-0.5 transition-transform shrink-0" />
            <span className="truncate">Voltar para dashboard</span>
          </button>
        )}
        {!collapsed && (
          <button onClick={onToggleCollapsed} className="w-7 h-7 rounded-md text-[var(--fg-faint)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)] flex items-center justify-center shrink-0" title="Recolher">
            <Icon name="panel-left-close" className="w-4 h-4" />
          </button>
        )}
      </div>

      {collapsed && (
        <button onClick={onToggleCollapsed} className="mx-auto mt-2 w-9 h-9 rounded-lg text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)] flex items-center justify-center" title="Expandir">
          <Icon name="panel-left-open" className="w-4 h-4" />
        </button>
      )}

      {/* Section title */}
      {!collapsed && (
        <div className="px-4 pt-5 pb-2">
          <div className="flex items-center gap-2">
            <div className="w-9 h-9 rounded-lg bg-[var(--accent-soft)] border border-[var(--accent)]/30 flex items-center justify-center">
              <Icon name="shield-check" className="w-4 h-4 text-[var(--accent)]" />
            </div>
            <div className="leading-tight">
              <div className="text-[14px] font-semibold tracking-tight">Administração</div>
              <div className="text-[10px] uppercase tracking-[0.16em] text-[var(--fg-faint)]">Tenant Demo · Owner</div>
            </div>
          </div>
        </div>
      )}

      {/* Nav items */}
      <nav className="flex-1 overflow-y-auto px-2 py-3 space-y-0.5">
        {ADMIN_NAV.map((item) => {
          const isActive = active === item.id;
          return (
            <button
              key={item.id}
              onClick={() => onNavigate(item.id)}
              className={`relative w-full flex items-start gap-3 rounded-lg text-[13px] transition-colors group ${isActive ? "nav-active" : "text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)]"} ${collapsed ? "justify-center px-2 py-2.5" : "px-3 py-2.5"}`}
              title={collapsed ? item.label : undefined}
            >
              <Icon name={item.icon} className={`w-[18px] h-[18px] shrink-0 mt-0.5 ${isActive ? "text-[var(--accent)]" : ""}`} strokeWidth={1.8} />
              {!collapsed && (
                <div className="flex-1 text-left min-w-0">
                  <div className="font-medium truncate">{item.label}</div>
                  <div className="text-[10.5px] text-[var(--fg-faint)] truncate leading-tight mt-0.5">{item.desc}</div>
                </div>
              )}
            </button>
          );
        })}
      </nav>

      {/* Footer */}
      {!collapsed ? (
        <div className="m-3 p-3 rounded-xl border border-[var(--border)] bg-[var(--panel-2)]">
          <div className="flex items-center gap-2 mb-2">
            <Icon name="life-buoy" className="w-3.5 h-3.5 text-[var(--accent)]" />
            <span className="text-[11px] font-medium">Precisa de ajuda?</span>
          </div>
          <p className="text-[10.5px] text-[var(--fg-muted)] leading-snug">Customer Success disponível para configurar SSO, branding e onboarding.</p>
          <button className="mt-2 text-[11px] text-[var(--accent)] font-medium flex items-center gap-1 hover:underline">
            Falar com suporte <Icon name="arrow-right" className="w-3 h-3" />
          </button>
        </div>
      ) : (
        <div className="mx-auto mb-3 w-9 h-9 rounded-lg flex items-center justify-center text-[var(--fg-muted)] hover:text-[var(--accent)] hover:bg-[var(--panel-2)] cursor-pointer" title="Suporte">
          <Icon name="life-buoy" className="w-4 h-4" />
        </div>
      )}
    </aside>
  );
}

function Sidebar({ active, onNavigate, collapsed, onToggleCollapsed, frame = "desktop", onFrame }) {
  const FRAMES = [
    { id: "desktop", icon: "monitor",    label: "Desktop" },
    { id: "tablet",  icon: "tablet",     label: "Tablet" },
    { id: "mobile",  icon: "smartphone", label: "Mobile" },
  ];
  return (
    <aside
      className={`relative h-screen shrink-0 border-r border-[var(--border)] bg-[var(--panel)] flex flex-col transition-all duration-200 ${collapsed ? "w-[68px]" : "w-[244px]"}`}
    >
      {/* Logo block */}
      <div className={`flex items-center ${collapsed ? "justify-center" : "justify-between"} px-3.5 h-[60px] border-b border-[var(--border)]`}>
        <BrandMark collapsed={collapsed} />
        {!collapsed && (
          <button onClick={onToggleCollapsed} className="w-7 h-7 rounded-md text-[var(--fg-faint)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)] flex items-center justify-center" title="Recolher">
            <Icon name="panel-left-close" className="w-4 h-4" />
          </button>
        )}
      </div>

      {/* Collapsed expand button */}
      {collapsed && (
        <button onClick={onToggleCollapsed} className="mx-auto mt-2 w-9 h-9 rounded-lg text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)] flex items-center justify-center" title="Expandir">
          <Icon name="panel-left-open" className="w-4 h-4" />
        </button>
      )}

      {/* Nav */}
      <nav className="flex-1 overflow-y-auto px-2 py-3 space-y-4">
        {NAV.map((group) => (
          <div key={group.section}>
            {!collapsed && (
              <div className="px-3 pt-1 pb-1.5 text-[9px] uppercase tracking-[0.18em] text-[var(--fg-faint)] font-semibold">{group.section}</div>
            )}
            <div className="space-y-0.5">
              {group.items.map((item) => {
                const isActive = active === item.id;
                return (
                  <button
                    key={item.id}
                    onClick={() => onNavigate(item.id)}
                    className={`relative w-full flex items-center gap-3 px-3 py-2 rounded-lg text-[13px] font-medium transition-colors ${isActive ? "nav-active" : "text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)]"} ${collapsed ? "justify-center" : ""}`}
                    title={collapsed ? item.label : undefined}
                  >
                    <Icon name={item.icon} className={`w-[18px] h-[18px] shrink-0 ${isActive ? "text-[var(--accent)]" : ""}`} strokeWidth={1.8} />
                    {!collapsed && (
                      <>
                        <span className="flex-1 text-left truncate">{item.label}</span>
                        {item.badge && <span className="badge badge-accent text-[8px] px-1.5 py-0.5">{item.badge}</span>}
                        {item.count && <span className="badge text-[9px] px-1.5 py-0.5">{item.count}</span>}
                      </>
                    )}
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </nav>

      {/* Footer — Viewport toggle + cartao de integracao do ERP */}
      {!collapsed ? (
        <div className="px-3 space-y-2">
          {/* Viewport toggle — Desktop · Tablet · Mobile */}
          <div className="p-1 rounded-xl border border-[var(--border)] bg-[var(--panel-2)] flex gap-0.5">
            {FRAMES.map((f) => {
              const isActive = frame === f.id;
              return (
                <button
                  key={f.id}
                  onClick={() => onFrame && onFrame(f.id)}
                  className={`flex-1 flex flex-col items-center gap-1 py-2 rounded-lg transition-colors ${isActive ? "bg-[var(--accent-soft)] text-[var(--accent)]" : "text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel)]"}`}
                  title={f.label}
                >
                  <Icon name={f.icon} className="w-3.5 h-3.5" />
                  <span className="text-[9.5px] font-medium">{f.label}</span>
                </button>
              );
            })}
          </div>
          <div className="p-3 rounded-xl border border-[var(--border)] bg-gradient-to-br from-[var(--panel-2)] to-[var(--panel)] relative overflow-hidden">
            <div className="absolute -top-8 -right-8 w-20 h-20 rounded-full bg-[var(--accent-glow)] blur-2xl" />
            <Tooltip
              content={
                <div>
                  <div className="font-semibold text-[12px] mb-1">Integração com o seu ERP</div>
                  <div className="text-[var(--fg-muted)] space-y-0.5">
                    <div>Última sincronização: <span className="font-mono">há 2 min</span></div>
                    <div>12 entidades em sincronia · 1,2M registros/24h</div>
                    <div>Health check: <span className="text-[var(--pos)]">100%</span></div>
                  </div>
                </div>
              }
              width={280}
            >
              <div className="cursor-help">
                <div className="flex items-center gap-2 mb-1.5 relative">
                  <div className="w-1.5 h-1.5 rounded-full bg-[var(--accent)] pulse-glow" />
                  <span className="text-[10px] uppercase tracking-[0.14em] font-semibold text-[var(--accent)]">Conectado</span>
                </div>
                <div className="text-[12px] font-medium relative">Seu ERP · conectado</div>
                <div className="text-[10px] text-[var(--fg-muted)] mt-0.5 relative">Sincronizado há 2 min</div>
              </div>
            </Tooltip>
          </div>
        </div>
      ) : (
        <div className="flex flex-col items-center gap-1.5 mb-3 px-1">
          {FRAMES.map((f) => {
            const isActive = frame === f.id;
            return (
              <button
                key={f.id}
                onClick={() => onFrame && onFrame(f.id)}
                className={`w-9 h-9 rounded-lg flex items-center justify-center transition-colors ${isActive ? "bg-[var(--accent-soft)] border border-[var(--accent)] text-[var(--accent)]" : "border border-[var(--border)] text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)]"}`}
                title={f.label}
              >
                <Icon name={f.icon} className="w-4 h-4" />
              </button>
            );
          })}
          <div className="w-9 h-9 mt-1 rounded-lg flex items-center justify-center bg-[var(--accent-soft)] border border-[var(--accent)]/30" title="ERP conectado">
            <div className="w-2 h-2 rounded-full bg-[var(--accent)] pulse-glow" />
          </div>
        </div>
      )}

      {/* Version */}
      {!collapsed && (
        <div className="px-4 py-3 text-[10px] uppercase tracking-wider text-[var(--fg-faint)] border-t border-[var(--border)] flex items-center justify-between">
          <span>DashM® MVP</span>
          <span className="font-mono">v0.9.0</span>
        </div>
      )}
    </aside>
  );
}

// ============================================================
// Theme toggle
// ============================================================
function ThemeToggle({ theme, onChange }) {
  return (
    <button
      onClick={() => onChange(theme === "dark" ? "light" : "dark")}
      className="relative w-9 h-9 rounded-lg flex items-center justify-center border border-[var(--border)] text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)] transition-colors"
      title={theme === "dark" ? "Mudar para claro" : "Mudar para escuro"}
    >
      <Icon name={theme === "dark" ? "sun" : "moon"} className="w-4 h-4" />
    </button>
  );
}

// ============================================================
// TopBar — search, period, theme, profile
// ============================================================
function TopBar({ theme, onTheme, onLogout, periodLabel, onTogglePeriod, screenTitle, screenIcon, onNavigate, isAdmin, onMobilePreview }) {
  const [profileOpen, setProfileOpen] = useState(false);
  const [searchFocused, setSearchFocused] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [searchActiveIdx, setSearchActiveIdx] = useState(0);
  const [notifOpen, setNotifOpen] = useState(false);
  const profRef = useRef(null);
  const notifRef = useRef(null);
  const searchInputRef = useRef(null);
  const searchBoxRef = useRef(null);

  // Recentes mockados (simulam histórico do usuário)
  const RECENTES = [
    { type: "sku",     id: "SKU-1042", label: "SKU-1042 · Item Padrão A",      icon: "package", target: "produtos" },
    { type: "filial",  id: "F03",      label: "Filial 03 · Centro-Oeste",       icon: "store",   target: "visao" },
    { type: "campanha",id: "camp-1",   label: "Campanha Liquidação Sazonal",   icon: "megaphone", target: "campanhas" },
  ];
  // Sugestões fixas (atalhos de navegação rápida)
  const SUGESTOES = [
    { type: "tela",   id: "fechamento",  label: "Fechamento do Dia",        icon: "sun-medium",   target: "fechamento", subtitle: "Resumo executivo + meta diária" },
    { type: "tela",   id: "ruptura",     label: "Ruptura & Cobertura",      icon: "shield-alert", target: "ruptura",    subtitle: "Monitor de risco ao vivo" },
    { type: "tela",   id: "previsao",    label: "Previsão de Vendas",       icon: "line-chart",   target: "forecast",   subtitle: "IA · próximas 4-12 semanas" },
    { type: "tela",   id: "comparativo", label: "Comparativo Lojas",        icon: "table-2",      target: "comparativo",subtitle: "Cross-filial · vendas, TKM, PA, MKP" },
    { type: "sku",    id: "SKU-4012",   label: "SKU-4012 · Item Top F",     icon: "package",     target: "produtos",   subtitle: "Curva A · giro alto" },
    { type: "sku",    id: "SKU-3309",   label: "SKU-3309 · Item Sazonal E", icon: "package",     target: "produtos",   subtitle: "Sazonalidade pico em jun" },
  ];

  // Filtra sugestões e recentes pela query
  const filterByQuery = (arr) => {
    if (!searchQuery.trim()) return arr;
    const q = searchQuery.toLowerCase();
    return arr.filter(item => item.label.toLowerCase().includes(q) || (item.subtitle || "").toLowerCase().includes(q));
  };
  const recentesFiltradas = filterByQuery(RECENTES);
  const sugestoesFiltradas = filterByQuery(SUGESTOES);
  const allResults = [...recentesFiltradas, ...sugestoesFiltradas];

  const handleSelectResult = (item) => {
    if (item.target && onNavigate) {
      onNavigate(item.target);
    }
    setSearchFocused(false);
    setSearchQuery("");
    setSearchActiveIdx(0);
    if (searchInputRef.current) searchInputRef.current.blur();
  };

  // ⌘K / Ctrl+K — abre busca; ESC fecha; arrows navegam; Enter seleciona
  useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        if (searchInputRef.current) {
          searchInputRef.current.focus();
          setSearchFocused(true);
        }
        return;
      }
      if (!searchFocused) return;
      if (e.key === "Escape") {
        setSearchFocused(false);
        searchInputRef.current?.blur();
      } else if (e.key === "ArrowDown") {
        e.preventDefault();
        setSearchActiveIdx(i => Math.min(allResults.length - 1, i + 1));
      } else if (e.key === "ArrowUp") {
        e.preventDefault();
        setSearchActiveIdx(i => Math.max(0, i - 1));
      } else if (e.key === "Enter") {
        e.preventDefault();
        const item = allResults[searchActiveIdx];
        if (item) handleSelectResult(item);
      }
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [searchFocused, allResults, searchActiveIdx]);

  // Notificações mock — deterministic, simulando alertas operacionais comuns
  const notifications = [
    { id: 1, type: "warn", icon: "shield-alert", title: "Ruptura crítica em Filial 05", desc: "12 SKUs zerados afetando R$ 87k este mês", time: "há 8 min", unread: true },
    { id: 2, type: "pos",  icon: "trending-up",  title: "Meta diária batida — Filial 01", desc: "+18% vs. ontem · 105% da meta",          time: "há 1h",   unread: true },
    { id: 3, type: "info", icon: "package",      title: "Forecast atualizado",            desc: "Modelo retreinado com dados de ontem (94% conf.)", time: "há 2h",   unread: true },
    { id: 4, type: "neg",  icon: "trending-down",title: "Atenção — Filial 05 abaixo de 80%", desc: "Performance 68% da meta · plano de recuperação sugerido", time: "ontem", unread: false },
    { id: 5, type: "info", icon: "users",        title: "Operadora B subiu pro top 3",    desc: "+12,3% vs. semana anterior",                time: "ontem",   unread: false },
  ];
  const unreadCount = notifications.filter(n => n.unread).length;

  useEffect(() => {
    const onClick = (e) => {
      if (profRef.current && !profRef.current.contains(e.target)) setProfileOpen(false);
      if (notifRef.current && !notifRef.current.contains(e.target)) setNotifOpen(false);
    };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);

  const NOTIF_COLORS = {
    warn: { bg: "color-mix(in oklch, var(--warn) 12%, transparent)", fg: "var(--warn)" },
    neg:  { bg: "color-mix(in oklch, var(--neg) 12%, transparent)",  fg: "var(--neg)" },
    pos:  { bg: "color-mix(in oklch, var(--pos) 12%, transparent)",  fg: "var(--pos)" },
    info: { bg: "color-mix(in oklch, var(--accent) 12%, transparent)", fg: "var(--accent)" },
  };

  return (
    <header className="h-[60px] shrink-0 border-b border-[var(--border)] bg-[var(--panel)] flex items-center px-5 gap-4">
      {/* Screen title */}
      <div className="flex items-center gap-2.5 min-w-0">
        {screenIcon && <Icon name={screenIcon} className="w-4 h-4 text-[var(--fg-muted)]" />}
        <div className="text-[15px] font-semibold tracking-tight truncate">{screenTitle}</div>
      </div>

      <div className="flex-1" />

      {/* Search global ⌘K */}
      <div ref={searchBoxRef} className={`relative hidden md:block transition-all ${searchFocused ? "w-[380px]" : "w-[220px]"}`}>
        <Icon name="search" className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-[var(--fg-faint)] z-10" />
        <input
          ref={searchInputRef}
          type="text"
          value={searchQuery}
          onChange={(e) => { setSearchQuery(e.target.value); setSearchActiveIdx(0); }}
          placeholder="Buscar SKU, pedido, loja…"
          onFocus={() => setSearchFocused(true)}
          onBlur={() => setTimeout(() => setSearchFocused(false), 150)} // delay pra dar tempo do click no item
          className="w-full bg-[var(--panel-2)] border border-[var(--border)] rounded-lg pl-8 pr-12 py-2 text-[12.5px] placeholder:text-[var(--fg-faint)] focus:outline-none focus:border-[var(--accent)] focus:shadow-[0_0_0_3px_var(--accent-glow)] transition-all"
        />
        <kbd className="absolute right-2.5 top-1/2 -translate-y-1/2 text-[9px] font-mono px-1.5 py-0.5 rounded border border-[var(--border)] bg-[var(--panel)] text-[var(--fg-faint)] z-10">⌘K</kbd>

        {/* Dropdown resultados */}
        {searchFocused && (
          <div className="absolute top-full mt-2 left-0 right-0 panel-hi shadow-[var(--shadow-lg)] z-50 fade-in overflow-hidden max-h-[400px] overflow-y-auto">
            {/* Recentes */}
            {recentesFiltradas.length > 0 && (
              <div>
                <div className="px-3 py-2 text-[10px] uppercase tracking-wider text-[var(--fg-muted)] font-semibold border-b border-[var(--border)] flex items-center gap-1.5">
                  <Icon name="history" className="w-3 h-3" /> Recentes
                </div>
                {recentesFiltradas.map((item, idx) => {
                  const isActive = idx === searchActiveIdx;
                  return (
                    <button
                      key={item.id}
                      onMouseDown={(e) => { e.preventDefault(); handleSelectResult(item); }}
                      onMouseEnter={() => setSearchActiveIdx(idx)}
                      className={`w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors ${isActive ? "bg-[var(--accent-soft)]" : "hover:bg-[var(--panel-2)]"}`}
                    >
                      <Icon name={item.icon} className={`w-3.5 h-3.5 shrink-0 ${isActive ? "text-[var(--accent)]" : "text-[var(--fg-muted)]"}`} />
                      <span className="text-[12.5px] flex-1 truncate">{item.label}</span>
                      <span className="text-[9px] uppercase text-[var(--fg-faint)] tracking-wider">{item.type}</span>
                    </button>
                  );
                })}
              </div>
            )}

            {/* Sugestões */}
            {sugestoesFiltradas.length > 0 && (
              <div>
                <div className="px-3 py-2 text-[10px] uppercase tracking-wider text-[var(--fg-muted)] font-semibold border-b border-t border-[var(--border)] flex items-center gap-1.5">
                  <Icon name="sparkles" className="w-3 h-3" /> Sugestões
                </div>
                {sugestoesFiltradas.map((item, idx) => {
                  const totalIdx = recentesFiltradas.length + idx;
                  const isActive = totalIdx === searchActiveIdx;
                  return (
                    <button
                      key={item.id}
                      onMouseDown={(e) => { e.preventDefault(); handleSelectResult(item); }}
                      onMouseEnter={() => setSearchActiveIdx(totalIdx)}
                      className={`w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors ${isActive ? "bg-[var(--accent-soft)]" : "hover:bg-[var(--panel-2)]"}`}
                    >
                      <div className={`w-7 h-7 rounded-md flex items-center justify-center shrink-0 ${isActive ? "bg-[var(--accent)] text-white" : "bg-[var(--panel-2)] text-[var(--fg-muted)]"}`}>
                        <Icon name={item.icon} className="w-3.5 h-3.5" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="text-[12.5px] font-medium truncate">{item.label}</div>
                        {item.subtitle && <div className="text-[10px] text-[var(--fg-muted)] truncate">{item.subtitle}</div>}
                      </div>
                      {isActive && <span className="text-[9px] font-mono text-[var(--fg-faint)]">↵</span>}
                    </button>
                  );
                })}
              </div>
            )}

            {allResults.length === 0 && (
              <div className="px-3 py-6 text-center">
                <Icon name="search-x" className="w-5 h-5 mx-auto text-[var(--fg-faint)] mb-1.5" />
                <div className="text-[11.5px] text-[var(--fg-muted)]">Nenhum resultado pra <span className="font-mono text-[var(--fg)]">"{searchQuery}"</span></div>
                <div className="text-[10px] text-[var(--fg-faint)] mt-1">Tente outro termo ou navegue pelo menu lateral</div>
              </div>
            )}

            {/* Footer com dicas de atalho */}
            <div className="px-3 py-2 border-t border-[var(--border)] bg-[var(--panel-2)]/40 flex items-center justify-between text-[9.5px] text-[var(--fg-faint)]">
              <div className="flex items-center gap-2">
                <span className="flex items-center gap-1"><kbd className="px-1 py-0.5 rounded border border-[var(--border)] bg-[var(--panel)] font-mono">↑↓</kbd> navegar</span>
                <span className="flex items-center gap-1"><kbd className="px-1 py-0.5 rounded border border-[var(--border)] bg-[var(--panel)] font-mono">↵</kbd> abrir</span>
                <span className="flex items-center gap-1"><kbd className="px-1 py-0.5 rounded border border-[var(--border)] bg-[var(--panel)] font-mono">esc</kbd> fechar</span>
              </div>
              <span>{allResults.length} resultado{allResults.length !== 1 ? "s" : ""}</span>
            </div>
          </div>
        )}
      </div>

      {/* Period toggle */}
      <button
        onClick={onTogglePeriod}
        className="hidden lg:flex items-center gap-2 px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--panel-2)] hover:bg-[var(--panel-hi)] transition-colors text-[12px]"
      >
        <Icon name="calendar-range" className="w-3.5 h-3.5 text-[var(--fg-muted)]" />
        <span className="font-medium">{periodLabel}</span>
        <Icon name="chevron-down" className="w-3 h-3 text-[var(--fg-faint)]" />
      </button>

      {/* Notifications */}
      <div className="relative" ref={notifRef}>
        <button
          onClick={() => setNotifOpen((o) => !o)}
          className="relative w-9 h-9 rounded-lg flex items-center justify-center border border-[var(--border)] text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)] transition-colors"
        >
          <Icon name="bell" className="w-4 h-4" />
          {unreadCount > 0 && (
            <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 rounded-full bg-[var(--accent)] text-white text-[9px] font-bold flex items-center justify-center pulse-glow">
              {unreadCount}
            </span>
          )}
        </button>

        {notifOpen && (
          <div className="absolute right-0 top-full mt-2 w-[360px] panel-hi shadow-[var(--shadow-lg)] fade-in z-30 overflow-hidden">
            <div className="px-4 py-3 border-b border-[var(--border)] flex items-center justify-between">
              <div>
                <div className="text-[13px] font-semibold">Notificações</div>
                <div className="text-[10.5px] text-[var(--fg-muted)]">{unreadCount} não lidas · {notifications.length} total</div>
              </div>
              <button className="text-[10.5px] text-[var(--accent)] hover:underline font-medium">
                Marcar todas como lidas
              </button>
            </div>
            <div className="max-h-[400px] overflow-y-auto">
              {notifications.map((n) => {
                const c = NOTIF_COLORS[n.type] || NOTIF_COLORS.info;
                return (
                  <button
                    key={n.id}
                    className={`w-full px-4 py-3 flex items-start gap-3 hover:bg-[var(--panel-2)] transition-colors text-left border-b border-[var(--border)] last:border-b-0 ${n.unread ? "" : "opacity-65"}`}
                  >
                    <div
                      className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0"
                      style={{ background: c.bg, color: c.fg }}
                    >
                      <Icon name={n.icon} className="w-4 h-4" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <div className="text-[12px] font-medium truncate">{n.title}</div>
                        {n.unread && <span className="w-1.5 h-1.5 rounded-full bg-[var(--accent)] shrink-0" />}
                      </div>
                      <div className="text-[10.5px] text-[var(--fg-muted)] mt-0.5 leading-snug">{n.desc}</div>
                      <div className="text-[9.5px] text-[var(--fg-faint)] mt-1 font-mono uppercase tracking-wider">{n.time}</div>
                    </div>
                  </button>
                );
              })}
            </div>
            <div className="px-4 py-2.5 border-t border-[var(--border)] bg-[var(--panel-2)]">
              <button className="w-full text-[11px] text-[var(--fg-muted)] hover:text-[var(--fg)] flex items-center justify-center gap-1.5">
                Ver todas as notificações
                <Icon name="arrow-right" className="w-3 h-3" />
              </button>
            </div>
          </div>
        )}
      </div>

      <ThemeToggle theme={theme} onChange={onTheme} />

      {/* Profile menu */}
      <div className="relative" ref={profRef}>
        <button
          onClick={() => setProfileOpen((o) => !o)}
          className="flex items-center gap-2 pl-1 pr-2 py-1 rounded-lg border border-transparent hover:border-[var(--border)] hover:bg-[var(--panel-2)] transition-colors"
        >
          {/* Avatar + coroinha de Studio sob medida (canto superior direito) */}
          <div className="relative">
            <div className="w-7 h-7 rounded-full bg-gradient-to-br from-[var(--accent)] to-[var(--accent-2)] flex items-center justify-center text-[11px] font-semibold text-[#ffffff]">DM</div>
            <div
              className="absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full flex items-center justify-center text-white shadow-[0_2px_6px_-1px_rgba(34,211,238,0.6)]"
              style={{ background: "linear-gradient(135deg, var(--accent-2) 0%, var(--accent) 100%)", border: "1.5px solid var(--panel)" }}
              title="DashM Studio · sob medida"
            >
              <Icon name="crown" className="w-2 h-2" fill="currentColor" />
            </div>
          </div>
          <div className="hidden lg:block leading-tight text-left">
            <div className="text-[12px] font-medium flex items-center gap-1">
              Operador
              <Icon name="crown" className="w-3 h-3 text-[var(--accent-2)]" fill="currentColor" />
            </div>
            <div className="text-[10px] text-[var(--fg-faint)]">Studio · admin</div>
          </div>
          <Icon name="chevron-down" className="w-3 h-3 text-[var(--fg-faint)] hidden lg:block" />
        </button>

        {profileOpen && (
          <div className="absolute right-0 top-full mt-2 w-[260px] panel-hi shadow-[var(--shadow-lg)] fade-in z-30 overflow-hidden">
            <div className="px-3.5 py-3 border-b border-[var(--border)]">
              <div className="text-[12px] font-medium flex items-center gap-1.5">
                Operador Demo
                <Icon name="crown" className="w-3.5 h-3.5 text-[var(--accent-2)]" fill="currentColor" />
              </div>
              <div className="text-[11px] text-[var(--fg-muted)]">demo@dashm.example</div>
              <div className="mt-2 flex items-center gap-1.5 flex-wrap">
                <span className="badge badge-accent">Tenant Demo</span>
                <span
                  className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider text-white"
                  style={{ background: "linear-gradient(135deg, var(--accent-2) 0%, var(--accent) 100%)" }}
                >
                  <Icon name="crown" className="w-2.5 h-2.5" fill="currentColor" />
                  DashM Studio
                </span>
                <span className="badge text-[9px]" style={{ borderColor: "var(--accent-2)", color: "var(--accent-2)" }}>SOB MEDIDA</span>
              </div>
            </div>
            {[
              { icon: "user", label: "Meu perfil", target: null },
              { icon: "smartphone", label: "Ver versão mobile", action: "mobile" },
              { icon: "shield-check", label: "Administração", target: "admin", badge: isAdmin ? null : "owner" },
              { icon: "key-round", label: "API & Webhooks", target: null },
              { icon: "life-buoy", label: "Suporte", target: null },
            ].map((it) => (
              <button key={it.label} onClick={() => {
                if (it.action === "mobile") { onMobilePreview(); setProfileOpen(false); }
                else if (it.target) { onNavigate(it.target); setProfileOpen(false); }
              }} className="w-full flex items-center gap-2.5 px-3.5 py-2 text-[12.5px] text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)] transition-colors">
                <Icon name={it.icon} className="w-3.5 h-3.5" />
                <span className="flex-1 text-left">{it.label}</span>
                {it.badge && <span className="badge text-[9px]">{it.badge}</span>}
              </button>
            ))}

            {/* Theme switcher inside profile menu */}
            <div className="px-3.5 py-2.5 border-t border-[var(--border)] flex items-center gap-2.5">
              <Icon name={theme === "dark" ? "moon" : "sun"} className="w-3.5 h-3.5 text-[var(--fg-muted)]" />
              <span className="text-[12.5px] text-[var(--fg-muted)] flex-1">Tema</span>
              <div className="inline-flex p-0.5 rounded-lg border border-[var(--border)] bg-[var(--panel-2)] gap-0.5">
                <button onClick={() => onTheme("light")} className={`px-2.5 py-1 rounded-md text-[11px] font-medium flex items-center gap-1 transition-all ${theme === "light" ? "bg-[var(--panel-hi)] text-[var(--fg)] shadow-[var(--shadow-sm)]" : "text-[var(--fg-muted)] hover:text-[var(--fg)]"}`}>
                  <Icon name="sun" className="w-3 h-3" /> Claro
                </button>
                <button onClick={() => onTheme("dark")} className={`px-2.5 py-1 rounded-md text-[11px] font-medium flex items-center gap-1 transition-all ${theme === "dark" ? "bg-[var(--panel-hi)] text-[var(--fg)] shadow-[var(--shadow-sm)]" : "text-[var(--fg-muted)] hover:text-[var(--fg)]"}`}>
                  <Icon name="moon" className="w-3 h-3" /> Escuro
                </button>
              </div>
            </div>
            <button onClick={onLogout} className="w-full flex items-center gap-2.5 px-3.5 py-2.5 text-[12.5px] text-[var(--neg)] hover:bg-[color-mix(in_oklch,var(--neg)_10%,transparent)] transition-colors border-t border-[var(--border)]">
              <Icon name="log-out" className="w-3.5 h-3.5" />
              Sair
            </button>
          </div>
        )}
      </div>
    </header>
  );
}

// ============================================================
// Shell layout
// ============================================================
function Shell({ active, onNavigate, theme, onTheme, onLogout, screenTitle, screenIcon, frame, onFrame, adminTab, onAdminTab, children }) {
  const [collapsed, setCollapsed] = useState(false);
  const [period, setPeriod] = useState(0);
  const periods = ["Este mês", "Mês anterior", "Últimos 30 dias", "Trimestre", "YTD"];
  const isAdmin = active === "admin";
  // Floating CTAs: aparecem na maioria das telas dashboard, omitir só no Admin pra
  // não competir com sidebar/conteúdo administrativo.
  const showFloatingCTAs = !isAdmin;
  return (
    <div className="flex h-screen overflow-hidden bg-[var(--bg)] text-[var(--fg)]">
      {isAdmin ? (
        <AdminSidebar
          active={adminTab}
          onNavigate={onAdminTab}
          onBack={() => onNavigate("home")}
          collapsed={collapsed}
          onToggleCollapsed={() => setCollapsed((c) => !c)}
        />
      ) : (
        <Sidebar active={active} onNavigate={onNavigate} collapsed={collapsed} onToggleCollapsed={() => setCollapsed((c) => !c)} frame={frame} onFrame={onFrame} />
      )}
      <div className="flex-1 flex flex-col min-w-0">
        <TopBar
          theme={theme}
          onTheme={onTheme}
          onLogout={onLogout}
          onNavigate={onNavigate}
          isAdmin={isAdmin}
          onMobilePreview={() => onFrame && onFrame("mobile")}
          periodLabel={periods[period]}
          onTogglePeriod={() => setPeriod((p) => (p + 1) % periods.length)}
          screenTitle={screenTitle}
          screenIcon={screenIcon}
        />
        <main className="flex-1 overflow-y-auto">
          <div className="max-w-[1480px] mx-auto px-6 py-6 fade-in" key={active + ":" + (adminTab || "")}>
            {children}
          </div>
        </main>
      </div>
      {showFloatingCTAs && (
        <FloatingCTAs
          onSeePlans={() => {
            onNavigate("admin");
            onAdminTab && onAdminTab("planosCatalog");
          }}
        />
      )}
    </div>
  );
}

// ============================================================
// FloatingCTAs — conversão: Ver planos + WhatsApp piscando no canto inferior direito
// Aparece em todas as telas dashboard (não no Admin pra não poluir).
// ============================================================
function FloatingCTAs({ onSeePlans }) {
  const whatsUrl = (typeof window !== "undefined" && window.buildWhatsAppUrl)
    ? window.buildWhatsAppUrl("Olá! Estou demonstrando o DashM e quero falar com vocês.")
    : "https://wa.me/5542999602137";
  const WLogo = (typeof window !== "undefined" && window.WhatsAppLogo) ? window.WhatsAppLogo : null;
  return (
    <div className="fixed bottom-5 right-5 z-40 flex flex-col items-center gap-3 pointer-events-none">
      {/* WhatsApp em CIMA — logo oficial pulando alternado com Ver planos */}
      <a
        href={whatsUrl}
        target="_blank"
        rel="noopener noreferrer"
        className="pointer-events-auto floating-whatsapp inline-flex items-center justify-center w-16 h-16 rounded-full text-white shadow-[0_8px_28px_-4px_rgba(37,211,102,0.55)] hover:shadow-[0_14px_38px_-4px_rgba(37,211,102,0.75)] transition-shadow"
        style={{ background: "linear-gradient(135deg, #25D366 0%, #1da851 100%)" }}
        title="Falar no WhatsApp"
      >
        {WLogo ? <WLogo size={32} /> : <Icon name="message-circle" className="w-7 h-7" strokeWidth={2.2} />}
      </a>

      {/* Ver planos EMBAIXO — pill accent comprido, base visual da coluna */}
      <button
        onClick={onSeePlans}
        className="pointer-events-auto floating-verplanos inline-flex items-center gap-2 px-5 py-3 rounded-full text-white text-[13px] font-bold tracking-tight shadow-[0_8px_28px_-4px_var(--accent-glow)] hover:shadow-[0_14px_38px_-4px_var(--accent-glow)] transition-shadow"
        style={{ background: "linear-gradient(135deg, var(--accent) 0%, var(--accent-2) 100%)" }}
      >
        <Icon name="sparkles" className="w-4 h-4" fill="currentColor" />
        Ver planos
        <Icon name="arrow-right" className="w-4 h-4" />
      </button>
    </div>
  );
}

Object.assign(window, { BrandMark, Sidebar, TopBar, ThemeToggle, Shell, NAV });
