import '../style.scss';
import '@/app/styles/data-table.scss';
import { Metadata } from 'next';
import MarketNav from '../_components/MarketNav';
import DividendCalendarTable from '../_components/DividendCalendarTable';
import Pager from '../_components/Pager';
import { fetchDividendCalendar } from '@/lib/api/seibro';
import { formatNumber } from '@/lib/utils/stock';

export const metadata: Metadata = {
	title: '배당 캘린더 — 개미투자',
	description: '국내 배당 일정 — 권리기준일·권리락일·배당구분(주식/현금)·시가배당율 (SEIBro 수집)'
};

const PER_PAGE = 30;

type Props = {
	searchParams: Promise<{
		page?: string;
	}>;
};

export default async function MarketDividendsPage({ searchParams }: Props)
{
	const query = await searchParams;
	const page = Math.max(Number(query.page) || 1, 1);

	const res = await fetchDividendCalendar({ page, perPage: PER_PAGE });
	const data = res.success ? res.data : null;

	return (
		<div className='market'>
			<div className='market__head'>
				<h1 className='market__title'>배당 캘린더</h1>
				<span className='market__basis'>권리기준일 최신순 · 주식/현금 구분 (SEIBro)</span>
			</div>

			<MarketNav />

			{!res.success ? (
				<div className='market__error' role='alert'>
					<strong>배당 일정을 불러오지 못했습니다.</strong>
					잠시 후 다시 시도해 주세요.
				</div>
			) : !data || data.list.length === 0 ? (
				<div className='market__empty'>표시할 배당 일정이 없습니다.</div>
			) : (
				<>
					<p className='market__total'>전체 {formatNumber(data.total)}건</p>
					<div className='market__table-wrap'>
						<DividendCalendarTable rows={data.list} />
					</div>
					<Pager
						total={data.total}
						page={page}
						perPage={PER_PAGE}
						basePath='/market/dividends'
						query={{}}
					/>
				</>
			)}
		</div>
	);
}
