'use client';

import './style.scss';
import { useEffect } from 'react';
import boardMeta from '@/types/forum/boardMeta';

type Props = {
	boardMeta: boardMeta;
	content: string;
}

export default function Content({ boardMeta, content }: Props)
{
	useEffect(() => {
		const handler = async (e: MouseEvent) => {
			const target = e.target as HTMLElement;

			// 파일 다운로드
			const file = target.closest('section.file-embed') as HTMLElement;
			if (file && file.dataset.uuid) {
				window.location.href = process.env.NEXT_PUBLIC_API_URL + `/api/forum/post/file/${file.dataset.uuid}`;
			}

			// 링크 클릭
			const anchor = target.closest('a[data-uuid]') as HTMLAnchorElement;
			if (anchor && anchor.dataset.uuid) {
				e.preventDefault();

				// 무조건 URL 새창 열림이라면 _blank 속성 강제 적용
				window.open((process.env.NEXT_PUBLIC_API_URL + `/api/forum/post/link/${anchor.dataset.uuid}`), boardMeta.view.allowContentLinkTargetBlank ? '_blank' : '_self');
			}
		}

		document.addEventListener('click', handler);
		return () => {
			document.removeEventListener('click', handler);
		}
	}, []);

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