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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
import { formatTime } from './utils.js';

export class AudioPlayer {
    /**
     * Creates an audio player instance
     * @param {HTMLElement} audioElement - The audio element to control
     * @param {HTMLElement} containerElement - The container element with player controls
     * @param {Object} options - Configuration options
     */
    constructor(audioElement, containerElement, options = {}) {
        if (!(audioElement instanceof HTMLAudioElement)) {
            throw new Error('First argument must be an HTMLAudioElement');
        }
        if (!(containerElement instanceof HTMLElement)) {
            throw new Error('Second argument must be an HTMLElement');
        }

        this.audio = audioElement;
        this.container = containerElement;
        this.options = {
            title: '',
            autoplay: false,
            volume: 1.0,
            onPlay: null,
            onPause: null,
            onEnded: null,
            onTimeUpdate: null,
            onVolumeChange: null,
            ...options,
        };

        this.isDragging = false;
        this.isDestroyed = false;

        // Store bound event handlers for cleanup
        this.boundHandlers = {
            // Audio event handlers
            audioLoadedMetadata: this.onAudioLoadedMetadata.bind(this),
            audioTimeUpdate: this.onAudioTimeUpdate.bind(this),
            audioPlay: this.onAudioPlay.bind(this),
            audioPause: this.onAudioPause.bind(this),
            audioEnded: this.onAudioEnded.bind(this),
            audioVolumeChange: this.onAudioVolumeChange.bind(this),
            // Control event handlers
            playPauseClick: this.onPlayPauseClick.bind(this),
            volumeClick: this.onVolumeClick.bind(this),
            volumeInput: this.onVolumeInput.bind(this),
            progressMouseDown: this.onProgressMouseDown.bind(this),
            progressClick: this.onProgressClick.bind(this),
            progressMouseMove: this.onProgressMouseMove.bind(this),
            documentMouseMove: this.onDocumentMouseMove.bind(this),
            documentMouseUp: this.onDocumentMouseUp.bind(this),
        };

        // MutationObserver for DOM cleanup detection
        this.observer = null;

        this.init();
    }

    /**
     * Initializes the audio player by setting up elements, events, and initial state
     * @returns {void}
     */
    init() {
        this.findElements();
        this.bindEvents();
        this.setupDOMObserver();

        if (this.options.title) {
            this.setTitle(this.options.title);
        } else if (this.audio.title) {
            this.setTitle(this.audio.title);
        } else if (this.audio.src) {
            const srcParts = this.audio.src.split('/');
            this.setTitle(decodeURIComponent(srcParts[srcParts.length - 1]));
        }

        if (this.options.autoplay) {
            this.play();
        }

        this.setVolume(this.options.volume);

        // Initialize time displays
        this.updateTimeDisplays();
    }

    /**
     * Finds and caches all required DOM elements within the container
     * @returns {void}
     */
    findElements() {
        this.elements = {
            title: this.container.querySelector('.audio-player-title'),
            playPauseBtn: this.container.querySelector('.audio-player-play-pause'),
            currentTime: this.container.querySelector('.audio-player-current-time'),
            totalTime: this.container.querySelector('.audio-player-total-time'),
            progress: this.container.querySelector('.audio-player-progress'),
            progressBar: this.container.querySelector('.audio-player-progress-bar'),
            volumeBtn: this.container.querySelector('.audio-player-volume'),
        };

        // Validate required elements
        const requiredElements = ['playPauseBtn', 'currentTime', 'totalTime', 'progress', 'progressBar', 'volumeBtn'];
        for (const key of requiredElements) {
            if (!this.elements[key]) {
                console.warn(`AudioPlayer: Required element .audio-player-${key.replace(/([A-Z])/g, '-$1').toLowerCase()} not found`);
            }
        }
    }

    /**
     * Sets up a MutationObserver to detect when audio or container elements are removed from DOM
     * @returns {void}
     */
    setupDOMObserver() {
        // Watch for removal of audio or container from DOM
        this.observer = new MutationObserver((mutations) => {
            for (const mutation of mutations) {
                for (const node of mutation.removedNodes) {
                    if (node === this.audio || node === this.container ||
                        node.contains?.(this.audio) || node.contains?.(this.container)) {
                        this.destroy();
                        return;
                    }
                }
            }
        });

        // Observe the parent nodes
        const chatParent = this.audio.closest('#chat') ?? document.body;

        if (chatParent) {
            this.observer.observe(chatParent, { childList: true, subtree: true });
        }
    }

