@using BTCPayServer.Abstractions.TagHelpers
@using BTCPayServer.Payments
@using BTCPayServer.Plugins.FixedFloat
@inject FixedFloatService FixedFloatService
@model BTCPayServer.Models.InvoicingModels.CheckoutModel 
@{
    var storeId = Model.StoreId;
    var settings = await FixedFloatService.GetFixedFloatForStore(storeId);
    var preferredTargetPaymentMethodId =  
        string.IsNullOrEmpty(settings?.PreferredTargetPaymentMethodId) ? null :
        Model.AvailablePaymentMethods.Any(crypto => crypto.PaymentMethodId.ToString() == PaymentMethodId.TryParse(settings.PreferredTargetPaymentMethodId)?.ToString()) ? 
            settings.PreferredTargetPaymentMethodId : null;
}
@if (settings?.Enabled is true)
{
    <template id="fixed-float-checkout-template">
        <iframe v-if="shown" :src="url" style="
        min-height:600px;
        border:none;
        width: calc(var(--wrap-max-width) - var(--btcpay-space-m) - var(--btcpay-space-m));
        margin-left: calc(var(--tile-padding) * -1);" allowtransparency="true" ref="iframe"></iframe>
    </template>
    <script>
        const markupPercentage = @settings.AmountMarkupPercentage;
        Vue.component("FixedFloatCheckout", {
            template: "#fixed-float-checkout-template",
            props: ["model"],
            data: function() {
                return {
                    explicitId: "",
                    preferredToCurrency: @Json.Serialize(preferredTargetPaymentMethodId),
                }
            },
            created () {
                const self = this;
            	setInterval(function() {
            	        if ( self.explicitId === window.ffExplicitId) {
            	            return;
            	        }
            	        self.explicitId = window.ffExplicitId;            	 
                },200)
            },
            computed: {
                shown (){
                
                    const result =  this.$parent.paymentMethodId === "FixedFloat";
                    
                    if(this.preferredToCurrency && this.model.paymentMethodId !== this.preferredToCurrency){
                        if (this.model.onChainWithLnInvoiceFallback && this.model.paymentMethodId === "BTC-CHAIN"){
                            return result;
                        }
                        this.$parent.paymentMethodId = this.preferredToCurrency;
                        this.$parent.fetchData().then(()=> {
                            this.$parent.paymentMethodId = "FixedFloat";
                        });
                        return false;
                    }
                    return result;
                },
                lightning () {
                    if (!this.model.onChainWithLnInvoiceFallback || this.model.paymentMethodId !== "BTC-CHAIN"){
                        return null;
                    }
                    const index = this.model.invoiceBitcoinUrl.indexOf("lightning=");
                    if (index === -1){
                        return null;
                    }
                    return this.model.invoiceBitcoinUrl.slice(index + "lightning=".length);
                },
                url () {
                    debugger;
                    const address=  this.lightning || this.model.address;
                    return "https://widget.ff.io/?" +
                        `to=${this.settleMethodId}` + 
                        "&lockReceive=true&ref=fkbyt39c" +
                        `&address=${address}` +
                        this.amountQuery +
                        this.explicitQuery;
                },
                currency () {
                    return this.model.paymentMethodId;
                },
                settleMethodId () {
                    return this.currency.endsWith('LN') || this.currency.endsWith('LNURL') || this.lightning
                        ? 'BTCLN'
                        : this.currency.replace('-CHAIN', '').replace('_CHAIN', '').toUpperCase();
                },
                explicitQuery (){
                    const isExplicit = !!this.explicitId;
                    const explicitFrom = isExplicit ? this.explicitId.replace('ff_', ''): null;
                    return isExplicit? `&from=${explicitFrom}&lockSend=true` : '';
                },
                amountQuery () {
                    return this.model.isUnsetTopUp
                        ? ''
                        : `&lockType=true&hideType=true&lockAmount=true&toAmount=${this.amountDue}`;
                },
                amountDue () {
                    return this.model.due * (1 + (markupPercentage / 100));
                }
            }
        });
    </script>
}
