import "../atomic-icon/atomic-icon.js";
import "../atomic-modal/atomic-modal.js";
import { LitElement, css, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { createRef, ref } from "lit/directives/ref.js";
import { ATOMIC_MODAL_EXPORT_PARTS } from "../atomic-modal/export-parts.js";
import { renderButton } from "../button.js";
import { renderFieldsetGroup } from "../fieldset-group.js";
import { renderIconButton } from "../icon-button.js";
import { renderRadioButton } from "../radio-button.js";
import { booleanConverter } from "../../../converters/boolean-converter.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { watch } from "../../../decorators/watch.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { multiClassMap } from "../../../directives/multi-class-map.js";
import { updateBreakpoints } from "../../../utils/replace-breakpoint-utils.js";
import { once, randomID } from "../../../utils/utils.js";
import images_close from "../../../images/close.js";
import success from "../../../images/success.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);
}
class AtomicGeneratedAnswerFeedbackModal extends LitElement {
    initialize() {}
    watchToggleOpen(_oldValue, newValue) {
        if (newValue) this.generatedAnswer.openFeedbackModal();
    }
    getInitialAnswerState() {
        return {
            documented: void 0,
            correctTopic: void 0,
            hallucinationFree: void 0,
            readable: void 0
        };
    }
    resetState() {
        this.feedbackSubmitted = false;
        this.currentAnswer = this.getInitialAnswerState();
        this.answerEvaluationRequired = false;
        this.isOpen = false;
    }
    clearInputRefs() {
        if (this.detailsInputRef.value) this.detailsInputRef.value.value = '';
        if (this.linkInputRef.value) this.linkInputRef.value.value = '';
    }
    close() {
        this.clearInputRefs();
        this.resetState();
        this.generatedAnswer.closeFeedbackModal();
    }
    setCurrentAnswer(key, value) {
        this.currentAnswer = {
            ...this.currentAnswer,
            [key]: value
        };
    }
    sendFeedback() {
        const feedback = {
            ...this.currentAnswer,
            helpful: this.helpful
        };
        this.generatedAnswer.sendFeedback(feedback);
        this.dispatchEvent(new CustomEvent('feedbackSent'));
    }
    handleSubmit(e) {
        e.preventDefault();
        if (this.isAnyAnswerEvaluationUndefined()) {
            this.answerEvaluationRequired = true;
            return;
        }
        this.feedbackSubmitted = true;
        this.answerEvaluationRequired = false;
        this.sendFeedback();
    }
    renderHeader() {
        return html`
      <div
        slot="header"
        part="modal-header"
        class=${multiClassMap({
            'flex w-full items-center justify-between': true
        })}
      >
        <h1>
          <span>${this.bindings.i18n.t('feedback-modal-title')}</span>
          <span class=${multiClassMap({
            'hide ml-0.5': true
        })}>
            ${this.bindings.i18n.t('additional-feedback')}
          </span>
        </h1>
        ${renderIconButton({
            props: {
                style: 'text-transparent',
                class: 'search-clear-button',
                onClick: ()=>this.close(),
                icon: images_close,
                partPrefix: 'close',
                ariaLabel: this.bindings.i18n.t('close')
            }
        })}
      </div>
    `;
    }
    renderFeedbackOption(option, correspondingAnswer) {
        const isSelected = this.currentAnswer[correspondingAnswer] === option;
        return renderRadioButton({
            props: {
                key: String(correspondingAnswer),
                groupName: this.bindings.i18n.t(correspondingAnswer),
                style: 'outline-neutral',
                checked: isSelected,
                onChecked: ()=>{
                    this.setCurrentAnswer(correspondingAnswer, option);
                },
                class: `min-w-20 flex items-center justify-center whitespace-nowrap px-3 py-1.5 mr-1 text-neutral-dark ${isSelected ? 'active' : ''}`,
                text: this.bindings.i18n.t(option)
            }
        });
    }
    renderAnswerEvaluation(label, correspondingAnswer) {
        const isRequired = this.answerEvaluationRequired && void 0 === this.currentAnswer[correspondingAnswer];
        return html`
      <div class=${multiClassMap({
            block: true
        })}>
        <div class=${multiClassMap({
            flex: true
        })}>
          <label class=${multiClassMap({
            'text-base': true
        })}>
            ${this.bindings.i18n.t(label)}
            <span class=${multiClassMap({
            'text-error-red ml-0.5': true
        })}
              >*</span
            >
          </label>
        </div>
        <span
          class=${multiClassMap({
            'text-error-red text-sm': true,
            hidden: !isRequired
        })}
        >
          ${this.bindings.i18n.t('required-fields-error')}
        </span>
      </div>
    `;
    }
    renderRequiredFieldsAlert() {
        return html`
      <span
        class=${multiClassMap({
            'sr-only': true,
            hidden: !this.answerEvaluationRequired
        })}
        role="alert"
      >
        ${this.bindings.i18n.t('required-fields-error')}
      </span>
    `;
    }
    renderFeedbackOptions() {
        return html`
      <fieldset>
        <legend class=${multiClassMap({
            'font-bold': true
        })}>
          ${this.bindings.i18n.t('answer-evaluation')}
        </legend>
        ${AtomicGeneratedAnswerFeedbackModal.options.map(({ localeKey, correspondingAnswer })=>renderFieldsetGroup({
                props: {
                    label: this.bindings.i18n.t(localeKey)
                }
            })(html`
              <div
                class=${multiClassMap({
                'answer-evaluation mt-3 flex items-center': true,
                [String(correspondingAnswer)]: true
            })}
                key=${String(correspondingAnswer)}
              >
                <div class=${multiClassMap({
                'flex-1 pr-4': true
            })}>
                  ${this.renderAnswerEvaluation(localeKey, correspondingAnswer)}
                </div>
                <div
                  class=${multiClassMap({
                'options flex flex-shrink-0 text-base': true
            })}
                >
                  ${this.renderFeedbackOption('yes', correspondingAnswer)}
                  ${this.renderFeedbackOption('unknown', correspondingAnswer)}
                  ${this.renderFeedbackOption('no', correspondingAnswer)}
                </div>
              </div>
            `))}
      </fieldset>
    `;
    }
    renderLinkToCorrectAnswerField() {
        return html`
      <fieldset>
        <legend class=${multiClassMap({
            'font-bold': true
        })}>
          ${this.bindings.i18n.t('generated-answer-feedback-link')}
        </legend>
        <input
          type="text"
          ${ref(this.linkInputRef)}
          placeholder="https://URL"
          class=${multiClassMap({
            'input-primary placeholder-neutral-dark mt-4 h-9 w-full rounded-md px-4': true
        })}
          @change=${(e)=>this.setCurrentAnswer('documentUrl', e.currentTarget.value)}
        />
      </fieldset>
    `;
    }
    renderAddNotesField() {
        return html`
      <fieldset>
        <legend class=${multiClassMap({
            'mt-8 font-bold': true
        })}>
          ${this.bindings.i18n.t('generated-answer-additional-notes')}
        </legend>
        <textarea
          name="answer-details"
          ${ref(this.detailsInputRef)}
          class=${multiClassMap({
            'placeholder-neutral-dark border-neutral hover:border-primary-light focus-visible:border-primary mt-4 w-full resize-none rounded-md border px-4 py-2 leading-5 focus:outline-hidden focus-visible:ring-2': true
        })}
          rows="4"
          placeholder=${this.bindings.i18n.t('add-notes')}
          @change=${(e)=>this.setCurrentAnswer('details', e.currentTarget.value)}
        ></textarea>
      </fieldset>
    `;
    }
    renderFeedbackForm() {
        return html`
      <form
        part="form"
        id=${this.formId}
        slot="body"
        @submit=${(e)=>this.handleSubmit(e)}
        class=${multiClassMap({
            'flex flex-col gap-8 leading-4': true
        })}
      >
        ${this.renderRequiredFieldsAlert()} ${this.renderFeedbackOptions()}
        ${this.renderLinkToCorrectAnswerField()} ${this.renderAddNotesField()}
      </form>
    `;
    }
    renderSuccessMessage() {
        return html`
      <div
        slot="body"
        class=${multiClassMap({
            'my-4 flex flex-col items-center gap-4': true
        })}
      >
        <atomic-icon
          icon=${success}
          class=${multiClassMap({
            'w-48': true
        })}
        ></atomic-icon>
        <p
          class=${multiClassMap({
            'text-base': true
        })}
          role="status"
          aria-live="polite"
          aria-atomic="true"
        >
          ${this.bindings.i18n.t('generated-answer-feedback-success')}
        </p>
      </div>
    `;
    }
    renderBody() {
        if (!this.feedbackSubmitted) return this.renderFeedbackForm();
        return this.renderSuccessMessage();
    }
    renderFeedbackFormFooter() {
        const buttonClasses = 'flex items-center justify-center text-sm leading-4 p-2 rounded-md';
        return html`
      <div slot="footer" part="modal-footer">
        <div
          class=${multiClassMap({
            'flex items-center justify-between': true
        })}
        >
          <div class=${multiClassMap({
            'required-label text-base': true
        })}>
            <span class=${multiClassMap({
            'text-error-red mr-0.5': true
        })}
              >*</span
            >
            ${this.bindings.i18n.t('required-fields')}
          </div>
          <div class=${multiClassMap({
            'flex gap-2': true
        })}>
            ${renderButton({
            props: {
                part: 'cancel-button',
                style: 'outline-primary',
                class: buttonClasses,
                ariaLabel: this.bindings.i18n.t('skip'),
                onClick: ()=>this.close()
            }
        })(html`${this.bindings.i18n.t('skip')}`)}
            ${renderButton({
            props: {
                part: 'submit-button',
                style: 'primary',
                type: 'submit',
                form: this.formId,
                class: buttonClasses,
                ariaLabel: this.bindings.i18n.t('generated-answer-send-feedback')
            }
        })(html`${this.bindings.i18n.t('generated-answer-send-feedback')}`)}
          </div>
        </div>
      </div>
    `;
    }
    renderSuccessFormFooter() {
        return html`
      <div slot="footer">
        <div class=${multiClassMap({
            'flex justify-end gap-2 p-2': true
        })}>
          ${renderButton({
            props: {
                part: 'cancel-button',
                style: 'primary',
                onClick: ()=>this.close(),
                class: 'flex justify-center p-2 text-sm leading-4',
                ariaLabel: this.bindings.i18n.t('modal-done')
            }
        })(html`${this.bindings.i18n.t('modal-done')}`)}
        </div>
      </div>
    `;
    }
    renderFooter() {
        if (!this.feedbackSubmitted) return this.renderFeedbackFormFooter();
        return this.renderSuccessFormFooter();
    }
    render() {
        this.updateBreakpoints();
        return html`
      <atomic-modal
        .fullscreen=${false}
        .isOpen=${this.isOpen}
        .close=${()=>this.close()}
        .container=${this}
        part="generated-answer-feedback-modal"
        exportparts=${ATOMIC_MODAL_EXPORT_PARTS}
      >
        ${this.renderHeader()} ${this.renderBody()} ${this.renderFooter()}
      </atomic-modal>
    `;
    }
    constructor(...args){
        super(...args), this.isOpen = false, this.helpful = false, this.currentAnswer = this.getInitialAnswerState(), this.feedbackSubmitted = false, this.answerEvaluationRequired = false, this.formId = randomID('atomic-generated-answer-feedback-modal-form-'), this.detailsInputRef = createRef(), this.linkInputRef = createRef(), this.updateBreakpoints = once(()=>updateBreakpoints(this)), this.isAnyAnswerEvaluationUndefined = ()=>Object.values(this.currentAnswer).some((value)=>void 0 === value);
    }
}
AtomicGeneratedAnswerFeedbackModal.options = [
    {
        localeKey: 'feedback-correct-topic',
        correspondingAnswer: 'correctTopic'
    },
    {
        localeKey: 'feedback-hallucination-free',
        correspondingAnswer: 'hallucinationFree'
    },
    {
        localeKey: 'feedback-documented',
        correspondingAnswer: 'documented'
    },
    {
        localeKey: 'feedback-readable',
        correspondingAnswer: 'readable'
    }
];
AtomicGeneratedAnswerFeedbackModal.styles = css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */[part=generated-answer-feedback-modal]::part(container){min-width:calc(var(--spacing,.25rem)*170)}[part=generated-answer-feedback-modal]::part(body),[part=generated-answer-feedback-modal]::part(footer),[part=generated-answer-feedback-modal]::part(header){max-width:calc(var(--spacing,.25rem)*170)}@media not all and (min-width:1024px){[part=generated-answer-feedback-modal]::part(container){min-width:100%;width:auto}[part=generated-answer-feedback-modal]::part(body),[part=generated-answer-feedback-modal]::part(footer),[part=generated-answer-feedback-modal]::part(header){max-width:100%}[part=generated-answer-feedback-modal] [part=buttons] .required-label{font-size:var(--atomic-text-sm);line-height:var(--tw-leading,var(--text-sm--line-height,1.42857))}[part=generated-answer-feedback-modal] [part=form] .answer-evaluation{display:block}[part=generated-answer-feedback-modal] [part=form] .options{margin-top:calc(var(--spacing,.25rem)*2)}[part=generated-answer-feedback-modal] [part=modal-header] .hide{display:none}}[part=form] .active{background-color:var(--atomic-primary-background);border-color:var(--atomic-primary-light);color:var(--atomic-primary-light)}[part=form] .text-error-red{color:var(--atomic-inline-code)}`;
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'is-open',
        converter: booleanConverter
    })
], AtomicGeneratedAnswerFeedbackModal.prototype, "isOpen", void 0);
_ts_decorate([
    property({
        type: Object,
        attribute: false
    }),
    _ts_metadata("design:type", "u" < typeof GeneratedAnswer ? Object : GeneratedAnswer)
], AtomicGeneratedAnswerFeedbackModal.prototype, "generatedAnswer", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true
    })
], AtomicGeneratedAnswerFeedbackModal.prototype, "helpful", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof AnyBindings ? Object : AnyBindings)
], AtomicGeneratedAnswerFeedbackModal.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicGeneratedAnswerFeedbackModal.prototype, "error", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Partial ? Object : Partial)
], AtomicGeneratedAnswerFeedbackModal.prototype, "currentAnswer", void 0);
_ts_decorate([
    state()
], AtomicGeneratedAnswerFeedbackModal.prototype, "feedbackSubmitted", void 0);
_ts_decorate([
    state()
], AtomicGeneratedAnswerFeedbackModal.prototype, "answerEvaluationRequired", void 0);
_ts_decorate([
    watch('isOpen'),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        Object,
        Object
    ]),
    _ts_metadata("design:returntype", void 0)
], AtomicGeneratedAnswerFeedbackModal.prototype, "watchToggleOpen", null);
_ts_decorate([
    errorGuard(),
    bindingGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicGeneratedAnswerFeedbackModal.prototype, "render", null);
AtomicGeneratedAnswerFeedbackModal = _ts_decorate([
    customElement('atomic-generated-answer-feedback-modal'),
    bindings(),
    withTailwindStyles
], AtomicGeneratedAnswerFeedbackModal);
export { AtomicGeneratedAnswerFeedbackModal };
