'use client';

import { useState, useEffect } from 'react';
import { useTranslation, formatPriceWithCurrency } from '@/lib/i18n';
import { useExchangeRateStore } from '@/lib/exchangeRateStore';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import SidebarLayout from '@/components/SidebarLayout';
import { useAuthStore } from '@/lib/store';

// Cost constants
const DOMESTIC_COST_KRW = 1150000; // ₩1,150,000
const KOREAN_FEE_PERCENT = 5; // 5% of vehicle price
const MONGOLIAN_FEE_PERCENT = 5; // 5% of vehicle price
const CUSTOMS_FEE_USD = 200; // $200
// Exchange rate is now fetched dynamically from useExchangeRateStore

// Car type ratio: Small:Compact = 5.5:4.5 (total 10)
// For 4 cars (2 small + 2 compact): 2.75 + 2.75 + 2.25 + 2.25 = 10
const SMALL_CAR_RATIO = 2.75; // 27.5% of total
const COMPACT_CAR_RATIO = 2.25; // 22.5% of total

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

// Container matching simulation
interface ContainerSlot {
  id: number;
  type: 'small' | 'compact';
  status: 'empty' | 'waiting' | 'matched';
  buyerName?: string;
  cost: number;
  ratio: number;
}

interface Settings {
  container_logistics_usd: number;
  shoring_cost_usd: number;
}