    /**
     * Binds all event listeners to audio and control elements
     * @returns {void}
     */
    bindEvents() {
        // Audio events
        this.audio.addEventListener('loadedmetadata', this.boundHandlers.audioLoadedMetadata);
        this.audio.addEventListener('timeupdate', this.boundHandlers.audioTimeUpdate);
        this.audio.addEventListener('play', this.boundHandlers.audioPlay);
        this.audio.addEventListener('pause', this.boundHandlers.audioPause);
        this.audio.addEventListener('ended', this.boundHandlers.audioEnded);
        this.audio.addEventListener('volumechange', this.boundHandlers.audioVolumeChange);

        // Control events
        if (this.elements.playPauseBtn) {
            this.elements.playPauseBtn.addEventListener('click', this.boundHandlers.playPauseClick);
        }
        if (this.elements.volumeBtn) {
            this.elements.volumeBtn.addEventListener('click', this.boundHandlers.volumeClick);
        }
        if (this.elements.progress) {
            this.elements.progress.addEventListener('mousedown', this.boundHandlers.progressMouseDown);
            this.elements.progress.addEventListener('click', this.boundHandlers.progressClick);
            this.elements.progress.addEventListener('mousemove', this.boundHandlers.progressMouseMove);
        }
    }

    /**
     * Removes all event listeners from audio and control elements
     * @returns {void}
     */
    unbindEvents() {
        // Audio events
        this.audio.removeEventListener('loadedmetadata', this.boundHandlers.audioLoadedMetadata);
        this.audio.removeEventListener('timeupdate', this.boundHandlers.audioTimeUpdate);
        this.audio.removeEventListener('play', this.boundHandlers.audioPlay);
        this.audio.removeEventListener('pause', this.boundHandlers.audioPause);
        this.audio.removeEventListener('ended', this.boundHandlers.audioEnded);
        this.audio.removeEventListener('volumechange', this.boundHandlers.audioVolumeChange);

        // Control events
        if (this.elements.playPauseBtn) {
            this.elements.playPauseBtn.removeEventListener('click', this.boundHandlers.playPauseClick);
        }
        if (this.elements.volumeBtn) {
            this.elements.volumeBtn.removeEventListener('click', this.boundHandlers.volumeClick);
        }
        if (this.elements.progress) {
            this.elements.progress.removeEventListener('mousedown', this.boundHandlers.progressMouseDown);
            this.elements.progress.removeEventListener('click', this.boundHandlers.progressClick);
            this.elements.progress.removeEventListener('mousemove', this.boundHandlers.progressMouseMove);
        }

        // Document events
        document.removeEventListener('mousemove', this.boundHandlers.documentMouseMove);
        document.removeEventListener('mouseup', this.boundHandlers.documentMouseUp);
    }

    // Audio event handlers
    /**
     * Handles the audio element's loadedmetadata event
     * @returns {void}
     */
    onAudioLoadedMetadata() {
        if (this.isDestroyed) return;
        this.updateTimeDisplays();
    }

    /**
     * Handles the audio element's timeupdate event
     * @returns {void}
     */
    onAudioTimeUpdate() {
        if (this.isDestroyed || this.isDragging) return;

        const percent = (this.audio.currentTime / this.audio.duration) * 100 || 0;
        if (this.elements.progressBar) {
            /** @type {HTMLElement} */ (this.elements.progressBar).style.width = percent + '%';
        }
        if (this.elements.currentTime) {
            this.elements.currentTime.textContent = formatTime(this.audio.currentTime);
        }

        if (typeof this.options.onTimeUpdate === 'function') {
            this.options.onTimeUpdate.call(this, this.audio.currentTime, this.audio.duration);
        }
    }

    /**
     * Handles the audio element's play event
     * @returns {void}
     */
    onAudioPlay() {
        if (this.isDestroyed) return;

        if (this.elements.playPauseBtn) {
            this.elements.playPauseBtn.classList.remove('fa-play');
            this.elements.playPauseBtn.classList.add('fa-pause');
            this.elements.playPauseBtn.setAttribute('title', 'Pause');
        }

        if (typeof this.options.onPlay === 'function') {
            this.options.onPlay.call(this);
        }
    }

