/**
 * <rstack-space-switcher> — Dropdown to switch between user's spaces.
 *
 * Attributes:
 *   current — the active space slug
 *   name    — the display name of the active space
 *
 * Fetches the user's spaces from /api/spaces on click.
 * Passes auth token so the API returns private spaces the user can access.
 */

import { isAuthenticated, getAccessToken, getUsername } from "./rstack-identity";
import { rspaceNavUrl, getCurrentModule as getModule, getModuleApiBase } from "../url-helpers";

interface SpaceInfo {
	slug: string;
	name: string;
	icon?: string;
	role?: string;
	visibility?: string;
	accessible?: boolean;
	relationship?: "owner" | "member" | "demo" | "other";
	pendingRequest?: boolean;
	isPersonal?: boolean;
}

export class RStackSpaceSwitcher extends HTMLElement {
	#shadow: ShadowRoot;
	#spaces: SpaceInfo[] = [];
	#loaded = false;
	// Preserved create-form state across open/close
	#createFormOpen = false;
	#createName = '';
	#createVisibility = 'public';
	#onDocPointerDown: ((e: PointerEvent) => void) | null = null;

	constructor() {
		super();
		this.#shadow = this.attachShadow({ mode: "open" });
	}

	static get observedAttributes() {
		return ["current", "name"];
	}

	get current(): string {
		return this.getAttribute("current") || "";
	}

	get spaceName(): string {
		return this.getAttribute("name") || this.current;
	}

	connectedCallback() {
		this.#render();
	}

	attributeChangedCallback() {
		this.#render();
	}

