'use client';

import { useEffect, useRef } from 'react';
import useTheme from '@/hooks/useTheme';

// TradingView 고급차트 임베드 — 세계지수 드릴다운(실시간 보완). 시세 표시 책임은 TradingView 측.
// symbol 은 types/worldIndex.ts TV_SYMBOL 매핑값(예: "KRX:KOSPI", "TVC:NI225").
type Props = {
	symbol: string;
};

export default function TradingViewChart({ symbol }: Props)
{
	const containerRef = useRef<HTMLDivElement>(null);
	const { isDark } = useTheme();

	useEffect(() => {
		const container = containerRef.current;
		if (!container) {
			return;
		}

		container.innerHTML = '';

		const widget = document.createElement('div');
		widget.className = 'tradingview-widget-container__widget';
		widget.style.height = '100%';
		widget.style.width = '100%';
		container.appendChild(widget);

		const script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = 'https://s3.tradingview.com/external-embedding/embed-widget-advanced-chart.js';
		script.async = true;
		script.innerHTML = JSON.stringify({
			symbol,
			autosize: true,
			interval: 'D',
			timezone: 'Asia/Seoul',
			theme: isDark ? 'dark' : 'light',
			style: '1',
			locale: 'kr',
			hide_side_toolbar: true,
			allow_symbol_change: false,
			calendar: false,
			support_host: 'https://www.tradingview.com'
		});
		container.appendChild(script);

		return () => {
			container.innerHTML = '';
		};
	}, [symbol, isDark]);

	return (
		<div className='tradingview-widget-container' ref={containerRef} style={{ height: '100%', width: '100%' }} />
	);
}
