// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/cr_components/localized_link/localized_link.js';
import 'chrome://resources/cr_elements/cr_radio_button/cr_radio_button.js';
import 'chrome://resources/cr_elements/cr_radio_group/cr_radio_group.js';
import '//resources/cr_elements/cr_icon/cr_icon.js';
import './icons.html.js';
import './supported_links_dialog.js';
import './supported_links_overlapping_apps_dialog.js';
import { WindowMode } from 'chrome://resources/cr_components/app_management/app_management.mojom-webui.js';
import { browserProxyFactory } from 'chrome://resources/cr_components/app_management/app_management.mojom-webui.js';
import { AppManagementUserAction } from 'chrome://resources/cr_components/app_management/constants.js';
import { castExists, recordAppManagementUserAction } from 'chrome://resources/cr_components/app_management/util.js';
import { I18nMixinLit } from 'chrome://resources/cr_elements/i18n_mixin_lit.js';
import { assert } from 'chrome://resources/js/assert.js';
import { focusWithoutInk } from 'chrome://resources/js/focus_without_ink.js';
import { loadTimeData } from 'chrome://resources/js/load_time_data.js';
import { CrLitElement } from 'chrome://resources/lit/v3_0/lit.rollup.js';
import { getCss } from './supported_links_item.css.js';
import { getHtml } from './supported_links_item.html.js';
import { createDummyApp } from './web_app_settings_utils.js';
const PREFERRED_APP_PREF = 'preferred';
const SupportedLinksItemElementBase = I18nMixinLit(CrLitElement);
export class SupportedLinksItemElement extends SupportedLinksItemElementBase {
    static get is() {
        return 'app-management-supported-links-item';
    }
    static get styles() {
        return getCss();
    }
    render() {
        return getHtml.bind(this)();
    }
    static get properties() {
        return {
            app: { type: Object },
            hidden: {
                type: Boolean,
                reflect: true,
            },
            disabled_: { type: Boolean },
            showSupportedLinksDialog_: { type: Boolean },
            showOverlappingAppsDialog_: { type: Boolean },
            overlappingAppsWarning_: { type: String },
            showOverlappingAppsWarning_: {
                type: Boolean,
                reflect: true,
            },
            apps: { type: Object },
            overlappingAppIds_: { type: Array },
        };
    }
    #app_accessor_storage = createDummyApp();
    get app() { return this.#app_accessor_storage; }
    set app(value) { this.#app_accessor_storage = value; }
    #apps_accessor_storage = {};
    get apps() { return this.#apps_accessor_storage; }
    set apps(value) { this.#apps_accessor_storage = value; }
    #hidden_accessor_storage = false;
    get hidden() { return this.#hidden_accessor_storage; }
    set hidden(value) { this.#hidden_accessor_storage = value; }
    #disabled__accessor_storage = false;
    get disabled_() { return this.#disabled__accessor_storage; }
    set disabled_(value) { this.#disabled__accessor_storage = value; }
    #overlappingAppsWarning__accessor_storage = '';
    get overlappingAppsWarning_() { return this.#overlappingAppsWarning__accessor_storage; }
    set overlappingAppsWarning_(value) { this.#overlappingAppsWarning__accessor_storage = value; }
    #overlappingAppIds__accessor_storage = [];
    get overlappingAppIds_() { return this.#overlappingAppIds__accessor_storage; }
    set overlappingAppIds_(value) { this.#overlappingAppIds__accessor_storage = value; }
    #showOverlappingAppsDialog__accessor_storage = false;
    get showOverlappingAppsDialog_() { return this.#showOverlappingAppsDialog__accessor_storage; }
    set showOverlappingAppsDialog_(value) { this.#showOverlappingAppsDialog__accessor_storage = value; }
    #showOverlappingAppsWarning__accessor_storage = false;
    get showOverlappingAppsWarning_() { return this.#showOverlappingAppsWarning__accessor_storage; }
    set showOverlappingAppsWarning_(value) { this.#showOverlappingAppsWarning__accessor_storage = value; }
    #showSupportedLinksDialog__accessor_storage = false;
    get showSupportedLinksDialog_() { return this.#showSupportedLinksDialog__accessor_storage; }
    set showSupportedLinksDialog_(value) { this.#showSupportedLinksDialog__accessor_storage = value; }
    willUpdate(changedProperties) {
        super.willUpdate(changedProperties);
        if (changedProperties.has('app')) {
            this.hidden = this.isHidden_();
            this.disabled_ = this.isDisabled_();
        }
        if (changedProperties.has('app') || changedProperties.has('apps')) {
            this.updateOverlappingAppsWarning_();
        }
    }
    /**
     * The supported links item is not available when an app has no supported
     * links.
     */
    isHidden_() {
        return !this.app.supportedLinks.length;
    }
    /**
     * Disable the radio button options if the app is a PWA and is set to open
     * in the browser.
     */
    isDisabled_() {
        return this.app.disableUserChoiceNavigationCapturing;
    }
    getCurrentPreferredApp_() {
        return this.app.isPreferredApp ? 'preferred' : 'browser';
    }
    getPreferredLabel_() {
        if (this.isBrowserTabAppSupportingExistingClient_()) {
            return this.i18n('appManagementIntentSharingOpenExistingTabLabel', String(this.app.title));
        }
        return this.i18n('appManagementIntentSharingOpenAppLabel', String(this.app.title));
    }
    getBrowserLabel_() {
        if (this.isBrowserTabAppSupportingExistingClient_()) {
            return this.i18n('appManagementIntentSharingOpenNewTabLabel');
        }
        return this.i18n('appManagementIntentSharingOpenBrowserLabel');
    }
    isBrowserTabAppSupportingExistingClient_() {
        return loadTimeData.getBoolean('updateAppStringsOnSettingsEnabled') &&
            this.app.windowMode === WindowMode.kBrowser &&
            !this.app.disableUserChoiceNavigationCapturing;
    }
    getDisabledExplanation_() {
        return this.i18nAdvanced('appManagementIntentSharingTabExplanation', { substitutions: [String(this.app.title)] });
    }
    async updateOverlappingAppsWarning_() {
        if (this.app.isPreferredApp) {
            this.showOverlappingAppsWarning_ = false;
            return;
        }
        let overlappingAppIds = [];
        try {
            const { appIds: appIds } = await browserProxyFactory.getInstance()
                .handler.getOverlappingPreferredApps(this.app.id);
            overlappingAppIds = appIds;
        }
        catch (err) {
            // If we fail to get the overlapping preferred apps, do not
            // show the overlap warning.
            console.warn(err);
            this.showOverlappingAppsWarning_ = false;
            return;
        }
        this.overlappingAppIds_ = overlappingAppIds;
        const appNames = overlappingAppIds.map(appId => this.apps[appId].title);
        if (appNames.length === 0) {
            this.showOverlappingAppsWarning_ = false;
            return;
        }
        switch (appNames.length) {
            case 1:
                assert(appNames[0]);
                this.overlappingAppsWarning_ = this.i18n('appManagementIntentOverlapWarningText1App', appNames[0]);
                break;
            case 2:
                this.overlappingAppsWarning_ = this.i18n('appManagementIntentOverlapWarningText2Apps', ...appNames);
                break;
            case 3:
                this.overlappingAppsWarning_ = this.i18n('appManagementIntentOverlapWarningText3Apps', ...appNames);
                break;
            case 4:
                this.overlappingAppsWarning_ = this.i18n('appManagementIntentOverlapWarningText4Apps', ...appNames.slice(0, 3));
                break;
            default:
                this.overlappingAppsWarning_ = this.i18n('appManagementIntentOverlapWarningText5OrMoreApps', ...appNames.slice(0, 3), appNames.length - 3);
                break;
        }
        this.showOverlappingAppsWarning_ = true;
    }
    /* Supported links list dialog functions ************************************/
    onLinkClicked_(e) {
        // A place holder href with the value "#" is used to have a compliant link.
        // This prevents the browser from navigating the window to "#"
        e.detail.event.preventDefault();
        e.stopPropagation();
        this.showSupportedLinksDialog_ = true;
        recordAppManagementUserAction(this.app.type, AppManagementUserAction.SUPPORTED_LINKS_LIST_SHOWN);
    }
    onDialogClose_() {
        this.showSupportedLinksDialog_ = false;
        focusWithoutInk(this.$.heading);
    }
    /* Preferred app state change dialog and related functions ******************/
    async onSupportedLinkPrefSelectedChanged_(event) {
        const preference = event.detail.value;
        const previous = this.getCurrentPreferredApp_();
        if (preference === previous) {
            return;
        }
        let overlappingAppIds = [];
        try {
            const { appIds: appIds } = await browserProxyFactory.getInstance()
                .handler.getOverlappingPreferredApps(this.app.id);
            overlappingAppIds = appIds;
        }
        catch (err) {
            // If we fail to get the overlapping preferred apps, don't prevent the
            // user from setting their preference.
            console.warn(err);
        }
        // If there are overlapping apps, show the overlap dialog to the user.
        if (preference === PREFERRED_APP_PREF && overlappingAppIds.length > 0) {
            this.overlappingAppIds_ = overlappingAppIds;
            this.showOverlappingAppsDialog_ = true;
            recordAppManagementUserAction(this.app.type, AppManagementUserAction.OVERLAPPING_APPS_DIALOG_SHOWN);
            return;
        }
        this.setAppAsPreferredApp_(preference);
    }
    onOverlappingDialogClose_() {
        this.showOverlappingAppsDialog_ = false;
        const overlapDialog = castExists(this.shadowRoot
            .querySelector('#overlapDialog'));
        if (overlapDialog.wasConfirmed()) {
            this.setAppAsPreferredApp_(PREFERRED_APP_PREF);
            // Return keyboard focus to the preferred radio button.
            focusWithoutInk(this.$.preferredRadioButton);
        }
        else {
            // Reset the radio button.
            this.shadowRoot.querySelector('#radioGroup').selected =
                this.getCurrentPreferredApp_();
            // Return keyboard focus to the browser radio button.
            focusWithoutInk(this.$.browserRadioButton);
        }
    }
    /**
     * Sets this.app as a preferred app or not depending on the value of
     * |preference|.
     */
    setAppAsPreferredApp_(preference) {
        const newState = preference === PREFERRED_APP_PREF;
        browserProxyFactory.getInstance().handler.setPreferredApp(this.app.id, newState);
        const userAction = newState ?
            AppManagementUserAction.PREFERRED_APP_TURNED_ON :
            AppManagementUserAction.PREFERRED_APP_TURNED_OFF;
        recordAppManagementUserAction(this.app.type, userAction);
    }
}
customElements.define(SupportedLinksItemElement.is, SupportedLinksItemElement);
