/** * Product Reviews - Frontend JavaScript * Handles review display, submission, and helpful voting */ const ProductReviews = (function() { 'use strict'; let currentPage = 1; let currentSort = 'helpful'; let productId = null; let isLoading = false; /** * Public API: Initialize reviews for a product */ function init(pid) { productId = pid; if (!productId) { console.warn('Product ID not provided to ProductReviews.init()'); return; } initializeReviewTab(); loadReviews(); } /** * Initialize review tab functionality */ function initializeReviewTab() { // Tab switching const tabButtons = document.querySelectorAll('.tab-btn'); tabButtons.forEach(btn => { btn.addEventListener('click', function() { const tabName = this.dataset.tab; switchTab(tabName); }); }); // Sort dropdown const sortSelect = document.getElementById('review-sort'); if (sortSelect) { sortSelect.addEventListener('change', function() { currentSort = this.value; currentPage = 1; loadReviews(); }); } // Load more button const loadMoreBtn = document.getElementById('load-more-reviews'); if (loadMoreBtn) { loadMoreBtn.addEventListener('click', function() { currentPage++; loadReviews(true); // Append mode }); } // Write review button const writeReviewBtn = document.getElementById('write-review-btn'); if (writeReviewBtn) { writeReviewBtn.addEventListener('click', showReviewModal); } } /** * Switch between product tabs */ function switchTab(tabName) { // Update button states document.querySelectorAll('.tab-btn').forEach(btn => { btn.classList.toggle('active', btn.dataset.tab === tabName); }); // Update content visibility document.querySelectorAll('.tab-content').forEach(content => { content.style.display = content.id === `${tabName}-tab` ? 'block' : 'none'; }); } /** * Load reviews from API */ async function loadReviews(append = false) { if (isLoading) return; isLoading = true; const container = document.getElementById('reviews-list'); const loadMoreBtn = document.getElementById('load-more-reviews'); // Check if review section exists (product might not have reviews section) if (!container) { console.log('Review section not found - product may not have reviews yet'); isLoading = false; return; } try { if (!append) { container.innerHTML = '