(function () {
    document.documentElement.dataset.studioReady = 'true';

    var csrf = window.ZALOROX_CSRF_TOKEN || '';

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

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

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

    document.querySelectorAll('[data-studio-sidebar]').forEach(function (sidebar) {
        var toggle = sidebar.querySelector('[data-studio-sidebar-toggle]');
        if (!toggle) return;

        function setOpen(open) {
            sidebar.classList.toggle('is-open', open);
            toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
            toggle.setAttribute('aria-label', open ? 'Studio menusunu kapat' : 'Studio menusunu ac');
        }

        toggle.addEventListener('click', function () {
            setOpen(!sidebar.classList.contains('is-open'));
        });

        sidebar.querySelectorAll('.studio-side-menu a').forEach(function (link) {
            link.addEventListener('click', function () {
                setOpen(false);
            });
        });
    });

    function userAvatar(user) {
        var name = user.display_name || user.username || 'U';
        return user.avatar
            ? '<span class="avatar"><img src="' + escapeHtml(user.avatar) + '" alt=""></span>'
            : '<span class="avatar">' + escapeHtml(name.charAt(0).toUpperCase()) + '</span>';
    }

    function actionButton(action, label, userId, friendshipId, primary) {
        return '<button type="button" class="pill' + (primary ? ' primary' : '') + '" data-friend-action="' + action + '" data-user-id="' + escapeHtml(userId) + '" data-friendship-id="' + escapeHtml(friendshipId || '') + '">' + escapeHtml(label) + '</button>';
    }

    function renderFriendRow(user, area) {
        var friendshipId = user.id || user.friendship_id || '';
        var targetUserId = user.user_id || user.id;
        var actions = '';

        if (area === 'friends') {
            actions = actionButton('message', 'Mesaj', targetUserId, friendshipId, true) + actionButton('remove', 'Cikar', targetUserId, friendshipId, false) + actionButton('block', 'Engelle', targetUserId, friendshipId, false);
        } else if (area === 'incoming') {
            actions = actionButton('accept', 'Kabul et', targetUserId, friendshipId, true) + actionButton('reject', 'Reddet', targetUserId, friendshipId, false);
        } else if (area === 'outgoing') {
            actions = '<span class="friend-state">Istek gonderildi</span>' + actionButton('remove', 'Iptal', targetUserId, friendshipId, false);
        } else if (area === 'blocked') {
            actions = actionButton('unblock', 'Engeli kaldir', targetUserId, friendshipId, false);
        } else {
            var relation = user.relationship || 'none';
            if (relation === 'friends') actions = actionButton('message', 'Mesaj', targetUserId, friendshipId, true);
            else if (relation === 'pending_sent') actions = '<span class="friend-state">Istek gonderildi</span>';
            else if (relation === 'pending_received') actions = actionButton('accept', 'Kabul et', targetUserId, friendshipId, true);
            else if (relation === 'blocked_by_me') actions = actionButton('unblock', 'Engeli kaldir', targetUserId, friendshipId, false);
            else if (relation !== 'blocked_me') actions = actionButton('request', 'Arkadas Ekle', targetUserId, friendshipId, true);
        }

        return '<article class="friend-row">' +
            userAvatar(user) +
            '<div><strong>' + escapeHtml(user.display_name || user.nickname || user.username) + '</strong><span>@' + escapeHtml(user.username || '') + '</span></div>' +
            '<div class="friend-actions">' + actions + '</div>' +
        '</article>';
    }

    function loadFriends(panel) {
        fetch('/api/friends/list', { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function (response) { return response.json(); })
            .then(function (json) {
                if (!json.ok) throw new Error(json.message || 'Liste yuklenemedi.');
                ['friends', 'incoming', 'outgoing', 'blocked'].forEach(function (area) {
                    var target = panel.querySelector('[data-friend-list="' + area + '"]');
                    var rows = (json.data && json.data[area]) || [];
                    if (!target) return;
                    target.innerHTML = rows.length
                        ? rows.map(function (item) { return renderFriendRow(item, area); }).join('')
                        : '<div class="empty-state small"><strong>Kayit yok</strong><p>Bu bolum su an bos.</p></div>';
                });
            })
            .catch(function (error) { toast(error.message || 'Arkadas listesi yuklenemedi.', 'error'); });
    }

    document.querySelectorAll('[data-friends-panel]').forEach(function (panel) {
        csrf = panel.dataset.csrf || csrf;
        loadFriends(panel);

        var form = panel.querySelector('[data-friend-search]');
        if (form) {
            form.addEventListener('submit', function (event) {
                event.preventDefault();
                var q = (new FormData(form).get('q') || '').toString().trim();
                var results = panel.querySelector('[data-friend-search-results]');
                if (!results || q.length < 2) return;

                results.innerHTML = '<div class="chat-empty">Araniyor...</div>';
                fetch('/api/friends/search?q=' + encodeURIComponent(q), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                    .then(function (response) { return response.json(); })
                    .then(function (json) {
                        if (!json.ok) throw new Error(json.message || 'Arama tamamlanamadi.');
                        results.innerHTML = json.users.length
                            ? json.users.map(function (item) { return renderFriendRow(item, 'search'); }).join('')
                            : '<div class="empty-state small"><strong>Sonuc yok</strong><p>Baska bir ad veya kullanici adi dene.</p></div>';
                    })
                    .catch(function (error) { toast(error.message || 'Arama tamamlanamadi.', 'error'); });
            });
        }
    });

    function refreshAround(button) {
        var panel = button.closest('[data-friends-panel]');
        if (panel) loadFriends(panel);
    }

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

        var action = button.dataset.friendAction;
        var userId = button.dataset.userId || '';
        var friendshipId = button.dataset.friendshipId || '';

        if (action === 'message') {
            var containerForMessage = button.closest('[data-profile-actions]');
            window.location.href = (containerForMessage && containerForMessage.dataset.messageUrl)
                ? containerForMessage.dataset.messageUrl
                : '/studyo/mesajlar?user_id=' + encodeURIComponent(userId);
            return;
        }

        var endpoint = '/api/friends/' + action;
        var payload = { user_id: userId };
        if (friendshipId) payload.friendship_id = friendshipId;

        var run = function () {
            button.disabled = true;
            post(endpoint, payload).then(function (json) {
                if (!json.ok) throw new Error(json.message || 'Islem tamamlanamadi.');
                toast(json.message || 'Islem tamamlandi.', 'success');
                refreshAround(button);
                if (json.friendship && json.friendship.id) {
                    var profileActions = button.closest('[data-profile-actions]');
                    if (profileActions) profileActions.dataset.friendshipId = json.friendship.id;
                }
                updateProfileState(button.closest('[data-profile-actions]'), json.state || 'none');
            }).catch(function (error) {
                toast(error.message || 'Islem tamamlanamadi.', 'error');
            }).finally(function () {
                button.disabled = false;
            });
        };

        if ((action === 'remove' || action === 'block') && window.ZaloroxModal) {
            window.ZaloroxModal.confirm(action === 'block' ? 'Bu kullaniciyi engellemek istiyor musun?' : 'Arkadasligi kaldirmak istiyor musun?', {
                confirmLabel: action === 'block' ? 'Engelle' : 'Kaldir',
                cancelLabel: 'Vazgec',
                danger: action === 'block'
            }).then(function (ok) { if (ok) run(); });
            return;
        }

        run();
    });

    function updateProfileState(container, state) {
        if (!container) return;
        container.dataset.state = state;
        container.querySelectorAll('[data-profile-action], [data-profile-state]').forEach(function (item) {
            item.hidden = true;
        });
        container.querySelectorAll('[data-profile-follow-action]').forEach(function (item) {
            item.hidden = state === 'blocked_by_me' || state === 'blocked_me';
        });

        var show = function (selector) {
            container.querySelectorAll(selector).forEach(function (item) { item.hidden = false; });
        };
        var canMessage = function (nextState) {
            if (nextState === 'blocked_by_me' || nextState === 'blocked_me') return false;
            if (container.dataset.canMessage === '1') return true;

            var privacy = container.dataset.messagePrivacy || 'everyone';
            if (privacy === 'friends') return nextState === 'friends';
            return privacy === 'everyone';
        };
        var showMessageState = function (nextState) {
            if (canMessage(nextState)) show('[data-profile-action="message"]');
            else show('[data-profile-state="message-disabled"]');
        };

        if (state === 'friends') {
            show('[data-profile-state="friends"], [data-profile-action="remove"], [data-profile-action="block"]');
            showMessageState(state);
        }
        else if (state === 'pending_sent') {
            show('[data-profile-state="pending"], [data-profile-action="block"]');
            showMessageState(state);
        }
        else if (state === 'pending_received') {
            show('[data-profile-action="accept"], [data-profile-action="block"]');
            showMessageState(state);
        }
        else if (state === 'blocked_by_me') show('[data-profile-action="unblock"]');
        else if (state === 'blocked_me') show('[data-profile-state="blocked-me"]');
        else {
            show('[data-profile-action="request"], [data-profile-action="block"]');
            showMessageState(state);
        }
    }

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

        var container = button.closest('[data-profile-actions]');
        if (!container) return;

        button.dataset.friendAction = button.dataset.profileAction;
        button.dataset.userId = container.dataset.userId || '';
        button.dataset.friendshipId = container.dataset.friendshipId || '';
    }, true);

    document.querySelectorAll('[data-studio-subscriptions]').forEach(function (panel) {
        csrf = panel.dataset.csrf || csrf;

        var form = panel.querySelector('[data-package-form]');
        var mode = panel.querySelector('[data-package-form-mode]');
        var submit = panel.querySelector('[data-package-submit]');
        var cancel = panel.querySelector('[data-package-cancel]');

        function field(name) {
            return form ? form.querySelector('[data-package-field="' + name + '"]') : null;
        }

        function setFormMode(label, submitLabel) {
            if (mode) mode.textContent = label;
            if (submit) submit.textContent = submitLabel;
            if (cancel) cancel.hidden = submitLabel === 'Paket Olustur';
        }

        function resetPackageForm() {
            if (!form) return;
            form.reset();
            ['id', 'name', 'description', 'price_monthly', 'price_6_month', 'price_12_month'].forEach(function (name) {
                var input = field(name);
                if (input) input.value = '';
            });
            var status = field('status');
            if (status) status.value = 'active';
            setFormMode('Yeni Paket', 'Paket Olustur');
        }

        function fillPackageForm(card) {
            if (!form || !card) return;
            var values = {
                id: card.dataset.packageId || '',
                name: card.dataset.packageName || '',
                description: card.dataset.packageDescription || '',
                price_monthly: card.dataset.packageMonthly || '',
                price_6_month: card.dataset.packageSix || '',
                price_12_month: card.dataset.packageTwelve || '',
                status: card.dataset.packageStatus || 'active'
            };

            Object.keys(values).forEach(function (name) {
                var input = field(name);
                if (input) input.value = values[name];
            });
            setFormMode('Paket Duzenle', 'Paketi Guncelle');
            form.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        if (form) {
            form.addEventListener('submit', function (event) {
                event.preventDefault();
                var data = Object.fromEntries(new FormData(form).entries());
                var isEdit = Boolean(data.id);
                var endpoint = isEdit ? '/api/studio/package/update' : '/api/studio/package/create';

                if (submit) submit.disabled = true;
                post(endpoint, data).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Paket kaydedilemedi.');
                    toast(json.message || 'Paket kaydedildi.', 'success');
                    window.setTimeout(function () { window.location.reload(); }, 450);
                }).catch(function (error) {
                    toast(error.message || 'Paket kaydedilemedi.', 'error');
                }).finally(function () {
                    if (submit) submit.disabled = false;
                });
            });
        }

        if (cancel) {
            cancel.addEventListener('click', resetPackageForm);
        }

        panel.addEventListener('click', function (event) {
            var edit = event.target.closest('[data-package-edit]');
            if (edit) {
                fillPackageForm(edit.closest('[data-package-id]'));
                return;
            }

            var toggle = event.target.closest('[data-package-toggle]');
            if (toggle) {
                var toggleCard = toggle.closest('[data-package-id]');
                if (!toggleCard) return;
                var nextStatus = toggleCard.dataset.packageStatus === 'active' ? 'inactive' : 'active';
                post('/api/studio/package/toggle', { id: toggleCard.dataset.packageId, status: nextStatus }).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Durum guncellenemedi.');
                    toast(json.message || 'Paket durumu guncellendi.', 'success');
                    window.setTimeout(function () { window.location.reload(); }, 450);
                }).catch(function (error) {
                    toast(error.message || 'Durum guncellenemedi.', 'error');
                });
                return;
            }

            var remove = event.target.closest('[data-package-delete]');
            if (!remove) return;
            var card = remove.closest('[data-package-id]');
            if (!card) return;

            var runDelete = function () {
                post('/api/studio/package/delete', { id: card.dataset.packageId }).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Paket pasife alinamadi.');
                    toast(json.message || 'Paket pasife alindi.', 'success');
                    window.setTimeout(function () { window.location.reload(); }, 450);
                }).catch(function (error) {
                    toast(error.message || 'Paket pasife alinamadi.', 'error');
                });
            };

            if (window.ZaloroxModal) {
                window.ZaloroxModal.confirm('Bu paket pasife alinacak. Devam edilsin mi?', {
                    confirmLabel: 'Pasife Al',
                    cancelLabel: 'Vazgec',
                    danger: true
                }).then(function (ok) { if (ok) runDelete(); });
                return;
            }

            runDelete();
        });
    });
})();

