(function () {
    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 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 };
            });
        });
    }

    function hasAuthGate(button) {
        return button && button.hasAttribute('data-auth-required');
    }

    function clearComposerError(root) {
        var error = root.querySelector('[data-community-form-error]');
        if (error) error.textContent = '';
    }

    function setComposerType(root, type) {
        root.querySelector('[data-community-post-type]').value = type;
        root.querySelectorAll('[data-community-type]').forEach(function (button) {
            button.classList.toggle('is-active', button.dataset.communityType === type);
        });
        root.querySelectorAll('[data-community-panel]').forEach(function (panel) {
            var active = panel.dataset.communityPanel === type;
            panel.hidden = !active;
            panel.classList.toggle('is-active', active);
        });
    }

    document.querySelectorAll('[data-community-composer]').forEach(function (root) {
        var form = root.querySelector('[data-community-form]');
        var typeInput = root.querySelector('[data-community-post-type]');
        var content = root.querySelector('textarea[name="content"]');
        var imageContent = root.querySelector('textarea[name="image_content"]');
        var imageInput = root.querySelector('[data-community-image-input]');
        var preview = root.querySelector('[data-community-image-preview]');
        var charCount = root.querySelector('[data-community-char-count]');

        root.querySelectorAll('[data-community-type]').forEach(function (button) {
            button.addEventListener('click', function () {
                setComposerType(root, button.dataset.communityType || 'text');
                clearComposerError(root);
            });
        });

        function updateCount() {
            if (charCount && content) charCount.textContent = String(content.value.length);
        }
        if (content) {
            content.addEventListener('input', updateCount);
            updateCount();
        }

        function renderImage(file) {
            if (!preview || !file || !file.type || file.type.indexOf('image/') !== 0) return;
            var reader = new FileReader();
            reader.onload = function () {
                preview.hidden = false;
                preview.innerHTML = '<img src="' + reader.result + '" alt=""><button class="pill" type="button" data-community-clear-image>Sil</button>';
            };
            reader.readAsDataURL(file);
        }

        if (imageInput) {
            imageInput.addEventListener('change', function () {
                renderImage(imageInput.files && imageInput.files[0]);
            });
        }

        root.querySelectorAll('[data-community-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 (!imageInput || !event.dataTransfer || !event.dataTransfer.files.length) return;
                imageInput.files = event.dataTransfer.files;
                renderImage(imageInput.files[0]);
            });
        });

        root.addEventListener('click', function (event) {
            var clear = event.target.closest('[data-community-clear-image]');
            if (clear && imageInput && preview) {
                imageInput.value = '';
                preview.hidden = true;
                preview.innerHTML = '';
            }

            var addOption = event.target.closest('[data-community-add-option]');
            if (addOption) {
                var builder = root.querySelector('[data-community-poll-builder]');
                if (!builder) return;
                var count = builder.querySelectorAll('input[name="poll_options[]"]').length;
                if (count >= 6) {
                    toast('En fazla 6 secenek ekleyebilirsin.', 'warning');
                    return;
                }
                var label = document.createElement('label');
                label.innerHTML = 'Secenek ' + (count + 1) + '<span class="community-option-row"><input name="poll_options[]" maxlength="160" placeholder="Secenek"><button class="icon-btn" type="button" data-community-remove-option aria-label="Secenegi sil">&times;</button></span>';
                builder.appendChild(label);
            }

            var removeOption = event.target.closest('[data-community-remove-option]');
            if (removeOption) {
                var optionLabels = root.querySelectorAll('[data-community-poll-builder] label');
                if (optionLabels.length <= 2) {
                    toast('Anket icin en az 2 secenek gerekli.', 'warning');
                    return;
                }
                removeOption.closest('label').remove();
            }
        });

        if (!form) return;
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            clearComposerError(root);
            var submit = form.querySelector('[type="submit"]');
            var type = (typeInput && typeInput.value) || 'text';
            var data = new FormData(form);
            data.set('post_type', type);
            data.set('_csrf', data.get('_csrf') || csrf);
            if (type === 'image') {
                data.set('content', imageContent ? imageContent.value : '');
            }

            if (submit) submit.disabled = true;
            fetch(form.action, {
                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 || 'Gonderi yayinlanamadi.');
                toast(json.message || 'Gonderi yayinlandi.', json.status === 'pending_review' ? 'warning' : 'success');
                window.setTimeout(function () { window.location.reload(); }, 550);
            }).catch(function (error) {
                var errorBox = root.querySelector('[data-community-form-error]');
                if (errorBox) errorBox.textContent = error.message || 'Gonderi yayinlanamadi.';
                toast(error.message || 'Gonderi yayinlanamadi.', 'error');
            }).finally(function () {
                if (submit) submit.disabled = false;
            });
        });
    });

    function updateCounts(card, json) {
        if (!card || !json) return;
        var like = card.querySelector('[data-like-count]');
        var dislike = card.querySelector('[data-dislike-count]');
        var comments = card.querySelector('[data-comment-count]');
        if (like && json.like_count !== undefined) like.textContent = String(json.like_count);
        if (dislike && json.dislike_count !== undefined) dislike.textContent = String(json.dislike_count);
        if (comments && json.comment_count !== undefined) comments.textContent = String(json.comment_count);
        card.querySelectorAll('[data-community-react]').forEach(function (button) {
            button.classList.toggle('is-active', button.dataset.communityReact === json.viewer_reaction);
        });
    }

    document.addEventListener('click', function (event) {
        var react = event.target.closest('[data-community-react]');
        if (react) {
            if (hasAuthGate(react)) return;
            event.preventDefault();
            var card = react.closest('[data-community-post]');
            if (!card) return;
            react.disabled = true;
            request('/api/community/react', {
                post_id: card.dataset.postId,
                reaction: react.dataset.communityReact
            }).then(function (json) {
                if (!json.ok) throw new Error(json.message || 'Reaksiyon kaydedilemedi.');
                updateCounts(card, json);
            }).catch(function (error) {
                toast(error.message || 'Reaksiyon kaydedilemedi.', 'error');
            }).finally(function () {
                react.disabled = false;
            });
            return;
        }

        var toggle = event.target.closest('[data-community-comments-toggle]');
        if (toggle) {
            var comments = toggle.closest('[data-community-post]').querySelector('[data-community-comments]');
            if (comments) comments.hidden = !comments.hidden;
            return;
        }

        var poll = event.target.closest('[data-community-poll-option]');
        if (poll) {
            if (hasAuthGate(poll)) return;
            event.preventDefault();
            var pollCard = poll.closest('[data-community-post]');
            if (!pollCard) return;
            poll.disabled = true;
            request('/api/community/poll-vote', {
                post_id: pollCard.dataset.postId,
                option_id: poll.dataset.optionId
            }).then(function (json) {
                if (!json.ok) throw new Error(json.message || 'Oy kaydedilemedi.');
                renderPoll(pollCard, json.post || {});
                toast(json.message || 'Oy kaydedildi.', 'success');
            }).catch(function (error) {
                toast(error.message || 'Oy kaydedilemedi.', 'error');
            }).finally(function () {
                poll.disabled = false;
            });
            return;
        }

        var share = event.target.closest('[data-community-share]');
        if (share) {
            var shareCard = share.closest('[data-community-post]');
            var link = shareCard ? shareCard.dataset.shareUrl : window.location.href;
            if (navigator.share) {
                navigator.share({ title: document.title || 'Zalorox', url: link }).catch(function () {});
                return;
            }
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(link).then(function () {
                    toast('Paylasim linki kopyalandi.', 'success');
                }).catch(function () {
                    toast(link, 'info');
                });
                return;
            }
            toast(link, 'info');
            return;
        }

        var remove = event.target.closest('[data-community-delete]');
        if (remove) {
            var removeCard = remove.closest('[data-community-post]');
            if (!removeCard) return;
            var run = function () {
                remove.disabled = true;
                request('/api/community/delete', { post_id: removeCard.dataset.postId }).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Gonderi silinemedi.');
                    toast(json.message || 'Gonderi silindi.', 'success');
                    removeCard.remove();
                }).catch(function (error) {
                    toast(error.message || 'Gonderi silinemedi.', 'error');
                }).finally(function () {
                    remove.disabled = false;
                });
            };
            if (window.ZaloroxModal && window.ZaloroxModal.confirm) {
                window.ZaloroxModal.confirm('Bu gonderi silinsin mi?', { confirmLabel: 'Sil', cancelLabel: 'Vazgec', danger: true }).then(function (ok) {
                    if (ok) run();
                });
            } else {
                run();
            }
        }
    });

    document.addEventListener('submit', function (event) {
        var form = event.target.closest('[data-community-comment-form]');
        if (!form) return;
        event.preventDefault();
        var card = form.closest('[data-community-post]');
        var textarea = form.querySelector('textarea[name="content"]');
        var content = textarea ? textarea.value.trim() : '';
        if (!card || content.length < 2) {
            toast('Yorum en az 2 karakter olmali.', 'warning');
            return;
        }
        var submit = form.querySelector('[type="submit"]');
        if (submit) submit.disabled = true;
        request('/api/community/comment', {
            post_id: card.dataset.postId,
            content: content
        }).then(function (json) {
            if (!json.ok) throw new Error(json.message || 'Yorum kaydedilemedi.');
            appendComment(card, json.comment || { content: content });
            if (textarea) textarea.value = '';
            updateCounts(card, { comment_count: Number((card.querySelector('[data-comment-count]') || {}).textContent || 0) + 1 });
            toast(json.message || 'Yorum yayinlandi.', json.status === 'pending_review' ? 'warning' : 'success');
        }).catch(function (error) {
            toast(error.message || 'Yorum kaydedilemedi.', 'error');
        }).finally(function () {
            if (submit) submit.disabled = false;
        });
    });

    function appendComment(card, comment) {
        var list = card.querySelector('[data-community-comment-list]');
        if (!list) return;
        var name = comment.display_name || 'Sen';
        var node = document.createElement('article');
        node.className = 'community-comment';
        node.innerHTML = '<strong>' + escapeHtml(name) + '</strong><p>' + escapeHtml(comment.content || '') + '</p>';
        list.prepend(node);
    }

    function renderPoll(card, post) {
        var wrapper = card.querySelector('[data-community-poll]');
        if (!wrapper || !post.poll_options) return;
        var total = Number(post.poll_total_votes || 0);
        var options = wrapper.querySelector('.community-poll-options');
        if (!options) return;
        options.innerHTML = post.poll_options.map(function (option) {
            var percent = Math.max(0, Math.min(100, Number(option.percent || 0)));
            return '<button type="button" class="community-poll-option' + (option.viewer_voted ? ' is-selected' : '') + '" style="--poll-percent: ' + percent + '%;" data-community-poll-option data-option-id="' + escapeHtml(option.id) + '">' +
                '<span class="community-poll-fill"></span><span>' + escapeHtml(option.option_text) + '</span><em>' + percent + '%</em></button>';
        }).join('');
        var totalNode = wrapper.querySelector('small');
        if (totalNode) totalNode.textContent = total.toLocaleString('tr-TR') + ' oy';
    }

    document.querySelectorAll('[data-community-feed-slider]').forEach(function (slider) {
        var wrap = slider.closest('.home-community-feed');
        var prev = wrap ? wrap.querySelector('[data-community-feed-prev]') : null;
        var next = wrap ? wrap.querySelector('[data-community-feed-next]') : null;

        function move(direction) {
            var distance = Math.max(280, Math.round(slider.clientWidth * 0.82));
            slider.scrollBy({ left: direction * distance, behavior: 'smooth' });
        }

        if (prev) prev.addEventListener('click', function () { move(-1); });
        if (next) next.addEventListener('click', function () { move(1); });

        slider.addEventListener('wheel', function (event) {
            if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
            slider.scrollLeft += event.deltaY;
            event.preventDefault();
        }, { passive: false });
    });
})();
