import { p as proxyCustomElement, H, h, c as Host } from './p-ae373651.js';
import { h as hark } from './p-3f882e7c.js';
import { e as defaultIconPack, i as useLanguage } from './p-5b3a7f00.js';
import { S as SyncWithStore } from './p-070aa695.js';
import { d as defineCustomElement$1 } from './p-3e0452c4.js';

/**
 * Draws audio visualizer of variant `bars`
 * @param canvas Canvas element
 * @param volume Current volume
 */
const drawBarsVisualizer = (canvas, volume) => {
    if (canvas == null) {
        return;
    }
    const nSlices = 3;
    const halfwaySlice = Math.round(nSlices / 2);
    const sample = [...Array(nSlices)].map((_, i) => {
        let index = i;
        if (index > halfwaySlice - 1) {
            index = nSlices - index - 1;
        }
        return Math.round(((index + 1) / (halfwaySlice + 1)) * volume);
    });
    const { width, height } = canvas;
    const context = canvas.getContext('2d');
    let x = 2;
    const sliceGraphicWidth = 4;
    const sliceWidth = (width * 1.0) / sample.length;
    const slicePadding = sliceWidth - sliceGraphicWidth;
    context.clearRect(0, 0, width, height);
    context.fillStyle = 'rgb(0,0,0,0.0)';
    context.fillRect(0, 0, width, height);
    const color = getComputedStyle(canvas).getPropertyValue('color');
    context.fillStyle = color;
    context.strokeStyle = color;
    context.lineCap = 'round';
    context.lineWidth = 4;
    context.beginPath();
    for (const item of sample) {
        const y = Math.min(-Math.abs(((item * 1.2) / 10) * height) + height / 2, height / 2 - 2.5);
        const sliceHeight = Math.max((height / 2 - y) * 2, 5);
        context.moveTo(x + slicePadding / 2, y);
        context.lineTo(x + slicePadding / 2, y + sliceHeight);
        x += sliceWidth;
    }
    context.stroke();
};

const rtkAudioVisualizerCss = ":host{line-height:initial;font-family:var(--rtk-font-family, sans-serif);font-feature-settings:normal;font-variation-settings:normal}p{margin:var(--rtk-space-0, 0px);padding:var(--rtk-space-0, 0px)}:host{display:block;width:-moz-fit-content;width:fit-content}.audioActivePadding{padding:var(--rtk-space-1, 4px)}canvas,rtk-icon{height:var(--rtk-space-6, 24px);width:var(--rtk-space-6, 24px)}:host([size='sm']){transform:scale(0.9)}canvas{display:none}canvas.visible{display:block}canvas.bars{--tw-text-opacity:1;color:rgba(var(--rtk-colors-brand-500, 33 96 253) / var(--tw-text-opacity))}";
const RtkAudioVisualizerStyle0 = rtkAudioVisualizerCss;

