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

export const metadata: Metadata = {
	title: '외화 커스터디 — 개미투자',
	description: '국가별 외화증권 보관금액 추이 — 서학개미 자금 흐름 (USD, SEIBro 수집)'
};

export default async function MarketForeignPage()
{
	const res = await fetchForeignCustody({});
	const nations = res.success ? (res.data?.nations ?? []) : [];

	return (
		<div className='market'>
			<div className='market__head'>
				<h1 className='market__title'>외화 커스터디</h1>
				<span className='market__basis'>국가별 외화증권 보관금액 추이 · USD 기준 (SEIBro)</span>
			</div>

			<MarketNav />

			{!res.success ? (
				<div className='market__error' role='alert'>
					<strong>외화 커스터디 데이터를 불러오지 못했습니다.</strong>
					잠시 후 다시 시도해 주세요.
				</div>
			) : nations.length === 0 ? (
				<div className='market__empty'>표시할 외화 커스터디 데이터가 없습니다.</div>
			) : (
				<div className='market__series-grid'>
					{nations.map((series, index) => {
						const latest = series.points.length > 0 ? series.points[series.points.length - 1] : null;
						const secnLabel = series.secnTpcd ? codeLabel(series.secnTpcd, FOREIGN_SECN_TPCD_LABEL) : '전체 합산';

						return (
							<div key={`${series.nationCd}-${series.secnTpcd ?? 'all'}-${index}`} className='market__series-card'>
								<div className='market__series-head'>
									<span className='market__series-name'>
										{codeLabel(series.nationCd, NATION_LABEL)}
									</span>
									<span className='market__cls-badge'>{secnLabel}</span>
								</div>

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

								<Sparkline
									values={series.points.map(p => p.custodyAmount)}
									label={`${codeLabel(series.nationCd, NATION_LABEL)} 보관금액 추이`}
								/>

								<div className='market__series-sub'>
									<span>{series.nationCd}</span>
									<span>{latest?.stdDt ?? '—'} 기준</span>
								</div>
							</div>
						);
					})}
				</div>
			)}
		</div>
	);
}
