/* global React, Icon, IconBtn, Avatar, Kbd, Pill, Badge, Popover, PopoverItem */
/* App shell: StatusStrip, Sidebar, TopBar, CommandPalette */

const { useState, useEffect, useRef, useMemo } = React;

function StatusStrip() {
  const [p, setP] = useState(8);
  useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      setP(Math.max(2, Math.min(100, (h.scrollTop / Math.max(1, max)) * 100)));
    };
    window.addEventListener("scroll", onScroll, true);
    onScroll();
    return () => window.removeEventListener("scroll", onScroll, true);
  }, []);
  return <div className="status-strip" aria-hidden><i style={{ "--p": `${p}%` }}/></div>;
}

function Wordmark({ collapsed }) {
  if (collapsed) {
    return (
      <div style={{
        width: 28, height: 28, borderRadius: 4,
        background: "var(--brand-grad)",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        color: "white", fontFamily: "var(--sans)", fontWeight: 700, fontSize: 13, letterSpacing: "-0.04em",
      }}>BG</div>
    );
  }
  return (
    <div className="row gap-8" style={{ alignItems: "center" }}>
      <div style={{
        width: 28, height: 28, borderRadius: 4,
        background: "var(--brand-grad)",
      }}/>
      <div className="col" style={{ lineHeight: 1 }}>
        <span style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 13, letterSpacing: "-0.02em" }}>BNMR GLVZ</span>
        <span className="mono" style={{ fontSize: 9, marginTop: 2, color: "var(--ink-3)" }}>Catalyst · v4.1</span>
      </div>
    </div>
  );
}

function NavItem({ icon, label, active, onClick, badge, collapsed, danger }) {
  return (
    <button
      onClick={onClick}
      title={collapsed ? label : undefined}
      style={{
        width: "100%", display: "flex", alignItems: "center", gap: 12,
        height: 36, padding: collapsed ? 0 : "0 12px",
        justifyContent: collapsed ? "center" : "flex-start",
        background: active ? "var(--bg-2)" : "transparent",
        color: active ? "var(--ink)" : (danger ? "var(--neg)" : "var(--ink-2)"),
        border: 0, borderRadius: "var(--r-sharp)",
        fontFamily: "var(--sans)", fontSize: 13, fontWeight: active ? 500 : 400,
        cursor: "pointer", textAlign: "left",
        position: "relative",
        transition: "background 200ms ease, color 200ms ease",
      }}
      onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = "var(--bg-2)"; }}
      onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = "transparent"; }}
    >
      {active && !collapsed && (
        <span style={{ position: "absolute", left: -16, top: 8, bottom: 8, width: 2, background: "var(--brand-grad)" }}/>
      )}
      <span style={{ display: "inline-flex", color: active ? "var(--ink)" : (danger ? "var(--neg)" : "var(--ink-3)") }}>{icon}</span>
      {!collapsed && <span style={{ flex: 1 }}>{label}</span>}
      {!collapsed && badge && <span style={{
        fontFamily: "var(--mono)", fontSize: 10, fontWeight: 700, letterSpacing: "0.06em",
        color: "var(--ink-3)",
      }}>{badge}</span>}
    </button>
  );
}

function NavSection({ title, children, collapsed }) {
  return (
    <div className="col gap-4" style={{ marginBottom: 18 }}>
      {!collapsed && title && (
        <div style={{
          padding: "0 12px", marginBottom: 4, fontFamily: "var(--mono)",
          fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-3)", fontWeight: 700,
        }}>{title}</div>
      )}
      {children}
    </div>
  );
}

