import { _ as generateId } from "./dist-Dacf6lFH.js";
import { _ as removeParticipant, h as addParticipant, v as updateParticipantRole, w as setChannelVisibility } from "./module-n9Qp3xPp.js";
import { S as unpinMessage, _ as deleteMessage, b as removeReaction, h as addReaction, x as sendMessage, y as pinMessage } from "./module-CADVf4FS.js";
import "./upgrade-manifest-CcsS1jx5.js";
import "./upgrade-manifest-By3kkz55.js";
import { n as useChannelDocumentsInSelectedDrive, t as useChannelDocumentById } from "./channel-8SbeRfu5.js";
import { s as useRenownAuth } from "./dist-rER8Mj9l.js";
import "./chunk-VBDAOXYI-D8dyGyUX.js";
import { i as useSelectedChatDocument } from "./chat-DlL9ydQT.js";
import { n as Avatar, t as PowerChatStyles } from "./PowerChatStyles-luNPWkXq.js";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
//#region editors/power-chat-editor/components/ChannelHeader.tsx
function ChannelHeader({ name, topic, visibility, participantCount, showMembers, onToggleMembers, onOpenSettings }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "powerchat-header",
		children: [/* @__PURE__ */ jsxs("div", {
			className: "powerchat-header-left",
			children: [
				/* @__PURE__ */ jsx("span", {
					className: "powerchat-header-icon",
					children: visibility === "PRIVATE" ? /* @__PURE__ */ jsx("svg", {
						width: "20",
						height: "20",
						viewBox: "0 0 16 16",
						children: /* @__PURE__ */ jsx("path", {
							fill: "currentColor",
							d: "M13 6h-1V4.5C12 2.019 9.981 0 7.5 0S3 2.019 3 4.5V6H2a1 1 0 0 0-1 1v7a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1zM4.5 4.5C4.5 2.846 5.846 1.5 7.5 1.5S10.5 2.846 10.5 4.5V6h-6V4.5z"
						})
					}) : /* @__PURE__ */ jsx("span", {
						className: "powerchat-header-hash",
						children: "#"
					})
				}),
				/* @__PURE__ */ jsx("h3", {
					className: "powerchat-header-name",
					children: name || "unnamed"
				}),
				topic && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
					className: "powerchat-header-divider",
					children: "|"
				}), /* @__PURE__ */ jsx("span", {
					className: "powerchat-header-topic",
					children: topic
				})] })
			]
		}), /* @__PURE__ */ jsxs("div", {
			className: "powerchat-header-right",
			children: [/* @__PURE__ */ jsxs("button", {
				className: `powerchat-header-btn ${showMembers ? "active" : ""}`,
				onClick: onToggleMembers,
				title: "Toggle member list",
				children: [/* @__PURE__ */ jsx("svg", {
					width: "20",
					height: "20",
					viewBox: "0 0 24 24",
					children: /* @__PURE__ */ jsx("path", {
						fill: "currentColor",
						d: "M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"
					})
				}), /* @__PURE__ */ jsx("span", { children: participantCount })]
			}), /* @__PURE__ */ jsx("button", {
				className: "powerchat-header-btn",
				onClick: onOpenSettings,
				title: "Channel settings",
				children: /* @__PURE__ */ jsx("svg", {
					width: "20",
					height: "20",
					viewBox: "0 0 24 24",
					children: /* @__PURE__ */ jsx("path", {
						fill: "currentColor",
						d: "M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.49.49 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96a.49.49 0 0 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.07.62-.07.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6A3.6 3.6 0 1 1 12 8.4a3.6 3.6 0 0 1 0 7.2z"
					})
				})
			})]
		})]
	});
}
//#endregion
//#region editors/power-chat-editor/components/ReactionBadge.tsx
function ReactionBadge({ emoji, count, isActive, onClick }) {
	return /* @__PURE__ */ jsxs("button", {
		className: `powerchat-reaction ${isActive ? "active" : ""}`,
		onClick,
		children: [/* @__PURE__ */ jsx("span", { children: emoji }), /* @__PURE__ */ jsx("span", {
			className: "powerchat-reaction-count",
			children: count
		})]
	});
}
//#endregion
//#region editors/power-chat-editor/components/LinkPreview.tsx
const GIF_EXTENSIONS = [".gif", ".gifv"];
const IMAGE_EXTENSIONS = [
	".png",
	".jpg",
	".jpeg",
	".webp",
	".svg"
];
function isGifUrl(url) {
	try {
		const pathname = new URL(url).pathname.toLowerCase();
		return GIF_EXTENSIONS.some((ext) => pathname.endsWith(ext)) || url.includes("giphy.com") || url.includes("tenor.com/view");
	} catch {
		return false;
	}
}
function isImageUrl(url) {
	try {
		const pathname = new URL(url).pathname.toLowerCase();
		return IMAGE_EXTENSIONS.some((ext) => pathname.endsWith(ext));
	} catch {
		return false;
	}
}
function extractDomain(url) {
	try {
		return new URL(url).hostname;
	} catch {
		return url;
	}
}
function LinkPreview({ url }) {
	if (isGifUrl(url)) return /* @__PURE__ */ jsx("div", {
		className: "powerchat-media-preview",
		children: /* @__PURE__ */ jsx("img", {
			src: url,
			alt: "GIF",
			loading: "lazy"
		})
	});
	if (isImageUrl(url)) return /* @__PURE__ */ jsx("div", {
		className: "powerchat-media-preview",
		children: /* @__PURE__ */ jsx("img", {
			src: url,
			alt: "Image",
			loading: "lazy"
		})
	});
	const domain = extractDomain(url);
	return /* @__PURE__ */ jsxs("a", {
		href: url,
		target: "_blank",
		rel: "noopener noreferrer",
		className: "powerchat-link-preview",
		children: [/* @__PURE__ */ jsx("div", { className: "powerchat-link-accent" }), /* @__PURE__ */ jsxs("div", {
			className: "powerchat-link-body",
			children: [/* @__PURE__ */ jsx("span", {
				className: "powerchat-link-domain",
				children: domain
			}), /* @__PURE__ */ jsx("span", {
				className: "powerchat-link-url",
				children: url
			})]
		})]
	});
}
const URL_REGEX = /https?:\/\/[^\s<]+/g;
function extractUrls(text) {
	return text.match(URL_REGEX) || [];
}
function renderMessageContent(content) {
	const urls = extractUrls(content);
	if (urls.length === 0) return content;
	const parts = [];
	let lastIndex = 0;
	for (const url of urls) {
		const idx = content.indexOf(url, lastIndex);
		if (idx > lastIndex) parts.push(content.slice(lastIndex, idx));
		parts.push(/* @__PURE__ */ jsx("a", {
			href: url,
			target: "_blank",
			rel: "noopener noreferrer",
			className: "powerchat-inline-link",
			children: url
		}, idx));
		lastIndex = idx + url.length;
	}
	if (lastIndex < content.length) parts.push(content.slice(lastIndex));
	return /* @__PURE__ */ jsx(Fragment, { children: parts });
}
//#endregion
//#region editors/power-chat-editor/components/EmojiPicker.tsx
const EMOJI_CATEGORIES = {
	Smileys: [
		"😀",
		"😃",
		"😄",
		"😁",
		"😆",
		"😅",
		"😂",
		"🤣",
		"😊",
		"😇",
		"🙂",
		"🙃",
		"😉",
		"😌",
		"😍",
		"🥰",
		"😘",
		"😗",
		"😙",
		"😚",
		"😋",
		"😛",
		"😜",
		"🤪",
		"😝",
		"🤑",
		"🤗",
		"🤭",
		"🤫",
		"🤔",
		"🤐",
		"🤨",
		"😐",
		"😑",
		"😶",
		"😏",
		"😒",
		"🙄",
		"😬",
		"🤥",
		"😌",
		"😔",
		"😪",
		"🤤",
		"😴",
		"😷",
		"🤒",
		"🤕",
		"🤢",
		"🤮",
		"🤧",
		"🥵",
		"🥶",
		"🥴",
		"😵",
		"🤯"
	],
	Gestures: [
		"👍",
		"👎",
		"👊",
		"✊",
		"🤛",
		"🤜",
		"👏",
		"🙌",
		"👐",
		"🤲",
		"🤝",
		"🙏",
		"✍",
		"💅",
		"🤳",
		"💪",
		"👋",
		"🤚",
		"🖐",
		"✋",
		"🖖",
		"👌",
		"✌",
		"🤞",
		"🤟",
		"🤘",
		"👈",
		"👉",
		"👆",
		"👇",
		"☝",
		"🤜"
	],
	Hearts: [
		"❤",
		"🧡",
		"💛",
		"💚",
		"💙",
		"💜",
		"🖤",
		"🤍",
		"🤎",
		"💘",
		"💝",
		"💖",
		"💗",
		"💓",
		"💞",
		"💕",
		"💌",
		"💟",
		"❣",
		"💔"
	],
	Objects: [
		"🔥",
		"⭐",
		"🌟",
		"💥",
		"🎉",
		"🎊",
		"💯",
		"💢",
		"💬",
		"💭",
		"💤",
		"👋",
		"📣",
		"🔔",
		"🎵",
		"🎶",
		"💡",
		"💰",
		"📎",
		"📋",
		"📅",
		"💻",
		"📱",
		"🔍",
		"🔒",
		"🔑",
		"🚩",
		"🏆",
		"🎯",
		"🚀",
		"✈",
		"🌍"
	]
};
function EmojiPicker({ onSelect, onClose }) {
	const [activeCategory, setActiveCategory] = useState("Smileys");
	return /* @__PURE__ */ jsxs("div", {
		className: "powerchat-emoji-picker",
		onClick: (e) => e.stopPropagation(),
		children: [/* @__PURE__ */ jsx("div", {
			className: "powerchat-emoji-tabs",
			children: Object.keys(EMOJI_CATEGORIES).map((cat) => /* @__PURE__ */ jsx("button", {
				className: `powerchat-emoji-tab ${activeCategory === cat ? "active" : ""}`,
				onClick: () => setActiveCategory(cat),
				children: cat
			}, cat))
		}), /* @__PURE__ */ jsx("div", {
			className: "powerchat-emoji-grid",
			children: EMOJI_CATEGORIES[activeCategory].map((emoji, i) => /* @__PURE__ */ jsx("button", {
				className: "powerchat-emoji-btn",
				onClick: () => {
					onSelect(emoji);
					onClose();
				},
				children: emoji
			}, i))
		})]
	});
}
//#endregion
//#region editors/power-chat-editor/components/MessageItem.tsx
function formatTime(timestamp) {
	try {
		return new Date(timestamp).toLocaleTimeString([], {
			hour: "2-digit",
			minute: "2-digit"
		});
	} catch {
		return "";
	}
}
function formatFullDate(timestamp) {
	try {
		return new Date(timestamp).toLocaleDateString([], {
			weekday: "long",
			year: "numeric",
			month: "long",
			day: "numeric"
		});
	} catch {
		return "";
	}
}
function MessageItem({ message, author, currentUserId, isFirstInGroup, replyToMessage, replyToAuthor, onReply, onAddReaction, onRemoveReaction, onPin, onDelete, isPinned }) {
	const [showActions, setShowActions] = useState(false);
	const [showEmojiPicker, setShowEmojiPicker] = useState(false);
	const authorName = author?.name || "Unknown";
	const urls = extractUrls(message.content);
	return /* @__PURE__ */ jsxs("div", {
		className: `powerchat-message ${isFirstInGroup ? "first-in-group" : ""}`,
		onMouseEnter: () => setShowActions(true),
		onMouseLeave: () => {
			setShowActions(false);
			setShowEmojiPicker(false);
		},
		children: [message.replyToId && replyToMessage && /* @__PURE__ */ jsxs("div", {
			className: "powerchat-reply-context",
			children: [
				/* @__PURE__ */ jsx("div", { className: "powerchat-reply-line" }),
				/* @__PURE__ */ jsx(Avatar, {
					name: replyToAuthor?.name || "Unknown",
					size: 16
				}),
				/* @__PURE__ */ jsx("span", {
					className: "powerchat-reply-author",
					children: replyToAuthor?.name || "Unknown"
				}),
				/* @__PURE__ */ jsxs("span", {
					className: "powerchat-reply-text",
					children: [replyToMessage.content.slice(0, 100), replyToMessage.content.length > 100 ? "..." : ""]
				})
			]
		}), /* @__PURE__ */ jsxs("div", {
			className: "powerchat-message-row",
			children: [
				isFirstInGroup ? /* @__PURE__ */ jsx(Avatar, {
					name: authorName,
					size: 40
				}) : /* @__PURE__ */ jsx("span", {
					className: "powerchat-message-time-gutter",
					title: formatFullDate(message.timestamp),
					children: formatTime(message.timestamp)
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "powerchat-message-content",
					children: [
						isFirstInGroup && /* @__PURE__ */ jsxs("div", {
							className: "powerchat-message-header",
							children: [
								/* @__PURE__ */ jsx("span", {
									className: "powerchat-author-name",
									children: authorName
								}),
								/* @__PURE__ */ jsx("span", {
									className: "powerchat-timestamp",
									title: formatFullDate(message.timestamp),
									children: formatTime(message.timestamp)
								}),
								isPinned && /* @__PURE__ */ jsx("span", {
									className: "powerchat-pin-badge",
									title: "Pinned message",
									children: "📌"
								})
							]
						}),
						/* @__PURE__ */ jsxs("div", {
							className: "powerchat-message-text",
							children: [renderMessageContent(message.content), message.edited && /* @__PURE__ */ jsx("span", {
								className: "powerchat-edited",
								children: "(edited)"
							})]
						}),
						urls.map((url, i) => /* @__PURE__ */ jsx(LinkPreview, { url }, i)),
						message.reactions.length > 0 && /* @__PURE__ */ jsx("div", {
							className: "powerchat-reactions",
							children: message.reactions.map((reaction) => /* @__PURE__ */ jsx(ReactionBadge, {
								emoji: reaction.emoji,
								count: reaction.participantIds.length,
								isActive: reaction.participantIds.includes(currentUserId),
								onClick: () => {
									if (reaction.participantIds.includes(currentUserId)) onRemoveReaction(message.id, reaction.emoji);
									else onAddReaction(message.id, reaction.emoji);
								}
							}, reaction.id))
						})
					]
				}),
				showActions && /* @__PURE__ */ jsxs("div", {
					className: "powerchat-message-actions",
					children: [
						/* @__PURE__ */ jsx("button", {
							title: "Add Reaction",
							onClick: () => setShowEmojiPicker(!showEmojiPicker),
							children: "😀"
						}),
						/* @__PURE__ */ jsx("button", {
							title: "Reply",
							onClick: () => onReply(message.id),
							children: "↩"
						}),
						/* @__PURE__ */ jsx("button", {
							title: isPinned ? "Unpin" : "Pin",
							onClick: () => onPin(message.id),
							children: "📌"
						}),
						/* @__PURE__ */ jsx("button", {
							title: "Delete",
							onClick: () => onDelete(message.id),
							children: "🗑"
						}),
						showEmojiPicker && /* @__PURE__ */ jsx("div", {
							className: "powerchat-emoji-picker-popup",
							children: /* @__PURE__ */ jsx(EmojiPicker, {
								onSelect: (emoji) => onAddReaction(message.id, emoji),
								onClose: () => setShowEmojiPicker(false)
							})
						})
					]
				})
			]
		})]
	});
}
function DateSeparator({ date }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "powerchat-date-separator",
		children: [
			/* @__PURE__ */ jsx("div", { className: "powerchat-date-line" }),
			/* @__PURE__ */ jsx("span", {
				className: "powerchat-date-text",
				children: date
			}),
			/* @__PURE__ */ jsx("div", { className: "powerchat-date-line" })
		]
	});
}
//#endregion
//#region editors/power-chat-editor/components/MessageList.tsx
function getParticipant(participants, id) {
	return participants.find((p) => p.id === id);
}
function isSameDay(a, b) {
	try {
		const da = new Date(a);
		const db = new Date(b);
		return da.getFullYear() === db.getFullYear() && da.getMonth() === db.getMonth() && da.getDate() === db.getDate();
	} catch {
		return false;
	}
}
function formatDateHeader(timestamp) {
	try {
		const date = new Date(timestamp);
		const today = /* @__PURE__ */ new Date();
		const yesterday = new Date(today);
		yesterday.setDate(yesterday.getDate() - 1);
		if (isSameDay(timestamp, today.toISOString())) return "Today";
		if (isSameDay(timestamp, yesterday.toISOString())) return "Yesterday";
		return date.toLocaleDateString([], {
			weekday: "long",
			month: "long",
			day: "numeric",
			year: "numeric"
		});
	} catch {
		return "";
	}
}
const MESSAGE_GROUP_THRESHOLD_MS = 300 * 1e3;
function isFirstInGroup(messages, index) {
	if (index === 0) return true;
	const prev = messages[index - 1];
	const curr = messages[index];
	if (prev.authorId !== curr.authorId) return true;
	try {
		return new Date(curr.timestamp).getTime() - new Date(prev.timestamp).getTime() > MESSAGE_GROUP_THRESHOLD_MS;
	} catch {
		return true;
	}
}
function MessageList({ messages, participants, currentUserId, pinnedMessageIds, onReply, onAddReaction, onRemoveReaction, onPin, onDelete }) {
	const bottomRef = useRef(null);
	const containerRef = useRef(null);
	useEffect(() => {
		bottomRef.current?.scrollIntoView({ behavior: "smooth" });
	}, [messages.length]);
	if (messages.length === 0) return /* @__PURE__ */ jsx("div", {
		className: "powerchat-message-list",
		ref: containerRef,
		children: /* @__PURE__ */ jsxs("div", {
			className: "powerchat-welcome",
			children: [
				/* @__PURE__ */ jsx("div", {
					className: "powerchat-welcome-icon",
					children: "#"
				}),
				/* @__PURE__ */ jsx("h3", { children: "Welcome to the channel!" }),
				/* @__PURE__ */ jsx("p", { children: "This is the start of the conversation." })
			]
		})
	});
	const messageMap = new Map(messages.map((m) => [m.id, m]));
	return /* @__PURE__ */ jsxs("div", {
		className: "powerchat-message-list",
		ref: containerRef,
		children: [messages.map((msg, i) => {
			const showDateSep = i === 0 || !isSameDay(messages[i - 1].timestamp, msg.timestamp);
			const replyTo = msg.replyToId ? messageMap.get(msg.replyToId) : void 0;
			return /* @__PURE__ */ jsxs(React.Fragment, { children: [showDateSep && /* @__PURE__ */ jsx(DateSeparator, { date: formatDateHeader(msg.timestamp) }), /* @__PURE__ */ jsx(MessageItem, {
				message: msg,
				author: getParticipant(participants, msg.authorId),
				currentUserId,
				isFirstInGroup: isFirstInGroup(messages, i),
				replyToMessage: replyTo,
				replyToAuthor: replyTo ? getParticipant(participants, replyTo.authorId) : void 0,
				onReply,
				onAddReaction,
				onRemoveReaction,
				onPin,
				onDelete,
				isPinned: pinnedMessageIds.includes(msg.id)
			})] }, msg.id);
		}), /* @__PURE__ */ jsx("div", { ref: bottomRef })]
	});
}
//#endregion
//#region editors/power-chat-editor/components/MessageInput.tsx
function MessageInput({ channelName, replyTo, onSendMessage, onCancelReply, disabled }) {
	const [text, setText] = useState("");
	const [showEmoji, setShowEmoji] = useState(false);
	const inputRef = useRef(null);
	const handleSend = () => {
		const trimmed = text.trim();
		if (!trimmed) return;
		onSendMessage(trimmed);
		setText("");
		inputRef.current?.focus();
	};
	const handleKeyDown = (e) => {
		if (e.key === "Enter" && !e.shiftKey) {
			e.preventDefault();
			handleSend();
		}
		if (e.key === "Escape" && replyTo) onCancelReply();
	};
	const insertEmoji = (emoji) => {
		setText((prev) => prev + emoji);
		inputRef.current?.focus();
	};
	return /* @__PURE__ */ jsxs("div", {
		className: "powerchat-input-area",
		children: [replyTo && /* @__PURE__ */ jsxs("div", {
			className: "powerchat-reply-bar",
			children: [/* @__PURE__ */ jsxs("span", { children: ["Replying to ", /* @__PURE__ */ jsx("strong", { children: replyTo.author?.name || "Unknown" })] }), /* @__PURE__ */ jsx("button", {
				className: "powerchat-reply-cancel",
				onClick: onCancelReply,
				children: "✕"
			})]
		}), /* @__PURE__ */ jsxs("div", {
			className: "powerchat-input-row",
			children: [/* @__PURE__ */ jsxs("div", {
				className: "powerchat-input-wrapper",
				children: [
					/* @__PURE__ */ jsx("button", {
						className: "powerchat-input-btn",
						onClick: () => setShowEmoji(!showEmoji),
						title: "Emoji",
						children: "😀"
					}),
					/* @__PURE__ */ jsx("textarea", {
						ref: inputRef,
						className: "powerchat-textarea",
						placeholder: disabled ? "Log in to send messages" : `Message #${channelName || "channel"}`,
						value: text,
						onChange: (e) => setText(e.target.value),
						onKeyDown: handleKeyDown,
						rows: 1,
						disabled
					}),
					/* @__PURE__ */ jsx("button", {
						className: "powerchat-send-btn",
						onClick: handleSend,
						disabled: disabled || !text.trim(),
						title: "Send",
						children: /* @__PURE__ */ jsx("svg", {
							width: "20",
							height: "20",
							viewBox: "0 0 20 20",
							fill: "none",
							children: /* @__PURE__ */ jsx("path", {
								d: "M3 10L17 3L10 17L9 11L3 10Z",
								fill: "currentColor"
							})
						})
					})
				]
			}), showEmoji && /* @__PURE__ */ jsx("div", {
				className: "powerchat-input-emoji-popup",
				children: /* @__PURE__ */ jsx(EmojiPicker, {
					onSelect: insertEmoji,
					onClose: () => setShowEmoji(false)
				})
			})]
		})]
	});
}
//#endregion
//#region editors/power-chat-editor/components/MemberList.tsx
function groupByRole(participants) {
	const groups = {};
	for (const p of participants) {
		const role = p.role;
		if (!(role in groups)) groups[role] = [];
		groups[role].push(p);
	}
	return groups;
}
const ROLE_ORDER = [
	"OWNER",
	"ADMIN",
	"MEMBER",
	"GUEST"
];
const ROLE_LABELS = {
	OWNER: "Owner",
	ADMIN: "Admin",
	MEMBER: "Members",
	GUEST: "Guests"
};
function MemberList({ participants }) {
	const groups = groupByRole(participants);
	return /* @__PURE__ */ jsxs("div", {
		className: "powerchat-members",
		children: [ROLE_ORDER.filter((role) => groups[role] && groups[role].length > 0).map((role) => /* @__PURE__ */ jsxs("div", {
			className: "powerchat-member-group",
			children: [/* @__PURE__ */ jsxs("div", {
				className: "powerchat-member-role",
				children: [
					ROLE_LABELS[role] || role,
					" — ",
					groups[role].length
				]
			}), groups[role].map((p) => /* @__PURE__ */ jsxs("div", {
				className: "powerchat-member-item",
				children: [/* @__PURE__ */ jsx(Avatar, {
					name: p.name,
					size: 32
				}), /* @__PURE__ */ jsxs("div", {
					className: "powerchat-member-info",
					children: [/* @__PURE__ */ jsx("span", {
						className: "powerchat-member-name",
						children: p.name
					}), /* @__PURE__ */ jsx("span", {
						className: "powerchat-member-role-badge",
						children: p.role
					})]
				})]
			}, p.id))]
		}, role)), participants.length === 0 && /* @__PURE__ */ jsx("div", {
			className: "powerchat-empty-members",
			children: "No members yet"
		})]
	});
}
//#endregion
//#region editors/power-chat-editor/components/ChannelSettings.tsx
const ROLES = [
	{
		value: "OWNER",
		label: "Owner",
		description: "Full control"
	},
	{
		value: "ADMIN",
		label: "Admin",
		description: "Manage channel and members"
	},
	{
		value: "MEMBER",
		label: "Write",
		description: "Read and send messages"
	},
	{
		value: "GUEST",
		label: "Read",
		description: "View messages only"
	}
];
function AddMemberInput({ participants, knownUsers, onAddMember }) {
	const [query, setQuery] = useState("");
	const [showDropdown, setShowDropdown] = useState(false);
	const [selectedRole, setSelectedRole] = useState("MEMBER");
	const inputRef = useRef(null);
	const participantIds = useMemo(() => new Set(participants.map((p) => p.id)), [participants]);
	const suggestions = useMemo(() => {
		if (!query.trim()) return [];
		const q = query.toLowerCase();
		return knownUsers.filter((u) => !participantIds.has(u.id) && (u.name.toLowerCase().includes(q) || u.id.toLowerCase().includes(q)));
	}, [
		query,
		knownUsers,
		participantIds
	]);
	const handleSelect = (user) => {
		onAddMember(user, selectedRole);
		setQuery("");
		setShowDropdown(false);
		inputRef.current?.focus();
	};
	return /* @__PURE__ */ jsx("div", {
		className: "powerchat-add-member",
		children: /* @__PURE__ */ jsxs("div", {
			className: "powerchat-add-member-row",
			children: [/* @__PURE__ */ jsxs("div", {
				className: "powerchat-add-member-input-wrap",
				children: [
					/* @__PURE__ */ jsx("input", {
						ref: inputRef,
						className: "powerchat-add-member-input",
						type: "text",
						placeholder: "Search users to add...",
						value: query,
						onChange: (e) => {
							setQuery(e.target.value);
							setShowDropdown(true);
						},
						onFocus: () => setShowDropdown(true),
						onBlur: () => {
							setTimeout(() => setShowDropdown(false), 200);
						}
					}),
					showDropdown && suggestions.length > 0 && /* @__PURE__ */ jsx("div", {
						className: "powerchat-add-member-dropdown",
						children: suggestions.map((user) => /* @__PURE__ */ jsxs("button", {
							className: "powerchat-add-member-option",
							onMouseDown: (e) => e.preventDefault(),
							onClick: () => handleSelect(user),
							children: [/* @__PURE__ */ jsx(Avatar, {
								name: user.name,
								size: 24
							}), /* @__PURE__ */ jsxs("div", {
								className: "powerchat-add-member-option-info",
								children: [/* @__PURE__ */ jsx("span", {
									className: "powerchat-add-member-option-name",
									children: user.name
								}), /* @__PURE__ */ jsx("span", {
									className: "powerchat-add-member-option-id",
									children: user.id.length > 30 ? `${user.id.slice(0, 12)}...${user.id.slice(-8)}` : user.id
								})]
							})]
						}, user.id))
					}),
					showDropdown && query.trim() && suggestions.length === 0 && /* @__PURE__ */ jsx("div", {
						className: "powerchat-add-member-dropdown",
						children: /* @__PURE__ */ jsx("div", {
							className: "powerchat-add-member-empty",
							children: "No matching users found"
						})
					})
				]
			}), /* @__PURE__ */ jsx("select", {
				className: "powerchat-settings-role-select",
				value: selectedRole,
				onChange: (e) => setSelectedRole(e.target.value),
				children: ROLES.map((r) => /* @__PURE__ */ jsx("option", {
					value: r.value,
					children: r.label
				}, r.value))
			})]
		})
	});
}
function ChannelSettings({ visibility, participants, knownUsers, onChangeVisibility, onChangeRole, onRemoveParticipant, onAddMember, onClose }) {
	return /* @__PURE__ */ jsx("div", {
		className: "powerchat-settings-overlay",
		onClick: onClose,
		children: /* @__PURE__ */ jsxs("div", {
			className: "powerchat-settings-panel",
			onClick: (e) => e.stopPropagation(),
			children: [
				/* @__PURE__ */ jsxs("div", {
					className: "powerchat-settings-header",
					children: [/* @__PURE__ */ jsx("h3", { children: "Channel Settings" }), /* @__PURE__ */ jsx("button", {
						className: "powerchat-settings-close",
						onClick: onClose,
						children: "✕"
					})]
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "powerchat-settings-section",
					children: [
						/* @__PURE__ */ jsx("h4", { children: "Visibility" }),
						/* @__PURE__ */ jsxs("div", {
							className: "powerchat-settings-toggle-group",
							children: [/* @__PURE__ */ jsxs("button", {
								className: `powerchat-settings-toggle ${visibility === "PUBLIC" ? "active" : ""}`,
								onClick: () => onChangeVisibility("PUBLIC"),
								children: [/* @__PURE__ */ jsx("svg", {
									width: "16",
									height: "16",
									viewBox: "0 0 16 16",
									children: /* @__PURE__ */ jsx("path", {
										fill: "currentColor",
										d: "M5.88 5.88a3 3 0 1 0 4.24 4.24 3 3 0 0 0-4.24-4.24zM8 1a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-1 0v-2A.5.5 0 0 1 8 1zm0 11a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-1 0v-2A.5.5 0 0 1 8 12zm7-4a.5.5 0 0 1-.5.5h-2a.5.5 0 0 1 0-1h2a.5.5 0 0 1 .5.5zM4 8a.5.5 0 0 1-.5.5h-2a.5.5 0 0 1 0-1h2A.5.5 0 0 1 4 8z"
									})
								}), /* @__PURE__ */ jsx("span", { children: "Public" })]
							}), /* @__PURE__ */ jsxs("button", {
								className: `powerchat-settings-toggle ${visibility === "PRIVATE" ? "active" : ""}`,
								onClick: () => onChangeVisibility("PRIVATE"),
								children: [/* @__PURE__ */ jsx("svg", {
									width: "16",
									height: "16",
									viewBox: "0 0 16 16",
									children: /* @__PURE__ */ jsx("path", {
										fill: "currentColor",
										d: "M13 6h-1V4.5C12 2.019 9.981 0 7.5 0S3 2.019 3 4.5V6H2a1 1 0 0 0-1 1v7a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1zM4.5 4.5C4.5 2.846 5.846 1.5 7.5 1.5S10.5 2.846 10.5 4.5V6h-6V4.5z"
									})
								}), /* @__PURE__ */ jsx("span", { children: "Private" })]
							})]
						}),
						/* @__PURE__ */ jsx("p", {
							className: "powerchat-settings-hint",
							children: visibility === "PUBLIC" ? "Anyone can see and join this channel." : "Only invited members can see this channel."
						})
					]
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "powerchat-settings-section",
					children: [/* @__PURE__ */ jsx("h4", { children: "Add Member" }), /* @__PURE__ */ jsx(AddMemberInput, {
						participants,
						knownUsers,
						onAddMember
					})]
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "powerchat-settings-section",
					children: [/* @__PURE__ */ jsxs("h4", { children: [
						"Members (",
						participants.length,
						")"
					] }), /* @__PURE__ */ jsxs("div", {
						className: "powerchat-settings-members",
						children: [participants.map((p) => /* @__PURE__ */ jsxs("div", {
							className: "powerchat-settings-member",
							children: [
								/* @__PURE__ */ jsx(Avatar, {
									name: p.name,
									size: 32
								}),
								/* @__PURE__ */ jsx("div", {
									className: "powerchat-settings-member-info",
									children: /* @__PURE__ */ jsx("span", {
										className: "powerchat-settings-member-name",
										children: p.name
									})
								}),
								/* @__PURE__ */ jsx("select", {
									className: "powerchat-settings-role-select",
									value: p.role,
									onChange: (e) => onChangeRole(p.id, e.target.value),
									children: ROLES.map((r) => /* @__PURE__ */ jsx("option", {
										value: r.value,
										children: r.label
									}, r.value))
								}),
								/* @__PURE__ */ jsx("button", {
									className: "powerchat-settings-remove",
									onClick: () => onRemoveParticipant(p.id),
									title: "Remove member",
									children: "✕"
								})
							]
						}, p.id)), participants.length === 0 && /* @__PURE__ */ jsx("p", {
							className: "powerchat-settings-hint",
							children: "No members yet. Add members above or they join automatically when sending a message."
						})]
					})]
				})
			]
		})
	});
}
//#endregion
//#region editors/power-chat-editor/editor.tsx
function useCurrentUser() {
	const auth = useRenownAuth();
	const did = auth.user?.did;
	const displayName = auth.displayName || auth.user?.profile?.username || auth.ensName || auth.displayAddress || "Anonymous";
	const avatarUrl = auth.avatarUrl || auth.user?.profile?.userImage || null;
	return {
		id: did || "anonymous",
		name: displayName,
		avatarUrl,
		isLoggedIn: auth.status === "authorized" && !!did
	};
}
function Editor() {
	const [chatDoc, chatDispatch] = useSelectedChatDocument();
	const currentUser = useCurrentUser();
	const channelId = chatDoc.state.global.channelId;
	const [channelDoc, channelDispatch] = useChannelDocumentById(channelId);
	const allChannels = useChannelDocumentsInSelectedDrive();
	const knownUsers = useMemo(() => {
		const userMap = /* @__PURE__ */ new Map();
		for (const ch of allChannels || []) for (const p of ch.state.global.participants) if (!userMap.has(p.id)) userMap.set(p.id, {
			id: p.id,
			name: p.name,
			avatar: p.avatar
		});
		return Array.from(userMap.values());
	}, [allChannels]);
	const [showMembers, setShowMembers] = useState(true);
	const [showSettings, setShowSettings] = useState(false);
	const [replyToId, setReplyToId] = useState(null);
	const chatState = chatDoc.state.global;
	const channelState = channelDoc?.state.global;
	const channelName = channelState?.name || channelDoc?.header.name || chatDoc.header.name || "unnamed";
	const participants = channelState?.participants || [];
	const visibility = channelState?.visibility || "PUBLIC";
	const replyToMessage = replyToId ? chatState.messages.find((m) => m.id === replyToId) : void 0;
	const replyToAuthor = replyToMessage ? participants.find((p) => p.id === replyToMessage.authorId) : void 0;
	const ensureParticipant = useCallback(() => {
		if (!currentUser.isLoggedIn || !channelDispatch) return;
		if (!participants.some((p) => p.id === currentUser.id)) channelDispatch(addParticipant({
			id: currentUser.id,
			name: currentUser.name,
			avatar: currentUser.avatarUrl,
			role: "MEMBER",
			joinedAt: (/* @__PURE__ */ new Date()).toISOString()
		}));
	}, [
		channelDispatch,
		participants,
		currentUser
	]);
	const handleSendMessage = useCallback((content) => {
		if (!currentUser.isLoggedIn) return;
		ensureParticipant();
		chatDispatch(sendMessage({
			id: generateId(),
			authorId: currentUser.id,
			content,
			timestamp: (/* @__PURE__ */ new Date()).toISOString(),
			replyToId: replyToId || void 0
		}, []));
		setReplyToId(null);
	}, [
		chatDispatch,
		replyToId,
		currentUser,
		ensureParticipant
	]);
	const handleAddReaction = useCallback((messageId, emoji) => {
		if (!currentUser.isLoggedIn) return;
		ensureParticipant();
		chatDispatch(addReaction({
			id: generateId(),
			messageId,
			emoji,
			participantId: currentUser.id
		}));
	}, [
		chatDispatch,
		currentUser,
		ensureParticipant
	]);
	const handleRemoveReaction = useCallback((messageId, emoji) => {
		if (!currentUser.isLoggedIn) return;
		chatDispatch(removeReaction({
			messageId,
			emoji,
			participantId: currentUser.id
		}));
	}, [chatDispatch, currentUser]);
	const handlePin = useCallback((messageId) => {
		if (chatState.pinnedMessageIds.includes(messageId)) chatDispatch(unpinMessage({ messageId }));
		else chatDispatch(pinMessage({ messageId }));
	}, [chatDispatch, chatState.pinnedMessageIds]);
	const handleDelete = useCallback((messageId) => {
		chatDispatch(deleteMessage({ messageId }));
	}, [chatDispatch]);
	const handleChangeVisibility = useCallback((vis) => {
		channelDispatch?.(setChannelVisibility({ visibility: vis }));
	}, [channelDispatch]);
	const handleChangeRole = useCallback((participantId, role) => {
		channelDispatch?.(updateParticipantRole({
			participantId,
			role
		}));
	}, [channelDispatch]);
	const handleRemoveParticipant = useCallback((participantId) => {
		channelDispatch?.(removeParticipant({ participantId }));
	}, [channelDispatch]);
	const handleAddMember = useCallback((user, role) => {
		channelDispatch?.(addParticipant({
			id: user.id,
			name: user.name,
			avatar: user.avatar || null,
			role,
			joinedAt: (/* @__PURE__ */ new Date()).toISOString()
		}));
	}, [channelDispatch]);
	return /* @__PURE__ */ jsxs("div", {
		className: "powerchat-channel-editor",
		children: [
			/* @__PURE__ */ jsx(PowerChatStyles, {}),
			/* @__PURE__ */ jsx(ChannelHeader, {
				name: channelName,
				topic: channelState?.topic,
				visibility,
				participantCount: participants.length,
				showMembers,
				onToggleMembers: () => setShowMembers(!showMembers),
				onOpenSettings: () => setShowSettings(true)
			}),
			/* @__PURE__ */ jsxs("div", {
				className: "powerchat-content",
				children: [/* @__PURE__ */ jsxs("div", {
					className: "powerchat-chat-area",
					children: [/* @__PURE__ */ jsx(MessageList, {
						messages: chatState.messages,
						participants,
						currentUserId: currentUser.id,
						pinnedMessageIds: chatState.pinnedMessageIds,
						onReply: setReplyToId,
						onAddReaction: handleAddReaction,
						onRemoveReaction: handleRemoveReaction,
						onPin: handlePin,
						onDelete: handleDelete
					}), /* @__PURE__ */ jsx(MessageInput, {
						channelName,
						replyTo: replyToMessage ? {
							message: replyToMessage,
							author: replyToAuthor
						} : null,
						onSendMessage: handleSendMessage,
						onCancelReply: () => setReplyToId(null),
						disabled: !currentUser.isLoggedIn
					})]
				}), showMembers && /* @__PURE__ */ jsx(MemberList, { participants })]
			}),
			showSettings && channelDoc && /* @__PURE__ */ jsx(ChannelSettings, {
				visibility,
				participants,
				knownUsers,
				onChangeVisibility: handleChangeVisibility,
				onChangeRole: handleChangeRole,
				onRemoveParticipant: handleRemoveParticipant,
				onAddMember: handleAddMember,
				onClose: () => setShowSettings(false)
			})
		]
	});
}
//#endregion
export { Editor as default };

//# sourceMappingURL=editor-BYUmTaRY.js.map