function GlobalSearch({ setPage }) {
  const [q, setQ]           = React.useState("");
  const [open, setOpen]     = React.useState(false);
  const [sel, setSel]       = React.useState(0);
  const inputRef            = React.useRef(null);
  const wrapRef             = React.useRef(null);

  // ⌘K / Ctrl+K focuses the input
  React.useEffect(() => {
    const handler = e => {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        inputRef.current?.focus();
        inputRef.current?.select();
      }
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, []);

  // Close on outside click
  React.useEffect(() => {
    const handler = e => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const trimmed = q.trim().toLowerCase();

  const userResults = !trimmed ? [] : (window.USERS || []).filter(u => {
    return [u.name, u.email, u.uid, u.childName].some(v => v && String(v).toLowerCase().includes(trimmed));
  }).slice(0, 4);

  const storyResults = !trimmed ? [] : (window.STORIES || []).filter(s => {
    return [s.title, s.childName, s.therapeuticTheme, s.theme].some(v => v && String(v).toLowerCase().includes(trimmed));
  }).slice(0, 4);

  const allResults = [
    ...userResults.map(u => ({ type: "user", item: u })),
    ...storyResults.map(s => ({ type: "story", item: s })),
  ];

  const hasResults = allResults.length > 0;
  const showDropdown = open && trimmed.length > 0;

  function navigate(result) {
    setOpen(false);
    setQ("");
    if (result.type === "user") {
      setPage("users");
      setTimeout(() => window.dispatchEvent(new CustomEvent("adminOpenUser", { detail: result.item })), 80);
    } else {
      setPage("stories");
      setTimeout(() => window.dispatchEvent(new CustomEvent("adminOpenStory", { detail: result.item })), 80);
    }
  }

  function onKey(e) {
    if (!showDropdown) return;
    if (e.key === "ArrowDown") { e.preventDefault(); setSel(s => Math.min(s + 1, allResults.length - 1)); }
    if (e.key === "ArrowUp")   { e.preventDefault(); setSel(s => Math.max(s - 1, 0)); }
    if (e.key === "Enter" && allResults[sel]) { navigate(allResults[sel]); }
    if (e.key === "Escape") { setOpen(false); inputRef.current?.blur(); }
  }

  return (
    <div ref={wrapRef} style={{ position: "relative", flex: 1, maxWidth: 420 }}>
      <div className="search" style={{ background: open ? "var(--bg-elev)" : undefined }}>
        <Icon.search size={13}/>
        <input
          ref={inputRef}
          placeholder="Search users, stories…"
          value={q}
          onChange={e => { setQ(e.target.value); setOpen(true); setSel(0); }}
          onFocus={() => setOpen(true)}
          onKeyDown={onKey}
        />
        {q ? (
          <button style={{ background: "none", border: "none", cursor: "pointer", padding: "0 2px", color: "var(--ink-4)" }}
            onClick={() => { setQ(""); inputRef.current?.focus(); }}>
            <Icon.close size={11}/>
          </button>
        ) : (
          <span className="kbd">⌘K</span>
        )}
      </div>

      {showDropdown && (
        <div style={{
          position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0,
          background: "var(--bg-elev)", border: "1px solid var(--border)",
          borderRadius: 12, boxShadow: "0 8px 24px -4px rgba(0,0,0,.12)",
          zIndex: 1000, overflow: "hidden",
        }}>
          {!hasResults && (
            <div style={{ padding: "16px 16px", fontSize: 13, color: "var(--ink-4)", textAlign: "center" }}>
              No results for "{q}"
            </div>
          )}

          {userResults.length > 0 && (
            <>
              <div style={{ padding: "8px 14px 4px", fontSize: 10, fontWeight: 700, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: ".08em" }}>
                Users
              </div>
              {userResults.map((u, i) => {
                const idx = i;
                const active = sel === idx;
                const display = u.name || u.email || "Guest";
                const sub = u.email || (u.childName ? `Kid: ${u.childName}` : u.uid?.slice(0, 12));
                const initials = display.split(/[\s@]/).filter(Boolean).map(n => n[0]).slice(0, 2).join("").toUpperCase() || "?";
                return (
                  <div key={u.uid} onMouseDown={() => navigate({ type: "user", item: u })}
                    onMouseEnter={() => setSel(idx)}
                    style={{
                      display: "flex", alignItems: "center", gap: 10,
                      padding: "8px 14px", cursor: "pointer",
                      background: active ? "var(--accent-soft)" : "transparent",
                    }}>
                    <div className="avatar" style={{ width: 26, height: 26, fontSize: 10, flexShrink: 0 }}>{initials}</div>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 500, fontSize: 13, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{display}</div>
                      {sub && <div style={{ fontSize: 11, color: "var(--ink-4)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{sub}</div>}
                    </div>
                    <div style={{ flexShrink: 0, marginLeft: "auto" }}>
                      <span className="badge">{u.stories || 0} stories</span>
                    </div>
                  </div>
                );
              })}
            </>
          )}

          {storyResults.length > 0 && (
            <>
              <div style={{ padding: "8px 14px 4px", fontSize: 10, fontWeight: 700, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: ".08em", borderTop: userResults.length ? "1px solid var(--border)" : "none", marginTop: userResults.length ? 4 : 0 }}>
                Stories
              </div>
              {storyResults.map((s, i) => {
                const idx = userResults.length + i;
                const active = sel === idx;
                const hue = storyHue(s.id);
                const bg = `linear-gradient(135deg, hsl(${hue},65%,62%), hsl(${(hue+60)%360},70%,45%))`;
                return (
                  <div key={s.id} onMouseDown={() => navigate({ type: "story", item: s })}
                    onMouseEnter={() => setSel(idx)}
                    style={{
                      display: "flex", alignItems: "center", gap: 10,
                      padding: "8px 14px", cursor: "pointer",
                      background: active ? "var(--accent-soft)" : "transparent",
                    }}>
                    <div style={{ width: 26, height: 26, borderRadius: 6, background: bg, flexShrink: 0,
                      ...(s.coverUrl ? { backgroundImage: `url(${s.coverUrl})`, backgroundSize: "cover" } : {}) }}/>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 500, fontSize: 13, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.title || "Untitled"}</div>
                      <div style={{ fontSize: 11, color: "var(--ink-4)" }}>{s.childName ? `${s.childName} · ` : ""}{s.therapeuticTheme || s.theme || "—"}</div>
                    </div>
                    {s.rating > 0 && <span style={{ flexShrink: 0, color: "var(--accent)", fontSize: 11, marginLeft: "auto" }}>{"★".repeat(s.rating)}</span>}
                  </div>
                );
              })}
            </>
          )}

          <div style={{ padding: "8px 14px", borderTop: "1px solid var(--border)", fontSize: 11, color: "var(--ink-4)", display: "flex", gap: 12 }}>
            <span><kbd style={{ fontFamily: "var(--mono)", fontSize: 10 }}>↑↓</kbd> navigate</span>
            <span><kbd style={{ fontFamily: "var(--mono)", fontSize: 10 }}>↵</kbd> open</span>
            <span><kbd style={{ fontFamily: "var(--mono)", fontSize: 10 }}>esc</kbd> close</span>
          </div>
        </div>
      )}
    </div>
  );
}

function handleLogout() {
  if (window.__signOut) window.__signOut();
  else location.reload();
}

function Shell({ page, setPage, children, moderationCount=3 }) {
  const [collapsed, setCollapsed] = React.useState(false);
  const nav = [
    { group: "Analyze", items: [
      { id:"overview", name:"Overview", icon:"home" },
      { id:"users", name:"Users", icon:"users", count: compact(KPIS.users) },
      { id:"stories", name:"Stories", icon:"book", count: compact(KPIS.storiesTotal) },
    ]},
    { group: "Monetize", items: [
      { id:"revenue", name:"Revenue", icon:"money" },
      { id:"credits", name:"Credits", icon:"coin" },
      { id:"subs", name:"Subscriptions", icon:"card" },
      { id:"pricing", name:"Pricing & Packs", icon:"tag" },
      { id:"promos", name:"Promos & Gifts", icon:"star" },
    ]},
    { group: "Engage", items: [
      { id:"crm", name:"CRM · Resend", icon:"mail" },
      { id:"announce", name:"Announcements", icon:"speaker" },
      { id:"banners", name:"Banner Builder", icon:"palette" },
      { id:"campaigns", name:"Push Campaigns", icon:"bell" },
    ]},
    { group: "Content", items: [
      { id:"music", name:"Background Music", icon:"music" },
      { id:"themes", name:"Themes & Prompts", icon:"palette" },
    ]},
    { group: "Operate", items: [
      { id:"moderation", name:"Moderation", icon:"shield", count: moderationCount },
      { id:"flags", name:"Feature Flags", icon:"flask" },
      { id:"audit", name:"Audit Log", icon:"log" },
      { id:"kanban", name:"Team Board", icon:"check" },
      { id:"settings", name:"Settings", icon:"settings" },
    ]},
  ];

  const activeItem = nav.flatMap(g=>g.items).find(i=>i.id===page);

  return (
    <div className="app" data-collapsed={collapsed}>
      <aside className="sidebar">
        <div className="sidebar-brand">
          <div className="mark">T</div>
          {!collapsed && <>
            <div className="name">Talio <span style={{color:"var(--ink-3)", fontWeight:400}}>Admin</span></div>
            <div className="env">PROD</div>
          </>}
        </div>

        <div className="sidebar-scroll">
          {nav.map(group => (
            <div key={group.group}>
              {!collapsed && <div className="nav-group-label">{group.group}</div>}
              {group.items.map(item => {
                const Ic = Icon[item.icon];
                return (
                  <div key={item.id} className="nav-item"
                    data-active={page===item.id}
                    onClick={()=>setPage(item.id)}
                    title={collapsed ? item.name : ""}>
                    <Ic size={15} className="icon"/>
                    {!collapsed && <>
                      <span>{item.name}</span>
                      {item.count != null && <span className="count">{item.count}</span>}
                    </>}
                  </div>
                );
              })}
            </div>
          ))}
        </div>

        <div className="sidebar-user">
          <div className="avatar">AG</div>
          {!collapsed && <div style={{minWidth:0, flex:1}}>
            <div style={{fontSize:12, fontWeight:500, overflow:"hidden", textOverflow:"ellipsis"}}>Adi Goldstein</div>
            <div style={{fontSize:10, color:"var(--ink-3)"}}>Super admin</div>
          </div>}
          <button className="btn ghost icon sm" title="Sign out" onClick={handleLogout}>
            <Icon.logout size={13}/>
          </button>
        </div>
      </aside>

      <div className="main">
        <div className="topbar">
          <button className="btn ghost icon" onClick={()=>setCollapsed(c=>!c)} title="Collapse sidebar">
            <Icon.panel size={15}/>
          </button>
          <div className="crumbs">
            <span>talio.fun</span>
            <Icon.chevRight size={11} className="sep"/>
            <span>admin</span>
            <Icon.chevRight size={11} className="sep"/>
            <span className="current">{activeItem?.name || "Dashboard"}</span>
          </div>

          <GlobalSearch setPage={setPage}/>

          <div className="right">
            <button className="btn ghost sm"><Icon.download size={13}/> Export</button>
            <div style={{width:1, height:20, background:"var(--border)"}}/>
            <button className="btn ghost icon sm" title="Notifications"><Icon.bell size={15}/></button>
            <span className="badge green"><span className="pulse"/> Live</span>
          </div>
        </div>

        <div className="page">{children}</div>
      </div>
    </div>
  );
}

window.Shell = Shell;
