// 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.
import '//resources/cr_components/composebox/composebox_dropdown.js';
import '//resources/cr_components/composebox/composebox_file_inputs.js';
import '//resources/cr_components/composebox/composebox_submit.js';
import '//resources/cr_components/composebox/contextual_entrypoint_and_menu.js';
import '//resources/cr_components/composebox/composebox_input.js';
import '//resources/cr_components/composebox/error_scrim.js';
import '//resources/cr_components/composebox/file_carousel.js';
import '//resources/cr_components/composebox/composebox_tool_chip.js';
import '//resources/cr_elements/cr_icon_button/cr_icon_button.js';
import '//resources/cr_components/composebox/composebox_voice_search.js';
import '//resources/cr_components/search/animated_glow.js';
import '//resources/cr_components/localized_link/localized_link.js';
import { getLoadTimeBoolean } from '//resources/cr_components/composebox/common.js';
import { ComposeboxEmbedderMixin } from '//resources/cr_components/composebox/composebox_mixin.js';
import { ComposeboxProxyImpl } from '//resources/cr_components/composebox/composebox_proxy.js';
import { GlowAnimationState } from '//resources/cr_components/search/constants.js';
import { EventTracker } from '//resources/js/event_tracker.js';
import { CrLitElement } from '//resources/lit/v3_0/lit.rollup.js';
import { InputSource, QueryActionOverride } from './fusebox_action.mojom-webui.js';
import { getCss } from './ntp_composebox.css.js';
import { getHtml } from './ntp_composebox.html.js';
export class NtpComposeboxElement extends ComposeboxEmbedderMixin(CrLitElement) {
    static get is() {
        return 'ntp-composebox';
    }
    static get styles() {
        return getCss();
    }
    render() {
        return getHtml.bind(this)();
    }
    static get properties() {
        return {
            entrypointName: { type: String, reflect: true },
            /*
            `expanding_` property is used in composebox.css styles. It is added
            so that the imported styles work well. Remove this property once each
            embedder has its own styles.
            */
            expanding_: {
                reflect: true,
                type: Boolean,
            },
            shouldRemainFolded_: {
                reflect: true,
                type: Boolean,
            },
            isDark: {
                reflect: true,
                type: Boolean,
            },
        };
    }
    #isDark_accessor_storage = false;
    get isDark() { return this.#isDark_accessor_storage; }
    set isDark(value) { this.#isDark_accessor_storage = value; }
    #entrypointName_accessor_storage = 'Realbox';
    get entrypointName() { return this.#entrypointName_accessor_storage; }
    set entrypointName(value) { this.#entrypointName_accessor_storage = value; }
    searchboxCallbackRouter_;
    pageHandler_;
    searchboxHandler_;
    eventTracker_ = new EventTracker();
    // Chip suggestion shown as the input placeholder while a hint action is
    // active. Set or replaced only by hint deliveries; ends with the element.
    chipHint_ = null;
    #expanding__accessor_storage = true;
    get expanding_() { return this.#expanding__accessor_storage; }
    set expanding_(value) { this.#expanding__accessor_storage = value; }
    #shouldRemainFolded__accessor_storage = true;
    get shouldRemainFolded_() { return this.#shouldRemainFolded__accessor_storage; }
    set shouldRemainFolded_(value) { this.#shouldRemainFolded__accessor_storage = value; }
    get keepMenuOpenOnTabSelect() {
        return getLoadTimeBoolean('keepMenuOpenOnTabSelectForRealbox', false);
    }
    getPageHandler() {
        return this.pageHandler_;
    }
    getSearchboxHandler() {
        return this.searchboxHandler_;
    }
    getSearchboxCallbackRouter() {
        return this.searchboxCallbackRouter_;
    }
    getActiveElement() {
        return this.shadowRoot?.activeElement || null;
    }
    getInputElement() {
        return this.$.composeboxInput;
    }
    getDropdownElement() {
        return this.$.matches;
    }
    getContextEntrypointElement() {
        return this.shadowRoot?.querySelector('#contextEntrypoint') ||
            null;
    }
    constructor() {
        super();
        this.pageHandler_ = ComposeboxProxyImpl.getInstance().handler;
        this.searchboxCallbackRouter_ =
            ComposeboxProxyImpl.getInstance().searchboxCallbackRouter;
        this.searchboxHandler_ = ComposeboxProxyImpl.getInstance().searchboxHandler;
    }
    connectedCallback() {
        super.connectedCallback();
        this.animationState = GlowAnimationState.EXPANDING;
        this.focusInput();
        this.refreshTabSuggestions(/*forceRefresh=*/ true);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.eventTracker_.removeAll();
    }
    willUpdate(changedProperties) {
        super.willUpdate(changedProperties);
        this.shouldRemainFolded_ = this.computeShouldRemainFolded();
    }
    computeShouldRemainFolded() {
        if (this.errorMessage) {
            return false;
        }
        if ((this.files?.size ?? 0) > 0) {
            return false;
        }
        if (this.inToolMode) {
            return false;
        }
        if ((this.result?.matches?.length ?? 0) > 0) {
            return false;
        }
        return true;
    }
    shouldShowDivider() {
        const hasNonTabFiles = Array.from(this.files.values()).some(f => !f.url);
        if (this.hasTabs() && !hasNonTabFiles) {
            return this.showDropdown;
        }
        return super.shouldShowDivider();
    }
    deleteFile(uuidToDelete, fromUserAction) {
        const file = super.deleteFile(uuidToDelete, fromUserAction);
        if (file) {
            this.queryAutocomplete(/* clearMatches= */ true);
        }
        return file;
    }
    // Keeps the active chip hint as the placeholder so that asynchronous
    // inputState recomputes cannot clobber it.
    updateInputPlaceholder() {
        if (this.chipHint_ !== null) {
            this.inputPlaceholder = this.chipHint_;
            return;
        }
        super.updateInputPlaceholder();
    }
    async handleFuseboxAction(action, suggestion) {
        if (action.queryActionOverride === QueryActionOverride.kHint &&
            suggestion !== undefined) {
            this.chipHint_ = suggestion;
            this.updateInputPlaceholder();
        }
        if (action.preselectedInputSource) {
            switch (action.preselectedInputSource) {
                case InputSource.kInputSourceGallery:
                    this.$.fileInputs.shadowRoot
                        ?.querySelector('#imageInput')
                        ?.click();
                    break;
                case InputSource.kInputSourceFilePicker:
                    this.$.fileInputs.shadowRoot
                        ?.querySelector('#fileInput')
                        ?.click();
                    break;
                case InputSource.kInputSourceTabPicker:
                    await this.openTabPicker();
                    break;
                default:
                    break;
            }
        }
    }
    async openTabPicker() {
        if (!this.inputState) {
            const response = await this.getSearchboxHandler().getInputState();
            if (response) {
                this.inputState = response.state;
            }
        }
        this.shareTabsFlyoutOpen = true;
        await this.refreshTabSuggestions(/*forceRefresh=*/ true);
        await this.updateComplete;
        const contextEntrypoint = this.getContextEntrypointElement();
        if (contextEntrypoint) {
            await contextEntrypoint.updateComplete;
            const entrypointButton = contextEntrypoint.shadowRoot?.querySelector('#entrypointButton');
            if (entrypointButton) {
                await entrypointButton.updateComplete;
            }
            entrypointButton?.shadowRoot?.querySelector('#entrypoint')
                ?.click();
        }
    }
}
customElements.define(NtpComposeboxElement.is, NtpComposeboxElement);