var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
        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;
};
const RtkAudioVisualizer = /*@__PURE__*/ proxyCustomElement(class RtkAudioVisualizer extends H {
    constructor() {
        super();
        this.__registerHost();
        this.__attachShadow();
        /** Variant */
        this.variant = 'bars';
        /** Icon pack */
        this.iconPack = defaultIconPack;
        /** Language */
        this.t = useLanguage();
        /** Hide the visualizer if audio is muted */
        this.hideMuted = false;
        /** Audio visualizer for screensharing, it will use screenShareTracks.audio instead of audioTrack */
        this.isScreenShare = false;
        this.volume = 0;
    }
    connectedCallback() {
        this.participantChanged(this.participant);
    }
    componentDidLoad() {
        drawBarsVisualizer(this.visualizer, 0);
    }
    disconnectedCallback() {
        var _a, _b, _c;
        (_a = this.hark) === null || _a === void 0 ? void 0 : _a.stop();
        this.audioUpdateListener &&
            ((_b = this.participant) === null || _b === void 0 ? void 0 : _b.removeListener('audioUpdate', this.audioUpdateListener));
        this.screenShareUpdateListener &&
            ((_c = this.participant) === null || _c === void 0 ? void 0 : _c.removeListener('screenShareUpdate', this.screenShareUpdateListener));
    }
    participantChanged(participant) {
        if (participant != null) {
            this.audioUpdateListener = ({ audioEnabled, audioTrack }) => {
                var _a;
                (_a = this.hark) === null || _a === void 0 ? void 0 : _a.stop();
                if (audioEnabled && audioTrack != null) {
                    this.audioEnabled = true;
                    const stream = new MediaStream();
                    stream.addTrack(audioTrack);
                    this.calcVolume(stream);
                    // initial draw with volume: 0
                    drawBarsVisualizer(this.visualizer, 0);
                }
                else {
                    this.volume = 0;
                    this.audioEnabled = false;
                }
            };
            if (this.isScreenShare) {
                this.screenShareUpdateListener = ({ screenShareEnabled, screenShareTracks }) => {
                    this.audioUpdateListener({
                        audioEnabled: screenShareEnabled && screenShareTracks.audio != null,
                        audioTrack: screenShareTracks.audio,
                    });
                };
                this.screenShareUpdateListener({
                    screenShareEnabled: participant.screenShareEnabled,
                    screenShareTracks: {
                        audio: participant.screenShareTracks.audio,
                        video: participant.screenShareTracks.video,
                    },
                });
                participant.addListener('screenShareUpdate', this.screenShareUpdateListener);
            }
            else {
                this.audioUpdateListener(participant);
                participant.addListener('audioUpdate', this.audioUpdateListener);
            }
        }
    }
    /**
     * Determines the volume from a given MediaStream and updates the components state
     * @param stream A MediaStream with AudioTrack(s) added
     */
    calcVolume(stream) {
        this.hark = hark(stream, {
            play: false,
            interval: 1000 / 10,
        });
        this.hark.on('volume_change', (dBs) => {
            const prevVolume = this.volume;
            // The exact formula to convert from dBs (-100..0) to linear (0..1) is:
            //   Math.pow(10, dBs / 20)
            // However it does not produce a visually useful output, so let exagerate
            // it a bit. Also, let convert it from 0..1 to 0..10 and avoid value 1 to
            // minimize component renderings.
            // if dBs is -Inifnity, set vol to 0
            let audioVol = Math.round(10 ** (dBs / 115) * 10);
            if (audioVol < 3)
                audioVol = 0;
            let volume = Math.round((prevVolume * 2 + audioVol) / 3);
            if (prevVolume !== volume) {
                this.volume = volume;
                drawBarsVisualizer(this.visualizer, this.volume);
            }
        });
    }
    render() {
        if (this.hideMuted && !this.audioEnabled)
            return null;
        return (h(Host, null, h("div", { class: {
                audioActivePadding: this.hideMuted && this.audioEnabled,
            } }, h("canvas", { width: "24", height: "24", class: {
                bars: true,
                visible: this.audioEnabled,
            }, ref: (el) => (this.visualizer = el), part: "canvas" }), !this.isScreenShare && !this.audioEnabled && (h("rtk-icon", { icon: this.iconPack.mic_off, part: "mic-off-icon" })))));
    }
    static get watchers() { return {
        "participant": ["participantChanged"]
    }; }
    static get style() { return RtkAudioVisualizerStyle0; }
}, [1, "rtk-audio-visualizer", {
        "variant": [513],
        "participant": [16],
        "size": [513],
        "iconPack": [16],
        "t": [16],
        "hideMuted": [4, "hide-muted"],
        "isScreenShare": [4, "is-screen-share"],
        "audioEnabled": [32],
        "volume": [32]
    }, undefined, {
        "participant": ["participantChanged"]
    }]);
__decorate([
    SyncWithStore()
], RtkAudioVisualizer.prototype, "iconPack", void 0);
__decorate([
    SyncWithStore()
], RtkAudioVisualizer.prototype, "t", void 0);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["rtk-audio-visualizer", "rtk-icon"];
    components.forEach(tagName => { switch (tagName) {
        case "rtk-audio-visualizer":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, RtkAudioVisualizer);
            }
            break;
        case "rtk-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}
defineCustomElement();

export { RtkAudioVisualizer as R, defineCustomElement as d };
