// Copyright 2025 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-identity-docs-page', is a subpage of the "Your saved
 * info" section. It manages the user's autofill data for identity documents.
 * Users can add, edit, or delete their saved document details, 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 { getTemplate } from './identity_docs_page.html.js';
import { checkAutofillPoliciesAndModifyPrefIfNecessary } from './policy_utils.js';
const SettingsIdentityDocsPageElementBase = SettingsViewMixin(PrefsMixin(PolymerElement));
export class SettingsIdentityDocsPageElement extends SettingsIdentityDocsPageElementBase {
    static get is() {
        return 'settings-identity-docs-page';
    }
    static get template() {
        return getTemplate();
    }
    static get properties() {
        return {
            /**
               Indicates if a user is eligible to change Enhanced Autofill data.
               If a user is not eligible for Enhanced Autofill (Autofill with Ai),
               but they have data saved, the code allows them only to edit and delete
               their data. They are not allowed to add new data, or to opt-in or
               opt-out of Enhanced Autofill using the corresponding toggle in this
               component. If a user is not eligible for Enhanced Autofill and they
               also have no data saved, then they cannot access this page at all.
             */
            enhancedAutofillEligibleUser_: {
                type: Boolean,
                value() {
                    return loadTimeData.getBoolean('userEligibleForAutofillAi');
                },
            },
            /**
               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');
                },
            },
            /**
             Controls whether the user can use Autofill AI (in this context, identity
             docs filling). As an example, this can be false if the extensions API
             disables the feature.
            */
            canEnableOrDisableAutofillAi_: {
                type: Boolean,
                value() {
                    return loadTimeData.getBoolean('canEnableOrDisableAutofillAi');
                },
            },
            enhancedAutofillOptedIn_: {
                type: Boolean,
                value: false,
            },
            /**
               Fake preference used by `this.$.optInToggle`. Stores the value of
               the `autofill.autofill_ai.identity_entities_enabled` preference if
               the toggle is enabled (clickable). If the toggle is disabled, then the
               value is overridden to be shown as false even if the preference is
               true.
             */
            identityDocsOptedIn_: {
                type: Object,
                computed: `computeIdentityDocsOptedIn_(enhancedAutofillEligibleUser_,
              enhancedAutofillOptedIn_,
              prefs.autofill.autofill_ai.identity_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');
                },
            },
            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);
        }
        // The identity docs opt-in toggle should be enabled (editable) when all
        // conditions are met:
        //  * User is eligible for enhanced autofill.
        //  * User is enrolled in enhanced autofill.
        //  * User is enrolled in address autofill (unless the experiment
        //    to ignore address autofill is active).
        const optInToggleEnabled = this.enhancedAutofillEligibleUser_ &&
            this.enhancedAutofillOptedIn_ &&
            (ignoreAddressAutofill || addressAutofillOptInStatus);
        return !optInToggleEnabled;
    }
    onAutofillOptInStatusChange_() {
        // If Autofill AI is enabled by default, there is no need to check the
        // opt-in status.
        if (this.autofillAiAvailableByDefault_) {
            return;
        }
        this.entityDataManager_.getOptInStatus().then(status => {
            this.set('enhancedAutofillOptedIn_', status);
        });
    }
    computeIdentityDocsOptedIn_() {
        const fakePref = {
            key: 'fake',
            type: chrome.settingsPrivate.PrefType.BOOLEAN,
            value: false,
        };
        if (!this.prefsInitialized_) {
            return fakePref;
        }
        fakePref.value =
            this.getPref('autofill.autofill_ai.identity_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.identity_entities_enabled', this.$.optInToggle.checked);
    }
    getAllowedEntityTypes_() {
        return new Set([
            EntityTypeName.kDriversLicense,
            EntityTypeName.kNationalIdCard,
            EntityTypeName.kPassport,
        ]);
    }
    getMetricEntityTypes_() {
        return {
            [EntityTypeName.kDriversLicense]: 'DriversLicense',
            [EntityTypeName.kNationalIdCard]: 'NationalIdCard',
            [EntityTypeName.kPassport]: 'Passport',
        };
    }
    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(SettingsIdentityDocsPageElement.is, SettingsIdentityDocsPageElement);
