/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useEffect, useMemo } from 'react';
import {
  TrendingUp,
  TrendingDown,
  Download,
  Filter,
  ChevronDown,
  TrendingUp as TrendUp,
  TrendingDown as TrendDown,
  Equal as TrendFlat,
  ChevronLeft,
  ChevronRight,
  Info,
  Activity,
  Package,
  ShoppingBag,
  AlertTriangle,
  MapPin,
  Calendar,
  Trophy,
  Store,
  CheckCircle2
} from 'lucide-react';
import { LeaderboardNode } from '../types';
import {
  useFiestaLocationSummary,
  useFiestaOrderInsight,
  useFiestaStoresStock,
  useFiestaOrderSummary,
  useFiestaRevenueSummary,
  useFiestaTimeSeries,
  useFiestaStoresTimeSeries,
} from '../services/fiestaQueries';
import { FIESTA_TENANT_ID, FIESTA_PRIMARY_LOCATION_ID, num as fnum, str as fstr, ymd } from '../services/fiestaApi';
import { stockRowToProduct } from '../services/fiestaMappers';
import AwaitingApi from './AwaitingApi';
import SalesRevenueReport from './SalesRevenueReport';

interface ReportsViewProps {
  searchQuery: string;
  isCoimbatoreView: boolean;
  setIsCoimbatoreView: (val: boolean) => void;
  tenantId?: number;
}

const WEEK_KEYS = ['week1', 'week2', 'week3', 'week4', 'week5'];
const WEEK_LABELS = ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5'];

