import React, { memo, useMemo, useState, useEffect, useRef, useCallback } from 'react';
import {
  Box,
  Paper,
  Typography,
  List,
  ListItem,
  ListItemButton,
  Autocomplete,
  TextField,
  Chip,
  keyframes,
  Tabs,
  Tab,
  IconButton,
  TableSortLabel,
  Divider,
} from '@mui/material';
import {
  Circle as CircleIcon,
  Star as StarIcon,
  StarBorder as StarBorderIcon,
  AddCircle as AddCircleIcon,
  AddCircleOutline as AddCircleOutlineIcon,
  RemoveCircleOutline as RemoveCircleOutlineIcon,
} from '@mui/icons-material';
import { MarketTicker } from '../types/ticker';
import { WebSocketStatus } from '../types/orderbook';
import { toggleFavorite, getAllFavorites } from '../services/cryptoFavoriteApi';
import { toggleHolding, getAllHoldings, CryptoHoldingDto } from '../services/cryptoHoldingApi';

/**
 * 가격 변동 플래시 애니메이션
 */
const flashRise = keyframes`
  0% { background-color: rgba(239, 68, 68, 0.3); }
  100% { background-color: transparent; }
`;

const flashFall = keyframes`
  0% { background-color: rgba(59, 130, 246, 0.3); }
  100% { background-color: transparent; }
`;

interface MarketListProps {
  tickers: Map<string, MarketTicker>;
  selectedMarket: string;
  onSelectMarket: (market: string) => void;
  wsStatus: WebSocketStatus;
}

/**
 * 정렬 타입
 */
type SortField = 'koreanName' | 'tradePrice' | 'changeRate' | 'accTradePrice24h';
type SortOrder = 'asc' | 'desc';

/**
 * 탭 타입
 */
type MarketTab = 'krw' | 'btc' | 'holdings' | 'favorites';

/**
 * 가격 포맷 (소수점 처리)
 */
