(function($) {
    var l10n = window.tipcgAdminL10n || {};

    function getText(key, fallback) {
        if (Object.prototype.hasOwnProperty.call(l10n, key) && l10n[key]) {
            return l10n[key];
        }

        return fallback;
    }

    function toggleTypeBlocks() {
        var type = $('.tipcg-countdown-type').val();
        $('.tipcg-type-block').removeClass('tipcg-active').hide();
        $('.tipcg-type-' + type).addClass('tipcg-active').show();
    }

    function isProTemplate(template) {
        return ['animated_flip', 'typewriter', 'paper'].indexOf(template) !== -1;
    }

    function updateLiteTemplateState() {
        $('.tipcg-template-select').each(function() {
            var $select = $(this);
            var template = ($select.val() || 'default').toString();
            var isUnavailable = isProTemplate(template);
            var $form = $select.closest('form');

            $select.closest('.input-right').find('.tipcg-template-pro-warning').toggle(isUnavailable);
            $form.find('.tipcg_save_countdown, .tipcg_save_countdown_exit').prop('disabled', isUnavailable);
        });
    }

    function updateTemplatePreview() {
        $('.ilrcp_template_preview').each(function() {
            var $preview = $(this);
            var $select = $preview.closest('.input-right').find('.tipcg-template-select');
            var template = ($select.val() || $preview.attr('data-template') || 'default').toString();
            var previewBase = ($preview.attr('data-preview-base') || '').toString();
            var imageUrl = '';

            if (['default', 'animated_flip', 'flip_clock', 'typewriter', 'paper'].indexOf(template) === -1) {
                template = 'default';
            }

            if (previewBase) {
                imageUrl = previewBase.replace(/\/?$/, '/') + template + '.gif';
            }

            $preview
                .attr('data-template', template)
                .attr('data-preview-url', imageUrl)
                .empty()
                .css('background-image', imageUrl ? 'url("' + imageUrl + '")' : '');
        });
    }

    function updateRangeProgress($input) {
        var min = parseFloat($input.attr('min'));
        var max = parseFloat($input.attr('max'));
        var value = parseFloat($input.val());
        var progress = 0;

        if (!isNaN(min) && !isNaN(max) && max > min && !isNaN(value)) {
            progress = ((value - min) / (max - min)) * 100;
        }

        progress = Math.max(0, Math.min(100, progress));
        $input.css('--tipcg-range-progress', progress + '%');
    }

    function updateRangeValue($input) {
        var fieldId = $input.attr('id');
        var suffix = $input.data('suffix') || '';

        updateRangeProgress($input);

        if (fieldId) {
            $('.tipcg-range-value[data-for="' + fieldId + '"]').text($input.val() + suffix);
        }
    }

    $(document).ready(function() {
        toggleTypeBlocks();
        updateTemplatePreview();
        updateLiteTemplateState();
        $('.tipcg-range-input').each(function() {
            updateRangeValue($(this));
        });

        $(document).on('change', '.tipcg-countdown-type', toggleTypeBlocks);
        $(document).on('change', '.tipcg-template-select', function() {
            updateTemplatePreview();
            updateLiteTemplateState();
        });
        $(document).on('click', '.tipcg_save_countdown, .tipcg_save_countdown_exit', function() {
            var template = ($('.tipcg-template-select').first().val() || 'default').toString();

            if (isProTemplate(template)) {
                window.alert(getText('templateProUnavailable', 'The selected template is available in the Pro version.'));
                return false;
            }
        });
        $(document).on('input change', '.tipcg-range-input', function() {
            updateRangeValue($(this));
        });
        $(document).on('focus click', '.tipcg-countdown-shortcode-field', function() {
            this.select();
        });

        $('.tipcg_panel_message').delay(1000).fadeOut(1000);

        if ($.fn.wpColorPicker) {
            $('.tipcg-color-picker').wpColorPicker();
        }

        $('.tipcg_export_settings').on('click', function() {
            if (!window.confirm(getText('confirmExportSettings', 'Do you want to export the plugin settings?'))) {
                return false;
            }
        });

        $('.tipcg_restore_settings').on('click', function() {
            if (!window.confirm(getText('confirmRestoreSettings', 'Do you want to restore the plugin settings?'))) {
                return false;
            }
        });

        // Datepicker fallback for browsers that do not support datetime-local.
        $('.tipcg-datetime').each(function() {
            var $field = $(this);
            if ($field.attr('type') === 'text' && $.fn.datepicker) {
                $field.datepicker({
                    dateFormat: 'yy-mm-dd'
                });
            }
        });
    });
})(jQuery);
