ifixkart-admin/components/dashboard/PillarGridCanvas.tsx

499 lines
16 KiB
TypeScript

'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<HTMLCanvasElement | null>(null);
const containerRef = useRef<HTMLDivElement | null>(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<number | null>(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<number, number>();
const currentOpacities = new Map<number, number>();
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 (
<div
ref={containerRef}
className={`relative w-full h-[230px] overflow-hidden rounded-t-xl bg-gradient-to-b from-slate-950 via-slate-900 to-slate-950 border-b border-border/60 select-none ${className}`}
>
<canvas ref={canvasRef} className="block w-full h-full cursor-pointer" />
{/* Subtle Matrix Hex Background Overlay */}
<div className="absolute inset-0 pointer-events-none bg-[radial-gradient(ellipse_at_center,_transparent_40%,_rgba(2,6,23,0.75)_95%)]" />
{/* Floating 21st.dev Style Black HUD Tooltip */}
{tooltip && tooltip.visible && (
<div
className="absolute z-30 pointer-events-none -translate-x-1/2 -translate-y-full transition-all duration-100"
style={{ left: `${tooltip.x}px`, top: `${tooltip.y}px` }}
>
<div className="px-3.5 py-1.5 rounded-lg bg-neutral-950/95 text-white border border-violet-500/80 shadow-[0_8px_20px_rgba(0,0,0,0.8)] backdrop-blur-md text-center min-w-[160px] max-w-[280px]">
<div className="flex items-center justify-center gap-1 text-[11px] font-semibold text-slate-100 truncate leading-snug">
<span className="text-amber-400 font-bold">#{tooltip.rank}</span>
<span className="truncate">{tooltip.title}</span>
</div>
<div className="flex items-center justify-center gap-2 mt-1 text-[10px]">
<span className="font-mono text-violet-300 font-bold bg-violet-950/70 px-1.5 py-0.5 rounded border border-violet-700/50">
{tooltip.sales} sold
</span>
<span className="text-emerald-400 font-medium">
{formatInr(tooltip.revenue)}
</span>
</div>
</div>
{/* Tooltip downward pointer arrow */}
<div className="w-0 h-0 border-x-4 border-x-transparent border-t-4 border-t-neutral-950 mx-auto" />
</div>
)}
{/* Header Info */}
<div className="absolute top-3 left-4 flex items-center gap-2">
<span className="text-[11px] font-semibold text-slate-200 tracking-wide">
Sales Volume Matrix
</span>
<span className="text-[10px] text-violet-400 font-mono font-semibold bg-violet-950/60 px-1.5 py-0.5 rounded border border-violet-800/40">
Top {Math.min(products.length, 25)} Hexagons Active
</span>
</div>
{/* Bottom Footer: Metric Label on Left + 21st.dev Exact 5-Tier Color Legend on Right */}
<div className="absolute bottom-2.5 left-4 right-4 flex items-center justify-between pointer-events-none">
<span className="text-[10px] text-slate-400 font-mono">
Pillars 1 to {Math.min(products.length, 25)} show product rank
</span>
{/* Exact 21st.dev Discrete Color Scale Legend: LESS [■][■][■][■][■] MORE */}
<div className="flex items-center gap-1.5 px-2 py-0.5 rounded-md bg-slate-950/80 border border-slate-800">
<span className="text-[9px] uppercase tracking-wider text-slate-400 font-semibold font-mono">
Less
</span>
<div className="flex items-center gap-1">
<span className="w-2.5 h-2.5 rounded-[2px] bg-slate-800 border border-slate-700" title="Baseline (21-25)" />
<span className="w-2.5 h-2.5 rounded-[2px] bg-[#3b0764] border border-[#581c87]" title="Low (15-20)" />
<span className="w-2.5 h-2.5 rounded-[2px] bg-[#6b21a8] border border-[#7e22ce]" title="Medium (8-14)" />
<span className="w-2.5 h-2.5 rounded-[2px] bg-[#9333ea] border border-[#a855f7]" title="High (3-7)" />
<span className="w-2.5 h-2.5 rounded-[2px] bg-[#c084fc] border border-[#e879f9]" title="Top Sellers (1-2)" />
</div>
<span className="text-[9px] uppercase tracking-wider text-slate-400 font-semibold font-mono">
More
</span>
</div>
</div>
</div>
);
}
export default PillarGridCanvas;