(function () {
    var csrf = window.ZALOROX_CSRF_TOKEN || '';
    var viewer = null;
    var state = { stories: [], index: 0, touchX: 0, touchY: 0 };

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

    function mediaUrl(path) {
        path = String(path || '').trim();
        if (!path) return '';
        if (/^https?:\/\//i.test(path) || path.charAt(0) === '/') return path;
        return '/' + path.replace(/^\/+/, '');
    }

    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;
            }).catch(function () {
                return { ok: false, message: 'Gecersiz JSON cevabi.', httpStatus: response.status };
            });
        });
    }

    document.addEventListener('click', function (event) {
        var opener = event.target.closest('[data-story-compose-open]');
        if (opener) {
            var strip = opener.closest('[data-story-strip]');
            var composer = strip ? strip.querySelector('[data-story-composer]') : document.querySelector('[data-story-composer]');
            if (composer) composer.hidden = !composer.hidden;
            return;
        }

        var story = event.target.closest('[data-story-open]');
        if (story) {
            event.preventDefault();
            loadStories(story.dataset.userId || '', story.dataset.storyId || '');
        }

        if (event.target.closest('[data-story-close]')) closeViewer();
        if (event.target.closest('[data-story-prev]')) renderStory(state.index - 1);
        if (event.target.closest('[data-story-next]')) renderStory(state.index + 1);

        var remove = event.target.closest('[data-story-delete]');
        if (remove) deleteCurrentStory(remove);
    });

    document.querySelectorAll('[data-story-composer]').forEach(function (form) {
        var file = form.querySelector('[data-story-file]');
        form.querySelectorAll('[data-story-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 (!file || !event.dataTransfer || !event.dataTransfer.files.length) return;
                file.files = event.dataTransfer.files;
            });
        });

        form.addEventListener('submit', function (event) {
            event.preventDefault();
            var submit = form.querySelector('[type="submit"]');
            var error = form.querySelector('[data-story-error]');
            var data = new FormData(form);
            var hasFile = file && file.files && file.files.length > 0;
            var hasText = String(data.get('content') || '').trim() !== '';
            if (!hasFile && !hasText) {
                if (error) error.textContent = 'Metin veya gorsel ekle.';
                toast('Story icin metin veya gorsel ekle.', 'warning');
                return;
            }
            data.set('story_type', hasFile ? 'image' : 'text');
            data.set('_csrf', data.get('_csrf') || csrf);

            if (submit) submit.disabled = true;
            fetch(form.action || '/api/stories/create', {
                method: 'POST',
                headers: { 'X-CSRF-TOKEN': csrf, 'X-Requested-With': 'XMLHttpRequest' },
                body: data
            }).then(function (response) {
                return response.json().then(function (json) {
                    json.httpStatus = response.status;
                    return json;
                });
            }).then(function (json) {
                if (!json.ok) throw new Error(json.message || 'Story yayinlanamadi.');
                toast(json.message || 'Story yayinlandi.', 'success');
                window.setTimeout(function () { window.location.reload(); }, 500);
            }).catch(function (err) {
                if (error) error.textContent = err.message || 'Story yayinlanamadi.';
                toast(err.message || 'Story yayinlanamadi.', 'error');
            }).finally(function () {
                if (submit) submit.disabled = false;
            });
        });
    });

    function ensureViewer() {
        viewer = viewer || document.querySelector('[data-story-viewer]');
        return viewer;
    }

    function loadStories(userId, storyId) {
        var url = '/api/stories/list';
        if (userId) url += '?user_id=' + encodeURIComponent(userId);
        fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function (response) { return response.json(); })
            .then(function (json) {
                if (!json.ok) throw new Error(json.message || 'Story yuklenemedi.');
                state.stories = json.stories || [];
                state.index = Math.max(0, state.stories.findIndex(function (item) { return String(item.id) === String(storyId); }));
                if (!state.stories.length) throw new Error('Aktif story yok.');
                openViewer();
                renderStory(state.index);
            }).catch(function (error) {
                toast(error.message || 'Story yuklenemedi.', 'error');
            });
    }

    function openViewer() {
        var node = ensureViewer();
        if (!node) return;
        node.hidden = false;
        document.body.classList.add('story-viewer-open');
    }

    function closeViewer() {
        var node = ensureViewer();
        if (!node) return;
        node.hidden = true;
        document.body.classList.remove('story-viewer-open');
    }

    function renderStory(index) {
        var node = ensureViewer();
        if (!node || !state.stories.length) return;
        state.index = (index + state.stories.length) % state.stories.length;
        var story = state.stories[state.index];
        var name = story.display_name || story.nickname || story.username || 'User';
        var avatar = mediaUrl(story.avatar || '');
        var media = node.querySelector('[data-story-media]');
        var caption = node.querySelector('[data-story-caption]');
        var link = node.querySelector('[data-story-link]');
        var deleteButton = node.querySelector('[data-story-delete]');

        node.querySelector('[data-story-name]').textContent = name;
        node.querySelector('[data-story-time]').textContent = story.created_at || '';
        node.querySelector('[data-story-avatar]').innerHTML = avatar ? '<img src="' + escapeHtml(avatar) + '" alt="">' : escapeHtml(name.charAt(0).toUpperCase());

        if (story.story_type === 'image' && story.media_path) {
            media.innerHTML = '<img src="' + escapeHtml(mediaUrl(story.media_path)) + '" alt="' + escapeHtml(name) + ' story">';
        } else {
            media.innerHTML = '<div class="story-text-card">' + escapeHtml(story.content || '') + '</div>';
        }
        caption.textContent = story.story_type === 'image' ? (story.content || '') : '';
        if (story.link_url) {
            link.href = story.link_url;
            link.hidden = false;
        } else {
            link.hidden = true;
        }
        deleteButton.hidden = String(story.user_id || '') !== String(window.ZALOROX_USER_ID || '');
        post('/api/stories/view', { story_id: story.id }).catch(function () {});
    }

    function deleteCurrentStory(button) {
        var story = state.stories[state.index];
        if (!story) return;
        var run = function () {
            button.disabled = true;
            post('/api/stories/delete', { story_id: story.id }).then(function (json) {
                if (!json.ok) throw new Error(json.message || 'Story silinemedi.');
                toast(json.message || 'Story silindi.', 'success');
                window.setTimeout(function () { window.location.reload(); }, 400);
            }).catch(function (error) {
                toast(error.message || 'Story silinemedi.', 'error');
            }).finally(function () {
                button.disabled = false;
            });
        };
        if (window.ZaloroxModal && window.ZaloroxModal.confirm) {
            window.ZaloroxModal.confirm('Bu story silinsin mi?', { confirmLabel: 'Sil', cancelLabel: 'Vazgec', danger: true }).then(function (ok) {
                if (ok) run();
            });
        } else {
            run();
        }
    }

    document.addEventListener('keydown', function (event) {
        if (!viewer || viewer.hidden) return;
        if (event.key === 'Escape') closeViewer();
        if (event.key === 'ArrowLeft') renderStory(state.index - 1);
        if (event.key === 'ArrowRight') renderStory(state.index + 1);
    });

    document.addEventListener('touchstart', function (event) {
        if (!viewer || viewer.hidden || !event.touches.length) return;
        state.touchX = event.touches[0].clientX;
        state.touchY = event.touches[0].clientY;
    }, { passive: true });

    document.addEventListener('touchend', function (event) {
        if (!viewer || viewer.hidden || !event.changedTouches.length) return;
        var dx = event.changedTouches[0].clientX - state.touchX;
        var dy = event.changedTouches[0].clientY - state.touchY;
        if (Math.abs(dx) > 42 && Math.abs(dx) > Math.abs(dy)) {
            renderStory(state.index + (dx > 0 ? -1 : 1));
        }
    }, { passive: true });
})();
