import type { PropsWithChildren, ReactNode } from "react";
import { useEffect, useRef } from "react";

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

import "./Layout.scss";

interface LayoutProps extends PropsWithChildren {
	header?: ReactNode;
	footer?: ReactNode;
}

export default function Layout({ header, footer, children }: LayoutProps) {
	const bodyRef = useRef<HTMLDivElement | null>(null);

	useEffect(() => {
		const scrollToBottom = () => {
			const element = bodyRef.current;
			if (element) {
				element.scrollTop = element.scrollHeight;
			}
		};

		const off = chatEventBus.on("scrollToBottom", scrollToBottom);
		window.addEventListener("resize", scrollToBottom);

		return () => {
			off();
			window.removeEventListener("resize", scrollToBottom);
		};
	}, []);

	return (
		<main className="chat-layout">
			{header && <div className="chat-header">{header}</div>}
			{children && (
				<div ref={bodyRef} className="chat-body">
					{children}
				</div>
			)}
			{footer && <div className="chat-footer">{footer}</div>}
		</main>
	);
}