	disconnectedCallback() {
		if (this.#onDocPointerDown) {
			document.removeEventListener("pointerdown", this.#onDocPointerDown);
			this.#onDocPointerDown = null;
		}
	}

	async #loadSpaces() {
		if (this.#loaded) return;
		try {
			const headers: Record<string, string> = {};
			const token = getAccessToken();
			if (token) headers["Authorization"] = `Bearer ${token}`;

			const res = await fetch("/api/spaces", { headers });
			if (res.ok) {
				const data = await res.json();
				this.#spaces = data.spaces || [];
			}
		} catch {
			// Offline or API not available — just show current
		}
		this.#loaded = true;
	}

	/** Force reload spaces on next open (e.g. after auth change) */
	reload() {
		this.#loaded = false;
		this.#spaces = [];
	}

	#render() {
		const current = this.current;
		const name = this.spaceName;

		this.#shadow.innerHTML = `
			<style>${STYLES}</style>
			<div class="switcher">
				<button class="trigger" id="trigger">
					<span class="space-name">${name || "Select space"}</span>
					<span class="caret">▾</span>
				</button>
				<div class="menu" id="menu">
					<div class="menu-loading">Loading spaces...</div>
				</div>
			</div>
		`;

		const trigger = this.#shadow.getElementById("trigger")!;
		const menu = this.#shadow.getElementById("menu")!;

		trigger.addEventListener("click", async (e) => {
			e.stopPropagation();
			const isOpen = menu.classList.toggle("open");
			if (isOpen) {
				const rect = trigger.getBoundingClientRect();
				menu.style.top = `${rect.bottom + 6}px`;
				menu.style.left = `${Math.max(4, Math.min(window.innerWidth - 268, rect.left))}px`;
				if (!this.#loaded) {
					await this.#loadSpaces();
					this.#renderMenu(menu, current);
				} else {
					// Restore create form state if it was open
					this.#restoreCreateFormState(menu);
				}
			} else {
				// Preserve create form state before closing
				this.#saveCreateFormState(menu);
			}
		});

		// Close menu only when clicking outside both trigger and menu
		if (this.#onDocPointerDown) {
			document.removeEventListener("pointerdown", this.#onDocPointerDown);
		}
		this.#onDocPointerDown = (e: PointerEvent) => {
			if (!menu.classList.contains("open")) return;
			const path = e.composedPath();
			if (path.includes(menu) || path.includes(trigger)) return;
			this.#saveCreateFormState(menu);
			menu.classList.remove("open");
		};
		document.addEventListener("pointerdown", this.#onDocPointerDown);

		// Prevent clicks inside menu from closing it
		menu.addEventListener("pointerdown", (e) => e.stopPropagation());
	}

	#visibilityInfo(s: SpaceInfo): { cls: string; label: string } {
		const v = s.visibility || "public";
		if (v === "private") return { cls: "vis-private", label: "🔒" };
		if (v === "permissioned") return { cls: "vis-permissioned", label: "🔑" };
		return { cls: "vis-public", label: "👁" };
	}

	/** Format display name — only rename the user's personal space */
	#displayName(s: SpaceInfo): string {
		if (s.isPersonal || s.slug === getUsername()?.toLowerCase()) {
			const username = getUsername();
			return username ? `${username}'s Space` : "My Space";
		}
		return s.name;
	}

	#renderSpaceGroup(spaces: SpaceInfo[], current: string, moduleId: string): string {
		return spaces
			.map((s) => {
				const vis = this.#visibilityInfo(s);
				const canEdit = s.role === "owner" || s.role === "admin";
				return `
			<div class="item-row ${vis.cls} ${s.slug === current ? "active" : ""}">
				<a class="item" href="${rspaceNavUrl(s.slug, moduleId)}">
					<span class="item-icon">${s.icon || "🌐"}</span>
					<span class="item-name">${this.#displayName(s)}</span>
					<span class="item-vis ${vis.cls}">${vis.label}</span>
				</a>${canEdit ? `<button class="item-gear" data-edit-slug="${s.slug}" data-edit-name="${s.name.replace(/"/g, "&quot;")}" title="Edit Space">⚙</button>` : ""}
			</div>`;
			})
			.join("");
	}

	#renderMenu(menu: HTMLElement, current: string) {
		const auth = isAuthenticated();
		const moduleId = this.#getCurrentModule();

		// Split spaces by visibility
		const privateSpaces = this.#spaces.filter((s) => s.visibility === "private");
		const permissionedSpaces = this.#spaces.filter((s) => s.visibility === "permissioned");
		const publicSpaces = this.#spaces.filter((s) => s.visibility === "public");

		const hasOwnedSpace = this.#spaces.some((s) => s.relationship === "owner");

		let html = "";

		// ── PRIVATE section ──
		html += `<div class="section-label section-label--private">Private</div>`;
		if (privateSpaces.length > 0) {
			html += this.#renderSpaceGroup(privateSpaces, current, moduleId);
		}
		if (!auth) {
			html += this.#yourSpaceCTAhtml("Sign in to create →");
		} else if (!hasOwnedSpace) {
			const username = getUsername();
			const label = username ? `Create ${username}'s Space →` : "Create My Space →";
			html += this.#yourSpaceCTAhtml(label);
		}

		// ── PERMISSIONED section ──
		if (permissionedSpaces.length > 0) {
			html += `<div class="divider"></div>`;
			html += `<div class="section-label section-label--permissioned">Permissioned</div>`;
			html += this.#renderSpaceGroup(permissionedSpaces, current, moduleId);
		}

		// ── PUBLIC section ──
		html += `<div class="divider"></div>`;
		html += `<div class="section-label section-label--public">Public</div>`;
		if (publicSpaces.length > 0) {
			html += this.#renderSpaceGroup(publicSpaces, current, moduleId);
		} else {
			html += `<div class="menu-empty">No public spaces</div>`;
		}

		// ── *Discover section ──
		html += `<div class="divider"></div>`;
		html += `<div class="section-label section-label--discover">✦ Discover</div>`;
		html += `<a class="item item--discover-link" href="/discover"><span class="item-name">Explore spaces →</span></a>`;

		// ── Create new space ──
		html += `<div class="divider"></div>`;
		html += `<button class="item item--create" id="create-toggle">+ Create new space</button>`;
		html += this.#createFormHTML();

		menu.innerHTML = html;

		// Intercept space link clicks — dispatch space-switch event for client-side switching
		menu.querySelectorAll("a.item[href]").forEach((link) => {
			link.addEventListener("click", (e) => {
				const href = link.getAttribute("href") || "";
				// Extract space slug from the link
				const linkEl = link as HTMLElement;
				const row = linkEl.closest(".item-row");
				// Find the space slug from the href pattern
				const match = href.match(/^(?:https?:\/\/([^.]+)\.rspace\.online)?\/([^/?]+)/);
				let spaceSlug = "";
				let moduleTarget = moduleId;
				if (match) {
					if (match[1]) {
						spaceSlug = match[1]; // subdomain pattern
					} else {
						// path pattern: /{space}/{moduleId} or /{moduleId}
						spaceSlug = match[2];
					}
				}
				// Also try data attribute on parent
				if (!spaceSlug) return; // let default navigation handle it

				// If same space, ignore
				if (spaceSlug === current) {
					menu.classList.remove("open");
					return;
				}

				// Dispatch space-switch event for client-side handling
				const event = new CustomEvent("space-switch", {
					bubbles: true,
					composed: true,
					detail: { space: spaceSlug, moduleId: moduleTarget, href },
				});
				const handled = this.dispatchEvent(event);

				// If a listener called preventDefault(), we handled it client-side
				if (event.defaultPrevented) {
					e.preventDefault();
					menu.classList.remove("open");
				}
				// Otherwise, let the default navigation happen
			});
		});

		// Attach Edit Space gear button listeners
		menu.querySelectorAll(".item-gear").forEach((btn) => {
			btn.addEventListener("click", (e) => {
				e.stopPropagation();
				e.preventDefault();
				const el = btn as HTMLElement;
				this.#showEditSpaceModal(el.dataset.editSlug!, el.dataset.editName!);
			});
		});

		// Attach personal space CTA listener
		this.#attachYourSpaceCTA(menu);

		// Attach create-space popout
		this.#attachCreatePopout(menu);
	}

	#yourSpaceCTAhtml(buttonLabel: string): string {
		const username = getUsername();
		const title = username ? `${username}'s Space` : "My Space";
		return `
			<div class="item item--yourspace vis-private">
				<span class="item-icon">🔒</span>
				<span class="item-name">${title}</span>
				<button class="yourspace-btn" id="yourspace-cta">${buttonLabel}</button>
			</div>`;
	}

	#createFormHTML(): string {
		return `<div class="create-popout hidden" id="create-popout">
			<input class="create-input" id="create-name" placeholder="Space name" maxlength="60" />
			<div class="create-slug" id="create-slug"></div>
			<div class="create-vis-row">
				<label class="create-vis-opt"><input type="radio" name="create-vis" value="public" checked /><span class="vis-dot vis-dot--public"></span> Public</label>
				<label class="create-vis-opt"><input type="radio" name="create-vis" value="permissioned" /><span class="vis-dot vis-dot--permissioned"></span> Permissioned</label>
				<label class="create-vis-opt"><input type="radio" name="create-vis" value="private" /><span class="vis-dot vis-dot--private"></span> Private</label>
			</div>
			<div class="create-actions">
				<button class="create-btn" id="create-submit">Create</button>
				<button class="create-cancel" id="create-cancel">Cancel</button>
			</div>
			<div class="create-status" id="create-status"></div>
		</div>`;
	}

	#attachYourSpaceCTA(menu: HTMLElement) {
		const btn = menu.querySelector("#yourspace-cta");
		if (!btn) return;

		btn.addEventListener("click", (e) => {
			e.stopPropagation();
			if (!isAuthenticated()) {
				// Find <rstack-identity> on page and open auth modal
				const identity = document.querySelector("rstack-identity") as any;
				if (identity?.showAuthModal) {
					identity.showAuthModal({
						onSuccess: () => this.#autoProvision(),
					});
				}
			} else {
				// Authenticated but no owned space — auto-provision
				this.#autoProvision();
			}
		});
	}

	#attachCreatePopout(menu: HTMLElement) {
		const toggle = menu.querySelector("#create-toggle") as HTMLElement;
		const popout = menu.querySelector("#create-popout") as HTMLElement;
		const nameInput = menu.querySelector("#create-name") as HTMLInputElement;
		const slugPreview = menu.querySelector("#create-slug") as HTMLElement;
		const submitBtn = menu.querySelector("#create-submit") as HTMLButtonElement;
		const cancelBtn = menu.querySelector("#create-cancel") as HTMLElement;
		const status = menu.querySelector("#create-status") as HTMLElement;
		if (!toggle || !popout) return;

		const toSlug = (name: string) =>
			name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);

		toggle.addEventListener("click", (e) => {
			e.preventDefault();
			const wasHidden = popout.classList.contains("hidden");
			popout.classList.toggle("hidden");
			this.#createFormOpen = wasHidden;
			if (wasHidden) nameInput.focus();
		});

		nameInput.addEventListener("input", () => {
			const slug = toSlug(nameInput.value);
			slugPreview.textContent = slug ? `slug: ${slug}` : "";
		});

		cancelBtn.addEventListener("click", () => {
			popout.classList.add("hidden");
			nameInput.value = "";
			slugPreview.textContent = "";
			status.textContent = "";
			this.#createFormOpen = false;
			this.#createName = '';
			this.#createVisibility = 'public';
		});

		submitBtn.addEventListener("click", async () => {
			const name = nameInput.value.trim();
			if (!name) { status.textContent = "Name required"; return; }

			const token = getAccessToken();
			if (!token) {
				const identity = document.querySelector("rstack-identity") as any;
				if (identity?.showAuthModal) identity.showAuthModal();
				return;
			}

			const slug = toSlug(name);
			const vis = (menu.querySelector('input[name="create-vis"]:checked') as HTMLInputElement)?.value || "public";

			// Close menu and open the Create Space modal
			menu.classList.remove("open");
			this.#showCreateSpaceModal(name, slug, vis);
		});
	}

	async #autoProvision() {
		const token = getAccessToken();
		if (!token) return;

		const moduleId = this.#getCurrentModule();

		try {
			const res = await fetch("/api/spaces/auto-provision", {
				method: "POST",
				headers: {
					Authorization: `Bearer ${token}`,
					"Content-Type": "application/json",
				},
			});
			const data = await res.json();
			if (data.slug) {
				window.location.href = rspaceNavUrl(data.slug, moduleId);
			}
		} catch {
			// Silently fail — autoResolveSpace in identity may still handle it
		}
	}

	#saveCreateFormState(menu: HTMLElement) {
		const popout = menu.querySelector("#create-popout") as HTMLElement;
		if (!popout) return;
		this.#createFormOpen = !popout.classList.contains("hidden");
		const nameInput = menu.querySelector("#create-name") as HTMLInputElement;
		if (nameInput) this.#createName = nameInput.value;
		const checkedRadio = menu.querySelector('input[name="create-vis"]:checked') as HTMLInputElement;
		if (checkedRadio) this.#createVisibility = checkedRadio.value;
	}

	#restoreCreateFormState(menu: HTMLElement) {
		const popout = menu.querySelector("#create-popout") as HTMLElement;
		const nameInput = menu.querySelector("#create-name") as HTMLInputElement;
		const slugPreview = menu.querySelector("#create-slug") as HTMLElement;
		if (!popout || !nameInput) return;

		if (this.#createFormOpen) {
			popout.classList.remove("hidden");
		}
		if (this.#createName) {
			nameInput.value = this.#createName;
			const toSlug = (name: string) =>
				name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
			if (slugPreview) {
				const slug = toSlug(this.#createName);
				slugPreview.textContent = slug ? `slug: ${slug}` : "";
			}
		}
		if (this.#createVisibility !== 'public') {
			const radio = menu.querySelector(`input[name="create-vis"][value="${this.#createVisibility}"]`) as HTMLInputElement;
			if (radio) radio.checked = true;
		}
		if (this.#createFormOpen) {
			requestAnimationFrame(() => nameInput.focus());
		}
	}

	#showRequestAccessModal(slug: string, spaceName: string) {
		if (document.querySelector(".rstack-auth-overlay")) return;

		const overlay = document.createElement("div");
		overlay.className = "rstack-auth-overlay";
		overlay.innerHTML = `
			<style>${REQUEST_MODAL_STYLES}</style>
			<div class="auth-modal">
				<button class="close-btn" data-action="close">&times;</button>
				<h2>Request Access</h2>
				<p>Request access to <strong>${spaceName.replace(/</g, "&lt;")}</strong></p>
				<textarea class="input" id="ra-message" rows="3" placeholder="Optional message to the space owner..." style="resize:vertical"></textarea>
				<div class="actions">
					<button class="btn btn--secondary" data-action="close">Cancel</button>
					<button class="btn btn--primary" data-action="submit">Send Request</button>
				</div>
				<div class="error" id="ra-error"></div>
			</div>
		`;

		const close = () => overlay.remove();
		overlay.querySelectorAll('[data-action="close"]').forEach((el) =>
			el.addEventListener("click", close)
		);
		overlay.addEventListener("click", (e) => { if (e.target === overlay) close(); });

		overlay.querySelector('[data-action="submit"]')?.addEventListener("click", async () => {
			const btn = overlay.querySelector('[data-action="submit"]') as HTMLButtonElement;
			const errEl = overlay.querySelector("#ra-error") as HTMLElement;
			const msg = (overlay.querySelector("#ra-message") as HTMLTextAreaElement).value.trim();
			errEl.textContent = "";
			btn.disabled = true;
			btn.innerHTML = '<span class="spinner"></span> Sending...';

			try {
				const token = getAccessToken();
				const res = await fetch(`/api/spaces/${slug}/access-requests`, {
					method: "POST",
					headers: {
						"Content-Type": "application/json",
						...(token ? { Authorization: `Bearer ${token}` } : {}),
					},
					body: JSON.stringify({ message: msg || undefined }),
				});
				const data = await res.json();
				if (!res.ok) throw new Error(data.error || "Failed to send request");

				// Mark as pending in local state
				const space = this.#spaces.find((s) => s.slug === slug);
				if (space) space.pendingRequest = true;

				close();

				// Re-render menu if open
				const menu = this.#shadow.getElementById("menu");
				if (menu?.classList.contains("open")) {
					this.#renderMenu(menu, this.current);
				}
			} catch (err: any) {
				btn.disabled = false;
				btn.innerHTML = "Send Request";
				errEl.textContent = err.message || "Failed to send request";
			}
		});

		document.body.appendChild(overlay);
	}

	/** Public entry point — both gear icons call this */
	openSettingsModal(slug: string, name: string, tab: "settings" | "modules" | "members" | "invitations" = "settings") {
		this.#showEditSpaceModal(slug, name, tab);
	}

	#showEditSpaceModal(slug: string, spaceName: string, initialTab: "settings" | "modules" | "members" | "invitations" = "settings") {
		if (document.querySelector(".rstack-auth-overlay")) return;

		const overlay = document.createElement("div");
		overlay.className = "rstack-auth-overlay";
		overlay.innerHTML = `
			<style>${EDIT_SPACE_MODAL_STYLES}</style>
			<div class="edit-modal">
				<button class="close-btn" data-action="close">&times;</button>
				<h2>Edit Space</h2>
				<div class="tabs">
					<button class="tab ${initialTab === "settings" ? "active" : ""}" data-tab="settings">Settings</button>
					<button class="tab ${initialTab === "modules" ? "active" : ""}" data-tab="modules">Modules</button>
					<button class="tab ${initialTab === "members" ? "active" : ""}" data-tab="members">Members</button>
					<button class="tab ${initialTab === "invitations" ? "active" : ""}" data-tab="invitations">Invitations</button>
				</div>

				<div class="tab-panel ${initialTab !== "settings" ? "hidden" : ""}" id="panel-settings">
					<label class="field-label">Name</label>
					<input class="input" id="es-name" value="${spaceName.replace(/"/g, "&quot;")}" />
					<label class="field-label">Visibility</label>
					<select class="input" id="es-visibility">
						<option value="public">👁 Public — anyone can read, sign in to write</option>
						<option value="permissioned">🔑 Permissioned — sign in to read & write</option>
						<option value="private">🔒 Private — invite-only</option>
					</select>
					<label class="field-label">Description</label>
					<textarea class="input" id="es-description" rows="3" placeholder="Optional description..." style="resize:vertical"></textarea>
					<div class="actions">
						<button class="btn btn--primary" id="es-save">Save Changes</button>
					</div>
					<div class="status" id="es-status"></div>
					<div class="danger-zone">
						<div class="danger-label">Danger Zone</div>
						<button class="btn btn--danger" id="es-delete">Delete Space</button>
					</div>
				</div>

				<div class="tab-panel ${initialTab !== "modules" ? "hidden" : ""}" id="panel-modules">
					<div id="es-modules-list" class="modules-list"><div class="loading">Loading modules...</div></div>
					<div class="status" id="es-modules-status"></div>
				</div>

				<div class="tab-panel ${initialTab !== "members" ? "hidden" : ""}" id="panel-members">
					<div id="es-members-list" class="member-list"><div class="loading">Loading members...</div></div>
				</div>

				<div class="tab-panel ${initialTab !== "invitations" ? "hidden" : ""}" id="panel-invitations">
					<div id="es-invitations-list" class="invitation-list"><div class="loading">Loading invitations...</div></div>
				</div>
			</div>
		`;

		const close = () => overlay.remove();
		overlay.querySelectorAll('[data-action="close"]').forEach((el) =>
			el.addEventListener("click", close)
		);
		overlay.addEventListener("click", (e) => { if (e.target === overlay) close(); });

		// Tab switching
		overlay.querySelectorAll(".tab").forEach((tab) => {
			tab.addEventListener("click", () => {
				overlay.querySelectorAll(".tab").forEach((t) => t.classList.remove("active"));
				overlay.querySelectorAll(".tab-panel").forEach((p) => p.classList.add("hidden"));
				tab.classList.add("active");
				const panel = overlay.querySelector(`#panel-${(tab as HTMLElement).dataset.tab}`);
				panel?.classList.remove("hidden");

				// Lazy-load content
				if ((tab as HTMLElement).dataset.tab === "modules") this.#loadModulesConfig(overlay, slug);
				if ((tab as HTMLElement).dataset.tab === "members") this.#loadMembers(overlay, slug);
				if ((tab as HTMLElement).dataset.tab === "invitations") this.#loadInvitations(overlay, slug);
			});
		});

		// Load current settings
		this.#loadSpaceSettings(overlay, slug);

		// Save handler
		overlay.querySelector("#es-save")?.addEventListener("click", () => this.#saveSpaceSettings(overlay, slug));

		// Delete handler
		overlay.querySelector("#es-delete")?.addEventListener("click", () => this.#deleteSpace(overlay, slug, spaceName));

		// Eager-load the initially-active tab (if not settings, which loads above)
		if (initialTab === "modules") this.#loadModulesConfig(overlay, slug);
		if (initialTab === "members") this.#loadMembers(overlay, slug);
		if (initialTab === "invitations") this.#loadInvitations(overlay, slug);

		document.body.appendChild(overlay);
	}

	async #loadSpaceSettings(overlay: HTMLElement, slug: string) {
		try {
			const token = getAccessToken();
			const res = await fetch(`/api/spaces/${slug}`, {
				headers: token ? { Authorization: `Bearer ${token}` } : {},
			});
			if (!res.ok) return;
			const data = await res.json();
			const vis = overlay.querySelector("#es-visibility") as HTMLSelectElement;
			if (vis && data.visibility) vis.value = data.visibility;
		} catch { /* ignore */ }
	}

	async #saveSpaceSettings(overlay: HTMLElement, slug: string) {
		const statusEl = overlay.querySelector("#es-status") as HTMLElement;
		const name = (overlay.querySelector("#es-name") as HTMLInputElement).value.trim();
		const visibility = (overlay.querySelector("#es-visibility") as HTMLSelectElement).value;
		const description = (overlay.querySelector("#es-description") as HTMLTextAreaElement).value.trim();

		if (!name) { statusEl.textContent = "Name is required"; statusEl.className = "status error"; return; }

		statusEl.textContent = "Saving...";
		statusEl.className = "status";

		try {
			const token = getAccessToken();
			const res = await fetch(`/api/spaces/${slug}`, {
				method: "PATCH",
				headers: {
					"Content-Type": "application/json",
					...(token ? { Authorization: `Bearer ${token}` } : {}),
				},
				body: JSON.stringify({ name, visibility, description }),
			});
			const data = await res.json();
			if (!res.ok) throw new Error(data.error || "Failed to save");

			statusEl.textContent = "Saved!";
			statusEl.className = "status success";

			// Update switcher display
			this.#loaded = false;
			this.setAttribute("name", name);

			setTimeout(() => { statusEl.textContent = ""; }, 2000);
		} catch (err: any) {
			statusEl.textContent = err.message || "Failed to save";
			statusEl.className = "status error";
		}
	}

	async #deleteSpace(overlay: HTMLElement, slug: string, spaceName: string) {
		if (!confirm(`Permanently delete "${spaceName}"? This cannot be undone.`)) return;

		const statusEl = overlay.querySelector("#es-status") as HTMLElement;
		statusEl.textContent = "Deleting...";
		statusEl.className = "status";

		try {
			const token = getAccessToken();
			const res = await fetch(`/api/spaces/${slug}`, {
				method: "DELETE",
				headers: token ? { Authorization: `Bearer ${token}` } : {},
			});
			const data = await res.json();
			if (!res.ok) throw new Error(data.error || "Failed to delete");

			overlay.remove();
			// Redirect to demo space
			window.location.href = rspaceNavUrl("demo", "rspace");
		} catch (err: any) {
			statusEl.textContent = err.message || "Failed to delete";
			statusEl.className = "status error";
		}
	}

	async #loadMembers(overlay: HTMLElement, slug: string) {
		const container = overlay.querySelector("#es-members-list") as HTMLElement;
		try {
			const token = getAccessToken();
			const res = await fetch(`/api/spaces/${slug}/members`, {
				headers: token ? { Authorization: `Bearer ${token}` } : {},
			});
			if (!res.ok) { container.innerHTML = `<div class="loading">Failed to load members</div>`; return; }
			const data = await res.json();
			const members: Array<{ did: string; role: string; displayName?: string; isOwner?: boolean }> = data.members || [];

			let membersHtml = "";
			if (members.length === 0) {
				membersHtml = `<div class="loading">No members</div>`;
			} else {
				membersHtml = members.map((m) => {
					const displayName = m.displayName || m.did.slice(0, 20) + "...";
					const roleOptions = ["viewer", "member", "moderator", "admin"]
						.map((r) => `<option value="${r}" ${r === m.role ? "selected" : ""}>${r}</option>`)
						.join("");
					return `
						<div class="member-item${m.isOwner ? " member-owner" : ""}">
							<span class="member-name">${displayName}</span>
							${m.isOwner
								? `<span class="role-badge role-owner">owner</span>`
								: `<select class="role-select" data-did="${m.did}">${roleOptions}</select>
								   <button class="member-remove" data-did="${m.did}" title="Remove member">&times;</button>`
							}
						</div>`;
				}).join("");
			}

			// Add Member section (admin-only)
			const addMemberHtml = `
				<div class="add-member-section">
					<div class="section-label">Add Member</div>
					<div class="add-member-toggle">
						<button class="add-toggle-btn active" data-add-mode="username">By Username</button>
						<button class="add-toggle-btn" data-add-mode="email">By Email</button>
					</div>
					<div class="add-member-form" id="add-member-form">
						<div class="add-member-username-mode">
							<div class="add-search-wrapper">
								<input class="input" id="am-username" placeholder="Search username..." autocomplete="off" style="margin-bottom:0" />
								<div class="add-search-dropdown" id="am-search-dropdown"></div>
							</div>
							<div class="add-selected-user" id="am-selected-user"></div>
							<div class="add-member-row">
								<select class="role-select" id="am-role">
									<option value="member">member</option>
									<option value="viewer">viewer</option>
									<option value="moderator">moderator</option>
									<option value="admin">admin</option>
								</select>
								<button class="btn-sm btn-sm--approve" id="am-add-btn" disabled>Invite</button>
							</div>
							<div class="add-feedback" id="am-feedback"></div>
						</div>
					</div>
					<div class="add-member-form hidden" id="add-email-form">
						<input type="email" class="input" id="am-email" placeholder="Email address..." style="margin-bottom:0" />
						<div class="add-member-row">
							<select class="role-select" id="am-email-role">
								<option value="member">member</option>
								<option value="viewer">viewer</option>
								<option value="moderator">moderator</option>
								<option value="admin">admin</option>
							</select>
							<button class="btn-sm btn-sm--approve" id="am-email-btn">Send Invite</button>
						</div>
						<div class="add-feedback" id="am-email-feedback"></div>
					</div>
				</div>`;

			container.innerHTML = membersHtml + addMemberHtml;

			// Role change handlers
			container.querySelectorAll(".role-select:not(#am-role):not(#am-email-role)").forEach((sel) => {
				sel.addEventListener("change", async () => {
					const el = sel as HTMLSelectElement;
					const did = el.dataset.did!;
					const role = el.value;
					const token = getAccessToken();
					try {
						const res = await fetch(`/api/spaces/${slug}/members/${encodeURIComponent(did)}`, {
							method: "PATCH",
							headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
							body: JSON.stringify({ role }),
						});
						if (!res.ok) { const d = await res.json(); alert(d.error || "Failed"); }
					} catch { alert("Failed to update role"); }
				});
			});

			// Remove member handlers
			container.querySelectorAll(".member-remove").forEach((btn) => {
				btn.addEventListener("click", async () => {
					const did = (btn as HTMLElement).dataset.did!;
					if (!confirm("Remove this member?")) return;
					const token = getAccessToken();
					try {
						const res = await fetch(`/api/spaces/${slug}/members/${encodeURIComponent(did)}`, {
							method: "DELETE",
							headers: token ? { Authorization: `Bearer ${token}` } : {},
						});
						if (!res.ok) { const d = await res.json(); alert(d.error || "Failed"); return; }
						this.#loadMembers(overlay, slug);
					} catch { alert("Failed to remove member"); }
				});
			});

			// Wire up add-member section
			this.#attachAddMemberHandlers(container, overlay, slug);
		} catch {
			container.innerHTML = `<div class="loading">Failed to load members</div>`;
		}
	}

	#attachAddMemberHandlers(container: HTMLElement, overlay: HTMLElement, slug: string) {
		// Toggle between username and email modes
		const usernameForm = container.querySelector("#add-member-form") as HTMLElement;
		const emailForm = container.querySelector("#add-email-form") as HTMLElement;

		container.querySelectorAll(".add-toggle-btn").forEach((btn) => {
			btn.addEventListener("click", () => {
				container.querySelectorAll(".add-toggle-btn").forEach((b) => b.classList.remove("active"));
				btn.classList.add("active");
				const mode = (btn as HTMLElement).dataset.addMode;
				if (mode === "username") {
					usernameForm?.classList.remove("hidden");
					emailForm?.classList.add("hidden");
				} else {
					usernameForm?.classList.add("hidden");
					emailForm?.classList.remove("hidden");
				}
			});
		});

		// Username search with debounce
		const usernameInput = container.querySelector("#am-username") as HTMLInputElement;
		const dropdown = container.querySelector("#am-search-dropdown") as HTMLElement;
		const selectedDiv = container.querySelector("#am-selected-user") as HTMLElement;
		const addBtn = container.querySelector("#am-add-btn") as HTMLButtonElement;
		const feedback = container.querySelector("#am-feedback") as HTMLElement;
		let selectedUser: { did: string; username: string; displayName: string } | null = null;
		let searchTimer: ReturnType<typeof setTimeout>;

		if (usernameInput) {
			usernameInput.addEventListener("input", () => {
				clearTimeout(searchTimer);
				selectedUser = null;
				addBtn.disabled = true;
				selectedDiv.innerHTML = "";
				const q = usernameInput.value.trim();
				if (q.length < 2) { dropdown.innerHTML = ""; dropdown.classList.remove("open"); return; }

				searchTimer = setTimeout(async () => {
					try {
						const token = getAccessToken();
						const res = await fetch(`/api/users/search?q=${encodeURIComponent(q)}&limit=5`, {
							headers: token ? { Authorization: `Bearer ${token}` } : {},
						});
						if (!res.ok) { dropdown.classList.remove("open"); return; }
						const users: Array<{ id: string; did: string; username: string; displayName: string }> = await res.json();
						if (users.length === 0) {
							dropdown.innerHTML = `<div class="add-dd-empty">No users found</div>`;
						} else {
							dropdown.innerHTML = users.map((u, i) => `
								<div class="add-dd-item" data-idx="${i}">
									<span class="add-dd-name">${u.displayName || u.username}</span>
									<span class="add-dd-user">@${u.username}</span>
								</div>
							`).join("");
							// Attach click handlers
							dropdown.querySelectorAll(".add-dd-item").forEach((item) => {
								item.addEventListener("click", () => {
									const idx = parseInt((item as HTMLElement).dataset.idx || "0");
									const u = users[idx];
									selectedUser = { did: u.id, username: u.username, displayName: u.displayName || u.username };
									usernameInput.value = u.username;
									dropdown.innerHTML = "";
									dropdown.classList.remove("open");
									selectedDiv.innerHTML = `<span class="add-selected-chip">Selected: <strong>${selectedUser.displayName}</strong> (@${selectedUser.username})</span>`;
									addBtn.disabled = false;
								});
							});
						}
						dropdown.classList.add("open");
					} catch { dropdown.classList.remove("open"); }
				}, 300);
			});

			// Close dropdown on outside click
			overlay.addEventListener("click", (e) => {
				if (!(e.target as HTMLElement).closest(".add-search-wrapper")) {
					dropdown.classList.remove("open");
				}
			});
		}

		// Add by username
		addBtn?.addEventListener("click", async () => {
			if (!selectedUser) return;
			const role = (container.querySelector("#am-role") as HTMLSelectElement).value;
			const token = getAccessToken();
			if (!token) return;
			try {
				const res = await fetch(`/api/spaces/${slug}/members/add`, {
					method: "POST",
					headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
					body: JSON.stringify({ username: selectedUser.username, role }),
				});
				if (res.ok) {
					feedback.textContent = `Invite sent to ${selectedUser.username}`;
					feedback.style.color = "#34d399";
					selectedUser = null;
					usernameInput.value = "";
					selectedDiv.innerHTML = "";
					addBtn.disabled = true;
					setTimeout(() => { feedback.textContent = ""; }, 3000);
					this.#loadMembers(overlay, slug);
					this.#loadInvitations(overlay, slug);
				} else {
					const err = await res.json();
					feedback.textContent = err.error || "Failed to invite";
					feedback.style.color = "#ef4444";
					setTimeout(() => { feedback.textContent = ""; }, 3000);
				}
			} catch {
				feedback.textContent = "Network error";
				feedback.style.color = "#ef4444";
				setTimeout(() => { feedback.textContent = ""; }, 3000);
			}
		});

		// Add by email
		const emailInput = container.querySelector("#am-email") as HTMLInputElement;
		const emailBtn = container.querySelector("#am-email-btn") as HTMLButtonElement;
		const emailFeedback = container.querySelector("#am-email-feedback") as HTMLElement;

		emailBtn?.addEventListener("click", async () => {
			if (!emailInput?.value) return;
			const role = (container.querySelector("#am-email-role") as HTMLSelectElement).value;
			const token = getAccessToken();
			if (!token) return;
			try {
				const res = await fetch(`/api/spaces/${slug}/invite`, {
					method: "POST",
					headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
					body: JSON.stringify({ email: emailInput.value, role }),
				});
				if (res.ok) {
					emailFeedback.textContent = "Invite sent";
					emailFeedback.style.color = "#34d399";
					emailInput.value = "";
					setTimeout(() => { emailFeedback.textContent = ""; }, 3000);
					this.#loadInvitations(overlay, slug);
				} else {
					const err = await res.json().catch(() => ({ error: "Failed to invite" })) as { error?: string };
					emailFeedback.textContent = err.error || "Failed to invite";
					emailFeedback.style.color = "#ef4444";
					setTimeout(() => { emailFeedback.textContent = ""; }, 3000);
				}
			} catch {
				emailFeedback.textContent = "Network error";
				emailFeedback.style.color = "#ef4444";
				setTimeout(() => { emailFeedback.textContent = ""; }, 3000);
			}
		});
	}

	async #loadInvitations(overlay: HTMLElement, slug: string) {
		const container = overlay.querySelector("#es-invitations-list") as HTMLElement;
		try {
			const token = getAccessToken();
			const headers: Record<string, string> = {};
			if (token) headers["Authorization"] = `Bearer ${token}`;

			// Fetch access requests and email invites in parallel
			const [reqRes, invRes] = await Promise.all([
				fetch(`/api/spaces/${slug}/access-requests`, { headers }),
				fetch(`/api/spaces/${slug}/invites`, { headers }).catch(() => null),
			]);

			// Access requests
			let html = "";
			if (reqRes.ok) {
				const data = await reqRes.json();
				const requests: Array<{ id: string; requesterUsername: string; message?: string; status: string; createdAt: number }> = data.requests || [];
				const pending = requests.filter((r) => r.status === "pending");
				const resolved = requests.filter((r) => r.status !== "pending");

				html += `<div class="section-label">Access Requests</div>`;
				if (pending.length > 0) {
					html += pending.map((r) => `
						<div class="invite-item">
							<div class="invite-info">
								<span class="invite-name">${r.requesterUsername}</span>
								${r.message ? `<span class="invite-msg">${r.message.replace(/</g, "&lt;")}</span>` : ""}
							</div>
							<div class="invite-actions">
								<button class="btn-sm btn-sm--approve" data-req-id="${r.id}" data-action="approve">Approve</button>
								<button class="btn-sm btn-sm--deny" data-req-id="${r.id}" data-action="deny">Deny</button>
							</div>
						</div>`).join("");
				} else {
					html += `<div class="loading" style="padding:8px 0">No pending requests</div>`;
				}
				if (resolved.length > 0) {
					html += `<div class="section-label" style="opacity:0.4;padding:8px 0 4px">Resolved</div>`;
					html += resolved.map((r) => `
						<div class="invite-item invite-resolved">
							<span class="invite-name">${r.requesterUsername}</span>
							<span class="invite-status invite-status--${r.status}">${r.status}</span>
						</div>`).join("");
				}
			} else {
				html += `<div class="loading">Failed to load access requests</div>`;
			}

			// Email invites
			html += `<div class="section-label" style="margin-top:16px">Pending Email Invites</div>`;
			if (invRes && invRes.ok) {
				const invData = await invRes.json();
				const invites: Array<{ id: string; email?: string; role: string; status: string; expiresAt: string }> = invData.invites || [];
				const pendingInvites = invites.filter((inv) => inv.status === "pending");

				if (pendingInvites.length > 0) {
					html += pendingInvites.map((inv) => {
						const expiry = new Date(inv.expiresAt).toLocaleDateString();
						return `
							<div class="invite-item">
								<div class="invite-info">
									<span class="invite-name">${(inv.email || "Link invite").replace(/</g, "&lt;")}</span>
									<span class="invite-msg">${inv.role} &middot; expires ${expiry}</span>
								</div>
								<button class="btn-sm btn-sm--deny" data-revoke-id="${inv.id}">Revoke</button>
							</div>`;
					}).join("");
				} else {
					html += `<div class="loading" style="padding:8px 0">No pending invites</div>`;
				}
			} else {
				html += `<div class="loading" style="padding:8px 0">No pending invites</div>`;
			}

			container.innerHTML = html;

			// Approve/Deny handlers
			container.querySelectorAll("[data-req-id]").forEach((btn) => {
				btn.addEventListener("click", async () => {
					const el = btn as HTMLElement;
					const reqId = el.dataset.reqId!;
					const action = el.dataset.action as "approve" | "deny";
					const token = getAccessToken();
					try {
						const res = await fetch(`/api/spaces/${slug}/access-requests/${reqId}`, {
							method: "PATCH",
							headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
							body: JSON.stringify({ action }),
						});
						if (!res.ok) { const d = await res.json(); alert(d.error || "Failed"); return; }
						this.#loadInvitations(overlay, slug);
					} catch { alert("Failed to process request"); }
				});
			});

			// Revoke invite handlers
			container.querySelectorAll("[data-revoke-id]").forEach((btn) => {
				btn.addEventListener("click", async () => {
					const id = (btn as HTMLElement).dataset.revokeId!;
					const token = getAccessToken();
					if (!token) return;
					try {
						const res = await fetch(`/api/spaces/${slug}/invites/${id}/revoke`, {
							method: "POST",
							headers: { Authorization: `Bearer ${token}` },
						});
						if (!res.ok) { const d = await res.json().catch(() => ({})); alert((d as any).error || "Failed"); return; }
						this.#loadInvitations(overlay, slug);
					} catch { alert("Failed to revoke invite"); }
				});
			});
		} catch {
			container.innerHTML = `<div class="loading">Failed to load invitations</div>`;
		}
	}

	async #loadModulesConfig(overlay: HTMLElement, slug: string) {
		const container = overlay.querySelector("#es-modules-list") as HTMLElement;
		const statusEl = overlay.querySelector("#es-modules-status") as HTMLElement;
		try {
			const token = getAccessToken();
			const headers: Record<string, string> = {};
			if (token) headers["Authorization"] = `Bearer ${token}`;

			// Fetch module config and encryption status in parallel
			const [modRes, encRes] = await Promise.all([
				fetch(`/api/spaces/${slug}/modules`, { headers }),
				fetch(`/api/spaces/${slug}/encryption`, { headers }),
			]);

			if (!modRes.ok) { container.innerHTML = `<div class="loading">Failed to load modules</div>`; return; }
			const modData = await modRes.json();
			const encData = encRes.ok ? await encRes.json() : { encrypted: false };

			interface SettingField {
				key: string; label: string; type: string; description?: string;
				default?: string | boolean; options?: Array<{ value: string; label: string }>;
			}
			interface ModConfig {
				id: string; name: string; icon: string; enabled: boolean;
				scoping: { defaultScope: string; userConfigurable: boolean; currentScope: string };
				settingsSchema?: SettingField[];
				settings?: Record<string, string | boolean>;
			}

			const modules: ModConfig[] = modData.modules || [];

			let html = `
				<div class="module-encryption">
					<label class="module-row">
						<span class="module-label">&#x1F512; End-to-end encryption</span>
						<label class="toggle-switch">
							<input type="checkbox" id="es-encrypt-toggle" ${encData.encrypted ? "checked" : ""} />
							<span class="toggle-slider"></span>
						</label>
					</label>
					<div class="module-hint">When enabled, documents are encrypted client-side. Server cannot read content.</div>
				</div>
				<div class="module-divider"></div>
				<div class="module-section-label">Enabled Modules</div>
			`;

			for (const m of modules) {
				if (m.id === "rspace") continue; // core module, always enabled
				const hasSettings = m.settingsSchema && m.settingsSchema.length > 0;
				html += `
					<label class="module-row">
						<span class="module-label">${m.icon} ${m.name}</span>
						<span style="display:flex;align-items:center;gap:6px;">
							${hasSettings ? `<button class="mod-settings-btn" data-mod-id="${m.id}" title="Settings" style="background:none;border:none;color:#737373;cursor:pointer;font-size:14px;padding:2px;">&#9881;</button>` : ''}
							<label class="toggle-switch">
								<input type="checkbox" class="mod-toggle" data-mod-id="${m.id}" ${m.enabled ? "checked" : ""} />
								<span class="toggle-slider"></span>
							</label>
						</span>
					</label>`;

				if (m.scoping.userConfigurable) {
					html += `
					<div class="scope-row">
						<span class="scope-label">Data scope:</span>
						<select class="scope-select data-scope-select" data-mod-id="${m.id}">
							<option value="space" ${m.scoping.currentScope === "space" ? "selected" : ""}>Space</option>
							<option value="global" ${m.scoping.currentScope === "global" ? "selected" : ""}>Global</option>
						</select>
					</div>`;
				}

				if (hasSettings) {
					html += `<div class="mod-settings-panel" data-mod-id="${m.id}" style="display:none;padding:8px 12px;background:#111;border:1px solid #333;border-radius:6px;margin:4px 0 8px;">`;
					for (const field of m.settingsSchema!) {
						const val = m.settings?.[field.key] ?? field.default ?? '';
						html += `<div style="margin-bottom:8px;">`;
						html += `<label style="display:block;font-size:11px;color:#a3a3a3;margin-bottom:3px;">${field.label}</label>`;

						if (field.type === 'boolean') {
							html += `<label class="toggle-switch"><input type="checkbox" class="mod-setting" data-mod-id="${m.id}" data-key="${field.key}" ${val ? 'checked' : ''} /><span class="toggle-slider"></span></label>`;
						} else if (field.type === 'select') {
							html += `<select class="mod-setting scope-select" data-mod-id="${m.id}" data-key="${field.key}">`;
							for (const opt of field.options || []) {
								html += `<option value="${opt.value}" ${val === opt.value ? 'selected' : ''}>${opt.label}</option>`;
							}
							html += `</select>`;
						} else if (field.type === 'notebook-id') {
							html += `<select class="mod-setting scope-select mod-notebook-select" data-mod-id="${m.id}" data-key="${field.key}" data-space="${slug}"><option value="">None</option></select>`;
						} else if (field.type === 'password') {
							html += `<input type="password" class="mod-setting" data-mod-id="${m.id}" data-key="${field.key}" value="${typeof val === 'string' ? val.replace(/"/g, '&quot;') : ''}" style="width:100%;padding:5px 8px;background:#0a0a0a;border:1px solid #404040;border-radius:4px;color:#e5e5e5;font-size:12px;" autocomplete="off" />`;
						} else {
							html += `<input type="text" class="mod-setting" data-mod-id="${m.id}" data-key="${field.key}" value="${typeof val === 'string' ? val.replace(/"/g, '&quot;') : ''}" style="width:100%;padding:5px 8px;background:#0a0a0a;border:1px solid #404040;border-radius:4px;color:#e5e5e5;font-size:12px;" />`;
						}

						if (field.description) {
							html += `<div style="font-size:10px;color:#525252;margin-top:2px;">${field.description}</div>`;
						}
						html += `</div>`;
					}
					html += `</div>`;
				}
			}

			html += `
				<div class="actions" style="margin-top:1rem">
					<button class="btn btn--primary" id="es-modules-save">Save Module Config</button>
				</div>
			`;

			container.innerHTML = html;

			// Gear button toggles settings panel
			container.querySelectorAll(".mod-settings-btn").forEach((btn) => {
				btn.addEventListener("click", (e) => {
					e.preventDefault();
					e.stopPropagation();
					const modId = (btn as HTMLElement).dataset.modId!;
					const panel = container.querySelector(`.mod-settings-panel[data-mod-id="${modId}"]`) as HTMLElement;
					if (panel) panel.style.display = panel.style.display === "none" ? "block" : "none";
				});
			});

			// Populate notebook-id selects
			container.querySelectorAll(".mod-notebook-select").forEach(async (sel) => {
				const select = sel as HTMLSelectElement;
				const space = select.dataset.space!;
				const modId = select.dataset.modId!;
				const key = select.dataset.key!;
				const savedVal = modules.find(m => m.id === modId)?.settings?.[key] || '';
				try {
					const token = getAccessToken();
					const nbRes = await fetch(`${getModuleApiBase("rnotes")}/api/notebooks`, {
						headers: token ? { Authorization: `Bearer ${token}` } : {},
					});
					if (nbRes.ok) {
						const nbData = await nbRes.json();
						const notebooks = nbData.notebooks || (Array.isArray(nbData) ? nbData : []);
						for (const nb of notebooks) {
							const opt = document.createElement("option");
							opt.value = nb.id;
							opt.textContent = nb.title;
							select.appendChild(opt);
						}
						if (savedVal) select.value = savedVal as string;
					}
				} catch {}
			});

			// Save handler
			container.querySelector("#es-modules-save")?.addEventListener("click", async () => {
				statusEl.textContent = "Saving...";
				statusEl.className = "status";

				// Collect enabled modules
				const enabledModules: string[] = ["rspace"];
				container.querySelectorAll(".mod-toggle").forEach((cb) => {
					const el = cb as HTMLInputElement;
					if (el.checked) enabledModules.push(el.dataset.modId!);
				});

				// Collect scope overrides
				const scopeOverrides: Record<string, string> = {};
				container.querySelectorAll(".data-scope-select").forEach((sel) => {
					const el = sel as HTMLSelectElement;
					scopeOverrides[el.dataset.modId!] = el.value;
				});

				// Check encryption toggle
				const encryptToggle = container.querySelector("#es-encrypt-toggle") as HTMLInputElement;
				const newEncrypted = encryptToggle?.checked ?? false;

				try {
					const token = getAccessToken();
					const authHeaders = { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) };

					// Collect module settings
					const moduleSettings: Record<string, Record<string, string | boolean>> = {};
					container.querySelectorAll(".mod-setting").forEach((el) => {
						const input = el as HTMLInputElement | HTMLSelectElement;
						const modId = input.dataset.modId!;
						const key = input.dataset.key!;
						if (!moduleSettings[modId]) moduleSettings[modId] = {};
						if (input.type === "checkbox") {
							moduleSettings[modId][key] = (input as HTMLInputElement).checked;
						} else {
							moduleSettings[modId][key] = input.value;
						}
					});

					// Save modules config
					const patchBody: Record<string, unknown> = { enabledModules, scopeOverrides };
					if (Object.keys(moduleSettings).length > 0) patchBody.moduleSettings = moduleSettings;

					const modSaveRes = await fetch(`/api/spaces/${slug}/modules`, {
						method: "PATCH",
						headers: authHeaders,
						body: JSON.stringify(patchBody),
					});
					if (!modSaveRes.ok) {
						const d = await modSaveRes.json();
						throw new Error(d.error || "Failed to save modules");
					}

					// Save encryption if changed
					if (newEncrypted !== encData.encrypted) {
						const encSaveRes = await fetch(`/api/spaces/${slug}/encryption`, {
							method: "PATCH",
							headers: authHeaders,
							body: JSON.stringify({ encrypted: newEncrypted }),
						});
						if (!encSaveRes.ok) {
							const d = await encSaveRes.json();
							throw new Error(d.error || "Failed to update encryption");
						}
					}

					statusEl.textContent = "Saved! Reload to apply changes.";
					statusEl.className = "status success";
				} catch (err: any) {
					statusEl.textContent = err.message || "Failed to save";
					statusEl.className = "status error";
				}
			});
		} catch {
			container.innerHTML = `<div class="loading">Failed to load module config</div>`;
		}
	}

	// ── Create Space Modal ──

	#pendingMembers: Array<{ username: string; did: string; displayName: string; role: string; type: 'username' }> = [];
	#pendingEmailInvites: Array<{ email: string; role: string }> = [];
	#slugManuallyEdited = false;

	#showCreateSpaceModal(name: string, slug: string, visibility: string) {
		if (document.querySelector(".rstack-create-space-overlay")) return;

		this.#pendingMembers = [];
		this.#pendingEmailInvites = [];
		this.#slugManuallyEdited = false;

		const discoverableDefault = visibility === 'public';

		const overlay = document.createElement("div");
		overlay.className = "rstack-create-space-overlay";
		overlay.innerHTML = `
			<style>${CREATE_SPACE_MODAL_STYLES}</style>
			<div class="cs-modal">
				<button class="cs-close" data-action="close">&times;</button>
				<h2 class="cs-title">Create Space</h2>

				<div class="cs-columns">
					<div class="cs-col-left">
						<label class="cs-label">Space Name</label>
						<input class="cs-input" id="cs-name" value="${name.replace(/"/g, "&quot;")}" maxlength="60" />

						<label class="cs-label">Slug</label>
						<div class="cs-slug-row">
							<input class="cs-input cs-slug-input" id="cs-slug" value="${slug}" maxlength="40" />
							<span class="cs-slug-suffix">.rspace.online</span>
						</div>
						<div class="cs-slug-status" id="cs-slug-status"></div>

						<label class="cs-label">Description</label>
						<textarea class="cs-input cs-textarea" id="cs-description" rows="3" placeholder="What is this space about?"></textarea>
					</div>

					<div class="cs-col-right">
						<label class="cs-label">Visibility</label>
						<div class="cs-vis-cards">
							<label class="cs-vis-card ${visibility === 'private' ? 'selected' : ''}">
								<input type="radio" name="cs-vis" value="private" ${visibility === 'private' ? 'checked' : ''} />
								<span class="cs-vis-dot cs-vis-dot--private"></span>
								<span class="cs-vis-card-title">Private</span>
								<span class="cs-vis-card-desc">Invite-only</span>
							</label>
							<label class="cs-vis-card ${visibility === 'permissioned' ? 'selected' : ''}">
								<input type="radio" name="cs-vis" value="permissioned" ${visibility === 'permissioned' ? 'checked' : ''} />
								<span class="cs-vis-dot cs-vis-dot--permissioned"></span>
								<span class="cs-vis-card-title">Permissioned</span>
								<span class="cs-vis-card-desc">Auth required</span>
							</label>
							<label class="cs-vis-card ${visibility === 'public' ? 'selected' : ''}">
								<input type="radio" name="cs-vis" value="public" ${visibility === 'public' ? 'checked' : ''} />
								<span class="cs-vis-dot cs-vis-dot--public"></span>
								<span class="cs-vis-card-title">Public</span>
								<span class="cs-vis-card-desc">Anyone can view</span>
							</label>
						</div>
						<label class="cs-discover-row ${visibility === 'private' ? 'cs-hidden' : ''}" id="cs-discover-row">
							<input type="checkbox" id="cs-discoverable" ${discoverableDefault ? 'checked' : ''} />
							<span>Show in Explore Spaces</span>
						</label>
					</div>
				</div>

				<div class="cs-section">
					<label class="cs-label">Add Members</label>
					<div class="cs-member-search-row">
						<div class="cs-search-wrapper">
							<input class="cs-input cs-member-input" id="cs-member-search" placeholder="@username or email" autocomplete="off" />
							<div class="cs-search-dropdown" id="cs-search-dropdown"></div>
						</div>
						<select class="cs-role-select" id="cs-member-role">
							<option value="member">member</option>
							<option value="viewer">viewer</option>
							<option value="admin">admin</option>
						</select>
						<button class="cs-add-btn" id="cs-add-member" disabled>Add</button>
					</div>
					<div class="cs-member-chips" id="cs-member-chips">
						<span class="cs-chip cs-chip--owner">You (owner)</span>
					</div>
				</div>

				<div class="cs-section">
					<label class="cs-label">Invite Link</label>
					<div class="cs-invite-row">
						<input class="cs-input cs-invite-input" id="cs-invite-link" value="" readonly placeholder="Created after space is made..." />
						<button class="cs-copy-btn" id="cs-copy-invite" disabled>Copy</button>
					</div>
					<div class="cs-invite-hint">A shareable invite link will be generated when you create the space.</div>
				</div>

				<div class="cs-footer">
					<div class="cs-status" id="cs-status"></div>
					<div class="cs-footer-actions">
						<button class="cs-btn cs-btn--secondary" data-action="close">Cancel</button>
						<button class="cs-btn cs-btn--primary" id="cs-create-btn">Create Space</button>
					</div>
				</div>
			</div>
		`;

		const close = () => {
			overlay.remove();
			// Re-open create form with values preserved
			this.#createFormOpen = true;
			this.#createName = (overlay.querySelector("#cs-name") as HTMLInputElement)?.value || name;
		};
		overlay.querySelectorAll('[data-action="close"]').forEach(el =>
			el.addEventListener("click", close)
		);
		overlay.addEventListener("click", (e) => { if (e.target === overlay) close(); });

		document.body.appendChild(overlay);

		// ── Wire up all interactivity ──
		const nameInput = overlay.querySelector("#cs-name") as HTMLInputElement;
		const slugInput = overlay.querySelector("#cs-slug") as HTMLInputElement;
		const slugStatus = overlay.querySelector("#cs-slug-status") as HTMLElement;
		const visCards = overlay.querySelectorAll<HTMLInputElement>('input[name="cs-vis"]');
		const discoverRow = overlay.querySelector("#cs-discover-row") as HTMLElement;
		const discoverCheck = overlay.querySelector("#cs-discoverable") as HTMLInputElement;
		const searchInput = overlay.querySelector("#cs-member-search") as HTMLInputElement;
		const searchDropdown = overlay.querySelector("#cs-search-dropdown") as HTMLElement;
		const roleSelect = overlay.querySelector("#cs-member-role") as HTMLSelectElement;
		const addBtn = overlay.querySelector("#cs-add-member") as HTMLButtonElement;
		const chipsEl = overlay.querySelector("#cs-member-chips") as HTMLElement;
		const createBtn = overlay.querySelector("#cs-create-btn") as HTMLButtonElement;
		const statusEl = overlay.querySelector("#cs-status") as HTMLElement;

		const toSlug = (n: string) =>
			n.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);

		// Name → slug auto-sync
		nameInput.addEventListener("input", () => {
			if (!this.#slugManuallyEdited) {
				slugInput.value = toSlug(nameInput.value);
				this.#checkSlugAvailability(slugInput.value, slugStatus, createBtn);
			}
		});

		// Slug manual edit detection
		slugInput.addEventListener("input", () => {
			this.#slugManuallyEdited = true;
			slugInput.value = toSlug(slugInput.value);
			this.#checkSlugAvailability(slugInput.value, slugStatus, createBtn);
		});

		// Visibility → discoverable sync
		visCards.forEach(radio => {
			radio.addEventListener("change", () => {
				// Update card selection styling
				overlay.querySelectorAll(".cs-vis-card").forEach(c => c.classList.remove("selected"));
				radio.closest(".cs-vis-card")?.classList.add("selected");

				const vis = radio.value;
				if (vis === 'private') {
					discoverRow.classList.add("cs-hidden");
					discoverCheck.checked = false;
				} else {
					discoverRow.classList.remove("cs-hidden");
					discoverCheck.checked = vis === 'public';
				}
			});
		});

		// Member search with debounce
		let searchTimer: ReturnType<typeof setTimeout>;
		let selectedUser: { username: string; did: string; displayName: string } | null = null;

		searchInput.addEventListener("input", () => {
			clearTimeout(searchTimer);
			const q = searchInput.value.trim();
			selectedUser = null;
			addBtn.disabled = true;

			if (q.length < 2) {
				searchDropdown.innerHTML = "";
				searchDropdown.classList.remove("open");
				return;
			}

			// Check if it looks like an email
			const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(q);

			searchTimer = setTimeout(async () => {
				if (isEmail) {
					searchDropdown.innerHTML = `<div class="cs-dd-item cs-dd-email" data-email="${q.replace(/"/g, "&quot;")}">Invite <strong>${q}</strong> by email</div>`;
					searchDropdown.classList.add("open");
					this.#attachDropdownEmail(searchDropdown, searchInput, roleSelect, addBtn, chipsEl);
					return;
				}

				try {
					const token = getAccessToken();
					const res = await fetch(`/api/users/search?q=${encodeURIComponent(q)}&limit=5`, {
						headers: token ? { Authorization: `Bearer ${token}` } : {},
					});
					if (!res.ok) { searchDropdown.classList.remove("open"); return; }
					const data = await res.json();
					const users: Array<{ username: string; did: string; displayName?: string }> = data.users || [];

					if (users.length === 0) {
						// Check for email-like input
						if (q.includes("@") && q.includes(".")) {
							searchDropdown.innerHTML = `<div class="cs-dd-item cs-dd-email" data-email="${q.replace(/"/g, "&quot;")}">Invite <strong>${q}</strong> by email</div>`;
						} else {
							searchDropdown.innerHTML = `<div class="cs-dd-empty">No users found</div>`;
						}
					} else {
						const myUsername = getUsername()?.toLowerCase();
						searchDropdown.innerHTML = users.map(u => {
							const isSelf = u.username.toLowerCase() === myUsername;
							const alreadyAdded = this.#pendingMembers.some(m => m.did === u.did);
							return `<div class="cs-dd-item ${isSelf ? 'cs-dd-self' : ''} ${alreadyAdded ? 'cs-dd-added' : ''}" data-username="${u.username}" data-did="${u.did}" data-display="${(u.displayName || u.username).replace(/"/g, "&quot;")}">
								<span class="cs-dd-name">${u.displayName || u.username}</span>
								<span class="cs-dd-user">@${u.username}</span>
								${isSelf ? '<span class="cs-dd-badge">You (owner)</span>' : ''}
								${alreadyAdded ? '<span class="cs-dd-badge">Added</span>' : ''}
							</div>`;
						}).join("");

						// Add email option at the bottom if input has @ and .
						if (q.includes("@") && q.includes(".")) {
							searchDropdown.innerHTML += `<div class="cs-dd-item cs-dd-email" data-email="${q.replace(/"/g, "&quot;")}">Invite <strong>${q}</strong> by email</div>`;
						}
					}
					searchDropdown.classList.add("open");

					// Attach click handlers
					searchDropdown.querySelectorAll(".cs-dd-item:not(.cs-dd-self):not(.cs-dd-added):not(.cs-dd-email)").forEach(item => {
						item.addEventListener("click", () => {
							const el = item as HTMLElement;
							selectedUser = {
								username: el.dataset.username!,
								did: el.dataset.did!,
								displayName: el.dataset.display!,
							};
							searchInput.value = `@${selectedUser.username}`;
							searchDropdown.classList.remove("open");
							addBtn.disabled = false;
						});
					});

					this.#attachDropdownEmail(searchDropdown, searchInput, roleSelect, addBtn, chipsEl);
				} catch {
					searchDropdown.classList.remove("open");
				}
			}, 300);
		});

		// Close dropdown on outside click
		overlay.addEventListener("click", (e) => {
			if (!(e.target as HTMLElement).closest(".cs-search-wrapper")) {
				searchDropdown.classList.remove("open");
			}
		});

		// Add member button
		addBtn.addEventListener("click", () => {
			if (selectedUser) {
				const role = roleSelect.value;
				this.#pendingMembers.push({ ...selectedUser, role, type: 'username' });
				selectedUser = null;
				searchInput.value = "";
				addBtn.disabled = true;
				this.#renderMemberChips(chipsEl);
			}
		});

		// Create button
		createBtn.addEventListener("click", () => {
			this.#doCreateSpace(overlay);
		});

		// Initial slug check
		if (slug) {
			this.#checkSlugAvailability(slug, slugStatus, createBtn);
		}
	}

	#attachDropdownEmail(dropdown: HTMLElement, searchInput: HTMLInputElement, roleSelect: HTMLSelectElement, addBtn: HTMLButtonElement, chipsEl: HTMLElement) {
		dropdown.querySelectorAll(".cs-dd-email").forEach(item => {
			item.addEventListener("click", () => {
				const email = (item as HTMLElement).dataset.email!;
				const role = roleSelect.value;
				if (!this.#pendingEmailInvites.some(e => e.email === email)) {
					this.#pendingEmailInvites.push({ email, role });
				}
				searchInput.value = "";
				dropdown.classList.remove("open");
				addBtn.disabled = true;
				this.#renderMemberChips(chipsEl);
			});
		});
	}

	#renderMemberChips(chipsEl: HTMLElement) {
		let html = '<span class="cs-chip cs-chip--owner">You (owner)</span>';
		for (const m of this.#pendingMembers) {
			html += `<span class="cs-chip">@${m.username} <span class="cs-chip-role">${m.role}</span> <button class="cs-chip-remove" data-type="username" data-did="${m.did}">&times;</button></span>`;
		}
		for (const e of this.#pendingEmailInvites) {
			html += `<span class="cs-chip cs-chip--email">${e.email} <span class="cs-chip-role">${e.role}</span> <button class="cs-chip-remove" data-type="email" data-email="${e.email}">&times;</button></span>`;
		}
		chipsEl.innerHTML = html;

		// Attach remove handlers
		chipsEl.querySelectorAll(".cs-chip-remove").forEach(btn => {
			btn.addEventListener("click", () => {
				const el = btn as HTMLElement;
				if (el.dataset.type === 'username') {
					this.#pendingMembers = this.#pendingMembers.filter(m => m.did !== el.dataset.did);
				} else {
					this.#pendingEmailInvites = this.#pendingEmailInvites.filter(e => e.email !== el.dataset.email);
				}
				this.#renderMemberChips(chipsEl);
			});
		});
	}

	#slugCheckTimer: ReturnType<typeof setTimeout> | null = null;

	#checkSlugAvailability(slug: string, statusEl: HTMLElement, createBtn: HTMLButtonElement) {
		if (this.#slugCheckTimer) clearTimeout(this.#slugCheckTimer);

		if (!slug) {
			statusEl.textContent = "";
			createBtn.disabled = true;
			return;
		}

		if (!/^[a-z0-9-]+$/.test(slug)) {
			statusEl.textContent = "Only lowercase letters, numbers, and hyphens";
			statusEl.className = "cs-slug-status cs-slug-taken";
			createBtn.disabled = true;
			return;
		}

		statusEl.textContent = "Checking...";
		statusEl.className = "cs-slug-status";

		this.#slugCheckTimer = setTimeout(async () => {
			try {
				const res = await fetch(`/api/spaces/${slug}`, { method: "GET" });
				if (res.status === 404) {
					statusEl.textContent = "Available";
					statusEl.className = "cs-slug-status cs-slug-available";
					createBtn.disabled = false;
				} else {
					statusEl.textContent = "Already taken";
					statusEl.className = "cs-slug-status cs-slug-taken";
					createBtn.disabled = true;
				}
			} catch {
				statusEl.textContent = "";
				createBtn.disabled = false;
			}
		}, 400);
	}

	async #doCreateSpace(overlay: HTMLElement) {
		const nameInput = overlay.querySelector("#cs-name") as HTMLInputElement;
		const slugInput = overlay.querySelector("#cs-slug") as HTMLInputElement;
		const descInput = overlay.querySelector("#cs-description") as HTMLTextAreaElement;
		const visRadio = overlay.querySelector('input[name="cs-vis"]:checked') as HTMLInputElement;
		const discoverCheck = overlay.querySelector("#cs-discoverable") as HTMLInputElement;
		const createBtn = overlay.querySelector("#cs-create-btn") as HTMLButtonElement;
		const statusEl = overlay.querySelector("#cs-status") as HTMLElement;
		const inviteLinkInput = overlay.querySelector("#cs-invite-link") as HTMLInputElement;
		const copyBtn = overlay.querySelector("#cs-copy-invite") as HTMLButtonElement;

		const name = nameInput.value.trim();
		const slug = slugInput.value.trim();
		const description = descInput.value.trim();
		const visibility = visRadio?.value || "public";
		const discoverable = discoverCheck?.checked ?? false;

		if (!name) { statusEl.textContent = "Name is required"; statusEl.className = "cs-status cs-status--error"; return; }
		if (!slug) { statusEl.textContent = "Slug is required"; statusEl.className = "cs-status cs-status--error"; return; }

		const token = getAccessToken();
		if (!token) { statusEl.textContent = "Please sign in first"; statusEl.className = "cs-status cs-status--error"; return; }

		createBtn.disabled = true;
		statusEl.textContent = "Creating space...";
		statusEl.className = "cs-status";

		try {
			// Step 1: Create the space
			const createRes = await fetch("/api/spaces", {
				method: "POST",
				headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
				body: JSON.stringify({ name, slug, visibility }),
			});
			const createData = await createRes.json();
			if (!createRes.ok) {
				statusEl.textContent = createData.error || "Failed to create space";
				statusEl.className = "cs-status cs-status--error";
				createBtn.disabled = false;
				return;
			}

			// Step 2: Apply description + discoverable (if non-default)
			if (description || discoverable) {
				statusEl.textContent = "Configuring space...";
				await fetch(`/api/spaces/${slug}`, {
					method: "PATCH",
					headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
					body: JSON.stringify({ description, discoverable }),
				}).catch(() => {});
			}

			// Step 3: Add members + send email invites (best-effort, parallel)
			if (this.#pendingMembers.length > 0 || this.#pendingEmailInvites.length > 0) {
				statusEl.textContent = "Adding members...";
				const memberPromises = this.#pendingMembers.map(m =>
					fetch(`/api/spaces/${slug}/members/add`, {
						method: "POST",
						headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
						body: JSON.stringify({ username: m.username, role: m.role }),
					}).catch(() => {})
				);
				const emailPromises = this.#pendingEmailInvites.map(e =>
					fetch(`/api/spaces/${slug}/invite`, {
						method: "POST",
						headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
						body: JSON.stringify({ email: e.email, role: e.role }),
					}).catch(() => {})
				);
				await Promise.all([...memberPromises, ...emailPromises]);
			}

			// Step 4: Generate invite link
			statusEl.textContent = "Generating invite link...";
			try {
				const inviteRes = await fetch(`/api/spaces/${slug}/invites`, {
					method: "POST",
					headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
					body: JSON.stringify({ role: "member", maxUses: 0, expiresInDays: 7 }),
				});
				if (inviteRes.ok) {
					const inviteData = await inviteRes.json();
					const inviteToken = inviteData.token || inviteData.inviteToken;
					if (inviteToken) {
						const inviteUrl = `https://${slug}.rspace.online/join/${inviteToken}`;
						inviteLinkInput.value = inviteUrl;
						copyBtn.disabled = false;
						copyBtn.addEventListener("click", () => {
							navigator.clipboard.writeText(inviteUrl).then(() => {
								copyBtn.textContent = "Copied!";
								setTimeout(() => { copyBtn.textContent = "Copy"; }, 2000);
							});
						});
					}
				}
			} catch {
				// invite link is best-effort
			}

			// Step 5: Success state
			statusEl.textContent = "Space created! Redirecting...";
			statusEl.className = "cs-status cs-status--success";
			createBtn.textContent = "Done";

			// Auto-redirect after 3 seconds
			setTimeout(() => {
				window.location.href = rspaceNavUrl(slug, "rspace");
			}, 3000);
		} catch (err: any) {
			statusEl.textContent = err.message || "Something went wrong";
			statusEl.className = "cs-status cs-status--error";
			createBtn.disabled = false;
		}
	}

	#getCurrentModule(): string {
		return getModule();
	}

	static define(tag = "rstack-space-switcher") {
		if (!customElements.get(tag)) customElements.define(tag, RStackSpaceSwitcher);
	}
}

