'use client';

import { createContext, useContext, useState, useCallback } from 'react';
import type { TickerData, TickerMeta } from '@/types/crypto';

interface CryptoContextType {
	selectedMarket: string;
	setSelectedMarket: (market: string) => void;
	quoteMarket: string;
	setQuoteMarket: (quote: string) => void;
	tickers: Map<string, TickerData>;
	setTickers: (tickers: Map<string, TickerData>) => void;
	tickerMeta: Map<string, TickerMeta>;
	setTickerMeta: (meta: Map<string, TickerMeta>) => void;
}

const CryptoContext = createContext<CryptoContextType>({
	selectedMarket: 'KRW-BTC',
	setSelectedMarket: () => {},
	quoteMarket: 'KRW',
	setQuoteMarket: () => {},
	tickers: new Map(),
	setTickers: () => {},
	tickerMeta: new Map(),
	setTickerMeta: () => {},
});

type Props = {
	children: React.ReactNode;
	initialMarket?: string;
};

export function CryptoProvider({ children, initialMarket = 'KRW-BTC' }: Props) {
	const [selectedMarket, setSelectedMarketState] = useState(initialMarket);
	const [quoteMarket, setQuoteMarketState] = useState('KRW');
	const [tickers, setTickersState] = useState<Map<string, TickerData>>(new Map());
	const [tickerMeta, setTickerMetaState] = useState<Map<string, TickerMeta>>(new Map());

	const setSelectedMarket = useCallback((market: string) => {
		setSelectedMarketState(market);
	}, []);

	const setQuoteMarket = useCallback((quote: string) => {
		setQuoteMarketState(quote);
	}, []);

	const setTickers = useCallback((t: Map<string, TickerData>) => {
		setTickersState(t);
	}, []);

	const setTickerMeta = useCallback((m: Map<string, TickerMeta>) => {
		setTickerMetaState(m);
	}, []);

	return (
		<CryptoContext.Provider value={{
			selectedMarket, setSelectedMarket,
			quoteMarket, setQuoteMarket,
			tickers, setTickers,
			tickerMeta, setTickerMeta,
		}}>
			{children}
		</CryptoContext.Provider>
	);
}

export function useCryptoContext() {
	return useContext(CryptoContext);
}