import { unsafeCSS, LitElement, nothing, html } from "lit";
import { customElement } from "../../decorator.js";
import componentStyle from "./textarea-field.css.js";
import { property, state, query } from "lit/decorators.js";
import { classMap } from "lit/directives/class-map.js";
import { ifDefined } from "lit/directives/if-defined.js";
import { localized, msg } from "@lit/localize";
import "../icon-button/icon-button.js";
import "../input-chip/input-chip.js";
import "../button/button.js";
import { AudioRecordingStatus } from "../audio-recording-item/audio-recording-item.js";
import "../../icons/icon-up-iec.js";
import "../../icons/icon-screen-shot.js";
import "../../icons/icon-image.js";
import "../../icons/icon-attachment.js";
import "../../icons/icon-com-microphone.js";
import "../../icons/icon-arrow-up-google.js";
import "../../icons/icon-check-google.js";
import "../../icons/icon-close-google.js";
import "../../icons/icon-delete.js";
import "../../icons/icon-media-pause.js";
import "../../icons/icon-media-play.js";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp(target, key, result);
  return result;
};
var TextareaFieldType = /* @__PURE__ */ ((TextareaFieldType2) => {
  TextareaFieldType2["Rich"] = "rich";
  TextareaFieldType2["Message"] = "message";
  return TextareaFieldType2;
})(TextareaFieldType || {});
var VoiceAction = /* @__PURE__ */ ((VoiceAction2) => {
  VoiceAction2["Start"] = "start";
  VoiceAction2["Cancel"] = "cancel";
  VoiceAction2["Confirm"] = "confirm";
  VoiceAction2["Delete"] = "delete";
  VoiceAction2["Pause"] = "pause";
  VoiceAction2["Resume"] = "resume";
  VoiceAction2["Transcribe"] = "transcribe";
  VoiceAction2["Send"] = "send";
  VoiceAction2["PlaybackToggle"] = "playback-toggle";
  return VoiceAction2;
})(VoiceAction || {});
let ObcTextareaField = class extends LitElement {
  constructor() {
    super(...arguments);
    this.type = "rich";
    this.value = "";
    this.rejectUpdatesOnFocus = false;
    this.rejectUpdates = false;
    this.rejectDuplicateUpdates = false;
    this.placeholder = "";
    this.label = "";
    this.errorText = "";
    this.disabled = false;
    this.error = false;
    this.required = false;
    this.showLabel = true;
    this.showToolbar = true;
    this.showVoiceRecording = true;
    this.hasLeadingIcon = false;
    this.recording = false;
    this.recordingDuration = 0;
    this.audioLevels = [];
    this.recordingStatus = AudioRecordingStatus.Recording;
    this.playbackPosition = 0;
    this.attachments = [];
    this._focused = false;
    this._statusAnnouncement = "";
    this._isPlayingRecording = false;
    this._previousValue = "";
    this._previousInputElementValue = "";
    this._pendingAnnouncementId = 0;
  }
  willUpdate(changedProperties) {
    if (changedProperties.has("value") && !this.shouldUpdateValue && this._textarea) {
      this.value = this._textarea.value;
    }
  }
  updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("recording")) {
      const wasRecording = changedProperties.get("recording");
      if (this.recording && !wasRecording) {
        this.announceStatus("Recording started");
        this.safeFocus(this._firstActionButton);
      } else if (!this.recording && wasRecording) {
        this.recordingStatus = AudioRecordingStatus.Recording;
        this.playbackPosition = 0;
        this._isPlayingRecording = false;
        this.safeFocus(this._textarea);
      }
    }
    if (changedProperties.has("recordingStatus") && this.recording) {
      const wasStatus = changedProperties.get(
        "recordingStatus"
      );
      if (wasStatus !== void 0) {
        const wasPausedOrPlayback = wasStatus === AudioRecordingStatus.Paused || wasStatus === AudioRecordingStatus.Playback;
        if (this.isPausedOrPlayback && !wasPausedOrPlayback) {
          this.announceStatus("Recording paused");
        } else if (!this.isPausedOrPlayback && wasPausedOrPlayback) {
          this.announceStatus("Recording resumed");
        }
      }
    }
    if (this.rejectDuplicateUpdates && this.value !== this._previousValue && (this._previousInputElementValue !== this.value || !this._focused)) {
      this._previousValue = this.value;
    }
  }
  /**
   * Announces a status message to screen readers via the aria-live region.
   * Uses a unique ID to prevent rapid calls from dropping messages.
   */
  announceStatus(message) {
    this._pendingAnnouncementId++;
    const announcementId = this._pendingAnnouncementId;
    this._statusAnnouncement = "";
    requestAnimationFrame(() => {
      if (this.isConnected && announcementId === this._pendingAnnouncementId) {
        this._statusAnnouncement = message;
      }
    });
  }
  /**
   * Safely focuses an element after a frame, checking that the component is still connected.
   */
  safeFocus(element) {
    requestAnimationFrame(() => {
      if (this.isConnected && element) {
        element.focus();
      }
    });
  }
  get isMessageType() {
    return this.type === "message";
  }
  get hasContent() {
    return this.value.trim().length > 0;
  }
  get canSend() {
    return this.hasContent || (this.attachments?.length ?? 0) > 0;
  }
  get showTitle() {
    return this.showLabel && this.label.length > 0;
  }
  get isPausedOrPlayback() {
    return this.recordingStatus === AudioRecordingStatus.Paused || this.recordingStatus === AudioRecordingStatus.Playback;
  }
  get shouldShowToolbar() {
    return this.showToolbar || this.isMessageType || this.recording;
  }
  get isEmpty() {
    return !this.hasContent && (this.attachments?.length ?? 0) === 0 && !this.recording;
  }
  emit(eventName, detail) {
    this.dispatchEvent(
      new CustomEvent(eventName, {
        detail,
        bubbles: true,
        composed: true
      })
    );
  }
  emitIfEnabled(eventName, detail) {
    if (!this.disabled) {
      this.emit(eventName, detail);
    }
  }
  handleInput(e) {
    const target = e.target;
    this.value = target.value;
    this._previousInputElementValue = this.value;
    e.stopPropagation();
    this.dispatchEvent(
      new CustomEvent("input", { detail: { value: target.value } })
    );
  }
  handleKeyDown(e) {
    if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
      e.preventDefault();
      if (this.canSend && this.isMessageType) {
        this.handleSendClick();
      }
    }
  }
  handleFocus() {
    this._focused = true;
  }
  handleBlur() {
    this._focused = false;
  }
  handleSendClick() {
    this.emitIfEnabled("send-click", { value: this.value });
  }
  handleAddClick() {
    this.emitIfEnabled("add-click");
  }
  handleScreenshotClick() {
    this.emitIfEnabled("screenshot-click");
  }
  handleImageClick() {
    this.emitIfEnabled("image-click");
  }
  handleAttachmentClick() {
    this.emitIfEnabled("attachment-click");
  }
  emitVoiceAction(action, playing) {
    const detail = { action };
    if (playing !== void 0) {
      detail.playing = playing;
    }
    this.emitIfEnabled("voice-action", detail);
  }
  handleVoiceRecordingStart() {
    this.emitVoiceAction(
      "start"
      /* Start */
    );
  }
  handleVoiceRecordingCancel() {
    this.emitVoiceAction(
      "cancel"
      /* Cancel */
    );
  }
  handleVoiceRecordingConfirm() {
    this.emitVoiceAction(
      "confirm"
      /* Confirm */
    );
  }
  handleVoiceRecordingDelete() {
    this.emitVoiceAction(
      "delete"
      /* Delete */
    );
  }
  handleVoiceRecordingPause() {
    this.emitVoiceAction(
      "pause"
      /* Pause */
    );
  }
  handleVoiceRecordingResume() {
    this.emitVoiceAction(
      "resume"
      /* Resume */
    );
  }
  handleVoiceTranscribe() {
    this.emitVoiceAction(
      "transcribe"
      /* Transcribe */
    );
  }
  handleVoiceSend() {
    this.emitVoiceAction(
      "send"
      /* Send */
    );
  }
  handleVoicePlaybackToggle(e) {
    const playing = e.detail.isPlaying;
    this._isPlayingRecording = playing;
    this.emitVoiceAction("playback-toggle", playing);
  }
  handleAttachmentRemove(attachment) {
    this.emitIfEnabled("attachment-remove", { id: attachment.id });
  }
  renderTitle() {
    if (!this.showTitle) return nothing;
    return html`
      <div class="title-text-container">
        <p id="title-text" class="title-text">${this.label}</p>
        ${this.required ? html`<div class="required-indicator"></div>` : nothing}
      </div>
    `;
  }
  renderLeadingIcon() {
    if (!this.hasLeadingIcon) return nothing;
    return html`
      <div class="leading-icon">
        <slot name="leading-icon"></slot>
      </div>
    `;
  }
  get shouldUpdateValue() {
    if (this.rejectUpdates) return false;
    if (this.rejectUpdatesOnFocus && this._focused) return false;
    if (this.rejectDuplicateUpdates && this.value === this._previousValue) {
      return false;
    }
    return true;
  }
  renderTextarea() {
    if (this.recording) return nothing;
    let value = this.value;
    if (!this.shouldUpdateValue && this._textarea) {
      value = this._textarea.value;
    }
    return html`
      <textarea
        class="input-field"
        .placeholder=${this.placeholder}
        .value=${value}
        @input=${this.handleInput}
        @change=${this.fireChangeEvent}
        @keydown=${this.handleKeyDown}
        @focus=${this.handleFocus}
        @blur=${this.handleBlur}
        ?disabled=${this.disabled}
        maxlength=${ifDefined(this.maxlength)}
        aria-label=${ifDefined(
      this.showTitle ? void 0 : this.placeholder || "Text input"
    )}
        aria-labelledby=${ifDefined(this.showTitle ? "title-text" : void 0)}
        aria-invalid=${this.error ? "true" : "false"}
        aria-required=${this.required ? "true" : "false"}
      ></textarea>
    `;
  }
  fireChangeEvent(e) {
    const target = e.target;
    this.dispatchEvent(
      new CustomEvent("change", { detail: { value: target.value } })
    );
  }
  renderAttachments() {
    if (this.attachments.length === 0) return nothing;
    return html`
      <div class="attachments-container">
        ${this.attachments.map(
      (attachment) => html`
            <obc-input-chip
              .label=${attachment.label}
              .showIcon=${attachment.showIcon ?? false}
              ?disabled=${this.disabled}
              @remove-chip=${() => this.handleAttachmentRemove(attachment)}
            ></obc-input-chip>
          `
    )}
      </div>
    `;
  }
  renderAudioRecordingItem() {
    if (!this.recording) return nothing;
    return html`
      <obc-audio-recording-item
        .audioLevels=${this.audioLevels}
        .duration=${this.recordingDuration}
        .status=${this.recordingStatus}
        .playbackPosition=${this.playbackPosition}
        .isPlaying=${this._isPlayingRecording}
        @status-toggle=${this.handleVoicePlaybackToggle}
      ></obc-audio-recording-item>
    `;
  }
  renderToolbar() {
    if (!this.shouldShowToolbar) return nothing;
    return html`
      <div class="tool-bar-container">
        ${this.recording ? this.renderRecordingToolbar() : this.renderNormalToolbar()}
      </div>
    `;
  }
  renderNormalToolbar() {
    return html`
      ${this.showToolbar ? html`
            <div class="tool-container">
              <div class="divider"></div>
              <obc-icon-button
                variant="flat"
                @click=${this.handleAddClick}
                ?disabled=${this.disabled}
                aria-label="Add content"
              >
                <obi-up-iec></obi-up-iec>
              </obc-icon-button>
              <obc-icon-button
                variant="flat"
                @click=${this.handleScreenshotClick}
                ?disabled=${this.disabled}
                aria-label="Take screenshot"
              >
                <obi-screen-shot></obi-screen-shot>
              </obc-icon-button>
              <obc-icon-button
                variant="flat"
                @click=${this.handleImageClick}
                ?disabled=${this.disabled}
                aria-label="Add image"
              >
                <obi-image></obi-image>
              </obc-icon-button>
              <obc-icon-button
                variant="flat"
                @click=${this.handleAttachmentClick}
                ?disabled=${this.disabled}
                aria-label="Add attachment"
              >
                <obi-attachment></obi-attachment>
              </obc-icon-button>
            </div>
          ` : nothing}

      <div class="action-container ${this.isEmpty ? "inactive" : ""}">
        ${this.showVoiceRecording ? html`
              <obc-icon-button
                variant="normal"
                @click=${this.handleVoiceRecordingStart}
                ?disabled=${this.disabled}
                aria-label="Start voice recording"
              >
                <obi-com-microphone></obi-com-microphone>
              </obc-icon-button>
            ` : nothing}
        ${this.isMessageType ? html`
              <obc-icon-button
                class="send-button"
                variant=${this.canSend && !this.disabled ? "raised" : "normal"}
                @click=${this.handleSendClick}
                ?disabled=${this.disabled || !this.canSend}
                aria-label="Send message"
              >
                <obi-arrow-up-google></obi-arrow-up-google>
              </obc-icon-button>
            ` : nothing}
      </div>
    `;
  }
  renderRecordingToolbar() {
    if (this.isMessageType) {
      return this.renderMessageRecordingToolbar();
    }
    return this.renderRichRecordingToolbar();
  }
  renderPauseResumeButton() {
    return html`
      <obc-icon-button
        variant="normal"
        @click=${this.isPausedOrPlayback ? this.handleVoiceRecordingResume : this.handleVoiceRecordingPause}
        ?disabled=${this.disabled}
        aria-label=${this.isPausedOrPlayback ? "Resume recording" : "Pause recording"}
      >
        ${this.isPausedOrPlayback ? html`<obi-com-microphone></obi-com-microphone>` : html`<obi-media-pause></obi-media-pause>`}
      </obc-icon-button>
    `;
  }
  renderRichRecordingToolbar() {
    return html`
      <div class="tool-container">
        <obc-icon-button
          variant="normal"
          @click=${this.handleVoiceRecordingCancel}
          ?disabled=${this.disabled}
          aria-label="Cancel recording"
        >
          <obi-close-google></obi-close-google>
        </obc-icon-button>
      </div>
      <div class="action-container recording-controls">
        ${this.renderPauseResumeButton()}
        <obc-icon-button
          variant="normal"
          @click=${this.handleVoiceRecordingConfirm}
          ?disabled=${this.disabled}
          aria-label="Confirm recording"
        >
          <obi-check-google></obi-check-google>
        </obc-icon-button>
      </div>
    `;
  }
  renderMessageRecordingToolbar() {
    return html`
      <div class="tool-container">
        <obc-icon-button
          variant="normal"
          @click=${this.handleVoiceRecordingDelete}
          ?disabled=${this.disabled}
          aria-label="Delete recording"
        >
          <obi-delete></obi-delete>
        </obc-icon-button>
      </div>
      <div class="action-container recording-controls">
        <obc-button
          variant="normal"
          @click=${this.handleVoiceTranscribe}
          ?disabled=${this.disabled}
        >
          ${msg("Transcribe")}
        </obc-button>
        ${this.renderPauseResumeButton()}
        <obc-icon-button
          class="send-button"
          variant="raised"
          @click=${this.handleVoiceSend}
          ?disabled=${this.disabled}
          aria-label="Send voice message"
        >
          <obi-arrow-up-google></obi-arrow-up-google>
        </obc-icon-button>
      </div>
    `;
  }
  renderErrorText() {
    if (!this.error || !this.errorText) return nothing;
    return html`
      <div class="error-text-container">
        <p class="error-text">${this.errorText}</p>
      </div>
    `;
  }
  /**
   * Renders a visually hidden live region for screen reader announcements.
   * Uses role="status" with aria-live="polite" to announce recording state changes
   * without interrupting the user.
   */
  renderStatusAnnouncement() {
    return html`
      <div
        role="status"
        aria-live="polite"
        aria-atomic="true"
        class="visually-hidden"
      >
        ${this._statusAnnouncement}
      </div>
    `;
  }
  render() {
    return html`
      <div
        part="wrapper"
        class=${classMap({
      wrapper: true,
      disabled: this.disabled,
      error: this.error,
      focused: this._focused,
      empty: this.isEmpty,
      "has-leading-icon": this.hasLeadingIcon,
      "voice-recording-active": this.recording,
      "type-rich": this.type === "rich",
      "type-message": this.type === "message"
      /* Message */
    })}
      >
        ${this.renderTitle()}
        <div part="content" class="content-container">
          ${this.renderLeadingIcon()} ${this.renderTextarea()}
          ${this.renderAttachments()} ${this.renderAudioRecordingItem()}
          ${this.renderToolbar()}
        </div>
        ${this.renderErrorText()} ${this.renderStatusAnnouncement()}
      </div>
    `;
  }
};
ObcTextareaField.styles = unsafeCSS(componentStyle);
__decorateClass([
  property({ type: String })
], ObcTextareaField.prototype, "type", 2);
__decorateClass([
  property({ type: String })
], ObcTextareaField.prototype, "value", 2);
__decorateClass([
  property({ type: Boolean })
], ObcTextareaField.prototype, "rejectUpdatesOnFocus", 2);
__decorateClass([
  property({ type: Boolean })
], ObcTextareaField.prototype, "rejectUpdates", 2);
__decorateClass([
  property({ type: Boolean })
], ObcTextareaField.prototype, "rejectDuplicateUpdates", 2);
__decorateClass([
  property({ type: String })
], ObcTextareaField.prototype, "placeholder", 2);
__decorateClass([
  property({ type: String })
], ObcTextareaField.prototype, "label", 2);
__decorateClass([
  property({ type: String })
], ObcTextareaField.prototype, "errorText", 2);
__decorateClass([
  property({ type: Number })
], ObcTextareaField.prototype, "maxlength", 2);
__decorateClass([
  property({ type: Boolean })
], ObcTextareaField.prototype, "disabled", 2);
__decorateClass([
  property({ type: Boolean })
], ObcTextareaField.prototype, "error", 2);
__decorateClass([
  property({ type: Boolean })
], ObcTextareaField.prototype, "required", 2);
__decorateClass([
  property({ type: Boolean, attribute: false })
], ObcTextareaField.prototype, "showLabel", 2);
__decorateClass([
  property({ type: Boolean, attribute: false })
], ObcTextareaField.prototype, "showToolbar", 2);
__decorateClass([
  property({ type: Boolean, attribute: false })
], ObcTextareaField.prototype, "showVoiceRecording", 2);
__decorateClass([
  property({ type: Boolean })
], ObcTextareaField.prototype, "hasLeadingIcon", 2);
__decorateClass([
  property({ type: Boolean })
], ObcTextareaField.prototype, "recording", 2);
__decorateClass([
  property({ type: Number })
], ObcTextareaField.prototype, "recordingDuration", 2);
__decorateClass([
  property({ type: Array })
], ObcTextareaField.prototype, "audioLevels", 2);
__decorateClass([
  property({ type: String })
], ObcTextareaField.prototype, "recordingStatus", 2);
__decorateClass([
  property({ type: Number })
], ObcTextareaField.prototype, "playbackPosition", 2);
__decorateClass([
  property({ type: Array })
], ObcTextareaField.prototype, "attachments", 2);
__decorateClass([
  state()
], ObcTextareaField.prototype, "_focused", 2);
__decorateClass([
  state()
], ObcTextareaField.prototype, "_statusAnnouncement", 2);
__decorateClass([
  state()
], ObcTextareaField.prototype, "_isPlayingRecording", 2);
__decorateClass([
  state()
], ObcTextareaField.prototype, "_previousValue", 2);
__decorateClass([
  state()
], ObcTextareaField.prototype, "_previousInputElementValue", 2);
__decorateClass([
  query(".input-field")
], ObcTextareaField.prototype, "_textarea", 2);
__decorateClass([
  query(".action-container obc-icon-button")
], ObcTextareaField.prototype, "_firstActionButton", 2);
ObcTextareaField = __decorateClass([
  customElement("obc-textarea-field"),
  localized()
], ObcTextareaField);
export {
  ObcTextareaField,
  TextareaFieldType,
  VoiceAction
};
//# sourceMappingURL=textarea-field.js.map