const STYLES = `
:host { display: contents; }

.switcher { position: relative; }

.trigger {
  display: flex; align-items: center; gap: 6px;
  padding: 6px 14px; border-radius: 8px; border: none;
  font-size: 0.9rem; font-weight: 600; cursor: pointer;
  transition: background 0.15s;
  background: var(--rs-btn-secondary-bg); color: var(--rs-text-primary);
  white-space: nowrap; min-width: 0; flex-shrink: 1;
}
.trigger:hover { background: var(--rs-bg-hover); }
.space-name { max-width: 160px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.caret { font-size: 0.7em; opacity: 0.6; }

.menu {
  position: fixed; margin-top: 0;
  min-width: 260px; max-width: calc(100vw - 8px); max-height: 400px; overflow-y: auto;
  border-radius: 12px; box-shadow: var(--rs-shadow-lg);
  display: none; z-index: 10001;
  background: var(--rs-bg-surface); border: 1px solid var(--rs-border);
}
.menu.open { display: block; }

.section-label {
  padding: 8px 14px 4px; font-size: 0.7rem; font-weight: 600;
  text-transform: uppercase; letter-spacing: 0.05em; opacity: 0.5;
}
.section-label--private { color: #f87171; opacity: 0.85; }
.section-label--permissioned { color: #fbbf24; opacity: 0.85; }
.section-label--public { color: #34d399; opacity: 0.85; }
.section-label--discover { color: #a78bfa; opacity: 0.85; }
.item--discover-link { font-size: 0.85rem; color: #a78bfa; text-decoration: none; }
.item--discover-link:hover { background: rgba(167,139,250,0.08); }

.item {
  display: flex; align-items: center; gap: 10px;
  padding: 10px 14px; text-decoration: none; cursor: pointer;
  transition: background 0.12s; border-left: 3px solid transparent;
  color: var(--rs-text-primary);
}
.item:hover { background: var(--rs-bg-hover); }
.item.active { background: var(--rs-bg-active); }

/* Visibility color accents — left border */
.item.vis-public { border-left-color: #34d399; }
.item.vis-private { border-left-color: #f87171; }
.item.vis-permissioned { border-left-color: #fbbf24; }

.item-icon { font-size: 1.1rem; flex-shrink: 0; }
.item-name { font-size: 0.875rem; font-weight: 500; flex: 1; }

/* Visibility badge */
.item-vis {
  font-size: 0.9rem; padding: 2px 4px; border-radius: 4px; flex-shrink: 0;
  line-height: 1; display: flex; align-items: center; justify-content: center;
}
.item-vis.vis-public { background: rgba(52,211,153,0.15); color: #34d399; }
.item-vis.vis-private { background: rgba(248,113,113,0.15); color: #f87171; }
.item-vis.vis-permissioned { background: rgba(251,191,36,0.15); color: #fbbf24; }

/* Item row: wraps link + gear icon */
.item-row {
  display: flex; align-items: center; border-left: 3px solid transparent;
  transition: background 0.12s;
}
.item-row .item {
  flex: 1; border-left: none;
}
.item-row:hover { background: var(--rs-bg-hover); }
.item-row.active { background: var(--rs-bg-active); }
.item-row.vis-public { border-left-color: #34d399; }
.item-row.vis-private { border-left-color: #f87171; }
.item-row.vis-permissioned { border-left-color: #fbbf24; }

.item-gear {
  background: none; border: none; cursor: pointer; padding: 6px 10px;
  font-size: 1rem; opacity: 0.4; transition: opacity 0.15s; flex-shrink: 0;
}
.item-gear:hover { opacity: 1; }
.item-gear { color: var(--rs-text-primary); }

.item--create {
  font-size: 0.85rem; font-weight: 600; color: #06b6d4 !important;
  border-left-color: transparent !important;
  background: none; border: none; width: 100%; text-align: left; cursor: pointer;
  font-family: inherit;
}
.item--create:hover { background: rgba(6,182,212,0.08) !important; }

/* Create-space popout */
.create-popout { padding: 8px 12px; }
.create-popout.hidden { display: none; }
.create-input {
  width: 100%; padding: 8px 10px; border-radius: 6px;
  border: 1px solid var(--rs-border); background: var(--rs-bg-surface-sunken);
  color: var(--rs-text-primary); font-size: 0.85rem; outline: none;
  box-sizing: border-box; font-family: inherit;
}
.create-input:focus { border-color: #06b6d4; }
.create-slug {
  font-size: 0.7rem; color: var(--rs-text-muted); padding: 2px 2px 6px;
  min-height: 1em;
}
.create-vis-row {
  display: flex; gap: 10px; margin-bottom: 8px; flex-wrap: wrap;
}
.create-vis-opt {
  display: flex; align-items: center; gap: 4px;
  font-size: 0.78rem; color: var(--rs-text-secondary); cursor: pointer;
}
.create-vis-opt input { margin: 0; }
.vis-dot {
  display: inline-block; width: 8px; height: 8px; border-radius: 50%;
}
.vis-dot--public { background: #34d399; }
.vis-dot--permissioned { background: #fbbf24; }
.vis-dot--private { background: #f87171; }
.create-actions { display: flex; gap: 8px; }
.create-btn {
  padding: 6px 16px; border-radius: 6px; border: none;
  font-size: 0.8rem; font-weight: 600; cursor: pointer;
  background: linear-gradient(135deg, #06b6d4, #7c3aed); color: white;
}
.create-btn:hover { opacity: 0.85; }
.create-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.create-cancel {
  padding: 6px 12px; border-radius: 6px; border: none;
  font-size: 0.8rem; cursor: pointer;
  background: var(--rs-btn-secondary-bg); color: var(--rs-text-secondary);
}
.create-cancel:hover { background: var(--rs-bg-hover); }
.create-status {
  font-size: 0.75rem; color: #f87171; margin-top: 4px; min-height: 1em;
}

/* Personal space CTA */
.item--yourspace {
  border-left-color: #f87171; padding: 12px 14px;
  background: var(--rs-bg-hover);
}
.item--yourspace .item-name { font-weight: 700; font-size: 0.9rem; }
.yourspace-btn {
  margin-left: auto; padding: 5px 12px; border-radius: 6px; border: none;
  font-size: 0.75rem; font-weight: 600; cursor: pointer; white-space: nowrap;
  background: linear-gradient(135deg, #06b6d4, #7c3aed); color: white;
  transition: opacity 0.15s, transform 0.15s;
}
.yourspace-btn:hover { opacity: 0.85; transform: translateY(-1px); }

.divider { height: 1px; margin: 4px 0; background: var(--rs-border-subtle); }

.menu-loading, .menu-empty {
  padding: 16px; text-align: center; font-size: 0.85rem; color: var(--rs-text-secondary);
}

/* Discover section — non-navigable items */
.item--discover { cursor: default; flex-wrap: wrap; }
.item--discover:hover { background: transparent !important; }

.item-request-btn {
  margin-left: auto; padding: 4px 10px; border-radius: 6px; border: none;
  font-size: 0.75rem; font-weight: 600; cursor: pointer;
  background: linear-gradient(135deg, #06b6d4, #7c3aed); color: white;
  transition: opacity 0.15s; white-space: nowrap;
}
.item-request-btn:hover { opacity: 0.85; }

.item-badge { font-size: 0.7rem; padding: 3px 8px; border-radius: 6px; margin-left: auto; white-space: nowrap; }
.item-badge--pending {
  background: rgba(251,191,36,0.15); color: #fbbf24; font-weight: 600;
}
`;

