// Copyright 2026 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
 * @fileoverview 'settings-shopping-page', is a subpage of the "Your saved info"
 * section. It manages the user's autofill data for shopping. Users can view and
 * hide their saved orders and shipments as well as opt out of the autofill
 * functionality entirely.
 */
import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.js';
import '/shared/settings/controls/extension_controlled_indicator.js';
import '/shared/settings/prefs/prefs.js';
import '../autofill_page/autofill_ai_entries_list.js';
import '../autofill_page/your_saved_info_shared.css.js';
import '../controls/settings_toggle_button.js';
import '../settings_page/settings_subpage.js';
import '../settings_shared.css.js';
import { PrefsMixin } from '/shared/settings/prefs/prefs_mixin.js';
import { CrSettingsPrefs } from '/shared/settings/prefs/prefs_types.js';
import { PolymerElement } from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import { AiEnterpriseFeaturePrefName } from '../ai_page/constants.js';
import { EntityTypeName } from '../autofill_ai_enums.mojom-webui.js';
import { EntityDataManagerProxyImpl } from '../autofill_page/entity_data_manager_proxy.js';
import { loadTimeData } from '../i18n_setup.js';
import { routes } from '../route.js';
import { Router } from '../router.js';
import { SettingsViewMixin } from '../settings_page/settings_view_mixin.js';
import { checkAutofillPoliciesAndModifyPrefIfNecessary } from './policy_utils.js';
import { getTemplate } from './shopping_page.html.js';
const SettingsShoppingPageElementBase = SettingsViewMixin(PrefsMixin(PolymerElement));
export class SettingsShoppingPageElement extends SettingsShoppingPageElementBase {
    static get is() {
        return 'settings-shopping-page';
    }
    static get template() {
        return getTemplate();
    }
    static get properties() {
        return {
            enhancedAutofillEligibleUser_: {
                type: Boolean,
                value() {
                    return loadTimeData.getBoolean('userEligibleForAutofillAi');
                },
            },
            enhancedAutofillOptedIn_: {
                type: Boolean,
                value: false,
            },
            /**
               Whether the feature kAutofillAiAvailableByDefault is enabled. When
               enabled, users do not need to opt-in to enhanced Autofill to use
               Autofill AI.
             */
            autofillAiAvailableByDefault_: {
                type: Boolean,
                value() {
                    return loadTimeData.getBoolean('autofillAiAvailableByDefault');
                },
            },
            canEnableOrDisableAutofillAi_: {
                type: Boolean,
                value() {
                    return loadTimeData.getBoolean('canEnableOrDisableAutofillAi');
                },
            },
            /**
               Fake preference used by `this.$.optInToggle`. Shows value of
               `autofill.autofill_ai.shopping_entities_enabled` preference if toggle
               is enabled (clickable). If toggle is disabled then the value is
               overridden to be shown as false even if the preference is true.
             */
            shoppingOptedIn_: {
                type: Object,
                computed: `computeShoppingOptedIn_(enhancedAutofillEligibleUser_,
              enhancedAutofillOptedIn_,
              prefs.autofill.autofill_ai.shopping_entities_enabled,
              prefs.autofill.profile_enabled.value,
              prefs.${AiEnterpriseFeaturePrefName.AUTOFILL_AI},
              prefsInitialized_)`,
            },
            /**
              If true, Autofill AI does not depend on whether Autofill for addresses
              is enabled.
            */
            // TODO(crbug.com/466345561): remove when enhanced autofill will stop
            // depending on addresses autofill
            autofillAddOtherDatatypesPrefIsEnabled_: {
                type: Boolean,
                value() {
                    return loadTimeData.getBoolean('AutofillAddOtherDatatypesPrefIsEnabled');
                },
            },
            /**
             * Set to true once CrSettingsPrefs is fully initialized.
             * Guards against race conditions where prefs are accessed before the full
             * preference tree is populated.
             */
            prefsInitialized_: {
                type: Boolean,
                value: false,
            },
            showSuggestionsFromGeminiSettings_: {
                type: Boolean,
                value() {
                    return loadTimeData.getBoolean('showSuggestionsFromGeminiSettings');
                },
            },
        };
    }
    static get observers() {
        return [
            'onAutofillOptInStatusChange_(prefs.autofill.autofill_ai.opt_in_status)',
        ];
    }
    entityDataManager_ = EntityDataManagerProxyImpl.getInstance();
    connectedCallback() {
        super.connectedCallback();
        CrSettingsPrefs.initialized.then(() => {
            this.prefsInitialized_ = true;
        });
    }
    optInToggleDisabled_() {
        if (!this.prefsInitialized_) {
            return true;
        }
        const addressAutofillOptInStatus = this.getPref('autofill.profile_enabled').value;
        const ignoreAddressAutofill = this.autofillAddOtherDatatypesPrefIsEnabled_;
        if (this.autofillAiAvailableByDefault_) {
            return !this.canEnableOrDisableAutofillAi_ ||
                (!ignoreAddressAutofill && !addressAutofillOptInStatus);
        }
        const optInToggleEnabled = this.enhancedAutofillEligibleUser_ &&
            this.enhancedAutofillOptedIn_ &&
            (ignoreAddressAutofill || addressAutofillOptInStatus);
        return !optInToggleEnabled;
    }
    onAutofillOptInStatusChange_() {
        if (this.autofillAiAvailableByDefault_) {
            return;
        }
        this.entityDataManager_.getOptInStatus().then(status => {
            this.set('enhancedAutofillOptedIn_', status);
        });
    }
    computeShoppingOptedIn_() {
        const fakePref = {
            key: 'fake',
            type: chrome.settingsPrivate.PrefType.BOOLEAN,
            value: false,
        };
        if (!this.prefsInitialized_) {
            return fakePref;
        }
        fakePref.value =
            this.getPref('autofill.autofill_ai.shopping_entities_enabled')
                .value;
        if (this.optInToggleDisabled_()) {
            fakePref.value = false;
        }
        const addressPolicy = this.getPref('autofill.profile_enabled');
        const autofillAiPolicy = this.getPref(AiEnterpriseFeaturePrefName.AUTOFILL_AI);
        checkAutofillPoliciesAndModifyPrefIfNecessary(fakePref, addressPolicy, autofillAiPolicy);
        return fakePref;
    }
    onOptInToggleChange_() {
        this.setPrefValue('autofill.autofill_ai.shopping_entities_enabled', this.$.optInToggle.checked);
    }
    getAllowedEntityTypes_() {
        return new Set([EntityTypeName.kOrder, EntityTypeName.kShipment]);
    }
    extensionControlledIndicatorIsVisible_() {
        if (!this.prefsInitialized_) {
            return false;
        }
        const addressAutofillEnabled = this.getPref('autofill.profile_enabled');
        return !!addressAutofillEnabled.extensionId &&
            !addressAutofillEnabled.value;
    }
    onSuggestionsFromGeminiClick_() {
        // TODO(crbug.com/512204278): Add metrics.
        Router.getInstance().navigateTo(routes.SUGGESTIONS_FROM_GEMINI);
    }
    // SettingsViewMixin implementation.
    focusBackButton() {
        this.shadowRoot.querySelector('settings-subpage').focusBackButton();
    }
}
customElements.define(SettingsShoppingPageElement.is, SettingsShoppingPageElement);
