/* Left sidebar — dark, near-black menu with light text/icons, and a persisted
   collapse toggle that shrinks it to an icons-only rail. */

// Dark menu palette (local to the nav; doesn't touch the app theme tokens).
const NAV = {
  bg: "#17181A",            // near-black
  fg: "#C9CDD3",            // normal text + icons
  fgStrong: "#F4F5F6",      // active / names
  muted: "#71767E",         // group labels, tagline, toggle
  hover: "rgba(255,255,255,.06)",
  activeBg: "rgba(14,165,183,.18)",
  activeFg: "#4DD0DE",      // light teal — active item on dark (DS primary)
  border: "rgba(255,255,255,.09)",
  surface: "rgba(255,255,255,.05)",
};

/* Client account switcher — agencies/freelancers scope all data to the active
   client. "Agency workspace" (null) holds anything not tied to a client. */
function ClientSwitcher({ onNav, collapsed }) {
  const S = window.CroprStore;
  const [open, setOpen] = React.useState(false);
  const clients = S.getClients();
  const active = S.getActiveClient();
  const dot = (c) => <span style={{ width: 26, height: 26, borderRadius: 7, flex: "none", background: c && c.logoUrl ? NAV.surface : (c ? c.color : NAV.surface), color: "#fff", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 800, overflow: "hidden" }}>{c && c.logoUrl ? <img src={c.logoUrl} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : c ? c.name.slice(0, 1).toUpperCase() : <Icon name="briefcase" size={13} color={NAV.muted} />}</span>;
  const pick = (id) => { S.setActiveClient(id); setOpen(false); };
  const menu = (
    <React.Fragment>
      <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 70 }} />
      <div style={{ position: "absolute", top: collapsed ? 46 : 54, left: collapsed ? 52 : 2, width: 232, zIndex: 71, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 12, boxShadow: "var(--shadow-lg)", padding: 6, maxHeight: 340, overflow: "auto" }}>
        {[null].concat(clients).map((c) => {
          const on = (c ? c.id : null) === S.getActiveClientId();
          return (
            <button key={c ? c.id : "agency"} onClick={() => pick(c ? c.id : null)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 9, padding: "8px 9px", borderRadius: 9, border: 0, cursor: "pointer", fontFamily: "inherit", background: on ? "var(--accent-weak)" : "transparent" }}>
              {dot(c)}
              <span style={{ flex: 1, minWidth: 0, textAlign: "left", fontSize: 13, fontWeight: 600, color: on ? "var(--accent)" : "var(--fg1)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c ? c.name : "Agency workspace"}</span>
              {on && <Icon name="check" size={15} color="var(--accent)" />}
            </button>
          );
        })}
        <div style={{ height: 1, background: "var(--border)", margin: "6px 4px" }} />
        <button onClick={() => { setOpen(false); onNav("clients"); }} style={{ width: "100%", display: "flex", alignItems: "center", gap: 9, padding: "8px 9px", borderRadius: 9, border: 0, cursor: "pointer", fontFamily: "inherit", background: "transparent", color: "var(--accent)", fontSize: 13, fontWeight: 600 }}>
          <span style={{ width: 24, display: "grid", placeItems: "center" }}><Icon name="plus" size={16} color="var(--accent)" /></span>Add / manage clients
        </button>
      </div>
    </React.Fragment>
  );

  if (collapsed) {
    return (
      <div style={{ position: "relative", display: "grid", placeItems: "center", padding: "0 0 8px" }}>
        <button title={active ? active.name : "Agency workspace"} onClick={() => setOpen((o) => !o)} style={{ display: "grid", placeItems: "center", padding: 5, borderRadius: 10, border: "1px solid " + NAV.border, background: NAV.surface, cursor: "pointer" }}>{dot(active)}</button>
        {open && menu}
      </div>
    );
  }
  return (
    <div style={{ position: "relative", padding: "0 2px 10px" }}>
      <button onClick={() => setOpen((o) => !o)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 9, padding: "8px 10px", borderRadius: 11, border: "1px solid " + NAV.border, background: NAV.surface, cursor: "pointer", fontFamily: "inherit" }}>
        {dot(active)}
        <span style={{ flex: 1, minWidth: 0, textAlign: "left" }}>
          <span style={{ display: "block", fontSize: 9, fontWeight: 700, color: NAV.muted, textTransform: "uppercase", letterSpacing: ".08em" }}>{active ? "Client" : "Workspace"}</span>
          <span style={{ display: "block", fontSize: 13, fontWeight: 700, color: NAV.fgStrong, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{active ? active.name : "Agency workspace"}</span>
        </span>
        <Icon name="chevron-down" size={15} color={NAV.muted} />
      </button>
      {open && menu}
    </div>
  );
}

