/* Wood OS — Sidebar, Header, AppLayout */
const { useState: useStateChrome, useEffect: useEffectChrome, useRef: useRefChrome } = React;

/* ============================================================
   SIDEBAR
   ============================================================ */
const NAV_GROUPS = [
  {
    label: "Operacional",
    items: [
      { route: "dashboard", icon: "home", label: "Painel Geral" },
      { route: "requests", icon: "inbox", label: "Solicitações", badge: 8 },
      { route: "new-request", icon: "plus-circle", label: "Nova Solicitação", primary: true },
    ],
  },
  {
    label: "Produção",
    items: [
      { route: "projects", icon: "hammer", label: "Obras" },
      { route: "teams", icon: "users", label: "Equipes" },
      { route: "inventory", icon: "package", label: "Almoxarifado", badge: 3 },
    ],
  },
  {
    label: "Logística",
    items: [
      { route: "vehicles", icon: "truck", label: "Veículos" },
      { route: "logistics", icon: "boxes", label: "Carga e Descarga" },
      { route: "history", icon: "history", label: "Histórico" },
    ],
  },
];

const Sidebar = ({ route, navigate, collapsed, setCollapsed, mobileOpen, setMobileOpen, sidebarStyle, isAdmin = false }) => {
  const onlyIcons = collapsed || sidebarStyle === "icons";

  const content = (
    <div className="flex flex-col" style={{ height: "100%" }}>
      {/* Brand */}
      <div className="flex items-center justify-between px-4 py-4 border-b" style={{ minHeight: 64 }}>
        {onlyIcons ? (
          <div className="mx-auto"><WoodLogo size={28} showText={false} /></div>
        ) : (
          <WoodLogo size={30} textSize={15} />
        )}
        {!onlyIcons && (
          <button
            className="wood-btn wood-btn-ghost wood-btn-icon-sm md-hide"
            onClick={() => setCollapsed(!collapsed)}
            aria-label={collapsed ? "Expandir sidebar" : "Recolher sidebar"}
          >
            <Icon name="panel-left" size={14} />
          </button>
        )}
      </div>

      {/* Org switcher */}
      {!onlyIcons && (
        <button
          className="flex items-center gap-3 mx-3 mt-3 px-3 py-2.5 rounded text-left"
          style={{ background: "var(--wood-surface-2)", border: "1px solid var(--wood-border)", color: "var(--text)" }}
        >
          <div style={{
            width: 30, height: 30, borderRadius: 8,
            background: "linear-gradient(135deg, #047857, #022C22)",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            fontSize: 12, fontWeight: 700, color: "#FFFFFF",
            border: "1px solid var(--wood-border-strong)", flexShrink: 0
          }}>MN</div>
          <div className="flex-1 min-w-0">
            <div className="text-sm truncate" style={{ fontWeight: 500 }}>Marcenaria Norte</div>
            <div className="text-xs text-4 truncate">Plano Profissional</div>
          </div>
          <Icon name="chevron-down" size={14} className="text-3" />
        </button>
      )}

      {/* Nav */}
      <nav className="flex-1 py-3 overflow-y-auto" style={{ paddingTop: onlyIcons ? 16 : 8 }}>
        {NAV_GROUPS.map((group) => (
          <div key={group.label}>
            {!onlyIcons && <div className="wood-group-label">{group.label}</div>}
            {onlyIcons && <div style={{ height: 16 }} />}
            {group.items.map((item) => (
              <button
                key={item.route}
                className={`wood-navlink ${route === item.route ? "active" : ""}`}
                onClick={() => { navigate(item.route); setMobileOpen(false); }}
                style={onlyIcons ? { padding: "9px 0", justifyContent: "center", margin: "0 8px" } : undefined}
                title={onlyIcons ? item.label : undefined}
              >
                <span className="wood-navlink-icon" style={item.primary ? { background: "rgba(16, 185, 129,0.25)", color: "var(--amber-bright)" } : undefined}>
                  <Icon name={item.icon} size={15} />
                </span>
                {!onlyIcons && (
                  <>
                    <span className="flex-1 truncate" style={{ textAlign: "left" }}>{item.label}</span>
                    {item.badge && (
                      <span className="wood-badge wood-badge-amber" style={{ padding: "1px 7px", fontSize: 10.5 }}>{item.badge}</span>
                    )}
                  </>
                )}
              </button>
            ))}
          </div>
        ))}

        {/* System */}
        {!onlyIcons && <div className="wood-group-label">Sistema</div>}
        {onlyIcons && <div style={{ height: 16 }} />}
        <button
          className={`wood-navlink ${route === "admin" ? "active" : ""}`}
          onClick={() => { navigate("admin"); setMobileOpen(false); }}
          style={onlyIcons ? { padding: "9px 0", justifyContent: "center", margin: "0 8px" } : undefined}
          title={onlyIcons ? "Painel Admin" : undefined}
        >
          <span className="wood-navlink-icon">
            <Icon name="shield" size={15} />
          </span>
          {!onlyIcons && (
            <>
              <span className="flex-1 truncate" style={{ textAlign: "left" }}>Painel Admin</span>
              <span className="wood-badge wood-badge-neutral" style={{ padding: "1px 6px", fontSize: 9.5, letterSpacing: "0.06em" }}>SaaS</span>
            </>
          )}
        </button>
      </nav>

      {/* Footer */}
      <div className="border-t" style={{ padding: onlyIcons ? "12px 8px" : "12px" }}>
        <div className="flex items-center gap-3 px-2 py-2 rounded cursor-pointer" style={{ background: "transparent" }}>
          <Avatar name="Eduardo Marques" size={onlyIcons ? 32 : 36} />
          {!onlyIcons && (
            <div className="flex-1 min-w-0">
              <div className="text-sm truncate" style={{ fontWeight: 500 }}>Eduardo Marques</div>
              <div className="text-xs text-4 truncate">Gerente operacional</div>
            </div>
          )}
          {!onlyIcons && <Icon name="more" size={14} className="text-3" />}
        </div>
      </div>
    </div>
  );

  // Mobile drawer
  if (mobileOpen) {
    return (
      <>
        <div
          onClick={() => setMobileOpen(false)}
          style={{ position: "fixed", inset: 0, background: "rgba(5,4,2,0.65)", backdropFilter: "blur(4px)", zIndex: 49 }}
          className="fade-in"
        />
        <aside
          className="wood-sidebar"
          style={{
            position: "fixed", left: 0, top: 0, bottom: 0,
            width: 280, height: "100vh", zIndex: 50,
            boxShadow: "8px 0 32px rgba(0,0,0,0.5)",
            animation: "drawer-in 0.42s cubic-bezier(0.16,1,0.3,1)"
          }}
        >
          {content}
        </aside>
      </>
    );
  }

  return (
    <aside className={`wood-sidebar md-hide ${collapsed ? "collapsed" : ""}`} style={{ width: onlyIcons ? 72 : 248 }}>
      {content}
    </aside>
  );
};

