'use client'; import React, { useEffect, useRef, useState } from 'react'; import { DashboardTopProduct } from '@/services/api/adminService'; import { formatInr } from '@/components/dashboard/DashboardShared'; export interface PillarMatrixProps { products: DashboardTopProduct[]; hoveredProductIndex?: number | null; onHoverProduct?: (index: number | null) => void; className?: string; } interface HexData { id: number; q: number; r: number; dist: number; productIndex: number; productName: string; salesCount: number; revenue: number; level: number; baseHeight: number; } // 5-Level Discrete Palette (21st.dev Style) const TIER_COLORS = [ { // Level 0: Baseline / Ranks 21-25 capTop: '#1e293b', capBottom: '#0f172a', sideLeft: '#0a0f1d', sideRight: '#030712', border: 'rgba(71, 85, 105, 0.4)', }, { // Level 1: Ranks 15-20 capTop: '#3b0764', capBottom: '#2e1065', sideLeft: '#1e1b4b', sideRight: '#0f0728', border: 'rgba(147, 51, 234, 0.4)', }, { // Level 2: Ranks 8-14 capTop: '#6b21a8', capBottom: '#581c87', sideLeft: '#3b0764', sideRight: '#1e053a', border: 'rgba(168, 85, 247, 0.55)', }, { // Level 3: Ranks 3-7 capTop: '#9333ea', capBottom: '#7e22ce', sideLeft: '#581c87', sideRight: '#2e0854', border: 'rgba(216, 180, 254, 0.75)', }, { // Level 4: Ranks 1-2 (Peak Top Sellers) capTop: '#c084fc', capBottom: '#a855f7', sideLeft: '#6b21a8', sideRight: '#3b0764', border: 'rgba(250, 204, 21, 0.9)', }, ]; // Generates concentric axial coordinates (q, r) for up to 25 products function generateConcentricCoords(count = 25): { q: number; r: number }[] { const coords: { q: number; r: number }[] = [{ q: 0, r: 0 }]; // Rank 1: Center for (let ring = 1; ring <= 3; ring++) { let q = -ring; let r = ring; const ringDirs = [ { dq: 1, dr: 0 }, { dq: 1, dr: -1 }, { dq: 0, dr: -1 }, { dq: -1, dr: 0 }, { dq: -1, dr: 1 }, { dq: 0, dr: 1 }, ]; for (const d of ringDirs) { for (let step = 0; step < ring; step++) { if (coords.length >= count) break; coords.push({ q, r }); q += d.dq; r += d.dr; } if (coords.length >= count) break; } if (coords.length >= count) break; } return coords; } export function PillarGridCanvas({ products = [], hoveredProductIndex = null, onHoverProduct, className = '', }: PillarMatrixProps) { const canvasRef = useRef(null); const containerRef = useRef(null); // Active Tooltip HUD const [tooltip, setTooltip] = useState<{ visible: boolean; x: number; y: number; rank: number; title: string; sales: number; revenue: number; } | null>(null); const hoveredIdxRef = useRef(hoveredProductIndex ?? null); useEffect(() => { hoveredIdxRef.current = hoveredProductIndex ?? null; }, [hoveredProductIndex]); useEffect(() => { const canvas = canvasRef.current; const container = containerRef.current; if (!canvas || !container) return; const ctx = canvas.getContext('2d', { alpha: true }); if (!ctx) return; let animId: number; let width = 0; let height = 0; const resize = () => { const dpr = Math.min(window.devicePixelRatio || 1, 2); const rect = container.getBoundingClientRect(); width = Math.max(rect.width, 240); height = Math.max(rect.height, 220); canvas.width = width * dpr; canvas.height = height * dpr; canvas.style.width = `${width}px`; canvas.style.height = `${height}px`; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); }; resize(); const ro = new ResizeObserver(resize); ro.observe(container); // Build 25 Active Hexagonal Nodes const targetCount = Math.max(Math.min(products.length, 25), 1); const coords = generateConcentricCoords(targetCount); const hexRadius = 14; // Compact size to fit all 25 hexes neatly const nodes: HexData[] = []; for (let i = 0; i < targetCount; i++) { const p = products[i]; const coord = coords[i] || { q: 0, r: 0 }; const dist = Math.hypot(coord.q, coord.r); // Determine level & base height by rank let level = 0; let baseHeight = 8; if (i === 0) { level = 4; baseHeight = 44; } else if (i === 1) { level = 4; baseHeight = 38; } else if (i < 7) { level = 3; baseHeight = 28 + (6 - i) * 1.5; } else if (i < 14) { level = 2; baseHeight = 20 + (13 - i) * 1.0; } else if (i < 20) { level = 1; baseHeight = 14 + (19 - i) * 0.8; } else { level = 0; baseHeight = 9; } nodes.push({ id: i, q: coord.q, r: coord.r, dist, productIndex: i, productName: p ? p.name : `Product #${i + 1}`, salesCount: p ? p.total_sold : 0, revenue: p ? p.total_revenue : 0, level, baseHeight, }); } // Sort back-to-front (isometric painter's algorithm) nodes.sort((a, b) => a.q + a.r * 1.2 - (b.q + b.r * 1.2)); // Dynamic height and opacity springs const currentHeights = new Map(); const currentOpacities = new Map(); nodes.forEach((n) => { currentHeights.set(n.id, n.baseHeight); currentOpacities.set(n.id, 1.0); }); let hoveredNodeId: number | null = null; const checkHover = (mx: number, my: number) => { const cos30 = Math.cos(Math.PI / 6); const sin30 = Math.sin(Math.PI / 6); const hexW = hexRadius * Math.sqrt(3); const originX = width / 2; const originY = height / 2 + 16; for (let i = nodes.length - 1; i >= 0; i--) { const node = nodes[i]; const cartX = (node.q + node.r / 2) * hexW; const cartY = node.r * (hexRadius * 1.5); const screenX = originX + (cartX - cartY) * cos30; const screenY = originY + (cartX + cartY) * sin30 * 0.72; const h = currentHeights.get(node.id) || node.baseHeight; const topY = screenY - h; const d = Math.hypot(mx - screenX, my - topY); if (d <= hexRadius) { return { node, screenX, topY }; } } return null; }; const onMouseMove = (e: MouseEvent) => { const rect = canvas.getBoundingClientRect(); const mx = e.clientX - rect.left; const my = e.clientY - rect.top; const hit = checkHover(mx, my); if (hit) { hoveredNodeId = hit.node.id; if (onHoverProduct) onHoverProduct(hit.node.productIndex); } else { hoveredNodeId = null; if (onHoverProduct && hoveredIdxRef.current !== null) { onHoverProduct(null); } } }; const onMouseLeave = () => { hoveredNodeId = null; if (onHoverProduct) onHoverProduct(null); }; canvas.addEventListener('mousemove', onMouseMove); canvas.addEventListener('mouseleave', onMouseLeave); const drawHexagon = (cx: number, cy: number, radius: number) => { ctx.beginPath(); for (let i = 0; i < 6; i++) { const rad = (Math.PI / 3) * i + Math.PI / 6; const px = cx + radius * Math.cos(rad); const py = cy + radius * Math.sin(rad) * 0.65; if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } ctx.closePath(); }; // Render loop const render = () => { ctx.clearRect(0, 0, width, height); const originX = width / 2; const originY = height / 2 + 16; const cos30 = Math.cos(Math.PI / 6); const sin30 = Math.sin(Math.PI / 6); const hexW = hexRadius * Math.sqrt(3); const activeProductIdx = hoveredIdxRef.current; const isAnyActive = activeProductIdx !== null; let activeTooltipData: typeof tooltip = null; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; const isThisProductActive = node.productIndex === activeProductIdx || node.id === hoveredNodeId; const targetH = isThisProductActive ? 58 : node.baseHeight; const targetAlpha = isAnyActive ? (isThisProductActive ? 1.0 : 0.32) : 1.0; const curH = currentHeights.get(node.id) || node.baseHeight; const newH = curH + (targetH - curH) * 0.28; currentHeights.set(node.id, newH); const curAlpha = currentOpacities.get(node.id) || 1.0; const newAlpha = curAlpha + (targetAlpha - curAlpha) * 0.28; currentOpacities.set(node.id, newAlpha); const cartX = (node.q + node.r / 2) * hexW; const cartY = node.r * (hexRadius * 1.5); const screenX = originX + (cartX - cartY) * cos30; const screenY = originY + (cartX + cartY) * sin30 * 0.72; const topY = screenY - newH; const baseY = screenY; ctx.save(); ctx.globalAlpha = newAlpha; const palette = TIER_COLORS[node.level]; // Left Extrusion Shadow Face ctx.fillStyle = palette.sideLeft; ctx.beginPath(); const leftX = screenX - (hexRadius * Math.sqrt(3)) / 2; const midX = screenX; const midTopY = topY + hexRadius * 0.35; ctx.moveTo(leftX, topY); ctx.lineTo(midX, midTopY); ctx.lineTo(midX, baseY + hexRadius * 0.35); ctx.lineTo(leftX, baseY); ctx.closePath(); ctx.fill(); // Right Extrusion Deep Shadow Face ctx.fillStyle = palette.sideRight; ctx.beginPath(); const rightX = screenX + (hexRadius * Math.sqrt(3)) / 2; ctx.moveTo(midX, midTopY); ctx.lineTo(rightX, topY); ctx.lineTo(rightX, baseY); ctx.lineTo(midX, baseY + hexRadius * 0.35); ctx.closePath(); ctx.fill(); // Hexagonal Top Cap const grad = ctx.createLinearGradient( screenX - hexRadius, topY - hexRadius * 0.5, screenX + hexRadius, topY + hexRadius * 0.5 ); if (isThisProductActive) { if (node.productIndex === 0) { grad.addColorStop(0, '#fef08a'); grad.addColorStop(1, '#eab308'); } else { grad.addColorStop(0, '#e879f9'); grad.addColorStop(1, '#a855f7'); } } else { grad.addColorStop(0, palette.capTop); grad.addColorStop(1, palette.capBottom); } ctx.fillStyle = grad; drawHexagon(screenX, topY, hexRadius); ctx.fill(); // Border highlighting ctx.strokeStyle = isThisProductActive ? '#ffffff' : node.level > 0 ? palette.border : 'rgba(255, 255, 255, 0.1)'; ctx.lineWidth = isThisProductActive ? 2.5 : 0.8; ctx.stroke(); // Permanent Visible Rank Badge on Top Cap for 1 to 25 const rankNum = node.productIndex + 1; ctx.font = `bold ${isThisProductActive ? '10px' : '8px'} monospace`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillStyle = isThisProductActive ? '#020617' : node.productIndex === 0 ? '#fbbf24' : '#e2e8f0'; ctx.fillText(String(rankNum), screenX, topY); ctx.restore(); // Active Tooltip HUD tracking if (isThisProductActive) { activeTooltipData = { visible: true, x: screenX, y: topY - 12, rank: node.productIndex + 1, title: node.productName, sales: node.salesCount, revenue: node.revenue, }; } } setTooltip(activeTooltipData); animId = requestAnimationFrame(render); }; render(); return () => { cancelAnimationFrame(animId); ro.disconnect(); canvas.removeEventListener('mousemove', onMouseMove); canvas.removeEventListener('mouseleave', onMouseLeave); }; }, [products]); return (
{/* Subtle Matrix Hex Background Overlay */}
{/* Floating 21st.dev Style Black HUD Tooltip */} {tooltip && tooltip.visible && (
#{tooltip.rank} {tooltip.title}
{tooltip.sales} sold {formatInr(tooltip.revenue)}
{/* Tooltip downward pointer arrow */}
)} {/* Header Info */}
Sales Volume Matrix Top {Math.min(products.length, 25)} Hexagons Active
{/* Bottom Footer: Metric Label on Left + 21st.dev Exact 5-Tier Color Legend on Right */}
Pillars 1 to {Math.min(products.length, 25)} show product rank {/* Exact 21st.dev Discrete Color Scale Legend: LESS [■][■][■][■][■] MORE */}
Less
More
); } export default PillarGridCanvas;