function Sidebar({ route, onRoute, sidebar, onPalette }) {
  const collapsed = sidebar === "icon";
  const hidden = sidebar === "hidden";
  if (hidden) return null;

  const sections = [
    {
      title: null,
      items: [
        { id: "analytics", icon: <Icon.Pulse size={16}/>, label: "Overview" },
        { id: "inbox", icon: <Icon.Inbox size={16}/>, label: "Inbox", badge: "12" },
        { id: "table", icon: <Icon.Database size={16}/>, label: "Audits" },
      ],
    },
    {
      title: "Intelligence Suite",
      items: [
        { id: "brandlens", icon: <Icon.Lens size={16}/>, label: "BrandLens" },
        { id: "catalyst", icon: <Icon.Bolt size={16}/>, label: "Catalyst" },
        { id: "bigsights", icon: <Icon.Compass size={16}/>, label: "BIGSights" },
        { id: "hive", icon: <Icon.Hive size={16}/>, label: "HIVE" },
        { id: "milton", icon: <Icon.Spark size={16}/>, label: "Milton.AI" },
      ],
    },
    {
      title: "Workspace",
      items: [
        { id: "workflow", icon: <Icon.Bolt size={16}/>, label: "New audit" },
        { id: "empty", icon: <Icon.Folder size={16}/>, label: "Projects" },
        { id: "settings", icon: <Icon.Settings size={16}/>, label: "Settings" },
      ],
    },
  ];

  return (
    <aside style={{
      borderRight: "1px solid var(--line)",
      display: "flex", flexDirection: "column", minHeight: 0,
      position: "sticky", top: 0, height: "100vh",
      background: "var(--bg)",
    }}>
      <div className="row" style={{
        height: "var(--shell-topbar-h)", padding: collapsed ? 0 : "0 16px",
        borderBottom: "1px solid var(--line)",
        justifyContent: collapsed ? "center" : "flex-start",
      }}>
        <Wordmark collapsed={collapsed}/>
      </div>

      <div className="scroll" style={{
        flex: 1, overflowY: "auto", padding: collapsed ? "16px 8px" : "16px",
        display: "flex", flexDirection: "column",
      }}>
        {!collapsed && (
          <button onClick={onPalette} style={{
            display: "flex", alignItems: "center", gap: 10,
            background: "var(--bg-2)", border: "1px solid var(--line)",
            borderRadius: "var(--r-sharp)", padding: "8px 12px", marginBottom: 18,
            color: "var(--ink-3)", fontFamily: "var(--sans)", fontSize: 13, cursor: "pointer",
            transition: "border-color 200ms ease",
          }}>
            <Icon.Search size={14}/>
            <span style={{ flex: 1, textAlign: "left" }}>Find anything…</span>
            <span className="kbd">⌘K</span>
          </button>
        )}
        {collapsed && (
          <button onClick={onPalette} style={{
            width: 40, height: 40, alignSelf: "center", marginBottom: 14,
            background: "var(--bg-2)", border: "1px solid var(--line)",
            borderRadius: "var(--r-sharp)", color: "var(--ink-2)", cursor: "pointer",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
          }} title="Search · ⌘K"><Icon.Search size={14}/></button>
        )}

        {sections.map((s, i) => (
          <NavSection key={i} title={s.title} collapsed={collapsed}>
            {s.items.map((it) => (
              <NavItem key={it.id} icon={it.icon} label={it.label}
                active={route === it.id} onClick={() => onRoute(it.id)}
                badge={it.badge} collapsed={collapsed}/>
            ))}
          </NavSection>
        ))}

        <div style={{ marginTop: "auto", paddingTop: 12 }}>
          <NavItem icon={<Icon.Help size={16}/>} label="Help & docs" collapsed={collapsed}/>
          <NavItem icon={<Icon.User size={16}/>} label="Auth screens" onClick={() => onRoute("auth")}
            active={route === "auth"} collapsed={collapsed}/>
          <NavItem icon={<Icon.Layers size={16}/>} label="Component gallery"
            onClick={() => onRoute("gallery")} active={route === "gallery"} collapsed={collapsed}/>
        </div>
      </div>

      {!collapsed && (
        <div className="row gap-8" style={{
          padding: "12px 16px", borderTop: "1px solid var(--line)", alignItems: "center",
        }}>
          <Avatar name="Inés Vidal" size={28}/>
          <div className="col" style={{ flex: 1, minWidth: 0, lineHeight: 1.2 }}>
            <span style={{ fontSize: 12, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
              Inés Vidal
            </span>
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-3)" }}>MIA · Strategy</span>
          </div>
          <button style={{ border: 0, background: "transparent", color: "var(--ink-3)", cursor: "pointer", padding: 4 }}>
            <Icon.MoreV size={14}/>
          </button>
        </div>
      )}
      {collapsed && (
        <div className="row" style={{ justifyContent: "center", padding: 12, borderTop: "1px solid var(--line)" }}>
          <Avatar name="Inés Vidal" size={28}/>
        </div>
      )}
    </aside>
  );
}

/* ---------- TopBar ---------- */
function TopBar({ breadcrumb, title, eyebrow, actions, onSidebarToggle, onPalette }) {
  return (
    <header style={{
      height: "var(--shell-topbar-h)",
      borderBottom: "1px solid var(--line)",
      padding: "0 var(--d-page-px)",
      display: "flex", alignItems: "center", gap: 16,
      background: "var(--bg)",
      position: "sticky", top: 0, zIndex: 50,
    }}>
      <div className="row gap-12" style={{ flex: 1, minWidth: 0, alignItems: "center" }}>
        <IconBtn icon={<Icon.Sidebar size={16}/>} onClick={onSidebarToggle} label="Toggle sidebar" size={32}/>
        {breadcrumb}
      </div>
      <div className="row gap-6" style={{ alignItems: "center" }}>
        <button onClick={onPalette} style={{
          display: "inline-flex", alignItems: "center", gap: 8, height: 32, padding: "0 12px",
          background: "var(--bg)", border: "1px solid var(--line)", borderRadius: "var(--r-sharp)",
          color: "var(--ink-3)", cursor: "pointer", fontFamily: "var(--sans)", fontSize: 13,
        }}>
          <Icon.Search size={13}/>
          <span>Search</span>
          <span className="kbd">⌘K</span>
        </button>
        <IconBtn icon={<Icon.Bell size={16}/>} label="Notifications" size={32}/>
        {actions}
        <span style={{ width: 1, height: 20, background: "var(--line)", margin: "0 4px" }}/>
        <span className="mono" style={{ color: "var(--ink-3)" }}>MIA · 09:42</span>
      </div>
    </header>
  );
}

/* ---------- Command Palette ---------- */
function CommandPalette({ open, onClose, onRoute }) {
  const [q, setQ] = useState("");
  const inputRef = useRef();
  useEffect(() => {
    if (!open) return;
    setTimeout(() => inputRef.current && inputRef.current.focus(), 50);
    setQ("");
    const onKey = (e) => {
      if (e.key === "Escape") onClose && onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const all = useMemo(() => [
    { group: "Pages", items: [
      { id: "analytics", icon: <Icon.Pulse size={14}/>, label: "Overview", hint: "Catalyst summary" },
      { id: "inbox", icon: <Icon.Inbox size={14}/>, label: "Inbox", hint: "12 new" },
      { id: "table", icon: <Icon.Database size={14}/>, label: "Audits", hint: "All audits" },
      { id: "settings", icon: <Icon.Settings size={14}/>, label: "Settings", hint: "Account, billing, team" },
      { id: "workflow", icon: <Icon.Bolt size={14}/>, label: "New audit", hint: "Start a paid audit · 2–3 weeks" },
      { id: "empty", icon: <Icon.Folder size={14}/>, label: "Projects (empty)", hint: "Onboarding state" },
      { id: "gallery", icon: <Icon.Layers size={14}/>, label: "Component gallery", hint: "All primitives" },
      { id: "auth", icon: <Icon.User size={14}/>, label: "Auth screens", hint: "Login · signup · reset" },
    ]},
    { group: "Suite", items: [
      { id: "brandlens", icon: <Icon.Lens size={14}/>, label: "BrandLens", hint: "Brand diagnostic" },
      { id: "catalyst", icon: <Icon.Bolt size={14}/>, label: "Catalyst Intelligence", hint: "Decision OS" },
      { id: "hive", icon: <Icon.Hive size={14}/>, label: "HIVE", hint: "Agent orchestration" },
      { id: "milton", icon: <Icon.Spark size={14}/>, label: "Milton.AI", hint: "Knowledge agent" },
    ]},
    { group: "Quick actions", items: [
      { id: "_run-audit", icon: <Icon.Play size={14}/>, label: "Run last audit", hint: "Re-execute Loop 14" },
      { id: "_invite", icon: <Icon.Plus size={14}/>, label: "Invite teammate", hint: "Send by email" },
      { id: "_export", icon: <Icon.Download size={14}/>, label: "Export current view", hint: "CSV · JSON" },
    ]},
  ], []);

  const filtered = useMemo(() => {
    if (!q.trim()) return all;
    const s = q.toLowerCase();
    return all.map(g => ({ ...g, items: g.items.filter(it => it.label.toLowerCase().includes(s) || (it.hint || "").toLowerCase().includes(s)) }))
      .filter(g => g.items.length);
  }, [q, all]);

  if (!open) return null;
  return (
    <div onClick={onClose}
      style={{
        position: "fixed", inset: 0, background: "rgba(10,10,10,0.55)", zIndex: 250,
        display: "flex", alignItems: "flex-start", justifyContent: "center",
        padding: "12vh 24px 24px", animation: "fadeIn 180ms ease",
      }}>
      <div onClick={(e) => e.stopPropagation()}
        style={{
          width: "100%", maxWidth: 600,
          background: "var(--bg)", border: "1px solid var(--ink)",
          borderRadius: "var(--r-sharp)", overflow: "hidden",
          animation: "popIn 220ms cubic-bezier(.2,.7,.2,1)",
        }}>
        <div className="row" style={{ borderBottom: "1px solid var(--line)", padding: "0 18px", height: 56, gap: 12 }}>
          <Icon.Search size={16}/>
          <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)}
            placeholder="Type a command, jump to a page, or run a query…"
            style={{
              flex: 1, border: 0, outline: 0, background: "transparent",
              fontFamily: "var(--sans)", fontSize: 16, color: "var(--ink)",
            }}/>
          <span className="kbd">ESC</span>
        </div>
        <div className="scroll" style={{ maxHeight: 420, overflowY: "auto", padding: 8 }}>
          {filtered.length === 0 ? (
            <div style={{ padding: "32px 12px", textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>
              No matches for "{q}"
            </div>
          ) : (
            filtered.map((g, gi) => (
              <div key={gi} style={{ marginBottom: 8 }}>
                <div style={{
                  fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase",
                  color: "var(--ink-3)", padding: "8px 10px 4px", fontWeight: 700,
                }}>{g.group}</div>
                {g.items.map((it) => (
                  <button key={it.id} onClick={() => { if (!it.id.startsWith("_")) onRoute(it.id); onClose(); }}
                    style={{
                      width: "100%", display: "flex", alignItems: "center", gap: 12,
                      padding: "10px 10px", border: 0, background: "transparent",
                      color: "var(--ink)", fontFamily: "var(--sans)", fontSize: 14,
                      cursor: "pointer", textAlign: "left", borderRadius: 2,
                    }}
                    onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-2)"}
                    onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                    <span style={{ color: "var(--ink-2)", display: "inline-flex" }}>{it.icon}</span>
                    <span style={{ flex: 1 }}>{it.label}</span>
                    <span className="mono" style={{ color: "var(--ink-3)", fontSize: 10 }}>{it.hint}</span>
                    <Icon.ChevronRight size={12}/>
                  </button>
                ))}
              </div>
            ))
          )}
        </div>
        <div className="row between" style={{ padding: "10px 18px", borderTop: "1px solid var(--line)", color: "var(--ink-3)" }}>
          <span className="mono" style={{ fontSize: 10 }}>↑↓ navigate · ↵ select · ⌘K toggle</span>
          <span className="mono" style={{ fontSize: 10 }}>Catalyst v4.1</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { StatusStrip, Wordmark, NavItem, NavSection, Sidebar, TopBar, CommandPalette });
