Update GrowthAnalyticsChart.tsx

This commit is contained in:
g
2026-01-07 12:52:20 +00:00
parent ce1d2d3fe8
commit 3e27a4b1f2

View File

@@ -8,7 +8,6 @@ import {
CardHeader, CardHeader,
CardTitle, CardTitle,
} from "@/components/ui/card"; } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { import {
Select, Select,
SelectContent, SelectContent,
@@ -16,6 +15,7 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { import {
TrendingUp, TrendingUp,
@@ -24,9 +24,7 @@ import {
ShoppingCart, ShoppingCart,
DollarSign, DollarSign,
Package, Package,
ArrowUpRight, RefreshCw,
ArrowDownRight,
Minus,
} from "lucide-react"; } from "lucide-react";
import { import {
getGrowthAnalyticsWithStore, getGrowthAnalyticsWithStore,
@@ -34,144 +32,149 @@ import {
} from "@/lib/services/analytics-service"; } from "@/lib/services/analytics-service";
import { formatGBP } from "@/utils/format"; import { formatGBP } from "@/utils/format";
import { import {
LineChart, ComposedChart,
Bar,
Line, Line,
XAxis, XAxis,
YAxis, YAxis,
CartesianGrid, CartesianGrid,
Tooltip, Tooltip,
ResponsiveContainer, ResponsiveContainer,
AreaChart, PieChart,
Area, Pie,
BarChart, Cell,
Bar,
} from "recharts"; } from "recharts";
import { ChartSkeleton } from "./SkeletonLoaders";
interface GrowthAnalyticsChartProps { interface GrowthAnalyticsChartProps {
hideNumbers?: boolean; hideNumbers?: boolean;
} }
const SEGMENT_COLORS = {
new: "#3b82f6",
returning: "#10b981",
loyal: "#f59e0b",
vip: "#8b5cf6",
};
export default function GrowthAnalyticsChart({ export default function GrowthAnalyticsChart({
hideNumbers = false, hideNumbers = false,
}: GrowthAnalyticsChartProps) { }: GrowthAnalyticsChartProps) {
const [data, setData] = useState<GrowthAnalytics | null>(null); const [data, setData] = useState<GrowthAnalytics | null>(null);
const [isLoading, setIsLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [period, setPeriod] = useState("30"); const [period, setPeriod] = useState("30");
const [refreshing, setRefreshing] = useState(false);
const { toast } = useToast(); const { toast } = useToast();
const fetchData = async () => {
try {
setLoading(true);
const response = await getGrowthAnalyticsWithStore(period);
setData(response);
} catch (err) {
console.error("Error fetching growth data:", err);
toast({
title: "Error",
description: "Failed to load growth analytics data.",
variant: "destructive",
});
} finally {
setLoading(false);
setRefreshing(false);
}
};
useEffect(() => { useEffect(() => {
const fetchData = async () => {
try {
setIsLoading(true);
setError(null);
const response = await getGrowthAnalyticsWithStore(period);
setData(response);
} catch (err) {
console.error("Error fetching growth data:", err);
setError("Failed to load growth data");
toast({
title: "Error",
description: "Failed to load growth analytics data.",
variant: "destructive",
});
} finally {
setIsLoading(false);
}
};
fetchData(); fetchData();
}, [period, toast]); }, [period]);
const maskValue = (value: string): string => { const handleRefresh = () => {
if (!hideNumbers) return value; setRefreshing(true);
if (value.includes("£")) return "£***"; fetchData();
if (value.match(/^\d/) || value.match(/^-?\d/)) return "***";
return value;
}; };
const formatGrowthRate = (rate: number): string => { const formatCurrency = (value: number) => {
const prefix = rate > 0 ? "+" : ""; if (hideNumbers) return "£***";
return `${prefix}${rate.toFixed(1)}%`; return new Intl.NumberFormat("en-GB", {
style: "currency",
currency: "GBP",
maximumFractionDigits: 0,
}).format(value);
}; };
const getGrowthIcon = (rate: number) => { const formatNumber = (value: number) => {
if (rate > 0) return <ArrowUpRight className="h-4 w-4 text-green-500" />; if (hideNumbers) return "***";
if (rate < 0) return <ArrowDownRight className="h-4 w-4 text-red-500" />; return value.toLocaleString();
return <Minus className="h-4 w-4 text-muted-foreground" />;
}; };
const getGrowthColor = (rate: number): string => { const TrendIndicator = ({
if (rate > 0) return "text-green-600"; value,
if (rate < 0) return "text-red-600"; suffix = "%",
return "text-muted-foreground"; }: {
value: number;
suffix?: string;
}) => {
if (hideNumbers) return <span className="text-muted-foreground">***</span>;
const isPositive = value > 0;
const isNeutral = value === 0;
return (
<div
className={`flex items-center text-sm font-medium ${
isNeutral
? "text-muted-foreground"
: isPositive
? "text-green-600"
: "text-red-600"
}`}
>
{isPositive ? (
<TrendingUp className="h-4 w-4 mr-1" />
) : isNeutral ? null : (
<TrendingDown className="h-4 w-4 mr-1" />
)}
{isPositive ? "+" : ""}
{value.toFixed(1)}
{suffix}
</div>
);
}; };
const CustomTooltip = ({ active, payload, label }: any) => { const CustomTooltip = ({ active, payload }: any) => {
if (active && payload && payload.length) { if (active && payload?.length) {
const item = payload[0].payload; const item = payload[0].payload;
return ( return (
<div className="bg-background p-3 border border-border rounded-lg shadow-lg"> <div className="bg-background border border-border p-3 rounded-lg shadow-lg">
<p className="text-sm font-medium text-foreground mb-2">{item.date}</p> <p className="font-medium mb-2">{item.date}</p>
<div className="space-y-1"> <p className="text-sm text-blue-600">
<p className="text-sm text-blue-600"> Orders: {hideNumbers ? "***" : item.orders.toLocaleString()}
Revenue:{" "} </p>
<span className="font-semibold"> <p className="text-sm text-green-600">
{hideNumbers ? "£***" : formatGBP(item.revenue)} Revenue: {hideNumbers ? "£***" : formatGBP(item.revenue)}
</span> </p>
</p> <p className="text-sm text-purple-600">
<p className="text-sm text-green-600"> Customers: {hideNumbers ? "***" : item.uniqueCustomers}
Orders:{" "} </p>
<span className="font-semibold">
{hideNumbers ? "***" : item.orders}
</span>
</p>
<p className="text-sm text-purple-600">
Customers:{" "}
<span className="font-semibold">
{hideNumbers ? "***" : item.uniqueCustomers}
</span>
</p>
<p className="text-sm text-orange-600">
Avg Order:{" "}
<span className="font-semibold">
{hideNumbers ? "£***" : formatGBP(item.avgOrderValue)}
</span>
</p>
</div>
</div> </div>
); );
} }
return null; return null;
}; };
if (isLoading) { if (loading && !data) {
return ( return (
<ChartSkeleton <div className="flex justify-center my-8">
title="Growth Analytics" <div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"></div>
description="Track your store's growth over time" </div>
icon={TrendingUp}
showStats={true}
/>
); );
} }
if (error || !data) { if (!data) {
return ( return (
<Card> <Card>
<CardHeader> <CardContent className="pt-6">
<CardTitle className="flex items-center gap-2"> <div className="text-center text-muted-foreground">
<TrendingUp className="h-5 w-5" /> No growth data available
Growth Analytics
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-center py-8">
<TrendingUp className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
<p className="text-muted-foreground">
{error || "No growth data available"}
</p>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
@@ -180,343 +183,315 @@ export default function GrowthAnalyticsChart({
const { summary, customerInsights, timeSeries, topGrowingProducts } = data; const { summary, customerInsights, timeSeries, topGrowingProducts } = data;
// Prepare pie chart data
const segmentData = [
{
name: "New",
value: customerInsights.newCustomers,
color: SEGMENT_COLORS.new,
},
{
name: "Returning",
value: customerInsights.returningCustomers,
color: SEGMENT_COLORS.returning,
},
];
return ( return (
<div className="space-y-6"> <div className="space-y-6">
{/* Period Selector */} {/* Header */}
<Card> <div className="flex justify-between items-center">
<CardHeader> <div>
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4"> <h3 className="text-lg font-semibold">Store Growth</h3>
<div> <p className="text-sm text-muted-foreground">
<CardTitle className="flex items-center gap-2"> {data.period.start} to {data.period.end} ({data.period.granularity})
<TrendingUp className="h-5 w-5" /> </p>
Growth Analytics </div>
</CardTitle> <div className="flex items-center gap-2">
<CardDescription> <Select value={period} onValueChange={setPeriod}>
Compare performance against the previous period <SelectTrigger className="w-[140px]">
</CardDescription> <SelectValue />
</div> </SelectTrigger>
<Select value={period} onValueChange={setPeriod}> <SelectContent>
<SelectTrigger className="w-40"> <SelectItem value="7">Last 7 days</SelectItem>
<SelectValue /> <SelectItem value="30">Last 30 days</SelectItem>
</SelectTrigger> <SelectItem value="90">Last 90 days</SelectItem>
<SelectContent> <SelectItem value="365">Last year</SelectItem>
<SelectItem value="7">Last 7 days</SelectItem> <SelectItem value="all">All time</SelectItem>
<SelectItem value="30">Last 30 days</SelectItem> </SelectContent>
<SelectItem value="90">Last 90 days</SelectItem> </Select>
<SelectItem value="365">Last 365 days</SelectItem> <Button
<SelectItem value="all">All time</SelectItem> variant="outline"
</SelectContent> size="icon"
</Select> onClick={handleRefresh}
</div> disabled={refreshing}
</CardHeader> >
</Card> <RefreshCw
className={`h-4 w-4 ${refreshing ? "animate-spin" : ""}`}
/>
</Button>
</div>
</div>
{/* Growth Rate Cards */} {/* Summary Cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4"> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{/* Revenue Growth */} {/* Orders */}
<Card> <Card>
<CardContent className="pt-6"> <CardHeader className="pb-2">
<div className="flex items-center justify-between"> <div className="flex justify-between items-start">
<div className="flex items-center gap-2"> <CardTitle className="text-sm font-medium">Orders</CardTitle>
<DollarSign className="h-5 w-5 text-blue-500" /> <ShoppingCart className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground">
Revenue
</span>
</div>
<div className="flex items-center gap-1">
{getGrowthIcon(summary.growthRates.revenue)}
<span
className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.revenue)}`}
>
{hideNumbers ? "***" : formatGrowthRate(summary.growthRates.revenue)}
</span>
</div>
</div> </div>
<div className="mt-3"> </CardHeader>
<div className="text-2xl font-bold"> <CardContent>
{maskValue(formatGBP(summary.currentPeriod.revenue))} <div className="text-2xl font-bold">
</div> {formatNumber(summary.currentPeriod.orders)}
<div className="text-xs text-muted-foreground mt-1"> </div>
vs {maskValue(formatGBP(summary.previousPeriod.revenue))} previous <div className="flex items-center justify-between mt-1">
</div> <span className="text-xs text-muted-foreground">
vs {formatNumber(summary.previousPeriod.orders)} prev
</span>
<TrendIndicator value={summary.growthRates.orders} />
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
{/* Orders Growth */} {/* Revenue */}
<Card> <Card>
<CardContent className="pt-6"> <CardHeader className="pb-2">
<div className="flex items-center justify-between"> <div className="flex justify-between items-start">
<div className="flex items-center gap-2"> <CardTitle className="text-sm font-medium">Revenue</CardTitle>
<ShoppingCart className="h-5 w-5 text-green-500" /> <DollarSign className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground">
Orders
</span>
</div>
<div className="flex items-center gap-1">
{getGrowthIcon(summary.growthRates.orders)}
<span
className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.orders)}`}
>
{hideNumbers ? "***" : formatGrowthRate(summary.growthRates.orders)}
</span>
</div>
</div> </div>
<div className="mt-3"> </CardHeader>
<div className="text-2xl font-bold"> <CardContent>
{maskValue(summary.currentPeriod.orders.toString())} <div className="text-2xl font-bold text-green-600">
</div> {formatCurrency(summary.currentPeriod.revenue)}
<div className="text-xs text-muted-foreground mt-1"> </div>
vs {maskValue(summary.previousPeriod.orders.toString())} previous <div className="flex items-center justify-between mt-1">
</div> <span className="text-xs text-muted-foreground">
vs {formatCurrency(summary.previousPeriod.revenue)} prev
</span>
<TrendIndicator value={summary.growthRates.revenue} />
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
{/* AOV Growth */} {/* Avg Order Value */}
<Card> <Card>
<CardContent className="pt-6"> <CardHeader className="pb-2">
<div className="flex items-center justify-between"> <div className="flex justify-between items-start">
<div className="flex items-center gap-2"> <CardTitle className="text-sm font-medium">Avg Order</CardTitle>
<Package className="h-5 w-5 text-purple-500" /> <Package className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground">
Avg Order
</span>
</div>
<div className="flex items-center gap-1">
{getGrowthIcon(summary.growthRates.avgOrderValue)}
<span
className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.avgOrderValue)}`}
>
{hideNumbers ? "***" : formatGrowthRate(summary.growthRates.avgOrderValue)}
</span>
</div>
</div> </div>
<div className="mt-3"> </CardHeader>
<div className="text-2xl font-bold"> <CardContent>
{maskValue(formatGBP(summary.currentPeriod.avgOrderValue))} <div className="text-2xl font-bold">
</div> {formatCurrency(summary.currentPeriod.avgOrderValue)}
<div className="text-xs text-muted-foreground mt-1"> </div>
vs {maskValue(formatGBP(summary.previousPeriod.avgOrderValue))} previous <div className="flex items-center justify-between mt-1">
</div> <span className="text-xs text-muted-foreground">
vs {formatCurrency(summary.previousPeriod.avgOrderValue)} prev
</span>
<TrendIndicator value={summary.growthRates.avgOrderValue} />
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
{/* Customers Growth */} {/* Customers */}
<Card> <Card>
<CardContent className="pt-6"> <CardHeader className="pb-2">
<div className="flex items-center justify-between"> <div className="flex justify-between items-start">
<div className="flex items-center gap-2"> <CardTitle className="text-sm font-medium">Customers</CardTitle>
<Users className="h-5 w-5 text-orange-500" /> <Users className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground">
Customers
</span>
</div>
<div className="flex items-center gap-1">
{getGrowthIcon(summary.growthRates.customers)}
<span
className={`text-sm font-semibold ${getGrowthColor(summary.growthRates.customers)}`}
>
{hideNumbers ? "***" : formatGrowthRate(summary.growthRates.customers)}
</span>
</div>
</div> </div>
<div className="mt-3"> </CardHeader>
<div className="text-2xl font-bold"> <CardContent>
{maskValue(summary.currentPeriod.customers.toString())} <div className="text-2xl font-bold">
</div> {formatNumber(summary.currentPeriod.customers)}
<div className="text-xs text-muted-foreground mt-1"> </div>
vs {maskValue(summary.previousPeriod.customers.toString())} previous <div className="flex items-center justify-between mt-1">
</div> <span className="text-xs text-muted-foreground">
vs {formatNumber(summary.previousPeriod.customers)} prev
</span>
<TrendIndicator value={summary.growthRates.customers} />
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
{/* Revenue Trend Chart */} {/* Orders & Revenue Chart */}
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>Revenue & Orders Over Time</CardTitle> <CardTitle>Orders & Revenue Trend</CardTitle>
<CardDescription> <CardDescription>
{data.period.granularity === "daily" Performance over the selected time period
? "Daily"
: data.period.granularity === "weekly"
? "Weekly"
: "Monthly"}{" "}
breakdown from {data.period.start} to {data.period.end}
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{timeSeries.length === 0 ? ( {loading || refreshing ? (
<div className="text-center py-8"> <div className="flex items-center justify-center h-80">
<TrendingUp className="h-12 w-12 mx-auto text-muted-foreground mb-4" /> <div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"></div>
<p className="text-muted-foreground">
No data available for this period
</p>
</div> </div>
) : ( ) : timeSeries.length > 0 ? (
<div className="h-72"> <div className="h-80">
<ResponsiveContainer width="100%" height="100%"> <ResponsiveContainer width="100%" height="100%">
<AreaChart <ComposedChart
data={timeSeries} data={timeSeries}
margin={{ top: 10, right: 30, left: 0, bottom: 0 }} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
> >
<defs>
<linearGradient id="colorRevenue" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#2563eb" stopOpacity={0.3} />
<stop offset="95%" stopColor="#2563eb" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" /> <CartesianGrid strokeDasharray="3 3" />
<XAxis <XAxis
dataKey="date" dataKey="date"
tick={{ fontSize: 11 }} tick={{ fontSize: 12 }}
angle={-45} angle={-45}
textAnchor="end" textAnchor="end"
height={60} height={60}
/> />
<YAxis <YAxis
yAxisId="left" yAxisId="left"
tick={{ fontSize: 11 }} tick={{ fontSize: 12 }}
tickFormatter={(value) => tickFormatter={(v) => (hideNumbers ? "***" : v)}
hideNumbers ? "***" : `£${(value / 1000).toFixed(0)}k`
}
/> />
<YAxis <YAxis
yAxisId="right" yAxisId="right"
orientation="right" orientation="right"
tick={{ fontSize: 11 }} tick={{ fontSize: 12 }}
tickFormatter={(value) => (hideNumbers ? "***" : value)} tickFormatter={(v) =>
hideNumbers ? "***" : `£${(v / 1000).toFixed(0)}k`
}
/> />
<Tooltip content={<CustomTooltip />} /> <Tooltip content={<CustomTooltip />} />
<Area <Bar
yAxisId="left" yAxisId="left"
type="monotone" dataKey="orders"
dataKey="revenue" fill="#3b82f6"
stroke="#2563eb" radius={[4, 4, 0, 0]}
strokeWidth={2} name="Orders"
fill="url(#colorRevenue)"
/> />
<Line <Line
yAxisId="right" yAxisId="right"
type="monotone" type="monotone"
dataKey="orders" dataKey="revenue"
stroke="#22c55e" stroke="#10b981"
strokeWidth={2} strokeWidth={3}
dot={false} dot={{ fill: "#10b981", r: 4 }}
name="Revenue"
/> />
</AreaChart> </ComposedChart>
</ResponsiveContainer> </ResponsiveContainer>
</div> </div>
) : (
<div className="flex items-center justify-center h-80 text-muted-foreground">
No data available for the selected period
</div>
)} )}
</CardContent> </CardContent>
</Card> </Card>
{/* Customer Insights */} {/* Customer Breakdown & Top Products */}
<Card> <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<CardHeader> {/* Customer Segments */}
<CardTitle className="flex items-center gap-2">
<Users className="h-5 w-5" />
Customer Insights
</CardTitle>
<CardDescription>
New vs returning customers and engagement metrics
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
<div className="text-center p-3 bg-muted/50 rounded-lg">
<div className="text-2xl font-bold text-green-600">
{maskValue(customerInsights.newCustomers.toString())}
</div>
<div className="text-xs text-muted-foreground">New Customers</div>
</div>
<div className="text-center p-3 bg-muted/50 rounded-lg">
<div className="text-2xl font-bold text-blue-600">
{maskValue(customerInsights.returningCustomers.toString())}
</div>
<div className="text-xs text-muted-foreground">Returning</div>
</div>
<div className="text-center p-3 bg-muted/50 rounded-lg">
<div className="text-2xl font-bold text-purple-600">
{maskValue(customerInsights.totalCustomers.toString())}
</div>
<div className="text-xs text-muted-foreground">Total</div>
</div>
<div className="text-center p-3 bg-muted/50 rounded-lg">
<div className="text-2xl font-bold text-orange-600">
{hideNumbers ? "***%" : `${customerInsights.newCustomerRate}%`}
</div>
<div className="text-xs text-muted-foreground">New Rate</div>
</div>
<div className="text-center p-3 bg-muted/50 rounded-lg">
<div className="text-2xl font-bold text-pink-600">
{maskValue(customerInsights.avgOrdersPerCustomer.toString())}
</div>
<div className="text-xs text-muted-foreground">Avg Orders</div>
</div>
<div className="text-center p-3 bg-muted/50 rounded-lg">
<div className="text-2xl font-bold text-teal-600">
{maskValue(formatGBP(customerInsights.avgSpentPerCustomer))}
</div>
<div className="text-xs text-muted-foreground">Avg Spent</div>
</div>
</div>
</CardContent>
</Card>
{/* Top Growing Products */}
{topGrowingProducts.length > 0 && (
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle className="flex items-center gap-2"> <CardTitle>Customer Breakdown</CardTitle>
<Package className="h-5 w-5" /> <CardDescription>New vs returning customers</CardDescription>
Top Growing Products
</CardTitle>
<CardDescription>
Products with the highest revenue growth compared to previous period
</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="space-y-3"> <div className="grid grid-cols-3 gap-4 mb-4">
{topGrowingProducts.slice(0, 5).map((product, index) => ( <div className="bg-muted/50 p-3 rounded-lg text-center">
<div <div className="text-2xl font-bold text-blue-600">
key={product.productId} {formatNumber(customerInsights.newCustomers)}
className="flex items-center justify-between p-3 bg-muted/30 rounded-lg"
>
<div className="flex items-center gap-3">
<div className="flex items-center justify-center w-8 h-8 rounded-full bg-primary/10 text-primary text-sm font-bold">
{index + 1}
</div>
<div>
<div className="font-medium">{product.productName}</div>
<div className="text-xs text-muted-foreground">
{maskValue(formatGBP(product.currentPeriodRevenue))} revenue
{" · "}
{maskValue(product.currentPeriodQuantity.toString())} sold
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Badge
variant={product.revenueGrowth >= 0 ? "default" : "destructive"}
className="flex items-center gap-1"
>
{product.revenueGrowth >= 0 ? (
<TrendingUp className="h-3 w-3" />
) : (
<TrendingDown className="h-3 w-3" />
)}
{hideNumbers ? "***" : formatGrowthRate(product.revenueGrowth)}
</Badge>
</div>
</div> </div>
))} <div className="text-xs text-muted-foreground">New</div>
</div>
<div className="bg-muted/50 p-3 rounded-lg text-center">
<div className="text-2xl font-bold text-green-600">
{formatNumber(customerInsights.returningCustomers)}
</div>
<div className="text-xs text-muted-foreground">Returning</div>
</div>
<div className="bg-muted/50 p-3 rounded-lg text-center">
<div className="text-2xl font-bold">
{formatNumber(customerInsights.totalCustomers)}
</div>
<div className="text-xs text-muted-foreground">Total</div>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="bg-muted/50 p-3 rounded-lg text-center">
<div className="text-lg font-bold">
{hideNumbers
? "***"
: customerInsights.avgOrdersPerCustomer.toFixed(1)}
</div>
<div className="text-xs text-muted-foreground">
Avg Orders/Customer
</div>
</div>
<div className="bg-muted/50 p-3 rounded-lg text-center">
<div className="text-lg font-bold">
{formatCurrency(customerInsights.avgSpentPerCustomer)}
</div>
<div className="text-xs text-muted-foreground">
Avg Spent/Customer
</div>
</div>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
)}
{/* Top Growing Products */}
<Card>
<CardHeader>
<CardTitle>Top Growing Products</CardTitle>
<CardDescription>
Highest revenue growth vs previous period
</CardDescription>
</CardHeader>
<CardContent>
{topGrowingProducts.length > 0 ? (
<div className="space-y-2">
{topGrowingProducts.slice(0, 5).map((product, index) => (
<div
key={product.productId}
className="flex items-center justify-between p-2 bg-muted/30 rounded-lg"
>
<div className="flex items-center gap-2">
<div className="flex items-center justify-center w-6 h-6 rounded-full bg-primary/10 text-primary text-xs font-semibold">
{index + 1}
</div>
<div>
<div className="text-sm font-medium truncate max-w-[150px]">
{product.productName}
</div>
<div className="text-xs text-muted-foreground">
{formatCurrency(product.currentPeriodRevenue)}
</div>
</div>
</div>
<div
className={`text-sm font-semibold ${
product.revenueGrowth >= 0
? "text-green-600"
: "text-red-600"
}`}
>
{hideNumbers
? "***"
: `${product.revenueGrowth >= 0 ? "+" : ""}${product.revenueGrowth.toFixed(0)}%`}
</div>
</div>
))}
</div>
) : (
<div className="text-center text-muted-foreground py-8">
No product growth data available
</div>
)}
</CardContent>
</Card>
</div>
</div> </div>
); );
} }