(function () {
    'use strict';

    function readCfg(wrap) {
        var kind = 'review';
        if (wrap) {
            var attr = wrap.getAttribute('data-zerti-feedback-kind');
            if (attr === 'comment' || attr === 'review') {
                kind = attr;
            }
        }
        if (kind === 'comment' && typeof window.zertiInvComments === 'object' && window.zertiInvComments !== null) {
            return window.zertiInvComments;
        }
        return typeof window.zertiInvReviews === 'object' && window.zertiInvReviews !== null
            ? window.zertiInvReviews
            : {};
    }

    function parseAjaxJson(res) {
        if (!res.ok) {
            throw new Error('http');
        }
        return res.json();
    }

    function findWrap(root, kind) {
        if (!root) {
            return null;
        }
        if (kind === 'review' || kind === 'comment') {
            return root.querySelector('[data-zerti-inv-reviews="1"][data-zerti-feedback-kind="' + kind + '"]');
        }
        return root.querySelector('[data-zerti-inv-reviews="1"]');
    }

    function feedbackKindFromTab(tab) {
        return tab === 'comments' ? 'comment' : 'review';
    }

    function zertiLatinToPersianDigits(str) {
        return window.zertiLocalizeDigits(str);
    }

    function zertiPersianToLatinDigits(str) {
        return window.zertiToLatinDigits(str);
    }

    function zertiFaDigitsUi(str) {
        return zertiLatinToPersianDigits(str == null ? '' : String(str));
    }

    function zertiNotifyNavBadgesChanged() {
        if (typeof window.zertiRefreshDashboard === 'function') {
            window.zertiRefreshDashboard();
            return;
        }
        if (typeof window.zertiRefreshNavBadges === 'function') {
            window.zertiRefreshNavBadges();
            return;
        }
        if (typeof window.zertiRefreshPendingFeedbackBadges === 'function') {
            window.zertiRefreshPendingFeedbackBadges();
            return;
        }
        if (typeof window.zertiRefreshPendingReviewsBadge === 'function') {
            window.zertiRefreshPendingReviewsBadge();
        }
        try {
            document.dispatchEvent(new CustomEvent('zerti:nav-badges-changed'));
        } catch (e) {
            /* IE / very old browsers */
        }
    }

    function zertiDeleteConfirm(message, i18n) {
        var api = window.zertiConfirmAlert;
        if (api && typeof api.showDeleteConfirm === 'function') {
            return api.showDeleteConfirm(message, i18n);
        }
        return Promise.resolve(window.confirm(message));
    }

    /**
     * Mirror #zertiAdmin color mode and text direction onto review modals (appended under body).
     */
    function zertiSyncReviewModalsTheme() {
        var admin = document.getElementById('zertiAdmin');
        var theme = admin && admin.getAttribute('data-bs-theme');
        if (theme !== 'dark' && theme !== 'light') {
            theme = 'light';
        }
        var dir =
            typeof window.zertiAdminTextDirection === 'function' ? window.zertiAdminTextDirection() : admin && admin.getAttribute('dir') === 'ltr' ? 'ltr' : 'rtl';
        document.querySelectorAll('.zerti-inv-reviews__edit-modal').forEach(function (el) {
            el.setAttribute('data-bs-theme', theme);
            el.setAttribute('dir', dir);
            el.querySelectorAll('[data-zerti-field="content"], [data-zerti-field="reply"]').forEach(function (field) {
                field.setAttribute('dir', dir);
            });
        });
    }

    function zertiEnsureReviewModalsThemeObserver() {
        if (window.__zertiReviewModalsThemeObserver) {
            return;
        }
        var admin = document.getElementById('zertiAdmin');
        if (!admin || typeof MutationObserver === 'undefined') {
            return;
        }
        window.__zertiReviewModalsThemeObserver = new MutationObserver(function () {
            zertiSyncReviewModalsTheme();
        });
        window.__zertiReviewModalsThemeObserver.observe(admin, {
            attributes: true,
            attributeFilter: ['data-bs-theme', 'dir'],
        });
    }

    /**
     * Bootstrap backdrops attach to body; modals must live outside overflow:hidden ancestors
     * (#zertiAdmin / inventory panels) or taps can hit the wrong layer on mobile.
     */
    function zertiMoveReviewModalsToBody(wrap) {
        if (!wrap || !document.body) {
            return;
        }
        function moveModal(selector, staleId) {
            var el = wrap.querySelector(selector);
            if (!el) {
                return;
            }
            if (staleId) {
                try {
                    document.querySelectorAll('#' + staleId).forEach(function (node) {
                        if (node !== el) {
                            try {
                                if (window.bootstrap && window.bootstrap.Modal) {
                                    var inst = window.bootstrap.Modal.getInstance(node);
                                    if (inst) {
                                        inst.dispose();
                                    }
                                }
                            } catch (eDispose) {}
                            node.remove();
                        }
                    });
                } catch (eQ) {}
            }
            if (el.parentNode !== document.body) {
                document.body.appendChild(el);
            }
        }
        var modalEl = wrap.querySelector('.zerti-inv-reviews__edit-modal');
        moveModal('.zerti-inv-reviews__edit-modal', modalEl && modalEl.id ? modalEl.id : '');
        zertiSyncReviewModalsTheme();
    }

    function postAction(action, fields, wrap) {
        var cfg = readCfg(wrap);
        var body = new window.FormData();
        body.append('action', action);
        body.append('nonce', cfg.nonce || '');
        if (cfg.kind) {
            body.append('kind', cfg.kind);
        }
        if (fields && typeof fields === 'object') {
            Object.keys(fields).forEach(function (key) {
                var val = fields[key];
                if (val !== undefined && val !== null) {
                    body.append(key, String(val));
                }
            });
        }
        return window.fetch(cfg.ajaxUrl || '', {
            method: 'POST',
            credentials: 'same-origin',
            body: body,
        }).then(parseAjaxJson);
    }

    function escapeHtml(str) {
        var div = document.createElement('div');
        div.textContent = str == null ? '' : String(str);
        return div.innerHTML;
    }

    function renderDetailLink(url, label) {
        var text = label == null ? '' : String(label);
        var safeText = escapeHtml(zertiFaDigitsUi(text));
        if (!url) {
            return safeText;
        }
        return (
            '<a href="' +
            escapeHtml(String(url)) +
            '" class="zerti-inv-reviews__detail-link" target="_blank" rel="noopener noreferrer">' +
            safeText +
            '</a>'
        );
    }

    function InvReviewsManager(wrap) {
        this.wrap = wrap;
        this.cfg = readCfg(wrap);
        this.searchInput = wrap.querySelector('.zerti-inv-categories__search-input');
        this.gridEl = wrap.querySelector('.zerti-reviews-grid');
        this.statusFilterValue = '';
        this.editorBarTitle = wrap.querySelector('.zerti-inv-reviews__editor-bar-title');
        this.authorNameEl = wrap.querySelector('.zerti-inv-reviews__author-name');
        this.productNameEl = wrap.querySelector('.zerti-inv-reviews__product-name');
        this.submittedAtEl = wrap.querySelector('.zerti-inv-reviews__submitted-at');
        this.defaultModalTitle = this.editorBarTitle ? this.editorBarTitle.textContent : '';
        this.form = wrap.querySelector('.zerti-inv-reviews__form');
        this.formError = wrap.querySelector('.zerti-inv-reviews__form-error');
        this.formSuccess = wrap.querySelector('.zerti-inv-reviews__form-success');
        this.editModalEl = wrap.querySelector('.zerti-inv-reviews__edit-modal');

        this.items = [];
        this.selectedId = 0;
        this.searchTimer = null;
        this.editModal = null;
        this.awaitingDeleteConfirm = false;

        zertiMoveReviewModalsToBody(wrap);
        zertiEnsureReviewModalsThemeObserver();

        this.bindGridHandlers();

        var panelRoot = wrap.closest('[data-zerti-slot]') || wrap;
        if (typeof window.zertiInitReviewsTable === 'function') {
            window.zertiInitReviewsTable(panelRoot);
        }

        this.bindEvents();
        this.loadList();
    }

    InvReviewsManager.prototype.bindGridHandlers = function () {
        var self = this;
        window.zertiReviewsGridHandlers = {
            onSelect: function (id) {
                self.selectReview(id);
            },
            getStatusFilter: function () {
                return self.statusFilterValue || '';
            },
            setStatusFilter: function (value) {
                self.statusFilterValue = value == null ? '' : String(value);
            },
            onStatusFilterChange: function () {
                self.loadList();
            },
        };
        this.wrap.__zertiInvReviewsManager = this;
    };

    InvReviewsManager.prototype.getI18n = function () {
        return (this.cfg || readCfg(this.wrap)).i18n || {};
    };

    InvReviewsManager.prototype.bindEvents = function () {
        var self = this;

        if (this.searchInput) {
            this.searchInput.addEventListener('input', function () {
                if (self.searchTimer) {
                    window.clearTimeout(self.searchTimer);
                }
                self.searchTimer = window.setTimeout(function () {
                    self.loadList();
                }, 280);
            });
        }

        if (this.editModalEl) {
            this.editModalEl.addEventListener('hidden.bs.modal', function () {
                if (self.awaitingDeleteConfirm) {
                    return;
                }
                if (self.selectedId < 1) {
                    return;
                }
                self.selectedId = 0;
                if (self.editorBarTitle) {
                    self.editorBarTitle.textContent = self.defaultModalTitle;
                }
                if (self.authorNameEl) {
                    self.authorNameEl.textContent = '';
                }
                if (self.productNameEl) {
                    self.productNameEl.textContent = '';
                }
                if (self.submittedAtEl) {
                    self.submittedAtEl.textContent = '';
                    self.submittedAtEl.removeAttribute('datetime');
                }
                self.hideFormMessages();
                self.renderGrid();
            });
        }

        var deleteBtn = this.editModalEl
            ? this.editModalEl.querySelector('.zerti-inv-reviews__delete-btn')
            : null;
        if (deleteBtn) {
            deleteBtn.addEventListener('click', function () {
                self.confirmDelete();
            });
        }

        if (this.form) {
            this.form.addEventListener('submit', function (e) {
                e.preventDefault();
                self.saveForm();
            });
        }
    };

    InvReviewsManager.prototype.setLoading = function (on) {
        if (typeof window.zertiReviewsGridSetLoading === 'function') {
            window.zertiReviewsGridSetLoading(this.gridEl, on);
        }
    };

    InvReviewsManager.prototype.loadList = function () {
        var self = this;
        var cfg = this.cfg || readCfg(this.wrap);
        var i18n = this.getI18n();
        if (!cfg.ajaxUrl || !cfg.nonce) {
            return;
        }

        var search = this.searchInput ? this.searchInput.value.trim() : '';
        var status = this.statusFilterValue || '';

        this.setLoading(true);
        postAction(cfg.listAction || 'zerti_product_reviews_list', { search: search, status: status }, this.wrap)
            .then(function (data) {
                if (!data || !data.success || !data.data) {
                    throw new Error('bad');
                }
                self.items = Array.isArray(data.data.items) ? data.data.items : [];
                self.renderGrid();
            })
            .catch(function () {
                if (typeof window.zertiReviewsGridSetRows === 'function') {
                    window.zertiReviewsGridSetRows(self.gridEl, [], 0);
                }
            })
            .finally(function () {
                self.setLoading(false);
            });
    };

    InvReviewsManager.prototype.renderGrid = function () {
        if (typeof window.zertiReviewsGridSetRows === 'function') {
            window.zertiReviewsGridSetRows(this.gridEl, this.items, this.selectedId);
        }
    };

    InvReviewsManager.prototype.findItem = function (id) {
        return this.items.find(function (r) {
            return parseInt(r.id, 10) === id;
        });
    };

    InvReviewsManager.prototype.openEditModal = function () {
        if (!this.editModalEl || !window.bootstrap || !window.bootstrap.Modal) {
            return;
        }
        if (!this.editModal) {
            this.editModal = new window.bootstrap.Modal(this.editModalEl);
        }
        zertiSyncReviewModalsTheme();
        this.editModal.show();
    };

    InvReviewsManager.prototype.closeEditor = function () {
        this.selectedId = 0;
        if (this.editModal) {
            this.editModal.hide();
        }
        if (this.editorBarTitle) {
            this.editorBarTitle.textContent = this.defaultModalTitle;
        }
        if (this.authorNameEl) {
            this.authorNameEl.textContent = '';
        }
        if (this.productNameEl) {
            this.productNameEl.textContent = '';
        }
        if (this.submittedAtEl) {
            this.submittedAtEl.textContent = '';
            this.submittedAtEl.removeAttribute('datetime');
        }
        this.hideFormMessages();
        this.renderGrid();
    };

    InvReviewsManager.prototype.selectReview = function (id) {
        var item = this.findItem(id);
        if (!item) {
            return;
        }
        this.selectedId = id;
        this.showForm(item);
        this.openEditModal();
        this.renderGrid();
    };

    InvReviewsManager.prototype.showForm = function (item) {
        if (this.editorBarTitle) {
            this.editorBarTitle.textContent = this.defaultModalTitle;
        }
        if (this.authorNameEl) {
            this.authorNameEl.innerHTML = renderDetailLink(item.customer_url, item.author || '');
        }
        if (this.productNameEl) {
            this.productNameEl.innerHTML = renderDetailLink(item.product_url, item.product_name || '');
        }
        if (this.submittedAtEl) {
            var submittedAt = item.submitted_at || item.date || '';
            var submittedDisplay = zertiFaDigitsUi(submittedAt);
            this.submittedAtEl.textContent = submittedDisplay;
            if (item.date_sort > 0) {
                this.submittedAtEl.setAttribute('datetime', new Date(item.date_sort * 1000).toISOString());
            } else {
                this.submittedAtEl.removeAttribute('datetime');
            }
        }
        this.setField('id', item.id || 0);
        this.setField('content', zertiFaDigitsUi(item.content || ''));
        this.setField('rating', item.rating || 0);
        this.setField('status', item.status || 'hold');
        this.setField('reply', zertiFaDigitsUi(item.reply || ''));
        this.setField('reply_id', item.reply_id || 0);
        this.hideFormMessages();
    };

    InvReviewsManager.prototype.setField = function (name, value) {
        var el = this.form ? this.form.querySelector('[data-zerti-field="' + name + '"]') : null;
        if (!el) {
            return;
        }
        el.value = value == null ? '' : String(value);
    };

    InvReviewsManager.prototype.getField = function (name) {
        var el = this.form ? this.form.querySelector('[data-zerti-field="' + name + '"]') : null;
        return el ? el.value : '';
    };

    InvReviewsManager.prototype.hideFormMessages = function () {
        if (this.formError) {
            this.formError.classList.add('d-none');
        }
        if (this.formSuccess) {
            this.formSuccess.classList.add('d-none');
        }
    };

    InvReviewsManager.prototype.showFormError = function (msg) {
        if (this.formError) {
            this.formError.textContent = zertiFaDigitsUi(msg || '');
            this.formError.classList.remove('d-none');
        }
        if (this.formSuccess) {
            this.formSuccess.classList.add('d-none');
        }
    };

    InvReviewsManager.prototype.saveForm = function () {
        var self = this;
        var cfg = this.cfg || readCfg(this.wrap);
        var i18n = this.getI18n();
        var id = parseInt(this.getField('id'), 10);
        if (id < 1) {
            return;
        }

        var saveBtn = this.editModalEl
            ? this.editModalEl.querySelector('.zerti-inv-reviews__save-btn')
            : null;
        if (saveBtn) {
            saveBtn.disabled = true;
        }

        postAction(cfg.saveAction || 'zerti_product_review_save', {
            id: id,
            content: zertiPersianToLatinDigits(this.getField('content')),
            rating: this.getField('rating'),
            status: this.getField('status'),
            reply: zertiPersianToLatinDigits(this.getField('reply')),
            reply_id: this.getField('reply_id'),
        }, this.wrap)
            .then(function (data) {
                if (!data || !data.success) {
                    var msg = data && data.data && data.data.message ? data.data.message : i18n.saveError || '';
                    throw new Error(msg);
                }
                self.items = Array.isArray(data.data.items) ? data.data.items : self.items;
                self.closeEditor();
                zertiNotifyNavBadgesChanged();
            })
            .catch(function (err) {
                self.showFormError(err && err.message ? err.message : i18n.saveError || '');
            })
            .finally(function () {
                if (saveBtn) {
                    saveBtn.disabled = false;
                }
            });
    };

    InvReviewsManager.prototype.confirmDelete = function () {
        var i18n = this.getI18n();
        var id = this.selectedId;
        if (id < 1) {
            return;
        }
        var self = this;
        var item = this.findItem(id);
        var text = zertiFaDigitsUi((i18n.deleteConfirm || '').replace('%s', item && item.author ? item.author : ''));
        self.awaitingDeleteConfirm = true;
        if (this.editModal) {
            this.editModal.hide();
        }
        zertiDeleteConfirm(text, i18n).then(function (ok) {
            self.awaitingDeleteConfirm = false;
            if (ok) {
                self.performDelete();
                return;
            }
            if (self.selectedId > 0 && self.editModal) {
                self.editModal.show();
            }
        });
    };

    InvReviewsManager.prototype.performDelete = function () {
        var self = this;
        var cfg = this.cfg || readCfg(this.wrap);
        var i18n = this.getI18n();
        var id = this.selectedId;
        if (id < 1) {
            return;
        }

        postAction(cfg.deleteAction || 'zerti_product_review_delete', { id: id, force: '1' }, this.wrap)
            .then(function (data) {
                if (!data || !data.success) {
                    var msg = data && data.data && data.data.message ? data.data.message : i18n.deleteError || '';
                    throw new Error(msg);
                }
                self.closeEditor();
                self.items = Array.isArray(data.data.items) ? data.data.items : [];
                self.renderGrid();
                zertiNotifyNavBadgesChanged();
            })
            .catch(function (err) {
                self.showFormError(err && err.message ? err.message : i18n.deleteError || '');
                if (self.editModal) {
                    self.editModal.show();
                }
            });
    };

    function initInventoryReviews(root, kind) {
        if (!root) {
            return;
        }
        var wrap = findWrap(root, kind);
        if (!wrap) {
            return;
        }
        var cfg = readCfg(wrap);
        if (!cfg.ajaxUrl || !cfg.nonce) {
            return;
        }
        if (wrap.getAttribute('data-zerti-inv-reviews-inited') === '1') {
            var existing = wrap.__zertiInvReviewsManager;
            if (existing && typeof existing.bindGridHandlers === 'function') {
                existing.bindGridHandlers();
                existing.loadList();
            }
            return;
        }
        wrap.setAttribute('data-zerti-inv-reviews-inited', '1');
        window.requestAnimationFrame(function () {
            try {
                new InvReviewsManager(wrap);
            } catch (e) {
                wrap.removeAttribute('data-zerti-inv-reviews-inited');
            }
        });
    }

    window.zertiInitInventoryReviews = initInventoryReviews;
    window.zertiSyncReviewModalsTheme = zertiSyncReviewModalsTheme;
})();