export default function CostPage() {
  const { t, language } = useTranslation();
  const { user, isLoading } = useAuthStore();
  const router = useRouter();

  // If not logged in, show login prompt
  if (!isLoading && !user) {
    return (
      <SidebarLayout groupKey="billing">
        <div className="min-h-[60vh] flex items-center justify-center">
          <div className="bg-white rounded-lg shadow-lg p-8 max-w-md text-center">
            <div className="text-6xl mb-6">🔒</div>
            <h2 className="text-2xl font-bold text-gray-800 mb-4">
              {language === 'ko' ? '회원 전용 서비스' :
               language === 'mn' ? 'Зөвхөн гишүүдэд' :
               language === 'ru' ? 'Только для участников' :
               'Members Only'}
            </h2>
            <p className="text-gray-600 mb-6">
              {language === 'ko' ? '비용 계산 기능은 가입된 회원만 이용하실 수 있습니다.' :
               language === 'mn' ? 'Зардал тооцоо нь зөвхөн бүртгэлтэй гишүүдэд боломжтой.' :
               language === 'ru' ? 'Калькулятор стоимости доступен только зарегистрированным пользователям.' :
               'Cost calculator is available only to registered members.'}
            </p>
            <div className="space-y-3">
              <Link
                href="/register"
                className="block w-full bg-primary-600 text-white py-3 px-6 rounded-lg font-medium hover:bg-primary-700 transition"
              >
                {language === 'ko' ? '회원가입' :
                 language === 'mn' ? 'Бүртгүүлэх' :
                 language === 'ru' ? 'Регистрация' :
                 'Sign Up'}
              </Link>
              <Link
                href="/login"
                className="block w-full bg-gray-100 text-gray-700 py-3 px-6 rounded-lg font-medium hover:bg-gray-200 transition"
              >
                {language === 'ko' ? '이미 계정이 있으신가요? 로그인' :
                 language === 'mn' ? 'Бүртгэлтэй юу? Нэвтрэх' :
                 language === 'ru' ? 'Уже есть аккаунт? Войти' :
                 'Already have an account? Login'}
              </Link>
            </div>
          </div>
        </div>
      </SidebarLayout>
    );
  }

  // Settings from API
  const [settings, setSettings] = useState<Settings>({
    container_logistics_usd: 3600,
    shoring_cost_usd: 300,
  });

  // Calculator state
  const [vehiclePrice, setVehiclePrice] = useState<string>('2000');
  const [carType, setCarType] = useState<'small' | 'compact'>('small');

  // Total container cost
  const totalContainerCost = settings.container_logistics_usd + settings.shoring_cost_usd;

  // Calculate shipping costs based on ratio
  const smallCarCost = Math.round(totalContainerCost * (SMALL_CAR_RATIO / 10));
  const compactCarCost = Math.round(totalContainerCost * (COMPACT_CAR_RATIO / 10));

  // Container matching demo state
  const [containerSlots, setContainerSlots] = useState<ContainerSlot[]>([
    { id: 1, type: 'small', status: 'empty', cost: 0, ratio: SMALL_CAR_RATIO },
    { id: 2, type: 'small', status: 'empty', cost: 0, ratio: SMALL_CAR_RATIO },
    { id: 3, type: 'compact', status: 'empty', cost: 0, ratio: COMPACT_CAR_RATIO },
    { id: 4, type: 'compact', status: 'empty', cost: 0, ratio: COMPACT_CAR_RATIO },
  ]);

  // Fetch settings from API
  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const response = await fetch(`${API_BASE_URL}/api/settings/`);
        if (response.ok) {
          const data = await response.json();
          setSettings({
            container_logistics_usd: data.container_logistics_usd || 3600,
            shoring_cost_usd: data.shoring_cost_usd || 300,
          });
        }
      } catch (error) {
        console.error('Failed to fetch settings:', error);
      }
    };
    fetchSettings();
  }, []);

  // Calculate cost for a single slot based on current matched slots
  const calculateSlotCosts = (slots: ContainerSlot[]): ContainerSlot[] => {
    const filledSlots = slots.filter(s => s.status !== 'empty');
    if (filledSlots.length === 0) return slots;

    const totalRatio = filledSlots.reduce((sum, s) => sum + s.ratio, 0);

    return slots.map(slot => {
      if (slot.status === 'empty') {
        return { ...slot, cost: 0 };
      }
      // Distribute cost proportionally based on ratio
      const cost = Math.round(totalContainerCost * (slot.ratio / totalRatio));
      return { ...slot, cost };
    });
  };

  // Add a buyer to a specific slot
  const addBuyerToSlot = (slotIndex: number) => {
    const buyerNames = language === 'ko'
      ? ['김철수', '이영희', '박민수', '최지연']
      : ['Kim', 'Lee', 'Park', 'Choi'];

    setContainerSlots(prev => {
      const newSlots = [...prev];
      const filledCount = newSlots.filter(s => s.status !== 'empty').length;

      if (newSlots[slotIndex].status === 'empty') {
        newSlots[slotIndex] = {
          ...newSlots[slotIndex],
          status: filledCount === 3 ? 'matched' : 'waiting',
          buyerName: buyerNames[filledCount],
        };

        // If this is the 4th car, mark all as matched
        if (filledCount === 3) {
          return calculateSlotCosts(newSlots.map(s =>
            s.status === 'waiting' ? { ...s, status: 'matched' as const } : s
          ));
        }

        return calculateSlotCosts(newSlots);
      }
      return prev;
    });
  };

  // Toggle slot car type
  const toggleSlotType = (slotIndex: number) => {
    setContainerSlots(prev => {
      const newSlots = [...prev];
      if (newSlots[slotIndex].status === 'empty') {
        const newType = newSlots[slotIndex].type === 'small' ? 'compact' : 'small';
        newSlots[slotIndex] = {
          ...newSlots[slotIndex],
          type: newType,
          ratio: newType === 'small' ? SMALL_CAR_RATIO : COMPACT_CAR_RATIO,
        };
      }
      return calculateSlotCosts(newSlots);
    });
  };

  // Reset container
  const resetContainer = () => {
    setContainerSlots([
      { id: 1, type: 'small', status: 'empty', cost: 0, ratio: SMALL_CAR_RATIO },
      { id: 2, type: 'small', status: 'empty', cost: 0, ratio: SMALL_CAR_RATIO },
      { id: 3, type: 'compact', status: 'empty', cost: 0, ratio: COMPACT_CAR_RATIO },
      { id: 4, type: 'compact', status: 'empty', cost: 0, ratio: COMPACT_CAR_RATIO },
    ]);
  };

  // Calculate costs
  const calculateCosts = () => {
    const priceKrw = parseInt(vehiclePrice) * 10000; // 만원 to 원
    if (isNaN(priceKrw) || priceKrw <= 0) {
      return null;
    }

    // Get dynamic USD to KRW rate from store
    const usdToKrw = useExchangeRateStore.getState().rates.USD?.rate || 1483;

    // Korean domestic cost
    const domesticCost = DOMESTIC_COST_KRW;

    // Korean fee (5% of vehicle price)
    const koreanFee = priceKrw * (KOREAN_FEE_PERCENT / 100);

    // Mongolian fee (5% of vehicle price)
    const mongolianFee = priceKrw * (MONGOLIAN_FEE_PERCENT / 100);

    // Shipping cost (USD) based on ratio
    const shippingCostUsd = carType === 'small' ? smallCarCost : compactCarCost;
    const shippingCostKrw = shippingCostUsd * usdToKrw;

    // Customs fee
    const customsFeeKrw = CUSTOMS_FEE_USD * usdToKrw;

    // Total cost
    const totalCost = priceKrw + domesticCost + koreanFee + mongolianFee + shippingCostKrw + customsFeeKrw;

    return {
      vehiclePrice: priceKrw,
      domesticCost,
      koreanFee,
      mongolianFee,
      shippingCostUsd,
      shippingCostKrw,
      customsFeeUsd: CUSTOMS_FEE_USD,
      customsFeeKrw,
      totalCost,
    };
  };

  const costs = calculateCosts();

  // Get exchange rates
  const rates = useExchangeRateStore.getState().rates;
  const usdRate = rates.USD?.rate || 1483;
  const mntRate = rates.MNT?.rate || 0.43;
  const rubRate = rates.RUB?.rate || 14.5;

  // Format currency based on language
  const formatKRW = (amount: number) => {
    return `₩${amount.toLocaleString()}`;
  };

  const formatUSD = (amount: number) => {
    return `$${amount.toLocaleString()}`;
  };

  // Format local currency based on language (MNT for Mongolian, RUB for Russian, KRW for others)
  const formatLocalCurrency = (krwAmount: number) => {
    if (language === 'mn') {
      // Convert KRW to MNT
      const mnt = Math.round(krwAmount / mntRate);
      return `${mnt.toLocaleString()} MNT`;
    } else if (language === 'ru') {
      // Convert KRW to RUB
      const rub = Math.round(krwAmount / rubRate);
      return `${rub.toLocaleString()} RUB`;
    } else {
      return formatKRW(krwAmount);
    }
  };

  // Format USD to local currency
  const formatUSDToLocal = (usdAmount: number) => {
    const krwAmount = usdAmount * usdRate;
    if (language === 'mn') {
      const mnt = Math.round(krwAmount / mntRate);
      return `${mnt.toLocaleString()} MNT`;
    } else if (language === 'ru') {
      const rub = Math.round(krwAmount / rubRate);
      return `${rub.toLocaleString()} RUB`;
    } else {
      return formatKRW(krwAmount);
    }
  };

  const formatToUSD = (krwAmount: number) => {
    const usd = krwAmount / usdRate;
    return `${usd.toLocaleString('en-US', { maximumFractionDigits: 0 })} USD`;
  };

  // Format total in local currency
  const formatTotalLocal = (krwAmount: number) => {
    if (language === 'mn') {
      const mnt = Math.round(krwAmount / mntRate);
      return `${mnt.toLocaleString()} MNT`;
    } else if (language === 'ru') {
      const rub = Math.round(krwAmount / rubRate);
      return `${rub.toLocaleString()} RUB`;
    } else {
      return formatKRW(krwAmount);
    }
  };

  // Get matched count
  const matchedCount = containerSlots.filter(s => s.status !== 'empty').length;
  const currentContainerCost = containerSlots.reduce((sum, s) => sum + s.cost, 0);

  return (
    <SidebarLayout groupKey="billing">
      {/* Hero Section */}
      <div className="bg-gradient-to-r from-primary-700 to-primary-900 text-white rounded-lg -mx-6 -mt-6 mb-6">
        <div className="container mx-auto px-4 py-16">
          <div className="max-w-4xl mx-auto text-center">
            <h1 className="text-4xl md:text-5xl font-bold mb-4">{t.costTitle}</h1>
            <p className="text-xl text-primary-100">{t.costSubtitle}</p>
          </div>
        </div>
      </div>

      {/* Cost Structure */}
      <div className="bg-white py-12">
        <div className="container mx-auto px-4">
          <div className="max-w-4xl mx-auto">
            <h2 className="text-2xl font-bold text-gray-800 text-center mb-8">{t.costTitle}</h2>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              {/* Domestic Costs */}
              <div className="bg-gray-50 rounded-lg p-6">
                <h3 className="text-xl font-bold text-gray-800 mb-4 flex items-center">
                  <span className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center text-white text-sm mr-3">1</span>
                  {t.domesticCosts}
                </h3>
                <div className="space-y-3">
                  <div className="flex justify-between items-center py-2 border-b">
                    <span className="text-gray-600">{t.vehiclePrice}</span>
                    <span className="font-medium">{language === 'ko' ? '차량가격' : 'Vehicle Price'}</span>
                  </div>
                  <div className="flex justify-between items-center py-2 border-b">
                    <span className="text-gray-600">{t.koreanDomesticCost}</span>
                    <span className="font-medium text-primary-600">{formatLocalCurrency(DOMESTIC_COST_KRW)}</span>
                  </div>
                  <div className="flex justify-between items-center py-2 border-b">
                    <span className="text-gray-600">{t.koreanMargin}</span>
                    <span className="font-medium text-primary-600">{KOREAN_FEE_PERCENT}%</span>
                  </div>
                </div>
              </div>

              {/* International Logistics */}
              <div className="bg-gray-50 rounded-lg p-6">
                <h3 className="text-xl font-bold text-gray-800 mb-4 flex items-center">
                  <span className="w-8 h-8 bg-green-500 rounded-full flex items-center justify-center text-white text-sm mr-3">2</span>
                  {t.internationalLogistics}
                </h3>
                <div className="space-y-3">
                  <div className="flex justify-between items-center py-2 border-b">
                    <span className="text-gray-600">{t.shippingCost} ({t.smallCar})</span>
                    <span className="font-medium text-green-600">
                      {formatUSD(smallCarCost)} <span className="text-gray-400 text-sm">({formatUSDToLocal(smallCarCost)})</span>
                    </span>
                  </div>
                  <div className="flex justify-between items-center py-2 border-b">
                    <span className="text-gray-600">{t.shippingCost} ({t.compactCar})</span>
                    <span className="font-medium text-green-600">
                      {formatUSD(compactCarCost)} <span className="text-gray-400 text-sm">({formatUSDToLocal(compactCarCost)})</span>
                    </span>
                  </div>
                  <div className="flex justify-between items-center py-2 border-b">
                    <span className="text-gray-600">{t.customsFee}</span>
                    <span className="font-medium text-green-600">
                      {formatUSD(CUSTOMS_FEE_USD)} <span className="text-gray-400 text-sm">({formatUSDToLocal(CUSTOMS_FEE_USD)})</span>
                    </span>
                  </div>
                  <div className="flex justify-between items-center py-2 border-b">
                    <span className="text-gray-600">{t.mongolianMargin}</span>
                    <span className="font-medium text-green-600">{MONGOLIAN_FEE_PERCENT}%</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Container Matching System */}
      <div className="container mx-auto px-4 py-12">
        <div className="max-w-5xl mx-auto">
          <div className="bg-white rounded-lg shadow-lg p-6 md:p-8">
            <div className="text-center mb-8">
              <h2 className="text-2xl font-bold text-gray-800 mb-2">{t.containerMatching}</h2>
              <p className="text-gray-600">{t.containerMatchingDesc}</p>
            </div>

            {/* Container Info Banner */}
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
              <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div>
                  <p className="font-semibold text-blue-800">
                    {language === 'ko' ? '컨테이너 물류비 + 쇼링' : 'Container Logistics + Shoring'}: {formatUSD(totalContainerCost)}
                  </p>
                  <p className="text-blue-600 text-sm">
                    {language === 'ko'
                      ? `물류비 ${formatUSD(settings.container_logistics_usd)} + 쇼링(고정) ${formatUSD(settings.shoring_cost_usd)}`
                      : `Logistics ${formatUSD(settings.container_logistics_usd)} + Shoring ${formatUSD(settings.shoring_cost_usd)}`}
                  </p>
                </div>
                <div className="text-right">
                  <p className="text-sm text-blue-600">{t.smallCar} (5.5): {formatUSD(smallCarCost)} ({formatUSDToLocal(smallCarCost)})</p>
                  <p className="text-sm text-blue-600">{t.compactCar} (4.5): {formatUSD(compactCarCost)} ({formatUSDToLocal(compactCarCost)})</p>
                </div>
              </div>
            </div>

            {/* Container Visualization */}
            <div className="mb-6">
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-semibold text-gray-700">Container #A-2024-001</h3>
                <div className="flex items-center gap-4">
                  <span className="text-sm text-gray-500">
                    {matchedCount}/4 {t.matched} ({formatUSD(currentContainerCost)}/{formatUSD(totalContainerCost)})
                  </span>
                  <button
                    onClick={resetContainer}
                    className="text-sm text-primary-600 hover:text-primary-800"
                  >
                    {language === 'ko' ? '초기화' : 'Reset'}
                  </button>
                </div>
              </div>

              {/* Container Slots */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                {containerSlots.map((slot, index) => (
                  <div
                    key={slot.id}
                    className={`rounded-lg p-4 border-2 transition-all ${
                      slot.status === 'empty'
                        ? 'border-dashed border-gray-300 bg-gray-50 cursor-pointer hover:border-primary-400 hover:bg-primary-50'
                        : slot.status === 'waiting'
                        ? 'border-yellow-400 bg-yellow-50'
                        : 'border-green-400 bg-green-50'
                    }`}
                    onClick={() => slot.status === 'empty' && addBuyerToSlot(index)}
                  >
                    <div className="text-center">
                      {/* Car Icon - clickable to toggle type when empty */}
                      <div
                        className={`text-3xl mb-2 ${slot.status === 'empty' ? 'opacity-50 cursor-pointer' : ''}`}
                        onClick={(e) => {
                          e.stopPropagation();
                          if (slot.status === 'empty') toggleSlotType(index);
                        }}
                        title={slot.status === 'empty' ? (language === 'ko' ? '클릭하여 차종 변경' : 'Click to change type') : ''}
                      >
                        {slot.type === 'small' ? '🚗' : '🚙'}
                      </div>

                      {/* Slot Type */}
                      <p className={`text-sm font-medium ${slot.status === 'empty' ? 'text-gray-400' : 'text-gray-700'}`}>
                        {slot.type === 'small' ? t.smallCar : t.compactCar}
                      </p>
                      <p className="text-xs text-gray-400">
                        ({language === 'ko' ? '비율' : 'Ratio'}: {slot.ratio})
                      </p>

                      {/* Status */}
                      {slot.status === 'empty' ? (
                        <p className="text-xs text-primary-500 mt-2 font-medium">
                          {language === 'ko' ? '클릭하여 추가' : 'Click to add'}
                        </p>
                      ) : (
                        <>
                          <p className="text-sm font-medium text-gray-800 mt-1">{slot.buyerName}</p>
                          <p className={`text-xs mt-1 ${slot.status === 'waiting' ? 'text-yellow-600' : 'text-green-600'}`}>
                            {slot.status === 'waiting' ? t.waitingForMatch : t.matched}
                          </p>
                          <p className="text-sm font-bold text-primary-600 mt-1">
                            {formatUSD(slot.cost)}
                          </p>
                          <p className="text-xs text-gray-500">
                            ({formatUSDToLocal(slot.cost)})
                          </p>
                        </>
                      )}
                    </div>
                  </div>
                ))}
              </div>

              {/* Explanation - Cost Calculation Method */}
              <div className="mt-6 bg-gray-50 rounded-lg p-4">
                <h4 className="font-medium text-gray-700 mb-3">
                  {language === 'ko' ? '📊 물류비 산출 방식' : '📊 How Logistics Cost is Calculated'}
                </h4>
                <div className="text-sm text-gray-600 space-y-2">
                  <div className="bg-white rounded p-3 border">
                    <p className="font-medium text-gray-700 mb-2">
                      {language === 'ko' ? '1. 총 컨테이너 비용' : '1. Total Container Cost'}
                    </p>
                    <p className="text-gray-600">
                      {language === 'ko'
                        ? `컨테이너 물류비 (${formatUSD(settings.container_logistics_usd)}) + 쇼링비 (${formatUSD(settings.shoring_cost_usd)}) = ${formatUSD(totalContainerCost)}`
                        : `Container Logistics (${formatUSD(settings.container_logistics_usd)}) + Shoring (${formatUSD(settings.shoring_cost_usd)}) = ${formatUSD(totalContainerCost)}`}
                    </p>
                  </div>

                  <div className="bg-white rounded p-3 border">
                    <p className="font-medium text-gray-700 mb-2">
                      {language === 'ko' ? '2. 차종별 비율 (소형:경차 = 5.5:4.5)' : '2. Car Type Ratio (Small:Compact = 5.5:4.5)'}
                    </p>
                    <ul className="space-y-1 ml-4">
                      <li>• {language === 'ko' ? '소형차 1대' : 'Small car'}: 2.75 / 10 = 27.5% → {formatUSD(smallCarCost)} ({formatUSDToLocal(smallCarCost)})</li>
                      <li>• {language === 'ko' ? '경차 1대' : 'Compact car'}: 2.25 / 10 = 22.5% → {formatUSD(compactCarCost)} ({formatUSDToLocal(compactCarCost)})</li>
                    </ul>
                  </div>

                  <div className="bg-white rounded p-3 border">
                    <p className="font-medium text-gray-700 mb-2">
                      {language === 'ko' ? '3. 매칭 진행 방식' : '3. How Matching Works'}
                    </p>
                    <ul className="space-y-1 ml-4">
                      <li>• {language === 'ko'
                        ? '구매자가 컨테이너에 합류하면 현재 참여자 수에 따라 비용이 재분배됩니다.'
                        : 'When a buyer joins, costs are redistributed based on current participants.'}</li>
                      <li>• {language === 'ko'
                        ? '4명이 모두 합류하면 최종 비율대로 확정됩니다.'
                        : 'When all 4 join, final costs are set according to the ratio.'}</li>
                      <li>• {language === 'ko'
                        ? '위 슬롯을 클릭하여 시뮬레이션해 보세요!'
                        : 'Click on the slots above to simulate!'}</li>
                    </ul>
                  </div>

                  <div className="bg-primary-50 rounded p-3 border border-primary-200">
                    <p className="font-medium text-primary-700">
                      {language === 'ko' ? '💡 계산 예시 (소형 2대 + 경차 2대)' : '💡 Example (2 Small + 2 Compact)'}
                    </p>
                    <p className="text-primary-600 mt-1">
                      ({formatUSD(smallCarCost)} × 2) + ({formatUSD(compactCarCost)} × 2) = {formatUSD(smallCarCost * 2 + compactCarCost * 2)}
                    </p>
                    <p className="text-primary-500 text-sm mt-1">
                      = {formatUSDToLocal((smallCarCost + compactCarCost) * 2)}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Cost Calculator */}
      <div className="container mx-auto px-4 py-12">
        <div className="max-w-2xl mx-auto">
          <div className="bg-white rounded-lg shadow-lg p-8">
            <h2 className="text-2xl font-bold text-gray-800 text-center mb-8">{t.costCalculator}</h2>

            {/* Input Fields */}
            <div className="space-y-6">
              {/* Vehicle Price */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t.vehiclePrice} ({language === 'ko' ? '만원' : '10,000 KRW'})
                </label>
                <div className="relative">
                  <input
                    type="number"
                    value={vehiclePrice}
                    onChange={(e) => setVehiclePrice(e.target.value)}
                    className="w-full border border-gray-300 rounded-lg px-4 py-3 text-lg focus:ring-primary-500 focus:border-primary-500"
                    placeholder="2000"
                  />
                  <span className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-500">
                    {language === 'ko' ? '만원' : 'x 10,000 KRW'}
                  </span>
                </div>
                <p className="mt-1 text-sm text-gray-500">
                  = {formatLocalCurrency(parseInt(vehiclePrice || '0') * 10000)}
                </p>
              </div>

              {/* Car Type */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t.selectCarType}
                </label>
                <div className="grid grid-cols-2 gap-4">
                  <button
                    onClick={() => setCarType('small')}
                    className={`p-4 rounded-lg border-2 transition ${
                      carType === 'small'
                        ? 'border-primary-500 bg-primary-50 text-primary-700'
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                  >
                    <div className="text-2xl mb-1">🚗</div>
                    <div className="font-semibold">{t.smallCar}</div>
                    <div className="text-sm text-gray-500">{formatUSD(smallCarCost)}</div>
                    <div className="text-xs text-gray-400">({formatUSDToLocal(smallCarCost)})</div>
                  </button>
                  <button
                    onClick={() => setCarType('compact')}
                    className={`p-4 rounded-lg border-2 transition ${
                      carType === 'compact'
                        ? 'border-primary-500 bg-primary-50 text-primary-700'
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                  >
                    <div className="text-2xl mb-1">🚙</div>
                    <div className="font-semibold">{t.compactCar}</div>
                    <div className="text-sm text-gray-500">{formatUSD(compactCarCost)}</div>
                    <div className="text-xs text-gray-400">({formatUSDToLocal(compactCarCost)})</div>
                  </button>
                </div>
              </div>
            </div>

            {/* Results */}
            {costs && (
              <div className="mt-8 pt-8 border-t">
                <h3 className="text-lg font-semibold text-gray-800 mb-4">{t.totalCost}</h3>

                <div className="space-y-3">
                  <div className="flex justify-between items-center py-2">
                    <span className="text-gray-600">{t.vehiclePrice}</span>
                    <span className="font-medium">{formatLocalCurrency(costs.vehiclePrice)}</span>
                  </div>
                  <div className="flex justify-between items-center py-2">
                    <span className="text-gray-600">{t.koreanDomesticCost}</span>
                    <span className="font-medium">{formatLocalCurrency(costs.domesticCost)}</span>
                  </div>
                  <div className="flex justify-between items-center py-2">
                    <span className="text-gray-600">{t.koreanMargin}</span>
                    <span className="font-medium">{formatLocalCurrency(costs.koreanFee)}</span>
                  </div>
                  <div className="flex justify-between items-center py-2">
                    <span className="text-gray-600">{t.shippingCost} ({carType === 'small' ? t.smallCar : t.compactCar})</span>
                    <span className="font-medium">{formatUSD(costs.shippingCostUsd)} ({formatLocalCurrency(costs.shippingCostKrw)})</span>
                  </div>
                  <div className="flex justify-between items-center py-2">
                    <span className="text-gray-600">{t.customsFee}</span>
                    <span className="font-medium">{formatUSD(costs.customsFeeUsd)} ({formatLocalCurrency(costs.customsFeeKrw)})</span>
                  </div>
                  <div className="flex justify-between items-center py-2">
                    <span className="text-gray-600">{t.mongolianMargin}</span>
                    <span className="font-medium">{formatLocalCurrency(costs.mongolianFee)}</span>
                  </div>

                  <div className="flex justify-between items-center py-4 border-t-2 border-primary-200">
                    <span className="text-lg font-bold text-gray-800">{t.totalCost}</span>
                    <div className="text-right">
                      <div className="text-2xl font-bold text-primary-600">{formatToUSD(costs.totalCost)}</div>
                      <div className="text-gray-500">{formatTotalLocal(costs.totalCost)}</div>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* CTA Section */}
      <div className="bg-primary-600 text-white py-12 rounded-lg -mx-6 mb-0 mt-6">
        <div className="container mx-auto px-4 text-center">
          <h2 className="text-2xl font-bold mb-4">{t.readyToFindYourCar}</h2>
          <p className="text-primary-100 mb-8">{t.quoteWithin24Hours}</p>
          <Link
            href="/vehicle-request"
            className="inline-block bg-white text-primary-600 px-8 py-3 rounded-lg font-medium hover:bg-gray-100 transition"
          >
            {t.requestVehicle}
          </Link>
        </div>
      </div>
    </SidebarLayout>
  );
}
