'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Car } from '@/types';
import { carsApi, inquiriesApi, ccApi, heroBannersApi } from '@/lib/api';
import { useAuthStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';
import { useTranslate } from '@/lib/useTranslate';

// 이미지 URL 변환 (로컬 경로는 백엔드 URL 추가)
const getImageUrl = (url: string | undefined): string => {
  if (!url) return '';
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  // 로컬 경로인 경우 백엔드 URL 추가
  const backendPort = process.env.NEXT_PUBLIC_API_URL?.includes('8001') ? 8001 : 8000;
  return `http://localhost:${backendPort}${url}`;
};

export default function CarDetailPage() {
  const params = useParams();
  const router = useRouter();
  const { user, setUser } = useAuthStore();
  const { t, formatPrice, language } = useTranslation();
  const { translate, preloadCarTranslations } = useTranslate();
  const [car, setCar] = useState<Car | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedImage, setSelectedImage] = useState(0);
  const [inquiryMessage, setInquiryMessage] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [inquirySuccess, setInquirySuccess] = useState(false);

  // CC Access Control
  const [hasAccess, setHasAccess] = useState(false);
  const [ccBalance, setCcBalance] = useState(0);
  const [purchasing, setPurchasing] = useState(false);
  const [checkingAccess, setCheckingAccess] = useState(true);
  const [isBannerCar, setIsBannerCar] = useState<boolean | null>(null);  // Banner 샘플 차량 여부 (null = 체크 전)

  // Performance Check
  const [performanceCheck, setPerformanceCheck] = useState<any>(null);
  const [hasPerformanceCheckAccess, setHasPerformanceCheckAccess] = useState(false);
  const [purchasingPerformanceCheck, setPurchasingPerformanceCheck] = useState(false);
  const [showFullReport, setShowFullReport] = useState(false);
  const [pdfBlobUrl, setPdfBlobUrl] = useState<string | null>(null);
  const [loadingPdf, setLoadingPdf] = useState(false);

  // Collapsible sections
  const [showDealerComment, setShowDealerComment] = useState(false);

  useEffect(() => {
    if (params.id) {
      loadCar(Number(params.id));
    }
  }, [params.id]);

  useEffect(() => {
    if (car) {
      // 먼저 Banner 차량인지 확인 (비로그인 사용자도 확인 필요)
      checkBannerCar(car.id);
    }
  }, [car]);

  useEffect(() => {
    // isBannerCar가 null이면 아직 배너 체크 중이므로 대기
    if (isBannerCar === null) return;

    if (car && user) {
      if (isBannerCar) {
        // 배너 차량은 이미 접근 권한이 있으므로 CC 잔액만 로드
        loadCcBalance();
      } else {
        // 일반 차량은 접근 권한 확인 (CC 잔액도 함께 로드됨)
        checkViewAccess(car.id);
      }
    } else if (!user && !isBannerCar) {
      setCheckingAccess(false);
    }
  }, [car, user, isBannerCar]);

  // Load performance check data
  useEffect(() => {
    if (car) {
      loadPerformanceCheck(car.id);
    }
  }, [car]);

  const loadCar = async (id: number) => {
    try {
      const data = await carsApi.getById(id);
      setCar(data);
      preloadCarTranslations([data]);
    } catch (error) {
      console.error('Failed to load car:', error);
    } finally {
      setLoading(false);
    }
  };

  const checkBannerCar = async (carId: number) => {
    try {
      const result = await heroBannersApi.checkBannerCar(carId);
      if (result.is_banner_car) {
        // Banner 차량은 무료로 전체 공개
        setIsBannerCar(true);
        setHasAccess(true);
        setCheckingAccess(false);
      } else {
        // Banner 차량이 아니면 isBannerCar를 false로 명시적 설정
        setIsBannerCar(false);
      }
    } catch (error) {
      console.error('Failed to check banner car:', error);
      setIsBannerCar(false);
    }
  };

  const checkViewAccess = async (carId: number) => {
    try {
      const result = await ccApi.checkView(carId);
      setHasAccess(result.has_access);
      setCcBalance(result.cc_balance);
    } catch (error) {
      console.error('Failed to check access:', error);
      setHasAccess(false);
    } finally {
      setCheckingAccess(false);
    }
  };

  const loadCcBalance = async () => {
    try {
      const result = await ccApi.getBalance();
      setCcBalance(result.cc_balance);
    } catch (error) {
      console.error('Failed to load CC balance:', error);
    }
  };

  const loadPerformanceCheck = async (carId: number) => {
    try {
      const result = await ccApi.getPerformanceCheck(carId);
      setPerformanceCheck(result);
      setHasPerformanceCheckAccess(result.has_access);
    } catch (error) {
      console.error('Failed to load performance check:', error);
    }
  };

  const handlePurchasePerformanceCheck = async () => {
    if (!car || !user) {
      router.push('/login');
      return;
    }

    if (ccBalance < 0.1) {
      alert(t.insufficientCC);
      return;
    }

    setPurchasingPerformanceCheck(true);
    try {
      const result = await ccApi.purchasePerformanceCheck(car.id);
      setCcBalance(result.cc_balance);
      // Reload performance check data
      await loadPerformanceCheck(car.id);
      // Update user's CC balance in store
      if (user) {
        setUser({ ...user, cc_balance: result.cc_balance });
      }
      alert('Performance check access purchased!');
    } catch (error: any) {
      console.error('Failed to purchase performance check:', error);
      alert(error.response?.data?.detail || 'Purchase failed');
    } finally {
      setPurchasingPerformanceCheck(false);
    }
  };

  // PDF 로드 함수
  const loadPdf = async () => {
    if (!car || loadingPdf) return;

    setLoadingPdf(true);
    try {
      const blob = await ccApi.downloadPerformanceCheckPdf(car.id);
      const url = URL.createObjectURL(blob);
      setPdfBlobUrl(url);
      setShowFullReport(true);
    } catch (error: any) {
      console.error('Failed to load PDF:', error);
      alert(error.response?.data?.detail || 'Failed to load PDF');
    } finally {
      setLoadingPdf(false);
    }
  };

  // PDF 다운로드 함수
  const downloadPdf = async () => {
    if (!car) return;

    try {
      const blob = await ccApi.downloadPerformanceCheckPdf(car.id);
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `performance_check_${car.id}.pdf`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (error: any) {
      console.error('Failed to download PDF:', error);
      alert(error.response?.data?.detail || 'Failed to download PDF');
    }
  };

  // Cleanup PDF blob URL
  useEffect(() => {
    return () => {
      if (pdfBlobUrl) {
        URL.revokeObjectURL(pdfBlobUrl);
      }
    };
  }, [pdfBlobUrl]);

  const handlePurchaseView = async () => {
    if (!car || !user) {
      router.push('/login');
      return;
    }

    if (ccBalance < 1) {
      alert(t.insufficientCC);
      return;
    }

    setPurchasing(true);
    try {
      const result = await ccApi.purchaseView(car.id);
      setHasAccess(true);
      setCcBalance(result.cc_balance);
      // Update user's CC balance in store
      if (user) {
        setUser({ ...user, cc_balance: result.cc_balance });
      }
      alert(t.purchaseSuccess);
    } catch (error: any) {
      console.error('Failed to purchase view:', error);
      alert(error.response?.data?.detail || 'Purchase failed');
    } finally {
      setPurchasing(false);
    }
  };

  const handleInquiry = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!user) {
      router.push('/login');
      return;
    }
    if (!car || !inquiryMessage.trim()) return;

    setSubmitting(true);
    try {
      await inquiriesApi.create(car.id, inquiryMessage);
      setInquirySuccess(true);
      setInquiryMessage('');
    } catch (error) {
      console.error('Failed to submit inquiry:', error);
      alert('Failed to submit inquiry. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const formatMileage = (mileage?: number) => {
    if (!mileage) return '-';
    return new Intl.NumberFormat('en-US').format(mileage) + ' km';
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
      </div>
    );
  }

  if (!car) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-800 mb-4">{t.carNotFound}</h1>
          <button
            onClick={() => router.push('/cars')}
            className="text-primary-600 hover:underline"
          >
            {t.backToCars}
          </button>
        </div>
      </div>
    );
  }

  const allImages = car.images?.length > 0 ? car.images : [];
  // Standard total photos count is 20
  const STANDARD_PHOTO_COUNT = 20;
  // Banner 차량이거나 hasAccess면 모든 이미지 표시
  // isBannerCar가 null이면 아직 체크 중이므로 checkingAccess처럼 취급
  const isBannerCarConfirmed = isBannerCar === true;
  const showAllImages = isBannerCarConfirmed || hasAccess;
  const displayImages = showAllImages ? allImages : allImages.slice(0, 2);
  // 잠긴 이미지 수 - checkingAccess 중이거나 배너 체크 중이면 0으로 표시
  const lockedImagesCount = (showAllImages || checkingAccess || isBannerCar === null) ? 0 : Math.max(0, STANDARD_PHOTO_COUNT - displayImages.length);

  return (
    <div className="bg-gray-50 min-h-screen py-8">
      <div className="container mx-auto px-4">
        {/* Back Button */}
        <button
          onClick={() => router.back()}
          className="mb-6 text-primary-600 hover:text-primary-700 flex items-center"
        >
          <svg className="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
          {t.back}
        </button>

        {/* Promoted Vehicle Banner (for banner cars) */}
        {isBannerCarConfirmed && (
          <div className="bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-lg p-4 mb-6 flex items-center justify-between">
            <div className="flex items-center">
              <div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center mr-3">
                <span className="text-xl">🎁</span>
              </div>
              <div>
                <p className="text-lg font-bold">{t.promotedVehicle}</p>
                <p className="text-sm opacity-90">{t.promotedVehicleDesc}</p>
              </div>
            </div>
          </div>
        )}

        {/* CC Balance Banner (for logged in users, non-banner cars) */}
        {user && isBannerCar === false && (
          <div className="bg-gradient-to-r from-yellow-400 to-yellow-500 text-white rounded-lg p-4 mb-6 flex items-center justify-between">
            <div className="flex items-center">
              <div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center mr-3">
                <span className="text-xl font-bold">CC</span>
              </div>
              <div>
                <p className="text-sm opacity-90">{t.ccBalance}</p>
                <p className="text-2xl font-bold">{ccBalance} CC</p>
              </div>
            </div>
            {!hasAccess && (
              <div className="text-right">
                <p className="text-sm opacity-90">{t.freePhotos}</p>
                <p className="text-sm font-medium">{t.unlockFullDetails}</p>
              </div>
            )}
          </div>
        )}

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Images */}
          <div>
            {/* Main Image */}
            <div className="bg-gray-200 rounded-lg overflow-hidden h-96 mb-4 relative">
              {displayImages.length > 0 ? (
                <img
                  src={getImageUrl(displayImages[selectedImage]?.url)}
                  alt={car.car_name || 'Car'}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center text-gray-400">
                  No Image Available
                </div>
              )}

              {/* Locked overlay for non-purchased views */}
              {!hasAccess && lockedImagesCount > 0 && (
                <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4">
                  <p className="text-white text-center text-sm">
                    +{lockedImagesCount} {t.viewAllPhotos}
                  </p>
                </div>
              )}
            </div>

            {/* Thumbnails */}
            <div className="flex space-x-2 overflow-x-auto pb-2">
              {displayImages.map((img, index) => (
                <button
                  key={img.id}
                  onClick={() => setSelectedImage(index)}
                  className={`flex-shrink-0 w-20 h-20 rounded-md overflow-hidden border-2 ${
                    selectedImage === index ? 'border-primary-600' : 'border-transparent'
                  }`}
                >
                  <img
                    src={getImageUrl(img.url)}
                    alt=""
                    className="w-full h-full object-cover"
                  />
                </button>
              ))}

              {/* Locked images placeholder */}
              {!hasAccess && lockedImagesCount > 0 && (
                <div className="flex-shrink-0 w-20 h-20 rounded-md overflow-hidden border-2 border-dashed border-gray-300 bg-gray-100 flex items-center justify-center">
                  <div className="text-center">
                    <svg className="w-6 h-6 text-gray-400 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                    </svg>
                    <span className="text-xs text-gray-500">+{lockedImagesCount}</span>
                  </div>
                </div>
              )}
            </div>

            {/* Unlock Button - Only show for non-banner cars without access */}
            {!hasAccess && isBannerCar === false && (
              <div className="mt-4 bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                <div className="flex items-center justify-between mb-3">
                  <div>
                    <h3 className="font-semibold text-gray-800">{t.unlockFullDetails}</h3>
                    <p className="text-sm text-gray-600">
                      {t.viewAllPhotos} + {t.viewPerformanceReport} + {t.dealerContact}
                    </p>
                    <p className="text-xs text-green-600 mt-1">
                      Performance check report included!
                    </p>
                  </div>
                  <div className="text-right">
                    <span className="text-2xl font-bold text-yellow-600">1 CC</span>
                  </div>
                </div>
                <button
                  onClick={handlePurchaseView}
                  disabled={purchasing || checkingAccess || !user}
                  className="w-full bg-yellow-500 text-white py-3 rounded-md hover:bg-yellow-600 transition disabled:opacity-50 font-semibold"
                >
                  {!user
                    ? t.loginToRequest
                    : purchasing
                    ? t.loading
                    : t.payOneCC
                  }
                </button>
              </div>
            )}

            {/* Dealer's Comment - Left Column (Collapsible) - Requires 0.1 CC */}
            {hasPerformanceCheckAccess && car.dealer_description && (
              <div className="mt-4 bg-amber-50 border border-amber-200 rounded-lg overflow-hidden">
                <button
                  onClick={() => setShowDealerComment(!showDealerComment)}
                  className="w-full p-4 flex items-center justify-between text-left hover:bg-amber-100 transition-colors"
                >
                  <h3 className="font-semibold text-amber-800 flex items-center">
                    <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
                    </svg>
                    {t.dealerDescription || "Dealer's Comment"}
                  </h3>
                  <svg
                    className={`w-5 h-5 text-amber-600 transition-transform ${showDealerComment ? 'rotate-180' : ''}`}
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </button>

                {showDealerComment && (
                  <div className="px-4 pb-4 space-y-3">
                    {/* Korean Original */}
                    <div className="p-3 bg-white rounded border border-amber-100">
                      <p className="text-xs text-gray-400 mb-1">한국어 원문 (Korean Original)</p>
                      <p className="text-gray-700 whitespace-pre-wrap text-sm">{car.dealer_description}</p>
                    </div>
                    {/* Translated Version - Use pre-translated fields */}
                    {language !== 'ko' && (
                      <div className="p-3 bg-white rounded border border-amber-100">
                        <p className="text-xs text-gray-400 mb-1">
                          {language === 'en' ? 'English Translation' : language === 'mn' ? 'Монгол орчуулга' : 'Русский перевод'}
                        </p>
                        <p className="text-gray-700 whitespace-pre-wrap text-sm">
                          {language === 'en' && car.dealer_description_en ? car.dealer_description_en :
                           language === 'mn' && car.dealer_description_mn ? car.dealer_description_mn :
                           language === 'ru' && car.dealer_description_ru ? car.dealer_description_ru :
                           <span className="text-gray-400 italic">Translation not available</span>}
                        </p>
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Details */}
          <div>
            <h1 className="text-3xl font-bold text-gray-800 mb-2">
              {translate(car.car_name) || `${translate(car.maker?.name) || ''} ${translate(car.model?.name) || ''}`.trim() || '-'}
            </h1>

            {(() => {
              const price = formatPrice(car.final_price_krw || car.price_krw);
              return (
                <div className="mb-6">
                  <p className="text-3xl font-bold text-primary-600">
                    {price.usdt !== '-' ? price.usdt : t.contactForPrice}
                  </p>
                  {/* Show local currency for all languages */}
                  {price.local !== '-' && (
                    <p className="text-lg text-gray-500">({price.local})</p>
                  )}
                </div>
              );
            })()}

            {/* Specs Grid */}
            <div className="bg-white rounded-lg shadow p-6 mb-6">
              <h2 className="text-lg font-semibold mb-4">{t.specifications}</h2>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <span className="text-gray-500">{t.year}</span>
                  <p className="font-medium">{car.year || '-'}{car.month ? ` / ${car.month}` : ''}</p>
                </div>
                <div>
                  <span className="text-gray-500">{t.mileage}</span>
                  <p className="font-medium">{formatMileage(car.mileage)}</p>
                </div>
                <div>
                  <span className="text-gray-500">{t.fuel}</span>
                  <p className="font-medium">{translate(car.fuel) || '-'}</p>
                </div>
                <div>
                  <span className="text-gray-500">{t.transmission}</span>
                  <p className="font-medium">{translate(car.transmission) || '-'}</p>
                </div>
                <div>
                  <span className="text-gray-500">{t.color}</span>
                  <p className="font-medium">{translate(car.color) || '-'}</p>
                </div>
                <div>
                  <span className="text-gray-500">{t.engine}</span>
                  <p className="font-medium">{car.displacement ? `${car.displacement} cc` : '-'}</p>
                </div>
                <div>
                  <span className="text-gray-500">{t.maker}</span>
                  <p className="font-medium">{translate(car.maker?.name) || '-'}</p>
                </div>
                <div>
                  <span className="text-gray-500">{t.model}</span>
                  <p className="font-medium">{translate(car.model?.name) || '-'}</p>
                </div>
              </div>
            </div>

            {/* Status - Only show full details if purchased */}
            <div className="bg-white rounded-lg shadow p-6 mb-6">
              <h2 className="text-lg font-semibold mb-4">{t.vehicleStatus}</h2>
              {hasAccess ? (
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <span className="text-gray-500">{t.seizure}</span>
                    <p className={`font-medium ${car.seize_count > 0 ? 'text-red-600' : 'text-green-600'}`}>
                      {car.seize_count > 0 ? `${car.seize_count} ${t.cases}` : t.none}
                    </p>
                  </div>
                  <div>
                    <span className="text-gray-500">{t.collateral}</span>
                    <p className={`font-medium ${car.collateral_count > 0 ? 'text-red-600' : 'text-green-600'}`}>
                      {car.collateral_count > 0 ? `${car.collateral_count} ${t.cases}` : t.none}
                    </p>
                  </div>
                  {car.check_num && (
                    <div className="col-span-2">
                      <span className="text-gray-500">{t.inspectionReport}</span>
                      <p className="font-medium text-primary-600">{car.check_num}</p>
                    </div>
                  )}
                </div>
              ) : (
                <div className="text-center py-4">
                  <svg className="w-12 h-12 text-gray-300 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                  </svg>
                  <p className="text-gray-500">{t.payOneCC}</p>
                </div>
              )}
            </div>

            {/* Performance Check Section */}
            {performanceCheck?.found && (
              <div className="bg-white rounded-lg shadow p-6 mb-6">
                <h2 className="text-lg font-semibold mb-4 flex items-center">
                  <svg className="w-5 h-5 mr-2 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  {t.performanceCheck || 'Performance Check Report'}
                </h2>

                {hasPerformanceCheckAccess ? (
                  // Full access - show details and full report
                  <div className="space-y-4">
                    {performanceCheck.data && (
                      <>
                        <div className="grid grid-cols-2 gap-4 text-sm">
                          <div>
                            <span className="text-gray-500">Check Number</span>
                            <p className="font-medium text-blue-600">{performanceCheck.data.check_number}</p>
                          </div>
                          <div>
                            <span className="text-gray-500">Check Date</span>
                            <p className="font-medium">{performanceCheck.data.check_date || '-'}</p>
                          </div>
                          <div>
                            <span className="text-gray-500">Valid Until</span>
                            <p className="font-medium">{performanceCheck.data.valid_until || '-'}</p>
                          </div>
                          <div>
                            <span className="text-gray-500">First Registration</span>
                            <p className="font-medium">{performanceCheck.data.first_registration || '-'}</p>
                          </div>
                        </div>

                        {/* Status Badges */}
                        <div className="flex flex-wrap gap-2 mt-4">
                          <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                            performanceCheck.data.is_flood_damaged ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'
                          }`}>
                            {performanceCheck.data.is_flood_damaged ? 'Flood Damaged' : 'No Flood Damage'}
                          </span>
                          <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                            performanceCheck.data.is_fire_damaged ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'
                          }`}>
                            {performanceCheck.data.is_fire_damaged ? 'Fire Damaged' : 'No Fire Damage'}
                          </span>
                          <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                            performanceCheck.data.is_total_loss ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'
                          }`}>
                            {performanceCheck.data.is_total_loss ? 'Total Loss' : 'No Total Loss'}
                          </span>
                        </div>

                        {/* 1. Full Report PDF Buttons */}
                        {performanceCheck.data?.pdf_path && (
                          <div className="mt-4 space-y-2">
                            <button
                              onClick={showFullReport ? () => setShowFullReport(false) : loadPdf}
                              disabled={loadingPdf}
                              className="w-full bg-blue-600 text-white py-3 rounded-md hover:bg-blue-700 transition font-medium flex items-center justify-center disabled:opacity-50"
                            >
                              {loadingPdf ? (
                                <>
                                  <svg className="animate-spin w-5 h-5 mr-2" fill="none" viewBox="0 0 24 24">
                                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                  </svg>
                                  Loading PDF...
                                </>
                              ) : (
                                <>
                                  <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                  </svg>
                                  {showFullReport ? 'Hide Full Report' : 'View Full Korean Performance Report (성능점검표)'}
                                </>
                              )}
                            </button>
                            <button
                              onClick={downloadPdf}
                              className="w-full bg-green-600 text-white py-2 rounded-md hover:bg-green-700 transition font-medium flex items-center justify-center"
                            >
                              <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                              </svg>
                              Download PDF
                            </button>
                          </div>
                        )}
                      </>
                    )}

                    {/* Full Report PDF Viewer */}
                    {showFullReport && pdfBlobUrl && (
                      <div className="mt-4 border rounded-lg overflow-hidden bg-white">
                        <div className="bg-gray-100 px-4 py-2 border-b flex items-center justify-between">
                          <span className="font-medium text-gray-700">중고자동차 성능·상태점검기록부 (PDF)</span>
                          <button
                            onClick={() => {
                              setShowFullReport(false);
                              if (pdfBlobUrl) {
                                URL.revokeObjectURL(pdfBlobUrl);
                                setPdfBlobUrl(null);
                              }
                            }}
                            className="text-gray-500 hover:text-gray-700"
                          >
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                            </svg>
                          </button>
                        </div>
                        <object
                          data={pdfBlobUrl}
                          type="application/pdf"
                          className="w-full"
                          style={{ height: '800px' }}
                        >
                          <p className="p-4 text-center text-gray-500">
                            Your browser does not support PDF viewing.{' '}
                            <button onClick={downloadPdf} className="text-blue-600 underline">
                              Download the PDF
                            </button>
                          </p>
                        </object>
                      </div>
                    )}

                    {/* 3. Detailed Specifications from AUTOBEGINS (Third) */}
                    {car.specification && (
                      <div className="mt-6 bg-gray-50 border border-gray-200 rounded-lg p-4">
                        <h3 className="font-semibold text-gray-800 mb-3 flex items-center">
                          <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                          </svg>
                          {t.detailedSpecifications || 'Detailed Specifications'}
                        </h3>
                        <div className="grid grid-cols-2 gap-3 text-sm">
                          {car.specification.manufacturer && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.maker || 'Manufacturer'}</span>
                              <span className="font-medium">{car.specification.manufacturer}</span>
                            </div>
                          )}
                          {car.specification.model_name && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.model || 'Model'}</span>
                              <span className="font-medium">{car.specification.model_name}</span>
                            </div>
                          )}
                          {car.specification.grade && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.grade || 'Grade'}</span>
                              <span className="font-medium">{car.specification.grade}</span>
                            </div>
                          )}
                          {car.specification.body_type && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.bodyType || 'Body Type'}</span>
                              <span className="font-medium">{translate(car.specification.body_type)}</span>
                            </div>
                          )}
                          {car.specification.fuel_type && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.fuel || 'Fuel'}</span>
                              <span className="font-medium">{translate(car.specification.fuel_type)}</span>
                            </div>
                          )}
                          {car.specification.transmission && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.transmission || 'Transmission'}</span>
                              <span className="font-medium">{translate(car.specification.transmission)}</span>
                            </div>
                          )}
                          {car.specification.drive_type && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.driveType || 'Drive Type'}</span>
                              <span className="font-medium">{translate(car.specification.drive_type)}</span>
                            </div>
                          )}
                          {car.specification.displacement && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.engine || 'Engine'}</span>
                              <span className="font-medium">{car.specification.displacement} cc</span>
                            </div>
                          )}
                          {car.specification.max_power && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.maxPower || 'Max Power'}</span>
                              <span className="font-medium">{car.specification.max_power}</span>
                            </div>
                          )}
                          {car.specification.max_torque && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.maxTorque || 'Max Torque'}</span>
                              <span className="font-medium">{car.specification.max_torque}</span>
                            </div>
                          )}
                          {car.specification.fuel_efficiency && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.fuelEfficiency || 'Fuel Efficiency'}</span>
                              <span className="font-medium">{car.specification.fuel_efficiency}</span>
                            </div>
                          )}
                          {car.specification.seating_capacity && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.seatingCapacity || 'Seating'}</span>
                              <span className="font-medium">{car.specification.seating_capacity} {t.persons || 'persons'}</span>
                            </div>
                          )}
                          {car.specification.door_count && (
                            <div className="flex justify-between border-b border-gray-100 pb-1">
                              <span className="text-gray-500">{t.doors || 'Doors'}</span>
                              <span className="font-medium">{car.specification.door_count}</span>
                            </div>
                          )}
                        </div>

                        {/* Dimensions */}
                        {(car.specification.length || car.specification.width || car.specification.height || car.specification.wheelbase) && (
                          <div className="mt-4">
                            <h4 className="text-xs font-semibold text-gray-500 uppercase mb-2">{t.dimensions || 'Dimensions'}</h4>
                            <div className="grid grid-cols-2 gap-2 text-sm">
                              {car.specification.length && (
                                <div className="flex justify-between">
                                  <span className="text-gray-500">{t.length || 'Length'}</span>
                                  <span className="font-medium">{car.specification.length} mm</span>
                                </div>
                              )}
                              {car.specification.width && (
                                <div className="flex justify-between">
                                  <span className="text-gray-500">{t.width || 'Width'}</span>
                                  <span className="font-medium">{car.specification.width} mm</span>
                                </div>
                              )}
                              {car.specification.height && (
                                <div className="flex justify-between">
                                  <span className="text-gray-500">{t.height || 'Height'}</span>
                                  <span className="font-medium">{car.specification.height} mm</span>
                                </div>
                              )}
                              {car.specification.wheelbase && (
                                <div className="flex justify-between">
                                  <span className="text-gray-500">{t.wheelbase || 'Wheelbase'}</span>
                                  <span className="font-medium">{car.specification.wheelbase} mm</span>
                                </div>
                              )}
                              {car.specification.curb_weight && (
                                <div className="flex justify-between">
                                  <span className="text-gray-500">{t.weight || 'Weight'}</span>
                                  <span className="font-medium">{car.specification.curb_weight} kg</span>
                                </div>
                              )}
                            </div>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                ) : (
                  // Preview - show locked state with purchase option
                  <div>
                    {performanceCheck?.preview && (
                      <div className="bg-gray-50 rounded-lg p-4 mb-4">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-sm text-gray-500">Check Number</p>
                            <p className="font-medium text-blue-600">{performanceCheck?.preview?.check_number}</p>
                          </div>
                          <div className="text-right">
                            <svg className="w-8 h-8 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                            </svg>
                          </div>
                        </div>
                      </div>
                    )}

                    <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                      <div className="flex items-center justify-between mb-3">
                        <div>
                          <h3 className="font-semibold text-gray-800">Unlock Detailed Information</h3>
                          <ul className="text-sm text-gray-600 mt-1 space-y-1">
                            <li className="flex items-center">
                              <svg className="w-4 h-4 mr-1 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4" />
                              </svg>
                              Performance Check Report (PDF)
                            </li>
                            <li className="flex items-center">
                              <svg className="w-4 h-4 mr-1 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4" />
                              </svg>
                              Dealer's Description
                            </li>
                          </ul>
                        </div>
                        <div className="text-right">
                          <span className="text-2xl font-bold text-blue-600">0.1 CC</span>
                        </div>
                      </div>
                      <button
                        onClick={handlePurchasePerformanceCheck}
                        disabled={purchasingPerformanceCheck || !user}
                        className="w-full bg-blue-500 text-white py-2 rounded-md hover:bg-blue-600 transition disabled:opacity-50 font-medium"
                      >
                        {!user
                          ? 'Login to Unlock'
                          : purchasingPerformanceCheck
                          ? 'Purchasing...'
                          : 'Pay 0.1 CC to Unlock'
                        }
                      </button>
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* Unlock section for banner cars without performance check access */}
            {!performanceCheck?.found && isBannerCar && !hasPerformanceCheckAccess && car.dealer_description && (
              <div className="bg-white rounded-lg shadow p-6 mb-6">
                <h2 className="text-lg font-semibold mb-4 flex items-center">
                  <svg className="w-5 h-5 mr-2 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  Detailed Information
                </h2>
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-3">
                    <div>
                      <h3 className="font-semibold text-gray-800">Unlock Detailed Information</h3>
                      <ul className="text-sm text-gray-600 mt-1 space-y-1">
                        <li className="flex items-center">
                          <svg className="w-4 h-4 mr-1 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4" />
                          </svg>
                          Dealer's Description
                        </li>
                      </ul>
                    </div>
                    <div className="text-right">
                      <span className="text-2xl font-bold text-blue-600">0.1 CC</span>
                    </div>
                  </div>
                  <button
                    onClick={handlePurchasePerformanceCheck}
                    disabled={purchasingPerformanceCheck || !user}
                    className="w-full bg-blue-500 text-white py-2 rounded-md hover:bg-blue-600 transition disabled:opacity-50 font-medium"
                  >
                    {!user
                      ? 'Login to Unlock'
                      : purchasingPerformanceCheck
                      ? 'Purchasing...'
                      : 'Pay 0.1 CC to Unlock'
                    }
                  </button>
                </div>
              </div>
            )}

            {/* Show unlocked content for banner cars with access but no performance check */}
            {!performanceCheck?.found && isBannerCar && hasPerformanceCheckAccess && (
              <div className="bg-white rounded-lg shadow p-6 mb-6">
                <h2 className="text-lg font-semibold mb-4 flex items-center text-gray-400">
                  <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  {t.performanceCheck || 'Performance Check Report'}
                </h2>
                <div className="text-center py-4">
                  <p className="text-gray-500">Performance check data is not available for this vehicle.</p>
                </div>

                {/* Still show AUTOBEGINS specs if available */}
                {car.specification && (
                  <div className="mt-4 bg-gray-50 border border-gray-200 rounded-lg p-4">
                    <h3 className="font-semibold text-gray-800 mb-3 flex items-center">
                      <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                      </svg>
                      {t.detailedSpecifications || 'Detailed Specifications'}
                    </h3>
                    <div className="grid grid-cols-2 gap-3 text-sm">
                      {car.specification.manufacturer && (
                        <div className="flex justify-between border-b border-gray-100 pb-1">
                          <span className="text-gray-500">{t.maker || 'Manufacturer'}</span>
                          <span className="font-medium">{car.specification.manufacturer}</span>
                        </div>
                      )}
                      {car.specification.model_name && (
                        <div className="flex justify-between border-b border-gray-100 pb-1">
                          <span className="text-gray-500">{t.model || 'Model'}</span>
                          <span className="font-medium">{car.specification.model_name}</span>
                        </div>
                      )}
                      {car.specification.body_type && (
                        <div className="flex justify-between border-b border-gray-100 pb-1">
                          <span className="text-gray-500">{t.bodyType || 'Body Type'}</span>
                          <span className="font-medium">{translate(car.specification.body_type)}</span>
                        </div>
                      )}
                      {car.specification.fuel_type && (
                        <div className="flex justify-between border-b border-gray-100 pb-1">
                          <span className="text-gray-500">{t.fuel || 'Fuel'}</span>
                          <span className="font-medium">{translate(car.specification.fuel_type)}</span>
                        </div>
                      )}
                      {car.specification.transmission && (
                        <div className="flex justify-between border-b border-gray-100 pb-1">
                          <span className="text-gray-500">{t.transmission || 'Transmission'}</span>
                          <span className="font-medium">{translate(car.specification.transmission)}</span>
                        </div>
                      )}
                      {car.specification.displacement && (
                        <div className="flex justify-between border-b border-gray-100 pb-1">
                          <span className="text-gray-500">{t.engine || 'Engine'}</span>
                          <span className="font-medium">{car.specification.displacement} cc</span>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* Dealer Contact - Only show if purchased (1CC for regular cars, 0.1CC for banner cars) */}
            {((isBannerCarConfirmed && hasPerformanceCheckAccess) || (!isBannerCarConfirmed && hasAccess)) && (
              <div className="bg-green-50 border border-green-200 rounded-lg p-6 mb-6">
                <h2 className="text-lg font-semibold mb-4 text-green-800">{t.dealerContact}</h2>
                <div className="space-y-2">
                  <p className="font-medium">DamonHong</p>
                  <p className="text-gray-700">+82-2-552-0773</p>
                  <p className="text-gray-600">Seoul, South Korea</p>
                </div>
              </div>
            )}

            {/* Inquiry Form */}
            <div className="bg-white rounded-lg shadow p-6">
              <h2 className="text-lg font-semibold mb-4">{t.interestedInThisCar}</h2>
              {inquirySuccess ? (
                <div className="bg-green-50 text-green-700 p-4 rounded-md">
                  {t.thankYouInquiry}
                </div>
              ) : (
                <form onSubmit={handleInquiry}>
                  <textarea
                    value={inquiryMessage}
                    onChange={(e) => setInquiryMessage(e.target.value)}
                    placeholder={t.inquiryPlaceholder}
                    rows={4}
                    className="w-full border border-gray-300 rounded-md px-4 py-2 mb-4 focus:ring-primary-500 focus:border-primary-500"
                    required
                  />
                  <button
                    type="submit"
                    disabled={submitting}
                    className="w-full bg-primary-600 text-white py-3 rounded-md hover:bg-primary-700 transition disabled:opacity-50"
                  >
                    {submitting ? t.submitting : user ? t.sendInquiry : t.loginToSendInquiry}
                  </button>
                </form>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