const REQUEST_MODAL_STYLES = `
.rstack-auth-overlay {
  position: fixed; inset: 0; background: rgba(0,0,0,0.6);
  -webkit-backdrop-filter: blur(4px); backdrop-filter: blur(4px); display: flex; align-items: center;
  justify-content: center; z-index: 10000; animation: fadeIn 0.2s;
}
.auth-modal {
  background: var(--rs-bg-surface); border: 1px solid var(--rs-border);
  border-radius: 16px; padding: 2rem; max-width: 420px; width: 90%;
  max-height: 90dvh; overflow-y: auto;
  text-align: center; color: var(--rs-text-primary); box-shadow: var(--rs-shadow-lg);
  animation: slideUp 0.3s; position: relative;
}
@media (max-width: 480px) { .auth-modal { padding: 1.25rem; } }
.auth-modal h2 {
  font-size: 1.5rem; margin-bottom: 0.5rem;
  background: linear-gradient(135deg, #06b6d4, #7c3aed);
  -webkit-background-clip: text; -webkit-text-fill-color: transparent;
}
.auth-modal p { color: var(--rs-text-secondary); font-size: 0.95rem; line-height: 1.6; margin-bottom: 1rem; }
.input {
  width: 100%; padding: 12px 16px; border-radius: 8px;
  border: 1px solid var(--rs-input-border); background: var(--rs-bg-hover);
  color: var(--rs-text-primary); font-size: 0.9rem; margin-bottom: 1rem; outline: none;
  transition: border-color 0.2s; box-sizing: border-box; font-family: inherit;
}
.input:focus { border-color: #06b6d4; }
.input::placeholder { color: var(--rs-text-muted); }
.actions { display: flex; gap: 12px; margin-top: 0.5rem; }
.btn {
  flex: 1; padding: 12px 20px; border-radius: 8px; border: none;
  font-size: 0.95rem; font-weight: 600; cursor: pointer; transition: all 0.2s;
}
.btn--primary { background: linear-gradient(135deg, #06b6d4, #7c3aed); color: white; }
.btn--primary:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(6,182,212,0.3); }
.btn--primary:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
.btn--secondary { background: var(--rs-btn-secondary-bg); color: var(--rs-text-secondary); border: 1px solid var(--rs-border); }
.btn--secondary:hover { background: var(--rs-bg-hover); color: var(--rs-text-primary); }
.error { color: #ef4444; font-size: 0.85rem; margin-top: 0.5rem; min-height: 1.2em; }
.close-btn {
  position: absolute; top: 12px; right: 16px;
  background: none; border: none; color: var(--rs-text-muted); font-size: 1.5rem;
  cursor: pointer; line-height: 1; padding: 4px 8px; border-radius: 6px;
}
.close-btn:hover, .close-btn:active { color: var(--rs-text-primary); background: var(--rs-border); }
.spinner {
  display: inline-block; width: 18px; height: 18px;
  border: 2px solid transparent; border-top-color: currentColor;
  border-radius: 50%; animation: spin 0.7s linear infinite;
  vertical-align: middle; margin-right: 6px;
}
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
@keyframes spin { to { transform: rotate(360deg); } }
`;

