/**
 * <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 } from "../url-helpers";

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

export class RStackSpaceSwitcher extends HTMLElement {
	#shadow: ShadowRoot;
	#spaces: SpaceInfo[] = [];
	#loaded = false;

	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();
	}

	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, rect.left)}px`;
				if (!this.#loaded) {
					await this.#loadSpaces();
					this.#renderMenu(menu, current);
				}
			}
		});

		document.addEventListener("click", () => menu.classList.remove("open"));
	}

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

	/** Format display name based on visibility type */
	#displayName(s: SpaceInfo): string {
		const v = s.visibility || "public_read";
		if (v === "members_only") {
			const username = getUsername();
			return username ? `${username}'s (you)rSpace` : "(you)rSpace";
		}
		return `${s.name} rSpace`;
	}

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

		if (this.#spaces.length === 0) {
			let cta = "";
			if (!auth) {
				cta = this.#yourSpaceCTAhtml("Sign in to create →");
			} else {
				const username = getUsername();
				const label = username ? `Create ${username}'s Space →` : "Create (you)rSpace →";
				cta = this.#yourSpaceCTAhtml(label);
			}
			menu.innerHTML = `
				${cta}
				<div class="divider"></div>
				<div class="menu-empty">
					${auth ? "No spaces yet" : "Sign in to see your spaces"}
				</div>
				<a class="item item--create" href="/new">+ Create new space</a>
			`;
			this.#attachYourSpaceCTA(menu);
			return;
		}

		const moduleId = this.#getCurrentModule();

		// 3-section split
		const mySpaces = this.#spaces.filter((s) => s.role);
		const publicSpaces = this.#spaces.filter((s) => s.accessible !== false && !s.role);
		const discoverSpaces = this.#spaces.filter((s) => s.accessible === false);

		const hasOwnedSpace = mySpaces.some((s) => s.relationship === "owner");

		let html = "";

		// ── Create (you)rSpace CTA — only if user has no owned spaces ──
		if (!auth) {
			html += this.#yourSpaceCTAhtml("Sign in to create →");
			html += `<div class="divider"></div>`;
		} else if (!hasOwnedSpace) {
			const username = getUsername();
			const label = username ? `Create ${username}'s Space →` : "Create (you)rSpace →";
			html += this.#yourSpaceCTAhtml(label);
			html += `<div class="divider"></div>`;
		}

		// ── Your spaces ──
		if (mySpaces.length > 0) {
			html += `<div class="section-label">Your spaces</div>`;
			html += mySpaces
				.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("");
		}

		// ── Public spaces ──
		if (publicSpaces.length > 0) {
			if (mySpaces.length > 0) html += `<div class="divider"></div>`;
			html += `<div class="section-label">Public spaces</div>`;
			html += publicSpaces
				.map((s) => {
					const vis = this.#visibilityInfo(s);
					return `
				<a class="item ${vis.cls} ${s.slug === current ? "active" : ""}"
				   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>`;
				})
				.join("");
		}

		// ── Discover (inaccessible spaces) ──
		if (auth && discoverSpaces.length > 0) {
			html += `<div class="divider"></div>`;
			html += `<div class="section-label">Discover</div>`;
			html += discoverSpaces
				.map((s) => {
					const vis = this.#visibilityInfo(s);
					const pending = s.pendingRequest;
					return `
				<div class="item item--discover ${vis.cls}">
					<span class="item-icon">${s.icon || "🌐"}</span>
					<span class="item-name">${this.#displayName(s)}</span>
					<span class="item-vis ${vis.cls}">${vis.label}</span>
					${pending
						? `<span class="item-badge item-badge--pending">Requested</span>`
						: `<button class="item-request-btn" data-slug="${s.slug}" data-name="${s.name.replace(/"/g, "&quot;")}">Request Access</button>`
					}
				</div>`;
				})
				.join("");
		}

		html += `<div class="divider"></div>`;
		html += `<a class="item item--create" href="/new">+ Create new space</a>`;

		menu.innerHTML = html;

		// Attach Request Access button listeners
		menu.querySelectorAll(".item-request-btn").forEach((btn) => {
			btn.addEventListener("click", (e) => {
				e.stopPropagation();
				const el = btn as HTMLElement;
				this.#showRequestAccessModal(el.dataset.slug!, el.dataset.name!);
			});
		});

		// 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 "(you)rSpace" CTA listener
		this.#attachYourSpaceCTA(menu);
	}

	#yourSpaceCTAhtml(buttonLabel: string): string {
		return `
			<div class="item item--yourspace vis-private">
				<span class="item-icon">🔒</span>
				<span class="item-name">(you)rSpace</span>
				<button class="yourspace-btn" id="yourspace-cta">${buttonLabel}</button>
			</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();
			}
		});
	}

	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
		}
	}

	#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);
	}

	#showEditSpaceModal(slug: string, spaceName: string) {
		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 active" data-tab="settings">Settings</button>
					<button class="tab" data-tab="members">Members</button>
					<button class="tab" data-tab="invitations">Invitations</button>
				</div>

				<div class="tab-panel" 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 (read + write)</option>
						<option value="public_read">Public (read only)</option>
						<option value="authenticated">Authenticated users</option>
						<option value="members_only">Members 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 hidden" id="panel-members">
					<div id="es-members-list" class="member-list"><div class="loading">Loading members...</div></div>
				</div>

				<div class="tab-panel 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 === "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));

		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 = "/demo/canvas";
		} 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 || [];

			if (members.length === 0) {
				container.innerHTML = `<div class="loading">No members</div>`;
				return;
			}

			container.innerHTML = members.map((m) => {
				const displayName = m.displayName || m.did.slice(0, 20) + "...";
				const roleOptions = ["viewer", "participant", "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("");

			// Role change handlers
			container.querySelectorAll(".role-select").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"); }
				});
			});
		} catch {
			container.innerHTML = `<div class="loading">Failed to load members</div>`;
		}
	}

	async #loadInvitations(overlay: HTMLElement, slug: string) {
		const container = overlay.querySelector("#es-invitations-list") as HTMLElement;
		try {
			const token = getAccessToken();
			const res = await fetch(`/api/spaces/${slug}/access-requests`, {
				headers: token ? { Authorization: `Bearer ${token}` } : {},
			});
			if (!res.ok) { container.innerHTML = `<div class="loading">Failed to load</div>`; return; }
			const data = await res.json();
			const requests: Array<{ id: string; requesterUsername: string; message?: string; status: string; createdAt: number }> = data.requests || [];

			if (requests.length === 0) {
				container.innerHTML = `<div class="loading">No access requests</div>`;
				return;
			}

			const pending = requests.filter((r) => r.status === "pending");
			const resolved = requests.filter((r) => r.status !== "pending");

			let html = "";
			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("");
			}
			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("");
			}

			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"); }
				});
			});
		} catch {
			container.innerHTML = `<div class="loading">Failed to load invitations</div>`;
		}
	}

	#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; color: inherit;
}
:host-context([data-theme="light"]) .trigger { background: rgba(0,0,0,0.05); color: #0f172a; }
:host-context([data-theme="light"]) .trigger:hover { background: rgba(0,0,0,0.08); }
:host-context([data-theme="dark"]) .trigger { background: rgba(255,255,255,0.08); color: #e2e8f0; }
:host-context([data-theme="dark"]) .trigger:hover { background: rgba(255,255,255,0.12); }
.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-height: 400px; overflow-y: auto;
  border-radius: 12px; box-shadow: 0 8px 30px rgba(0,0,0,0.25);
  display: none; z-index: 10001;
}
.menu.open { display: block; }
:host-context([data-theme="light"]) .menu { background: white; border: 1px solid rgba(0,0,0,0.1); }
:host-context([data-theme="dark"]) .menu { background: #1e293b; border: 1px solid rgba(255,255,255,0.1); }

.section-label {
  padding: 8px 14px 4px; font-size: 0.7rem; font-weight: 600;
  text-transform: uppercase; letter-spacing: 0.05em; opacity: 0.5;
}

.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;
}
:host-context([data-theme="light"]) .item { color: #374151; }
:host-context([data-theme="light"]) .item:hover { background: #f1f5f9; }
:host-context([data-theme="light"]) .item.active { background: #e0f2fe; }
:host-context([data-theme="dark"]) .item { color: #e2e8f0; }
:host-context([data-theme="dark"]) .item:hover { background: rgba(255,255,255,0.05); }
:host-context([data-theme="dark"]) .item.active { background: rgba(6,182,212,0.1); }

/* 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; }
:host-context([data-theme="light"]) .item-vis.vis-public { background: #d1fae5; color: #059669; }
:host-context([data-theme="light"]) .item-vis.vis-private { background: #fee2e2; color: #dc2626; }
:host-context([data-theme="light"]) .item-vis.vis-permissioned { background: #fef3c7; color: #d97706; }

/* 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;
}
:host-context([data-theme="light"]) .item-row:hover { background: #f1f5f9; }
:host-context([data-theme="light"]) .item-row.active { background: #e0f2fe; }
:host-context([data-theme="dark"]) .item-row:hover { background: rgba(255,255,255,0.05); }
:host-context([data-theme="dark"]) .item-row.active { background: rgba(6,182,212,0.1); }
.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; }
:host-context([data-theme="light"]) .item-gear { color: #374151; }
:host-context([data-theme="dark"]) .item-gear { color: #e2e8f0; }

.item--create {
  font-size: 0.85rem; font-weight: 600; color: #06b6d4 !important;
  border-left-color: transparent !important;
}
.item--create:hover { background: rgba(6,182,212,0.08) !important; }

/* (you)rSpace CTA */
.item--yourspace {
  border-left-color: #f87171; padding: 12px 14px;
}
.item--yourspace .item-name { font-weight: 700; font-size: 0.9rem; }
:host-context([data-theme="light"]) .item--yourspace { background: #fff5f5; }
:host-context([data-theme="dark"]) .item--yourspace { background: rgba(248,113,113,0.06); }
.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; }
:host-context([data-theme="light"]) .divider { background: rgba(0,0,0,0.08); }
:host-context([data-theme="dark"]) .divider { background: rgba(255,255,255,0.08); }

.menu-loading, .menu-empty {
  padding: 16px; text-align: center; font-size: 0.85rem; color: #94a3b8;
}

/* Discover section — non-navigable items */
.item--discover { cursor: default; flex-wrap: wrap; }
.item--discover:hover { background: transparent !important; }
:host-context([data-theme="light"]) .item--discover:hover { background: transparent !important; }
:host-context([data-theme="dark"]) .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;
}
:host-context([data-theme="light"]) .item-badge--pending { background: #fef3c7; color: #d97706; }
`;

const REQUEST_MODAL_STYLES = `
.rstack-auth-overlay {
  position: fixed; inset: 0; background: rgba(0,0,0,0.6);
  backdrop-filter: blur(4px); display: flex; align-items: center;
  justify-content: center; z-index: 10000; animation: fadeIn 0.2s;
}
.auth-modal {
  background: #1e293b; border: 1px solid rgba(255,255,255,0.1);
  border-radius: 16px; padding: 2rem; max-width: 420px; width: 90%;
  text-align: center; color: white; box-shadow: 0 20px 60px rgba(0,0,0,0.4);
  animation: slideUp 0.3s; position: relative;
}
.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: #94a3b8; font-size: 0.95rem; line-height: 1.6; margin-bottom: 1rem; }
.input {
  width: 100%; padding: 12px 16px; border-radius: 8px;
  border: 1px solid rgba(255,255,255,0.15); background: rgba(255,255,255,0.05);
  color: white; 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: #64748b; }
.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: rgba(255,255,255,0.08); color: #94a3b8; border: 1px solid rgba(255,255,255,0.1); }
.btn--secondary:hover { background: rgba(255,255,255,0.12); color: white; }
.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: #64748b; font-size: 1.5rem;
  cursor: pointer; line-height: 1; padding: 4px 8px; border-radius: 6px;
}
.close-btn:hover { color: white; background: rgba(255,255,255,0.1); }
.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);
  backdrop-filter: blur(4px); display: flex; align-items: center;
  justify-content: center; z-index: 10000; animation: fadeIn 0.2s;
}
.edit-modal {
  background: #1e293b; border: 1px solid rgba(255,255,255,0.1);
  border-radius: 16px; padding: 2rem; max-width: 520px; width: 92%;
  color: white; box-shadow: 0 20px 60px rgba(0,0,0,0.4);
  animation: slideUp 0.3s; position: relative;
}
.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: #64748b; font-size: 1.5rem;
  cursor: pointer; line-height: 1; padding: 4px 8px; border-radius: 6px;
}
.close-btn:hover { color: white; background: rgba(255,255,255,0.1); }

/* Tabs */
.tabs { display: flex; gap: 4px; margin-bottom: 1.2rem; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 0; }
.tab {
  padding: 8px 16px; border: none; background: none; color: #94a3b8;
  font-size: 0.85rem; font-weight: 600; cursor: pointer; border-bottom: 2px solid transparent;
  transition: all 0.15s; border-radius: 6px 6px 0 0;
}
.tab:hover { color: #e2e8f0; background: rgba(255,255,255,0.05); }
.tab.active { color: #06b6d4; border-bottom-color: #06b6d4; }

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

/* Form fields */
.field-label { display: block; font-size: 0.75rem; font-weight: 600; color: #94a3b8; margin-bottom: 4px; text-transform: uppercase; letter-spacing: 0.05em; }
.input {
  width: 100%; padding: 10px 14px; border-radius: 8px;
  border: 1px solid rgba(255,255,255,0.15); background: rgba(255,255,255,0.05);
  color: white; 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 rgba(255,255,255,0.06);
}
.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 rgba(255,255,255,0.15);
  background: rgba(255,255,255,0.05); color: white; font-size: 0.8rem; outline: none;
}
.member-remove {
  background: none; border: none; color: #64748b; 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 rgba(255,255,255,0.06);
}
.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: #64748b; 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: #94a3b8; }

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