function Sidebar({ active, onNav }) {
  const S = window.CroprStore;
  const [collapsed, setCollapsed] = React.useState(() => { try { return localStorage.getItem("leap_nav_collapsed") === "1"; } catch (e) { return false; } });
  const toggle = () => setCollapsed((c) => { const n = !c; try { localStorage.setItem("leap_nav_collapsed", n ? "1" : "0"); } catch (e) {} return n; });

  const showClients = S.getOnboarding().role === "agency" || S.getClients().length > 0;
  const creds = S.getIntegrations();
  const menuLinks = (window.CROPR_DATA.MENU_INTEGRATIONS || []).filter((mi) => creds[mi.name] && Object.keys(creds[mi.name]).length);
  const groups = [
    ["", [["dashboard", "layout-dashboard", "Dashboard"]]],
    ["Plan", [["posts", "layout-list", "Posts"], ["calendar", "calendar-days", "Calendar"], ["queue", "calendar-clock", "Queue"]]],
    ["Create", [["campaigns", "megaphone", "Campaigns"], ["pulse", "activity", "Pulse Desk"], ["wizards", "wand-2", "Wizards"]]],
    ["Engage", [["screener", "radar", "Screener"], ["replies", "message-square", "Replies"]]],
    ["Workspace", [].concat(showClients ? [["clients", "users", "Clients"]] : [], [["assets", "image", "Assets"], ["settings", "settings", "Settings"]])],
  ];
  const houseRules = (S.getHouseRules() || []);

  const sb = { width: collapsed ? 74 : 244, flex: "none", background: NAV.bg, borderRight: "1px solid " + NAV.border,
    display: "flex", flexDirection: "column", padding: collapsed ? "18px 12px" : "18px 14px", gap: 3, height: "100%", boxSizing: "border-box",
    transition: "width 160ms var(--ease-standard)" };
  const item = (id) => ({ display: "flex", alignItems: "center", justifyContent: collapsed ? "center" : "flex-start", gap: 12,
    padding: collapsed ? "11px 0" : "10px 12px", borderRadius: 10, fontSize: 14, fontWeight: active === id ? 600 : 500, cursor: "pointer",
    width: "100%", textAlign: "left", border: "1px solid transparent", fontFamily: "inherit",
    color: active === id ? NAV.activeFg : NAV.fg, background: active === id ? NAV.activeBg : "transparent",
    transition: "background 140ms var(--ease-standard), color 140ms" });
  const label = { fontSize: 11, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", color: NAV.muted, padding: "16px 12px 6px" };
  const toggleBtn = { background: "transparent", border: "1px solid " + NAV.border, borderRadius: 9, padding: 6, cursor: "pointer", color: NAV.muted, display: "grid", placeItems: "center" };

  const Row = ([id, icon, text]) => (
    <button key={id} type="button" title={collapsed ? text : undefined} aria-current={active === id ? "page" : undefined} style={item(id)} onClick={() => onNav(id)}
      onMouseEnter={(e) => { if (active !== id) e.currentTarget.style.background = NAV.hover; }}
      onMouseLeave={(e) => { if (active !== id) e.currentTarget.style.background = "transparent"; }}>
      <Icon name={icon} size={19} />{!collapsed && text}
    </button>
  );

  return (
    <nav style={sb}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: collapsed ? "center" : "space-between", padding: collapsed ? "4px 0 10px" : "4px 4px 10px" }}>
        <img src={collapsed ? "assets/leap-mark.svg" : "assets/leap-logo-inverse.svg"} alt="Leap" style={{ height: collapsed ? 32 : 30 }} />
        {!collapsed && <button title="Collapse menu" onClick={toggle} style={toggleBtn}><Icon name="chevrons-left" size={18} /></button>}
      </div>
      {collapsed && <button title="Expand menu" onClick={toggle} style={{ ...toggleBtn, margin: "0 auto 8px" }}><Icon name="chevrons-right" size={18} /></button>}
      {!collapsed && <div style={{ fontSize: 14, fontWeight: 700, fontFamily: "var(--font-display)", color: NAV.activeFg, padding: "2px 12px 14px", letterSpacing: ".005em", lineHeight: 1.35 }}>Post smarter.<br />Make a Leap.</div>}
      {showClients && <ClientSwitcher onNav={onNav} collapsed={collapsed} />}
      <div className="no-scrollbar" style={{ overflowX: "hidden", overflowY: "auto", flex: 1, minWidth: 0 }}>
        {groups.map(([title, rows], gi) => (
          <React.Fragment key={title || "top"}>
            {gi > 0 && (collapsed ? <div style={{ height: 1, background: NAV.border, margin: "10px 8px" }} /> : <div style={label}>{title}</div>)}
            {rows.map(Row)}
          </React.Fragment>
        ))}
        {menuLinks.map((mi) => (
          <a key={mi.name} href={mi.url} target="_blank" rel="noreferrer" title={collapsed ? mi.label : undefined} style={{ ...item("_"), textDecoration: "none" }}
            onMouseEnter={(e) => (e.currentTarget.style.background = NAV.hover)}
            onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
            <Icon name={mi.icon} size={19} />{!collapsed && mi.label}{!collapsed && <Icon name="external-link" size={13} style={{ marginLeft: "auto", opacity: .5 }} />}
          </a>
        ))}
      </div>
      {!collapsed && (
        <div style={{ background: "var(--gradient-core)", borderRadius: 14, padding: 15, color: "#fff", position: "relative", overflow: "hidden" }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, marginBottom: 6 }}>House rules</div>
          {houseRules.length ? (
            <ul style={{ margin: 0, paddingLeft: 16, fontSize: 11.5, lineHeight: 1.6, opacity: .95 }}>
              {houseRules.map((r, i) => <li key={i}>{r}</li>)}
            </ul>
          ) : (
            <div style={{ fontSize: 11.5, lineHeight: 1.5, opacity: .9 }}>No house rules yet — add them in Settings.</div>
          )}
        </div>
      )}
    </nav>
  );
}
window.Sidebar = Sidebar;
