'use client';

import './style.scss';
import { useEffect, useRef } from 'react';
import BoardMeta from '@/types/forum/boardMeta';
import BoardManager from '@/types/forum/boardManager';
import { checkPermission } from '@/lib/utils/permission';

type Props = {
	boardMeta: BoardMeta;
	content: string;
	boardManagers?: BoardManager[];
}

export default function Content({ boardMeta, content, boardManagers }: Props)
{
	const articleRef = useRef<HTMLElement>(null);
	const allowTargetBlank = boardMeta.view.allowContentLinkTargetBlank;

	useEffect(() => {
		const el = articleRef.current;
		if (!el) {
			return;
		}

		const handler = (e: MouseEvent) => {
			const target = e.target as HTMLElement;

			// 파일 다운로드
			const file = target.closest('section.file-embed') as HTMLElement;
			if (file && file.dataset.uuid) {
				// 파일 다운로드 권한 체크
				if (boardManagers) {
					const stored = localStorage.getItem('member');
					const member = stored ? JSON.parse(stored) : null;

					if (!checkPermission(boardMeta, boardManagers, member).canDownloadFile) {
						alert('파일을 다운로드할 수 있는 권한이 없습니다.');
						return;
					}
				}

				window.location.href = `/api/forum/post/file/${file.dataset.uuid}`;
			}

			// 링크 클릭
			const anchor = target.closest('a[data-uuid]') as HTMLAnchorElement;
			if (anchor && anchor.dataset.uuid) {
				e.preventDefault();
				window.open(`/api/forum/post/link/${anchor.dataset.uuid}`, allowTargetBlank ? '_blank' : '_self');
			}
		}

		el.addEventListener('click', handler);
		return () => {
			el.removeEventListener('click', handler);
		}
	}, [allowTargetBlank, boardMeta, boardManagers]);

	return (
		<article ref={articleRef} dangerouslySetInnerHTML={{ __html: content }} className='whitespace-normal break-words'></article>
	);
}
