import React, { useMemo, useState, useEffect, useCallback } from 'react'; import * as XLSX from 'xlsx'; import { CombinedKPIs } from '../types'; import { pivotWeeklySalesData, WeeklyPivotRow } from '../services/dataProcessor'; interface WeeklyGridProps { data: CombinedKPIs[]; top50Ranking?: Map; // Static ranking of Top 50 ASINs by 2025 Sell Out } type SortConfig = { key: string; // weekKey direction: 'asc' | 'desc'; metric: 'units' | 'spend'; } | null; const ROWS_PER_PAGE = 50; const MAX_VISIBLE_WEEKS = 8; // Limit visible weeks for performance // Debounce hook for search const useDebounce = (value: string, delay: number) => { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { const handler = setTimeout(() => setDebouncedValue(value), delay); return () => clearTimeout(handler); }, [value, delay]); return debouncedValue; }; // Top 50 Badge Component const Top50Badge: React.FC<{ rank: number }> = ({ rank }) => ( 🏆 {rank} ); const WeeklyGrid: React.FC = ({ data, top50Ranking }) => { // Pivot data - memoized const { rows, weeks: allWeeks } = useMemo(() => pivotWeeklySalesData(data), [data]); // Limit visible weeks for performance const weeks = useMemo(() => allWeeks.slice(0, MAX_VISIBLE_WEEKS), [allWeeks]); const [searchTerm, setSearchTerm] = useState(''); const debouncedSearch = useDebounce(searchTerm, 300); const [currentPage, setCurrentPage] = useState(1); const [growthFilterMode, setGrowthFilterMode] = useState<'all' | 'up' | 'down' | 'stable'>('all'); const [growthThreshold, setGrowthThreshold] = useState(10); // Default sort: most recent week, descending, units const [sortConfig, setSortConfig] = useState(() => { if (weeks.length > 0) { return { key: weeks[0], direction: 'desc', metric: 'units' }; } return null; }); // Reset pagination when search changes useEffect(() => { setCurrentPage(1); }, [debouncedSearch]); const handleSort = useCallback((weekKey: string, metric: 'units' | 'spend') => { setSortConfig(prev => { if (prev?.key === weekKey && prev.metric === metric) { return { key: weekKey, direction: prev.direction === 'asc' ? 'desc' : 'asc', metric }; } return { key: weekKey, direction: 'desc', metric }; }); }, []); // Calculate totals in a SINGLE PASS (O(rows) instead of O(weeks × rows)) const weekTotals = useMemo(() => { const totals: { [weekKey: string]: { units: number, spend: number } } = {}; // Initialize all weeks weeks.forEach(week => { totals[week] = { units: 0, spend: 0 }; }); // Single pass through rows rows.forEach(row => { weeks.forEach(week => { totals[week].units += (row.unitsByWeek[week] || 0); totals[week].spend += (row.spendByWeek[week] || 0); }); }); return totals; }, [rows, weeks]); // 1. Filter by search term (using debounced value) const filteredRows = useMemo(() => { let result = rows; // Search Filter if (debouncedSearch) { const lowSearch = debouncedSearch.toLowerCase(); result = result.filter(r => r.sku.toLowerCase().includes(lowSearch) || r.asin.toLowerCase().includes(lowSearch) || r.title.toLowerCase().includes(lowSearch) || r.line.toLowerCase().includes(lowSearch) ); } // Growth Filter (if active) if (growthFilterMode !== 'all' && sortConfig) { const currentWeek = sortConfig.key; const currentWeekIdx = weeks.indexOf(currentWeek); const prevWeek = weeks[currentWeekIdx + 1]; if (prevWeek) { result = result.filter(r => { const currentUnits = r.unitsByWeek[currentWeek] || 0; const prevUnits = r.unitsByWeek[prevWeek] || 0; if (prevUnits === 0) { if (currentUnits === 0) return growthFilterMode === 'stable'; return growthFilterMode === 'up'; } const growth = ((currentUnits - prevUnits) / prevUnits) * 100; if (growthFilterMode === 'up') return growth >= growthThreshold; if (growthFilterMode === 'down') return growth <= -Math.abs(growthThreshold); if (growthFilterMode === 'stable') return Math.abs(growth) < growthThreshold; return true; }); } } return result; }, [rows, debouncedSearch, growthFilterMode, growthThreshold, sortConfig, weeks]); // 2. Sort results const sortedRows = useMemo(() => { if (!sortConfig) return filteredRows; const result = [...filteredRows]; const metricKey = sortConfig.metric === 'units' ? 'unitsByWeek' : 'spendByWeek'; const weekKey = sortConfig.key; const direction = sortConfig.direction; result.sort((a, b) => { const valA = a[metricKey][weekKey] || 0; const valB = b[metricKey][weekKey] || 0; return direction === 'asc' ? valA - valB : valB - valA; }); return result; }, [filteredRows, sortConfig]); // 3. Paginate const paginatedRows = useMemo(() => { const start = (currentPage - 1) * ROWS_PER_PAGE; return sortedRows.slice(start, start + ROWS_PER_PAGE); }, [sortedRows, currentPage]); const totalPages = Math.ceil(sortedRows.length / ROWS_PER_PAGE); const renderGrowth = useCallback((current: number, previous: number) => { if (!previous || previous === 0) return null; const pct = ((current - previous) / previous) * 100; const isPositive = pct >= 0; return ( {isPositive ? '▲' : '▼'}{Math.abs(pct).toFixed(0)}% ); }, []); // Export to Excel const handleExportExcel = useCallback(() => { const exportData = sortedRows.map(row => { const rowData: { [key: string]: string | number } = { SKU: row.sku, ASIN: row.asin, Title: row.title, Line: row.line, }; allWeeks.forEach(week => { rowData[`${week} Units`] = row.unitsByWeek[week] || 0; rowData[`${week} Spend`] = row.spendByWeek[week] || 0; }); return rowData; }); const ws = XLSX.utils.json_to_sheet(exportData); const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, 'Weekly Sales'); XLSX.writeFile(wb, `Weekly_Sales_Export_${new Date().toISOString().slice(0, 10)}.xlsx`); }, [sortedRows, allWeeks]); return (
{/* Toolbar: Search & Pagination */}
{/* Search Input */}
setSearchTerm(e.target.value)} className="w-full bg-slate-950 border border-white/10 rounded-lg px-4 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all pl-10" />
{/* Growth Filter */}
Growth Filter {growthFilterMode !== 'all' && (
Thresh: setGrowthThreshold(Number(e.target.value))} className="w-12 bg-slate-900 border border-white/10 rounded px-1.5 py-1 text-xs text-white text-center focus:outline-none focus:ring-1 focus:ring-indigo-500" /> %
)}
{/* Export Button */}
Showing {Math.min(filteredRows.length, (currentPage - 1) * ROWS_PER_PAGE + 1)}-{Math.min(filteredRows.length, currentPage * ROWS_PER_PAGE)} of {filteredRows.length}
{currentPage} / {Math.max(1, totalPages)}
{weeks.map(week => ( ))} {weeks.map((week, idx) => ( ))} {paginatedRows.length > 0 ? ( paginatedRows.map((row) => { const top50Rank = top50Ranking?.get(row.asin.trim().toUpperCase()); return ( {weeks.map((week, idx) => { const val = row.unitsByWeek[week] || 0; const prevVal = row.unitsByWeek[weeks[idx + 1]] || 0; const spend = row.spendByWeek[week] || 0; return ( ); })} ); }) ) : ( )}
Product Details
{/* Week Label */}
{week.split('-')[1]}/{week.split('-')[0].slice(-2)}
{/* Units Sort Trigger */}
handleSort(week, 'units')} className={`flex-1 p-1.5 cursor-pointer hover:bg-indigo-500/10 transition-colors flex items-center justify-center gap-1 border-b border-white/5 ${sortConfig?.key === week && sortConfig.metric === 'units' ? 'bg-indigo-500/5 text-indigo-400' : 'text-slate-500 hover:text-slate-300'}`} > Units {sortConfig?.key === week && sortConfig.metric === 'units' && ( {sortConfig.direction === 'asc' ? '↑' : '↓'} )}
{/* Spend Sort Trigger */}
handleSort(week, 'spend')} className={`flex-1 p-1.5 cursor-pointer hover:bg-amber-500/10 transition-colors flex items-center justify-center gap-1 ${sortConfig?.key === week && sortConfig.metric === 'spend' ? 'bg-amber-500/5 text-amber-400' : 'text-slate-500 hover:text-slate-300'}`} > Spend {sortConfig?.key === week && sortConfig.metric === 'spend' && ( {sortConfig.direction === 'asc' ? '↑' : '↓'} )}
TOTALS
{weekTotals[week]?.units.toLocaleString('de-DE') || 0} {renderGrowth(weekTotals[week]?.units || 0, weekTotals[weeks[idx + 1]]?.units || 0)}
€{(weekTotals[week]?.spend || 0).toLocaleString('de-DE', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}
{top50Rank && } {row.sku || '-'} {row.asin}
{row.title} {row.line}
0 ? (sortConfig?.key === week && sortConfig.metric === 'units' ? 'text-indigo-400' : 'text-white') : 'text-slate-700'}`}> {val > 0 ? val.toLocaleString('de-DE') : '-'} {val > 0 && renderGrowth(val, prevVal)}
{spend > 0 && ( €{spend.toLocaleString('de-DE', { minimumFractionDigits: 0, maximumFractionDigits: 0 })} )}
No SKUs found matching "{debouncedSearch}"
); }; export default WeeklyGrid;