const formatPrice = (price: number): string => {
  if (price >= 1000) {
    return price.toLocaleString('ko-KR', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
  } else if (price >= 100) {
    return price.toLocaleString('ko-KR', { minimumFractionDigits: 0, maximumFractionDigits: 1 });
  } else if (price >= 1) {
    return price.toLocaleString('ko-KR', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
  } else {
    return price.toLocaleString('ko-KR', { minimumFractionDigits: 0, maximumFractionDigits: 4 });
  }
};

/**
 * 거래대금 포맷 (억 단위)
 */
const formatTradePrice = (price: number): string => {
  const billion = price / 100000000; // 억 단위
  if (billion >= 100) {
    return `${Math.floor(billion).toLocaleString()}억`;
  } else if (billion >= 1) {
    return `${billion.toFixed(0)}억`;
  } else {
    return `${(price / 1000000).toFixed(0)}백만`;
  }
};

/**
 * 등락률 색상
 */
const getChangeColor = (change: 'RISE' | 'EVEN' | 'FALL'): string => {
  switch (change) {
    case 'RISE':
      return '#ef4444'; // 빨간색
    case 'FALL':
      return '#3b82f6'; // 파란색
    case 'EVEN':
    default:
      return '#6b7280'; // 회색
  }
};

/**
 * 연결 상태 색상
 */
const getStatusColor = (status: WebSocketStatus): string => {
  switch (status) {
    case 'connected':
      return '#22c55e';
    case 'connecting':
      return '#eab308';
    case 'disconnected':
    case 'error':
      return '#ef4444';
    default:
      return '#9ca3af';
  }
};

/**
 * 종목 목록 컴포넌트
 */
/**
 * 가격 변동 추적 컴포넌트 (업비트 스타일)
 */
/** code(KRW-BTC) → "BTC/KRW" 형태 심볼 변환 */
const codeToSymbolLabel = (code: string): string => {
  const parts = code.split('-');
  if (parts.length === 2) return `${parts[1]}/${parts[0]}`;
  return code;
};

/** 변동 지시자 바 (이미지 스타일) */
const ChangeBar = memo<{ change: 'RISE' | 'EVEN' | 'FALL' }>(({ change }) => {
  const color = getChangeColor(change);
  if (change === 'EVEN') {
    return (
      <Box sx={{ width: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Box sx={{ width: 8, height: 2, bgcolor: color, borderRadius: 1 }} />
      </Box>
    );
  }
  return (
    <Box sx={{ width: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      <Box sx={{
        width: 0, height: 0,
        borderLeft: '5px solid transparent',
        borderRight: '5px solid transparent',
        ...(change === 'RISE'
          ? { borderBottom: `7px solid ${color}` }
          : { borderTop: `7px solid ${color}` }),
      }} />
    </Box>
  );
});
ChangeBar.displayName = 'ChangeBar';

/** USD 가격 포맷 */
const formatUsdPrice = (krwPrice: number, usdtKrwRate: number): string => {
  if (!usdtKrwRate || usdtKrwRate === 0) return '-';
  const usd = krwPrice / usdtKrwRate;
  if (usd >= 10000) return `$${usd.toLocaleString('en-US', { maximumFractionDigits: 0 })}`;
  if (usd >= 1) return `$${usd.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  return `$${usd.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 6 })}`;
};

const TickerItem = memo<{
  ticker: MarketTicker;
  isSelected: boolean;
  isFavorite: boolean;
  onSelect: () => void;
  onToggleFavorite: (e: React.MouseEvent) => void;
  priceUnit?: 'krw' | 'usd';
  usdtKrwRate?: number;
  /** 'favorite': 별 아이콘  |  'holding': +/- 아이콘 */
  iconMode?: 'favorite' | 'holding';
  isHolding?: boolean;
  onToggleHolding?: (e: React.MouseEvent) => void;
}>(({
  ticker, isSelected, isFavorite, onSelect, onToggleFavorite,
  priceUnit = 'krw', usdtKrwRate = 1,
  iconMode = 'favorite', isHolding = false, onToggleHolding,
}) => {
  const [priceFlash, setPriceFlash] = useState<'rise' | 'fall' | null>(null);
  const prevPriceRef = useRef(ticker.tradePrice);

  useEffect(() => {
    if (prevPriceRef.current !== ticker.tradePrice) {
      const flash = ticker.tradePrice > prevPriceRef.current ? 'rise' : 'fall';
      setPriceFlash(flash);
      prevPriceRef.current = ticker.tradePrice;
      const timer = setTimeout(() => setPriceFlash(null), 600);
      return () => clearTimeout(timer);
    }
  }, [ticker.tradePrice]);

  const changeColor = getChangeColor(ticker.change);
  const symbolLabel = codeToSymbolLabel(ticker.code);
  const displayPrice = priceUnit === 'usd'
    ? formatUsdPrice(ticker.tradePrice, usdtKrwRate)
    : formatPrice(ticker.tradePrice);

  return (
    <ListItem
      disablePadding
      sx={{
        borderBottom: 1,
        borderColor: 'divider',
        '&:hover .favorite-icon': { opacity: 1 },
      }}
    >
      <ListItemButton
        selected={isSelected}
        onClick={onSelect}
        sx={{
          py: 0.75,
          px: 1,
          width: '100%',
          boxSizing: 'border-box',
          display: 'flex',
          alignItems: 'center',
          gap: 0.5,
          overflow: 'hidden',
          '&.Mui-selected': { backgroundColor: 'action.selected' },
          '&:hover': { backgroundColor: 'action.hover' },
          animation: priceFlash
            ? `${priceFlash === 'rise' ? flashRise : flashFall} 0.6s ease-out`
            : 'none',
        }}
      >
        {/* 아이콘: 즐겨찾기 별 또는 보유 +/- */}
        {iconMode === 'holding' ? (
          <IconButton
            size="small"
            onClick={onToggleHolding}
            className="favorite-icon"
            sx={{
              opacity: isHolding ? 1 : 0.3,
              transition: 'opacity 0.2s, color 0.2s',
              color: isHolding ? '#26a69a' : 'text.secondary',
              p: 0.25,
              flexShrink: 0,
              '&:hover': { opacity: 1, color: isHolding ? '#ef5350' : '#26a69a' },
            }}
          >
            {isHolding
              ? <RemoveCircleOutlineIcon sx={{ fontSize: 15 }} />
              : <AddCircleOutlineIcon sx={{ fontSize: 15 }} />}
          </IconButton>
        ) : (
          <IconButton
            size="small"
            onClick={onToggleFavorite}
            className="favorite-icon"
            sx={{
              opacity: isFavorite ? 1 : 0.25,
              transition: 'opacity 0.2s',
              color: isFavorite ? 'warning.main' : 'text.secondary',
              p: 0.25,
              flexShrink: 0,
            }}
          >
            {isFavorite ? <StarIcon sx={{ fontSize: 14 }} /> : <StarBorderIcon sx={{ fontSize: 14 }} />}
          </IconButton>
        )}

        {/* 변동 지시자 */}
        <ChangeBar change={ticker.change} />

        {/* 한글명 + 영문심볼 */}
        <Box sx={{ flex: '1 1 0', minWidth: 0, overflow: 'hidden' }}>
          <Typography
            variant="body2"
            fontWeight={700}
            sx={{
              fontSize: '0.82rem',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              lineHeight: 1.3,
            }}
          >
            {ticker.koreanName}
          </Typography>
          <Typography
            variant="caption"
            color="text.secondary"
            sx={{ fontSize: '0.68rem', lineHeight: 1.2, display: 'block' }}
          >
            {symbolLabel}
          </Typography>
        </Box>

        {/* 현재가 */}
        <Box sx={{ width: 90, flexShrink: 0, textAlign: 'right', overflow: 'hidden' }}>
          <Typography
            variant="body2"
            fontWeight={700}
            sx={{
              color: changeColor,
              fontFamily: 'monospace',
              fontSize: '0.82rem',
              lineHeight: 1.3,
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
            }}
          >
            {displayPrice}
          </Typography>
        </Box>

        {/* 전일대비 */}
        <Box sx={{ width: 68, flexShrink: 0, textAlign: 'right', overflow: 'hidden' }}>
          <Typography
            variant="caption"
            sx={{
              color: changeColor,
              fontWeight: 700,
              display: 'block',
              fontSize: '0.75rem',
              lineHeight: 1.3,
              whiteSpace: 'nowrap',
            }}
          >
            {ticker.changeRate > 0 ? '+' : ''}{ticker.changeRate.toFixed(2)}%
          </Typography>
        </Box>
      </ListItemButton>
    </ListItem>
  );
});

TickerItem.displayName = 'TickerItem';

export const MarketList = memo<MarketListProps>(({ tickers, selectedMarket, onSelectMarket, wsStatus }) => {
  const [selectedTicker, setSelectedTicker] = useState<MarketTicker | null>(null);
  const [currentTab, setCurrentTab] = useState<MarketTab>('krw');
  const [sortField, setSortField] = useState<SortField>('accTradePrice24h');
  const [sortOrder, setSortOrder] = useState<SortOrder>('desc');
  const [favorites, setFavorites] = useState<Set<string>>(new Set());
  const [holdings, setHoldings] = useState<Set<string>>(new Set());

  // 즐겨찾기 로드
  useEffect(() => {
    loadFavorites();
  }, []);

  const loadFavorites = async () => {
    try {
      const favoriteList = await getAllFavorites();
      const favoriteSet = new Set(favoriteList.map(f => f.symbol));
      setFavorites(favoriteSet);
    } catch (error) {
      console.error('즐겨찾기 로드 실패:', error);
    }
  };

  // 보유 종목 로드
  useEffect(() => {
    loadHoldings();
  }, []);

  const loadHoldings = async () => {
    try {
      const list = await getAllHoldings();
      setHoldings(new Set(list.map(h => h.symbol)));
    } catch (error) {
      console.error('보유 종목 로드 실패:', error);
    }
  };

  // 보유 토글
  const handleToggleHolding = async (e: React.MouseEvent, ticker: MarketTicker) => {
    e.stopPropagation();
    try {
      const isAdded = await toggleHolding({
        symbol: ticker.code,
        koreanName: ticker.koreanName,
        englishName: ticker.englishName,
      });
      setHoldings(prev => {
        const next = new Set(prev);
        if (isAdded) next.add(ticker.code);
        else next.delete(ticker.code);
        return next;
      });
    } catch (error) {
      console.error('보유 종목 토글 실패:', error);
    }
  };

  // USDT/KRW 환율 (BTC 탭 USD 가격 표시용) — 30초마다만 재계산
  const usdtKrwRateRef = useRef<number>(1350);
  const usdtKrwRate = useMemo(() => {
    const rate = tickers.get('KRW-USDT')?.tradePrice || 1350;
    usdtKrwRateRef.current = rate;
    return rate;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [Math.floor(Date.now() / 30000)]); // 30초 버킷

  // 즐겨찾기 토글
  const handleToggleFavorite = async (e: React.MouseEvent, ticker: MarketTicker) => {
    e.stopPropagation();
    try {
      const isFavorite = await toggleFavorite({
        symbol: ticker.code,
        koreanName: ticker.koreanName,
        englishName: ticker.englishName,
      });
      setFavorites(prev => {
        const newSet = new Set(prev);
        if (isFavorite) newSet.add(ticker.code);
        else newSet.delete(ticker.code);
        return newSet;
      });
    } catch (error) {
      console.error('즐겨찾기 토글 실패:', error);
    }
  };

  // 정렬 변경 핸들러
  const handleSortChange = (field: SortField) => {
    if (sortField === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortOrder('desc');
    }
  };

  // 항상 최신 tickers/favorites/holdings를 ref로 유지 (interval 클로저용)
  const tickersRef = useRef(tickers);
  tickersRef.current = tickers;
  const favoritesRef = useRef(favorites);
  favoritesRef.current = favorites;
  const holdingsRef = useRef(holdings);
  holdingsRef.current = holdings;

  /** 현재 상태 기준으로 정렬된 코드 배열 계산 */
  const computeSortedKeys = useCallback((
    _tickers: Map<string, MarketTicker>,
    _tab: MarketTab,
    _sortField: SortField,
    _sortOrder: SortOrder,
    _favorites: Set<string>,
    _holdings: Set<string>,
  ): string[] => {
    let arr = Array.from(_tickers.values());

    switch (_tab) {
      case 'krw':
      case 'btc':
        arr = arr.filter(t => t.code.startsWith('KRW-'));
        break;
      case 'favorites':
        arr = arr.filter(t => t.code.startsWith('KRW-') && _favorites.has(t.code));
        break;
      case 'holdings':
        // 보유 탭: 전체 KRW 목록, 보유 종목은 상단 정렬
        arr = arr.filter(t => t.code.startsWith('KRW-'));
        break;
    }

    arr.sort((a, b) => {
      // 보유 탭: 보유 종목 항상 상단
      if (_tab === 'holdings') {
        const aH = _holdings.has(a.code) ? 0 : 1;
        const bH = _holdings.has(b.code) ? 0 : 1;
        if (aH !== bH) return aH - bH;
      }

      let cmp = 0;
      switch (_sortField) {
        case 'koreanName':
          cmp = a.koreanName.localeCompare(b.koreanName, 'ko');
          break;
        case 'tradePrice':
          cmp = a.tradePrice - b.tradePrice;
          break;
        case 'changeRate':
          cmp = a.changeRate - b.changeRate;
          break;
        case 'accTradePrice24h':
          cmp = a.accTradePrice24h - b.accTradePrice24h;
          break;
      }
      return _sortOrder === 'asc' ? cmp : -cmp;
    });

    return arr.map(t => t.code);
  }, []);

  // 정렬된 코드 배열 state — 이 순서로 목록을 렌더
  const [sortedKeys, setSortedKeys] = useState<string[]>([]);

  // 정렬 기준(탭/필드/방향/즐겨찾기/보유) 변경 시 즉시 재정렬
  useEffect(() => {
    setSortedKeys(
      computeSortedKeys(tickersRef.current, currentTab, sortField, sortOrder, favoritesRef.current, holdingsRef.current)
    );
  }, [currentTab, sortField, sortOrder, favorites, holdings, computeSortedKeys]);

  // 가격·등락률 기준 정렬 시 2초마다 순서 갱신 (한글명·거래대금은 즉시만)
  useEffect(() => {
    if (sortField !== 'tradePrice' && sortField !== 'changeRate') return;

    const interval = setInterval(() => {
      setSortedKeys(
        computeSortedKeys(tickersRef.current, currentTab, sortField, sortOrder, favoritesRef.current, holdingsRef.current)
      );
    }, 2000);

    return () => clearInterval(interval);
  }, [currentTab, sortField, sortOrder, computeSortedKeys]);

  // tickers 첫 수신 시 초기 정렬 (sortedKeys가 비어 있을 때)
  useEffect(() => {
    if (sortedKeys.length === 0 && tickers.size > 0) {
      setSortedKeys(
        computeSortedKeys(tickers, currentTab, sortField, sortOrder, favoritesRef.current, holdingsRef.current)
      );
    }
  }, [tickers.size]); // eslint-disable-line react-hooks/exhaustive-deps

  // sortedKeys 순서로 현재 tickers 값 조회
  const sortedTickers = useMemo(() => {
    return sortedKeys
      .map(code => tickers.get(code))
      .filter((t): t is MarketTicker => t !== undefined);
  }, [sortedKeys, tickers]);

  // 보유 탭용 전체 KRW 목록 (검색 드롭다운에서 사용)
  const allKrwTickers = useMemo(() => {
    return Array.from(tickers.values())
      .filter(t => t.code.startsWith('KRW-'))
      .sort((a, b) => a.koreanName.localeCompare(b.koreanName, 'ko'));
  }, [tickers]);

  // 검색용 옵션 리스트 — 보유/관심 탭은 전체 KRW, 나머지는 현재 탭 필터 기반
  const searchOptions = useMemo(() => {
    const base = (currentTab === 'holdings' || currentTab === 'favorites') ? allKrwTickers : sortedTickers;
    return base.map(ticker => ({
      label: `${ticker.koreanName} (${ticker.symbol})`,
      value: ticker.code,
      ticker: ticker,
    }));
  }, [currentTab, allKrwTickers, sortedTickers]);

  return (
    <Paper
      elevation={0}
      sx={{
        width: '100%',
        maxWidth: '100%',
        boxSizing: 'border-box',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        border: 1,
        borderColor: 'divider',
        overflow: 'hidden',
      }}
    >
      {/* 탭 네비게이션 */}
      <Box sx={{ borderBottom: 1, borderColor: 'divider', flexShrink: 0, overflow: 'hidden' }}>
        <Tabs
          value={currentTab}
          onChange={(_, newValue) => setCurrentTab(newValue)}
          variant="fullWidth"
          sx={{
            minHeight: 42,
            '& .MuiTab-root': {
              minHeight: 42,
              fontSize: '0.875rem',
              fontWeight: 600,
              minWidth: 0,
            },
          }}
        >
          <Tab label="원화" value="krw" />
          <Tab label="BTC" value="btc" />
          <Tab label="보유" value="holdings" />
          <Tab label="관심" value="favorites" />
        </Tabs>
      </Box>

      {/* 검색 (Autocomplete) */}
      <Box sx={{ p: 1.5, borderBottom: 1, borderColor: 'divider' }}>
        <Autocomplete
          size="small"
          options={searchOptions}
          value={(currentTab === 'holdings' || currentTab === 'favorites') ? null : (selectedTicker ? { label: `${selectedTicker.koreanName} (${selectedTicker.symbol})`, value: selectedTicker.code, ticker: selectedTicker } : null)}
          onChange={(_, newValue) => {
            if (newValue && currentTab !== 'holdings' && currentTab !== 'favorites') {
              setSelectedTicker(newValue.ticker);
              onSelectMarket(newValue.value);
            }
          }}
          getOptionLabel={(option) => option.label}
          clearOnBlur={currentTab === 'holdings' || currentTab === 'favorites'}
          blurOnSelect={currentTab === 'holdings' || currentTab === 'favorites'}
          renderInput={(params) => (
            <TextField
              {...params}
              placeholder={
                currentTab === 'holdings'
                  ? '종목 검색 후 + 버튼으로 추가'
                  : currentTab === 'favorites'
                  ? '종목 검색 후 ★ 버튼으로 즐겨찾기 추가'
                  : '코인명/심볼검색'
              }
            />
          )}
          renderOption={(props, option) => {
            const changeColor = getChangeColor(option.ticker.change);
            const alreadyHolding = holdings.has(option.value);
            const alreadyFavorite = favorites.has(option.value);
            return (
              <li {...props} key={option.value} style={{ paddingRight: (currentTab === 'holdings' || currentTab === 'favorites') ? 4 : undefined }}>
                <Box sx={{ width: '100%', display: 'flex', alignItems: 'center', gap: 0.5 }}>
                  <Box sx={{ flex: 1, minWidth: 0 }}>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Typography variant="body2" fontWeight={600} sx={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {option.ticker.koreanName}
                      </Typography>
                      <Typography variant="caption" sx={{ color: changeColor, fontWeight: 600, flexShrink: 0, ml: 0.5 }}>
                        {option.ticker.changeRate > 0 ? '+' : ''}
                        {option.ticker.changeRate.toFixed(2)}%
                      </Typography>
                    </Box>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 0.25 }}>
                      <Typography variant="caption" color="text.secondary">
                        {option.ticker.symbol}
                      </Typography>
                      <Typography variant="caption" fontWeight={700} sx={{ color: changeColor, fontFamily: 'monospace' }}>
                        {formatPrice(option.ticker.tradePrice)}
                      </Typography>
                    </Box>
                  </Box>

                  {/* 보유탭: 드롭다운 내 추가/제거 버튼 */}
                  {currentTab === 'holdings' && (
                    <IconButton
                      size="small"
                      onMouseDown={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        handleToggleHolding(e, option.ticker);
                      }}
                      sx={{
                        flexShrink: 0,
                        color: alreadyHolding ? '#ef5350' : '#26a69a',
                        p: 0.5,
                        '&:hover': { bgcolor: 'action.hover' },
                      }}
                    >
                      {alreadyHolding
                        ? <RemoveCircleOutlineIcon sx={{ fontSize: 18 }} />
                        : <AddCircleIcon sx={{ fontSize: 18 }} />}
                    </IconButton>
                  )}

                  {/* 관심탭: 드롭다운 내 즐겨찾기 토글 버튼 */}
                  {currentTab === 'favorites' && (
                    <IconButton
                      size="small"
                      onMouseDown={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        handleToggleFavorite(e, option.ticker);
                      }}
                      sx={{
                        flexShrink: 0,
                        color: alreadyFavorite ? 'warning.main' : 'text.secondary',
                        opacity: alreadyFavorite ? 1 : 0.4,
                        p: 0.5,
                        transition: 'opacity 0.2s, color 0.2s',
                        '&:hover': { bgcolor: 'action.hover', opacity: 1 },
                      }}
                    >
                      {alreadyFavorite
                        ? <StarIcon sx={{ fontSize: 18 }} />
                        : <StarBorderIcon sx={{ fontSize: 18 }} />}
                    </IconButton>
                  )}
                </Box>
              </li>
            );
          }}
          noOptionsText="검색 결과가 없습니다"
        />
      </Box>

      {/* 정렬 헤더 */}
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          px: 1,
          py: 0.75,
          borderBottom: 1,
          borderColor: 'divider',
          backgroundColor: 'action.hover',
          gap: 0.5,
        }}
      >
        {/* 별 + 변동 아이콘 공간 */}
        <Box sx={{ width: 34, flexShrink: 0 }} />

        {/* 한글명 */}
        <Box sx={{ flex: '1 1 0' }}>
          <TableSortLabel
            active={sortField === 'koreanName'}
            direction={sortField === 'koreanName' ? sortOrder : 'asc'}
            onClick={() => handleSortChange('koreanName')}
            sx={{ '& .MuiTableSortLabel-icon': { fontSize: '0.9rem' } }}
          >
            <Typography variant="caption" fontWeight={700} color="text.secondary" sx={{ fontSize: '0.72rem' }}>
              한글명
            </Typography>
          </TableSortLabel>
        </Box>

        {/* 현재가 */}
        <Box sx={{ width: 90, flexShrink: 0, textAlign: 'right', overflow: 'hidden' }}>
          <TableSortLabel
            active={sortField === 'tradePrice'}
            direction={sortField === 'tradePrice' ? sortOrder : 'desc'}
            onClick={() => handleSortChange('tradePrice')}
            sx={{ '& .MuiTableSortLabel-icon': { fontSize: '0.9rem' }, justifyContent: 'flex-end', maxWidth: '100%' }}
          >
            <Typography variant="caption" fontWeight={700} color="text.secondary"
              sx={{ fontSize: '0.72rem', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}
            >
              {currentTab === 'btc' ? '현재가(USD)' : '현재가'}
            </Typography>
          </TableSortLabel>
        </Box>

        {/* 전일대비 */}
        <Box sx={{ width: 68, textAlign: 'right', flexShrink: 0 }}>
          <TableSortLabel
            active={sortField === 'changeRate'}
            direction={sortField === 'changeRate' ? sortOrder : 'desc'}
            onClick={() => handleSortChange('changeRate')}
            sx={{ '& .MuiTableSortLabel-icon': { fontSize: '0.9rem' }, justifyContent: 'flex-end' }}
          >
            <Typography variant="caption" fontWeight={700} color="text.secondary" sx={{ fontSize: '0.72rem' }}>
              전일대비
            </Typography>
          </TableSortLabel>
        </Box>
      </Box>

      {/* 종목 목록 — overflowY:scroll로 스크롤바 공간을 항상 점유 */}
      <List
        sx={{
          flex: 1,
          overflowY: 'scroll',
          overflowX: 'hidden',
          p: 0,
          '&::-webkit-scrollbar': {
            width: '8px',
          },
          '&::-webkit-scrollbar-track': {
            backgroundColor: 'background.default',
          },
          '&::-webkit-scrollbar-thumb': {
            backgroundColor: 'divider',
            borderRadius: '4px',
          },
        }}
      >
        {currentTab === 'holdings' ? (
          // 보유 탭: DB 보유 종목만 표시
          holdings.size === 0 ? (
            <Box sx={{ p: 3, textAlign: 'center' }}>
              <Typography variant="body2" color="text.secondary" sx={{ lineHeight: 1.8 }}>
                보유 종목이 없습니다.{'\n'}
                <Box component="span" sx={{ fontSize: '0.75rem', opacity: 0.7 }}>
                  위 검색창에서 종목 검색 후 + 버튼으로 추가하세요.
                </Box>
              </Typography>
            </Box>
          ) : (
            sortedTickers
              .filter(t => holdings.has(t.code))
              .map(ticker => (
                <TickerItem
                  key={ticker.code}
                  ticker={ticker}
                  isSelected={ticker.code === selectedMarket}
                  isFavorite={favorites.has(ticker.code)}
                  onSelect={() => { setSelectedTicker(ticker); onSelectMarket(ticker.code); }}
                  onToggleFavorite={(e) => handleToggleFavorite(e, ticker)}
                  iconMode="holding"
                  isHolding={true}
                  onToggleHolding={(e) => handleToggleHolding(e, ticker)}
                />
              ))
          )
        ) : sortedTickers.length === 0 ? (
          <Box sx={{ p: 3, textAlign: 'center' }}>
            <Typography variant="body2" color="text.secondary">
              {currentTab === 'favorites'
                ? '즐겨찾기한 종목이 없습니다.\n별 아이콘을 눌러 추가하세요.'
                : '데이터 로딩 중...'}
            </Typography>
          </Box>
        ) : (
          sortedTickers.map(ticker => (
            <TickerItem
              key={ticker.code}
              ticker={ticker}
              isSelected={ticker.code === selectedMarket}
              isFavorite={favorites.has(ticker.code)}
              onSelect={() => {
                setSelectedTicker(ticker);
                onSelectMarket(ticker.code);
              }}
              onToggleFavorite={(e) => handleToggleFavorite(e, ticker)}
              priceUnit={currentTab === 'btc' ? 'usd' : 'krw'}
              usdtKrwRate={usdtKrwRate}
            />
          ))
        )}
      </List>
    </Paper>
  );
});

MarketList.displayName = 'MarketList';

export default MarketList;
