/* 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 · Mitryus core</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: "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: "Mitryus, 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 */}
      <div className={`flex items-center ${collapsed ? "justify-center px-2" : "justify-between px-3.5"} h-[60px] border-b border-[var(--border)] gap-2`}>
        {collapsed ? (
          <button onClick={onBack} className="w-9 h-9 rounded-lg flex items-center justify-center text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)]" title="Voltar para dashboard">
            <Icon name="arrow-left" className="w-4 h-4" />
          </button>
        ) : (
          <button onClick={onBack} className="flex items-center gap-2 text-[12px] text-[var(--fg-muted)] hover:text-[var(--fg)] transition-colors min-w-0">
            <Icon name="arrow-left" className="w-3.5 h-3.5" />
            <span>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" 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, onMobilePreview }) {
  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 — Mitryus integration card */}
      {!collapsed ? (
        <div className="px-3 space-y-2">
          <button
            onClick={onMobilePreview}
            className="w-full flex items-center gap-2.5 px-3 py-2.5 rounded-xl border border-[var(--accent)] bg-[var(--accent-soft)] hover:bg-[color-mix(in_oklch,var(--accent)_18%,transparent)] transition-all text-[12px] font-medium text-[var(--accent)] group"
          >
            <Icon name="smartphone" className="w-4 h-4" />
            <span className="flex-1 text-left">Ver versão mobile</span>
            <Icon name="arrow-up-right" className="w-3 h-3" />
          </button>
          <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 Mitryus</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">Mitryus · ERP Core</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-2 mb-3 px-1">
          <button onClick={onMobilePreview} className="w-9 h-9 rounded-lg bg-[var(--accent-soft)] border border-[var(--accent)] text-[var(--accent)] flex items-center justify-center hover:scale-105 transition-transform" title="Ver versão mobile">
            <Icon name="smartphone" className="w-4 h-4" />
          </button>
          <div className="w-9 h-9 rounded-lg flex items-center justify-center bg-[var(--accent-soft)] border border-[var(--accent)]/30" title="Mitryus 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 profRef = useRef(null);
  useEffect(() => {
    const onClick = (e) => { if (profRef.current && !profRef.current.contains(e.target)) setProfileOpen(false); };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);

  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 */}
      <div className={`relative hidden md:block transition-all ${searchFocused ? "w-[320px]" : "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)]" />
        <input
          type="text"
          placeholder="Buscar SKU, pedido, loja…"
          onFocus={() => setSearchFocused(true)}
          onBlur={() => setSearchFocused(false)}
          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)]">⌘K</kbd>
      </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 */}
      <button 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" />
        <span className="absolute top-1.5 right-1.5 w-2 h-2 rounded-full bg-[var(--accent)] pulse-glow" />
      </button>

      <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"
        >
          <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="hidden lg:block leading-tight text-left">
            <div className="text-[12px] font-medium">Operador</div>
            <div className="text-[10px] text-[var(--fg-faint)]">Demo · 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-[240px] 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">Operador Demo</div>
              <div className="text-[11px] text-[var(--fg-muted)]">demo@dashm.example</div>
              <div className="mt-2 flex items-center gap-1.5"><span className="badge badge-accent">Tenant Demo</span><span className="badge">Plano Pro</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, onMobilePreview, 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";
  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)} onMobilePreview={onMobilePreview} />
      )}
      <div className="flex-1 flex flex-col min-w-0">
        <TopBar
          theme={theme}
          onTheme={onTheme}
          onLogout={onLogout}
          onNavigate={onNavigate}
          isAdmin={isAdmin}
          onMobilePreview={onMobilePreview}
          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>
    </div>
  );
}

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