import React, { useState, useEffect } from "react";
import {
  View,
  StyleSheet,
  Text,
  TouchableOpacity,
  ScrollView,
  Image,
  Modal,
  TextInput,
  KeyboardAvoidingView,
  Platform,
  ActivityIndicator,
} from "react-native";
import { StatusBar } from "expo-status-bar";
import { WebView } from "react-native-webview";
import { Buffer } from "buffer";
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 { useFocusEffect } from "@react-navigation/native";
import { title } from "@/theme/typography";
import { COLOR_SCALES } from "@/theme/colors";
import { getPackages, buyPackage, applyCoupon } 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 useGuest from "@/hooks/useGuest";

const PackagesScreen = () => {
  const router = useRouter();

  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [selectedPackage, setSelectedPackage] = useState(null);
  const [packages, setPackages] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [appliedCoupon, setAppliedCoupon] = useState(null);
  const [couponCode, setCouponCode] = useState("");
  const [show3dsModal, setShow3dsModal] = useState(false);
  const [threeDSHtml, setThreeDSHtml] = useState("");
  const [threeDSUrl, setThreeDSUrl] = useState("");
  const [threeDSHandled, setThreeDSHandled] = useState(false);

  const { toast, showSuccessToast, showErrorToast, hideToast } = useToast();
  const { isGuest, isLoading: isGuestLoading } = useGuest();
  const [guestToastShown, setGuestToastShown] = useState(false);

  // API'den paketleri çek
  const fetchPackages = React.useCallback(async () => {
    if (isGuest) {
      setIsLoading(false);
      setPackages([]);
      return;
    }
    try {
      setIsLoading(true);
      setError(null);
      const response = await getPackages();
      if (response?.success && response?.data) {
        setPackages(response.data);
      } else {
        throw new Error("Paketler yüklenemedi");
      }
    } catch (err) {
      setError(err);
    } finally {
      setIsLoading(false);
    }
  }, [isGuest]);

  useEffect(() => {
    fetchPackages();
  }, [fetchPackages]);

  // Sayfaya her odaklandığında paketleri yenile (satın alım sonrası "Aktif" görünsün)
  useFocusEffect(
    React.useCallback(() => {
      fetchPackages();
    }, [fetchPackages])
  );

  // Kuponu otomatik çek ve uygula - devre dışı
  // useEffect(() => { ... }, [isGuest]);

  useEffect(() => {
    if (isGuest && !guestToastShown) {
      showErrorToast({
        title: "Üye Ol Gerekli",
        message: "Paketleri görüntülemek ve satın almak için lütfen üye olun.",
      });
      setGuestToastShown(true);
    }
  }, [isGuest, guestToastShown, showErrorToast]);

  const handleBuyPackage = (packageData) => {
    if (isGuest) {
      showErrorToast({
        title: "Üye Ol Gerekli",
        message: "Misafir modunda paket satın alamazsınız.",
      });
      return;
    }
    setSelectedPackage(packageData);
    setShowPaymentModal(true);
  };

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

  const handlePayment = async () => {
    if (isGuest) {
      showErrorToast({
        title: "Üye Ol Gerekli",
        message: "Misafir modunda paket satın alamazsınız.",
      });
      return;
    }
    try {
      const payload = {
        packageId: selectedPackage?.id,
        couponId: appliedCoupon?.id ?? null,
        price: selectedPackage?.finalPrice ?? null,
      };
      const res = await buyPackage(payload);
      setShowPaymentModal(false);
      if (res?.success && res?.url) {
        setThreeDSHandled(false);
        setThreeDSUrl(res.url);
        setThreeDSHtml("");
        setShow3dsModal(true);
      } else 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);
  };

  const handleApplyCoupon = async () => {
    if (!couponCode.trim()) return;
    try {
      const res = await applyCoupon({ code: couponCode.trim() });
      if (res?.success && res?.data) {
        console.log("Kupon data:", JSON.stringify(res.data));
        setAppliedCoupon(res.data);
        showSuccessToast({ title: 'Kupon Uygulandı', message: 'İndirim uygulandı.' });
      } 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ı.' });
    }
  };

  // Tüm paketleri göster
  const packagesToShow = Array.isArray(packages) ? packages : [];

  // Paket verilerini formatla — appliedCoupon değişince yeniden hesapla
  const formattedPackages = React.useMemo(() => {
    return packagesToShow.map((pkg) => {
      const features = [];
      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);
        });
      }
      if (pkg?.items?.length > 0) {
        pkg.items.forEach(item => { if (item?.name) features.push(item.name); });
      }

      const originalBasePrice = Number(pkg?.price ?? 0);
      const discountPrice = pkg?.discountPrice != null ? Number(pkg.discountPrice) : null;
      const hasPackageDiscount = typeof discountPrice === 'number' && discountPrice > 0 && discountPrice < originalBasePrice;
      let finalPrice = hasPackageDiscount ? discountPrice : originalBasePrice;

      if (appliedCoupon) {
        const couponType = appliedCoupon?.type;
        const couponVal = Number(appliedCoupon?.price ?? 0);
        if (couponType === 1) {
          finalPrice = Math.max(0, finalPrice - couponVal);
        } else if (couponType === 2) {
          const percent = Math.min(100, Math.max(0, couponVal));
          finalPrice = Math.max(0, finalPrice - finalPrice * (percent / 100));
        }
      }

      return {
        id: pkg?.id,
        title: pkg?.name || 'Paket',
        badge: pkg?.title || '',
        features: features.length > 0 ? features : ['Detaylar için iletişime geçin'],
        currentPrice: `${finalPrice}₺`,
        finalPrice,
        originalPrice: finalPrice !== originalBasePrice ? `${originalBasePrice}₺` : null,
        owned: pkg?.hasPackage === true,
      };
    });
  }, [packagesToShow, appliedCoupon]);

  // Loading state
  if (isGuestLoading || isLoading) {
    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>
    );
  }

  // Misafir modu view
  if (isGuest) {
    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" />
        <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="Misafir Modu"
          description="Paketleri görüntülemek için üye olmanız gerekmektedir. Lütfen giriş yaparak tüm avantajlara erişin."
          icon={<Ionicons name="person-circle-outline" size={48} color={COLOR_SCALES.primary[40]} />}
        />
      </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={{ flex: 1 }}
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        keyboardVerticalOffset={Platform.OS === "ios" ? 0 : 20}
      >
      <ScrollView
        style={styles.mainScrollView}
        contentContainerStyle={styles.mainScrollContent}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
      >
        {/* 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}>
                  {formattedPackage.badge && (
                    <View style={styles.badgeContainer}>
                      <Text style={styles.badgeText}>{formattedPackage.badge}</Text>
                    </View>
                  )}

                  <Text style={styles.packageTitle}>{formattedPackage.title}</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>

                  <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.ownedBadge}>
                        <Ionicons name="checkmark-circle" size={16} color={COLOR_SCALES.primary[60]} />
                        <Text style={styles.ownedBadgeText}>Aktif</Text>
                      </View>
                    ) : (
                      <TouchableOpacity
                        style={styles.buyButton}
                        onPress={() => handleBuyPackage(formattedPackage)}
                        activeOpacity={0.8}
                      >
                        <Text style={styles.buyButtonText}>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"
            />
            {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",
  },
  mainScrollView: {
    flex: 1,
    marginBottom: 0,
  },
  mainScrollContent: {
    paddingBottom: 120,
  },
  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: 380,
  },
  
  packagesContent: {
    paddingHorizontal: 20,
    paddingBottom: 20,
  },
  couponRow: {
    flexDirection: "row",
    alignItems: "stretch",
    paddingHorizontal: 20,
    marginTop: 8,
    marginBottom: 12,
    gap: 10,
  },
  couponInputContainer: {
    flex: 1,
    backgroundColor: COLOR_SCALES.white.white,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: COLOR_SCALES.colorGray[60],
    paddingHorizontal: 10,
    paddingVertical: 6,
  },
  couponLabel: {
    fontSize: 12,
    fontWeight: "600",
    color: COLOR_SCALES.colorGray[90],
    marginBottom: 6,
  },
  couponTextInput: {
    height: 36,
    borderRadius: 6,
    borderWidth: 0,
    backgroundColor: COLOR_SCALES.white.white,
    paddingHorizontal: 8,
    paddingVertical: 6,
    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: 48,
    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: 48,
    borderRadius: 10,
    borderWidth: 2,
    borderColor: "#420F1B",
    backgroundColor: "#FF0025",
    alignItems: "center",
    justifyContent: "center",
  },
  couponApplyText: {
    fontSize: 14,
    fontWeight: "700",
    color: "#fff",
  },
  packageCard: {
    width: 300,
    minHeight: 360,
    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",
  },
  badgeContainer: {
    minWidth: 70,
    maxWidth: "50%",
    backgroundColor: "#fff",
    paddingHorizontal: 12,
    paddingVertical: 4,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: "#333",
  },
  badgeText: {
    fontSize: 12,
    fontWeight: "600",
    color: "#000",
  },
  packageTitle: {
    fontSize: 18,
    fontWeight: "700",
    color: "#333",
    marginTop: 10,
    marginBottom: 12,
  },
  packageFeatures: {
    flex: 1,
    marginBottom: 20,
  },
  featureItem: {
    flexDirection: "row",
    alignItems: "center",
  },
  featureText: {
    fontSize: 14,
    color: "#666",
    marginLeft: 8,
    flex: 1,
  },
  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],
  },
  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,
  },
  buyButtonText: {
    color: "#FFFFFF",
    fontSize: 14,
    fontWeight: "700",
    fontFamily: "Rubik",
    lineHeight: 20,
  },
  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,
  },
});

export default PackagesScreen;
