/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

define([
    'jquery',
    'ko',
    'uiComponent',
    'mage/translate',
    'WriteTextAI_WriteTextAI/js/model/total-credits',
    'WriteTextAI_WriteTextAI/js/utils/total-credits',
    'WriteTextAI_WriteTextAI/js/utils/pro-badge',
], function ($, ko, Component, $t, totalCredits, totalCreditsUtils, proBadgeUtils) {
    'use strict';

    return Component.extend({
        defaults: {
            totalCredits: 0,
            availableCredits: "-",
            selectors: {
                tooltipSelector: '.wtai-credit-help-container .admin__field-tooltip-action'
            }
        },

        /** @inheritdoc */
        initialize: function () {
            this._super();

            self = this;

            this.initTooltip();

            totalCredits.totalCredits.subscribe(function (credits) {
                this.totalCredits(credits);
            }, this);

            totalCredits.availableCredits.subscribe(function (credits) {
                this.availableCredits(credits);
            }, this);

            this.initUpdatePremium();
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe([
                    'totalCredits',
                    'availableCredits'
                ]);

            this.getTotalCreditsText = ko.computed(function () {
                if (this.totalCredits() <= 1) {
                    return $t('%s credit available').replace('%s', this.totalCredits());
                }
                return $t('%s credits available').replace('%s', this.totalCredits());
            }, this);

            this.getAvailableCreditsText = ko.computed(function () {
                if (this.availableCredits() <= 1) {
                    return $t('%s credit available').replace('%s', this.availableCredits());
                }
                return $t('%s credits available').replace('%s', this.availableCredits());
            }, this);

            return this;
        },

        /**
         * Initialize tooltip
         */
        initTooltip: function () {
            $(self.selectors.tooltipSelector).dropdown({
                parent: '.admin__field-tooltip',
                autoclose: true
            });
        },

        /**
         * Initialize update premium
         */
        initUpdatePremium: function () {
            $(document).on("ajaxSuccess", function (event, jqXHR, ajaxOptions, data) {
                totalCreditsUtils.updatePremium(data);
                proBadgeUtils.updateProBadge(data);
            });
        }
    });
});