const EDIT_SPACE_MODAL_STYLES = `
.rstack-auth-overlay {
  position: fixed; inset: 0; background: rgba(0,0,0,0.6);
  -webkit-backdrop-filter: blur(4px); backdrop-filter: blur(4px); display: flex; align-items: center;
  justify-content: center; z-index: 10000; animation: fadeIn 0.2s;
}
.edit-modal {
  background: var(--rs-bg-surface); border: 1px solid var(--rs-border);
  border-radius: 16px; padding: 2rem; max-width: 520px; width: 92%;
  max-height: 90dvh; overflow-y: auto;
  color: var(--rs-text-primary); box-shadow: var(--rs-shadow-lg);
  animation: slideUp 0.3s; position: relative;
}
@media (max-width: 480px) { .edit-modal { padding: 1.25rem; } }
.edit-modal h2 {
  font-size: 1.5rem; margin: 0 0 1rem;
  background: linear-gradient(135deg, #06b6d4, #7c3aed);
  -webkit-background-clip: text; -webkit-text-fill-color: transparent;
}
.close-btn {
  position: absolute; top: 12px; right: 16px;
  background: none; border: none; color: var(--rs-text-muted); font-size: 1.5rem;
  cursor: pointer; line-height: 1; padding: 4px 8px; border-radius: 6px;
}
.close-btn:hover, .close-btn:active { color: var(--rs-text-primary); background: var(--rs-border); }

/* Tabs */
.tabs { display: flex; gap: 4px; margin-bottom: 1.2rem; border-bottom: 1px solid var(--rs-border); padding-bottom: 0; overflow-x: auto; -webkit-overflow-scrolling: touch; scrollbar-width: none; }
.tabs::-webkit-scrollbar { display: none; }
.tab {
  padding: 8px 16px; border: none; background: none; color: var(--rs-text-secondary);
  font-size: 0.85rem; font-weight: 600; cursor: pointer; border-bottom: 2px solid transparent;
  transition: all 0.15s; border-radius: 6px 6px 0 0; white-space: nowrap; flex-shrink: 0;
}
.tab:hover, .tab:active { color: var(--rs-text-primary); background: var(--rs-bg-hover); }
.tab.active { color: #06b6d4; border-bottom-color: #06b6d4; }
@media (max-width: 480px) { .tab { padding: 8px 12px; font-size: 0.8rem; } }

.tab-panel { }
.tab-panel.hidden { display: none; }

/* Form fields */
.field-label { display: block; font-size: 0.75rem; font-weight: 600; color: var(--rs-text-secondary); margin-bottom: 4px; text-transform: uppercase; letter-spacing: 0.05em; }
.input {
  width: 100%; padding: 10px 14px; border-radius: 8px;
  border: 1px solid var(--rs-input-border); background: var(--rs-bg-hover);
  color: var(--rs-text-primary); font-size: 0.9rem; margin-bottom: 0.75rem; outline: none;
  transition: border-color 0.2s; box-sizing: border-box; font-family: inherit;
}
.input:focus { border-color: #06b6d4; }
select.input { appearance: auto; }

.actions { display: flex; gap: 12px; margin-top: 0.5rem; }
.btn {
  padding: 10px 20px; border-radius: 8px; border: none;
  font-size: 0.9rem; font-weight: 600; cursor: pointer; transition: all 0.2s;
}
.btn--primary { background: linear-gradient(135deg, #06b6d4, #7c3aed); color: white; flex: 1; }
.btn--primary:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(6,182,212,0.3); }
.btn--danger { background: #dc2626; color: white; flex: 1; }
.btn--danger:hover { background: #b91c1c; }

.status { font-size: 0.85rem; margin-top: 0.5rem; min-height: 1.2em; text-align: center; }
.status.success { color: #34d399; }
.status.error { color: #ef4444; }

/* Danger zone */
.danger-zone {
  margin-top: 1.5rem; padding-top: 1rem;
  border-top: 1px solid rgba(239,68,68,0.3);
}
.danger-label { font-size: 0.75rem; font-weight: 600; color: #ef4444; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }

/* Members list */
.member-list { max-height: 320px; overflow-y: auto; }
.member-item {
  display: flex; align-items: center; gap: 10px;
  padding: 8px 0; border-bottom: 1px solid var(--rs-border-subtle);
}
.member-item:last-child { border-bottom: none; }
.member-name { flex: 1; font-size: 0.875rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.role-badge {
  font-size: 0.7rem; padding: 3px 8px; border-radius: 6px; font-weight: 600;
}
.role-owner { background: rgba(251,191,36,0.15); color: #fbbf24; }
.role-select {
  padding: 4px 8px; border-radius: 6px; border: 1px solid var(--rs-input-border);
  background: var(--rs-bg-hover); color: var(--rs-text-primary); font-size: 0.8rem; outline: none;
}
.member-remove {
  background: none; border: none; color: var(--rs-text-muted); font-size: 1.2rem;
  cursor: pointer; padding: 2px 6px; border-radius: 4px; line-height: 1;
}
.member-remove:hover { color: #ef4444; background: rgba(239,68,68,0.1); }
.member-owner { opacity: 0.7; }

/* Invitations */
.invitation-list { max-height: 320px; overflow-y: auto; }
.invite-item {
  display: flex; align-items: center; gap: 10px;
  padding: 8px 0; border-bottom: 1px solid var(--rs-border-subtle);
}
.invite-item:last-child { border-bottom: none; }
.invite-info { flex: 1; min-width: 0; }
.invite-name { font-size: 0.875rem; font-weight: 500; display: block; }
.invite-msg { font-size: 0.8rem; color: var(--rs-text-muted); display: block; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.invite-actions { display: flex; gap: 6px; flex-shrink: 0; }
.btn-sm {
  padding: 4px 10px; border-radius: 6px; border: none;
  font-size: 0.75rem; font-weight: 600; cursor: pointer; transition: opacity 0.15s;
}
.btn-sm--approve { background: #059669; color: white; }
.btn-sm--approve:hover { opacity: 0.85; }
.btn-sm--deny { background: rgba(239,68,68,0.15); color: #f87171; }
.btn-sm--deny:hover { background: rgba(239,68,68,0.25); }
.invite-resolved { opacity: 0.4; }
.invite-status { font-size: 0.75rem; padding: 3px 8px; border-radius: 6px; font-weight: 600; margin-left: auto; }
.invite-status--approved { background: rgba(52,211,153,0.15); color: #34d399; }
.invite-status--denied { background: rgba(239,68,68,0.15); color: #f87171; }

.loading { padding: 16px; text-align: center; font-size: 0.85rem; color: var(--rs-text-secondary); }

/* Modules config panel */
.modules-list { max-height: 400px; overflow-y: auto; }
.module-encryption { margin-bottom: 0.25rem; }
.module-divider { height: 1px; background: var(--rs-btn-secondary-bg); margin: 0.75rem 0; }
.module-section-label { font-size: 0.72rem; font-weight: 700; color: var(--rs-text-secondary); text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 0.5rem; }
.module-row {
  display: flex; align-items: center; justify-content: space-between;
  padding: 6px 0; cursor: pointer;
}
.module-label { font-size: 0.875rem; }
.module-hint { font-size: 0.75rem; color: var(--rs-text-muted); margin-top: 2px; padding-left: 2px; }
.scope-row {
  display: flex; align-items: center; gap: 8px;
  padding: 2px 0 6px 24px; font-size: 0.8rem; color: var(--rs-text-secondary);
}
.scope-label { font-size: 0.75rem; }
.scope-select {
  padding: 3px 8px; border-radius: 6px; border: 1px solid var(--rs-border);
  background: var(--rs-bg-hover); color: var(--rs-text-primary); font-size: 0.75rem; outline: none;
}
.toggle-switch {
  position: relative; display: inline-block; width: 36px; height: 20px;
}
.toggle-switch input { opacity: 0; width: 0; height: 0; }
.toggle-slider {
  position: absolute; cursor: pointer; inset: 0;
  background: var(--rs-input-border); border-radius: 20px; transition: 0.2s;
}
.toggle-slider:before {
  content: ""; position: absolute; height: 14px; width: 14px;
  left: 3px; bottom: 3px; background: white; border-radius: 50%; transition: 0.2s;
}
input:checked + .toggle-slider { background: #06b6d4; }
input:checked + .toggle-slider:before { transform: translateX(16px); }

/* Section labels */
.section-label { font-size: 0.72rem; font-weight: 700; color: var(--rs-text-secondary); text-transform: uppercase; letter-spacing: 0.06em; padding: 8px 0 4px; }

/* Add member section */
.add-member-section { margin-top: 16px; padding-top: 12px; border-top: 1px solid var(--rs-border-subtle); }
.add-member-toggle { display: flex; gap: 4px; margin-bottom: 10px; }
.add-toggle-btn {
  flex: 1; padding: 6px 10px; background: var(--rs-bg-hover); border: 1px solid var(--rs-input-border, #404040);
  color: var(--rs-text-secondary); border-radius: 6px; font-size: 0.78rem; cursor: pointer; transition: all 0.15s;
}
.add-toggle-btn.active { background: rgba(6,182,212,0.1); border-color: rgba(6,182,212,0.3); color: #06b6d4; }
.add-member-form { display: flex; flex-direction: column; gap: 8px; }
.add-member-form.hidden { display: none; }
.add-member-row { display: flex; gap: 8px; align-items: center; margin-top: 10px; }
.add-search-wrapper { position: relative; }
.add-search-dropdown { position: absolute; top: 100%; left: 0; right: 0; background: var(--rs-bg-surface); border: 1px solid var(--rs-border); border-radius: 8px; margin-top: 4px; overflow: hidden; z-index: 10; box-shadow: 0 4px 16px rgba(0,0,0,0.25); display: none; }
.add-search-dropdown.open { display: block; }
.add-dd-item { display: flex; align-items: center; gap: 8px; padding: 8px 12px; cursor: pointer; transition: background 0.1s; }
.add-dd-item:hover { background: var(--rs-bg-hover); }
.add-dd-name { font-size: 0.82rem; font-weight: 500; color: var(--rs-text-primary); }
.add-dd-user { font-size: 0.72rem; color: var(--rs-text-muted); }
.add-dd-empty { padding: 8px 12px; font-size: 0.8rem; color: var(--rs-text-muted); }
.add-selected-chip { font-size: 0.78rem; color: #06b6d4; }
.add-selected-user { min-height: 0; }
.add-feedback { font-size: 0.78rem; min-height: 16px; }

@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
`;

