import '../style.scss';
import { Metadata } from 'next';
import MarketNav from '../_components/MarketNav';
import Sparkline from '../_components/Sparkline';
import { fetchElsRisk } from '@/lib/api/seibro';
import { codeLabel, formatAmountCompact, formatShares } from '@/lib/utils/market';
import { ELS_SECN_TPCD_LABEL } from '@/types/seibro';

export const metadata: Metadata = {
	title: 'ELS 리스크보드 — 개미투자',
	description: 'ELS/DLS 기초자산별 미상환잔액 추이 — 지수 하락 리스크 지표 (SEIBro 수집)'
};

export default async function MarketElsRiskPage()
{
	const res = await fetchElsRisk({});
	const assets = res.success ? (res.data?.assets ?? []) : [];

	return (
		<div className='market'>
			<div className='market__head'>
				<h1 className='market__title'>ELS 리스크보드</h1>
				<span className='market__basis'>기초자산별 미상환잔액 추이 · 지수 하락 리스크 (SEIBro)</span>
			</div>

			<MarketNav />

			{!res.success ? (
				<div className='market__error' role='alert'>
					<strong>ELS 리스크 데이터를 불러오지 못했습니다.</strong>
					잠시 후 다시 시도해 주세요.
				</div>
			) : assets.length === 0 ? (
				<div className='market__empty'>표시할 ELS 리스크 데이터가 없습니다.</div>
			) : (
				<div className='market__series-grid'>
					{assets.map((series, index) => {
						const latest = series.points.length > 0 ? series.points[series.points.length - 1] : null;

						return (
							<div key={`${series.bassetCd}-${series.secnTpcd}-${index}`} className='market__series-card'>
								<div className='market__series-head'>
									<span className='market__series-name' title={series.bassetContent ?? series.bassetCd}>
										{series.bassetContent ?? series.bassetCd}
									</span>
									<span className='market__cls-badge'>{codeLabel(series.secnTpcd, ELS_SECN_TPCD_LABEL)}</span>
								</div>

								<span className='market__series-latest'>{formatAmountCompact(latest?.unredeemedRemaining)}</span>

								<Sparkline
									values={series.points.map(p => p.unredeemedRemaining)}
									label={`${series.bassetContent ?? series.bassetCd} 미상환잔액 추이`}
								/>

								<div className='market__series-sub'>
									<span>미상환 {formatShares(latest?.unredeemedCount)}종목</span>
									<span>{latest?.stdDt ?? '—'} 기준</span>
								</div>
							</div>
						);
					})}
				</div>
			)}
		</div>
	);
}
