// 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_input.js';
import '//resources/cr_components/composebox/composebox_submit.js';
import '//resources/cr_components/composebox/composebox_tool_chip.js';
import '//resources/cr_components/composebox/composebox_voice_search.js';
import '//resources/cr_components/composebox/contextual_entrypoint_button.js';
import '//resources/cr_components/composebox/error_scrim.js';
import '//resources/cr_components/composebox/file_carousel.js';
import '//resources/cr_components/localized_link/localized_link.js';
import '//resources/cr_components/search/animated_glow.js';
import '//resources/cr_elements/cr_icon_button/cr_icon_button.js';
import { ComposeboxFile, mapUploadErrorToProcessFilesError, ProcessFilesError, TabUploadOrigin } 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 { ContextUploadStatus } from '//resources/cr_components/composebox/composebox_query.mojom-webui.js';
import { GlowAnimationState } from '//resources/cr_components/search/constants.js';
import { CrLitElement } from '//resources/lit/v3_0/lit.rollup.js';
import { DragAndDropHandler } from '//resources/cr_components/search/drag_drop_handler.js';
import { ToolMode } from '//resources/mojo/components/omnibox/composebox/composebox_query.mojom-webui.js';
import { getCss } from './omnibox_composebox.css.js';
import { getHtml } from './omnibox_composebox.html.js';
export class OmniboxComposeboxElement extends ComposeboxEmbedderMixin(CrLitElement) {
    static get is() {
        return 'cr-omnibox-composebox';
    }
    static get styles() {
        return getCss();
    }
    render() {
        return getHtml.bind(this)();
    }
    static get properties() {
        return {
            applyContextButtonBackground: {
                reflect: true,
                type: Boolean,
            },
            expanding_: {
                reflect: true,
                type: Boolean,
            },
            animationState: {
                type: String,
                reflect: true,
            },
            entrypointName: { type: String, reflect: true },
            enableCarouselScrolling: { type: Boolean },
        };
    }
    #entrypointName_accessor_storage = 'Omnibox';
    get entrypointName() { return this.#entrypointName_accessor_storage; }
    set entrypointName(value) { this.#entrypointName_accessor_storage = value; }
    #applyContextButtonBackground_accessor_storage = false;
    get applyContextButtonBackground() { return this.#applyContextButtonBackground_accessor_storage; }
    set applyContextButtonBackground(value) { this.#applyContextButtonBackground_accessor_storage = value; }
    #enableCarouselScrolling_accessor_storage = false;
    get enableCarouselScrolling() { return this.#enableCarouselScrolling_accessor_storage; }
    set enableCarouselScrolling(value) { this.#enableCarouselScrolling_accessor_storage = value; }
    #animationState_accessor_storage = GlowAnimationState.NONE;
    get animationState() { return this.#animationState_accessor_storage; }
    set animationState(value) { this.#animationState_accessor_storage = value; }
    #expanding__accessor_storage = true;
    get expanding_() { return this.#expanding__accessor_storage; }
    set expanding_(value) { this.#expanding__accessor_storage = value; }
    dragAndDropHandler_;
    pageHandler_;
    searchboxCallbackRouter_;
    searchboxHandler_;
    constructor() {
        super();
        this.pageHandler_ = ComposeboxProxyImpl.getInstance().handler;
        this.searchboxCallbackRouter_ =
            ComposeboxProxyImpl.getInstance().searchboxCallbackRouter;
        this.searchboxHandler_ = ComposeboxProxyImpl.getInstance().searchboxHandler;
        this.dragAndDropHandler_ =
            new DragAndDropHandler(this, this.dragAndDropEnabled);
    }
    connectedCallback() {
        super.connectedCallback();
        this.animationState = GlowAnimationState.EXPANDING;
    }
    willUpdate(changedProperties) {
        super.willUpdate(changedProperties);
        if (changedProperties.has('inputState') ||
            changedProperties.has('webuiOmniboxSimplificationEnabled')) {
            const inToolMode = this.inputState?.activeTool !== ToolMode.kUnspecified;
            this.applyContextButtonBackground =
                this.webuiOmniboxSimplificationEnabled && !inToolMode;
        }
    }
    firstUpdated(changedProperties) {
        super.firstUpdated(changedProperties);
        this.focusInput();
    }
    deleteFile(uuidToDelete, fromUserAction) {
        const file = super.deleteFile(uuidToDelete, fromUserAction);
        if (!file) {
            return null;
        }
        this.queryAutocomplete(/* clearMatches= */ true);
        return file;
    }
    getActiveElement() {
        return this.shadowRoot?.activeElement || null;
    }
    getDropdownElement() {
        return this.$.matches;
    }
    getInputElement() {
        return this.$.composeboxInput;
    }
    getPageHandler() {
        return this.pageHandler_;
    }
    getSearchboxCallbackRouter() {
        return this.searchboxCallbackRouter_;
    }
    getSearchboxHandler() {
        return this.searchboxHandler_;
    }
    getContextEntrypointElement() {
        return this.shadowRoot?.querySelector('#contextEntrypoint') ||
            null;
    }
    /*
     * Used by drag/drop host interface so the drag and drop handler can access
     * `addDroppedFiles`.
     */
    getDropTarget() {
        return this;
    }
    shouldShowDivider() {
        if (this.searchboxLayoutMode === 'TallBottomContext' &&
            !this.showFileCarousel) {
            return false;
        }
        return super.shouldShowDivider();
    }
    addSearchContext(context) {
        if (context) {
            if (context.input.length > 0) {
                this.input = context.input;
            }
            for (const attachment of context.attachments) {
                if (attachment.fileAttachment) {
                    this.addFileFromAttachment_(attachment.fileAttachment);
                }
                else if (attachment.tabAttachment) {
                    this.addTabFromAttachment_(attachment.tabAttachment);
                }
            }
        }
        // Query for ZPS even if there's no context.
        if (this.showZps) {
            // Clear the autocomplete matches here, as failure to do so triggers a
            // DCHECK in `ZpsSection::InitMatches()` whenever the user tries to upload
            // a file after having uploaded an invalid file earlier in the session.
            this.queryAutocomplete(/* clearMatches= */ true);
        }
    }
    playGlowAnimation() {
        // If |animationState_| were still EXPANDING, this function would have no
        // effect because nothing changes in CSS and therefore animations wouldn't
        // be re-trigered. Resetting it to NONE forces the animation related styles
        // to reset before switching to EXPANDING.
        this.animationState = GlowAnimationState.NONE;
        // Wait for the style change for NONE to commit. This ensures the browser
        // detects a state change when we switch to EXPANDING.
        // If the composebox is not submittable, trigger the animation.
        if (!this.submitEnabled) {
            requestAnimationFrame(() => {
                this.animationState = GlowAnimationState.EXPANDING;
            });
        }
    }
    isExpanded() {
        return this.expanding_;
    }
    addFileFromAttachment_(fileAttachment) {
        const errorType = fileAttachment.errorType ?? null;
        if (errorType) {
            const processFilesError = mapUploadErrorToProcessFilesError(errorType);
            if (processFilesError !== ProcessFilesError.NONE) {
                this.handleProcessFilesError(processFilesError);
                if (!super.deleteFile(fileAttachment.uuid)) {
                    this.getSearchboxHandler().deleteContext(fileAttachment.uuid, /*fromAutomaticChip=*/ false);
                }
                return;
            }
        }
        const pendingStatus = this.files.get(fileAttachment.uuid)?.status;
        const composeboxFile = ComposeboxFile.createFromFile(fileAttachment.uuid, { name: fileAttachment.name, type: fileAttachment.mimeType }, pendingStatus ?? ContextUploadStatus.kNotUploaded, {
            dataUrl: fileAttachment.imageDataUrl ?? null,
            iconUrl: fileAttachment.iconUrl,
            supportsUnimodal: true,
        });
        this.onFileContextAdded(composeboxFile);
    }
    addTabFromAttachment_(tabAttachment) {
        this.addTabContextHandleCallback({
            tabId: tabAttachment.tabId,
            title: tabAttachment.title,
            url: tabAttachment.url,
            delayUpload: false,
            origin: TabUploadOrigin.OTHER,
        });
    }
}
customElements.define(OmniboxComposeboxElement.is, OmniboxComposeboxElement);
