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

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

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

    function humanSize(bytes) {
        bytes = Number(bytes || 0);
        if (bytes >= 1024 * 1024) return (Math.round(bytes / 1024 / 102.4) / 10) + ' MB';
        if (bytes >= 1024) return Math.round(bytes / 1024) + ' KB';
        return bytes + ' B';
    }

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

    function normalizeTagKey(value) {
        return String(value || '').toLocaleLowerCase('tr-TR')
            .replace(/[ç]/g, 'c')
            .replace(/[ğ]/g, 'g')
            .replace(/[ıi̇]/g, 'i')
            .replace(/[ö]/g, 'o')
            .replace(/[ş]/g, 's')
            .replace(/[ü]/g, 'u')
            .replace(/[^a-z0-9]+/g, ' ')
            .trim();
    }

    function splitTags(value) {
        return String(value || '').split(/[,#\n]+/).map(function (tag) {
            return tag.trim().replace(/\s+/g, ' ');
        }).filter(Boolean);
    }

    function addTags(input, tags) {
        if (!input) return;
        var current = splitTags(input.value);
        var seen = {};
        current.forEach(function (tag) { seen[normalizeTagKey(tag)] = true; });
        (tags || []).forEach(function (tag) {
            tag = String(tag || '').trim().replace(/\s+/g, ' ');
            var key = normalizeTagKey(tag);
            if (!key || seen[key]) return;
            seen[key] = true;
            current.push(tag);
        });
        input.value = current.join(', ');
        input.dispatchEvent(new Event('input', { bubbles: true }));
    }

    function videoThumb(url) {
        try {
            var parsed = new URL(url);
            var host = parsed.hostname.toLowerCase();
            var id = '';
            if (host.indexOf('youtu.be') !== -1) {
                id = parsed.pathname.replace(/^\//, '').split('/')[0] || '';
            } else if (host.indexOf('youtube.com') !== -1) {
                id = parsed.searchParams.get('v') || '';
            }
            return id ? 'https://img.youtube.com/vi/' + encodeURIComponent(id) + '/hqdefault.jpg' : '';
        } catch (error) {
            return '';
        }
    }

    function isSupportedVideoUrl(url) {
        try {
            var host = new URL(url).hostname.toLowerCase();
            return host.indexOf('youtube.com') !== -1 || host.indexOf('youtu.be') !== -1 || host.indexOf('vimeo.com') !== -1;
        } catch (error) {
            return false;
        }
    }

    function setLiveCover(form, src) {
        var img = form.querySelector('[data-live-cover]');
        var empty = form.querySelector('[data-live-cover-empty]');
        if (!img) return;
        img.src = src;
        img.hidden = false;
        if (empty) empty.hidden = true;
    }

    function updateImagePreview(input, files) {
        var zone = input.closest('[data-dropzone]');
        var form = input.closest('form');
        var panel = input.closest('.upload-panel');
        var kind = zone ? zone.dataset.dropzoneKind : 'image';
        files = Array.prototype.slice.call(files || input.files || []);
        if (!files.length) return;

        if (kind === 'model') {
            var modelList = panel ? panel.querySelector('[data-model-list]') : null;
            if (!modelList) return;
            files.forEach(function (file) {
                var extension = (file.name.split('.').pop() || '').toLowerCase();
                if (['glb', 'gltf', 'usdz'].indexOf(extension) === -1) {
                    toast('Sadece GLB, GLTF veya USDZ model eklenebilir.', 'warning');
                    return;
                }
                var item = document.createElement('div');
                item.className = 'model-preview-item';
                item._zaloroxFile = file;
                item.innerHTML = '<span>3D</span>' +
                    '<label>Baslik<input name="new_model_titles[]" value="' + escapeHtml(file.name.replace(/\.[^.]+$/, '')) + '"></label>' +
                    '<small>' + escapeHtml(file.name) + ' | ' + humanSize(file.size) + '</small>' +
                    '<button type="button" data-remove-model>Sil</button>';
                modelList.appendChild(item);
            });
            syncModelInput(modelList);
            return;
        }

        if (kind === 'gallery') {
            var grid = panel ? panel.querySelector('[data-image-grid]') : null;
            if (!grid) return;
            files.forEach(function (file) {
                if (!file.type || file.type.indexOf('image/') !== 0) return;
                var reader = new FileReader();
                reader.onload = function () {
                    var item = document.createElement('div');
                    item.className = 'image-preview-item';
                    item.draggable = true;
                    item._zaloroxFile = file;
                    item.dataset.newImage = '1';
                    item.innerHTML = '<img src="' + reader.result + '" alt="">' +
                        '<span>' + (grid.querySelectorAll('.image-preview-item').length + 1) + '</span>' +
                        '<button type="button" data-remove-preview>Sil</button>';
                    grid.appendChild(item);
                    renumberGrid(grid);
                };
                reader.readAsDataURL(file);
            });
            return;
        }

        var file = files[0];
        if (!file.type || file.type.indexOf('image/') !== 0) return;
        var preview = zone ? zone.querySelector('[data-dropzone-preview]') : null;
        var removeMarker = form ? form.querySelector('input[name="remove_cover"]') : null;
        if (removeMarker) removeMarker.remove();
        var reader = new FileReader();
        reader.onload = function () {
            if (preview) {
                preview.innerHTML = '<img src="' + reader.result + '" alt=""><button type="button" data-clear-dropzone>Sil</button>';
                preview.hidden = false;
                preview.classList.add('is-filled');
            }
            if (form) setLiveCover(form, reader.result);
        };
        reader.readAsDataURL(file);
    }

    function updateAudioPreview(input) {
        var form = input.closest('form');
        var file = input.files && input.files[0];
        var preview = form ? form.querySelector('[data-audio-preview]') : null;
        if (!file || !preview) return;

        var player = preview.querySelector('[data-audio-player]');
        var name = preview.querySelector('[data-audio-name]');
        var details = preview.querySelector('[data-audio-details]');
        var removeMarker = form ? form.querySelector('input[name="remove_audio"]') : null;
        var src = URL.createObjectURL(file);

        if (removeMarker) removeMarker.remove();
        preview.classList.add('is-ready');
        if (name) name.textContent = file.name;
        if (details) details.textContent = humanSize(file.size) + ' | ' + (file.name.split('.').pop() || '').toUpperCase();
        if (player) {
            player.src = src;
            player.onloadedmetadata = function () {
                if (details) details.textContent = humanSize(file.size) + ' | ' + (file.name.split('.').pop() || '').toUpperCase() + ' | ' + formatTime(player.duration);
            };
        }
    }

    function syncGalleryInput(grid) {
        if (!grid || typeof DataTransfer === 'undefined') return;
        var panel = grid.closest('.upload-panel');
        var input = panel ? panel.querySelector('[data-dropzone-kind="gallery"] [data-upload-input]') : null;
        if (!input) return;

        var transfer = new DataTransfer();
        var newIndex = 0;
        grid.querySelectorAll('.image-preview-item').forEach(function (item) {
            if (!item._zaloroxFile) return;
            item.dataset.fileOrder = String(newIndex++);
            transfer.items.add(item._zaloroxFile);
        });
        input.files = transfer.files;
    }

    function syncModelInput(list) {
        if (!list || typeof DataTransfer === 'undefined') return;
        var panel = list.closest('.upload-panel');
        var input = panel ? panel.querySelector('[data-dropzone-kind="model"] [data-upload-input]') : null;
        if (!input) return;

        var transfer = new DataTransfer();
        list.querySelectorAll('.model-preview-item').forEach(function (item) {
            if (item._zaloroxFile) transfer.items.add(item._zaloroxFile);
        });
        input.files = transfer.files;
    }

    function renumberGrid(grid) {
        syncGalleryInput(grid);
        grid.querySelectorAll('.image-preview-item').forEach(function (item, index) {
            var badge = item.querySelector('span');
            if (badge) badge.textContent = String(index + 1);

            var order = item.querySelector('[data-gallery-order]');
            if (!order) {
                order = document.createElement('input');
                order.type = 'hidden';
                order.name = 'gallery_order[]';
                order.dataset.galleryOrder = 'true';
                item.appendChild(order);
            }

            var existing = item.querySelector('input[name="existing_gallery[]"]');
            order.value = existing ? 'existing:' + existing.value : 'new:' + (item.dataset.fileOrder || '0');
        });
    }

    function updateLiveText(form) {
        var title = form.querySelector('[data-live-title]');
        var artist = form.querySelector('[data-live-artist]');
        var liveTitle = form.querySelector('[data-live-preview-title]');
        var liveArtist = form.querySelector('[data-live-preview-artist]');
        if (title && liveTitle) liveTitle.textContent = title.value.trim() || (form.dataset.uploadType === 'music' ? 'Sarki adi' : 'Mod basligi');
        if (artist && liveArtist) liveArtist.textContent = artist.value.trim() || 'Sanatci';
    }

    function clearErrors(form) {
        form.querySelectorAll('.field-error').forEach(function (node) { node.textContent = ''; });
        form.querySelectorAll('[aria-invalid="true"]').forEach(function (node) { node.removeAttribute('aria-invalid'); });
    }

    function showErrors(form, errors) {
        Object.keys(errors || {}).forEach(function (key) {
            var node = form.querySelector('[data-error-for="' + CSS.escape(key) + '"]');
            var field = form.querySelector('[name="' + CSS.escape(key) + '"]');
            if (node) node.textContent = errors[key];
            if (field) field.setAttribute('aria-invalid', 'true');
        });
    }

    document.querySelectorAll('[data-dropzone]').forEach(function (zone) {
        var input = zone.querySelector('[data-upload-input]');
        if (!input) return;

        input.addEventListener('change', function () {
            if (zone.dataset.dropzoneKind === 'audio') {
                updateAudioPreview(input);
            } else {
                updateImagePreview(input);
            }
            input.dispatchEvent(new CustomEvent('zalorox:upload-selected', { bubbles: true }));
        });

        ['dragenter', 'dragover'].forEach(function (eventName) {
            zone.addEventListener(eventName, function (event) {
                event.preventDefault();
                zone.classList.add('is-dragging');
            });
        });

        ['dragleave', 'drop'].forEach(function (eventName) {
            zone.addEventListener(eventName, function () {
                zone.classList.remove('is-dragging');
            });
        });

        zone.addEventListener('drop', function (event) {
            event.preventDefault();
            if (!event.dataTransfer || !event.dataTransfer.files.length) return;
            input.files = event.dataTransfer.files;
            input.dispatchEvent(new Event('change', { bubbles: true }));
        });
    });

    document.addEventListener('click', function (event) {
        var clear = event.target.closest('[data-clear-dropzone]');
        if (clear) {
            var zone = clear.closest('[data-dropzone]');
            var input = zone ? zone.querySelector('[data-upload-input]') : null;
            var preview = zone ? zone.querySelector('[data-dropzone-preview]') : null;
            var form = zone ? zone.closest('form') : null;
            if (input) input.value = '';
            if (input && input.name === 'cover' && form) {
                var marker = form.querySelector('input[name="remove_cover"]') || document.createElement('input');
                marker.type = 'hidden';
                marker.name = 'remove_cover';
                marker.value = '1';
                form.appendChild(marker);
            }
            if (preview) {
                preview.innerHTML = '';
                preview.hidden = true;
            }
            if (form && input && input.name === 'cover') {
                var liveImg = form.querySelector('[data-live-cover]');
                var liveEmpty = form.querySelector('[data-live-cover-empty]');
                if (liveImg) {
                    liveImg.removeAttribute('src');
                    liveImg.hidden = true;
                }
                if (liveEmpty) liveEmpty.hidden = false;
            }
            return;
        }

        var removePreview = event.target.closest('[data-remove-preview]');
        if (removePreview) {
            var item = removePreview.closest('.image-preview-item');
            var grid = item ? item.closest('[data-image-grid]') : null;
            if (item) item.remove();
            if (grid) renumberGrid(grid);
            return;
        }

        var removeVideo = event.target.closest('[data-remove-video]');
        if (removeVideo) {
            var video = removeVideo.closest('.video-preview-item');
            if (video) video.remove();
        }

        var removeModel = event.target.closest('[data-remove-model]');
        if (removeModel) {
            var model = removeModel.closest('.model-preview-item');
            var modelList = model ? model.closest('[data-model-list]') : null;
            if (model) model.remove();
            if (modelList) syncModelInput(modelList);
        }

        var clearAudio = event.target.closest('[data-clear-audio]');
        if (clearAudio) {
            var form = clearAudio.closest('form');
            var preview = clearAudio.closest('[data-audio-preview]');
            var input = form ? form.querySelector('[data-dropzone-kind="audio"] [data-upload-input]') : null;
            var player = preview ? preview.querySelector('[data-audio-player]') : null;
            var name = preview ? preview.querySelector('[data-audio-name]') : null;
            var details = preview ? preview.querySelector('[data-audio-details]') : null;

            if (input) input.value = '';
            if (player) {
                player.pause();
                player.removeAttribute('src');
                player.load();
            }
            if (name) name.textContent = 'Audio dosyasi secilmedi';
            if (details) details.textContent = 'MP3, WAV, OGG, M4A';
            if (preview) preview.classList.remove('is-ready');
            if (form) {
                var marker = form.querySelector('input[name="remove_audio"]') || document.createElement('input');
                marker.type = 'hidden';
                marker.name = 'remove_audio';
                marker.value = '1';
                form.appendChild(marker);
            }
        }
    });

    var dragged = null;
    document.addEventListener('dragstart', function (event) {
        var item = event.target.closest('.image-preview-item');
        if (!item) return;
        dragged = item;
        event.dataTransfer.effectAllowed = 'move';
    });

    document.addEventListener('dragover', function (event) {
        var item = event.target.closest('.image-preview-item');
        if (!item || !dragged || item === dragged) return;
        event.preventDefault();
        item.classList.add('is-drag-over');
    });

    document.addEventListener('dragleave', function (event) {
        var item = event.target.closest('.image-preview-item');
        if (item) item.classList.remove('is-drag-over');
    });

    document.addEventListener('drop', function (event) {
        var item = event.target.closest('.image-preview-item');
        if (!item || !dragged || item === dragged) return;
        event.preventDefault();
        item.classList.remove('is-drag-over');
        item.parentNode.insertBefore(dragged, item.nextSibling);
        renumberGrid(item.parentNode);
        dragged = null;
    });

    document.querySelectorAll('[data-category-selector]').forEach(function (selector) {
        var value = selector.querySelector('[data-category-value]');
        selector.addEventListener('click', function (event) {
            var tab = event.target.closest('[data-category-tab]');
            if (tab) {
                selector.querySelectorAll('[data-category-tab]').forEach(function (item) { item.classList.toggle('is-active', item === tab); });
                selector.querySelectorAll('[data-category-panel]').forEach(function (panel) { panel.classList.toggle('is-active', panel.dataset.categoryPanel === tab.dataset.categoryTab); });
                return;
            }

            var option = event.target.closest('[data-category-option]');
            if (!option) return;
            selector.querySelectorAll('[data-category-option]').forEach(function (item) { item.classList.toggle('is-selected', item === option); });
            if (value) value.value = option.dataset.categoryOption || '';
            var form = selector.closest('form');
            var liveCategory = form ? form.querySelector('[data-live-preview-category]') : null;
            if (liveCategory) liveCategory.textContent = option.dataset.categoryLabel || 'Kategori';
        });
    });

    document.querySelectorAll('[data-privacy-selector]').forEach(function (selector) {
        selector.addEventListener('change', function (event) {
            if (!event.target.matches('input')) return;
            selector.querySelectorAll('.privacy-card, .package-select-card').forEach(function (card) {
                var input = card.querySelector('input');
                card.classList.toggle('is-selected', input && input.checked);
            });
            var selectedPrivacy = selector.querySelector('input[name="privacy"]:checked');
            var packages = selector.querySelector('[data-package-options]');
            if (packages) packages.classList.toggle('is-open', selectedPrivacy && selectedPrivacy.value === 'package');
            var form = selector.closest('form');
            var badge = form ? form.querySelector('[data-live-privacy]') : null;
            if (badge && selectedPrivacy) badge.textContent = selectedPrivacy.value === 'public' ? 'Free' : 'Premium';
        });
    });

    document.querySelectorAll('[data-video-builder]').forEach(function (builder) {
        var input = builder.querySelector('[data-video-url]');
        var list = builder.querySelector('[data-video-list]');
        var error = builder.querySelector('[data-error-for="videos"]');
        var add = builder.querySelector('[data-add-video]');
        if (!input || !list || !add) return;

        add.addEventListener('click', function () {
            var value = input.value.trim();
            if (!/^https?:\/\//i.test(value) || !isSupportedVideoUrl(value)) {
                if (error) error.textContent = 'Gecerli bir video linki yaz.';
                toast('YouTube veya Vimeo linki ekleyebilirsin.', 'warning');
                return;
            }
            if (error) error.textContent = '';
            var host = '';
            try { host = new URL(value).hostname; } catch (e) { host = 'Video'; }
            var thumb = videoThumb(value);
            var item = document.createElement('div');
            item.className = 'video-preview-item';
            item.innerHTML = '<span data-video-thumb' + (thumb ? ' style="background-image:url(' + escapeHtml(thumb) + ')"' : '') + '></span><strong>' + escapeHtml(host) + '</strong><small>' + escapeHtml(value) + '</small>' +
                '<input type="hidden" name="videos[]" value="' + escapeHtml(value) + '">' +
                '<button type="button" data-remove-video>Sil</button>';
            list.appendChild(item);
            input.value = '';
        });
    });

    document.querySelectorAll('[data-add-model-link]').forEach(function (button) {
        button.addEventListener('click', function () {
            var panel = button.closest('.upload-panel');
            var input = panel ? panel.querySelector('[data-model-link-input]') : null;
            var list = panel ? panel.querySelector('[data-model-list]') : null;
            if (!input || !list) return;

            var value = input.value.trim();
            var ok = false;
            try {
                var parsed = new URL(value);
                var extension = parsed.pathname.split('.').pop().toLowerCase();
                ok = /^https?:$/i.test(parsed.protocol) && ['glb', 'gltf', 'usdz'].indexOf(extension) !== -1;
            } catch (error) {
                ok = false;
            }

            if (!ok) {
                toast('GLB, GLTF veya USDZ uzantili gecerli bir model linki yaz.', 'warning');
                return;
            }

            var title = panel.querySelector('[data-model-title]');
            var item = document.createElement('div');
            item.className = 'model-preview-item';
            item.innerHTML = '<span>3D</span>' +
                '<label>Baslik<input name="existing_model_titles[]" value="' + escapeHtml(title && title.value ? title.value : 'Harici 3D Model') + '"></label>' +
                '<small>' + escapeHtml(value) + '</small>' +
                '<input type="hidden" name="model_links[]" value="' + escapeHtml(value) + '">' +
                '<button type="button" data-remove-model>Sil</button>';
            list.appendChild(item);
            input.value = '';
        });
    });

    document.querySelectorAll('[data-ai-tag-suggester]').forEach(function (box) {
        var form = box.closest('form');
        var tagInput = form ? form.querySelector('[data-tag-input], input[name="tags"]') : null;
        var generate = box.querySelector('[data-ai-generate]');
        var addAll = box.querySelector('[data-ai-add-all]');
        var clear = box.querySelector('[data-ai-clear]');
        var chips = box.querySelector('[data-ai-tags]');
        var errorText = box.querySelector('[data-ai-error]');
        var timer = null;
        var latestTags = [];

        if (!form || !generate || !chips) return;

        function setBusy(isBusy) {
            generate.disabled = isBusy;
            generate.classList.toggle('is-loading', isBusy);
            generate.textContent = isBusy ? 'Uretiliyor...' : 'Zalorox AI ile Etiket Uret';
        }

        function setError(message) {
            if (!errorText) return;
            errorText.textContent = message || '';
            errorText.hidden = !message;
        }

        function render(tags) {
            latestTags = Array.isArray(tags) ? tags : [];
            chips.innerHTML = '';

            if (!latestTags.length) {
                chips.innerHTML = '<span class="muted">Öneri bulunamadı. Başlık, açıklama veya kategori ekle.</span>';
                if (addAll) addAll.disabled = true;
                if (clear) clear.disabled = true;
                return;
            }

            latestTags.forEach(function (tag) {
                var button = document.createElement('button');
                button.type = 'button';
                button.className = 'ai-tag-chip';
                button.textContent = tag;
                button.dataset.aiTag = tag;
                chips.appendChild(button);
            });

            if (addAll) addAll.disabled = false;
            if (clear) clear.disabled = false;
        }

        function categoryValue() {
            var field = form.querySelector('input[name="category_id"], input[name="genre_id"]');
            return field ? field.value : '';
        }

        function currentFileName() {
            var file = form.querySelector('input[type="file"]');
            return file && file.files && file.files[0] ? file.files[0].name : '';
        }

        function suggestionPayload() {
            var title = form.querySelector('[name="title"]');
            var description = form.querySelector('[name="description"]');
            var game = form.querySelector('[name="game"], [name="game_series"], [name="series"]');
            var video = form.querySelector('[name="video_title"], [name="video_url"], [data-video-title]');

            return new URLSearchParams({
                title: title ? title.value : '',
                description: description ? description.value : '',
                category_id: categoryValue(),
                game: game ? game.value : '',
                file_name: currentFileName(),
                video_title: video ? (video.dataset.videoTitle || video.value || '') : '',
                tags: tagInput ? tagInput.value : '',
                type: box.dataset.aiType || form.dataset.uploadType || 'mod',
                _csrf: csrf()
            });
        }

        function renderContentSuggestions(json) {
            var panel = box.querySelector('[data-ai-content-suggestions]');
            if (!panel) {
                panel = document.createElement('div');
                panel.className = 'ai-content-suggestions';
                panel.dataset.aiContentSuggestions = 'true';
                chips.insertAdjacentElement('afterend', panel);
            }

            var warnings = Array.isArray(json.warnings) ? json.warnings : [];
            panel.innerHTML =
                '<div><strong>Kisa ozet</strong><span>' + escapeHtml(json.summary || 'Ozet onerisi yok.') + '</span></div>' +
                '<div><strong>SEO</strong><span>' + escapeHtml(json.seo_description || 'SEO onerisi yok.') + '</span></div>' +
                '<div><strong>Kategori</strong><span>' + escapeHtml(json.category_suggestion || 'Kategori onerisi yok.') + '</span></div>' +
                (warnings.length ? '<ul>' + warnings.map(function (warning) { return '<li>' + escapeHtml(warning) + '</li>'; }).join('') + '</ul>' : '');
        }

        function requestContentSuggestions(body, quiet) {
            return fetch('/api/studio/ai/content-suggestions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRF-TOKEN': csrf(),
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: new URLSearchParams(body)
            }).then(function (response) {
                return response.json();
            }).then(function (json) {
                if (!json.ok && !json.success) throw new Error(json.message || 'Icerik onerisi uretilemedi.');
                renderContentSuggestions(json);
            }).catch(function (error) {
                if (!quiet) toast(error.message || 'Icerik onerisi uretilemedi.', 'warning');
            });
        }

        function requestSuggestions(quiet) {
            var body = suggestionPayload();
            setError('');

            if (!String(body.get('title') || '').trim() && !String(body.get('description') || '').trim()) {
                if (!quiet) toast('Etiket üretmek için başlık veya açıklama yaz.', 'warning');
                setError('Baslik veya aciklama ekleyince oneriler hazirlanabilir.');
                return Promise.resolve();
            }

            setBusy(true);
            return fetch(box.dataset.aiEndpoint || '/api/studio/ai/tags', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRF-TOKEN': csrf(),
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: body
            }).then(function (response) {
                return response.json().then(function (json) {
                    json.httpStatus = response.status;
                    return json;
                });
            }).then(function (json) {
                if (!json.ok && !json.success) throw new Error(json.message || 'Etiket önerisi üretilemedi.');
                render(json.tags || []);
                setError('');
                requestContentSuggestions(body, quiet);
                if (!quiet) toast('Zalorox AI önerileri hazır.', 'success');
            }).catch(function (error) {
                setError(error.message || 'Etiket onerisi uretilemedi.');
                if (!quiet) toast(error.message || 'Etiket önerisi üretilemedi.', 'error');
            }).finally(function () {
                setBusy(false);
            });
        }

        generate.addEventListener('click', function () {
            requestSuggestions(false);
        });

        chips.addEventListener('click', function (event) {
            var chip = event.target.closest('[data-ai-tag]');
            if (!chip) return;
            addTags(tagInput, [chip.dataset.aiTag || chip.textContent]);
            chip.classList.add('is-added');
        });

        if (addAll) {
            addAll.addEventListener('click', function () {
                addTags(tagInput, latestTags);
                box.querySelectorAll('.ai-tag-chip').forEach(function (chip) { chip.classList.add('is-added'); });
                toast('AI etiketleri eklendi.', 'success');
            });
        }

        if (clear) {
            clear.addEventListener('click', function () {
                latestTags = [];
                chips.innerHTML = '<span class="muted">Öneriler temizlendi.</span>';
                addAll.disabled = true;
                clear.disabled = true;
                setError('');
            });
        }

        form.addEventListener('input', function (event) {
            if (!event.target.matches('[name="title"]')) return;
            window.clearTimeout(timer);
            if (event.target.value.trim().length < 6) return;
            timer = window.setTimeout(function () { requestSuggestions(true); }, 750);
        });
    });

    document.addEventListener('click', function (event) {
        var scan = event.target.closest('[data-link-scan]');
        if (!scan) return;
        var form = scan.closest('form');
        var input = form ? form.querySelector('[data-link-input]') : null;
        var statusBox = form ? form.querySelector('[data-shield-status]') : null;
        var hidden = form ? form.querySelector('[data-link-status-input]') : null;
        var url = input ? input.value.trim() : '';
        if (!url) {
            toast('Once indirme linki yaz.', 'warning');
            return;
        }

        scan.disabled = true;
        if (statusBox) {
            statusBox.classList.remove('is-safe', 'is-review', 'is-blocked');
            statusBox.querySelector('span').textContent = 'Taranıyor...';
        }

        var runner = window.ZaloroxSecurity && window.ZaloroxSecurity.scanLink
            ? window.ZaloroxSecurity.scanLink(url)
            : fetch('/api/security/scan-link', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': csrf() },
                body: new URLSearchParams({ url: url, _csrf: csrf() })
            }).then(function (response) { return response.json(); });

        runner.then(function (json) {
            if (!json.ok) throw new Error(json.message || 'Tarama tamamlanamadi.');
            var status = json.status || 'safe';
            if (hidden) hidden.value = status;
            if (statusBox) {
                statusBox.classList.toggle('is-safe', status === 'safe');
                statusBox.classList.toggle('is-review', status === 'review');
                statusBox.classList.toggle('is-blocked', status === 'blocked');
                statusBox.querySelector('span').textContent = status === 'safe' ? 'Guvenli' : (status === 'review' ? 'Inceleme gerekli' : 'Engellendi');
            }
            toast(status === 'safe' ? 'Link guvenli gorunuyor.' : 'Link inceleme durumuna alindi.', status === 'blocked' ? 'error' : (status === 'review' ? 'warning' : 'success'));
        }).catch(function (error) {
            toast(error.message || 'Link taranamadi.', 'error');
        }).finally(function () {
            scan.disabled = false;
        });
    });

    document.addEventListener('input', function (event) {
        var form = event.target.closest('[data-studio-upload-form]');
        if (!form) return;
        if (event.target.matches('[data-live-title], [data-live-artist]')) updateLiveText(form);
    });

    document.addEventListener('click', function (event) {
        var submit = event.target.closest('[data-submit-intent]');
        if (!submit) return;
        var form = submit.closest('form');
        var action = form ? form.querySelector('[data-submit-action]') : null;
        if (action) action.value = submit.dataset.submitIntent || 'publish';
    });

    document.addEventListener('submit', function (event) {
        var form = event.target.closest('[data-studio-upload-form]');
        if (!form) return;
        event.preventDefault();
        clearErrors(form);

        var progress = form.querySelector('[data-upload-progress]');
        var bar = form.querySelector('[data-progress-bar]');
        var label = form.querySelector('[data-progress-label]');
        var xhr = new XMLHttpRequest();
        var data = new FormData(form);
        if (!data.get('_csrf')) data.append('_csrf', csrf());

        xhr.open('POST', form.action, true);
        xhr.setRequestHeader('X-CSRF-TOKEN', csrf());
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

        xhr.upload.addEventListener('progress', function (event) {
            if (!event.lengthComputable) return;
            var percent = Math.round((event.loaded / event.total) * 100);
            if (progress) progress.hidden = false;
            if (bar) bar.style.width = percent + '%';
            if (label) label.textContent = percent + '%';
        });

        xhr.onload = function () {
            var json = {};
            try { json = JSON.parse(xhr.responseText || '{}'); } catch (error) {}
            if (progress) progress.hidden = true;
            if (!json.ok) {
                showErrors(form, json.errors || {});
                toast(json.message || 'Kayit tamamlanamadi.', xhr.status >= 500 ? 'error' : 'warning');
                return;
            }

            toast(json.message || 'Kaydedildi.', 'success');
            if (json.redirect_url) {
                window.setTimeout(function () { window.location.href = json.redirect_url; }, 650);
            }
        };

        xhr.onerror = function () {
            if (progress) progress.hidden = true;
            toast('Baglanti hatasi nedeniyle kaydedilemedi.', 'error');
        };

        xhr.send(data);
    });

    document.addEventListener('click', function (event) {
        var button = event.target.closest('[data-delete-content]');
        if (!button) return;
        var endpoint = button.dataset.deleteEndpoint;
        if (!endpoint) return;

        var run = function () {
            var body = new URLSearchParams({ _csrf: csrf() });
            if (button.dataset.contentId) {
                body.append('id', button.dataset.contentId);
                body.append('content_id', button.dataset.contentId);
            }

            button.disabled = true;
            fetch(endpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': csrf(), 'X-Requested-With': 'XMLHttpRequest' },
                body: body
            }).then(function (response) {
                return response.json();
            }).then(function (json) {
                if (!json.ok) throw new Error(json.message || 'Silinemedi.');
                toast(json.message || 'Silindi.', 'success');
                if (json.redirect_url) window.setTimeout(function () { window.location.href = json.redirect_url; }, 500);
            }).catch(function (error) {
                toast(error.message || 'Silinemedi.', 'error');
            }).finally(function () {
                button.disabled = false;
            });
        };

        if (window.ZaloroxModal) {
            window.ZaloroxModal.confirm('Bu kaydi silmek istiyor musun?', {
                title: 'Silme onayi',
                confirmLabel: 'Sil',
                cancelLabel: 'Vazgec',
                danger: true
            }).then(function (ok) {
                if (ok) run();
            });
        } else {
            toast('Silme onayi icin modal yuklenemedi.', 'warning');
        }
    });
})();