(function () {
    var csrf = window.ZALOROX_CSRF_TOKEN || '';

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

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

    document.querySelectorAll('[data-studio-finance], [data-studio-withdrawals], [data-studio-bank-accounts]').forEach(function (root) {
        csrf = root.dataset.csrf || csrf;

        root.querySelectorAll('[data-finance-form]').forEach(function (form) {
            form.addEventListener('submit', function (event) {
                event.preventDefault();
                var endpoint = form.dataset.endpoint || '';
                if (!endpoint) return;
                var submit = form.querySelector('[type="submit"]');
                if (submit) submit.disabled = true;

                request(endpoint, Object.fromEntries(new FormData(form).entries())).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Islem tamamlanamadi.');
                    toast(json.message || 'Kaydedildi.', 'success');
                    window.setTimeout(function () { window.location.reload(); }, 450);
                }).catch(function (error) {
                    toast(error.message || 'Islem tamamlanamadi.', 'error');
                }).finally(function () {
                    if (submit) submit.disabled = false;
                });
            });
        });

        root.addEventListener('click', function (event) {
            var button = event.target.closest('[data-finance-action]');
            if (!button) return;
            var endpoint = button.dataset.financeAction || '';
            if (!endpoint) return;
            var run = function () {
                button.disabled = true;
                request(endpoint, { id: button.dataset.id || '' }).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Islem tamamlanamadi.');
                    toast(json.message || 'Islem tamamlandi.', 'success');
                    window.setTimeout(function () { window.location.reload(); }, 450);
                }).catch(function (error) {
                    toast(error.message || 'Islem tamamlanamadi.', 'error');
                }).finally(function () {
                    button.disabled = false;
                });
            };

            if (button.dataset.confirm && window.ZaloroxModal) {
                window.ZaloroxModal.confirm(button.dataset.confirm, {
                    confirmLabel: 'Onayla',
                    cancelLabel: 'Vazgec',
                    danger: button.classList.contains('danger')
                }).then(function (ok) { if (ok) run(); });
                return;
            }

            run();
        });
    });
})();

