import $ from 'jquery'
import('bootstrap');

$(function () {
    var getLang = function () {
        if (window.location.href.indexOf("/de/") > -1) {
            return 'de';
        }
        if (window.location.href.indexOf("/en/") > -1) {
            return 'en';
        }
        if (window.location.href.indexOf("/es/") > -1) {
            return 'es';
        }
        if (window.location.href.indexOf("/ru/") > -1) {
            return 'ru';
        }
        return 'de';
    };


    $('#payment_information_iban').on('input', function () {
        var $form = $('form[name="payment_information"]');
        if (!$form.length) return;
        var iban = $('#payment_information_iban').val();
        var ibanStr = typeof iban === 'string' ? iban : (Array.isArray(iban) ? (iban[0] || '') : String(iban || ''));
        var url = '/app/' + getLang() + '/payment/check-iban?iban=' + encodeURIComponent(ibanStr);
        $('#output_iban_error').load(url, function (response, status) {
            if (status !== 'success') {
                $form.find(':input').prop('disabled', false);
                return;
            }
            var isInvalid = response && response.indexOf('alert alert-danger') > -1;
            if (isInvalid) {
                $form.find(':input').prop('disabled', true);
                $('#payment_information_iban').prop('disabled', false).trigger('focus');
            } else {
                $form.find(':input').prop('disabled', false);
            }
        });
    });

    // Promo code: in right card; Apply button validates and shows final price message
    var promoCodeTimeout: ReturnType<typeof setTimeout> | null = null;
    var $promoInput = $('.js-promo-code-input');
    var $planContainer = $('.your-plan-container[data-original-price]');
    var $priceDisplay = $('.js-price-display');
    var $promoSection = $('.promo-code-section');
    var $promoMessage = $('.js-promo-message');
    // Use delegation so Apply works even if elements load in different order
    $(document).on('click', '.js-apply-promo', function (e) {
        e.preventDefault();
        var $btn = $(this);
        var $section = $btn.closest('.promo-code-section');
        var $container = $section.closest('.your-plan-container');
        var $input = $section.find('.js-promo-code-input');
        var $priceDisplay = $container.find('.js-price-display');
        var $message = $section.find('.js-promo-message');
        if (!$container.length || !$priceDisplay.length || !$input.length) return;
        var code = ($input.val() as string || '').trim();
        var originalPriceStr = $container.attr('data-original-price');
        var originalPrice = originalPriceStr ? parseFloat(originalPriceStr) : 0;
        var interval = $container.attr('data-interval') || '';
        var plan = $container.attr('data-plan') || '';
        var msgApplied = $section.attr('data-msg-applied') || 'Promo applied! Final price: €%price%';
        var msgInvalid = $section.attr('data-msg-invalid') || 'Invalid or expired promo code.';

        var setPrice = function (val: number) {
            $priceDisplay.text('€' + (typeof val === 'number' && !isNaN(val) ? val.toFixed(2) : String(originalPrice)));
        };
        var showMsg = function (text: string, ok: boolean) {
            $message.removeClass('text-success text-danger').addClass(ok ? 'text-success' : 'text-danger').text(text);
        };

        if (!code) {
            $message.removeClass('text-success text-danger').text('');
            setPrice(originalPrice);
            return;
        }

        var base = '/app/' + getLang() + '/payment/validate-promo-code';
        var params = 'code=' + encodeURIComponent(code) + '&originalPrice=' + encodeURIComponent(String(originalPrice));
        if (interval) params += '&interval=' + encodeURIComponent(interval);
        if (plan) params += '&plan=' + encodeURIComponent(plan);
        $.ajax({ url: base + '?' + params, method: 'GET', dataType: 'json' })
            .done(function (data: { valid?: boolean; discountedPrice?: number }) {
                if (data.valid === true && typeof data.discountedPrice === 'number') {
                    setPrice(data.discountedPrice);
                    showMsg(msgApplied.replace('%price%', data.discountedPrice.toFixed(2)), true);
                } else {
                    setPrice(originalPrice);
                    showMsg(msgInvalid, false);
                }
            })
            .fail(function () {
                setPrice(originalPrice);
                showMsg(msgInvalid, false);
            });
    });

    if ($promoInput.length && $planContainer.length && $priceDisplay.length && $promoMessage.length) {
        var originalPriceStr = $planContainer.attr('data-original-price');
        var originalPrice = originalPriceStr ? parseFloat(originalPriceStr) : 0;
        var interval = $planContainer.attr('data-interval') || '';
        var plan = $planContainer.attr('data-plan') || '';
        var msgApplied = $promoSection.attr('data-msg-applied') || 'Promo applied! Final price: €%price%';
        var msgInvalid = $promoSection.attr('data-msg-invalid') || 'Invalid or expired promo code.';

        var setPrice = function (value: number, formatted: string) {
            $priceDisplay.text('€' + (typeof value === 'number' && !isNaN(value) ? value.toFixed(2) : formatted));
        };

        var resetPrice = function () {
            setPrice(originalPrice, originalPriceStr || '0');
        };

        var showPromoMessage = function (text: string, isSuccess: boolean) {
            $promoMessage.removeClass('text-success text-danger').addClass(isSuccess ? 'text-success' : 'text-danger').text(text);
        };

        var clearPromoMessage = function () {
            $promoMessage.removeClass('text-success text-danger').text('');
        };

        var doValidate = function (code: string, onSuccess: (discountedPrice: number) => void, onError: () => void) {
            var base = '/app/' + getLang() + '/payment/validate-promo-code';
            var params = 'code=' + encodeURIComponent(code) + '&originalPrice=' + encodeURIComponent(String(originalPrice));
            if (interval) params += '&interval=' + encodeURIComponent(interval);
            if (plan) params += '&plan=' + encodeURIComponent(plan);
            $.ajax({ url: base + '?' + params, method: 'GET', dataType: 'json' })
                .done(function (data: { valid?: boolean; discountedPrice?: number }) {
                    if (data.valid === true && typeof data.discountedPrice === 'number') {
                        setPrice(data.discountedPrice, data.discountedPrice.toFixed(2));
                        onSuccess(data.discountedPrice);
                    } else {
                        resetPrice();
                        onError();
                    }
                })
                .fail(function () {
                    resetPrice();
                    onError();
                });
        };

        $promoInput.on('input', function () {
            var code = ($(this).val() as string || '').trim();
            if (promoCodeTimeout) clearTimeout(promoCodeTimeout);
            if (!code) {
                resetPrice();
                clearPromoMessage();
                return;
            }
            promoCodeTimeout = setTimeout(function () {
                doValidate(code, function () {}, function () {});
            }, 400);
        });
    }

});