'use client';

// D6 §5.1 — 종목행(StockRow) 열 구성 빌더 + StockDataTable 편의 래퍼.
// 한 줄 완결: 종목명+코드 | 현재가 | 등락률(색+부호) | 시가총액 | 시장.
// 거래량/시총 등 우선순위 낮은 열은 mobile drop (data-priority='low').
import Link from 'next/link';
import DataTable, { DataTableColumn } from '@/components/table/DataTable';
import PriceChange from '@/components/table/PriceChange';
import { StockListRow } from '@/types/stock';
import { formatKrwCompact, formatNumber, tradingStatusLabel } from '@/lib/utils/stock';

export function buildStockColumns(): DataTableColumn<StockListRow>[] {
	return [
		{
			key: 'name',
			header: '종목명',
			align: 'left',
			priority: 'high',
			cellClassName: 'data-table__cell--name',
			cell: (row) => {
				const status = tradingStatusLabel(row.tradingStatus);

				return (
					<Link href={`/stock/${row.code}`} className='stock-cell'>
						<span className='stock-cell__name'>{row.name}</span>
						<span className='stock-cell__code'>{row.code}</span>
						{status && (
							<span className={`stock-badge stock-badge--${row.tradingStatus.toLowerCase()}`}>{status}</span>
						)}
					</Link>
				);
			}
		},
		{
			key: 'price',
			header: <>현재가 <small>(전일종가)</small></>,
			align: 'right',
			priority: 'high',
			cell: (row) => formatNumber(row.closePrice)
		},
		{
			key: 'change',
			header: '등락률',
			align: 'right',
			priority: 'high',
			cell: (row) => <PriceChange rate={row.changeRate} />
		},
		{
			key: 'cap',
			header: '시가총액',
			align: 'right',
			priority: 'low',
			cell: (row) => formatKrwCompact(row.marketCap)
		},
		{
			key: 'market',
			header: '시장',
			align: 'center',
			priority: 'medium',
			cell: (row) => <span className={`stock-badge stock-badge--${row.market.toLowerCase()}`}>{row.market}</span>
		}
	];
}

interface StockDataTableProps {
	rows: StockListRow[];
	caption?: string;
	emptyMessage?: string;
}

// 종목 목록 편의 래퍼 — 기본 열 구성으로 DataTable 렌더
export default function StockDataTable({ rows, caption, emptyMessage }: StockDataTableProps)
{
	return (
		<DataTable<StockListRow>
			caption={caption ?? '종목 목록 — 종목명, 현재가(전일 종가), 등락률, 시가총액, 시장'}
			columns={buildStockColumns()}
			rows={rows}
			rowKey={(row) => row.code}
			emptyMessage={emptyMessage}
		/>
	);
}