    /**
     * Handles the audio element's pause event
     * @returns {void}
     */
    onAudioPause() {
        if (this.isDestroyed) return;

        if (this.elements.playPauseBtn) {
            this.elements.playPauseBtn.classList.remove('fa-pause');
            this.elements.playPauseBtn.classList.add('fa-play');
            this.elements.playPauseBtn.setAttribute('title', 'Play');
        }

        if (typeof this.options.onPause === 'function') {
            this.options.onPause.call(this);
        }
    }

    /**
     * Handles the audio element's ended event
     * @returns {void}
     */
    onAudioEnded() {
        if (this.isDestroyed) return;

        if (this.elements.playPauseBtn) {
            this.elements.playPauseBtn.classList.remove('fa-pause');
            this.elements.playPauseBtn.classList.add('fa-play');
            this.elements.playPauseBtn.setAttribute('title', 'Play');
        }

        if (typeof this.options.onEnded === 'function') {
            this.options.onEnded.call(this);
        }
    }

    /**
     * Handles the audio element's volumechange event
     * @returns {void}
     */
    onAudioVolumeChange() {
        if (this.isDestroyed) return;

        this.updateVolumeIcon();

        if (typeof this.options.onVolumeChange === 'function') {
            this.options.onVolumeChange.call(this, this.audio.volume, this.audio.muted);
        }
    }

    // Control event handlers
    /**
     * Handles click events on the play/pause button
     * @param {MouseEvent} e - The click event
     * @returns {void}
     */
    onPlayPauseClick(e) {
        e.preventDefault();
        this.togglePlay();
    }

    /**
     * Handles click events on the volume button
     * @param {MouseEvent} e - The click event
     * @returns {void}
     */
    onVolumeClick(e) {
        e.preventDefault();
        this.toggleMute();
    }

    /**
     * Handles input events on the volume slider
     * @param {InputEvent} e - The input event
     * @returns {void}
     */
    onVolumeInput(e) {
        if (!(e.target instanceof HTMLInputElement)) return;
        const value = parseFloat(e.target.value);
        this.setVolume(value);
    }

    /**
     * Handles mousedown events on the progress bar
     * @param {MouseEvent} e - The mousedown event
     * @returns {void}
     */
    onProgressMouseDown(e) {
        this.isDragging = true;
        this.updateProgress(e);
        document.addEventListener('mousemove', this.boundHandlers.documentMouseMove);
        document.addEventListener('mouseup', this.boundHandlers.documentMouseUp);
    }

    /**
     * Handles click events on the progress bar
     * @param {MouseEvent} e - The click event
     * @returns {void}
     */
    onProgressClick(e) {
        if (!this.isDragging) {
            this.updateProgress(e);
        }
    }

    /**
     * Handles mousemove on the progress bar (no-op if dragging)
     * @param {MouseEvent} e - The mousemove event
     * @returns {void}
     */
    onProgressMouseMove(e) {
        if (!this.isDragging) {
            this.updateProgressTitle(e);
        }
    }

    /**
     * Handles document mousemove events during progress bar dragging
     * @param {MouseEvent} e - The mousemove event
     * @returns {void}
     */
    onDocumentMouseMove(e) {
        if (this.isDragging) {
            this.updateProgress(e);
        }
    }

    /**
     * Handles document mouseup events to end progress bar dragging
     * @returns {void}
     */
    onDocumentMouseUp() {
        if (this.isDragging) {
            this.isDragging = false;
            document.removeEventListener('mousemove', this.boundHandlers.documentMouseMove);
            document.removeEventListener('mouseup', this.boundHandlers.documentMouseUp);
        }
    }

    /**
     * Updates the progress bar position and seeks audio based on mouse position
     * @param {MouseEvent} e - The mouse event containing position information
     * @returns {void}
     */
    updateProgress(e) {
        if (!this.elements.progress) return;

        const rect = this.elements.progress.getBoundingClientRect();
        const offsetX = e.clientX - rect.left;
        const width = rect.width;
        const percent = Math.max(0, Math.min(100, (offsetX / width) * 100));

        if (this.elements.progressBar) {
            /** @type {HTMLElement} */ (this.elements.progressBar).style.width = percent + '%';
        }

        const seekTime = (percent / 100) * this.audio.duration;
        if (isFinite(seekTime)) {
            this.audio.currentTime = seekTime;
            if (this.elements.currentTime) {
                this.elements.currentTime.textContent = formatTime(seekTime);
            }
        }
    }

