
import React, { useState, useEffect, useMemo } from 'react';
import { X, RotateCcw, ChevronDown, Zap, Plus, Minus, Calendar, ToggleLeft, ToggleRight, CheckSquare, Square, TrendingUp, TrendingDown, Wallet, Target, ShieldAlert, BadgePercent, Save, PlayCircle, Info, BarChart3, Maximize2, Circle, CheckCircle2 } from 'lucide-react';
import { StockItem, OrderType, MarketType, ReservedOrder, TradeOrder } from '../types';
import { DbService, HoldingItem } from '../services/dbService';

interface TradeModalProps {
  stock: StockItem;
  type: OrderType;
  onClose: () => void;
  onExecute: (order: Omit<ReservedOrder, 'id' | 'status' | 'createdAt'>) => Promise<void>;
  onImmediateOrder?: (order: Omit<TradeOrder, 'id' | 'timestamp' | 'status'>) => Promise<void>;
}

type StrategyType = 'NONE' | 'PROFIT' | 'LOSS' | 'TRAILING_STOP';

const TradeModal: React.FC<TradeModalProps> = ({ stock, type: initialType, onClose, onExecute, onImmediateOrder }) => {
  const [orderType, setOrderType] = useState<OrderType>(initialType);
  const isBuyMode = orderType === OrderType.BUY;

  const [holding, setHolding] = useState<HoldingItem | null>(null);
  const [buyingPower, setBuyingPower] = useState(0);
  const dbService = useMemo(() => new DbService(), []);

  useEffect(() => {
    const fetchData = async () => {
      const holdings = await dbService.getHoldings();
      const currentHolding = holdings.find(h => h.code === stock.code) || null;
      setHolding(currentHolding);
      
      const summary = await dbService.getAccountSummary();
      setBuyingPower(summary.buyingPower);
    };
    fetchData();
  }, [stock.code, dbService, orderType]);

  const plInfo = useMemo(() => {
    if (!holding) return null;
    const pl = (stock.price - holding.avgPrice) * holding.quantity;
    const percent = ((stock.price - holding.avgPrice) / holding.avgPrice) * 100;
    return { pl, percent };
  }, [holding, stock.price]);

  const [monitoringEnabled, setMonitoringEnabled] = useState(false);
  const [immediateStart, setImmediateStart] = useState(true);
  
  // 전략 선택 (라디오 버튼 방식)
  const [activeStrategy, setActiveStrategy] = useState<StrategyType>(isBuyMode ? 'TRAILING_STOP' : 'NONE');

  // TS 설정
  const [tsValue, setTsValue] = useState<number>(3);
  const [tsUnit, setTsUnit] = useState<'PERCENT' | 'TICK' | 'AMOUNT'>('PERCENT');

  // TS 내부 감시 시작 조건 (Trigger)
  const [triggerEnabled, setTriggerEnabled] = useState(false); 
  const [triggerType, setTriggerType] = useState<'CURRENT' | 'HIGH' | 'LOW' | 'VOLUME'>('CURRENT');
  const [triggerValue, setTriggerValue] = useState<number>(stock.price);
  const [monCondition, setMonCondition] = useState<'ABOVE' | 'BELOW'>(isBuyMode ? 'BELOW' : 'ABOVE');

  // 자동 조건 결정 로직
  const applyAutoCondition = (type: string, buyMode: boolean) => {
    if (!buyMode) {
      setMonCondition('ABOVE'); // 매도시에는 현재/고/저/거래량 모두 이상
    } else {
      // 매수시
      if (type === 'CURRENT' || type === 'HIGH') {
        setMonCondition('BELOW'); // 현재가, 고가는 이하
      } else {
        setMonCondition('ABOVE'); // 저가, 거래량은 이상
      }
    }
  };

  // 모드 변경 시 전략 및 조건 초기화
  useEffect(() => {
    if (isBuyMode) {
        setActiveStrategy('TRAILING_STOP');
    } else {
        setActiveStrategy('NONE');
    }
    applyAutoCondition(triggerType, isBuyMode);
    if (triggerType !== 'VOLUME') {
      setTriggerValue(stock.price);
    }
  }, [isBuyMode, stock.price]);

  const [monTargetUnit, setMonTargetUnit] = useState<'PRICE' | 'PERCENT' | 'AMOUNT'>('PRICE');
  const [profitValue, setProfitValue] = useState<number>(stock.price * 1.1);
  const [lossValue, setLossValue] = useState<number>(stock.price * 0.9);

  const [expiryDays, setExpiryDays] = useState<number>(1);
  const [customExpiryDate, setCustomExpiryDate] = useState<string>(
    new Date(Date.now() + 86400000).toISOString().split('T')[0]
  );

  const [priceMethod, setPriceMethod] = useState<'CURRENT' | 'MARKET' | 'HIGH' | 'LOW'>('CURRENT');
  const [tickOffset, setTickOffset] = useState<number>(0);
  const [quantityMode, setQuantityMode] = useState<'DIRECT' | 'RATIO'>('DIRECT');
  const [quantity, setQuantity] = useState<number>(1);
  const [quantityRatio, setQuantityRatio] = useState<number>(isBuyMode ? 10 : 100);

  const currencySymbol = stock.market === MarketType.DOMESTIC ? '원' : '$';

  const handleMaxQuantity = () => {
    if (quantityMode === 'RATIO') {
      setQuantityRatio(100);
    } else {
      if (isBuyMode) {
        const maxQty = Math.floor(buyingPower / stock.price);
        setQuantity(maxQty > 0 ? maxQty : 1);
      } else if (holding) {
        setQuantity(holding.quantity);
      }
    }
  };

  const handleReset = () => {
    setMonitoringEnabled(false);
    setImmediateStart(true);
    setActiveStrategy(isBuyMode ? 'TRAILING_STOP' : 'NONE');
    setTriggerEnabled(false);
    setTriggerType('CURRENT');
    setTriggerValue(stock.price);
    applyAutoCondition('CURRENT', isBuyMode);
    setPriceMethod('CURRENT');
    setTickOffset(0);
    setQuantity(1);
    setQuantityRatio(isBuyMode ? 10 : 100);
    setExpiryDays(1);
  };

  const finalQuantity = useMemo(() => {
    if (quantityMode === 'RATIO') {
      if (isBuyMode) {
        const targetBudget = buyingPower * (quantityRatio / 100);
        return Math.floor(targetBudget / stock.price) || 0;
      } else if (holding) {
        return Math.floor(holding.quantity * (quantityRatio / 100));
      }
    }
    return quantity;
  }, [isBuyMode, quantityMode, quantity, quantityRatio, holding, buyingPower, stock.price]);

  const handleExecute = () => {
    if (monitoringEnabled) {
      let finalExpiry = new Date();
      if (expiryDays > 0) finalExpiry.setDate(finalExpiry.getDate() + expiryDays);
      else finalExpiry = new Date(customExpiryDate);

      onExecute({
        stockCode: stock.code,
        stockName: stock.name,
        type: orderType,
        quantity: finalQuantity,
        monitoringType: activeStrategy === 'TRAILING_STOP' ? 'TRAILING_STOP' : 'PRICE_TRIGGER',
        triggerPrice: triggerEnabled ? triggerValue : stock.price,
        trailingType: tsUnit === 'PERCENT' ? 'PERCENT' : 'AMOUNT',
        trailingValue: tsValue,
        market: stock.market,
        expiryDate: finalExpiry
      });
    } else {
      if (onImmediateOrder) {
        onImmediateOrder({
          stockCode: stock.code,
          stockName: stock.name,
          type: orderType,
          price: priceMethod === 'MARKET' ? 0 : stock.price,
          quantity: finalQuantity
        });
      }
    }
    onClose();
  };

  const StrategyRadio = ({ type, label, icon: Icon }: { type: StrategyType, label: string, icon: any }) => {
    const isSelected = activeStrategy === type;
    return (
      <div 
        onClick={() => setActiveStrategy(type)}
        className={`p-4 rounded-2xl border-2 transition-all cursor-pointer flex items-center justify-between ${isSelected ? 'bg-amber-50/40 border-amber-300 shadow-sm' : 'bg-transparent border-slate-100 opacity-60'}`}
      >
        <div className="flex items-center gap-3">
          {isSelected ? <CheckCircle2 className="text-amber-600" size={18} /> : <Circle className="text-slate-300" size={18} />}
          <Icon className={isSelected ? 'text-amber-600' : 'text-slate-300'} size={18} />
          <span className="text-[13px] font-black text-slate-800 uppercase tracking-tight">{label}</span>
        </div>
        
        {isSelected && type === 'TRAILING_STOP' && (
          <div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
            <input type="number" className="w-16 p-2 bg-white rounded-xl text-center font-black text-[14px] border border-amber-200 shadow-inner outline-none" value={tsValue} onChange={(e) => setTsValue(Number(e.target.value))} />
            <select value={tsUnit} onChange={(e) => setTsUnit(e.target.value as any)} className="bg-transparent font-black text-[12px] text-amber-600 outline-none">
              <option value="PERCENT">%</option>
              <option value="TICK">틱</option>
              <option value="AMOUNT">{currencySymbol}</option>
            </select>
          </div>
        )}

        {isSelected && type === 'PROFIT' && (
          <div className="flex items-center gap-2" onClick={e => e.stopPropagation()}>
            <input type="number" className="w-20 p-2 bg-white rounded-xl text-center font-black text-[14px] border border-rose-200 shadow-inner outline-none" value={profitValue} onChange={e => setProfitValue(Number(e.target.value))} />
            <span className="text-[12px] font-black text-rose-500">{monTargetUnit === 'PERCENT' ? '%' : currencySymbol}</span>
          </div>
        )}

        {isSelected && type === 'LOSS' && (
          <div className="flex items-center gap-2" onClick={e => e.stopPropagation()}>
            <input type="number" className="w-20 p-2 bg-white rounded-xl text-center font-black text-[14px] border border-blue-200 shadow-inner outline-none" value={lossValue} onChange={e => setLossValue(Number(e.target.value))} />
            <span className="text-[12px] font-black text-blue-500">{monTargetUnit === 'PERCENT' ? '%' : currencySymbol}</span>
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="fixed inset-0 z-[300] bg-slate-900/60 backdrop-blur-md flex items-center justify-center p-4">
      <div className="bg-white w-full max-w-5xl rounded-3xl shadow-2xl animate-in zoom-in-95 duration-200 flex flex-col max-h-[90vh] overflow-hidden border border-slate-200">
        
        {/* 헤더 */}
        <div className="px-6 py-3 flex justify-between items-center bg-white border-b border-slate-100 shrink-0">
          <button onClick={handleReset} className="flex items-center gap-1.5 text-slate-400 hover:text-slate-600 transition-colors">
            <RotateCcw size={16} />
            <span className="text-[11px] font-black uppercase tracking-wider">전체 초기화</span>
          </button>
          
          <div className="flex bg-slate-100 p-1 rounded-xl border border-slate-200 shadow-inner">
             <button onClick={() => setOrderType(OrderType.BUY)} className={`px-10 py-1.5 rounded-lg text-[11px] font-black transition-all ${isBuyMode ? 'bg-rose-500 text-white shadow-md' : 'text-slate-400 hover:text-slate-600'}`}>매수설정</button>
             <button onClick={() => setOrderType(OrderType.SELL)} className={`px-10 py-1.5 rounded-lg text-[11px] font-black transition-all ${!isBuyMode ? 'bg-blue-600 text-white shadow-md' : 'text-slate-400 hover:text-slate-600'}`}>매도설정</button>
          </div>

          <button onClick={onClose} className="p-1.5 hover:bg-slate-100 rounded-full transition-colors text-slate-400"><X size={24} /></button>
        </div>

        <div className="flex-1 overflow-y-auto custom-scrollbar bg-slate-50/20">
          {/* 상단 통합 정보 */}
          <div className="px-8 py-6 bg-white border-b border-slate-100 grid grid-cols-1 lg:grid-cols-2 gap-6 items-center">
            <div className="flex items-center gap-6">
              <div className="w-16 h-16 bg-slate-900 rounded-2xl flex items-center justify-center text-white font-black italic text-[20px] shadow-lg">{stock.name[0]}</div>
              <div className="space-y-0.5">
                <h3 className="text-xl font-black text-slate-900 tracking-tighter flex items-center gap-1.5">{stock.name} <ChevronDown size={18} className="text-slate-200" /></h3>
                <div className="flex items-center gap-2.5 text-[11px] font-black uppercase text-slate-400">
                  <span className="bg-slate-100 px-2 py-0.5 rounded-md border border-slate-200 text-slate-600">{stock.market === MarketType.DOMESTIC ? 'KRX' : 'NYSE'}</span>
                  <span className="tracking-widest">{stock.code}</span>
                </div>
              </div>
              <div className="ml-4 border-l border-slate-100 pl-6 space-y-0.5 flex flex-col justify-center">
                <p className={`text-2xl font-black font-mono tracking-tighter leading-none ${stock.changePercent >= 0 ? 'text-rose-500' : 'text-blue-600'}`}>
                  {stock.market === MarketType.DOMESTIC ? stock.price.toLocaleString() : `$${stock.price}`}
                </p>
                <div className={`text-[12px] font-black flex items-center gap-1.5 ${stock.changePercent >= 0 ? 'text-rose-500' : 'text-blue-600'}`}>
                  {stock.changePercent >= 0 ? <TrendingUp size={14} /> : <TrendingDown size={14} />}
                  {Math.abs(stock.changePercent)}%
                </div>
              </div>
              <div className="ml-4 border-l border-slate-100 pl-6 flex flex-col justify-center gap-1">
                 <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest leading-none">거래량</p>
                 <p className="text-[14px] font-black font-mono text-slate-900 leading-none">{stock.volume.toLocaleString()}</p>
                 <div className="flex items-center gap-1 text-[10px] font-black text-rose-500">
                    <TrendingUp size={10} /> +5.2%
                 </div>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4 bg-slate-50 p-4 rounded-2xl border border-slate-100 shadow-sm">
               <div className="space-y-0.5 pr-4 border-r border-slate-200">
                  <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1.5"><Wallet size={12} className="text-blue-500" /> 사용가능 예수금</p>
                  <p className="text-[14px] font-black font-mono text-slate-900">{buyingPower.toLocaleString()}{currencySymbol}</p>
               </div>
               {holding ? (
                 <div className="flex flex-col gap-1.5">
                   <div className="flex justify-between items-center">
                      <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest">보유수량</p>
                      <p className="text-[12px] font-black font-mono text-slate-900">{holding.quantity} <span className="text-[9px] text-slate-400">EA</span></p>
                   </div>
                   <div className="flex justify-between items-center">
                      <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest">평가수익금</p>
                      <p className={`text-[12px] font-black font-mono ${plInfo!.pl >= 0 ? 'text-rose-500' : 'text-blue-600'}`}>
                        {plInfo!.pl > 0 ? '+' : ''}{plInfo!.pl.toLocaleString()} <span className="text-[10px]">({plInfo!.percent.toFixed(2)}%)</span>
                      </p>
                   </div>
                 </div>
               ) : (
                 <div className="flex items-center justify-center opacity-20">
                    <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">미보유 종목</p>
                 </div>
               )}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-px bg-slate-200">
            <div className={`bg-white p-8 space-y-6 transition-all duration-300 ${!monitoringEnabled ? 'opacity-40 grayscale-[0.5]' : ''}`}>
              <div className="flex items-center justify-between">
                <h4 className="text-[14px] font-black text-slate-800 uppercase tracking-tight flex items-center gap-2">
                   <ShieldAlert size={18} className={monitoringEnabled ? 'text-rose-500' : 'text-slate-300'} />
                   1. 자동 감시 전략
                </h4>
                <button 
                  onClick={() => setMonitoringEnabled(!monitoringEnabled)}
                  className={`flex items-center gap-2 px-4 py-1.5 rounded-full text-[10px] font-black transition-all border shadow-sm ${monitoringEnabled ? 'bg-slate-900 border-slate-900 text-white' : 'bg-white border-slate-200 text-slate-400 hover:border-slate-300'}`}
                >
                  {monitoringEnabled ? <ToggleRight size={18} /> : <ToggleLeft size={18} />}
                  {monitoringEnabled ? '감시 중' : '비활성'}
                </button>
              </div>

              <div className="space-y-6">
                {!isBuyMode ? (
                  <div className="space-y-4">
                     <div className="flex items-center justify-between pl-1">
                        <label className="text-[11px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1.5">
                           <TrendingUp size={14} /> 스마트 수익/손실 관리
                        </label>
                        <div className="flex gap-1 bg-slate-100 p-0.5 rounded-lg border border-slate-200">
                           {['PRICE', 'PERCENT', 'AMOUNT'].map(unit => (
                             <button key={unit} onClick={() => setMonTargetUnit(unit as any)} className={`text-[9px] font-black px-2 py-1 rounded-md transition-all ${monTargetUnit === unit ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-400 hover:text-slate-600'}`}>
                               {unit === 'PRICE' ? '현재가' : unit === 'PERCENT' ? '수익률(%)' : '수익금액'}
                             </button>
                           ))}
                        </div>
                     </div>
                     
                     <div className="space-y-3">
                        <StrategyRadio type="PROFIT" label="이익실현 (TAKE PROFIT)" icon={Target} />
                        <StrategyRadio type="LOSS" label="손실제한 (STOP LOSS)" icon={ShieldAlert} />
                        <StrategyRadio type="TRAILING_STOP" label="반등 시 주문 (TRAILING STOP)" icon={PlayCircle} />
                     </div>
                  </div>
                ) : (
                  <div className="space-y-3">
                    <StrategyRadio type="TRAILING_STOP" label="반등 시 주문 (TRAILING STOP)" icon={PlayCircle} />
                  </div>
                )}
                
                {/* TS 내부 감시 시작 조건 설정 (TS 선택 시에만 표시) */}
                {activeStrategy === 'TRAILING_STOP' && (
                  <div className="mt-3 p-4 rounded-2xl border border-amber-100 bg-amber-50/20 space-y-3 animate-in slide-in-from-top-1">
                    <div className="flex items-center justify-between">
                      <div 
                        onClick={() => setTriggerEnabled(!triggerEnabled)}
                        className="flex items-center gap-2 cursor-pointer group"
                      >
                        {triggerEnabled ? <CheckSquare size={16} className="text-amber-600" /> : <Square size={16} className="text-slate-300" />}
                        <span className="text-[11px] font-black text-amber-700/80 uppercase tracking-widest">목표가 설정</span>
                      </div>
                    </div>

                    {triggerEnabled && (
                      <div className="flex items-center gap-1.5 bg-white/70 p-2 rounded-xl border border-amber-100 shadow-sm overflow-hidden">
                        <select 
                          value={triggerType} 
                          onChange={(e) => {
                            const newType = e.target.value as any;
                            setTriggerType(newType);
                            applyAutoCondition(newType, isBuyMode);
                            if (newType === 'VOLUME') {
                              setTriggerValue(100000);
                            } else {
                              setTriggerValue(stock.price);
                            }
                          }} 
                          className="bg-white p-2 rounded-lg font-black text-[10px] outline-none text-slate-700 w-32 border border-slate-100 shadow-sm shrink-0"
                        >
                          <option value="CURRENT">현재가(\)</option>
                          <option value="HIGH">고가(\)</option>
                          <option value="LOW">저가(\)</option>
                          <option value="VOLUME">거래량(주)</option>
                        </select>
                        <input 
                          type="number" 
                          className="flex-1 min-w-0 p-2 rounded-lg font-black text-[14px] text-center outline-none bg-white border border-slate-100 focus:border-amber-300 transition-all shadow-sm" 
                          value={triggerValue} 
                          onChange={(e) => setTriggerValue(Number(e.target.value))} 
                        />
                        <select 
                          value={monCondition}
                          onChange={(e) => setMonCondition(e.target.value as any)}
                          className={`p-2 rounded-lg font-black text-[10px] outline-none border border-slate-100 shadow-sm w-16 shrink-0 transition-colors ${monCondition === 'ABOVE' ? 'bg-blue-50 text-blue-600' : 'bg-rose-50 text-rose-500'}`}
                        >
                          <option value="ABOVE">이상</option>
                          <option value="BELOW">이하</option>
                        </select>
                      </div>
                    )}
                    
                    {!triggerEnabled && (
                      <p className="text-[10px] font-bold text-amber-600/60 pl-1 italic">※ 조건 미설정 시 현재 시점부터 즉시 반등 감시를 시작합니다.</p>
                    )}
                  </div>
                )}

                <div className="flex items-center gap-4 pt-4 border-t border-slate-100">
                  <span className="text-[11px] font-black text-slate-400 uppercase tracking-widest whitespace-nowrap">유효기간</span>
                  <div className="flex flex-1 gap-2">
                    {[1, 5, 30].map(d => (
                      <button key={d} onClick={() => setExpiryDays(d)} className={`flex-1 py-2 rounded-xl text-[11px] font-black transition-all ${expiryDays === d ? 'bg-slate-900 text-white shadow-md' : 'bg-slate-100 border border-slate-200 text-slate-400 hover:border-slate-300'}`}>
                        {d}일
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className="bg-white p-8 space-y-6">
              <h4 className="text-[14px] font-black text-slate-800 uppercase tracking-tight flex items-center gap-2">
                 <Zap size={18} className="text-blue-500" />
                 2. 매매 실행 조건
              </h4>
              
              <div className="space-y-8">
                <div className="space-y-3">
                  <label className="text-[11px] font-black text-slate-400 uppercase tracking-widest pl-1">주문 가격 유형</label>
                  <div className="grid grid-cols-4 gap-2 bg-slate-50 p-1 rounded-2xl border border-slate-100">
                    {['CURRENT', 'MARKET', 'HIGH', 'LOW'].map((method) => (
                      <button key={method} onClick={() => { setPriceMethod(method as any); if (method === 'MARKET') setTickOffset(0); }} className={`py-2 rounded-xl text-[11px] font-black transition-all border ${priceMethod === method ? 'bg-white text-slate-900 border-slate-200 shadow-md' : 'bg-transparent text-slate-400 border-transparent hover:text-slate-600'}`}>
                        {method === 'CURRENT' ? '현재' : method === 'MARKET' ? '시장' : method === 'HIGH' ? '고가' : '저가'}
                      </button>
                    ))}
                  </div>
                </div>

                <div className="space-y-6">
                  <div className="space-y-3">
                    <label className="text-[11px] font-black text-slate-400 uppercase tracking-widest pl-1">가격 조정 (틱)</label>
                    <div className="flex items-center gap-4 bg-slate-50 p-1.5 rounded-2xl border border-slate-100">
                      <button disabled={priceMethod === 'MARKET'} onClick={() => setTickOffset(prev => prev - 1)} className="p-2.5 bg-white rounded-xl text-slate-400 hover:text-blue-500 disabled:opacity-20 shadow-sm transition-all"><Minus size={18} /></button>
                      <div className="flex-1 text-center font-black font-mono text-[18px] text-slate-800">{tickOffset > 0 ? `+${tickOffset}` : tickOffset}</div>
                      <button disabled={priceMethod === 'MARKET'} onClick={() => setTickOffset(prev => prev + 1)} className="p-2.5 bg-white rounded-xl text-slate-400 hover:text-blue-500 disabled:opacity-20 shadow-sm transition-all"><Plus size={18} /></button>
                    </div>
                  </div>

                  <div className="space-y-3">
                    <div className="flex items-center justify-between pl-1">
                       <label className="text-[11px] font-black text-slate-400 uppercase tracking-widest">주문 수량</label>
                       <span className="text-[9px] font-bold text-blue-500 bg-blue-50 px-2 py-0.5 rounded-full">
                          {isBuyMode ? `예수금` : `보유수량`}
                       </span>
                    </div>
                    <div className="bg-slate-50 p-3 rounded-2xl border border-slate-100 space-y-4">
                       <div className="flex items-center gap-1.5 bg-white/60 p-1 rounded-xl border border-slate-100 shadow-inner">
                          <button onClick={() => setQuantityMode('DIRECT')} className={`flex-1 py-2 rounded-lg text-[10px] font-black transition-all ${quantityMode === 'DIRECT' ? 'bg-white text-slate-900 shadow-sm border border-slate-200' : 'text-slate-400 hover:text-slate-600'}`}>직접입력</button>
                          <button onClick={() => setQuantityMode('RATIO')} className={`flex-1 py-2 rounded-lg text-[10px] font-black transition-all ${quantityMode === 'RATIO' ? 'bg-white text-slate-900 shadow-sm border border-slate-200' : 'text-slate-400 hover:text-slate-600'}`}>비중(%)</button>
                       </div>
                       <div className="flex items-center gap-3 px-2 pb-1 relative">
                          {quantityMode === 'DIRECT' ? (
                             <div className="flex items-center w-full gap-2 group">
                                <input type="number" min="1" className="flex-1 bg-transparent text-center font-black text-[24px] outline-none placeholder:text-slate-200 text-slate-900 min-w-0" placeholder="0" value={quantity} onChange={e => setQuantity(Math.max(1, parseInt(e.target.value) || 0))} />
                                <div className="flex flex-col items-center gap-1">
                                   <button onClick={handleMaxQuantity} className="px-3 py-1 bg-blue-600 text-white rounded-lg font-black text-[9px] uppercase tracking-tighter hover:bg-blue-700 transition-all shadow-md">MAX</button>
                                   <div className="px-2 py-1 bg-slate-900 text-white rounded-lg font-black text-[9px] uppercase tracking-wider shrink-0">EA / UNIT</div>
                                </div>
                             </div>
                          ) : (
                             <div className="flex items-center w-full gap-2">
                                <input type="number" min="0" max="100" className="flex-1 bg-transparent text-center font-black text-[24px] outline-none text-slate-900 min-w-0" value={quantityRatio} onChange={e => setQuantityRatio(Math.min(100, Math.max(0, parseInt(e.target.value) || 0)))} />
                                <div className="flex flex-col items-center gap-1">
                                   <button onClick={handleMaxQuantity} className="px-3 py-1 bg-blue-600 text-white rounded-lg font-black text-[9px] uppercase tracking-tighter hover:bg-blue-700 transition-all shadow-md">MAX</button>
                                   <div className={`px-2 py-1 text-white rounded-lg font-black text-[9px] uppercase tracking-wider flex items-center gap-1 shrink-0 ${isBuyMode ? 'bg-rose-500' : 'bg-blue-600'}`}>
                                      <BadgePercent size={12} /> PERCENT
                                   </div>
                                </div>
                             </div>
                          )}
                       </div>
                    </div>
                  </div>
                </div>

                <div className="p-4 bg-slate-900/5 rounded-2xl border border-slate-100 text-center">
                   <p className="text-[12px] font-black text-slate-600 leading-tight">
                     <span className={`${isBuyMode ? 'text-rose-500' : 'text-blue-600'}`}>{finalQuantity}주</span>를 {isBuyMode ? '매수' : '매도'}합니다.
                   </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 푸터 */}
        <div className="px-8 py-6 bg-white border-t border-slate-100 flex items-center justify-between shrink-0 gap-6">
          {monitoringEnabled && (
            <div className="flex items-center gap-3 bg-slate-50 px-4 py-2 rounded-2xl border border-slate-200 shadow-sm">
               <div className="flex flex-col">
                  <span className="text-[10px] font-black text-slate-800 uppercase tracking-tight leading-none">즉시 실행</span>
                  <span className="text-[8px] text-slate-400 font-bold leading-none mt-1">엔진 자동 가동</span>
               </div>
               <button 
                onClick={() => setImmediateStart(!immediateStart)}
                className={`relative inline-flex h-6 w-10 items-center rounded-full transition-all focus:outline-none shadow-inner ${immediateStart ? 'bg-emerald-500' : 'bg-slate-300'}`}
               >
                 <span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform shadow-md ${immediateStart ? 'translate-x-5' : 'translate-x-1'}`} />
               </button>
            </div>
          )}
          
          <button 
            onClick={handleExecute} 
            className={`flex-1 py-4 rounded-2xl font-black text-[16px] text-white shadow-xl transition-all active:scale-[0.98] flex items-center justify-center gap-3 ${monitoringEnabled ? (isBuyMode ? 'bg-rose-500' : 'bg-blue-600') : 'bg-slate-900 hover:bg-slate-800'}`}
          >
            {monitoringEnabled ? <><Save className="w-5 h-5" /> 전략 저장 및 {immediateStart ? '즉시 활성화' : '대기 저장'}</> : <><Zap size={22} fill="currentColor" /> {isBuyMode ? '매수' : '매도'} 주문 즉시 전송</>}
          </button>
        </div>
      </div>
    </div>
  );
};

export default TradeModal;
