/**
 * 전역 알림 UI — 모든 화면 위에 표시 (body 포털)
 */
import React from 'react';
import { createPortal } from 'react-dom';
import TradeSignalSnackbar from './TradeSignalSnackbar';
import TradeAlertModal from './TradeAlertModal';
import { useTradeNotification } from '../contexts/TradeNotificationContext';
import {
  normalizeTradeAlertGridCols,
  normalizeTradeAlertPopupLayout,
  normalizeTradeAlertPopupPosition,
} from '../utils/tradeAlertPopupLayout';
import type { MenuPage } from './TopMenuBar';

interface Props {
  menuPage: MenuPage;
  onPage: (page: MenuPage) => void;
  onGoToChart: (market: string) => void;
  tradingMode?: string;
  hasUpbitKeys?: boolean;
  paperTradingEnabled?: boolean;
  liveAutoTradeBudgetPct?: number;
  paperAutoTradeBudgetPct?: number;
  tradeAlertPopupPosition?: string;
  tradeAlertPopupLayout?: string;
  tradeAlertPopupGridCols?: number;
  onOrderDone?: () => void;
}

export const AppNotificationLayer: React.FC<Props> = ({
  menuPage,
  onPage,
  onGoToChart,
  tradingMode,
  hasUpbitKeys,
  paperTradingEnabled,
  liveAutoTradeBudgetPct,
  paperAutoTradeBudgetPct,
  tradeAlertPopupPosition = 'right',
  tradeAlertPopupLayout = 'stack',
  tradeAlertPopupGridCols = 2,
  onOrderDone,
}) => {
  const { detailSignal, detailCentered, closeDetail } = useTradeNotification();
  const popupPosition = normalizeTradeAlertPopupPosition(tradeAlertPopupPosition);
  const popupLayout = normalizeTradeAlertPopupLayout(tradeAlertPopupLayout);
  const gridCols = normalizeTradeAlertGridCols(tradeAlertPopupGridCols);

  const content = (
    <div className="app-notification-layer" aria-hidden={false}>
      <TradeSignalSnackbar
        onGoToChart={market => {
          onGoToChart(market);
          onPage('chart');
        }}
        onOpenList={() => onPage('notifications')}
        popupPosition={popupPosition}
        popupLayout={popupLayout}
        gridCols={gridCols}
      />
      {detailSignal && (
        <TradeAlertModal
          key={`${detailSignal.market}-${detailSignal.candleTime}-${detailSignal.signalType}`}
          signal={detailSignal}
          centered={detailCentered}
          onClose={closeDetail}
          tradingMode={tradingMode}
          hasUpbitKeys={hasUpbitKeys}
          paperTradingEnabled={paperTradingEnabled}
          liveAutoTradeBudgetPct={liveAutoTradeBudgetPct}
          paperAutoTradeBudgetPct={paperAutoTradeBudgetPct}
          onOrderDone={onOrderDone}
        />
      )}
    </div>
  );

  if (typeof document === 'undefined') return null;
  return createPortal(content, document.body);
};

export default AppNotificationLayer;
