(function () {
    var STORAGE_KEY = 'zalorox_music_player_state';
    var QUEUE_ENDPOINT = '/api/music/queue';
    var audio = new Audio();
    var active = null;
    var history = [];
    var queue = [];
    var playSent = {};
    var pendingSeek = null;
    var formatter = new Intl.NumberFormat('tr-TR');

    audio.preload = 'metadata';

    function toast(message, type) {
        if (window.ZaloroxToast) {
            window.ZaloroxToast.show(message, type || 'info');
        }
    }

    function csrf() {
        return window.ZALOROX_CSRF_TOKEN || '';
    }

    function post(endpoint, data) {
        data = data || {};
        if (!data._csrf) data._csrf = csrf();

        return fetch(endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-TOKEN': data._csrf,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: new URLSearchParams(data)
        }).then(function (response) {
            return response.json().then(function (json) {
                json.httpStatus = response.status;
                return json;
            });
        });
    }

    function getJson(endpoint) {
        return fetch(endpoint, {
            method: 'GET',
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        }).then(function (response) {
            return response.json().then(function (json) {
                json.httpStatus = response.status;
                return json;
            });
        });
    }

    function escapeHtml(value) {
        return String(value || '').replace(/[&<>"']/g, function (char) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            }[char];
        });
    }

    function formatTime(seconds) {
        seconds = Number.isFinite(seconds) ? Math.max(0, Math.floor(seconds)) : 0;
        var minutes = Math.floor(seconds / 60);
        var rest = seconds % 60;
        return minutes + ':' + String(rest).padStart(2, '0');
    }

    function absoluteUrl(value) {
        if (!value) return '';
        try {
            return new URL(value, window.location.origin).href;
        } catch (error) {
            return value;
        }
    }

    function normalizeTrack(raw, button) {
        raw = raw || {};
        var dataset = raw.dataset || {};
        var trackId = raw.trackId || raw.track_id || raw.id || dataset.trackId || '';
        var audioSrc = raw.audioSrc || raw.audio_src || raw.audio || dataset.audioSrc || '';
        var detailUrl = raw.detailUrl || raw.detail_url || dataset.detailUrl || '';

        return {
            trackId: String(trackId || ''),
            title: raw.title || dataset.trackTitle || 'Zalorox Music',
            artist: raw.artist || raw.artist_name || dataset.trackArtist || 'Zalorox Music',
            cover: raw.cover || raw.cover_image || dataset.trackCover || '/uploads/music-covers/track-1.svg',
            audioSrc: audioSrc ? absoluteUrl(audioSrc) : '',
            detailUrl: detailUrl ? absoluteUrl(detailUrl) : window.location.href,
            genre: raw.genre || dataset.trackGenre || 'Music',
            genreSlug: raw.genreSlug || raw.genre_slug || dataset.trackGenreSlug || 'music',
            locked: raw.locked === true || raw.locked === '1' || dataset.locked === '1' || dataset.trackLocked === '1',
            premium: raw.premium === true || raw.premium === '1',
            playEndpoint: raw.playEndpoint || raw.play_endpoint || dataset.playEndpoint || '/api/music/play',
            button: button || raw.button || null,
            panel: raw.panel || null
        };
    }

    function publicTrack(track) {
        if (!track) return null;

        return {
            trackId: track.trackId,
            title: track.title,
            artist: track.artist,
            cover: track.cover,
            audioSrc: track.audioSrc,
            detailUrl: track.detailUrl,
            genre: track.genre,
            genreSlug: track.genreSlug,
            locked: track.locked === true,
            premium: track.premium === true,
            playEndpoint: track.playEndpoint || '/api/music/play'
        };
    }

    function loadState() {
        try {
            var parsed = JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '{}');
            return parsed && typeof parsed === 'object' ? parsed : {};
        } catch (error) {
            return {};
        }
    }

    function saveState() {
        try {
            window.localStorage.setItem(STORAGE_KEY, JSON.stringify({
                track_id: active ? active.trackId : '',
                current_time: Number.isFinite(audio.currentTime) ? audio.currentTime : 0,
                volume: Number.isFinite(audio.volume) ? audio.volume : 0.82,
                muted: audio.muted === true,
                playing: active ? !audio.paused : false,
                track: publicTrack(active),
                queue: queue.map(publicTrack).filter(Boolean),
                history: history.map(publicTrack).filter(Boolean).slice(-8),
                saved_at: Date.now()
            }));
        } catch (error) {
            /* Music persistence is progressive enhancement. */
        }
    }

    function setButtonPlaying(button, playing) {
        if (!button) return;
        button.innerHTML = playing ? '<span aria-hidden="true">||</span>' : '<span aria-hidden="true">&#9658;</span>';
        button.setAttribute('aria-label', playing ? 'Duraklat' : 'Oynat');
    }

    function updateAllPlayButtons() {
        var playing = active ? !audio.paused : false;
        document.querySelectorAll('[data-player-toggle], [data-mini-toggle]').forEach(function (button) {
            setButtonPlaying(button, playing);
        });

        document.querySelectorAll('[data-track-play]').forEach(function (button) {
            var isCurrent = active && String(button.dataset.trackId || '') === active.trackId;
            button.classList.toggle('is-playing', isCurrent && playing);
            button.innerHTML = (isCurrent && playing ? '<span aria-hidden="true">||</span> Pause' : '<span aria-hidden="true">&#9658;</span> Play');
        });
    }

    function updateCounts(trackId, playCount, likeCount) {
        if (playCount !== undefined) {
            document.querySelectorAll('[data-play-count="' + trackId + '"]').forEach(function (node) {
                node.textContent = formatter.format(Number(playCount || 0)) + ' dinlenme';
            });
        }

        if (likeCount !== undefined) {
            document.querySelectorAll('[data-like-count="' + trackId + '"]').forEach(function (node) {
                node.textContent = formatter.format(Number(likeCount || 0)) + ' begeni';
            });
        }
    }

    function mini() {
        return document.querySelector('[data-mini-player]');
    }

    function syncMiniVisibility() {
        var box = mini();
        var visible = !!(active && !audio.paused && active.audioSrc);
        if (box) {
            box.hidden = !visible;
            box.classList.toggle('is-active', visible);
        }
        document.body.classList.toggle('has-active-mini-player', visible);

        var panel = queuePanel();
        if (!visible && panel) panel.hidden = true;
    }

    function attachVisiblePanel() {
        if (!active) return;
        var panel = document.querySelector('[data-music-player][data-track-id="' + active.trackId + '"]');
        active.panel = panel || null;
        active.button = panel ? panel.querySelector('[data-player-toggle]') : active.button || null;
    }

    function syncTrackMeta() {
        if (!active) return;
        attachVisiblePanel();

        var box = mini();
        if (box) {
            var cover = box.querySelector('[data-mini-cover]');
            var title = box.querySelector('[data-mini-title]');
            var artist = box.querySelector('[data-mini-artist]');

            if (cover && active.cover) cover.src = active.cover;
            if (title) title.textContent = active.title || 'Zalorox Music';
            if (artist) artist.textContent = active.artist || '';
            syncMiniVisibility();
        }

        updateAllPlayButtons();
        syncProgress();
        renderQueue();
    }

    function syncVolumeControls() {
        document.querySelectorAll('[data-player-volume], [data-mini-volume]').forEach(function (input) {
            if (document.activeElement !== input) input.value = String(audio.volume);
        });

        document.querySelectorAll('[data-player-mute], [data-mini-mute]').forEach(function (button) {
            button.classList.toggle('is-muted', audio.muted);
            button.textContent = audio.muted ? 'Sessiz' : 'Ses';
        });
    }

    function syncProgress() {
        var duration = Number.isFinite(audio.duration) ? audio.duration : 0;
        var current = Number.isFinite(audio.currentTime) ? audio.currentTime : 0;
        var ratio = duration ? current / duration : 0;
        var remaining = duration ? '-' + formatTime(Math.max(0, duration - current)) : '-0:00';

        if (active && active.panel) {
            var progress = active.panel.querySelector('[data-player-progress]');
            var currentNode = active.panel.querySelector('[data-player-current]');
            var remainingNode = active.panel.querySelector('[data-player-remaining]');
            var durationNode = active.panel.querySelector('[data-player-duration]');
            if (progress && document.activeElement !== progress) progress.value = Math.round(ratio * 1000);
            if (currentNode) currentNode.textContent = formatTime(current);
            if (remainingNode) remainingNode.textContent = remaining;
            if (durationNode) durationNode.textContent = formatTime(duration);
        }

        var miniProgress = document.querySelector('[data-mini-progress]');
        var miniCurrent = document.querySelector('[data-mini-current]');
        var miniRemaining = document.querySelector('[data-mini-remaining]');
        if (miniProgress) miniProgress.style.width = Math.max(0, Math.min(100, ratio * 100)) + '%';
        if (miniCurrent) miniCurrent.textContent = formatTime(current);
        if (miniRemaining) miniRemaining.textContent = remaining;
    }

    function showPremium(detailUrl) {
        if (window.ZaloroxModal) {
            window.ZaloroxModal.open('Site Premium', 'Bu sarki site premium aboneligi gerektiriyor. Muzik tarafinda creator paketi kullanilmaz.', [
                {
                    label: 'Kapat',
                    onClick: function () { window.ZaloroxModal.close(); }
                },
                {
                    label: 'Premium',
                    primary: true,
                    onClick: function () { window.location.href = '/checkout?site_plan=premium'; }
                },
                {
                    label: 'Detaya Git',
                    onClick: function () { window.location.href = detailUrl || '/music'; }
                }
            ]);
            return;
        }

        toast('Bu sarki site premium aboneligi gerektiriyor.', 'warning');
    }

    function showMissingAudio(detailUrl) {
        if (window.ZaloroxModal) {
            window.ZaloroxModal.open('Audio dosyasi yok', 'Bu kayitta yerel audio dosyasi yok. Detay sayfasindaki YouTube, Spotify veya Apple Music linklerini kullanabilirsin.', [
                {
                    label: 'Kapat',
                    onClick: function () { window.ZaloroxModal.close(); }
                },
                {
                    label: 'Detaya Git',
                    primary: true,
                    onClick: function () { window.location.href = detailUrl || '/music'; }
                }
            ]);
            return;
        }

        toast('Bu kayitta audio dosyasi yok.', 'info');
    }

    function sendPlay(trackId, endpoint) {
        if (!trackId || playSent[trackId]) return;
        playSent[trackId] = true;

        post(endpoint || '/api/music/play', { track_id: trackId }).then(function (json) {
            if (!json.ok) {
                if (json.httpStatus === 403) showPremium('/music');
                return;
            }

            updateCounts(trackId, json.play_count);
        }).catch(function () {
            playSent[trackId] = false;
        });
    }

    function setAudioTrack(track, seekTo) {
        var src = track.audioSrc ? absoluteUrl(track.audioSrc) : '';
        if (!src) return;

        if (audio.src !== src) {
            pendingSeek = Number.isFinite(seekTo) ? Math.max(0, seekTo) : 0;
            audio.src = src;
            audio.load();
            return;
        }

        if (Number.isFinite(seekTo)) {
            try {
                audio.currentTime = Math.max(0, seekTo);
            } catch (error) {
                pendingSeek = Math.max(0, seekTo);
            }
        }
    }

    function queueHasTrack(trackId) {
        return queue.some(function (item) {
            return item.trackId === String(trackId || '');
        });
    }

    function mergeQueue(items, replace) {
        var seen = active ? [active.trackId] : [];
        var next = [];
        if (!replace) {
            queue.forEach(function (item) {
                if (!item || !item.trackId || seen.indexOf(item.trackId) !== -1) return;
                seen.push(item.trackId);
                next.push(item);
            });
        }

        (items || []).forEach(function (item) {
            var track = normalizeTrack(item);
            if (!track.trackId || seen.indexOf(track.trackId) !== -1) return;
            seen.push(track.trackId);
            next.push(track);
        });

        queue = next.slice(0, 24);
        saveState();
        renderQueue();
    }

    function fetchQueueFor(track, replace) {
        if (!track || !track.trackId) return Promise.resolve([]);

        return getJson(QUEUE_ENDPOINT + '?track_id=' + encodeURIComponent(track.trackId)).then(function (json) {
            if (!json.ok && !Array.isArray(json.queue)) return [];
            var tracks = Array.isArray(json.queue) ? json.queue : [];
            mergeQueue(tracks, replace);
            return queue;
        }).catch(function () {
            return [];
        });
    }

    function playActive(silent) {
        if (!active) return;
        audio.play().then(function () {
            updateAllPlayButtons();
            saveState();
        }).catch(function () {
            updateAllPlayButtons();
            saveState();
            if (!silent) toast('Tarayici oynatmayi baslatamadi.', 'warning');
        });
    }

    function startTrack(track, options) {
        options = options || {};
        track = normalizeTrack(track, track.button || null);
        if (!track || !track.trackId) return;

        if (track.locked) {
            showPremium(track.detailUrl);
            return;
        }

        if (!track.audioSrc) {
            showMissingAudio(track.detailUrl);
            return;
        }

        if (active && active.trackId !== track.trackId && !options.fromHistory) {
            history.push(publicTrack(active));
            history = history.slice(-12);
        }

        active = track;
        setAudioTrack(track, Number.isFinite(options.seekTo) ? options.seekTo : 0);
        syncTrackMeta();
        syncVolumeControls();
        sendPlay(track.trackId, track.playEndpoint);

        if (!options.skipQueueRefresh && (!queue.length || !queueHasTrack(track.trackId))) {
            fetchQueueFor(track, true);
        }

        playActive(options.silent === true);
    }

    function pauseTrack() {
        audio.pause();
        updateAllPlayButtons();
        syncMiniVisibility();
        saveState();
    }

    function stopTrack() {
        audio.pause();
        audio.removeAttribute('src');
        try { audio.load(); } catch (error) {}
        active = null;
        queue = [];
        pendingSeek = null;
        updateAllPlayButtons();
        renderQueue();
        syncMiniVisibility();
        saveState();
        try {
            var stored = loadState();
            stored.playing = false;
            window.localStorage.setItem(STORAGE_KEY, JSON.stringify(stored));
        } catch (error) {}
    }

    function toggleTrack(track) {
        track = normalizeTrack(track, track.button || null);
        if (active && active.trackId === track.trackId && !audio.paused) {
            pauseTrack();
            return;
        }

        startTrack(track);
    }

    function findNextPlayable() {
        var skippedLocked = false;
        while (queue.length) {
            var candidate = queue.shift();
            if (!candidate || !candidate.trackId) continue;
            if (candidate.locked || !candidate.audioSrc) {
                skippedLocked = skippedLocked || candidate.locked;
                continue;
            }

            if (skippedLocked) toast('Premium sarkilar sirada kilitli oldugu icin atlandi.', 'info');
            return candidate;
        }

        if (skippedLocked) toast('Premium sarkilar sirada kilitli oldugu icin atlandi.', 'info');
        return null;
    }

    function playNext() {
        var next = findNextPlayable();
        if (next) {
            startTrack(next, { fromQueue: true, skipQueueRefresh: queue.length > 0 });
            renderQueue();
            saveState();
            return;
        }

        if (!active) return;
        fetchQueueFor(active, true).then(function () {
            var fetchedNext = findNextPlayable();
            if (fetchedNext) {
                startTrack(fetchedNext, { fromQueue: true, skipQueueRefresh: queue.length > 0 });
            } else {
                pauseTrack();
                toast('Siradaki sarki bulunamadi.', 'info');
            }
        });
    }

    function playPrevious() {
        if (audio.currentTime > 4) {
            audio.currentTime = 0;
            saveState();
            return;
        }

        var previous = history.pop();
        if (previous) {
            startTrack(previous, { fromHistory: true, skipQueueRefresh: true });
        }
    }

    function trackFromButton(button) {
        return normalizeTrack({
            dataset: button.dataset,
            button: button
        }, button);
    }

    function trackFromPanel(panel) {
        return normalizeTrack({
            dataset: panel.dataset,
            detailUrl: panel.dataset.detailUrl || window.location.href,
            button: panel.querySelector('[data-player-toggle]'),
            panel: panel
        }, panel.querySelector('[data-player-toggle]'));
    }

    function queuePanel() {
        return document.querySelector('[data-music-queue-panel]');
    }

    function toggleQueuePanel(forceOpen) {
        var panel = queuePanel();
        if (!panel) return;

        var open = typeof forceOpen === 'boolean' ? forceOpen : panel.hidden;
        panel.hidden = !open;
        document.querySelectorAll('[data-player-queue-toggle], [data-mini-queue]').forEach(function (button) {
            button.setAttribute('aria-expanded', open ? 'true' : 'false');
        });
        if (open) renderQueue();
    }

    function renderQueue() {
        var list = document.querySelector('[data-queue-list]');
        var count = document.querySelector('[data-queue-count]');
        if (count) count.textContent = queue.length + ' sarki';
        if (!list) return;

        if (!queue.length) {
            list.innerHTML = '<div class="music-queue-empty">Kuyruk bos.</div>';
            return;
        }

        list.innerHTML = queue.map(function (track, index) {
            return '<button class="music-queue-item' + (track.locked ? ' is-locked' : '') + '" type="button" data-queue-index="' + index + '">' +
                '<img src="' + escapeHtml(track.cover || '/uploads/music-covers/track-1.svg') + '" alt="">' +
                '<span><strong>' + escapeHtml(track.title || 'Track') + '</strong><small>' + escapeHtml(track.artist || 'Zalorox Music') + '</small></span>' +
                '<em>' + (track.locked ? 'Premium' : 'Play') + '</em>' +
                '</button>';
        }).join('');
    }

    function setVolume(value) {
        var next = Math.max(0, Math.min(1, Number(value)));
        audio.volume = Number.isFinite(next) ? next : 0.82;
        if (audio.volume > 0) audio.muted = false;
        syncVolumeControls();
        saveState();
    }

    function toggleMute() {
        audio.muted = !audio.muted;
        syncVolumeControls();
        saveState();
    }

    function restorePlayer() {
        var stored = loadState();
        var storedTrack = normalizeTrack(stored.track || {});
        if (!storedTrack.trackId || !storedTrack.audioSrc) return;

        active = storedTrack;
        queue = Array.isArray(stored.queue) ? stored.queue.map(function (item) { return normalizeTrack(item); }).filter(function (item) { return item.trackId; }) : [];
        history = Array.isArray(stored.history) ? stored.history.map(function (item) { return normalizeTrack(item); }).filter(function (item) { return item.trackId; }) : [];
        audio.volume = Number.isFinite(Number(stored.volume)) ? Math.max(0, Math.min(1, Number(stored.volume))) : 0.82;
        audio.muted = stored.muted === true;
        setAudioTrack(active, Number(stored.current_time || 0));
        syncTrackMeta();
        syncVolumeControls();

        if (stored.playing === true) {
            playActive(true);
        } else {
            updateAllPlayButtons();
        }
    }

    document.addEventListener('click', function (event) {
        var cardButton = event.target.closest('[data-track-play]');
        if (cardButton) {
            event.preventDefault();
            toggleTrack(trackFromButton(cardButton));
            return;
        }

        var playerButton = event.target.closest('[data-player-toggle]');
        if (playerButton) {
            event.preventDefault();
            var panel = playerButton.closest('[data-music-player]');
            if (!panel) return;
            toggleTrack(trackFromPanel(panel));
            return;
        }

        if (event.target.closest('[data-mini-toggle]')) {
            event.preventDefault();
            if (!active) return;
            if (audio.paused) {
                startTrack(active, { seekTo: audio.currentTime, skipQueueRefresh: true });
            } else {
                pauseTrack();
            }
            return;
        }

        if (event.target.closest('[data-mini-stop]')) {
            event.preventDefault();
            stopTrack();
            return;
        }

        if (event.target.closest('[data-player-next], [data-mini-next]')) {
            event.preventDefault();
            playNext();
            return;
        }

        if (event.target.closest('[data-player-prev], [data-mini-prev]')) {
            event.preventDefault();
            playPrevious();
            return;
        }

        if (event.target.closest('[data-player-mute], [data-mini-mute]')) {
            event.preventDefault();
            toggleMute();
            return;
        }

        if (event.target.closest('[data-player-queue-toggle]')) {
            event.preventDefault();
            toggleQueuePanel();
            return;
        }

        if (event.target.closest('[data-player-queue-close]')) {
            event.preventDefault();
            toggleQueuePanel(false);
            return;
        }

        var queueItem = event.target.closest('[data-queue-index]');
        if (queueItem) {
            event.preventDefault();
            var index = Number(queueItem.dataset.queueIndex || -1);
            var item = queue[index];
            if (!item) return;
            queue.splice(index, 1);
            startTrack(item, { fromQueue: true });
            renderQueue();
            return;
        }

        if (event.target.closest('[data-mini-like]')) {
            event.preventDefault();
            if (active) likeTrack(active.trackId, event.target.closest('[data-mini-like]'));
            return;
        }

        if (event.target.closest('[data-mini-share]')) {
            event.preventDefault();
            if (active) shareTrack(active.trackId);
        }
    });

    document.addEventListener('input', function (event) {
        var progress = event.target.closest('[data-player-progress]');
        if (progress) {
            if (!audio.duration) return;
            audio.currentTime = (Number(progress.value || 0) / 1000) * audio.duration;
            syncProgress();
            saveState();
            return;
        }

        var volume = event.target.closest('[data-player-volume], [data-mini-volume]');
        if (volume) {
            setVolume(volume.value);
        }
    });

    audio.addEventListener('loadedmetadata', function () {
        if (pendingSeek !== null) {
            try {
                audio.currentTime = Math.min(Math.max(0, pendingSeek), Number.isFinite(audio.duration) ? audio.duration : pendingSeek);
            } catch (error) {
                /* Some browsers only allow seeking after more data is buffered. */
            }
            pendingSeek = null;
        }
        syncProgress();
    });

    audio.addEventListener('timeupdate', function () {
        syncProgress();
        saveState();
    });

    audio.addEventListener('play', function () {
        updateAllPlayButtons();
        syncMiniVisibility();
        saveState();
    });

    audio.addEventListener('pause', function () {
        updateAllPlayButtons();
        syncMiniVisibility();
        saveState();
    });

    audio.addEventListener('ended', function () {
        playNext();
    });

    document.addEventListener('visibilitychange', function () {
        saveState();
    });

    window.addEventListener('beforeunload', function () {
        saveState();
    });

    function likeTrack(trackId, sourceButton) {
        if (!trackId) return;
        var buttons = Array.prototype.slice.call(document.querySelectorAll('[data-music-like][data-track-id="' + trackId + '"]'));
        if (sourceButton) buttons.push(sourceButton);
        buttons.forEach(function (button) { button.disabled = true; });

        post('/api/music/like', { track_id: trackId }).then(function (json) {
            if (!json.ok) {
                if (json.httpStatus === 403 && window.ZaloroxModal) {
                    window.ZaloroxModal.confirm(json.message || 'Giris yapmalisin.', {
                        title: 'Giris gerekli',
                        confirmLabel: 'Giris Yap',
                        cancelLabel: 'Vazgec'
                    }).then(function (ok) {
                        if (ok) window.location.href = '/giris-yap';
                    });
                    return;
                }

                toast(json.message || 'Begeni kaydedilemedi.', 'warning');
                return;
            }

            buttons.forEach(function (button) {
                button.classList.toggle('is-active', json.liked === true);
            });
            updateCounts(trackId, undefined, json.like_count);
            toast(json.liked ? 'Sarki begenildi.' : 'Begeni kaldirildi.', 'success');
        }).catch(function () {
            toast('Begeni kaydedilemedi.', 'error');
        }).finally(function () {
            buttons.forEach(function (button) { button.disabled = false; });
        });
    }

    document.addEventListener('click', function (event) {
        var like = event.target.closest('[data-music-like]');
        if (!like) return;

        event.preventDefault();
        likeTrack(like.dataset.trackId || '', like);
    });

    function shareTrack(trackId) {
        if (!trackId) return;
        post('/api/music/share-track', { track_id: trackId }).then(function (json) {
            if (!json.ok) {
                toast(json.message || 'Paylasim hazirlanamadi.', 'warning');
                return;
            }

            var payload = { title: json.title || document.title, url: json.url || (active ? active.detailUrl : window.location.href) };
            if (navigator.share) {
                navigator.share(payload).then(function () {
                    toast('Paylasim penceresi acildi.', 'success');
                }).catch(function () {
                    toast('Paylasim iptal edildi.', 'info');
                });
                return;
            }

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(payload.url).then(function () {
                    toast('Baglanti kopyalandi.', 'success');
                }).catch(function () {
                    toast(payload.url, 'info');
                });
                return;
            }

            toast(payload.url, 'info');
        }).catch(function () {
            toast('Paylasim hazirlanamadi.', 'error');
        });
    }

    document.addEventListener('click', function (event) {
        var share = event.target.closest('[data-music-share]');
        if (!share) return;

        event.preventDefault();
        shareTrack(share.dataset.trackId || '');
    });

    function renderSearchResult(track) {
        var cover = track.cover_image || track.cover || '/uploads/music-covers/track-1.svg';
        var slug = track.slug || '';
        return '<a class="music-search-result" href="/music/sarki/' + encodeURIComponent(slug) + '">' +
            '<img src="' + escapeHtml(cover) + '" alt="">' +
            '<span><strong>' + escapeHtml(track.title || 'Track') + '</strong><br>' + escapeHtml(track.artist_name || track.artist || 'Zalorox Music') + '</span>' +
            '<small>' + escapeHtml(track.genre || 'Music') + '</small>' +
            '</a>';
    }

    document.querySelectorAll('[data-music-search-form]').forEach(function (form) {
        var input = form.querySelector('[data-music-live-search]');
        var results = form.querySelector('[data-music-search-results]');
        var timer = null;
        var focused = false;
        if (!input || !results) return;

        function hideResults() {
            results.hidden = true;
            results.innerHTML = '';
        }

        function runSearch() {
            var q = input.value.trim();

            if (!focused || q.length < 2) {
                hideResults();
                return;
            }

            post('/api/music/search', { q: q, sort: 'popular' }).then(function (json) {
                var tracks = Array.isArray(json.tracks) ? json.tracks.slice(0, 6) : [];
                if (!focused || input.value.trim().length < 2) {
                    hideResults();
                    return;
                }
                if (!tracks.length) {
                    results.innerHTML = '<div class="music-search-result music-search-empty"><span><strong>Sonuc yok</strong><br>Farkli bir kelime dene.</span></div>';
                    results.hidden = false;
                    return;
                }

                results.innerHTML = tracks.map(renderSearchResult).join('');
                results.hidden = false;
            }).catch(hideResults);
        }

        input.addEventListener('focus', function () {
            focused = true;
            if (input.value.trim().length >= 2 && results.innerHTML !== '') {
                results.hidden = false;
            } else if (input.value.trim().length >= 2) {
                runSearch();
            }
        });

        input.addEventListener('input', function () {
            window.clearTimeout(timer);
            if (input.value.trim().length < 2) {
                hideResults();
                return;
            }
            timer = window.setTimeout(runSearch, 260);
        });

        input.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') {
                hideResults();
                input.blur();
            }
        });

        form.addEventListener('submit', function () {
            hideResults();
        });
    });

    document.addEventListener('click', function (event) {
        document.querySelectorAll('[data-music-search-results]').forEach(function (results) {
            if (results.closest('form') && results.closest('form').contains(event.target)) return;
            results.hidden = true;
        });

        var panel = queuePanel();
        if (panel && !panel.hidden && !panel.contains(event.target) && !event.target.closest('[data-player-queue-toggle]')) {
            toggleQueuePanel(false);
        }
    });

    restorePlayer();
})();