export default function ReportsView({ searchQuery, isCoimbatoreView, setIsCoimbatoreView, tenantId = FIESTA_TENANT_ID }: ReportsViewProps) {
  const [selectedTimeframe, setSelectedTimeframe] = useState('This Year (YTD)');
  const [selectedRegion, setSelectedRegion] = useState<'all' | 'coimbatore' | 'chennai' | 'bangalore'>('all');
  const [activeStoreId, setActiveStoreId] = useState<number | 'all'>('all');
  const [stockFilter, setStockFilter] = useState<'All' | 'Healthy' | 'Low Stock' | 'Critical'>('All');
  const [selectedCell, setSelectedCell] = useState<{ day: string; hour: string; val: number } | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [chartMetric, setChartMetric] = useState<'orders' | 'revenue' | 'cancelled' | 'skus'>('orders');
  const [chartTimeframe, setChartTimeframe] = useState<'day' | 'week' | 'month'>('week');
  const [expandedProductId, setExpandedProductId] = useState<string | null>(null);
  const [exportingFormat, setExportingFormat] = useState<'PDF' | 'CSV' | null>(null);
  const [exportProgress, setExportProgress] = useState(0);
  const [activeTab, setActiveTab] = useState<'overview' | 'sales_revenue'>('overview');

  // Dropdown open states
  const [showTimeframeDropdown, setShowTimeframeDropdown] = useState(false);
  const [showRegionDropdown, setShowRegionDropdown] = useState(false);

  // Sync state with parent component's CoimbatoreView flag
  useEffect(() => {
    if (isCoimbatoreView && selectedRegion !== 'coimbatore') {
      setSelectedRegion('coimbatore');
    } else if (!isCoimbatoreView && selectedRegion === 'coimbatore') {
      setSelectedRegion('all');
    }
  }, [isCoimbatoreView]);

  const handleRegionChange = (region: 'all' | 'coimbatore' | 'chennai' | 'bangalore') => {
    setSelectedRegion(region);
    if (region === 'coimbatore') {
      setIsCoimbatoreView(true);
    } else {
      setIsCoimbatoreView(false);
    }
  };

  // ── Live analytics (Fiesta) ───────────────────────────────────────────────
  const today = new Date();
  const yearStart = new Date(today.getFullYear(), 0, 1);
  const todate = ymd(today);

  // Previous equal-length window (same number of days immediately before the
  // current YTD window) so we can derive a REAL orders/cancelled delta.
  const periodDays = Math.round((today.getTime() - yearStart.getTime()) / 86400000);
  const prevEnd = new Date(yearStart.getTime() - 86400000);
  const prevStart = new Date(prevEnd.getTime() - periodDays * 86400000);

  // Helper matching local hubs belonging to Coimbatore
  const isCoimbatoreNode = (name: string) => {
    const coimbatoreZones = ['gandhipuram', 'rs puram', 'peelamedu', 'saravanampatti', 'coimbatore'];
    return coimbatoreZones.some(zone => name.toLowerCase().includes(zone));
  };

  const locSummaryQ = useFiestaLocationSummary(tenantId, ymd(yearStart), todate);
  
  const regionLocations = useMemo(() => {
    const rawLocations = [...(locSummaryQ.data ?? [])];
    if (selectedRegion === 'coimbatore') {
      return rawLocations.filter(r => isCoimbatoreNode(r.locationname || ''));
    }
    if (selectedRegion === 'chennai' || selectedRegion === 'bangalore') {
      return [];
    }
    return rawLocations;
  }, [locSummaryQ.data, selectedRegion]);

  const effectiveStoreId = activeTab === 'sales_revenue' ? activeStoreId : 'all';

  const filteredLocations = useMemo(() => {
    if (effectiveStoreId !== 'all') {
      return regionLocations.filter(r => Number(r.locationid) === effectiveStoreId);
    }
    return regionLocations;
  }, [regionLocations, effectiveStoreId]);

  const mappedLocations = useMemo(() => {
    return filteredLocations.map(l => ({ locationid: Number(l.locationid), locationname: l.locationname || '' }));
  }, [filteredLocations]);

  const summaryQ = useFiestaOrderSummary(tenantId, ymd(yearStart), todate);
  const prevSummaryQ = useFiestaOrderSummary(tenantId, ymd(prevStart), ymd(prevEnd));
  const insightQ = useFiestaOrderInsight(tenantId);
  const revSummaryQ = useFiestaRevenueSummary({ tenantid: tenantId, fromdate: ymd(yearStart), todate });
  const prevRevSummaryQ = useFiestaRevenueSummary({ tenantid: tenantId, fromdate: ymd(prevStart), todate: ymd(prevEnd) });

  const storesStock = useFiestaStoresStock(tenantId, mappedLocations);

  const s = summaryQ.data;
  const prevS = prevSummaryQ.data;
  const revS = revSummaryQ.data;
  const prevRevS = prevRevSummaryQ.data;

  // Real period-over-period % change (null when we can't compute it yet).
  const pctChange = (current: number, previous: number): number | null => {
    if (previous <= 0) return null;
    return ((current - previous) / previous) * 100;
  };

  const isGlobalView = selectedRegion === 'all' && effectiveStoreId === 'all';
  const ordersDelta = (s && prevS && isGlobalView) ? pctChange(s.total, prevS.total) : null;
  const cancelledDelta = (s && prevS && isGlobalView) ? pctChange(s.cancelled, prevS.cancelled) : null;
  const revenueDelta = (revS && prevRevS && isGlobalView) ? pctChange(revS.overallrevenue, prevRevS.overallrevenue) : null;

  const fmtDelta = (d: number) => `${d >= 0 ? '+' : ''}${d.toFixed(1)}%`;

  // Dynamic sparkline generator helper
  const getSparkPath = (values: number[], width: number, height: number) => {
    const max = Math.max(...values);
    const min = Math.min(...values);
    const range = max - min || 1;
    return values.map((val, idx) => {
      const x = (idx / (values.length - 1)) * width;
      const y = height - ((val - min) / range) * height;
      return `${idx === 0 ? 'M' : 'L'} ${x} ${y}`;
    }).join(' ');
  };

  // Tab thematic config
  const getChartColors = () => {
    switch (chartMetric) {
      case 'orders':
        return {
          stroke: 'url(#chart-indigo-grad)',
          fill: 'url(#chart-indigo-area)',
          hoverCircle: '#4f46e5',
          activeLine: '#6366f1',
          pointFill: '#818cf8'
        };
      case 'revenue':
        return {
          stroke: 'url(#chart-emerald-grad)',
          fill: 'url(#chart-emerald-area)',
          hoverCircle: '#059669',
          activeLine: '#10b981',
          pointFill: '#34d399'
        };
      case 'cancelled':
        return {
          stroke: 'url(#chart-rose-grad)',
          fill: 'url(#chart-rose-area)',
          hoverCircle: '#e11d48',
          activeLine: '#f43f5e',
          pointFill: '#fb7185'
        };
      case 'skus':
        return {
          stroke: 'url(#chart-sky-grad)',
          fill: 'url(#chart-sky-area)',
          hoverCircle: '#0284c7',
          activeLine: '#0ea5e9',
          pointFill: '#38bdf8'
        };
    }
  };
  const theme = getChartColors();

  let totalOrdersVal = 0;
  let deliveredVal = 0;
  let cancelledVal = 0;
  let grossRevenueVal = 0;
  let avgOrderVal = 0;
  let activeSkusVal = 0;

  if (isGlobalView) {
    totalOrdersVal = s?.total ?? 0;
    deliveredVal = s?.delivered ?? 0;
    cancelledVal = s?.cancelled ?? 0;
    grossRevenueVal = revS?.overallrevenue ?? 0;
    avgOrderVal = (s?.total && s.total > 0 && revS) ? revS.overallrevenue / s.total : 0;
  } else {
    const locIds = new Set(filteredLocations.map(l => Number(l.locationid)));
    
    (locSummaryQ.data ?? []).forEach(loc => {
      if (locIds.has(Number(loc.locationid))) {
        totalOrdersVal += Number(loc.total || 0);
        deliveredVal += Number(loc.delivered || 0);
        cancelledVal += Number(loc.cancelled || 0);
      }
    });

    // We do not have location-level revenue from the API yet.
    grossRevenueVal = 0;
    avgOrderVal = 0;
  }

  const skuSet = new Set<string>();
  storesStock.forEach(store => {
    if (store.rows) {
      store.rows.forEach(row => skuSet.add(`SKU-${row.productid}`));
    }
  });
  activeSkusVal = skuSet.size;

  // KPI Row Configuration. `awaiting` cards have no live value (rendered via
  // AwaitingApi). `trend` is only set where a REAL delta could be derived.
  const reportsKPIs = [
    {
      id: 'orders' as const,
      title: 'Orders',
      value: totalOrdersVal.toLocaleString('en-IN'),
      trend: ordersDelta !== null ? fmtDelta(ordersDelta) : null,
      status: `${deliveredVal.toLocaleString('en-IN')} filled`,
      isPositive: ordersDelta === null ? true : ordersDelta >= 0,
      spark: [30, 45, 35, 60, 55, 70, 65, 80],
      color: 'indigo',
      awaiting: false,
    },
    {
      id: 'revenue' as const,
      title: 'Revenue',
      value: `₹${grossRevenueVal.toLocaleString('en-IN')}`,
      trend: revenueDelta !== null ? fmtDelta(revenueDelta) : null,
      status: `₹${avgOrderVal.toLocaleString('en-IN')} avg. order`,
      isPositive: revenueDelta === null ? true : revenueDelta >= 0,
      spark: [20, 30, 25, 45, 40, 55, 50, 68],
      color: 'emerald',
      awaiting: !isGlobalView,
    },
    {
      id: 'cancelled' as const,
      title: 'Cancelled',
      value: cancelledVal.toLocaleString('en-IN'),
      // Lower cancellations is good, so a negative delta is "positive".
      trend: cancelledDelta !== null ? fmtDelta(cancelledDelta) : null,
      status: `${(s?.created ?? 0).toLocaleString('en-IN')} active`,
      isPositive: cancelledDelta === null ? false : cancelledDelta <= 0,
      spark: [15, 10, 8, 12, 5, 9, 4, 3],
      color: 'rose',
      awaiting: false,
    },
    {
      id: 'skus' as const,
      title: 'Active SKUs',
      value: activeSkusVal.toLocaleString('en-IN'),
      // SKU delta value itself was fabricated — show no trend chip.
      trend: null,
      status: `All verified`,
      isPositive: true,
      spark: [50, 50, 55, 60, 60, 68, 70, 72],
      color: 'sky',
      awaiting: false,
    },
  ];



  // Weekly order distribution per outlet — includes all stores.
  // Stores with no orders will simply show 0s across the board.
  const insightRows = (() => {
    return filteredLocations.map(loc => {
      const locName = loc.locationname || `Location ${loc.locationid}`;
      // Find the corresponding row from insightQ.data
      const insightData = (insightQ.data ?? []).find(
        r => (fstr(r.locationname) || `Location ${fstr(r.locationid)}`) === locName
      );
      
      return {
        name: locName,
        weeks: (insightData?.orderweeks ?? {}) as Record<string, unknown>,
      };
    });
  })();

  // Leaderboard — outlets ranked by current month's live orders.
  const leaderboard: LeaderboardNode[] = (() => {
    
    let rows = filteredLocations.map(loc => {
      const name = loc.locationname || `Location ${loc.locationid}`;
      // Find the corresponding insight row for this store
      const insightRow = insightRows.find(r => r.name === name);
      // Fallback to summing up the weekly mock data for the current 'month' value
      let total = 0;
      if (insightRow) {
        total = WEEK_KEYS.reduce((acc, k) => acc + fnum(insightRow.weeks[k]), 0);
      }
      
      return { name, total };
    });
    
    rows = rows.sort((a, b) => b.total - a.total);
    const max = rows.length ? rows[0].total : 0;
    return rows.map((r, i) => ({
      rank: String(i + 1).padStart(2, '0'),
      name: r.name,
      percentage: max > 0 ? Math.round((r.total / max) * 100) : 0,
      revenue: `${r.total.toLocaleString()} ord`,
    }));
  })();
  const currentLeaderboard = leaderboard;

  const heatmapMax = Math.max(
    1,
    ...insightRows.flatMap((row) => WEEK_KEYS.map((k) => fnum(row.weeks[k]))),
  );

  // Live product performance matrix.
  const activeRegionStock = storesStock;

  const liveProducts = useMemo(() => {
    const agg = new Map<string, any>();

    activeRegionStock.forEach(store => {
      if (store.rows) {
        store.rows.forEach(row => {
          const sku = `SKU-${row.productid}`;
          if (!agg.has(sku)) {
            agg.set(sku, { ...row, closing: 0, debit: 0, credit: 0, opening: 0 });
          }
          const existing = agg.get(sku);
          existing.closing += Number(row.closing || 0);
          existing.debit += Number(row.debit || 0);
          existing.credit += Number(row.credit || 0);
          existing.opening += Number(row.opening || 0);
        });
      }
    });

    return Array.from(agg.values()).map(stockRowToProduct);
  }, [activeRegionStock]);

  const filteredProducts = liveProducts.filter((prod) => {
    const matchesSearch =
      prod.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      prod.sku.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStock = stockFilter === 'All' ? true : prod.stockStatus === stockFilter;
    return matchesSearch && matchesStock;
  });

  const ITEMS_PER_PAGE = 10;
  const totalPages = Math.max(1, Math.ceil(filteredProducts.length / ITEMS_PER_PAGE));
  
  useEffect(() => {
    if (currentPage > totalPages) {
      setCurrentPage(1);
    }
  }, [totalPages, currentPage]);

  const paginatedProducts = filteredProducts.slice((currentPage - 1) * ITEMS_PER_PAGE, currentPage * ITEMS_PER_PAGE);

  // Derived Top Products
  const topOverallProducts = useMemo(() => {
    return [...liveProducts].sort((a, b) => b.revenue - a.revenue).slice(0, 3);
  }, [liveProducts]);

  const topProductsByStore = useMemo(() => {
    return activeRegionStock.map(store => {
      const prods = (store.rows || []).map(stockRowToProduct);
      return {
        locationname: store.locationname || `Location ${store.locationid}`,
        topProducts: prods.sort((a, b) => b.revenue - a.revenue).slice(0, 3)
      };
    }).filter(s => s.topProducts.length > 0);
  }, [activeRegionStock]);

  // Heatmap cell color gradient scale (multi-stop violet theme)
  const getHeatmapColorClass = (val: number) => {
    const ratio = val / heatmapMax;
    if (ratio < 0.15) {
      return 'bg-slate-50 text-zinc-400 border border-slate-100/50 hover:bg-slate-100 hover:text-zinc-650 hover:scale-105';
    }
    if (ratio <= 0.4) {
      return 'bg-purple-50 text-purple-700 border border-purple-100/50 hover:bg-purple-100 hover:scale-105';
    }
    if (ratio <= 0.7) {
      return 'bg-purple-200/50 text-purple-900 border border-purple-200/40 hover:bg-purple-200 hover:scale-105';
    }
    if (ratio <= 0.9) {
      return 'bg-[#7c3aed]/20 text-[#7c3aed] border border-[#7c3aed]/20 hover:bg-[#7c3aed]/30 hover:scale-105';
    }
    return 'bg-gradient-to-br from-[#7c3aed] to-[#662582] text-white border-none shadow-sm hover:scale-108 hover:shadow-md hover:brightness-110';
  };

  // Triggers progress bar simulated exporting
  const startExportSim = (format: 'PDF' | 'CSV') => {
    setExportingFormat(format);
    setExportProgress(0);
    const interval = setInterval(() => {
      setExportProgress(prev => {
        if (prev >= 100) {
          clearInterval(interval);
          setTimeout(() => {
            setExportingFormat(null);
            alert(`${format} ledger exported successfully.`);
          }, 450);
          return 100;
        }
        return prev + 10;
      });
    }, 120);
  };

  // Real chart data from API
  const tsGranularity = chartTimeframe === 'month' ? 'month' : 'day';
  const tsFromDate = useMemo(() => {
    const d = new Date();
    if (chartTimeframe === 'day') d.setDate(d.getDate() - 60); // last 60 days (covers May)
    else if (chartTimeframe === 'week') d.setDate(d.getDate() - 180); // last 6 months
    else d.setFullYear(d.getFullYear() - 1); // last year
    return ymd(d);
  }, [chartTimeframe]);

  const tsQ_all = useFiestaTimeSeries({
    tenantid: tenantId,
    granularity: tsGranularity,
    fromdate: tsFromDate,
    todate: todate,
  });

  const tsQ_stores = useFiestaStoresTimeSeries(
    tenantId,
    mappedLocations,
    tsGranularity,
    tsFromDate,
    todate
  );

  const chartData = useMemo(() => {
    const data = isGlobalView ? (tsQ_all.data || []) : (tsQ_stores.data || []);
    if (data.length === 0) return [{ label: 'No Data', value: 0 }];
    
    return data.map((d: any) => {
      let labelStr = d.label || d.date || d.createdat || "Unknown";
      if (tsGranularity === 'day' && labelStr !== "Unknown") {
        const dt = new Date(labelStr);
        const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
        labelStr = `${dt.getDate()} ${months[dt.getMonth()]}`;
      }
      
      let val = 0;
      if (chartMetric === 'skus') {
        val = Number(d.activeskus || d.skus || 0);
      } else if (chartMetric === 'orders') {
        val = Number(d.orders || d.totalorders || d.total || 0);
      } else if (chartMetric === 'revenue') {
        val = Number(d.revenue || d.grossrevenue || d.overallrevenue || 0);
      } else {
        val = Number(d[chartMetric]) || 0;
      }
      
      return {
        label: labelStr,
        value: val
      };
    });
  }, [tsQ_all.data, tsQ_stores.data, isGlobalView, chartMetric, tsGranularity]);

  const maxChartVal = useMemo(() => Math.max(...chartData.map(d => d.value), 1), [chartData]);

  return (
    <div className="space-y-lg animate-in fade-in duration-500 font-sans">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 relative z-20 -mt-2 pb-2 border-b border-slate-200/70">
        <div className="flex items-center gap-4">
          <button 
            onClick={() => setActiveTab('overview')} 
            className={`pb-1 text-sm font-bold border-b-2 transition-colors ${activeTab === 'overview' ? 'border-[#662582] text-[#662582]' : 'border-transparent text-slate-500 hover:text-slate-700'}`}
          >
            Overview
          </button>
          <button 
            onClick={() => setActiveTab('sales_revenue')} 
            className={`pb-1 text-sm font-bold border-b-2 transition-colors ${activeTab === 'sales_revenue' ? 'border-[#662582] text-[#662582]' : 'border-transparent text-slate-500 hover:text-slate-700'}`}
          >
            Sales & Revenue
          </button>
        </div>
        
        {/* Global Store Filter */}
        {activeTab === 'sales_revenue' && (
          <div className="flex items-center gap-2">
            <Store size={16} className="text-slate-500" />
            <select
              value={activeStoreId}
              onChange={(e) => setActiveStoreId(e.target.value === 'all' ? 'all' : Number(e.target.value))}
              className="text-sm font-bold outline-none rounded-lg px-3 py-1 border border-slate-200 bg-white text-slate-700 focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all cursor-pointer"
            >
              <option value="all">All Stores</option>
              {regionLocations.map(loc => (
                <option key={loc.locationid} value={Number(loc.locationid)}>
                  {loc.locationname || `Store ${loc.locationid}`}
                </option>
              ))}
            </select>
          </div>
        )}
      </div>

      {activeTab === 'overview' ? (
        <>
      {/* Primary KPI Row - 4 Key Tab buttons with Sparklines */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-gutter text-xs font-sans relative z-10">
        {reportsKPIs.map((kpi) => {
          const isActive = chartMetric === kpi.id;

          // Theme-based conditional classes
          let activeStyles = '';
          let strokeColor = '';
          let IconComponent = ShoppingBag;
          let iconBg = '';
          let iconTextColor = '';

          if (kpi.color === 'indigo') {
            activeStyles = isActive
              ? 'border-indigo-200 bg-white shadow-[0_8px_24px_rgba(99,102,241,0.12)] ring-1 ring-indigo-500/20 z-10'
              : 'border-slate-200/70 bg-white hover:border-indigo-200 hover:shadow-[0_8px_24px_rgba(99,102,241,0.06)] opacity-70 hover:opacity-100';
            strokeColor = '#6366f1';
            IconComponent = ShoppingBag;
            iconBg = 'bg-indigo-50 text-indigo-600 ring-1 ring-indigo-100';
          } else if (kpi.color === 'emerald') {
            activeStyles = isActive
              ? 'border-emerald-200 bg-white shadow-[0_8px_24px_rgba(16,185,129,0.12)] ring-1 ring-emerald-500/20 z-10'
              : 'border-slate-200/70 bg-white hover:border-emerald-200 hover:shadow-[0_8px_24px_rgba(16,185,129,0.06)] opacity-70 hover:opacity-100';
            strokeColor = '#10b981';
            IconComponent = Activity;
            iconBg = 'bg-emerald-50 text-emerald-600 ring-1 ring-emerald-100';
          } else if (kpi.color === 'rose') {
            activeStyles = isActive
              ? 'border-rose-200 bg-white shadow-[0_8px_24px_rgba(244,63,94,0.12)] ring-1 ring-rose-500/20 z-10'
              : 'border-slate-200/70 bg-white hover:border-rose-200 hover:shadow-[0_8px_24px_rgba(244,63,94,0.06)] opacity-70 hover:opacity-100';
            strokeColor = '#f43f5e';
            IconComponent = AlertTriangle;
            iconBg = 'bg-rose-50 text-rose-600 ring-1 ring-rose-100';
          } else {
            activeStyles = isActive
              ? 'border-sky-200 bg-white shadow-[0_8px_24px_rgba(14,165,233,0.12)] ring-1 ring-sky-500/20 z-10'
              : 'border-slate-200/70 bg-white hover:border-sky-200 hover:shadow-[0_8px_24px_rgba(14,165,233,0.06)] opacity-70 hover:opacity-100';
            strokeColor = '#0ea5e9';
            IconComponent = Package;
            iconBg = 'bg-sky-50 text-sky-600 ring-1 ring-sky-100';
          }

          return (
            <button
              key={kpi.id}
              onClick={() => setChartMetric(kpi.id)}
              className={`rounded-xl p-3 flex flex-col justify-between transition-all duration-300 text-left cursor-pointer outline-none relative group border ${activeStyles}`}
            >
              <div className="flex justify-between items-start w-full">
                <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">{kpi.title}</span>
                <div className="flex items-center gap-2">
                  {kpi.trend && (
                    <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded-md flex items-center gap-1 leading-none ${kpi.isPositive ? 'bg-emerald-50 text-emerald-700' : 'bg-rose-50 text-rose-700'}`}>
                      {kpi.isPositive ? <TrendingUp size={10} /> : <TrendingDown size={10} />}
                      {kpi.trend}
                    </span>
                  )}
                  <div className={`p-1.5 rounded-lg transition-transform group-hover:scale-110 ${iconBg.replace('ring-1', '').replace(/ring-\w+-100/, '').trim()}`}>
                    <IconComponent className="w-3.5 h-3.5" />
                  </div>
                </div>
              </div>
              
              <div className="mt-2 flex justify-between items-end w-full">
                <div>
                  {kpi.awaiting ? (
                    <div className="mt-1">
                      <AwaitingApi label="Revenue" api="[R1]" compact />
                    </div>
                  ) : (
                    <h3 className="text-lg font-extrabold tracking-tight font-mono text-slate-900">
                      {kpi.value}
                    </h3>
                  )}
                  <p className="text-[10px] text-slate-400 font-semibold mt-0.5">{kpi.status}</p>
                </div>
                
                <div className="w-12 h-6 select-none shrink-0 opacity-80 group-hover:opacity-100 transition-opacity">
                  <svg className="w-full h-full" viewBox="0 0 64 32">
                    <path
                      d={getSparkPath(kpi.spark, 64, 32)}
                      fill="none"
                      stroke={strokeColor}
                      strokeWidth="2.5"
                      strokeLinecap="round"
                    />
                  </svg>
                </div>
              </div>
            </button>
          );
        })}
      </div>



      {/* Bento split maps (Heatmap grid & Leaderboard) */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-gutter text-xs font-sans relative z-10">

        {/* Revenue Heatmap table - 8 Cols */}
        <div className="lg:col-span-8 bg-white border border-slate-200/70 overflow-hidden flex flex-col justify-between shadow-[0_1px_3px_rgba(16,24,40,0.05)] hover:-translate-y-1 hover:shadow-xl transition-all duration-300">

          <div className="bg-slate-50/50 border-b border-slate-100 px-5 py-4 flex justify-between items-center select-none">
            <span className="text-[11px] font-sans font-bold text-slate-800 uppercase tracking-widest block">
              Weekly Order Distribution
            </span>

            <div className="flex items-center gap-2 text-[10px] font-bold text-slate-400 uppercase tracking-tight">
              <span className="w-1.5 h-1.5 rounded-full bg-purple-600 animate-pulse"></span>
              <span>Busiest Week</span>
            </div>
          </div>

          <div className="p-5 flex-1 overflow-x-auto">
            {selectedCell && (
              <div className="mb-4 p-4 bg-purple-50 border border-purple-100 rounded-xl text-xs flex justify-between items-center animate-in slide-in-from-top-2 duration-300">
                <div className="flex items-center gap-2.5">
                  <div className="w-7 h-7 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 shrink-0">
                    <Info size={14} />
                  </div>
                  <span className="font-sans text-purple-900 font-semibold">
                    {selectedCell.day} · {selectedCell.hour} : {selectedCell.val} orders
                  </span>
                </div>
                <button
                  onClick={() => setSelectedCell(null)}
                  className="text-xs font-bold text-purple-700 hover:text-purple-900 cursor-pointer border-none bg-transparent hover:underline px-2"
                >
                  Dismiss
                </button>
              </div>
            )}

            {insightRows.length === 0 ? (
              <div className="py-12 text-center text-slate-400 text-xs">
                {insightQ.isLoading ? 'Loading weekly order distribution…' : 'No order insight available for this region.'}
              </div>
            ) : (
              <table className="w-full text-center border-collapse text-xs font-sans">
                <thead>
                  <tr>
                    <th className="p-2 text-[9px] font-bold text-slate-400 w-32 uppercase italic text-left pl-4">Outlet Name</th>
                    {WEEK_LABELS.map((w) => (
                      <th key={w} className="p-2 text-[10px] font-bold text-slate-800 border-b border-slate-100">
                        {w}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {insightRows.map((row, idx) => (
                    <tr key={idx}>
                      <td className="p-2 text-left font-bold text-slate-800 tracking-wide truncate max-w-[8rem] border-r border-slate-100 pl-4">
                        {row.name}
                      </td>
                      {WEEK_KEYS.map((key, mIdx) => {
                        const val = fnum(row.weeks[key]);
                        return (
                          <td key={key} className="p-1 border border-white">
                            <button
                              onClick={() => setSelectedCell({ day: row.name, hour: WEEK_LABELS[mIdx], val })}
                              className={`w-full py-2.5 rounded-lg font-semibold transition-all duration-200 cursor-pointer border-none ${getHeatmapColorClass(val)}`}
                            >
                              {val}
                            </button>
                          </td>
                        );
                      })}
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>

        {/* Leaderboard nodes bar list - 4 Cols */}
        <div className="lg:col-span-4 bg-white border border-slate-200/70 flex flex-col shadow-[0_1px_3px_rgba(16,24,40,0.05)] hover:-translate-y-1 hover:shadow-xl transition-all duration-300">
          <div className="bg-slate-50/50 border-b border-slate-100 px-5 py-4 select-none">
            <span className="text-[11px] font-sans font-bold text-slate-800 uppercase tracking-widest block">
              Top Performing Nodes
            </span>
          </div>

          <div className="p-5 flex-1 space-y-4 flex flex-col justify-center">
            {currentLeaderboard.length === 0 ? (
              <div className="text-center py-8 text-slate-400 font-medium">
                No active nodes in this region.
              </div>
            ) : (
              currentLeaderboard.map((node, index) => {
                let badgeStyle = '';
                let badgeContent: React.ReactNode = node.rank;

                if (index === 0) {
                  badgeStyle = 'bg-gradient-to-tr from-amber-300 via-yellow-400 to-amber-500 text-amber-950 shadow-md shadow-amber-500/20';
                  badgeContent = '🥇';
                } else if (index === 1) {
                  badgeStyle = 'bg-gradient-to-tr from-slate-200 via-slate-300 to-slate-400 text-slate-800 shadow-md shadow-slate-400/10';
                  badgeContent = '🥈';
                } else if (index === 2) {
                  badgeStyle = 'bg-gradient-to-tr from-amber-600 via-amber-700 to-orange-800 text-white shadow-md shadow-amber-800/20';
                  badgeContent = '🥉';
                } else {
                  badgeStyle = 'bg-slate-100 text-slate-500 border border-slate-200';
                }

                return (
                  <div key={node.rank} className="flex items-center gap-4 text-xs hover:bg-slate-50 p-2.5 rounded-xl transition-all duration-200 group">
                    {/* Ranking circle avatar */}
                    <div className={`w-9 h-9 rounded-full font-black flex items-center justify-center font-mono shrink-0 select-none text-sm transition-transform duration-300 group-hover:scale-105 ${badgeStyle}`}>
                      {badgeContent}
                    </div>

                    <div className="flex-1 min-w-0">
                      <div className="flex justify-between items-center font-medium mb-1.5">
                        <span className="text-slate-900 font-bold truncate max-w-[12rem] flex items-center gap-1.5">
                          {node.name}
                          {index < 3 && (
                            <span className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[8px] font-black uppercase tracking-widest bg-emerald-50 text-emerald-600 border border-emerald-100" title="Verified Top Performer">
                              <CheckCircle2 size={10} /> Verified
                            </span>
                          )}
                        </span>
                        <span className="text-purple-700 font-mono font-bold">{node.revenue}</span>
                      </div>

                      <div className="w-full bg-slate-100 h-1.5 rounded-full overflow-hidden">
                        <div
                          className="bg-gradient-to-r from-purple-500 to-purple-700 h-full rounded-full transition-all duration-500 ease-out origin-left"
                          style={{ width: `${node.percentage}%` }}
                        />
                      </div>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        </div>
      </div>

      {/* Top Products Section */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-5 text-xs font-sans relative z-10 mb-8">
        {/* Top 3 Overall Products - 4 Cols */}
        <div className="lg:col-span-4 bg-gradient-to-br from-white/95 to-purple-50/80 backdrop-blur-xl border border-purple-100/60 rounded-[1.5rem] flex flex-col shadow-xl shadow-purple-900/5 relative overflow-hidden">
          {/* Subtle glow background */}
          <div className="absolute top-0 right-0 w-32 h-32 bg-purple-400/20 rounded-full blur-[40px] -mr-10 -mt-10 pointer-events-none" />
          
          <div className="px-5 py-4 border-b border-purple-100/40 flex items-center justify-between relative z-10">
            <span className="text-[13px] font-sans font-black text-slate-800 tracking-tight flex items-center gap-2">
              <div className="w-6 h-6 rounded-full bg-amber-100 flex items-center justify-center shadow-inner">
                <Trophy className="text-amber-500 fill-amber-100" size={12} />
              </div>
              Overall Top 3
            </span>
          </div>

          <div className="p-5 flex-1 space-y-3 flex flex-col relative z-10">
            {topOverallProducts.length === 0 ? (
              <div className="text-center py-6 text-slate-400 font-medium text-[11px]">No sales data available.</div>
            ) : (
              topOverallProducts.map((prod, index) => {
                const isFirst = index === 0;
                return (
                  <div key={prod.id} className={`flex items-center gap-3 text-[11px] p-2.5 rounded-xl transition-all duration-300 group cursor-default relative overflow-hidden ${isFirst ? 'bg-gradient-to-r from-amber-50 to-orange-50/30 border border-amber-200/60 shadow-sm hover:shadow-[0_4px_15px_rgba(245,158,11,0.2)] hover:-translate-y-0.5' : 'bg-white border border-slate-100/80 shadow-sm hover:shadow-md hover:border-purple-200/60 hover:-translate-y-0.5'}`}>
                    
                    {/* Rank Badge */}
                    <div className={`w-7 h-7 rounded-full flex items-center justify-center shrink-0 shadow-inner ${isFirst ? 'bg-gradient-to-br from-amber-300 to-amber-500 text-amber-950 text-xs font-black ring-2 ring-amber-100 ring-offset-1' : index === 1 ? 'bg-gradient-to-br from-slate-200 to-slate-400 text-slate-800 text-[10px] font-bold' : 'bg-gradient-to-br from-orange-300 to-orange-500 text-orange-950 text-[10px] font-bold'}`}>
                      #{index + 1}
                    </div>

                    {/* Image */}
                    <div className={`w-10 h-10 rounded-lg overflow-hidden shrink-0 bg-white ${isFirst ? 'border-2 border-amber-300 shadow-sm' : 'border border-slate-200 shadow-sm'}`}>
                      <img src={prod.image} alt={prod.name} referrerPolicy="no-referrer" className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" />
                    </div>

                    <div className="flex-1 min-w-0 py-0.5">
                      <div className={`font-black truncate ${isFirst ? 'text-slate-900 text-sm' : 'text-slate-800 text-xs'}`}>{prod.name}</div>
                      <div className="flex items-center gap-1.5 mt-1">
                        <span className={`text-[10px] font-black tracking-wide ${isFirst ? 'text-amber-600 bg-amber-100/50 px-1 py-0.5 rounded' : 'text-purple-600 bg-purple-50 px-1 py-0.5 rounded'}`}>
                          ₹{prod.revenue.toLocaleString()} rev
                        </span>
                        <span className="w-1 h-1 rounded-full bg-slate-300" />
                        <span className="text-[9px] text-slate-500 font-bold uppercase tracking-wider">{prod.category}</span>
                      </div>
                    </div>
                    
                    {isFirst && (
                      <div className="absolute right-0 top-0 bottom-0 w-24 bg-gradient-to-l from-amber-100/40 to-transparent pointer-events-none" />
                    )}
                  </div>
                );
              })
            )}
          </div>
        </div>

        {/* Store-wise Top Products - 8 Cols */}
        <div className="lg:col-span-8 bg-white/95 backdrop-blur-xl border border-slate-200/80 rounded-[1.5rem] flex flex-col shadow-xl shadow-slate-200/20 relative overflow-hidden">
          <div className="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
            <span className="text-[13px] font-sans font-black text-slate-800 tracking-tight flex items-center gap-2">
              <div className="w-6 h-6 rounded-full bg-indigo-50 flex items-center justify-center shadow-inner">
                <Store className="text-indigo-500" size={12} />
              </div>
              Store-Wise Top Performers
            </span>
          </div>
          <div className="p-5 flex-1 overflow-x-auto scrollbar-thin scrollbar-thumb-slate-300 scrollbar-track-transparent pb-4">
            {topProductsByStore.length === 0 ? (
              <div className="text-center py-6 text-slate-400 font-medium text-[11px] flex items-center justify-center h-full">No store data available.</div>
            ) : (
              <div className="flex gap-4 min-w-max h-full items-stretch px-0.5 pb-1">
                {topProductsByStore.map(store => (
                  <div key={store.locationname} className="w-[230px] rounded-[1rem] bg-gradient-to-b from-slate-50/80 to-white border border-slate-200/80 p-4 shrink-0 shadow-sm hover:shadow-[0_4px_15px_rgba(99,102,241,0.08)] hover:-translate-y-1 hover:border-indigo-200 transition-all duration-300 group">
                    <div className="font-black text-slate-800 text-xs mb-4 pb-3 border-b border-slate-100 flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-indigo-500 shadow-[0_0_8px_rgba(99,102,241,0.6)] animate-pulse" />
                      <span className="truncate">{store.locationname}</span>
                    </div>

                    <div className="space-y-3">
                      {store.topProducts.map((prod, idx) => (
                        <div key={prod.id} className="flex items-center gap-2.5 group/item">
                          <div className={`w-5 h-5 rounded-md flex items-center justify-center shrink-0 font-black text-[9px] shadow-sm ${idx === 0 ? 'bg-amber-100 text-amber-600' : idx === 1 ? 'bg-slate-100 text-slate-600' : 'bg-orange-50 text-orange-600'}`}>
                            {idx + 1}
                          </div>
                          
                          <div className="w-9 h-9 rounded-lg border border-slate-200 bg-white shrink-0 overflow-hidden shadow-sm group-hover/item:shadow-md group-hover/item:border-indigo-200 transition-all">
                            <img src={prod.image} alt={prod.name} referrerPolicy="no-referrer" className="w-full h-full object-cover group-hover/item:scale-110 transition-transform duration-500" />
                          </div>

                          <div className="flex-1 min-w-0 flex flex-col justify-center">
                            <div className="font-bold text-slate-800 text-[11px] truncate leading-tight mb-0.5 group-hover/item:text-indigo-600 transition-colors">{prod.name}</div>
                            <div className="flex items-center">
                              <span className="text-[9px] text-indigo-700 bg-indigo-50 border border-indigo-100/50 px-1.5 py-0.5 rounded font-black tracking-wider">₹{prod.revenue.toLocaleString()} rev</span>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Detailed Performance Matrix table */}
      <div className="bg-white/70 backdrop-blur-md border border-[#e2e8f0] overflow-hidden shadow-sm relative z-10">


        {/* Table header with filters control */}
        <div className="bg-[#f8fafc] border-b border-[#e2e8f0] p-md flex flex-col sm:flex-row justify-between items-start sm:items-center gap-sm select-none">
          <div>
            <h3 className="font-sans font-bold text-sm text-[#0f172a] flex items-center gap-1.5">
              <Activity size={15} className="text-[#662582]" /> Product Performance Matrix
            </h3>
          </div>

          {/* Quick interactive filter pills */}
          <div className="flex gap-2 text-[10px] font-bold uppercase tracking-wider">
            {(['All', 'Healthy', 'Low Stock', 'Critical'] as const).map((filter) => (
              <button
                key={filter}
                onClick={() => setStockFilter(filter)}
                className={`px-3 py-1.5 rounded-lg cursor-pointer transition-colors border ${stockFilter === filter
                    ? 'bg-[#662582] text-white border-[#662582] shadow-sm'
                    : 'bg-white border-[#e2e8f0] text-zinc-655 hover:bg-zinc-55'
                  }`}
              >
                {filter}
              </button>
            ))}
          </div>
        </div>

        {/* Matrix Data table */}
        <div className="overflow-x-auto text-xs font-sans">
          <table className="w-full text-left">
            <thead className="bg-[#f8fafc] border-b border-[#e2e8f0] text-zinc-500 text-[9px] uppercase font-bold tracking-wider">
              <tr>
                <th className="w-10 px-md py-sm"></th>
                <th className="px-md py-sm">Product Name</th>
                <th className="px-md py-sm">SKU ID</th>
                <th className="px-md py-sm text-right">Units Sold</th>
                <th className="px-md py-sm text-right">Overall Revenue</th>
                <th className="px-md py-sm text-right">Stock Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#f1f5f9]">
              {paginatedProducts.length === 0 ? (
                <tr>
                  <td colSpan={6} className="text-center py-8 text-zinc-400 font-medium">
                    No matching items matching stock filter criteria.
                  </td>
                </tr>
              ) : (
                paginatedProducts.map((prod) => {
                  const isExpanded = expandedProductId === prod.id;
                  return (
                    <React.Fragment key={prod.id}>
                      <tr
                        onClick={() => setExpandedProductId(isExpanded ? null : prod.id)}
                        className={`hover:bg-[#f2f4f6]/40 transition-all font-medium text-zinc-700 cursor-pointer ${isExpanded ? 'bg-slate-50/50' : ''}`}
                      >
                        <td className="px-md py-md text-center text-zinc-400">
                          <ChevronDown
                            size={14}
                            className={`transition-transform duration-200 ${isExpanded ? 'rotate-180 text-purple-650' : 'text-zinc-400'}`}
                          />
                        </td>
                        <td className="px-md py-md flex items-center gap-sm">
                          <div className="w-8 h-8 rounded-lg shrink-0 border border-[#e2e8f0] overflow-hidden bg-zinc-50">
                            <img
                              src={prod.image}
                              alt={prod.name}
                              referrerPolicy="no-referrer"
                              className="w-full h-full object-cover"
                            />
                          </div>
                          <div>
                            <span className="font-bold text-[#0f172a] block">{prod.name}</span>
                            <span className="text-[9px] text-zinc-455 block font-semibold uppercase mt-0.5">{prod.category}</span>
                          </div>
                        </td>
                        <td className="px-md py-md font-mono text-zinc-500 font-semibold">
                          {prod.sku}
                        </td>
                        <td className="px-md py-md text-right font-mono text-zinc-655 font-bold">
                          {prod.unitsSold.toLocaleString()}
                        </td>
                        <td className="px-md py-md text-right font-mono text-zinc-800 font-extrabold">
                          ₹{prod.revenue.toLocaleString()}
                        </td>
                        <td className="px-md py-md text-right">
                          <span className={`px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wide inline-block ${prod.stockStatus === 'Healthy'
                              ? 'bg-emerald-50 text-emerald-600 border border-emerald-100'
                              : prod.stockStatus === 'Low Stock'
                                ? 'bg-amber-50 text-amber-600 border border-amber-100'
                                : 'bg-rose-50 text-rose-600 border border-rose-100'
                            }`}>
                            {prod.stockStatus}
                          </span>
                        </td>
                      </tr>

                      {/* Expanded details row */}
                      {isExpanded && (() => {
                        const storeBreakdown = activeRegionStock.map(store => {
                          if (!store.rows) return null;
                          const rawProdId = prod.sku.replace('SKU-', '');
                          const row = store.rows.find(r => 
                            r.productid?.toString() === rawProdId || 
                            r.productname === prod.name
                          );
                          if (!row) return null;

                          const closing = Number(row.closing || 0);
                          const debit = Math.max(0, Number(row.debit || 0));
                          const retail = Number(row.retailprice) || Number(row.productcost) || 0;
                          const rev = debit * retail;

                          let status = 'Healthy';
                          if (closing <= 0) status = 'Critical';
                          else if (closing < 25) status = 'Critical';
                          else if (closing < 120) status = 'Low Stock';

                          return {
                            locationname: store.locationname || `Store ${store.locationid}`,
                            closing,
                            debit,
                            revenue: rev,
                            status
                          };
                        }).filter(Boolean);

                        return (
                          <tr className="bg-slate-50/50 border-b border-[#e2e8f0]">
                            <td colSpan={6} className="p-0">
                              <div className="px-8 py-6 bg-white border-y border-slate-100 shadow-[inset_0_4px_6px_-4px_rgba(0,0,0,0.05)] animate-in slide-in-from-top-2 duration-300">
                                <h4 className="text-xs font-bold text-slate-800 mb-4 flex items-center gap-2">
                                  <div className="w-1.5 h-1.5 rounded-full bg-purple-600 animate-pulse"></div>
                                  Store-by-Store Breakdown
                                </h4>
                                
                                {storeBreakdown.length === 0 ? (
                                  <div className="text-center py-6 text-slate-400 text-xs font-medium">No store data available for this product.</div>
                                ) : (
                                  <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                                    {storeBreakdown.map((b: any, idx) => (
                                      <div key={idx} className="bg-white border border-slate-200/80 rounded-xl p-4 shadow-sm hover:shadow-md transition-shadow hover:border-purple-200 group">
                                        <div className="flex justify-between items-start mb-3">
                                          <div className="font-bold text-slate-800 text-xs group-hover:text-purple-700 transition-colors">{b.locationname}</div>
                                          <span className={`px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wide ${
                                              b.status === 'Healthy' ? 'bg-emerald-50 text-emerald-600 border border-emerald-100' :
                                              b.status === 'Low Stock' ? 'bg-amber-50 text-amber-600 border border-amber-100' :
                                              'bg-rose-50 text-rose-600 border border-rose-100'
                                            }`}>
                                            {b.status}
                                          </span>
                                        </div>
                                        <div className="flex items-center justify-between text-[11px]">
                                          <div>
                                            <div className="text-slate-400 font-semibold mb-0.5 uppercase tracking-wider text-[9px]">In Stock</div>
                                            <div className="font-mono font-bold text-slate-700">{b.closing.toLocaleString()}</div>
                                          </div>
                                          <div className="w-px h-6 bg-slate-100"></div>
                                          <div>
                                            <div className="text-slate-400 font-semibold mb-0.5 uppercase tracking-wider text-[9px]">Units Sold</div>
                                            <div className="font-mono font-bold text-purple-600">{b.debit.toLocaleString()}</div>
                                          </div>
                                          <div className="w-px h-6 bg-slate-100"></div>
                                          <div className="text-right">
                                            <div className="text-slate-400 font-semibold mb-0.5 uppercase tracking-wider text-[9px]">Revenue</div>
                                            <div className="font-mono font-bold text-emerald-600">₹{b.revenue.toLocaleString()}</div>
                                          </div>
                                        </div>
                                      </div>
                                    ))}
                                  </div>
                                )}
                              </div>
                            </td>
                          </tr>
                        );
                      })()}
                    </React.Fragment>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Matrix table pagination */}
        <div className="p-md bg-[#f8fafc] border-t border-[#e2e8f0] flex justify-between items-center text-[10px] text-zinc-500 font-bold font-sans select-none">
          <span>Showing {Math.min((currentPage - 1) * ITEMS_PER_PAGE + 1, filteredProducts.length)}-{Math.min(currentPage * ITEMS_PER_PAGE, filteredProducts.length)} of {filteredProducts.length} filtered products (from {liveProducts.length} total)</span>

          <div className="flex gap-xs">
            <button
              onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
              disabled={currentPage === 1}
              className={`w-8 h-8 border border-[#e2e8f0] rounded-lg flex items-center justify-center cursor-pointer transition-colors ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : 'hover:bg-white active:bg-[#f8fafc]'}`}
            >
              <ChevronLeft size={12} />
            </button>
            
            <div className="flex items-center px-2 font-bold text-[10px] text-zinc-600">
              Page {currentPage} of {totalPages}
            </div>

            <button
              onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
              disabled={currentPage === totalPages}
              className={`w-8 h-8 border border-[#e2e8f0] rounded-lg flex items-center justify-center cursor-pointer transition-colors ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : 'hover:bg-white active:bg-[#f8fafc]'}`}
            >
              <ChevronRight size={12} />
            </button>
          </div>
        </div>
      </div>

      {/* EXPORTING DIALOG MODAL */}
      {exportingFormat && (
        <div className="fixed inset-0 bg-[#0f172a]/35 backdrop-blur-sm z-[200] flex items-center justify-center p-md">
          <div className="bg-white border border-[#e2e8f0] rounded-2xl w-full max-w-[20rem] p-lg flex flex-col items-center justify-center shadow-2xl animate-in zoom-in-95 duration-200 text-center font-sans">
            <div className="w-12 h-12 rounded-full bg-purple-50 flex items-center justify-center text-[#581c87] mb-md animate-bounce">
              <Download size={20} />
            </div>
            <h4 className="font-bold text-slate-900 text-sm mb-xs">
              Generating {exportingFormat} Report
            </h4>
            <p className="text-[10px] text-zinc-405 font-semibold mb-lg">
              Compiling database records and SVG vector curves...
            </p>

            {/* Progress track */}
            <div className="w-full bg-slate-100 h-2 rounded-full overflow-hidden mb-sm relative">
              <div
                className="bg-gradient-to-r from-purple-500 to-[#581c87] h-full rounded-full transition-all duration-150"
                style={{ width: `${exportProgress}%` }}
              />
            </div>
            <span className="text-xs font-mono font-bold text-purple-750">{exportProgress}%</span>
          </div>
        </div>
      )}
        </>
      ) : (
        <SalesRevenueReport tenantId={tenantId} locationid={activeStoreId === 'all' ? undefined : Number(activeStoreId)} />
      )}
    </div>
  );
}
