import React, { useState } from 'react';

interface WatchListProps {
  watchlist: string[];
  currentSymbol: string;
  onSelect: (symbol: string) => void;
  onAdd: (symbol: string) => void;
  onRemove: (symbol: string) => void;
  onClose: () => void;
  priceMap: Record<string, { price: number; changePct: number }>;
}

const WatchList: React.FC<WatchListProps> = ({
  watchlist, currentSymbol, onSelect, onAdd, onRemove, onClose, priceMap,
}) => {
  const [input, setInput] = useState('');

  const handleAdd = () => {
    const sym = input.trim().toUpperCase();
    if (sym && !watchlist.includes(sym)) {
      onAdd(sym);
      setInput('');
    }
  };

  return (
    <div className="watchlist-panel">
      <div className="watchlist-header">
        <span className="watchlist-title">⭐ 관심 종목</span>
        <button className="watchlist-close" onClick={onClose}>✕</button>
      </div>
      <div className="watchlist-add">
        <input
          className="watchlist-input"
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && handleAdd()}
          placeholder="심볼 추가..."
        />
        <button className="watchlist-add-btn" onClick={handleAdd}>+</button>
      </div>
      <div className="watchlist-body">
        {watchlist.map(sym => {
          const info = priceMap[sym];
          const pct = info?.changePct ?? 0;
          const isActive = sym === currentSymbol;
          return (
            <div
              key={sym}
              className={`watchlist-item ${isActive ? 'active' : ''}`}
              onClick={() => onSelect(sym)}
            >
              <span className="watchlist-sym">{sym}</span>
              <div className="watchlist-right">
                {info && (
                  <>
                    <span className="watchlist-price">{info.price.toFixed(2)}</span>
                    <span className={`watchlist-change ${pct >= 0 ? 'up' : 'down'}`}>
                      {pct >= 0 ? '+' : ''}{pct.toFixed(2)}%
                    </span>
                  </>
                )}
                <button
                  className="watchlist-remove"
                  onClick={e => { e.stopPropagation(); onRemove(sym); }}
                >✕</button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default WatchList;