(function () {
    var csrf = window.ZALOROX_CSRF_TOKEN || '';

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

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

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

    function renderAvatar(path, displayName) {
        var initial = String(displayName || 'Z').charAt(0).toUpperCase();
        document.querySelectorAll('[data-profile-avatar-preview]').forEach(function (node) {
            node.innerHTML = path ? '<img src="' + path + '" alt="">' : initial;
        });
        document.querySelectorAll('.user-chip .avatar, .user-dropdown-head .avatar').forEach(function (node) {
            node.innerHTML = path ? '<img src="' + path + '" alt="">' : initial;
        });
    }

    function renderCover(path) {
        document.querySelectorAll('[data-profile-cover-preview], .profile-preview-cover').forEach(function (node) {
            node.innerHTML = path ? '<img src="' + path + '" alt="">' : '<span>Kapak</span>';
        });
    }

    document.querySelectorAll('[data-studio-profile-form]').forEach(function (form) {
        csrf = (form.querySelector('[name="_csrf"]') || {}).value || csrf;
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            clearErrors(form);
            var submit = form.querySelector('[type="submit"]');
            if (submit) submit.disabled = true;

            fetch(form.action, {
                method: 'POST',
                headers: { 'X-CSRF-TOKEN': csrf, 'X-Requested-With': 'XMLHttpRequest' },
                body: new FormData(form)
            }).then(function (response) {
                return response.json().then(function (json) {
                    json.httpStatus = response.status;
                    return json;
                });
            }).then(function (json) {
                if (!json.ok) {
                    showErrors(form, json.errors || {});
                    throw new Error(json.message || 'Profil kaydedilemedi.');
                }

                var profile = json.profile || {};
                document.querySelectorAll('.user-name').forEach(function (node) {
                    node.textContent = profile.display_name || node.textContent;
                });
                toast(json.message || 'Profil kaydedildi.', 'success');
            }).catch(function (error) {
                toast(error.message || 'Profil kaydedilemedi.', 'error');
            }).finally(function () {
                if (submit) submit.disabled = false;
            });
        });
    });

    document.querySelectorAll('[data-profile-image-form]').forEach(function (form) {
        var type = form.dataset.profileImageType || 'avatar';
        var input = form.querySelector('[data-profile-image-input]');
        var remove = form.querySelector('[data-profile-image-remove]');

        csrf = (form.querySelector('[name="_csrf"]') || {}).value || csrf;

        if (input) {
            input.addEventListener('change', function () {
                var file = input.files && input.files[0];
                if (!file || !file.type || file.type.indexOf('image/') !== 0) return;
                var reader = new FileReader();
                reader.onload = function () {
                    if (type === 'cover') renderCover(reader.result);
                    else renderAvatar(reader.result, document.querySelector('[name="display_name"]') ? document.querySelector('[name="display_name"]').value : '');
                };
                reader.readAsDataURL(file);
            });
        }

        form.querySelectorAll('[data-profile-dropzone]').forEach(function (zone) {
            ['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 (!input || !event.dataTransfer || !event.dataTransfer.files.length) return;
                input.files = event.dataTransfer.files;
                input.dispatchEvent(new Event('change', { bubbles: true }));
            });
        });

        if (remove) {
            remove.addEventListener('click', function () {
                var marker = form.querySelector('[name="' + (type === 'cover' ? 'remove_cover' : 'remove_avatar') + '"]') || document.createElement('input');
                marker.type = 'hidden';
                marker.name = type === 'cover' ? 'remove_cover' : 'remove_avatar';
                marker.value = '1';
                form.appendChild(marker);
                if (input) input.value = '';
                form.requestSubmit();
            });
        }

        form.addEventListener('submit', function (event) {
            event.preventDefault();
            clearErrors(form);
            var submit = form.querySelector('[type="submit"]');
            if (submit) submit.disabled = true;

            fetch(form.action, {
                method: 'POST',
                headers: { 'X-CSRF-TOKEN': csrf, 'X-Requested-With': 'XMLHttpRequest' },
                body: new FormData(form)
            }).then(function (response) {
                return response.json().then(function (json) {
                    json.httpStatus = response.status;
                    return json;
                });
            }).then(function (json) {
                if (!json.ok) {
                    showErrors(form, json.errors || {});
                    throw new Error(json.message || 'Gorsel kaydedilemedi.');
                }

                var profile = json.profile || {};
                var path = json.path || '';
                if (type === 'cover') renderCover(path);
                else renderAvatar(path, profile.display_name || '');
                toast(json.message || 'Gorsel guncellendi.', 'success');
                var marker = form.querySelector('[name="remove_cover"], [name="remove_avatar"]');
                if (marker) marker.remove();
            }).catch(function (error) {
                toast(error.message || 'Gorsel kaydedilemedi.', 'error');
            }).finally(function () {
                if (submit) submit.disabled = false;
            });
        });
    });

    document.querySelectorAll('[data-studio-account-form]').forEach(function (form) {
        csrf = (form.querySelector('[name="_csrf"]') || {}).value || csrf;
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            clearErrors(form);

            var run = function () {
                var submit = form.querySelector('[type="submit"]');
                if (submit) submit.disabled = true;

                fetch(form.action, {
                    method: 'POST',
                    headers: { 'X-CSRF-TOKEN': csrf, 'X-Requested-With': 'XMLHttpRequest' },
                    body: new FormData(form)
                }).then(function (response) {
                    return response.json().then(function (json) {
                        json.httpStatus = response.status;
                        return json;
                    });
                }).then(function (json) {
                    if (!json.ok) {
                        showErrors(form, json.errors || {});
                        throw new Error(json.message || 'Islem tamamlanamadi.');
                    }

                    toast(json.message || 'Islem tamamlandi.', 'success');
                    if (json.redirect_url) {
                        window.setTimeout(function () { window.location.href = json.redirect_url; }, 550);
                    } else if (form.action.indexOf('/artist/') !== -1) {
                        window.setTimeout(function () { window.location.reload(); }, 550);
                    } else {
                        form.reset();
                    }
                }).catch(function (error) {
                    toast(error.message || 'Islem tamamlanamadi.', 'error');
                }).finally(function () {
                    if (submit) submit.disabled = false;
                });
            };

            if (form.dataset.dangerConfirm && window.ZaloroxModal) {
                window.ZaloroxModal.confirm(form.dataset.dangerConfirm, {
                    confirmLabel: 'Onayla',
                    cancelLabel: 'Vazgec',
                    danger: true
                }).then(function (ok) { if (ok) run(); });
                return;
            }

            run();
        });
    });
})();
