'use client';

import { useState, useRef, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faGear, faRotate, faUpRightFromSquare, faEraser, faMagnifyingGlassPlus, faMagnifyingGlassMinus } from '@fortawesome/free-solid-svg-icons';

type Props = {
	onRefresh: () => void;
	onOpenPopup: () => void;
	onClear: () => void;
	onFontLarger: () => void;
	onFontSmaller: () => void;
	// 팝업 창 내부에서는 "새창으로 보기" 숨김
	showPopup?: boolean;
};

// 채팅 설정 dropdown (톱니바퀴) — 새로고침 / 새창으로 보기 / 지우개(로컬) / 글씨 크게·작게
export default function ChatSettingsMenu({ onRefresh, onOpenPopup, onClear, onFontLarger, onFontSmaller, showPopup = true }: Props)
{
	const [open, setOpen] = useState(false);
	const ref = useRef<HTMLDivElement>(null);

	useEffect(() => {
		const handleClickOutside = (e: MouseEvent) => {
			if (ref.current && !ref.current.contains(e.target as Node)) {
				setOpen(false);
			}
		};

		if (open) {
			document.addEventListener('mousedown', handleClickOutside);
		}

		return () => {
			document.removeEventListener('mousedown', handleClickOutside);
		};
	}, [open]);

	// 실행 후 dropdown 닫기 (글씨 크게/작게는 연속 조작을 위해 열어둠)
	const run = (fn: () => void, keepOpen = false) => () => {
		fn();
		if (!keepOpen) {
			setOpen(false);
		}
	};

	return (
		<div className='chat-menu' ref={ref}>
			<button
				type='button'
				className='chat-menu__trigger'
				onClick={() => setOpen((v) => !v)}
				aria-haspopup='menu'
				aria-expanded={open}
				title='채팅 설정'
			>
				<FontAwesomeIcon icon={faGear} />
			</button>

			{open && (
				<div className='chat-menu__dropdown' role='menu'>
					<button type='button' role='menuitem' className='chat-menu__item' onClick={run(onRefresh)}>
						<FontAwesomeIcon icon={faRotate} />
						<span>새로고침</span>
					</button>
					{showPopup && (
						<button type='button' role='menuitem' className='chat-menu__item' onClick={run(onOpenPopup)}>
							<FontAwesomeIcon icon={faUpRightFromSquare} />
							<span>새창으로 보기</span>
						</button>
					)}
					<button type='button' role='menuitem' className='chat-menu__item' onClick={run(onClear)}>
						<FontAwesomeIcon icon={faEraser} />
						<span>지우개</span>
					</button>
					<div className='chat-menu__divider' role='separator' />
					<button type='button' role='menuitem' className='chat-menu__item' onClick={run(onFontLarger, true)}>
						<FontAwesomeIcon icon={faMagnifyingGlassPlus} />
						<span>글씨 크게</span>
					</button>
					<button type='button' role='menuitem' className='chat-menu__item' onClick={run(onFontSmaller, true)}>
						<FontAwesomeIcon icon={faMagnifyingGlassMinus} />
						<span>글씨 작게</span>
					</button>
				</div>
			)}
		</div>
	);
}
