/** @odoo-module **/

import publicWidget from "@web/legacy/js/public/public_widget";
import { jsonrpc } from "@web/core/network/rpc_service";

publicWidget.registry.ServiceModeSelector = publicWidget.Widget.extend({
    selector: '#service_mode_selector',
    events: {
        'change input[name="fulfilment_type"]': '_onChangeServiceMode',
    },

    start: function () {
        // Init visual selection
        this.$('input[name="fulfilment_type"]:checked').closest('.service-option').find('.service-card')
            .css({ 'border-color': '#FECD4F', 'background-color': '#fffdf6', 'box-shadow': '0 4px 10px rgba(254, 205, 79, 0.2)' });
        return this._super.apply(this, arguments);
    },

    _onChangeServiceMode: function (ev) {
        var $input = $(ev.currentTarget);
        var mode = $input.val();

        // Reset styles
        this.$('.service-card').css({ 'border-color': '', 'background-color': '', 'box-shadow': '' });
        // Apply active styles
        $input.closest('.service-option').find('.service-card')
            .css({ 'border-color': '#FECD4F', 'background-color': '#fffdf6', 'box-shadow': '0 4px 10px rgba(254, 205, 79, 0.2)' });

        // Hide error if present
        this.$('#service_mode_error').addClass('d-none');

        // RPC Call to update order
        jsonrpc('/shop/update_service_mode', {
            service_mode: mode
        });
    }
});

// Intercept checkout to ensure a service mode is selected
publicWidget.registry.CartCheckoutValidation = publicWidget.Widget.extend({
    selector: '.oe_cart',
    events: {
        'click a[href="/shop/checkout"]': '_onCheckoutClicked',
    },

    _onCheckoutClicked: function (ev) {
        // If there's a selector on the page
        if (this.$('#service_mode_selector').length > 0) {
            var selectedMode = this.$('input[name="fulfilment_type"]:checked').val();
            if (!selectedMode) {
                ev.preventDefault();
                this.$('#service_mode_error').removeClass('d-none');

                // Highlight the box
                this.$('#service_mode_selector').css('border', '1px solid #dc3545').addClass('shake-animation');
                setTimeout(() => {
                    this.$('#service_mode_selector').removeClass('shake-animation');
                }, 500);
            }
        }
    }
});
