import { useCallback, useEffect, useState } from "react";

import IconChat from "virtual:icons/mdi/chat";
import IconChevronDown from "virtual:icons/mdi/chevron-down";

import Chat from "./Chat";
import { chatEventBus } from "../event-buses";

import "./ChatWindow.scss";

export default function ChatWindow() {
	const [isOpen, setIsOpen] = useState(false);

	const toggle = useCallback(() => {
		setIsOpen((current) => {
			const next = !current;
			if (next) {
				if (typeof queueMicrotask === "function") {
					queueMicrotask(() => chatEventBus.emit("scrollToBottom"));
				} else {
					setTimeout(() => chatEventBus.emit("scrollToBottom"), 0);
				}
			}
			return next;
		});
	}, []);

	useEffect(() => {
		const off = chatEventBus.on("close", () => {
			setIsOpen(false);
		});

		return () => {
			off();
		};
	}, []);

	return (
		<div className="chat-window-wrapper">
			{isOpen ? (
				<div className="chat-window chat-window--open" aria-hidden={false}>
					<Chat />
				</div>
			) : null}

			<button
				className="chat-window-toggle"
				type="button"
				onClick={toggle}
				aria-expanded={isOpen}
			>
				{isOpen ? (
					<IconChevronDown height="32" width="32" />
				) : (
					<IconChat height="32" width="32" />
				)}
			</button>
		</div>
	);
}