/* ============================================================
   HEADER
   ============================================================ */
const Header = ({ title, subtitle, onSearch, onToggleTheme, theme, onOpenMobile, onOpenAdmin, route, navigate }) => {
  const [notifOpen, setNotifOpen] = useStateChrome(false);
  const [userOpen, setUserOpen] = useStateChrome(false);

  // Close dropdowns when clicking outside
  useEffectChrome(() => {
    const onClick = (e) => {
      if (!e.target.closest("[data-dropdown-trigger]") && !e.target.closest("[data-dropdown-menu]")) {
        setNotifOpen(false);
        setUserOpen(false);
      }
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  return (
    <header className="wood-header slide-up">
      <button
        className="wood-btn wood-btn-ghost wood-btn-icon md-only"
        style={{ display: "none" }}
        onClick={onOpenMobile}
        aria-label="Abrir menu"
      >
        <Icon name="menu" size={18} />
      </button>
      <style>{`@media (max-width: 1100px) { .md-only { display: inline-flex !important; } }`}</style>

      <div className="flex flex-col flex-1 min-w-0">
        <div className="flex items-center gap-2 text-xs text-4 tracking-wide mb-0.5">
          <span>Wood OS</span>
          <Icon name="chevron-right" size={11} />
          <span className="text-3 capitalize">{subtitle || "Painel"}</span>
        </div>
        <h1 className="text-lg font-semibold tracking-tight truncate" style={{ marginTop: -2 }}>{title}</h1>
      </div>

      <div
        className="wood-cmd md-hide"
        onClick={onSearch}
        style={{ maxWidth: 420 }}
      >
        <Icon name="search" size={15} className="text-3" />
        <input
          readOnly
          placeholder="Buscar solicitações, obras, equipes ou veículos…"
          style={{ pointerEvents: "none" }}
        />
        <span className="wood-kbd">⌘K</span>
      </div>

      <div className="flex items-center gap-1">
        <button className="wood-btn wood-btn-ghost wood-btn-icon sm-hide" onClick={onToggleTheme} aria-label="Alternar tema">
          <Icon name={theme === "dark" ? "sun" : "moon"} size={16} />
        </button>
        <button
          className="wood-btn wood-btn-ghost wood-btn-icon relative"
          onClick={(e) => { e.stopPropagation(); setNotifOpen(!notifOpen); setUserOpen(false); }}
          data-dropdown-trigger
          aria-label="Notificações"
        >
          <Icon name="bell" size={16} />
          <span style={{
            position: "absolute", top: 8, right: 8,
            width: 7, height: 7, borderRadius: "50%",
            background: "var(--amber-bright)",
            boxShadow: "0 0 0 2px var(--wood-bg), 0 0 8px var(--amber)"
          }} />
        </button>
        <button
          className="wood-btn wood-btn-ghost wood-btn-icon-sm sm-hide relative"
          style={{ marginLeft: 4 }}
          onClick={(e) => { e.stopPropagation(); setUserOpen(!userOpen); setNotifOpen(false); }}
          data-dropdown-trigger
          aria-label="Conta"
        >
          <Avatar name="Eduardo Marques" size={30} />
        </button>
      </div>

      {notifOpen && <NotificationsMenu onClose={() => setNotifOpen(false)} navigate={navigate} />}
      {userOpen && <UserMenu onClose={() => setUserOpen(false)} navigate={navigate} onToggleTheme={onToggleTheme} theme={theme} />}
    </header>
  );
};

/* ============================================================
   User dropdown menu
   ============================================================ */
const UserMenu = ({ onClose, navigate, onToggleTheme, theme }) => {
  const go = (route) => { navigate(route); onClose(); };
  return (
    <div
      data-dropdown-menu
      style={{
        position: "absolute", top: 56, right: 16,
        width: 260,
        background: "var(--wood-surface)",
        border: "1px solid var(--wood-border-strong)",
        borderRadius: 14,
        boxShadow: "var(--shadow-lg)",
        zIndex: 30,
        animation: "fade-in 0.18s var(--ease-out)",
        overflow: "hidden"
      }}
    >
      {/* User card */}
      <div className="flex items-center gap-3 px-4 py-3.5" style={{ borderBottom: "1px solid var(--wood-border)" }}>
        <Avatar name="Eduardo Marques" size={40} />
        <div className="flex-1 min-w-0">
          <div className="text-sm truncate" style={{ fontWeight: 600 }}>Eduardo Marques</div>
          <div className="text-xs text-3 truncate">eduardo@marcenarianorte.com.br</div>
        </div>
      </div>

      {/* Org */}
      <div className="px-4 py-3" style={{ background: "rgba(255,255,255,0.02)" }}>
        <div className="text-xs uppercase tracking-widest text-4 mb-2" style={{ fontWeight: 600 }}>MARCENARIA</div>
        <div className="flex items-center gap-2.5">
          <div style={{
            width: 28, height: 28, borderRadius: 7,
            background: "linear-gradient(135deg, var(--wood-light), var(--wood-dark))",
            color: "var(--cream)", border: "1px solid var(--wood-border-strong)",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            fontSize: 10, fontWeight: 700, flexShrink: 0
          }}>MN</div>
          <div className="flex-1 min-w-0">
            <div className="text-sm truncate" style={{ fontWeight: 500 }}>Marcenaria Norte</div>
            <div className="text-xs text-3">Plano Profissional</div>
          </div>
        </div>
      </div>

      <div style={{ padding: 6 }}>
        <UserMenuItem icon="users" label="Minha conta" onClick={() => go("settings")} />
        <UserMenuItem icon="building" label="Minha marcenaria" onClick={() => go("settings")} />
        <UserMenuItem icon="credit-card" label="Plano & cobrança" onClick={() => go("settings")} />
        <UserMenuItem icon="bell" label="Notificações" onClick={() => go("settings")} />
        <div className="wood-divider my-1" style={{ margin: "6px 0" }} />
        <UserMenuItem icon="settings" label="Configurações" onClick={() => go("settings")} />
        <UserMenuItem
          icon={theme === "dark" ? "sun" : "moon"}
          label={theme === "dark" ? "Tema claro" : "Tema escuro"}
          onClick={() => { onToggleTheme(); onClose(); }}
        />
        <UserMenuItem icon="support" label="Ajuda & suporte" onClick={onClose} />
        <UserMenuItem icon="key" label="Painel Admin" badge="SaaS" onClick={() => go("admin")} />
      </div>

      <div style={{ padding: 6, borderTop: "1px solid var(--wood-border)" }}>
        <UserMenuItem icon="logout" label="Sair" onClick={() => go("landing")} danger />
      </div>
    </div>
  );
};

const UserMenuItem = ({ icon, label, onClick, badge, danger }) => (
  <button
    onClick={onClick}
    className="flex items-center gap-3 w-full"
    style={{
      padding: "8px 10px",
      borderRadius: 8,
      background: "transparent",
      border: "none",
      cursor: "pointer",
      color: danger ? "var(--error)" : "var(--text-2)",
      textAlign: "left",
      transition: "background 0.14s"
    }}
    onMouseEnter={e => e.currentTarget.style.background = danger ? "rgba(239,68,68,0.08)" : "rgba(255,255,255,0.04)"}
    onMouseLeave={e => e.currentTarget.style.background = "transparent"}
  >
    <Icon name={icon} size={14} className={danger ? "" : "text-3"} />
    <span className="flex-1 text-sm">{label}</span>
    {badge && (
      <span className="wood-badge wood-badge-neutral" style={{ padding: "1px 6px", fontSize: 9.5, letterSpacing: "0.08em" }}>{badge}</span>
    )}
  </button>
);

/* ============================================================
   Notifications menu (extracted)
   ============================================================ */
const NotificationsMenu = ({ onClose, navigate }) => (
  <div
    data-dropdown-menu
    style={{
      position: "absolute", top: 56, right: 16,
      width: 380, maxWidth: "calc(100vw - 32px)",
      background: "var(--wood-surface)", border: "1px solid var(--wood-border-strong)",
      borderRadius: 14, boxShadow: "var(--shadow-lg)", zIndex: 30,
      animation: "fade-in 0.18s var(--ease-out)"
    }}
  >
    <div className="flex items-center justify-between px-4 py-3 border-b">
      <div className="text-sm font-semibold">Notificações</div>
      <button className="text-xs text-amber" style={{ background: "none", border: "none", padding: 0, cursor: "pointer", fontWeight: 600 }}>Marcar todas</button>
    </div>
    <div style={{ maxHeight: 360, overflowY: "auto" }}>
      {[
        { icon: "alert", color: "var(--error)", title: "Solicitação WO-2808 atrasou", desc: "Ipanema 802 · 3 dias de atraso", time: "8 min" },
        { icon: "fire", color: "var(--amber-bright)", title: "Carga urgente saindo agora", desc: "RIO-2A18 para Vieira Souto 1102", time: "12 min" },
        { icon: "package", color: "var(--info)", title: "Recebimento ORD-1206", desc: "Verniz acetinado entregue por Almoxarifado", time: "1h" },
        { icon: "check", color: "var(--success)", title: "WO-2811 marcada como pronta", desc: "Apto Leblon 1101", time: "2h" },
      ].map((n, i) => (
        <div key={i} className="flex items-start gap-3 px-4 py-3" style={{ borderBottom: i < 3 ? "1px solid var(--wood-border-soft)" : "none" }}>
          <div style={{ width: 32, height: 32, borderRadius: 8, background: `${n.color}1A`, color: n.color, display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name={n.icon} size={15} />
          </div>
          <div className="flex-1 min-w-0">
            <div className="text-sm" style={{ fontWeight: 500 }}>{n.title}</div>
            <div className="text-xs text-3 mt-0.5">{n.desc}</div>
          </div>
          <div className="text-xs text-4 whitespace-nowrap">{n.time}</div>
        </div>
      ))}
    </div>
    <div className="px-4 py-2.5 border-t text-center">
      <button className="text-sm text-amber" style={{ background: "none", border: "none", cursor: "pointer", fontWeight: 600 }} onClick={() => { navigate?.("history"); onClose(); }}>
        Ver tudo no Histórico
      </button>
    </div>
  </div>
);

/* ============================================================
   PageHeader (in-page hero)
   ============================================================ */
const PageHeader = ({ title, subtitle, actions, kicker }) => (
  <div className="flex items-end justify-between flex-wrap gap-4 mb-6 slide-up">
    <div>
      {kicker && <div className="text-xs uppercase tracking-widest text-amber mb-2" style={{ fontWeight: 600 }}>{kicker}</div>}
      <h1 className="text-3xl font-semibold tracking-tighter mb-1">{title}</h1>
      {subtitle && <div className="text-3 text-md max-w-2xl text-pretty">{subtitle}</div>}
    </div>
    {actions && <div className="flex items-center gap-2">{actions}</div>}
  </div>
);

Object.assign(window, { Sidebar, Header, PageHeader, NAV_GROUPS });