    /**
     * Updates the volume icon based on current volume and mute state
     * @returns {void}
     */
    updateVolumeIcon() {
        if (!this.elements.volumeBtn) return;

        const volume = this.audio.volume;
        const isMuted = this.audio.muted;

        this.elements.volumeBtn.classList.remove('fa-volume-high', 'fa-volume-low', 'fa-volume-off', 'fa-volume-xmark');

        if (isMuted || volume === 0) {
            this.elements.volumeBtn.classList.add('fa-volume-xmark');
        } else if (volume < 0.5) {
            this.elements.volumeBtn.classList.add('fa-volume-low');
        } else {
            this.elements.volumeBtn.classList.add('fa-volume-high');
        }
    }

    /**
     * Updates the current time and total time display elements
     * @returns {void}
     */
    updateTimeDisplays() {
        if (this.elements.currentTime) {
            this.elements.currentTime.textContent = formatTime(this.audio.currentTime || 0);
        }
        if (this.elements.totalTime) {
            this.elements.totalTime.textContent = formatTime(this.audio.duration || 0);
        }
    }

    /**
     * Updates the mouseover title on the progress bar to show time at cursor position
     * @param {MouseEvent} e - The mouse event
     * @returns {void}
     */
    updateProgressTitle(e) {
        if (!this.elements.progress) return;

        const rect = this.elements.progress.getBoundingClientRect();
        const offsetX = e.clientX - rect.left;
        const width = rect.width;
        const percent = Math.max(0, Math.min(100, (offsetX / width) * 100));

        this.elements.progress.setAttribute('title', formatTime((percent / 100) * this.audio.duration));
    }

    // Public methods
    /**
     * Starts audio playback
     * @returns {void}
     */
    play() {
        if (this.isDestroyed) return;
        if (this.audio.paused) {
            const playPromise = this.audio.play();
            if (playPromise !== undefined) {
                playPromise.catch(error => {
                    console.error('Audio play failed:', error);
                });
            }
        }
    }

    /**
     * Pauses audio playback
     * @returns {void}
     */
    pause() {
        if (this.isDestroyed) return;
        if (!this.audio.paused) {
            this.audio.pause();
        }
    }

    /**
     * Toggles between play and pause states
     * @returns {void}
     */
    togglePlay() {
        if (this.audio.paused) {
            this.play();
        } else {
            this.pause();
        }
    }

    /**
     * Seeks to a specific time in the audio
     * @param {number} time - The time in seconds to seek to
     * @returns {void}
     */
    seek(time) {
        if (this.isDestroyed) return;
        if (isFinite(time) && time >= 0 && time <= this.audio.duration) {
            this.audio.currentTime = time;
        }
    }

    /**
     * Sets the volume level
     * @param {number} volume - Volume level between 0.0 and 1.0
     * @returns {void}
     */
    setVolume(volume) {
        if (this.isDestroyed) return;
        volume = Math.max(0, Math.min(1, volume));
        this.audio.volume = volume;

        if (volume > 0 && this.audio.muted) {
            this.audio.muted = false;
        }
    }

    /**
     * Mutes the audio
     * @returns {void}
     */
    mute() {
        if (this.isDestroyed) return;
        this.audio.muted = true;
    }

    /**
     * Unmutes the audio
     * @returns {void}
     */
    unmute() {
        if (this.isDestroyed) return;
        this.audio.muted = false;
    }

    /**
     * Toggles the mute state
     * @returns {void}
     */
    toggleMute() {
        if (this.isDestroyed) return;
        this.audio.muted = !this.audio.muted;
    }

    /**
     * Sets the audio source URL
     * @param {string} src - The URL of the audio file
     * @returns {void}
     */
    setSrc(src) {
        if (this.isDestroyed) return;
        this.audio.src = src;
    }

    /**
     * Sets the title displayed in the player
     * @param {string} title - The title text to display
     * @returns {void}
     */
    setTitle(title) {
        if (this.isDestroyed) return;
        this.options.title = title;
        if (this.elements.title) {
            this.elements.title.textContent = title;
        }
    }

    /**
     * Cleans up the player by removing event listeners and clearing references
     * @returns {void}
     */
    destroy() {
        if (this.isDestroyed) return;
        this.isDestroyed = true;

        // Stop observing DOM changes
        if (this.observer) {
            this.observer.disconnect();
            this.observer = null;
        }

        // Pause and clear audio
        this.pause();
        this.audio.src = '';

        // Remove all event listeners
        this.unbindEvents();

        // Clear references to prevent memory leaks
        this.audio = null;
        this.container = null;
        this.elements = null;
        this.options = null;
        this.boundHandlers = null;
    }
}