import { copyToClipboard } from './utils/copy-to-clipboard';

var Wick = window.Wick || {};

Wick.TradeProRewards = {
    el: {
        $tradeProRewards: $('.page_tradePro-rewards'),
        buttonSelector: '.copy-tradePro-barcode',
    },

    message: 'Code copied to clipboard',
    errorMessage: 'Unable to copy. Please copy manually',

    copyToClipboardInit() {
        Wick.SnackBar.init();

        $(document).on('click', Wick.TradeProRewards.el.buttonSelector, async function (e) {
            e.preventDefault();
            e.stopPropagation();

            const $btn = $(this);
            const $input = $btn.parent().find('input');

            if (!$input.length) return false;

            const discountCodeValue = ($input.val() || '').trim();
            if (!discountCodeValue) return false;

            $input.removeAttr('disabled').attr('readonly', 'readonly');

            try {
                await copyToClipboard(discountCodeValue, e.currentTarget, { noUpperCase: true });

                Wick.SnackBar.show({
                    text: Wick.TradeProRewards.message,
                    type: Wick.SnackBar.types.SUCCESS,
                    withCloseButton: false,
                    autoClose: true,
                    delayBeforeClose: 3000,
                });
            } catch (err) {
                try {
                    const el = $input.get(0);
                    el.focus();
                    el.select();
                    el.setSelectionRange(0, 999999);
                } catch (e) {
                    console.error(e);
                }

                Wick.SnackBar.show({
                    text: Wick.TradeProRewards.errorMessage,
                    type: Wick.SnackBar.types.ERROR,
                    withCloseButton: false,
                    autoClose: true,
                    delayBeforeClose: 4000,
                });
            }

            $input.attr('disabled', 'disabled').removeAttr('readonly');
            window.getSelection()?.removeAllRanges?.();

            return false;
        });
    },

    init() {
        Wick.TradeProRewards.copyToClipboardInit();
    },
};

$(document).ready(function () {
    if (Wick.TradeProRewards.el.$tradeProRewards.length) {
        Wick.TradeProRewards.init();
    }
});