const CREATE_SPACE_MODAL_STYLES = `
.rstack-create-space-overlay {
  position: fixed; inset: 0; background: rgba(0,0,0,0.6);
  -webkit-backdrop-filter: blur(4px); backdrop-filter: blur(4px);
  display: flex; align-items: center; justify-content: center;
  z-index: 10001; animation: cssFadeIn 0.2s;
}

.cs-modal {
  background: var(--rs-bg-surface, #0a0a0a); border: 1px solid var(--rs-border, #262626);
  border-radius: 16px; padding: 1.75rem 2rem; max-width: 640px; width: 94%;
  max-height: 90vh; overflow-y: auto;
  color: var(--rs-text-primary, #e5e5e5); box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5);
  animation: cssSlideUp 0.3s; position: relative;
}

.cs-title {
  font-size: 1.4rem; margin: 0 0 1.25rem;
  background: linear-gradient(135deg, #06b6d4, #7c3aed);
  -webkit-background-clip: text; -webkit-text-fill-color: transparent;
}

.cs-close {
  position: absolute; top: 12px; right: 16px;
  background: none; border: none; color: var(--rs-text-muted, #525252); font-size: 1.5rem;
  cursor: pointer; line-height: 1; padding: 4px 8px; border-radius: 6px;
}
.cs-close:hover { color: var(--rs-text-primary, #e5e5e5); background: var(--rs-border, #262626); }

/* Two-column layout */
.cs-columns { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 1.25rem; }
@media (max-width: 560px) { .cs-columns { grid-template-columns: 1fr; } }

.cs-label {
  display: block; font-size: 0.72rem; font-weight: 700; color: var(--rs-text-secondary, #a3a3a3);
  text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 5px; margin-top: 0.75rem;
}
.cs-label:first-child { margin-top: 0; }

.cs-input {
  width: 100%; padding: 9px 12px; border-radius: 8px;
  border: 1px solid var(--rs-input-border, #404040); background: var(--rs-bg-hover, #171717);
  color: var(--rs-text-primary, #e5e5e5); font-size: 0.875rem; outline: none;
  transition: border-color 0.2s; box-sizing: border-box; font-family: inherit;
}
.cs-input:focus { border-color: #06b6d4; }
.cs-input::placeholder { color: var(--rs-text-muted, #525252); }

.cs-textarea { resize: vertical; min-height: 60px; }

/* Slug row */
.cs-slug-row { display: flex; align-items: center; gap: 0; }
.cs-slug-input { border-radius: 8px 0 0 8px !important; }
.cs-slug-suffix {
  padding: 9px 12px 9px 0; background: var(--rs-bg-hover, #171717);
  border: 1px solid var(--rs-input-border, #404040); border-left: none;
  border-radius: 0 8px 8px 0; font-size: 0.8rem; color: var(--rs-text-muted, #525252);
  white-space: nowrap;
}

.cs-slug-status { font-size: 0.72rem; min-height: 1.1em; margin-top: 3px; }
.cs-slug-available { color: #34d399; }
.cs-slug-taken { color: #f87171; }

/* Visibility radio cards */
.cs-vis-cards { display: flex; flex-direction: column; gap: 6px; }
.cs-vis-card {
  display: flex; align-items: center; gap: 8px;
  padding: 8px 12px; border-radius: 8px; cursor: pointer;
  border: 1px solid var(--rs-border, #262626);
  transition: border-color 0.15s, background 0.15s;
}
.cs-vis-card:hover { background: var(--rs-bg-hover, #171717); }
.cs-vis-card.selected { border-color: #06b6d4; background: rgba(6,182,212,0.05); }
.cs-vis-card input[type="radio"] { display: none; }
.cs-vis-dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; }
.cs-vis-dot--private { background: #f87171; }
.cs-vis-dot--permissioned { background: #fbbf24; }
.cs-vis-dot--public { background: #34d399; }
.cs-vis-card-title { font-size: 0.85rem; font-weight: 600; }
.cs-vis-card-desc { font-size: 0.75rem; color: var(--rs-text-muted, #525252); margin-left: auto; }

/* Discoverable toggle */
.cs-discover-row {
  display: flex; align-items: center; gap: 8px; margin-top: 0.75rem;
  font-size: 0.82rem; color: var(--rs-text-secondary, #a3a3a3); cursor: pointer;
}
.cs-discover-row input[type="checkbox"] { margin: 0; accent-color: #06b6d4; }
.cs-hidden { display: none !important; }

/* Sections */
.cs-section { margin-bottom: 1rem; }

/* Member search */
.cs-member-search-row { display: flex; gap: 8px; align-items: center; }
.cs-search-wrapper { position: relative; flex: 1; }
.cs-member-input { width: 100%; }

.cs-search-dropdown {
  display: none; position: absolute; top: 100%; left: 0; right: 0;
  background: var(--rs-bg-surface, #0a0a0a); border: 1px solid var(--rs-border, #262626);
  border-radius: 8px; margin-top: 4px; max-height: 200px; overflow-y: auto;
  z-index: 100; box-shadow: 0 8px 24px rgba(0,0,0,0.4);
}
.cs-search-dropdown.open { display: block; }

.cs-dd-item {
  display: flex; align-items: center; gap: 8px;
  padding: 8px 12px; cursor: pointer; transition: background 0.1s;
  font-size: 0.85rem;
}
.cs-dd-item:hover { background: var(--rs-bg-hover, #171717); }
.cs-dd-name { font-weight: 500; }
.cs-dd-user { color: var(--rs-text-muted, #525252); font-size: 0.8rem; }
.cs-dd-badge {
  margin-left: auto; font-size: 0.7rem; padding: 2px 6px; border-radius: 4px;
  background: var(--rs-bg-hover, #171717); color: var(--rs-text-muted, #525252);
}
.cs-dd-self { opacity: 0.4; cursor: default; }
.cs-dd-self:hover { background: transparent; }
.cs-dd-added { opacity: 0.4; cursor: default; }
.cs-dd-added:hover { background: transparent; }
.cs-dd-email { color: #06b6d4; }
.cs-dd-empty { padding: 12px; text-align: center; font-size: 0.82rem; color: var(--rs-text-muted, #525252); }

.cs-role-select {
  padding: 8px 10px; border-radius: 8px;
  border: 1px solid var(--rs-input-border, #404040); background: var(--rs-bg-hover, #171717);
  color: var(--rs-text-primary, #e5e5e5); font-size: 0.82rem; outline: none;
}

.cs-add-btn {
  padding: 8px 16px; border-radius: 8px; border: none;
  background: #06b6d4; color: white; font-size: 0.82rem; font-weight: 600;
  cursor: pointer; transition: opacity 0.15s; white-space: nowrap;
}
.cs-add-btn:hover { opacity: 0.85; }
.cs-add-btn:disabled { opacity: 0.35; cursor: not-allowed; }

/* Member chips */
.cs-member-chips {
  display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; min-height: 28px;
}
.cs-chip {
  display: inline-flex; align-items: center; gap: 4px;
  padding: 4px 10px; border-radius: 20px; font-size: 0.78rem;
  background: var(--rs-bg-hover, #171717); border: 1px solid var(--rs-border, #262626);
  color: var(--rs-text-primary, #e5e5e5);
}
.cs-chip--owner {
  background: rgba(251,191,36,0.1); border-color: rgba(251,191,36,0.3); color: #fbbf24;
}
.cs-chip--email { color: #06b6d4; border-color: rgba(6,182,212,0.3); }
.cs-chip-role { font-size: 0.68rem; color: var(--rs-text-muted, #525252); }
.cs-chip-remove {
  background: none; border: none; color: var(--rs-text-muted, #525252);
  cursor: pointer; font-size: 1rem; line-height: 1; padding: 0 2px;
}
.cs-chip-remove:hover { color: #f87171; }

/* Invite link row */
.cs-invite-row { display: flex; gap: 8px; }
.cs-invite-input { flex: 1; font-size: 0.8rem; color: var(--rs-text-muted, #525252); }
.cs-copy-btn {
  padding: 8px 16px; border-radius: 8px; border: none;
  background: var(--rs-bg-hover, #171717); border: 1px solid var(--rs-border, #262626);
  color: var(--rs-text-primary, #e5e5e5); font-size: 0.82rem; font-weight: 600;
  cursor: pointer; transition: all 0.15s; white-space: nowrap;
}
.cs-copy-btn:hover { background: var(--rs-border, #262626); }
.cs-copy-btn:disabled { opacity: 0.35; cursor: not-allowed; }

.cs-invite-hint { font-size: 0.72rem; color: var(--rs-text-muted, #525252); margin-top: 4px; }

/* Footer */
.cs-footer {
  margin-top: 1.25rem; padding-top: 1rem; border-top: 1px solid var(--rs-border, #262626);
  display: flex; align-items: center; justify-content: space-between; gap: 12px;
}
.cs-footer-actions { display: flex; gap: 10px; }

.cs-status { font-size: 0.82rem; flex: 1; }
.cs-status--error { color: #f87171; }
.cs-status--success { color: #34d399; }

.cs-btn {
  padding: 10px 22px; border-radius: 8px; border: none;
  font-size: 0.9rem; font-weight: 600; cursor: pointer; transition: all 0.2s;
}
.cs-btn--primary {
  background: linear-gradient(135deg, #06b6d4, #7c3aed); color: white;
}
.cs-btn--primary:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(6,182,212,0.3); }
.cs-btn--primary:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
.cs-btn--secondary {
  background: var(--rs-btn-secondary-bg, #1a1a1a); color: var(--rs-text-secondary, #a3a3a3);
  border: 1px solid var(--rs-border, #262626);
}
.cs-btn--secondary:hover { background: var(--rs-bg-hover, #171717); color: var(--rs-text-primary, #e5e5e5); }

@keyframes cssFadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes cssSlideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
`;
