import React, { useState, useEffect } from "react";
import {
  View,
  StyleSheet,
  Text,
  TouchableOpacity,
  ScrollView,
  Image,
  Modal,
  TextInput,
  Platform,
  KeyboardAvoidingView,
  Alert,
  AppState,
} from "react-native";
import { StatusBar } from "expo-status-bar";
import { WebView } from "react-native-webview";
import { SafeAreaView } from "react-native-safe-area-context";
import { FLEX } from "@/theme/mixins";
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import { title } from "@/theme/typography";
import { COLOR_SCALES } from "@/theme/colors";
import { applyCoupon, buyPackage, getPackages, checkUserPackage } from "@/services/user";
import Loading from "@/components/common/Loading";
import Empty from "@/components/common/Empty";
import Toast from "@/components/common/Toast";
import useToast from "@/hooks/useToast";
import * as Linking from 'expo-linking';

import RevenueCatServiceModule from "@/services/revenueCat";

const PackagesScreen = () => {
  const RevenueCatService =
    RevenueCatServiceModule?.getOfferings
      ? RevenueCatServiceModule
      : RevenueCatServiceModule?.default;

  const router = useRouter();
  const scrollViewRef = React.useRef(null);

  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [selectedPackage, setSelectedPackage] = useState(null);
  const [isRevenueCatLoading, setIsRevenueCatLoading] = useState(true);
  const [isApiLoading, setIsApiLoading] = useState(true);
  const [isPurchasing, setIsPurchasing] = useState(false);
  const [error, setError] = useState(null);
  const [appliedCoupon, setAppliedCoupon] = useState(null);
  const [couponCode, setCouponCode] = useState("");
  const [show3dsModal, setShow3dsModal] = useState(false);
  const [threeDSHtml] = useState("");
  const [threeDSUrl] = useState("");
  const [threeDSHandled, setThreeDSHandled] = useState(false);
  
  // RevenueCat states
  const [revenueCatPackages, setRevenueCatPackages] = useState([]);
  const [apiPackages, setApiPackages] = useState([]);
  const [userPackage, setUserPackage] = useState(null);

  const { toast, showSuccessToast, showErrorToast, hideToast } = useToast();

  // RevenueCat paketlerini yükle
  useEffect(() => {
    const loadRevenueCatPackages = async () => {
      try {
        setIsRevenueCatLoading(true);
        console.log('Loading RevenueCat packages...');
        
        const offerings = await RevenueCatService.getOfferings();
        console.log('RevenueCat offerings:', JSON.stringify(offerings, null, 2));
        
        if (!offerings?.current) {
          console.warn('⚠️ No current offering found');
          setRevenueCatPackages([]);
          setError(new Error('RevenueCat\'te aktif offering bulunamadı.'));
          setIsRevenueCatLoading(false);
          return;
        }
        
        const availablePackages = Array.isArray(offerings?.current?.availablePackages)
          ? offerings.current.availablePackages
          : [];

        console.log('Available packages count:', availablePackages.length);

        if (availablePackages.length > 0) {
          const rcPackages = availablePackages.map((pkg) => {
            const productIdentifier = pkg?.product?.identifier;
            const productPrice = pkg?.product?.price;
            const productPriceString = pkg?.product?.priceString;
            
            console.log('📦 Processing package:', {
              identifier: pkg.identifier,
              productId: productIdentifier,
              title: pkg?.product?.title,
              price: productPrice,
              priceString: productPriceString,
              currencyCode: pkg?.product?.currencyCode,
            });

            // Ürün bilgisi eksikse uyarı ver
            if (!productIdentifier) {
              console.error('⚠️ Product identifier missing for package:', pkg.identifier);
            }
            if (productPrice === undefined || productPrice === null) {
              console.error('⚠️ Product price missing for package:', pkg.identifier);
            }

            return {
              id: `rc_${pkg.identifier}`,
              name: pkg?.product?.title || pkg?.product?.identifier || pkg?.identifier,
              title: pkg?.product?.description || "Premium Paket",
              price: productPrice || 0,
              priceString: productPriceString || `${productPrice || 0}`,
              discountPrice: null,
              hasPackage: false,
              isRevenueCat: true,
              revenueCatPackage: pkg,
              items: [
                { name: "Premium İçerik Erişimi" },
                { name: "Reklamsız Deneyim" },
                { name: "Özel Destek" }
              ],
              modules: []
            };
          });
          
          setRevenueCatPackages(rcPackages);
          setError(null);
          console.log('✅ RevenueCat packages loaded successfully:', rcPackages.length);
        } else {
          console.warn('⚠️ No packages available in current offering');
          setRevenueCatPackages([]);
          setError(new Error('RevenueCat\'te hiç paket bulunamadı. Dashboard\'da paket tanımlı olduğundan emin olun.'));
        }
      } catch (error) {
        console.error('❌ RevenueCat packages loading error:', error);
        console.error('Error details:', {
          message: error?.message,
          code: error?.code,
          userCancelled: error?.userCancelled
        });
        setError(error);
        setRevenueCatPackages([]);
      } finally {
        setIsRevenueCatLoading(false);
      }
    };

    loadRevenueCatPackages();
  }, []);

  // API'den paketleri çek
  useEffect(() => {
    const loadApiPackages = async () => {
      try {
        setIsApiLoading(true);
        console.log('Loading API packages...');
        
        const response = await getPackages();
        const packages = response?.data || [];
        
        console.log('API packages loaded:', packages.length);
        setApiPackages(packages);

        // Kullanıcının aktif paketini de çek
        try {
          const userPackageResponse = await checkUserPackage();
          console.log('User package response:', userPackageResponse);
          if (userPackageResponse?.success && userPackageResponse?.data) {
            setUserPackage(userPackageResponse.data);
            console.log('User active package:', userPackageResponse.data);
          }
        } catch (error) {
          console.log('No active user package or error:', error);
        }
      } catch (error) {
        console.error('API packages loading error:', error);
        setApiPackages([]);
      } finally {
        setIsApiLoading(false);
      }
    };

    loadApiPackages();
  }, []);

  // Kupon otomatik çekilmeyecek, sadece manuel girilecek
  // useEffect kaldırıldı

  const handleBuyPackage = async (packageData) => {
    // RevenueCat paketi varsa satın al ve backend'e bildir
    if (packageData?.revenueCatPackage) {
      try {
        setIsPurchasing(true);
        console.log('Starting RevenueCat purchase...');
        console.log('Package details:', {
          identifier: packageData.revenueCatPackage.identifier,
          productId: packageData.revenueCatPackage.product?.identifier,
          price: packageData.revenueCatPackage.product?.price,
        });
        
        // 1. RevenueCat ile satın al
        const customerInfo = await RevenueCatService.purchasePackage(packageData.revenueCatPackage);
        
        console.log('RevenueCat purchase successful:', customerInfo);
        
        // 2. Backend'e bildirimi gönder
        try {
          const { processRevenueCatPurchase } = await import('@/services/user');
          const productId = packageData.revenueCatPackage.product?.identifier;
          const ids = RevenueCatService.extractPurchaseIds?.(customerInfo, productId) || {};
          
          // Gerçek Apple transaction ID (expiration date DEĞİL)
          const transactionId =
            ids.storeTransactionId ||
            customerInfo?.subscriptionsByProductIdentifier?.[productId]?.storeTransactionId ||
            `${productId}_${Date.now()}`;
          
          console.log('Sending to backend:', {
            productId,
            transactionId,
            periodType: ids.periodType,
            price: ids.price,
            receiptData: customerInfo
          });
          
          const backendResponse = await processRevenueCatPurchase({
            productId,
            transactionId,
            receiptData: JSON.stringify(customerInfo)
          });
          
          console.log('Backend response:', backendResponse);
          
          if (backendResponse?.success) {
            showSuccessToast({ 
              title: 'Satın Alma Başarılı', 
              message: 'Aboneliğiniz aktifleştirildi.' 
            });
            
            try {
              router.replace('/');
            } catch (_) {}
          } else {
            showErrorToast({ 
              title: 'Uyarı', 
              message: backendResponse?.message || 'Satın alma başarılı ancak sunucu kaydı oluşturulamadı.' 
            });
          }
        } catch (backendError) {
          console.error('Backend notification error:', backendError);
          // RevenueCat başarılı olduğu için kullanıcıya başarı göster
          showSuccessToast({ 
            title: 'Satın Alma Başarılı', 
            message: 'Aboneliğiniz aktifleştirildi. (Sunucu senkronizasyonu başarısız)' 
          });
          
          try {
            router.replace('/');
          } catch (_) {}
        }
        
        return;
      } catch (error) {
        console.error('RevenueCat purchase error:', error);
        console.error('Error details:', {
          message: error?.message,
          code: error?.code,
          userCancelled: error?.userCancelled,
          underlyingErrorMessage: error?.underlyingErrorMessage,
        });
        
        if (error.message === 'cancelled') {
          return;
        }
        
        // Daha açıklayıcı hata mesajları
        let errorMessage = 'Satın alma işlemi tamamlanamadı.';
        
        if (error?.message?.includes('configuration')) {
          errorMessage = 'Simulator\'da test için StoreKit Configuration dosyası gerekli. Gerçek cihazda deneyin veya StoreKit Config ekleyin.';
        } else if (error?.message?.includes('product')) {
          errorMessage = 'Ürün bulunamadı. Lütfen daha sonra tekrar deneyin.';
        } else if (error?.message?.includes('network')) {
          errorMessage = 'İnternet bağlantınızı kontrol edin.';
        } else if (error?.message) {
          errorMessage = error.message;
        }
        
        showErrorToast({ 
          title: 'Satın Alma Başarısız', 
          message: errorMessage
        });
        return;
      } finally {
        setIsPurchasing(false);
      }
    }

    // Normal API paketi
    setSelectedPackage(packageData);
    setShowPaymentModal(true);
  };

  const handleBack = () => {
    router.back();
  };

  const handlePayment = async () => {
    try {
      // RevenueCat paketi kontrolü
      if (selectedPackage?.revenueCatPackage) {
        try {
          console.log('Starting RevenueCat purchase...');
          const customerInfo = await RevenueCatService.purchasePackage(selectedPackage.revenueCatPackage);
          
          console.log('RevenueCat purchase successful:', customerInfo);
          
          // Backend'e bildirimi gönder
          try {
            const { processRevenueCatPurchase } = await import('@/services/user');
            const productId = selectedPackage.revenueCatPackage.product?.identifier;
            const ids = RevenueCatService.extractPurchaseIds?.(customerInfo, productId) || {};
            const transactionId =
              ids.storeTransactionId ||
              customerInfo?.subscriptionsByProductIdentifier?.[productId]?.storeTransactionId ||
              `${productId}_${Date.now()}`;
            
            const backendResponse = await processRevenueCatPurchase({
              productId,
              transactionId,
              receiptData: JSON.stringify(customerInfo)
            });
            
            setShowPaymentModal(false);
            
            if (backendResponse?.success) {
              showSuccessToast({ 
                title: 'Satın Alma Başarılı', 
                message: 'RevenueCat aboneliğiniz aktifleştirildi.' 
              });
            } else {
              showSuccessToast({ 
                title: 'Satın Alma Başarılı', 
                message: backendResponse?.message || 'Aboneliğiniz aktifleştirildi.' 
              });
            }
            
            try {
              router.replace('/');
            } catch (_) {}
          } catch (backendError) {
            console.error('Backend notification error:', backendError);
            setShowPaymentModal(false);
            showSuccessToast({ 
              title: 'Satın Alma Başarılı', 
              message: 'Aboneliğiniz aktifleştirildi.' 
            });
            
            try {
              router.replace('/');
            } catch (_) {}
          }
          
          return;
        } catch (error) {
          console.error('RevenueCat purchase error:', error);
          
          if (error.message === 'cancelled') {
            setShowPaymentModal(false);
            return;
          }
          
          setShowPaymentModal(false);
          showErrorToast({ 
            title: 'Satın Alma Başarısız', 
            message: error.message || 'RevenueCat işlemi tamamlanamadı.' 
          });
          return;
        }
      }

      // Normal API paketi
      const payload = {
        packageId: selectedPackage?.id,
        couponId: appliedCoupon?.id ?? null,
      };
      const res = await buyPackage(payload);
      setShowPaymentModal(false);
      if (res?.success) {
        showSuccessToast({ title: 'Satın Alma Başarılı', message: res?.message ?? 'Paketiniz aktifleştirildi.' });
        try {
          router.replace('/');
        } catch (_) {}
      } else {
        showErrorToast({ title: 'Satın Alma Başarısız', message: res?.message ?? 'İşlem tamamlanamadı.' });
      }
    } catch (e) {
      setShowPaymentModal(false);
      showErrorToast({ title: 'Satın Alma Başarısız', message: 'İşlem tamamlanamadı.' });
    }
  };

  const parsePaymentSuccessFromText = (text = "") => {
    const lower = String(text).toLowerCase();
    return (
      lower.includes('"paymentstatus":"success"') ||
      lower.includes('paymentstatus":"success"') ||
      lower.includes('paymentstatus=success') ||
      lower.includes('"status":"success"') ||
      lower.includes('status=success')
    );
  };

  const handle3dsSuccess = () => {
    if (threeDSHandled) return;
    setThreeDSHandled(true);
    setShow3dsModal(false);
    showSuccessToast({ title: 'Ödeme Başarılı', message: 'Paketiniz aktifleştirildi.' });
  };

  const handle3dsFailure = () => {
    if (threeDSHandled) return;
    setThreeDSHandled(true);
    setShow3dsModal(false);
    showErrorToast({ title: 'Ödeme Başarısız', message: 'İşleminiz tamamlanamadı.' });
  };

  const handleWebViewNavChange = (navState) => {
    if (threeDSHandled) return;
    const url = navState?.url ?? '';
    const lowerUrl = String(url).toLowerCase();
    if (!url) return;
    if (lowerUrl.includes('/api/payments/callback-hosted-3ds')) {
      if (
        lowerUrl.includes('paymentstatus=success') ||
        lowerUrl.includes('status=success')
      ) {
        handle3dsSuccess();
      } else if (lowerUrl.includes('failed') || lowerUrl.includes('error')) {
        handle3dsFailure();
      } else {
        handle3dsSuccess();
      }
    }
    if (lowerUrl.includes('esnekpos') && (lowerUrl.includes('basarili') || lowerUrl.includes('success'))) {
      handle3dsSuccess();
    }
  };

  const handleWebViewMessage = (event) => {
    if (threeDSHandled) return;
    try {
      const data = JSON.parse(event?.nativeEvent?.data ?? '{}');
      const text = data?.text ?? '';
      if (parsePaymentSuccessFromText(text)) {
        handle3dsSuccess();
      }
    } catch (_) {
      // yoksay
    }
  };

  const handleCancel = () => {
    setShowPaymentModal(false);
    setSelectedPackage(null);
  };

  // App Store'dan dönünce durumu senkronla (webhook + customerInfo)
  useEffect(() => {
    const onAppState = async (state) => {
      if (state !== "active") return;
      try {
        const info = await RevenueCatService.getCustomerInfo?.();
        const productId = "com.bugunyap.aylik";
        const sub = info?.subscriptionsByProductIdentifier?.[productId];
        const stillActive = sub?.isActive === true;
        const expired =
          sub?.expiresDate && new Date(sub.expiresDate).getTime() <= Date.now();

        if (sub && stillActive && !expired) {
          // App Store aktif → backend'de yoksa/yanlış kapandıysa geri aç
          const ids = RevenueCatService.extractPurchaseIds?.(info, productId) || {};
          const transactionId =
            ids.storeTransactionId ||
            `${productId}_sync_${Date.now()}`;
          const { processRevenueCatPurchase } = await import("@/services/user");
          await processRevenueCatPurchase({
            productId,
            transactionId,
            receiptData: JSON.stringify(info),
          });
        } else if (sub && (!stillActive || expired)) {
          // App Store'da bitmişse backend'i kapat
          const { deactivateRevenueCatPackages } = await import("@/services/user");
          await deactivateRevenueCatPackages({ productId });
        }

        const pkgRes = await checkUserPackage();
        if (pkgRes?.success) setUserPackage(pkgRes.data || null);
        else setUserPackage(null);
      } catch (_) {
        // sessiz
      }
    };
    const sub = AppState.addEventListener("change", onAppState);
    return () => sub?.remove?.();
  }, []);

  const handleCancelSubscription = () => {
    Alert.alert(
      "Aboneliği İptal Et",
      "İptal işlemi App Store üzerinden yapılır. Açılacak sayfada Bugün YAP aboneliğini iptal edin.\n\nApp Store'da iptal etmeden paketiniz kapanmaz.",
      [
        { text: "Vazgeç", style: "cancel" },
        {
          text: "App Store'a Git",
          style: "destructive",
          onPress: async () => {
            try {
              setIsPurchasing(true);
              // Backend'i burada SİLME — sadece App Store yönetim sayfasını aç
              await RevenueCatService.openManageSubscriptions?.();
              showSuccessToast({
                title: "App Store açıldı",
                message: "Aboneliği oradan iptal edin. İptal sonrası paket otomatik kapanır.",
              });
            } catch (e) {
              showErrorToast({
                title: "Hata",
                message: e?.message || "App Store sayfası açılamadı.",
              });
            } finally {
              setIsPurchasing(false);
            }
          },
        },
      ]
    );
  };

  const handleApplyCoupon = async () => {
    if (!couponCode.trim()) return;
    
    const code = couponCode.trim().toUpperCase();
    
    try {
      const res = await applyCoupon({ code });
      if (res?.success && res?.data) {
        console.log("Kupon data:", JSON.stringify(res.data));
        setAppliedCoupon(res.data);

        if (code === 'BGNYAP') {
          // BGNYAP → backend'den paketi direkt aktifleştir
          try {
            const { processRevenueCatPurchase } = await import('@/services/user');
            const backendResponse = await processRevenueCatPurchase({
              productId: 'com.bugunyap.aylik',
              transactionId: `BGNYAP_${Date.now()}`,
              receiptData: JSON.stringify({ couponCode: code, freeAccess: true })
            });
            if (backendResponse?.success) {
              showSuccessToast({ title: 'Hoş Geldiniz!', message: 'Paketiniz ücretsiz aktifleştirildi.' });
              setTimeout(() => { router.replace('/'); }, 1500);
            } else {
              showErrorToast({ title: 'Hata', message: backendResponse?.message || 'Aktivasyon başarısız.' });
            }
          } catch (e) {
            showErrorToast({ title: 'Hata', message: e?.message || 'Aktivasyon başarısız.' });
          }
        } else {
          // Diğer kuponlar → App Store'a yönlendir
          const redemptionUrl = `https://apps.apple.com/redeem?ctx=offercodes&id=6749271181&code=${code}`;
          showSuccessToast({ title: 'Kupon Uygulandı', message: 'App Store\'a yönlendiriliyorsunuz...' });
          setTimeout(() => { Linking.openURL(redemptionUrl); }, 1200);
        }
      } else {
        showErrorToast({ title: 'Geçersiz Kupon', message: res?.message ?? 'Kupon kodu geçerli değil.' });
      }
    } catch (e) {
      showErrorToast({ title: 'Hata', message: e?.message ?? 'Kupon uygulanamadı.' });
    }
  };

  // RevenueCat ve API paketlerini birleştir
  const packagesToShow = React.useMemo(() => {
    if (!Array.isArray(revenueCatPackages) || revenueCatPackages.length === 0) {
      return [];
    }

    // RevenueCat paketlerini API paketleriyle eşleştir
    return revenueCatPackages.map((rcPkg) => {
      const productId = rcPkg?.revenueCatPackage?.product?.identifier;
      
      // API'den app_store_id ile eşleşen paketi bul
      const matchedApiPackage = apiPackages.find(
        (apiPkg) => apiPkg?.app_store_id === productId
      );

      if (matchedApiPackage) {
        console.log('✅ Matched package:', {
          productId,
          apiPackageName: matchedApiPackage.name,
          itemsCount: matchedApiPackage.items?.length || 0,
          modulesCount: matchedApiPackage.modules?.length || 0
        });

        return {
          ...rcPkg,
          apiPackage: matchedApiPackage,
          name: matchedApiPackage.name || rcPkg.name,
          title: matchedApiPackage.title || rcPkg.title,
          items: matchedApiPackage.items || rcPkg.items,
          modules: matchedApiPackage.modules || rcPkg.modules,
          hasPackage: matchedApiPackage.hasPackage || false,
        };
      }

      console.log('⚠️ No API match for product:', productId);
      return rcPkg;
    });
  }, [revenueCatPackages, apiPackages]);

  // Paket verilerini formatla — appliedCoupon değişince yeniden hesapla
  const formattedPackages = React.useMemo(() => {
    return packagesToShow.map((pkg) => {
      const features = [];
      
      // Önce modülleri ekle
      if (pkg?.modules?.length > 0) {
        pkg.modules.forEach(module => {
          const courseTitle = module?.course?.title;
          if (courseTitle) {
            features.push(`${courseTitle} Modülü`);
          } else if (module?.name) {
            features.push(module.name);
          }
        });
      }
      
      // Sonra item'ları ekle
      if (pkg?.items?.length > 0) {
        pkg.items.forEach(item => {
          if (item?.name) features.push(item.name);
        });
      }
      
      // Eğer hiç özellik yoksa varsayılan özellikleri kullan
      if (features.length === 0) {
        features.push('Tüm premium içeriklere erişim');
        features.push('Reklamsız deneyim');
        features.push('Özel destek');
      }

      // Tarihleri formatla (gün.ay.yıl - saat:dakika)
      const formatDate = (dateString) => {
        if (!dateString) return null;
        try {
          const date = new Date(dateString);
          const day = date.getDate();
          const month = date.getMonth() + 1;
          const year = date.getFullYear();
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          return `${day}.${month}.${year} - ${hours}:${minutes}`;
        } catch (error) {
          return null;
        }
      };

      // Kullanıcının bu paketi varsa tarih bilgilerini al
      let startDate = null;
      let endDate = null;
      let isOwned = pkg?.apiPackage?.hasPackage || pkg?.hasPackage === true;
      
      if (isOwned && userPackage) {
        // userPackage'dan tarihleri al
        startDate = formatDate(userPackage?.startDate);
        endDate = formatDate(userPackage?.endDate);
      }

      // Debug için console log
      console.log('=== PACKAGE DEBUG ===');
      console.log('Package ID:', pkg?.id);
      console.log('Package Name:', pkg?.name);
      console.log('Owned:', isOwned);
      console.log('User Package:', userPackage);
      console.log('Start Date (raw):', userPackage?.startDate);
      console.log('End Date (raw):', userPackage?.endDate);
      console.log('Start Date (formatted):', startDate);
      console.log('End Date (formatted):', endDate);

      // RevenueCat paketi için fiyat bilgisi
      let originalBasePrice, finalPrice, priceDisplay, currencySymbol, currencyCode;
      
      if (pkg?.revenueCatPackage) {
        originalBasePrice = pkg.price || 29.99;
        finalPrice = originalBasePrice;
        currencyCode = pkg.revenueCatPackage.product.currencyCode || 'USD';
        
        // Para birimi sembolünü belirle
        if (currencyCode === 'TRY') {
          currencySymbol = '₺';
        } else if (currencyCode === 'USD') {
          currencySymbol = '$';
        } else if (currencyCode === 'EUR') {
          currencySymbol = '€';
        } else {
          currencySymbol = currencyCode;
        }
        
        // RevenueCat'ten gelen formatlanmış fiyat string'ini kullan
        priceDisplay = pkg.priceString || pkg.revenueCatPackage.product.priceString || `${currencySymbol}${finalPrice.toFixed(2)}`;
        
        console.log('=== PRICE DISPLAY ===');
        console.log('Original price:', originalBasePrice);
        console.log('Final price:', finalPrice);
        console.log('Currency code:', currencyCode);
        console.log('Currency symbol:', currencySymbol);
        console.log('Price display:', priceDisplay);
      } else {
        originalBasePrice = Number(pkg?.price ?? 0);
        const discountPrice = pkg?.discountPrice != null ? Number(pkg.discountPrice) : null;
        const hasPackageDiscount = typeof discountPrice === 'number' && discountPrice > 0 && discountPrice < originalBasePrice;
        finalPrice = hasPackageDiscount ? discountPrice : originalBasePrice;
        priceDisplay = `${finalPrice.toFixed(2)}₺`;
        currencySymbol = '₺';
        currencyCode = 'TRY';
      }

      // Kupon uygulaması - sadece kod girilip doğrulandıysa
      let couponApplied = false;
      if (appliedCoupon && couponCode.trim()) {
        const couponType = appliedCoupon?.type;
        const couponVal = Number(appliedCoupon?.price ?? 0);
        
        console.log('=== APPLYING COUPON ===');
        console.log('Coupon type:', couponType);
        console.log('Coupon price value:', couponVal);
        console.log('Original price:', finalPrice);
        
        if (couponType === 1) {
          // Type 1: Sabit indirim - price değeri kadar indirim
          finalPrice = Math.max(0, finalPrice - couponVal);
          couponApplied = true;
          console.log(`Fixed discount: -${couponVal}. New price: ${finalPrice}`);
        } else if (couponType === 2) {
          // Type 2: Yüzdelik indirim - price değeri yüzde olarak
          const discountAmount = finalPrice * (couponVal / 100);
          finalPrice = Math.max(0, finalPrice - discountAmount);
          couponApplied = true;
          console.log(`Percentage discount: ${couponVal}%. Discount amount: ${discountAmount}. New price: ${finalPrice}`);
        }
      }

      return {
        id: pkg?.id,
        title: pkg?.name || 'Paket',
        badge: pkg?.title || '',
        features: features.length > 0 ? features : ['Detaylar için iletişime geçin'],
        isRevenueCat: Boolean(pkg?.revenueCatPackage),
        currentPrice: couponApplied ? `${currencySymbol}${finalPrice.toFixed(2)}` : priceDisplay,
        finalPrice,
        originalPrice: couponApplied ? priceDisplay : null,
        owned: isOwned,
        startDate,
        endDate,
        revenueCatPackage: pkg?.revenueCatPackage,
        apiPackage: pkg?.apiPackage,
      };
    });
  }, [packagesToShow, appliedCoupon, userPackage]);

  // Loading state
  if (isRevenueCatLoading || isApiLoading) {
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar style="dark" backgroundColor="#F5F5F5" />
        <View style={styles.header}>
          <View style={styles.headerContent}>
            <TouchableOpacity style={styles.backButton} onPress={handleBack}>
              <Image
                source={require("@/assets/images/icons/back-button.png")}
                style={styles.backButtonIcon}
                resizeMode="contain"
              />
            </TouchableOpacity>
            <Text style={styles.title}>Paketler</Text>
            <TouchableOpacity style={styles.bugunYapButton}>
              <Image
                source={require("@/assets/images/logo/logo-small.png")}
                style={styles.logo}
              />
            </TouchableOpacity>
          </View>
        </View>
        <Loading size="large" message="Paketler yükleniyor..." />
      </SafeAreaView>
    );
  }

  // Error state
  if (error) {
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar style="dark" backgroundColor="#F5F5F5" />
        <View style={styles.header}>
          <View style={styles.headerContent}>
            <TouchableOpacity style={styles.backButton} onPress={handleBack}>
              <Image
                source={require("@/assets/images/icons/back-button.png")}
                style={styles.backButtonIcon}
                resizeMode="contain"
              />
            </TouchableOpacity>
            <Text style={styles.title}>Paketler</Text>
            <TouchableOpacity style={styles.bugunYapButton}>
              <Image
                source={require("@/assets/images/logo/logo-small.png")}
                style={styles.logo}
              />
            </TouchableOpacity>
          </View>
        </View>
        <Empty
          title="Bir Hata Oluştu"
          description={error?.message || "Paketler yüklenemedi. Lütfen tekrar deneyin."}
          icon={<Ionicons name="alert-circle-outline" size={48} color={COLOR_SCALES.primary[40]} />}
        />
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      <Toast
        visible={toast?.visible}
        title={toast?.title}
        message={toast?.message}
        type={toast?.type}
        duration={toast?.duration}
        onHide={hideToast}
      />
      <StatusBar style="dark" backgroundColor="#F5F5F5" />
      {/* Header */}
      <View style={styles.header}>
        <View style={styles.headerContent}>
          <TouchableOpacity style={styles.backButton} onPress={handleBack}>
            <Image
              source={require("@/assets/images/icons/back-button.png")}
              style={styles.backButtonIcon}
              resizeMode="contain"
            />
          </TouchableOpacity>
          <Text style={styles.title}>Paketler</Text>
          <TouchableOpacity style={styles.bugunYapButton}>
            <Image
              source={require("@/assets/images/logo/logo-small.png")}
              style={styles.logo}
            />
          </TouchableOpacity>
        </View>
      </View>
      {/* Character Section */}
      <View style={styles.characterSection}>
        <Image
          source={require("@/assets/images/lokma.png")}
          style={styles.characterImage}
        />
      </View>
      
      <KeyboardAvoidingView 
        style={styles.keyboardAvoidingView}
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        keyboardVerticalOffset={Platform.OS === 'ios' ? 100 : 0}
      >
        <ScrollView
          ref={scrollViewRef}
          style={styles.mainScrollView}
          contentContainerStyle={styles.mainScrollContent}
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps="handled"
          keyboardDismissMode="interactive"
        >
        {/* Package Cards Slider */}

        {packagesToShow?.length > 0 ? (
          <ScrollView
            style={styles.packagesContainer}
            contentContainerStyle={styles.packagesContent}
            horizontal={true}
            showsHorizontalScrollIndicator={false}
            snapToInterval={320}
            decelerationRate="fast"
            snapToAlignment="center"
            nestedScrollEnabled={true}
          >
            {formattedPackages.map((formattedPackage) => {
              return (
                <View key={formattedPackage?.id} style={styles.packageCard}>
                  {/* App Store Badge - En üstte */}
                  {formattedPackage.revenueCatPackage && (
                    <View style={styles.appStoreBadge}>
                      <Ionicons name="logo-apple" size={14} color="#000" style={styles.appStoreIcon} />
                      <Text style={styles.appStoreText}>App Store</Text>
                    </View>
                  )}

                  <Text style={styles.packageTitle}>{formattedPackage.title}</Text>
                  
                  {formattedPackage.badge && (
                    <Text style={styles.packageSubtitle}>{formattedPackage.badge}</Text>
                  )}

                  <View style={styles.packageFeatures}>
                    {formattedPackage.features?.map((feature, index) => (
                      <View key={index} style={styles.featureItem}>
                        <Ionicons name="checkmark" size={16} color="#4CAF50" />
                        <Text style={styles.featureText}>{feature}</Text>
                      </View>
                    ))}
                  </View>

                  {/* Paket alınmışsa tarih bilgileri, alınmamışsa sözleşmeler */}
                  {(() => {
                    console.log('=== RENDER CHECK ===');
                    console.log('Package:', formattedPackage.title);
                    console.log('Owned:', formattedPackage.owned);
                    console.log('Start Date:', formattedPackage.startDate);
                    console.log('End Date:', formattedPackage.endDate);
                    console.log('Show Dates:', formattedPackage.owned && formattedPackage.startDate && formattedPackage.endDate);
                    
                    if (formattedPackage.owned && formattedPackage.startDate && formattedPackage.endDate) {
                      return (
                        <View style={styles.dateInfoContainer}>
                          <View style={styles.dateRow}>
                            <Ionicons name="calendar-outline" size={14} color="#666" />
                            <Text style={styles.dateLabel}>Başlangıç:</Text>
                            <Text style={styles.dateValue}>{formattedPackage.startDate}</Text>
                          </View>
                          <View style={styles.dateRow}>
                            <Ionicons name="calendar-outline" size={14} color="#666" />
                            <Text style={styles.dateLabel}>Bitiş:</Text>
                            <Text style={styles.dateValue}>{formattedPackage.endDate}</Text>
                          </View>
                        </View>
                      );
                    } else {
                      return (
                        <View style={styles.legalLinksContainer}>
                          <TouchableOpacity 
                            onPress={() => Linking.openURL('https://bugunyap.com/?page=gizlilik_sozlesmesi')}
                            style={styles.legalLink}
                          >
                            <Text style={styles.legalLinkText}>Gizlilik Politikası</Text>
                          </TouchableOpacity>
                          <Text style={styles.legalSeparator}>•</Text>
                          <TouchableOpacity 
                            onPress={() => Linking.openURL('https://www.apple.com/legal/internet-services/itunes/dev/stdeula/')}
                            style={styles.legalLink}
                          >
                            <Text style={styles.legalLinkText}>Kullanım Şartları</Text>
                          </TouchableOpacity>
                        </View>
                      );
                    }
                  })()}

                  <View style={styles.priceSection}>
                    <View style={styles.priceContainer}>
                      <Text style={styles.currentPrice}>
                        {formattedPackage.currentPrice}
                      </Text>
                      {formattedPackage.originalPrice && (
                        <Text style={styles.originalPrice}>
                          {" "}
                          / {formattedPackage.originalPrice}
                        </Text>
                      )}
                    </View>

                    {formattedPackage.owned ? (
                      <View style={styles.ownedActions}>
                        <View style={styles.ownedBadge}>
                          <Ionicons name="checkmark-circle" size={16} color={COLOR_SCALES.primary[60]} />
                          <Text style={styles.ownedBadgeText}>Aktif</Text>
                        </View>
                        <TouchableOpacity
                          style={[styles.cancelSubButton, isPurchasing && styles.buyButtonDisabled]}
                          onPress={handleCancelSubscription}
                          activeOpacity={0.85}
                          disabled={isPurchasing}
                        >
                          <Ionicons name="close-circle-outline" size={16} color="#B4001A" />
                          <Text style={styles.cancelSubButtonText}>Aboneliği İptal Et</Text>
                        </TouchableOpacity>
                      </View>
                    ) : (
                      <TouchableOpacity
                        style={[styles.buyButton, isPurchasing && styles.buyButtonDisabled]}
                        onPress={() => handleBuyPackage(formattedPackage)}
                        activeOpacity={0.8}
                        disabled={isPurchasing}
                      >
                        {formattedPackage.revenueCatPackage ? (
                          <View style={styles.buyButtonContent}>
                            {isPurchasing ? (
                              <>
                                <Text style={styles.buyButtonText}>Yükleniyor...</Text>
                              </>
                            ) : (
                              <>
                                <Ionicons name="logo-apple" size={16} color="#FFFFFF" />
                                <Text style={styles.buyButtonText}>App Store</Text>
                              </>
                            )}
                          </View>
                        ) : (
                          <Text style={styles.buyButtonText}>
                            {isPurchasing ? 'Yükleniyor...' : 'Satın Al'}
                          </Text>
                        )}
                      </TouchableOpacity>
                    )}
                  </View>
                </View>
              );
            })}
          </ScrollView>
        ) : (
          <Empty
            title="Paket Bulunamadı"
            description={"Gösterilecek paket bulunmamaktadır."}
            icon={<Ionicons name="package-outline" size={48} color={COLOR_SCALES.primary[40]} />}
          />
        )}

        {/* Kupon Kodu */}
        <View style={styles.couponRow}>
          <View style={styles.couponInputContainer}>
            <Text style={styles.couponLabel}>Kupon Kodu</Text>
            <TextInput
              style={styles.couponTextInput}
              value={couponCode}
              onChangeText={setCouponCode}
              placeholder="Kupon kodunuzu girin"
              placeholderTextColor={COLOR_SCALES.colorGray[50]}
              editable={!appliedCoupon}
              autoCapitalize="characters"
              autoCorrect={false}
              autoComplete="off"
              textContentType="none"
              keyboardType="default"
              returnKeyType="done"
              clearButtonMode="while-editing"
              onFocus={() => {
                // Kupon input'una focus olduğunda scroll yap
                setTimeout(() => {
                  scrollViewRef.current?.scrollToEnd({ animated: true });
                }, 100);
              }}
            />
            {appliedCoupon && (
              <Text style={[styles.couponHelper, { color: "#4CAF50" }]}>✓ Kupon uygulandı</Text>
            )}
          </View>
          {appliedCoupon ? (
            <TouchableOpacity
              style={styles.couponAppliedButton}
              onPress={() => { setAppliedCoupon(null); setCouponCode(""); }}
            >
              <Text style={styles.couponAppliedText}>Kaldır</Text>
            </TouchableOpacity>
          ) : (
            <TouchableOpacity style={styles.couponApplyButton} onPress={handleApplyCoupon}>
              <Text style={styles.couponApplyText}>Uygula</Text>
            </TouchableOpacity>
          )}
        </View>
        </ScrollView>
      </KeyboardAvoidingView>


      {/* Payment Modal */}
      <Modal
        visible={showPaymentModal}
        transparent={true}
        animationType="slide"
        onRequestClose={handleCancel}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContainer}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>Ödeme Onayı</Text>
              <TouchableOpacity onPress={handleCancel}>
                <Ionicons name="close" size={24} color="#333" />
              </TouchableOpacity>
            </View>
            <View style={styles.modalContent}>
              <Text style={styles.modalText}>
                {selectedPackage?.title} paketini satın almak istediğinizden
                emin misiniz?
              </Text>
              <Text style={styles.modalPrice}>
                Toplam: {selectedPackage?.currentPrice}
              </Text>
            </View>
            <View style={styles.modalButtons}>
              <TouchableOpacity
                style={styles.modalCancelButton}
                onPress={handleCancel}
              >
                <Text style={styles.modalCancelText}>İptal</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.modalConfirmButton}
                onPress={handlePayment}
              >
                <Text style={styles.modalConfirmText}>Onayla</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>

      {/* 3DS Modal */}
      <Modal
        visible={show3dsModal}
        transparent={false}
        animationType="slide"
        onRequestClose={() => setShow3dsModal(false)}
      >
        <SafeAreaView style={{ flex: 1, backgroundColor: "#fff" }}>
          <View style={{ height: 56, flexDirection: "row", alignItems: "center", paddingHorizontal: 12, borderBottomWidth: 1, borderBottomColor: "#eee" }}>
            <TouchableOpacity onPress={() => setShow3dsModal(false)} style={{ padding: 8 }}>
              <Ionicons name="close" size={24} color="#333" />
            </TouchableOpacity>
            <Text style={{ marginLeft: 8, fontWeight: "700", fontSize: 16 }}>3D Secure</Text>
          </View>
          <WebView
            originWhitelist={["*"]}
            source={threeDSUrl ? { uri: threeDSUrl } : { html: threeDSHtml }}
            javaScriptEnabled
            domStorageEnabled
            startInLoadingState
            injectedJavaScript={`(function(){try{var t=document && document.body ? document.body.innerText||'' : ''; if(t){window.ReactNativeWebView.postMessage(JSON.stringify({text:t.slice(0,10000)}));}}catch(e){};})(); true;`}
            onNavigationStateChange={handleWebViewNavChange}
            onMessage={handleWebViewMessage}
          />
        </SafeAreaView>
      </Modal>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  headerContent: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginBottom: 0,
    paddingTop: 0,
    width: "100%",
  },
  backButton: {
    width: 40,
    height: 40,
    alignItems: "center",
    justifyContent: "center",
  },
  backButtonIcon: {
    width: 40,
    height: 40,
  },
  title: {
    ...title["M/Bold"],
    color: "#000",
  },
  container: {
    ...FLEX.fill,
    backgroundColor: "#F5F5F5",
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  mainScrollView: {
    flex: 1,
    marginBottom: 0,
  },
  mainScrollContent: {
    paddingBottom: 32,
  },
  couponFooter: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 20,
    paddingVertical: 12,
    backgroundColor: "#fff",
    borderTopWidth: 1,
    borderTopColor: "#EEE",
    gap: 12,
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingHorizontal: 20,
    paddingVertical: 8,
    backgroundColor: "#F5F5F5",
  },
  greeting: {
    fontSize: 20,
    fontWeight: "700",
    color: "#333",
  },
  logoContainer: {
    width: 60,
    height: 60,
    borderRadius: 30,
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
  },
  logo: {
    width: 50,
    height: 50,
  },
  logoText: {
    fontSize: 12,
    fontWeight: "700",
    color: "#fff",
    textAlign: "center",
    lineHeight: 14,
  },
  logoCheck: {
    position: "absolute",
    bottom: 4,
    right: 4,
    backgroundColor: "#4CAF50",
    borderRadius: 8,
    width: 16,
    height: 16,
    textAlign: "center",
    lineHeight: 16,
  },
  characterSection: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    paddingHorizontal: 20,
    paddingVertical: 10,
    backgroundColor: "#F5F5F5",
  },
  characterImage: {
    width: 84,
    height: 100,
    marginRight: 16,
  },
  chatBubble: {
    flex: 1,
    backgroundColor: "#26252A",
    borderRadius: 20,
    borderBottomLeftRadius: 4,
    padding: 16,
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  chatText: {
    fontSize: 14,
    color: "#FFF",
    lineHeight: 20,
  },
  
  packagesContainer: {
    height: 420,
  },
  
  packagesContent: {
    paddingHorizontal: 20,
    paddingBottom: 20,
  },
  couponRow: {
    flexDirection: "row",
    alignItems: "flex-end",
    paddingHorizontal: 20,
    marginTop: 8,
    marginBottom: 12,
    gap: 10,
  },
  couponInputContainer: {
    flex: 1,
    backgroundColor: COLOR_SCALES.white.white,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: COLOR_SCALES.colorGray[30],
    paddingHorizontal: 12,
    paddingVertical: 8,
  },
  couponLabel: {
    fontSize: 12,
    fontWeight: "600",
    color: COLOR_SCALES.colorGray[90],
    marginBottom: 6,
  },
  couponTextInput: {
    height: 40,
    borderRadius: 6,
    borderWidth: 1,
    borderColor: COLOR_SCALES.colorGray[30],
    backgroundColor: COLOR_SCALES.white.white,
    paddingHorizontal: 12,
    paddingVertical: 8,
    color: COLOR_SCALES.colorGray[90],
    fontSize: 14,
    lineHeight: 20,
    textAlignVertical: "center",
  },
  couponHelper: {
    fontSize: 11,
    color: COLOR_SCALES.colorGray[50],
    marginTop: 4,
  },
  couponAppliedButton: {
    width: 110,
    height: 56,
    borderRadius: 10,
    borderWidth: 2,
    borderColor: COLOR_SCALES.primary[60],
    backgroundColor: COLOR_SCALES.primary[10],
    alignItems: "center",
    justifyContent: "center",
  },
  couponAppliedText: {
    fontSize: 14,
    fontWeight: "700",
    color: COLOR_SCALES.primary[70],
  },
  couponApplyButton: {
    width: 110,
    height: 56,
    borderRadius: 10,
    borderWidth: 2,
    borderColor: "#420F1B",
    backgroundColor: "#FF0025",
    alignItems: "center",
    justifyContent: "center",
  },
  couponApplyText: {
    fontSize: 14,
    fontWeight: "700",
    color: "#fff",
  },
  packageCard: {
    width: 300,
    minHeight: 420,
    backgroundColor: "#fff",
    borderRadius: 20,
    padding: 20,
    marginRight: 20,
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 4,
    },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 5,
    position: "relative",
    justifyContent: "space-between",
    flexDirection: "column",
  },
  appStoreBadge: {
    alignSelf: 'flex-start',
    backgroundColor: "#fff",
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    borderWidth: 1.5,
    borderColor: "#000",
    flexDirection: "row",
    alignItems: "center",
    gap: 6,
    marginBottom: 16,
  },
  appStoreIcon: {
    marginRight: 2,
  },
  appStoreText: {
    fontSize: 13,
    fontWeight: "700",
    color: "#000",
    letterSpacing: 0.3,
  },
  packageTitle: {
    fontSize: 20,
    fontWeight: "700",
    color: "#000",
    marginBottom: 4,
  },
  packageSubtitle: {
    fontSize: 14,
    fontWeight: "400",
    color: "#666",
    marginBottom: 16,
  },
  packageFeatures: {
    flex: 1,
    marginBottom: 20,
  },
  featureItem: {
    flexDirection: "row",
    alignItems: "flex-start",
    marginBottom: 8,
  },
  featureText: {
    fontSize: 14,
    color: "#666",
    marginLeft: 8,
    flex: 1,
    lineHeight: 20,
  },
  priceSection: {
    borderTopWidth: 1,
    borderTopColor: "#F0F0F0",
    paddingTop: 16,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  priceContainer: {
    flexDirection: "row",
    alignItems: "center",
    flex: 1,
  },
  currentPrice: {
    fontSize: 18,
    fontWeight: "700",
    color: "#E50012",
  },
  originalPrice: {
    fontSize: 14,
    color: "#999",
    textDecorationLine: "line-through",
  },
  ownedBadge: {
    flexDirection: "row",
    alignItems: "center",
    gap: 6,
    paddingVertical: 8,
    paddingHorizontal: 14,
    borderRadius: 20,
    borderWidth: 2,
    borderColor: COLOR_SCALES.primary[60],
    backgroundColor: COLOR_SCALES.primary[10],
  },
  ownedBadgeText: {
    fontSize: 14,
    fontWeight: "700",
    color: COLOR_SCALES.primary[70],
  },
  ownedActions: {
    alignItems: "flex-end",
    gap: 10,
    maxWidth: "52%",
  },
  cancelSubButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    gap: 6,
    backgroundColor: "#FFFFFF",
    paddingVertical: 10,
    paddingHorizontal: 14,
    borderRadius: 20,
    borderWidth: 2,
    borderColor: "#B4001A",
    shadowColor: "#B4001A",
    shadowOffset: { width: 1, height: 1 },
    shadowOpacity: 0.25,
    shadowRadius: 0,
    elevation: 2,
  },
  cancelSubButtonText: {
    color: "#B4001A",
    fontSize: 12,
    fontWeight: "700",
  },
  buyButton: {
    backgroundColor: "#FF0025",
    paddingVertical: 10,
    paddingHorizontal: 36,
    borderRadius: 20,
    borderWidth: 2,
    borderColor: "#420F1B",
    alignItems: "center",
    shadowColor: "#DB0020",
    shadowOffset: {
      width: 2,
      height: 2,
    },
    shadowOpacity: 1,
    shadowRadius: 0,
    elevation: 4,
  },
  buyButtonDisabled: {
    backgroundColor: "#999",
    borderColor: "#666",
    shadowColor: "#666",
  },
  buyButtonText: {
    color: "#FFFFFF",
    fontSize: 14,
    fontWeight: "700",
    fontFamily: "Rubik",
    lineHeight: 20,
  },
  buyButtonContent: {
    flexDirection: "row",
    alignItems: "center",
    gap: 6,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: "rgba(0, 0, 0, 0.5)",
    justifyContent: "center",
    alignItems: "center",
  },
  modalContainer: {
    backgroundColor: "#fff",
    borderRadius: 20,
    padding: 20,
    width: "90%",
    maxWidth: 400,
  },
  modalHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 20,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: "700",
    color: "#333",
  },
  modalContent: {
    marginBottom: 20,
  },
  modalText: {
    fontSize: 16,
    color: "#666",
    lineHeight: 22,
    marginBottom: 12,
  },
  modalPrice: {
    fontSize: 20,
    fontWeight: "700",
    color: "#E50012",
  },
  modalButtons: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  modalCancelButton: {
    flex: 1,
    paddingVertical: 12,
    borderRadius: 12,
    marginRight: 8,
    alignItems: "center",
    borderRadius: 24,
    border: 2,
    borderColor: COLOR_SCALES.primary[100],
    backgroundColor: COLOR_SCALES.white.white,
    boxShadow: "0 1px 0 0 #FFF inset, 2px 2px 0 0 #DB0020",
  },
  modalCancelText: {
    fontSize: 16,
    fontWeight: "600",
    color: COLOR_SCALES.primary[50],
  },
  modalConfirmButton: {
    flex: 1,
    paddingVertical: 12,
    borderRadius: 12,
    marginLeft: 8,
    alignItems: "center",
    borderRadius: 24,
    border: 2,
    borderColor: COLOR_SCALES.primary[100],
    backgroundColor: COLOR_SCALES.primary[60],
    boxShadow: "0 1px 0 0 #FFF inset, 2px 2px 0 0 #DB0020",
  },
  modalConfirmText: {
    fontSize: 16,
    fontWeight: "600",
    color: "#fff",
  },
  logoSmall: {
    width: 60,
    height: 60,
  },
  legalLinksContainer: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    marginTop: 12,
    marginBottom: 16,
    paddingTop: 0,
  },
  legalLink: {
    paddingHorizontal: 4,
  },
  legalLinkText: {
    fontSize: 11,
    color: "#666",
    textDecorationLine: "underline",
  },
  legalSeparator: {
    fontSize: 11,
    color: "#999",
    marginHorizontal: 8,
  },
  dateInfoContainer: {
    marginTop: 12,
    marginBottom: 16,
    paddingVertical: 8,
    paddingHorizontal: 12,
    backgroundColor: "#F8F8F8",
    borderRadius: 8,
    gap: 6,
  },
  dateRow: {
    flexDirection: "row",
    alignItems: "center",
    gap: 6,
  },
  dateLabel: {
    fontSize: 11,
    color: "#666",
    fontWeight: "600",
  },
  dateValue: {
    fontSize: 11,
    color: "#333",
    fontWeight: "400",
  },
});

export default PackagesScreen;
