/** @odoo-module **/

import publicWidget from "@web/legacy/js/public/public_widget";

publicWidget.registry.TimezoneAutoDetect = publicWidget.Widget.extend({
    selector: 'body',

    start() {
        this._super(...arguments);
        this._detectAndSaveTimezone();
    },

    _detectAndSaveTimezone() {
        let detectedTz;
        try {
            detectedTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
        } catch {
            return;
        }
        if (!detectedTz) return;

        const cookieTz = this._getCookie('tz');
        if (cookieTz === detectedTz) return;

        document.cookie = `tz=${detectedTz};path=/;max-age=${60 * 60 * 24 * 365};SameSite=Lax`;

        this._rpc('/my/timezone/detect', { timezone: detectedTz }).catch(() => {});
    },

    _getCookie(name) {
        const match = document.cookie.match(new RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
        return match ? decodeURIComponent(match[1]) : null;
    },
});
