import { LitElement, html } from "lit";
import { provide } from "@lit/context";
import { customElement, property, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import atomic_generated_answer_tw_css from "../../search/atomic-generated-answer/atomic-generated-answer.tw.css.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import "../atomic-agent-stream-of-thought/atomic-agent-stream-of-thought.js";
import { renderGeneratedContentContainer } from "../generated-answer/generated-content-container.js";
import { renderFeedbackAndCopyButtons } from "../generated-answer/render-feedback-and-copy-buttons.js";
import { renderSourceCitations } from "../generated-answer/source-citations.js";
import { answerContext } from "./answer-context.js";
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
    if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
}
const COPY_RESET_DURATION_MS = 2000;
class AtomicGeneratedAnswerContent extends LitElement {
    disconnectedCallback() {
        super.disconnectedCallback();
        clearTimeout(this.resetCopyTimeout);
    }
    render() {
        const { answer, answerContentFormat, isStreaming, generationSteps, citations = [], answerId, error, cannotAnswer } = this.generatedAnswer || {};
        this.answerId = answerId || '';
        if (error) return this.renderError();
        if (cannotAnswer) return this.renderCannotAnswer();
        if (!answerId) return html``;
        const shouldRenderFeedbackAndCopyButtons = Boolean(answer) && !isStreaming;
        return html`
      <div>
        <atomic-agent-stream-of-thought
          .i18n=${this.i18n}
          .agentSteps=${generationSteps ?? []}
          .isStreaming=${Boolean(isStreaming)}
        ></atomic-agent-stream-of-thought>
        <div>
          ${renderGeneratedContentContainer({
            props: {
                answer,
                answerContentFormat,
                isStreaming: Boolean(isStreaming)
            }
        })(html`
            ${renderSourceCitations({
            props: {
                label: this.i18n.t('citations'),
                isVisible: citations.length > 0
            }
        })(html`${this.renderCitations(citations, answerId)}`)}
          `)}
        </div>
        ${when(shouldRenderFeedbackAndCopyButtons, ()=>this.renderFeedbackAndCopyButtons(answerId))}
      </div>
    `;
    }
    renderFeedbackAndCopyButtons(answerId) {
        return html`
      <div class="mt-4" part="feedback-and-copy-buttons">
        ${renderFeedbackAndCopyButtons({
            props: {
                i18n: this.i18n,
                generatedAnswerActionsState: {
                    liked: this.generatedAnswer.liked,
                    disliked: this.generatedAnswer.disliked,
                    isStreaming: this.generatedAnswer.isStreaming,
                    isLoading: this.generatedAnswer.isLoading,
                    answer: this.generatedAnswer.answer
                },
                copied: 'success' === this.copyState,
                copyError: 'error' === this.copyState,
                getCopyToClipboardTooltip: ()=>this.getCopyToClipboardTooltip(),
                onClickLike: ()=>this.onClickLike(answerId),
                onClickDislike: ()=>this.onClickDislike(answerId),
                onCopyToClipboard: ()=>this.copyToClipboard()
            }
        })}
      </div>
    `;
    }
    async copyToClipboard() {
        const { answer, answerId } = this.generatedAnswer;
        if (!answer || !answerId) return;
        try {
            await navigator.clipboard.writeText(answer);
            this.copyState = 'success';
            this.onCopyToClipboard(answerId);
        } catch (error) {
            this.copyState = 'error';
            console.error(`Failed to copy to clipboard: ${error}`);
        }
        this.scheduleCopyReset();
    }
    scheduleCopyReset() {
        clearTimeout(this.resetCopyTimeout);
        this.resetCopyTimeout = window.setTimeout(()=>{
            this.copyState = 'idle';
        }, COPY_RESET_DURATION_MS);
    }
    getCopyToClipboardTooltip() {
        switch(this.copyState){
            case 'error':
                return this.i18n.t('failed-to-copy-generated-answer');
            case 'success':
                return this.i18n.t('generated-answer-copied');
            default:
                return this.i18n.t('copy-generated-answer');
        }
    }
    renderError() {
        const errorMessageKey = this.generatedAnswer.error?.isSseTurnLimitReachedError?.() ? 'generated-answer-error-turn-limit-reached' : 'generated-answer-error-generic';
        return html`
      <div part="generated-answer-error">
        <p>${this.i18n.t(errorMessageKey)}</p>
      </div>
    `;
    }
    renderCannotAnswer() {
        return html`
      <div part="generated-answer-cannot-answer">
        <p>${this.i18n.t('generated-answer-cannot-generate-answer')}</p>
      </div>
    `;
    }
    constructor(...args){
        super(...args), this.answerId = '', this.renderCitations = ()=>html``, this.onClickLike = ()=>{}, this.onClickDislike = ()=>{}, this.onCopyToClipboard = ()=>{}, this.copyState = 'idle';
    }
}
AtomicGeneratedAnswerContent.styles = [
    atomic_generated_answer_tw_css
];
_ts_decorate([
    provide({
        context: answerContext
    })
], AtomicGeneratedAnswerContent.prototype, "answerId", void 0);
_ts_decorate([
    property({
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof GeneratedAnswer ? Object : GeneratedAnswer)
], AtomicGeneratedAnswerContent.prototype, "generatedAnswer", void 0);
_ts_decorate([
    property({
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof i18n ? Object : i18n)
], AtomicGeneratedAnswerContent.prototype, "i18n", void 0);
_ts_decorate([
    property({
        attribute: false
    }),
    _ts_metadata("design:type", Function)
], AtomicGeneratedAnswerContent.prototype, "renderCitations", void 0);
_ts_decorate([
    property({
        attribute: false
    }),
    _ts_metadata("design:type", Function)
], AtomicGeneratedAnswerContent.prototype, "onClickLike", void 0);
_ts_decorate([
    property({
        attribute: false
    }),
    _ts_metadata("design:type", Function)
], AtomicGeneratedAnswerContent.prototype, "onClickDislike", void 0);
_ts_decorate([
    property({
        attribute: false
    }),
    _ts_metadata("design:type", Function)
], AtomicGeneratedAnswerContent.prototype, "onCopyToClipboard", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof CopyState ? Object : CopyState)
], AtomicGeneratedAnswerContent.prototype, "copyState", void 0);
AtomicGeneratedAnswerContent = _ts_decorate([
    customElement('atomic-generated-answer-content'),
    withTailwindStyles
], AtomicGeneratedAnswerContent);
export { AtomicGeneratedAnswerContent };
