package com.tt.honeyDue.platform

import android.app.Activity
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import com.tt.honeyDue.ui.subscription.UpgradeScreen
import kotlinx.coroutines.launch

@Composable
actual fun PlatformUpgradeScreen(
    onNavigateBack: () -> Unit,
    onSubscriptionChanged: () -> Unit
) {
    val context = LocalContext.current
    val activity = context as? Activity
    val billingManager = remember { BillingManager.getInstance(context) }
    val scope = rememberCoroutineScope()

    // Load products on launch
    LaunchedEffect(Unit) {
        billingManager.startConnection(
            onSuccess = {
                scope.launch { billingManager.loadProducts() }
            }
        )
    }

    // Watch for successful purchase
    val purchasedProductIDs by billingManager.purchasedProductIDs.collectAsState()
    var initialPurchaseCount by remember { mutableStateOf(purchasedProductIDs.size) }

    LaunchedEffect(purchasedProductIDs) {
        if (purchasedProductIDs.size > initialPurchaseCount) {
            onSubscriptionChanged()
            onNavigateBack()
        }
    }

    UpgradeScreen(
        onNavigateBack = onNavigateBack,
        onPurchase = { planId ->
            val product = billingManager.getProduct(planId)
            if (product != null && activity != null) {
                billingManager.launchPurchaseFlow(activity, product)
            }
        },
        onRestorePurchases = {
            scope.launch {
                val restored = billingManager.restorePurchases()
                if (restored) {
                    onSubscriptionChanged()
                    onNavigateBack()
                }
            }
        }
    )
}
