import '../market/style.scss';
import { Metadata } from 'next';
import MarketNav from '../market/_components/MarketNav';
import MarketFilterTabs from '../market/_components/MarketFilterTabs';
import DisclosureList from '../market/_components/DisclosureList';
import Pager from '../market/_components/Pager';
import { fetchDisclosures } from '@/lib/api/market';
import { CorpClsCode } from '@/types/market';
import { formatNumber } from '@/lib/utils/stock';

export const metadata: Metadata = {
	title: '공시 — 개미투자',
	description: 'DART 전자공시 피드 — 유가·코스닥·코넥스·기타 법인 최근 공시 (실시간 반영)'
};

const CLS_TABS: { value: ''|CorpClsCode; label: string }[] = [
	{ value: '', label: '전체' },
	{ value: 'Y', label: '유가' },
	{ value: 'K', label: '코스닥' },
	{ value: 'N', label: '코넥스' },
	{ value: 'E', label: '기타' }
];

const PER_PAGE = 20;

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

export default async function DisclosureFeedPage({ searchParams }: Props)
{
	const query = await searchParams;
	const corpCls = CLS_TABS.some(c => c.value === query.corpCls) ? (query.corpCls as ''|CorpClsCode) : '';
	const page = Math.max(Number(query.page) || 1, 1);

	const res = await fetchDisclosures({ corpCls: corpCls || undefined, 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'>DART 전자공시 · 최신순</span>
			</div>

			<MarketNav />

			<div className='market__filters'>
				<MarketFilterTabs
					label='법인구분'
					paramKey='corpCls'
					tabs={CLS_TABS}
					active={corpCls}
					basePath='/disclosure'
				/>
			</div>

			{!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>
					<DisclosureList rows={data.list} />
					<Pager
						total={data.total}
						page={page}
						perPage={PER_PAGE}
						basePath='/disclosure'
						query={{ ...(corpCls ? { corpCls } : {}) }}
					/>
				</>
			)}
		</div>
	);
}
