(function (window, document) {
    'use strict';

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

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

    function statusBadgeClass(status) {
        switch (status) {
            case 'approve':
                return 'bg-success';
            case 'hold':
                return 'bg-warning text-dark';
            case 'spam':
                return 'bg-danger';
            default:
                return 'bg-secondary';
        }
    }

    function mapItemsToRows(items) {
        return (items || []).map(function (item) {
            var id = parseInt(item.id || 0, 10);
            var rating = parseInt(item.rating || 0, 10);
            var stars = rating > 0 ? '★'.repeat(rating) : '—';
            var status = item.status || '';
            var statusLabel = item.status_label || status;
            return {
                idRaw: id,
                product_name: item.product_name || '',
                author: item.author || '',
                rating_display: zertiLatinToPersianDigits(stars),
                rating_raw: rating,
                status: status,
                status_label: statusLabel,
                status_html:
                    '<span class="badge ' +
                    statusBadgeClass(status) +
                    '">' +
                    escapeHtml(statusLabel) +
                    '</span>',
                date: item.date || '',
                date_sort: parseInt(item.date_sort || 0, 10),
            };
        });
    }

    function reviewsStatusFilterOptions() {
        var cfg = typeof window.zertiInvReviews === 'object' && window.zertiInvReviews !== null ? window.zertiInvReviews : {};
        var choices = cfg.statusChoices && typeof cfg.statusChoices === 'object' ? cfg.statusChoices : {};
        return Object.keys(choices).map(function (value) {
            return {
                value: value,
                label: choices[value],
            };
        });
    }

    function reviewsStatusHeaderParams(i18n) {
        return {
            getOptions: reviewsStatusFilterOptions,
            selectClass: 'zerti-grid-filter-select',
            filterAllLabel: i18n.filterAll || '',
            onFilterChange: function (value) {
                var handlers =
                    typeof window.zertiReviewsGridHandlers === 'object' && window.zertiReviewsGridHandlers !== null
                        ? window.zertiReviewsGridHandlers
                        : {};
                if (typeof handlers.setStatusFilter === 'function') {
                    handlers.setStatusFilter(value);
                }
                if (typeof handlers.onStatusFilterChange === 'function') {
                    handlers.onStatusFilterChange(value);
                }
            },
            getFilterValue: function () {
                var handlers =
                    typeof window.zertiReviewsGridHandlers === 'object' && window.zertiReviewsGridHandlers !== null
                        ? window.zertiReviewsGridHandlers
                        : {};
                return typeof handlers.getStatusFilter === 'function' ? handlers.getStatusFilter() : '';
            },
        };
    }

    function buildColumnDefs(i18n, viewport) {
        var isCompact = viewport && viewport.isCompact;
        return [
            {
                colId: 'product',
                headerName: i18n.colProduct || '',
                field: 'product_name',
                minWidth: isCompact ? 96 : 160,
                flex: isCompact ? 2.5 : 5,
            },
            {
                colId: 'author',
                headerName: i18n.colAuthor || '',
                field: 'author',
                minWidth: 88,
                flex: 1,
            },
            {
                colId: 'rating',
                headerName: i18n.colRating || '',
                field: 'rating_display',
                cellClass: 'text-center',
                minWidth: 72,
                maxWidth: 88,
                flex: 0,
            },
            {
                colId: 'status',
                headerName: i18n.colStatus || '',
                field: 'status_html',
                cellRenderer: function (params) {
                    return params.value || '';
                },
                flex: 0,
                minWidth: isCompact ? 64 : 96,
                maxWidth: isCompact ? 200 : 220,
                suppressSizeToFit: true,
                resizable: true,
                filter: false,
                suppressHeaderFilterButton: true,
                headerComponent: 'zertiInlineFilterHeader',
                headerComponentParams: reviewsStatusHeaderParams(i18n),
            },
            {
                colId: 'date',
                headerName: i18n.colDate || '',
                field: 'date',
                comparator: function (valueA, valueB, nodeA, nodeB) {
                    var a = nodeA && nodeA.data ? nodeA.data.date_sort || 0 : 0;
                    var b = nodeB && nodeB.data ? nodeB.data.date_sort || 0 : 0;
                    return a - b;
                },
                flex: 0,
                minWidth: isCompact ? 72 : 80,
                maxWidth: isCompact ? 120 : 128,
                suppressSizeToFit: true,
                resizable: true,
            },
        ];
    }

    function reviewsGridInnerWidth(gridEl) {
        if (!gridEl) {
            return 0;
        }
        var wrap = gridEl.closest('.zerti-reviews-wrap');
        return Math.max(
            wrap && wrap.clientWidth ? wrap.clientWidth : 0,
            gridEl.clientWidth || 0,
            gridEl.offsetWidth || 0
        );
    }

    function isReviewsGridCompact(width) {
        return width < 992;
    }

    function applyReviewsResponsiveColumns(api, gridEl) {
        if (!api || !gridEl) {
            return;
        }
        var width = reviewsGridInnerWidth(gridEl);
        var isCompact = isReviewsGridCompact(width);
        var viewport = { isCompact: isCompact };
        var i18n = (typeof window.zertiInvReviews === 'object' && window.zertiInvReviews.i18n) || {};
        var nextMode = isCompact ? 'compact' : 'desktop';

        if (gridEl.__zertiReviewsViewportMode !== nextMode) {
            gridEl.__zertiReviewsViewportMode = nextMode;
            var columnDefs = buildColumnDefs(i18n, viewport);
            if (api.setGridOption) {
                api.setGridOption('columnDefs', columnDefs);
            } else if (api.setColumnDefs) {
                api.setColumnDefs(columnDefs);
            }
        }

        var visibility = {
            product: true,
            author: !isCompact,
            rating: !isCompact,
            status: true,
            date: true,
        };
        var state = Object.keys(visibility).map(function (colId) {
            return {
                colId: colId,
                hide: !visibility[colId],
            };
        });

        if (api.applyColumnState) {
            api.applyColumnState({ state: state, applyOrder: false });
        } else if (api.setColumnsVisible) {
            Object.keys(visibility).forEach(function (colId) {
                api.setColumnsVisible([colId], visibility[colId]);
            });
        }

        gridEl.classList.toggle('zerti-reviews-grid--compact', isCompact);
        stabilizeReviewsLayout(api, gridEl);
    }

    function stabilizeReviewsLayout(api, gridEl) {
        if (!api || !gridEl) {
            return;
        }
        if (api.setGridOption) {
            api.setGridOption('suppressHorizontalScroll', isReviewsGridCompact(reviewsGridInnerWidth(gridEl)));
        }
        window.requestAnimationFrame(function () {
            try {
                if (api.autoSizeColumns) {
                    api.autoSizeColumns({
                        columns: ['status', 'date'],
                        skipHeader: false,
                    });
                }
            } catch (e1) {}
            window.requestAnimationFrame(function () {
                try {
                    if (api.sizeColumnsToFit) {
                        api.sizeColumnsToFit();
                    }
                } catch (e2) {}
            });
        });
    }

    function findReviewsGridEl(root) {
        if (!root) {
            return null;
        }
        return (
            root.querySelector('.zerti-reviews-grid') ||
            root.querySelector('#zertiInvReviewsGrid') ||
            root.querySelector('#zertiInvCommentsGrid')
        );
    }

    function destroyReviewsGrid(root) {
        if (!root) {
            return;
        }
        var gridEl = findReviewsGridEl(root);
        if (!gridEl) {
            return;
        }
        if (typeof gridEl.__zertiAgGridCleanup === 'function') {
            gridEl.__zertiAgGridCleanup();
            gridEl.__zertiAgGridCleanup = null;
        }
        if (gridEl.__zertiAgGridApi && typeof gridEl.__zertiAgGridApi.destroy === 'function') {
            gridEl.__zertiAgGridApi.destroy();
            gridEl.__zertiAgGridApi = null;
        }
    }

    function zertiInitReviewsTable(root) {
        if (!root || !window.agGrid || typeof window.agGrid.createGrid !== 'function') {
            return null;
        }

        var gridEl = findReviewsGridEl(root);
        if (!gridEl) {
            return null;
        }

        destroyReviewsGrid(root);

        var i18n = (typeof window.zertiInvReviews === 'object' && window.zertiInvReviews.i18n) || {};
        var handlers =
            typeof window.zertiReviewsGridHandlers === 'object' && window.zertiReviewsGridHandlers !== null
                ? window.zertiReviewsGridHandlers
                : {};

        var gridWidth = reviewsGridInnerWidth(gridEl);
        var initialViewport = {
            isCompact: isReviewsGridCompact(gridWidth),
        };
        gridEl.__zertiReviewsViewportMode = initialViewport.isCompact ? 'compact' : 'desktop';

        var gridOptions = {
            theme: 'legacy',
            rowModelType: 'clientSide',
            components: typeof window.zertiAgGridComponents === 'function' ? window.zertiAgGridComponents() : {},
            columnDefs: buildColumnDefs(i18n, initialViewport),
            rowData: [],
            defaultColDef: {
                sortable: true,
                resizable: true,
                filter: false,
                floatingFilter: false,
                cellClass: 'zerti-reviews-grid-cell',
            },
            enableRtl: window.zertiIsAdminRtl ? window.zertiIsAdminRtl() : true,
            animateRows: true,
            pagination: true,
            paginationPageSize: 50,
            paginationPageSizeSelector: false,
            paginationPanels: ['pageSummary', 'rowSummary'],
            paginationNumberFormatter: function (params) {
                return zertiLatinToPersianDigits(params.value);
            },
            suppressNoRowsOverlay: true,
            suppressRowClickSelection: true,
            getRowId: function (params) {
                return String(params.data.idRaw);
            },
            rowClassRules: {
                'zerti-reviews-grid-row--active': function (params) {
                    var sel = window.zertiReviewsGridSelectedId || 0;
                    return params.data && parseInt(params.data.idRaw, 10) === parseInt(sel, 10);
                },
            },
            localeText: window.zertiAgGridLocaleText
                ? window.zertiAgGridLocaleText(i18n, 'noRowsToShow')
                : {
                    page: '',
                    loadingOoo: i18n.loading || '',
                    noRowsToShow: i18n.noRowsToShow || i18n.emptyList || '',
                },
            onRowClicked: function (event) {
                if (!event || !event.data) {
                    return;
                }
                var domEvent = event.event;
                var target = domEvent && domEvent.target ? domEvent.target : null;
                if (target && target.closest) {
                    if (
                        target.closest(
                            'button, a, select, input, textarea, label, .ag-header, .ag-paging-panel'
                        )
                    ) {
                        return;
                    }
                }
                var id = parseInt(event.data.idRaw || 0, 10);
                if (id > 0 && typeof handlers.onSelect === 'function') {
                    handlers.onSelect(id);
                }
            },
            onGridReady: function (params) {
                gridEl.__zertiAgGridApi = params.api;
                applyReviewsResponsiveColumns(params.api, gridEl);
            },
            onFirstDataRendered: function (params) {
                applyReviewsResponsiveColumns(params.api, gridEl);
            },
        };

        var api = window.agGrid.createGrid(gridEl, gridOptions);
        gridEl.__zertiAgGridApi = api;
        gridEl.classList.add('zerti-reviews-grid--row-nav');

        var resizeTimer = null;
        var onResize = function () {
            if (resizeTimer) {
                window.clearTimeout(resizeTimer);
            }
            resizeTimer = window.setTimeout(function () {
                resizeTimer = null;
                applyReviewsResponsiveColumns(api, gridEl);
            }, 120);
        };
        window.addEventListener('resize', onResize);

        gridEl.__zertiAgGridCleanup = function () {
            if (resizeTimer) {
                window.clearTimeout(resizeTimer);
                resizeTimer = null;
            }
            window.removeEventListener('resize', onResize);
        };

        return api;
    }

    function zertiReviewsGridSetRows(gridEl, items, selectedId) {
        if (!gridEl || !gridEl.__zertiAgGridApi) {
            return;
        }
        var rows = mapItemsToRows(items);
        var api = gridEl.__zertiAgGridApi;
        if (api.setGridOption) {
            api.setGridOption('rowData', rows);
        } else if (api.setRowData) {
            api.setRowData(rows);
        }
        window.zertiReviewsGridSelectedId = selectedId > 0 ? selectedId : 0;
        zertiReviewsGridSetSelected(gridEl, selectedId);
        if (api.redrawRows) {
            api.redrawRows();
        }
        applyReviewsResponsiveColumns(api, gridEl);
    }

    function zertiReviewsGridSetSelected(gridEl, selectedId) {
        if (!gridEl || !gridEl.__zertiAgGridApi) {
            return;
        }
        var api = gridEl.__zertiAgGridApi;
        api.deselectAll();
        if (!(selectedId > 0)) {
            return;
        }
        var node = api.getRowNode(String(selectedId));
        if (node) {
            node.setSelected(true);
            if (api.ensureIndexVisible) {
                api.ensureIndexVisible(node.rowIndex, 'middle');
            }
        }
    }

    function zertiReviewsGridSetLoading(gridEl, on) {
        if (!gridEl) {
            return;
        }
        if (apiSetLoading(gridEl, on)) {
            return;
        }
        gridEl.classList.toggle('opacity-50', !!on);
    }

    function apiSetLoading(gridEl, on) {
        var api = gridEl && gridEl.__zertiAgGridApi;
        if (!api) {
            return false;
        }
        if (on) {
            if (api.showLoadingOverlay) {
                api.showLoadingOverlay();
                return true;
            }
        } else if (api.hideOverlay) {
            api.hideOverlay();
            return true;
        }
        return false;
    }

    window.zertiDestroyReviewsGrid = destroyReviewsGrid;
    window.zertiInitReviewsTable = zertiInitReviewsTable;
    window.zertiReviewsGridSetRows = zertiReviewsGridSetRows;
    window.zertiReviewsGridSetSelected = zertiReviewsGridSetSelected;
    window.zertiReviewsGridSetLoading = zertiReviewsGridSetLoading;
})(window, document);
