import {
  HasSlotController
} from "./chunk.IVMQWO2L.js";
import {
  LocalizeController
} from "./chunk.X3FE7OHE.js";
import {
  SolidElement,
  customElement
} from "./chunk.H53WQBDK.js";
import {
  Wave
} from "./chunk.POFWU6ZT.js";
import {
  __decorateClass
} from "./chunk.S3NI7NKU.js";

// src/components/audio/audio.ts
import { css, html } from "lit";
import { property, query, state } from "lit/decorators.js";
import cx from "classix";
var SdAudio = class extends SolidElement {
  constructor() {
    super();
    this.localize = new LocalizeController(this);
    this.hasSlotController = new HasSlotController(this, "transcript");
    this.reversedLayout = false;
    this.hideTimestamps = false;
    this.animated = false;
    this.inverted = false;
    this.speed = 1;
    this.currentTime = this.formatTime(0);
    this.duration = "";
    this.isPlaying = false;
    this.isMuted = false;
    this.isTranscriptOpen = false;
    this.progress = 0;
    this.updateCurrentTime = this.updateCurrentTime.bind(this);
    this.handleAudioEnd = this.handleAudioEnd.bind(this);
    this.handleAudioProgress = this.handleAudioProgress.bind(this);
    this.handleAudioProgressKeydown = this.handleAudioProgressKeydown.bind(this);
    this.handleTranscriptDrawerToggle = this.handleTranscriptDrawerToggle.bind(this);
  }
  firstUpdated() {
    if (!this.audioElement) return;
    this.audioElement.addEventListener("timeupdate", this.updateCurrentTime);
    this.audioElement.addEventListener("ended", this.handleAudioEnd);
    this.audioElement.setAttribute("controlsList", "nodownload");
    document.addEventListener("sd-after-hide", this.handleTranscriptDrawerToggle);
    this.audioElement.playbackRate = this.speed;
    this.progressSlider.tooltipFormatter = (value) => this.localize.term("seconds", Number(value).toFixed(0));
    if (this.animated) {
      this.initAnimation();
    }
  }
  updated(changedProperties) {
    if (changedProperties.has("animated")) {
      const oldValue = changedProperties.get("animated");
      if (!oldValue && this.animated) {
        this.initAnimation();
      } else if (oldValue && !this.animated) {
        this.clear();
      }
    }
  }
  get audioElement() {
    const slot = this.shadowRoot.querySelector("slot");
    if ((slot == null ? void 0 : slot.assignedElements().length) > 0) {
      return slot.assignedElements()[0];
    }
    return null;
  }
  updateCurrentTime() {
    if (!this.audioElement) return;
    const currentTime = this.audioElement.currentTime;
    this.currentTime = this.formatTime(currentTime);
    this.progress = currentTime;
    if (this.progressSlider) {
      this.progressSlider.value = this.progress.toString();
    }
  }
  updateAudioDuration() {
    if (!this.audioElement) return;
    if (isNaN(this.audioElement.duration)) {
      setTimeout(() => {
        this.updateAudioDuration();
      }, 100);
      return;
    }
    this.duration = this.formatTime(this.audioElement.duration);
    this.progressSlider.max = this.audioElement.duration;
  }
  playAudio() {
    if (!this.audioElement) return;
    this.isPlaying = true;
    this.audioElement.play();
    this.emit("sd-playback-start");
    if (this.animated) {
      this.draw();
    }
  }
  pauseAudio() {
    if (!this.audioElement) return;
    this.isPlaying = false;
    this.audioElement.pause();
    this.emit("sd-playback-pause");
    if (this.animated) {
      this.stopAnimation();
    }
  }
  handleAudioEnd() {
    this.emit("sd-playback-end");
    this.isPlaying = false;
    this.progress = 0;
    this.progressSlider.value = "0";
    this.currentTime = this.formatTime(0);
    if (this.animated) {
      this.stopAnimation();
    }
  }
  toggleMute() {
    if (!this.audioElement) return;
    this.isMuted = !this.isMuted;
    if (this.isMuted) {
      this.emit("sd-playback-mute");
      this.audioElement.muted = true;
    } else {
      this.emit("sd-playback-unmute");
      this.audioElement.muted = false;
    }
  }
  toggleMuteKeydown(event) {
    if (event.key === "Enter") {
      event.preventDefault();
      this.toggleMute();
    }
  }
  togglePlaybackSpeed() {
    if (!this.audioElement) return;
    this.emit("sd-playback-speed");
    this.speed = this.speed === 1.5 ? 1 : this.speed + 0.25;
    this.audioElement.playbackRate = this.speed;
  }
  togglePlaybackSpeedKeydown(event) {
    if (event.key === "Enter") {
      event.preventDefault();
      this.togglePlaybackSpeed();
    }
  }
  formatTime(time) {
    const minutes = Math.floor(time / 60).toString().padStart(2, "0");
    const seconds = Math.floor(time % 60).toString().padStart(2, "0");
    return `${minutes}:${seconds}`;
  }
  handleAudioProgress() {
    if (!this.audioElement) return;
    const newTime = Number(this.progressSlider.value);
    this.audioElement.currentTime = newTime;
    this.progress = newTime;
    this.currentTime = this.formatTime(newTime);
  }
  handleAudioProgressKeydown(event) {
    if (event.key === "ArrowRight") {
      this.progressSlider.value = (Number(this.progressSlider.value) + 1).toString();
      this.handleAudioProgress();
    }
    if (event.key === "ArrowLeft") {
      this.progressSlider.value = (Number(this.progressSlider.value) - 1).toString();
      this.handleAudioProgress();
    }
  }
  handleTranscriptDrawerToggle() {
    this.isTranscriptOpen = !this.isTranscriptOpen;
  }
  handleThumbGrab() {
    var _a;
    (_a = this.audioElement) == null ? void 0 : _a.pause();
  }
  handleThumbRelease() {
    var _a;
    if (this.isPlaying) {
      (_a = this.audioElement) == null ? void 0 : _a.play();
    }
  }
  showTranscript() {
    this.emit("sd-transcript-click");
    this.drawer.open = true;
    this.handleTranscriptDrawerToggle();
  }
  showTranscriptKeydown(event) {
    if (event.key === "Enter" || event.key === " ") {
      this.showTranscript();
    }
  }
  rgbToHex(rgbString) {
    const result = rgbString.match(/\d+/g);
    if ((result == null ? void 0 : result.length) === 3) {
      const r = parseInt(result[0]);
      const g = parseInt(result[1]);
      const b = parseInt(result[2]);
      const valueToHex = (value) => value.toString(16).padStart(2, "0");
      const hex = `#${valueToHex(r)}${valueToHex(g)}${valueToHex(b)}`.toUpperCase();
      return hex;
    }
    return null;
  }
  onThemeChange() {
    this.clear();
    setTimeout(this.initAnimation.bind(this), this.token("--sd-duration-fast", 150));
  }
  initAnimation() {
    var _a;
    const context = (_a = this.canvas) == null ? void 0 : _a.getContext("2d");
    if (!context) return;
    this.context = context;
    const button = this.audioPlayerContainer.querySelector(".playback-speed");
    const computedStyles = window.getComputedStyle(button);
    const color = computedStyles.color;
    const computedColor = this.inverted ? `#FFFFFF33` : this.rgbToHex(color) + "33";
    this.waveList = [
      new Wave({
        canvas: this.canvas,
        color: computedColor,
        phase: 240,
        shift: 1.5,
        amplitude: 230,
        frequency: 0.012,
        damping: 1
      }),
      new Wave({
        canvas: this.canvas,
        color: computedColor,
        phase: 180,
        shift: 2.5,
        amplitude: 250,
        frequency: 5e-3,
        damping: 1
      }),
      new Wave({
        canvas: this.canvas,
        color: computedColor,
        phase: 180,
        shift: -2.5,
        amplitude: 250,
        frequency: 5e-3,
        damping: 1
      }),
      new Wave({
        canvas: this.canvas,
        color: computedColor,
        phase: 180,
        shift: -1,
        amplitude: 200,
        frequency: 0.018,
        damping: 1
      }),
      new Wave({
        canvas: this.canvas,
        color: computedColor,
        phase: 180,
        shift: 1.5,
        amplitude: 150,
        frequency: 0.01,
        damping: 1
      })
    ];
    if (this.animated) {
      this.drawStillWaves();
    }
  }
  drawStillWaves() {
    this.waveList.forEach((wave) => {
      wave.redraw();
    });
  }
  stopAnimation() {
    this.isPlaying = false;
  }
  clear() {
    if (!this.context || !this.canvas) return;
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  }
  async draw() {
    if (!this.isPlaying || !this.animated) return;
    this.clear();
    this.waveList.forEach((wave) => {
      wave.redraw();
    });
    await new Promise((resolve) => {
      setTimeout(resolve, 1e3 / 30);
    });
    await this.draw();
  }
  render() {
    const renderAudioControls = html`<div class="${cx(
      "controls grid grid-cols-3 justify-items-center items-center",
      this.reversedLayout ? "mt-2" : "mb-2",
      !this.animated && "relative",
      this.animated && !this.reversedLayout && "absolute -top-4 left-0 w-full"
    )}" part="audio-controls"><button class="${cx(
      "playback-speed justify-self-start text-base font-bold hover:cursor-pointer sd-interactive",
      this.inverted && "sd-interactive--inverted"
    )}" aria-label="${this.localize.term("playbackSpeed")} (${this.speed}x)" @click="${this.togglePlaybackSpeed}" @keydown="${this.togglePlaybackSpeedKeydown}" part="playback-speed">${this.speed}x</button><sd-6-22-0-button ?inverted="${this.inverted ? true : false}" part="play-button" size="lg" @click="${!this.isPlaying ? this.playAudio : this.pauseAudio}" aria-label="${this.isPlaying ? this.localize.term("pauseAudio") : this.localize.term("playAudio")}" title="${this.isPlaying ? this.localize.term("pauseAudio") : this.localize.term("playAudio")}" class="mb-4">${this.isPlaying ? html`<slot name="pause-icon"><sd-6-22-0-icon class="text-xl" name="pause" library="_internal"></sd-6-22-0-icon></slot>` : html`<slot name="play-icon"><sd-6-22-0-icon class="text-xl" name="start" library="_internal"></sd-6-22-0-icon></slot>`}</sd-6-22-0-button><div class="flex items-center gap-6 justify-self-end">${this.hasSlotController.test("transcript") ? html`<button class="${cx("w-6 h-6 hover:cursor-pointer sd-interactive", this.inverted && "sd-interactive--inverted")}" aria-label="${this.isTranscriptOpen ? this.localize.term("transcriptIsOpen") : this.localize.term("openTranscript")}" @click="${this.showTranscript}" @keydown="${this.showTranscriptKeydown}" part="transcript"><sd-6-22-0-icon class="w-6 h-6" name="transcript" library="_internal"></sd-6-22-0-icon></button>` : null} <button class="${cx("w-6 h-6 hover:cursor-pointer sd-interactive", this.inverted && "sd-interactive--inverted")}" part="volume" aria-label="${!this.isMuted ? this.localize.term("mute") : this.localize.term("unmute")}" @click="${this.toggleMute}" @keydown="${this.toggleMuteKeydown}"><sd-6-22-0-icon class="w-6 h-6" name="${this.isMuted ? "mute" : "volume"}" library="_internal"></sd-6-22-0-icon></button></div></div>`;
    const renderTimestamps = html`<div class="${cx(
      "w-full flex justify-between",
      this.reversedLayout ? "mb-0.5" : "mt-0.5",
      this.animated && this.reversedLayout && "absolute bottom-0 left-0 !mb-4"
    )}" part="timestamps"><div class="${cx("current-time text-sm", this.inverted ? "text-primary-400" : "sd-6-22-0-audio__timestamp-color-text")}">${this.currentTime}</div><div class="${cx("current-time text-sm", this.inverted ? "text-primary-400" : "sd-6-22-0-audio__timestamp-color-text")}">${this.duration}</div></div>`;
    return html`<div class="${cx("w-full flex relative", this.reversedLayout ? "flex-col-reverse" : "flex-col")}" aria-label="${this.localize.term("audioPlayer")}" part="audio-player"><slot @slotchange="${this.updateAudioDuration}"></slot>${!this.animated || this.animated && this.reversedLayout ? renderAudioControls : null}<div class="relative">${this.animated && !this.reversedLayout ? html`${renderAudioControls}` : null} ${this.animated ? html`<canvas class="w-full h-16 -mb-2"></canvas>` : null} ${!this.hideTimestamps && this.animated && this.reversedLayout ? renderTimestamps : null}<sd-6-22-0-range part="progress-slider" tooltip="hidden" min="0" max="100" step="0.001" label="${this.localize.term("seekBar")}" @mousedown="${this.handleThumbGrab}" @touchstart="${this.handleThumbGrab}" @mouseup="${this.handleThumbRelease}" @touchend="${this.handleThumbRelease}" @sd-6-22-0-input="${this.handleAudioProgress}" @keydown="${this.handleAudioProgressKeydown}"></sd-6-22-0-range></div>${this.hasSlotController.test("transcript") ? html`<sd-6-22-0-drawer><slot name="transcript"></slot></sd-6-22-0-drawer>` : null} ${!this.hideTimestamps && (!this.animated || !this.reversedLayout) ? renderTimestamps : null}</div><sd-6-22-0-theme-listener></sd-6-22-0-theme-listener>`;
  }
};
SdAudio.styles = [
  ...SolidElement.styles,
  css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer theme,base,components,utilities;
sd-6-22-0-button::part(base){display:flex;height:var(--sd-spacing-12);width:var(--sd-spacing-12);align-items:center;justify-content:center;border-radius:var(--sd-radius-full)}sd-6-22-0-button::part(motion-wrapper){border-radius:var(--sd-radius-full)}sd-6-22-0-button::part(label){display:flex;flex-grow:0;align-items:center}sd-6-22-0-range::part(form-control-label){display:none}:host([inverted]) sd-6-22-0-range::part(thumb){outline-color:rgba(var(--sd-color-border-white,var(--sd-color-white)));background-color:rgba(var(--sd-color-icon-fill-white,rgba(var(--sd-color-white))))}:host([animated]) sd-6-22-0-range::part(track){background-color:transparent}:host([inverted]:not([animated])) sd-6-22-0-range::part(track){background-color:rgba(var(--sd-audio__slide-bar--inverted-color-background,rgba(var(--sd-color-primary-400))))}:host([inverted]:not([animated])) sd-6-22-0-range::part(active-track){background-color:rgba(var(--sd-audio__track-bar--inverted-color-background,rgba(var(--sd-color-white))))}.sd-6-22-0-audio__timestamp-color-text{color:rgb(var(--sd-audio__timestamp-color-text,var(--sd-color-text-neutral-700)))}`
];
__decorateClass([
  property({ type: Boolean, reflect: true, attribute: "reversed-layout" })
], SdAudio.prototype, "reversedLayout", 2);
__decorateClass([
  property({ type: Boolean, reflect: true, attribute: "hide-timestamps" })
], SdAudio.prototype, "hideTimestamps", 2);
__decorateClass([
  property({ type: Boolean, reflect: true })
], SdAudio.prototype, "animated", 2);
__decorateClass([
  property({ type: Boolean, reflect: true })
], SdAudio.prototype, "inverted", 2);
__decorateClass([
  property({ type: Number, reflect: true })
], SdAudio.prototype, "speed", 2);
__decorateClass([
  state()
], SdAudio.prototype, "currentTime", 2);
__decorateClass([
  state()
], SdAudio.prototype, "duration", 2);
__decorateClass([
  state()
], SdAudio.prototype, "isPlaying", 2);
__decorateClass([
  state()
], SdAudio.prototype, "isMuted", 2);
__decorateClass([
  state()
], SdAudio.prototype, "isTranscriptOpen", 2);
__decorateClass([
  state()
], SdAudio.prototype, "progress", 2);
__decorateClass([
  query('[part="progress-slider"]')
], SdAudio.prototype, "progressSlider", 2);
__decorateClass([
  query('[part="audio-player"]')
], SdAudio.prototype, "audioPlayerContainer", 2);
__decorateClass([
  query("sd-6-22-0-drawer")
], SdAudio.prototype, "drawer", 2);
__decorateClass([
  query("canvas")
], SdAudio.prototype, "canvas", 2);
SdAudio = __decorateClass([
  customElement("sd-6-22-0-audio")
], SdAudio);

export {
  SdAudio
};
