/* ============================================================
   ADMIN SHELL — sidebar, topbar, role switcher, perm gating
   window: AdminShell, useCurrentStaff, RoleBadge
   ============================================================ */
(function () {
  const { useApp, H, Icon } = window;

  function useCurrentStaff() {
    const app = useApp();
    return app.state.staffUser || {
      id: null, name: "—", en: "—", role: "moderator",
      cats: [], status: "active", initials: "?", last: "",
      perms: { create: false, edit: false, publish: false, delete: false, rss: false, manageUsers: false },
    };
  }
  window.useCurrentStaff = useCurrentStaff;

  function RoleBadge({ role, sm }) {
    const isAdmin = role === "admin";
    return (
      <span className={"badge " + (isAdmin ? "teal" : "amber")} style={{ fontSize: sm ? 10 : 11 }}>
        {isAdmin ? "অ্যাডমিন" : "মডারেটর"}
      </span>
    );
  }
  window.RoleBadge = RoleBadge;

  const NAV = [
    { key: "admin", icon: "grid", label: "ড্যাশবোর্ড", perm: null },
    { key: "admin-posts", icon: "file", label: "সব পোস্ট", perm: null },
    { key: "admin-editor", icon: "edit", label: "নতুন পোস্ট", perm: "create" },
    { key: "admin-rss", icon: "rss", label: "আরএসএস ও রিভিউ", perm: "rss", badge: "queue" },
    { key: "admin-people", icon: "users", label: "মডারেটর", perm: "manageUsers" },
  ];

  function AdminShell({ children, active }) {
    const app = useApp();
    const me = useCurrentStaff();
    const [roleOpen, setRoleOpen] = React.useState(false);
    const queueCount = app.state.queue.length;

    const can = (p) => !p || (me.perms && me.perms[p]);

    return (
      <div data-admin style={{ display: "grid", gridTemplateColumns: "248px 1fr", minHeight: "100vh", background: "var(--surface-2)" }}>
        {/* sidebar */}
        <aside style={{ background: "var(--ink)", color: "var(--bg)", display: "flex", flexDirection: "column", position: "sticky", top: 0, height: "100vh" }}>
          <div style={{ padding: "22px 22px 18px", borderBottom: "1px solid oklch(1 0 0 / 0.1)" }}>
            <div className="serif" style={{ fontSize: 24, fontWeight: 700 }}>প্রভাত<span style={{ color: "var(--accent)" }}>.</span></div>
            <div style={{ fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", opacity: .5, marginTop: 2 }}>Newsroom CMS</div>
          </div>

          <nav style={{ padding: 14, display: "grid", gap: 3, flex: 1, alignContent: "start", gridAutoRows: "max-content" }}>
            {NAV.map(n => {
              const allowed = can(n.perm);
              const isActive = active === n.key;
              return (
                <button key={n.key} disabled={!allowed} onClick={() => allowed && app.nav(n.key)}
                  style={{
                    display: "flex", alignItems: "center", gap: 12, width: "100%", textAlign: "right",
                    background: isActive ? "oklch(1 0 0 / 0.12)" : "transparent",
                    border: 0, borderRadius: 7, padding: "11px 13px", cursor: allowed ? "pointer" : "not-allowed",
                    color: isActive ? "#fff" : (allowed ? "rgba(255,255,255,.72)" : "rgba(255,255,255,.28)"),
                    fontFamily: "var(--font-ui)", fontSize: 14.5, fontWeight: isActive ? 700 : 500, position: "relative",
                  }}>
                  <Icon name={n.icon} size={18} />
                  <span style={{ flex: 1 }}>{n.label}</span>
                  {n.badge === "queue" && queueCount > 0 && allowed &&
                    <span style={{ background: "var(--accent)", color: "#fff", fontSize: 11, fontWeight: 700, minWidth: 20, height: 20, borderRadius: 999, display: "grid", placeItems: "center", padding: "0 5px" }}>{H.toBn(queueCount)}</span>}
                  {!allowed && <Icon name="x" size={13} style={{ opacity: .5 }} />}
                </button>
              );
            })}
          </nav>

          <div style={{ padding: 14, borderTop: "1px solid oklch(1 0 0 / 0.1)" }}>
            <button onClick={() => app.nav("home")}
              style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", background: "transparent", border: "1px solid oklch(1 0 0 / 0.18)", borderRadius: 7, padding: "10px 13px", cursor: "pointer", color: "rgba(255,255,255,.8)", fontFamily: "var(--font-ui)", fontSize: 13.5, whiteSpace: "nowrap" }}>
              <Icon name="home" size={16} /> সাইটে ফিরে যান
            </button>
          </div>
        </aside>

        {/* main */}
        <div style={{ display: "flex", flexDirection: "column", minWidth: 0 }}>
          {/* topbar */}
          <div style={{ background: "var(--surface)", borderBottom: "1px solid var(--line)", height: 62, display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 26px", position: "sticky", top: 0, zIndex: 20 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--ink-3)", fontSize: 13 }}>
              <Icon name="clock" size={15} /> সর্বশেষ সিংক: <span style={{ color: "var(--ink-2)", fontWeight: 600 }}>১ মিনিট আগে</span>
            </div>

            {/* current user + logout */}
            <div style={{ position: "relative" }}>
              <button onClick={() => setRoleOpen(o => !o)} className="btn sm" style={{ paddingLeft: 6 }}>
                <span style={{ width: 26, height: 26, borderRadius: "50%", background: me.role === "admin" ? "var(--accent)" : "var(--amber)", color: "#fff", display: "grid", placeItems: "center", fontWeight: 700, fontSize: 12 }}>{me.initials}</span>
                <span style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", lineHeight: 1.1 }}>
                  <span style={{ fontSize: 13, fontWeight: 700 }}>{me.name}</span>
                  <span style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{me.role === "admin" ? "অ্যাডমিন" : "মডারেটর"}</span>
                </span>
                <Icon name="chevD" size={14} />
              </button>
              {roleOpen && (
                <>
                  <div onClick={() => setRoleOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 30 }} />
                  <div className="fade-in" style={{ position: "absolute", top: 46, left: 0, width: 260, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 8, boxShadow: "var(--shadow-2)", zIndex: 31, overflow: "hidden" }}>
                    <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--line-2)" }}>
                      <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)" }}>{me.name}</div>
                      <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{me.email || ""}</div>
                    </div>
                    <button onClick={() => { setRoleOpen(false); app.staffLogout(); app.nav("home"); }}
                      style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", textAlign: "right", background: "none", border: 0, padding: "12px 14px", cursor: "pointer", color: "var(--red)", fontSize: 14, fontWeight: 600 }}>
                      <Icon name="logout" size={16} /> লগআউট
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>

          <main style={{ padding: "28px 26px 60px", flex: 1, minWidth: 0 }}>{children}</main>
        </div>
      </div>
    );
  }
  window.AdminShell = AdminShell;
})();
