'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { cn, fetchApi } from '@/lib/utils/client';
import { formatBpPercent, bpDirection } from '@/lib/utils/paper';
import type { PaperLeaderboardResponse, PaperLeaderboardRow } from '@/types/paper';

// 홈 리더보드 Top10 미니 — 수익률·전체 기준
export default function PaperLeaderboardMini()
{
	const [rows, setRows] = useState<PaperLeaderboardRow[]>([]);
	const [loading, setLoading] = useState(true);

	useEffect(() => {
		let cancelled = false;

		(async () => {
			const res = await fetchApi<PaperLeaderboardResponse>('/api/paper/leaderboard?sort=return&period=all&page=1', { silent: true });
			if (cancelled) {
				return;
			}

			setRows(res.success ? (res.data?.rows ?? []).slice(0, 10) : []);
			setLoading(false);
		})();

		return () => {
			cancelled = true;
		};
	}, []);

	return (
		<section className='paper__section'>
			<div className='paper__section-head'>
				<h2 className='paper__section-title'>리더보드 Top 10</h2>
				<Link href='/paper/leaderboard' className='paper__section-link'>전체 보기</Link>
			</div>

			{loading ? (
				<div className='paper__empty'>불러오는 중...</div>
			) : rows.length === 0 ? (
				<div className='paper__empty'>아직 등재된 참여자가 없습니다.</div>
			) : (
				<div className='paper__table-wrap'>
					<table className='paper__table'>
						<thead>
							<tr>
								<th className='paper__th--center'>순위</th>
								<th className='paper__th--left'>닉네임</th>
								<th>수익률</th>
							</tr>
						</thead>
						<tbody>
							{rows.map(row => {
								const dir = bpDirection(row.returnBp);

								return (
									<tr key={row.memberSID}>
										<td className='paper__td--center paper__rank'>{row.rank}</td>
										<td className='paper__td--left'>
											<Link href={`/user/${row.memberSID}/paper`} className='paper__nick-name'>
												{row.nickname || '익명'}
											</Link>
										</td>
										<td className={cn(`paper__value--${dir}`)}>{formatBpPercent(row.returnBp)}</td>
									</tr>
								);
							})}
						</tbody>
					</table>
				</div>
			)}
		</section>
	);
}
