import React, { useState, useEffect } from 'react';
import { 
  BarChart2, Users, CreditCard, Activity, Package, Settings, Monitor, MessageCircle, AlertCircle, ShoppingCart, Truck, Target, PlusCircle, CheckCircle, Smartphone, Tag, FileText, Menu, ExternalLink, ChevronDown, Download, Lock, MapPin, MousePointerClick, TrendingUp as TrendingUpIcon, TrendingDown as TrendingDownIcon, Search, Facebook, ShoppingBag, TrendingUp, Calendar, XCircle, Eye as EyeIcon, Eye, Filter, Edit3, Trash2, Shield, Heart, ClipboardList 
} from 'lucide-react';
import { Order, Product, SiteSettings, User } from '../../types';
import AdminBannerCarousel from '../AdminBannerCarousel';

interface DashboardOverviewProps {
  orders: Order[];
  leads: any[];
  products: Product[];
  currentUser: User | null;
  settings: SiteSettings;
  activeTab: string;
  adminBanners: any[];
  testimonials: any[];
  todayPageViews: number;
  initiatedCheckouts: number;
  analyticsPeriod: string;
  setAnalyticsPeriod: (p: any) => void;
  analyticsStart: string;
  setAnalyticsStart: (d: string) => void;
  analyticsEnd: string;
  setAnalyticsEnd: (d: string) => void;
}

export default function DashboardOverview({ orders, leads, products, currentUser, settings, activeTab, adminBanners, testimonials, todayPageViews, initiatedCheckouts, analyticsPeriod, setAnalyticsPeriod, analyticsStart, setAnalyticsStart, analyticsEnd, setAnalyticsEnd }: DashboardOverviewProps) {
  const [pageViews, setPageViews] = useState<number>(0);
  const [contentViews, setContentViews] = useState<number>(0);
  const [totalSales, setTotalSales] = useState<number>(0);
  const [recentSalesChart, setRecentSalesChart] = useState<any[]>([]);
  const [topProducts, setTopProducts] = useState<any[]>([]);
  const [deliveryStats, setDeliveryStats] = useState<any[]>([]);
  const [trafficSources, setTrafficSources] = useState<any[]>([]);

  const totalOrders = orders.length;
  const pendingOrders = orders.filter(o => o.status === 'pending').length;
  const completedOrders = orders.filter(o => o.status === 'completed').length;
  const totalLeads = leads?.length || 0;
  const totalInitiatedCheckouts = leads?.filter(l => l.status === 'initiated_checkout').length || 0;

  const validOrders = orders.filter(o => o.status !== 'cancelled');
  const confirmedOrderValue = validOrders.reduce((sum, o) => sum + (Number(o.total) || 0), 0);
  const estimatedGrossProfit = confirmedOrderValue;

  // ── Financial Breakdown Calculations ──────────────────────────────────────────
  const readFbCache = React.useCallback(() => {
    try {
      const cache = localStorage.getItem('fb_ads_cache');
      if (cache) {
        const d = JSON.parse(cache);
        return {
          spend: d.spend_bdt || 0,
          spend_usd: d.spend_usd || 0,
          cpa: d.purchases > 0 ? Math.round((d.spend_bdt || 0) / d.purchases) : 0,
          purchases: d.purchases || 0,
          roas: d.roas || 0,
          clicks: d.clicks || 0,
          impressions: d.impressions || 0,
          ctr: d.ctr || 0,
          cpc: d.cpc || 0,
          rate: d.rate || 110,
          preset: d.preset || 'this_month',
          loading: false,
          connected: !!(localStorage.getItem('fb_ads_token')),
          updatedAt: d.updatedAt || null,
        };
      }
    } catch { }
    return { spend: 0, spend_usd: 0, cpa: 0, purchases: 0, roas: 0, clicks: 0, impressions: 0, ctr: 0, cpc: 0, rate: 110, preset: 'this_month', loading: false, connected: !!(localStorage.getItem('fb_ads_token')), updatedAt: null };
  }, []);

  const [fbAdsData, setFbAdsData] = useState(readFbCache);

  useEffect(() => {
    const refresh = () => setFbAdsData(readFbCache());
    refresh();
    window.addEventListener('fb_ads_cache_updated', refresh);
    return () => window.removeEventListener('fb_ads_cache_updated', refresh);
  }, [readFbCache]);

  const totalCost = React.useMemo(() => {
    let cost = 0;
    validOrders.forEach(o => {
      o.items?.forEach((item: any) => {
        const pId = item.productId || item.product_id;
        const p = products.find(prod => String(prod.id) === String(pId));
        if (p && p.priceConfigs) {
          const size = item.size || 'Size 1';
          const priceConfig = p.priceConfigs[size] || Object.values(p.priceConfigs)[0];
          if (priceConfig && priceConfig.mainBalance) {
            cost += Number(priceConfig.mainBalance) * Number(item.quantity || item.qty || 1);
          }
        }
      });
    });
    return cost;
  }, [validOrders, products]);

  const totalDeliveryCharges = React.useMemo(() => {
    return validOrders.reduce((acc, o) => acc + Number(o.deliveryCharge || (o as any).delivery_charge || 0), 0);
  }, [validOrders]);

  const confirmedOrdersCount = validOrders.length;
  
  const fbAdsCostBDT = fbAdsData.spend || 0;
  const totalExpenses = fbAdsCostBDT + totalDeliveryCharges;
  const fbSalesRatio = confirmedOrdersCount > 0 && fbAdsData.purchases > 0
    ? Math.min(100, (fbAdsData.purchases / confirmedOrdersCount) * 100)
    : 0;

  const cancelledOrders = orders.filter(o => o.status === 'cancelled').length;

  const grossProfit = confirmedOrderValue - totalCost;
  const netProfit = grossProfit - totalExpenses;
  const grossMargin = confirmedOrderValue > 0 ? (grossProfit / confirmedOrderValue) * 100 : 0;
  const profitMargin = confirmedOrderValue > 0 ? (netProfit / confirmedOrderValue) * 100 : 0;
  const isProfit = netProfit >= 0;

  const salesData = recentSalesChart.length > 0 ? recentSalesChart : [
    { name: 'Mon', revenue: 0, orders: 0 },
    { name: 'Tue', revenue: 0, orders: 0 },
    { name: 'Wed', revenue: 0, orders: 0 },
    { name: 'Thu', revenue: 0, orders: 0 },
    { name: 'Fri', revenue: 0, orders: 0 },
    { name: 'Sat', revenue: 0, orders: 0 },
    { name: 'Sun', revenue: 0, orders: 0 }
  ];

  const fetchAnalytics = async () => {
    try {
      const token = localStorage.getItem('tenant_token');
      if (!token) return;
      const res = await fetch('/api/analytics?action=summary', {
        headers: { 'X-Tenant-Token': token }
      });
      const data = await res.json();
      if (data.success) {
        const sum = data.summary || data.data || {};
        setPageViews(sum.page_views || 0);
        setContentViews(sum.product_views || sum.content_views || 0);
        setTotalSales(sum.order_completes || sum.total_sales || 0);
        setRecentSalesChart(data.data?.recent_sales_chart || []);
        setTopProducts(data.top_products || data.data?.top_products || []);
        setDeliveryStats(data.data?.delivery_stats || []);
        setTrafficSources(data.data?.traffic_sources || []);
      }
    } catch (e) {
      console.error('Failed to fetch analytics', e);
    }
  };

  useEffect(() => {
    if (activeTab === 'dashboard') {
      fetchAnalytics();
    }
  }, [activeTab]);

  return (
    <>
                <div className="space-y-5">
                  <AdminBannerCarousel banners={adminBanners} />

                  {/* ── HERO WELCOME BANNER ── */}
                  <div className="rounded-2xl bg-white border border-slate-200 shadow-sm p-6 flex flex-col md:flex-row md:items-center justify-between gap-5">
                    <div>
                      <div className="flex items-center gap-2 mb-2">
                        <span className="inline-block w-2 h-5 rounded-full bg-indigo-500"></span>
                        <p className="text-[11px] font-black uppercase tracking-widest text-indigo-600">Live Dashboard</p>
                      </div>
                      <h2 className="text-2xl md:text-3xl font-black text-slate-800 leading-tight">
                        স্বাগতম, <span className="text-indigo-600">{currentUser?.name?.split(' ')[0] || 'Admin'}</span> 👋
                      </h2>
                      <p className="text-slate-500 text-sm mt-1.5 max-w-md">আপনার স্টোরের সম্পূর্ণ আর্থিক চিত্র — রেভিনিউ, খরচ এবং মুনাফা একনজরে।</p>
                      <div className="flex flex-wrap gap-2 mt-3">
                        {[
                          { label: `${orders.filter(o => o.status === 'pending').length} Pending`, bg: 'bg-amber-50', text: 'text-amber-700', border: 'border-amber-200' },
                          { label: `${completedOrders} Completed`, bg: 'bg-green-50', text: 'text-green-700', border: 'border-green-200' },
                          { label: `${products.length} Products`, bg: 'bg-blue-50', text: 'text-blue-700', border: 'border-blue-200' },
                        ].map(p => (
                          <span key={p.label} className={`px-3 py-1 rounded-full text-[11px] font-bold border ${p.bg} ${p.text} ${p.border}`}>{p.label}</span>
                        ))}
                      </div>
                    </div>
                    <div className="flex flex-row md:flex-col gap-3">
                      {[
                        { label: 'Pending', value: orders.filter(o => o.status === 'pending').length, icon: '⏳', bg: 'bg-amber-50', text: 'text-amber-700', border: 'border-amber-200' },
                        { label: 'Revenue', value: `৳${confirmedOrderValue.toLocaleString()}`, icon: '💰', bg: 'bg-green-50', text: 'text-green-700', border: 'border-green-200' },
                        { label: isProfit ? 'Net Profit' : 'Net Loss', value: `${isProfit ? '+' : '-'}৳${Math.abs(netProfit).toLocaleString()}`, icon: isProfit ? '📈' : '📉', bg: isProfit ? 'bg-emerald-50' : 'bg-red-50', text: isProfit ? 'text-emerald-700' : 'text-red-700', border: isProfit ? 'border-emerald-200' : 'border-red-200' },
                      ].map((s, i) => (
                        <div key={i} className={`flex items-center gap-3 px-4 py-2.5 rounded-xl border ${s.bg} ${s.border}`}>
                          <span className="text-base">{s.icon}</span>
                          <div>
                            <p className="text-[10px] font-bold uppercase tracking-wide text-slate-500 leading-none">{s.label}</p>
                            <p className={`text-base font-black leading-tight mt-0.5 ${s.text}`}>{s.value}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* ── REDESIGNED STAT CARDS ── */}
                  <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6">
                    {[
                      { label: 'Total Orders', value: totalOrders, sub: `${pendingOrders} pending`, icon: ClipboardList, color: 'text-blue-600', bg: 'bg-blue-50', border: 'border-blue-100', shadow: 'shadow-blue-500/10' },
                      { label: 'Incomplete', value: totalLeads, sub: `${totalInitiatedCheckouts} initiated`, icon: Users, color: 'text-purple-600', bg: 'bg-purple-50', border: 'border-purple-100', shadow: 'shadow-purple-500/10' },
                      { label: 'Revenue', value: `৳${confirmedOrderValue.toLocaleString()}`, sub: `${grossMargin.toFixed(1)}% gross margin`, icon: CreditCard, color: 'text-emerald-600', bg: 'bg-emerald-50', border: 'border-emerald-100', shadow: 'shadow-emerald-500/10' },
                      { label: 'Net Margin', value: `${profitMargin.toFixed(1)}%`, sub: `৳${Math.abs(netProfit).toLocaleString()} ${isProfit ? 'profit' : 'loss'}`, icon: isProfit ? TrendingUpIcon : TrendingDownIcon, color: isProfit ? 'text-emerald-600' : 'text-red-600', bg: isProfit ? 'bg-emerald-50' : 'bg-red-50', border: isProfit ? 'border-emerald-100' : 'border-red-100', shadow: isProfit ? 'shadow-emerald-500/10' : 'shadow-red-500/10' },
                    ].map((s, i) => (
                      <div key={i} className={`bg-white rounded-3xl p-6 border ${s.border} hover:shadow-xl hover:-translate-y-1 transition-all duration-300 cursor-default shadow-sm ${s.shadow}`}>
                        <div className={`w-12 h-12 rounded-2xl flex items-center justify-center mb-4 ${s.bg} ${s.color}`}>
                          <s.icon size={22} />
                        </div>
                        <p className="text-3xl font-black text-slate-800 tracking-tight leading-none mb-2">{s.value}</p>
                        <p className="text-sm font-bold text-slate-500">{s.label}</p>
                        <div className="mt-4 inline-flex items-center px-2.5 py-1 rounded-lg text-[10px] font-black uppercase tracking-wider bg-slate-50 text-slate-600 border border-slate-200">
                          {s.sub}
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* ── P&L STATEMENT ── */}
                  <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
                    <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div className="w-9 h-9 rounded-xl bg-indigo-600 flex items-center justify-center">
                          <BarChart2 size={16} className="text-white" />
                        </div>
                        <div>
                          <h3 className="font-black text-slate-800 text-base leading-tight">Profit &amp; Loss Statement</h3>
                          <p className="text-xs text-slate-500">Based on all non-cancelled orders</p>
                        </div>
                      </div>
                      <span className={`px-3 py-1.5 rounded-xl text-xs font-black flex items-center gap-1.5 ${isProfit ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                        {isProfit ? <TrendingUpIcon size={12} /> : <TrendingDownIcon size={12} />}
                        {isProfit ? 'PROFITABLE' : 'LOSS'}
                      </span>
                    </div>
                    <div className="p-6 grid grid-cols-1 lg:grid-cols-3 gap-5">

                      {/* Column 1: Income */}
                      <div className="space-y-3">
                        <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">💰 Income</p>
                        <div className="p-4 rounded-xl bg-slate-50 border border-slate-100">
                          <div className="flex items-center justify-between mb-1">
                            <span className="text-xs text-slate-600 font-medium">Total Sales Revenue</span>
                            <span className="text-lg font-black text-slate-800">৳{confirmedOrderValue.toLocaleString()}</span>
                          </div>
                          <p className="text-[10px] text-slate-400">All non-cancelled orders</p>
                        </div>
                        <div className="px-4 py-2.5 rounded-xl bg-green-50 border border-green-100">
                          <div className="flex items-center justify-between">
                            <span className="text-xs font-black text-green-700">Gross Profit</span>
                            <span className="text-base font-black text-green-700">৳{grossProfit.toLocaleString()}</span>
                          </div>
                          <p className="text-[10px] text-green-600 mt-0.5">{grossMargin.toFixed(1)}% Gross Margin</p>
                        </div>
                      </div>

                      {/* Column 2: Expenses */}
                      <div className="space-y-3">
                        <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">📤 Expenses</p>
                        <div className="p-4 rounded-xl bg-amber-50 border border-amber-100">
                          <div className="flex items-center justify-between mb-1">
                            <span className="text-xs text-slate-600 font-medium">Product Cost (COGS)</span>
                            <span className="text-sm font-black text-amber-700">-৳{totalCost.toLocaleString()}</span>
                          </div>
                          <p className="text-[10px] text-slate-400">From mainBalance per variation</p>
                        </div>
                        <div className="p-4 rounded-xl bg-violet-50 border border-violet-100">
                          <div className="flex items-center justify-between mb-1">
                            <span className="text-xs text-slate-600 font-medium">Delivery Charges</span>
                            <span className="text-sm font-black text-violet-700">-৳{totalDeliveryCharges.toLocaleString()}</span>
                          </div>
                          <p className="text-[10px] text-slate-400">Total accumulated delivery cost</p>
                        </div>
                        <div className="p-4 rounded-xl bg-blue-50 border border-blue-100">
                          <div className="flex items-center justify-between mb-1">
                            <span className="text-xs text-slate-600 font-medium">Facebook Ads Spend</span>
                            <span className="text-sm font-black text-blue-700">-৳{Math.round(fbAdsData.spend).toLocaleString()}</span>
                          </div>
                          <p className="text-[10px] text-slate-400">{fbAdsData.connected ? `ROAS ${fbAdsData.roas.toFixed(1)}x` : 'connect করুন'}</p>
                        </div>
                        <div className="px-4 py-2.5 rounded-xl bg-red-50 border border-red-100 flex items-center justify-between">
                          <span className="text-xs font-black text-red-700">Total Expenses</span>
                          <span className="text-base font-black text-red-700">-৳{(totalCost + totalExpenses).toLocaleString()}</span>
                        </div>
                      </div>

                      {/* Column 3: Result */}
                      <div className="space-y-3">
                        <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">📈 Result</p>
                        <div className={`p-5 rounded-xl text-center flex flex-col items-center gap-2 min-h-[120px] justify-center ${isProfit ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'}`}>
                          <div className={`w-11 h-11 rounded-xl flex items-center justify-center ${isProfit ? 'bg-green-100' : 'bg-red-100'}`}>
                            {isProfit ? <TrendingUpIcon size={22} className="text-green-600" /> : <TrendingDownIcon size={22} className="text-red-600" />}
                          </div>
                          <p className={`text-xs font-black uppercase tracking-widest ${isProfit ? 'text-green-600' : 'text-red-600'}`}>{isProfit ? '✅ NET PROFIT' : '❌ NET LOSS'}</p>
                          <p className={`text-3xl font-black ${isProfit ? 'text-green-700' : 'text-red-700'}`}>{isProfit ? '+' : '-'}৳{Math.abs(netProfit).toLocaleString()}</p>
                          <span className={`px-3 py-1 rounded-full text-[10px] font-black ${isProfit ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>{profitMargin.toFixed(1)}% Net Margin</span>
                        </div>
                        <div className="space-y-1.5">
                          {[
                            { label: 'Revenue', val: confirmedOrderValue, cls: 'text-green-600' },
                            { label: 'COGS', val: -totalCost, cls: 'text-amber-600' },
                            { label: 'Delivery', val: -totalDeliveryCharges, cls: 'text-violet-600' },
                            { label: 'FB Ads', val: -Math.round(fbAdsData.spend), cls: 'text-blue-600' },
                          ].map(r => (
                            <div key={r.label} className="flex items-center justify-between px-3 py-1.5 rounded-lg bg-slate-50 border border-slate-100">
                              <span className="text-[11px] text-slate-500 font-medium">{r.label}</span>
                              <span className={`text-[11px] font-black ${r.cls}`}>{r.val < 0 ? '-' : '+'} ৳{Math.abs(r.val).toLocaleString()}</span>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* ── FACEBOOK ADS PERFORMANCE WIDGET ─────────── */}
                  {fbAdsData.connected ? (
                    <div className="bg-white rounded-2xl border border-blue-100 shadow-sm overflow-hidden">
                      <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <div className="w-9 h-9 rounded-xl bg-blue-600 flex items-center justify-center flex-shrink-0">
                            <Facebook size={16} className="text-white" />
                          </div>
                          <div>
                            <h3 className="font-black text-slate-800 text-sm leading-tight">Facebook Ads Performance</h3>
                            <p className="text-[10px] text-slate-500 mt-0.5">
                              {fbAdsData.preset === 'today' ? 'আজকের' : fbAdsData.preset === 'last_7d' ? 'গত ৭ দিন' : fbAdsData.preset === 'this_month' ? 'এই মাস' : fbAdsData.preset === 'last_30d' ? 'গত ৩০ দিন' : 'এই বছর'} ডেটা
                            </p>
                          </div>
                        </div>
                        <span className="px-3 py-1 rounded-full text-[10px] font-black bg-blue-50 text-blue-700 border border-blue-200">📡 Live</span>
                      </div>
                      <div className="p-6 space-y-5">
                        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
                          {[
                            { label: 'Ad Spend', value: `৳${fbAdsData.spend.toLocaleString()}`, sub: `$${(fbAdsData.spend_usd || 0).toFixed(2)}`, color: '#f87171', bg: 'bg-red-50', br: 'border-red-100', icon: '💸' },
                            { label: 'FB Sales', value: String(fbAdsData.purchases || 0), sub: `${fbSalesRatio.toFixed(1)}% of orders`, color: '#22c55e', bg: 'bg-green-50', br: 'border-green-100', icon: '🛍' },
                            { label: 'ROAS', value: fbAdsData.roas > 0 ? `${fbAdsData.roas.toFixed(1)}x` : '—', sub: fbAdsData.roas >= 8 ? '✅ Good' : fbAdsData.roas >= 5 ? '⚠️ Avg' : fbAdsData.roas > 0 ? '❌ Low' : 'No data', color: fbAdsData.roas >= 5 ? '#22c55e' : '#f59e0b', bg: fbAdsData.roas >= 5 ? 'bg-green-50' : 'bg-amber-50', br: fbAdsData.roas >= 5 ? 'border-green-100' : 'border-amber-100', icon: '📈' },
                            { label: 'Cost/Sale', value: fbAdsData.cpa > 0 ? `৳${fbAdsData.cpa.toLocaleString()}` : '—', sub: fbAdsData.cpa > 0 && fbAdsData.cpa < 500 ? '✅ Good CPA' : fbAdsData.cpa >= 500 ? '⚠️ High' : '—', color: fbAdsData.cpa > 0 && fbAdsData.cpa < 500 ? '#22c55e' : '#f59e0b', bg: 'bg-slate-50', br: 'border-slate-100', icon: '🎯' },
                            { label: 'Clicks', value: (fbAdsData.clicks || 0) >= 1000 ? `${((fbAdsData.clicks || 0) / 1000).toFixed(1)}K` : String(fbAdsData.clicks || 0), sub: `CTR ${(fbAdsData.ctr || 0).toFixed(2)}%`, color: '#0ea5e9', bg: 'bg-sky-50', br: 'border-sky-100', icon: '🖱' },
                            { label: 'Impressions', value: (fbAdsData.impressions || 0) >= 1000000 ? `${((fbAdsData.impressions || 0) / 1000000).toFixed(1)}M` : (fbAdsData.impressions || 0) >= 1000 ? `${((fbAdsData.impressions || 0) / 1000).toFixed(1)}K` : String(fbAdsData.impressions || 0), sub: `CPC $${(fbAdsData.cpc || 0).toFixed(2)}`, color: '#8b5cf6', bg: 'bg-violet-50', br: 'border-violet-100', icon: '👁' },
                          ].map(m => (
                            <div key={m.label} className={`rounded-2xl p-3 border ${m.bg} ${m.br}`}>
                              <p className="text-[9px] font-black uppercase tracking-wider mb-1.5 text-slate-400">{m.icon} {m.label}</p>
                              <p className="text-base font-black leading-none mb-0.5" style={{ color: m.color }}>{m.value}</p>
                            </div>
                          ))}
                        </div>
                        <div className="rounded-2xl p-4" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
                          <div className="flex items-center justify-between mb-3">
                            <div>
                              <p className="text-xs font-black text-slate-800 dark:text-white">📊 Sales Attribution — FB Ads vs Organic</p>
                              <p className="text-[10px] text-slate-500 mt-0.5">Facebook Ads থেকে কত % order এসেছে</p>
                            </div>
                            <div className="text-right">
                              <p className="text-2xl font-black" style={{ color: '#60a5fa' }}>{fbSalesRatio.toFixed(1)}%</p>
                              <p className="text-[9px] text-slate-500">FB Ads থেকে</p>
                            </div>
                          </div>
                          <div className="h-2.5 rounded-full overflow-hidden" style={{ background: 'rgba(255,255,255,0.06)' }}>
                            <div className="h-full rounded-full" style={{ width: `${Math.max(fbSalesRatio, fbSalesRatio > 0 ? 2 : 0)}%`, background: 'linear-gradient(90deg,#1877F2,#60a5fa)', transition: 'width 0.7s ease' }} />
                          </div>
                          <div className="flex justify-between mt-2 text-[10px]">
                            <span style={{ color: '#60a5fa' }}>📘 FB: {fbAdsData.purchases} sales · ৳{fbAdsData.spend.toLocaleString()} cost</span>
                            <span style={{ color: '#475569' }}>Total confirmed: {confirmedOrdersCount}</span>
                          </div>
                          {fbAdsCostBDT > 0 && fbAdsData.purchases > 0 && (() => {
                            const fbRevEst = Math.round(confirmedOrderValue * (fbSalesRatio / 100));
                            const fbNet = fbRevEst - fbAdsCostBDT;
                            return (
                              <div className="mt-3 pt-3 border-t grid grid-cols-3 gap-3 text-center" style={{ borderColor: 'rgba(255,255,255,0.06)' }}>
                                {[
                                  { label: 'Est. FB Revenue', val: `৳${fbRevEst.toLocaleString()}`, color: '#4ade80' },
                                  { label: 'FB Ad Cost', val: `৳${fbAdsCostBDT.toLocaleString()}`, color: '#f87171' },
                                  { label: 'FB Net', val: `${fbNet >= 0 ? '+' : '-'}৳${Math.abs(fbNet).toLocaleString()}`, color: fbNet >= 0 ? '#4ade80' : '#f87171' },
                                ].map(r => (
                                  <div key={r.label} className="rounded-xl p-2.5" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
                                    <p className="text-[9px] text-slate-500 mb-1">{r.label}</p>
                                    <p className="text-xs font-black" style={{ color: r.color }}>{r.val}</p>
                                  </div>
                                ))}
                              </div>
                            );
                          })()}
                        </div>
                      </div>
                    </div>
                  ) : (
                    <div className="rounded-3xl p-5 flex items-center gap-4" style={{ background: 'rgba(24,119,242,0.04)', border: '1px dashed rgba(24,119,242,0.2)' }}>
                      <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: 'rgba(24,119,242,0.1)' }}><Facebook size={20} className="text-blue-500" /></div>
                      <div>
                        <p className="font-black text-slate-800 dark:text-white text-sm">Facebook Ads সংযুক্ত করুন</p>
                        <p className="text-xs text-slate-500 mt-0.5">"Facebook Ads" ট্যাবে গিয়ে API connect করলে এখানে live spend, ROAS, sales ratio দেখা যাবে।</p>
                      </div>
                    </div>
                  )}

                  {/* ── 3 COLUMN INFO ROW ─────────────────────── */}
                  <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">

                    {/* Order Status */}
                    <div className="bg-white dark:bg-slate-900 rounded-2xl p-5 border border-slate-100 dark:border-slate-800 shadow-sm">
                      <h3 className="text-sm font-black mb-4 flex items-center gap-2 text-slate-800 dark:text-white">
                        <span className="w-7 h-7 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg,#f59e0b,#ea580c)' }}>
                          <BarChart2 size={14} className="text-slate-800 dark:text-white" />
                        </span>
                        Order Status
                      </h3>
                      <div className="space-y-3">
                        {[
                          { label: 'Pending', count: pendingOrders, color: '#f59e0b', bg: '#fef3c7' },
                          { label: 'Confirmed', count: orders.filter(o => o.status === 'Confirmed Order').length, color: '#3b82f6', bg: '#dbeafe' },
                          { label: 'Completed', count: completedOrders, color: '#059669', bg: '#d1fae5' },
                          { label: 'Cancelled', count: cancelledOrders, color: '#ef4444', bg: '#fee2e2' },
                        ].map(s => (
                          <div key={s.label}>
                            <div className="flex justify-between text-xs mb-1">
                              <span className="text-slate-500 font-medium">{s.label}</span>
                              <span className="font-black" style={{ color: s.color }}>{s.count}</span>
                            </div>
                            <div className="w-full h-1.5 rounded-full" style={{ background: s.bg }}>
                              <div className="h-1.5 rounded-full transition-all" style={{ width: `${totalOrders > 0 ? (s.count / totalOrders) * 100 : 0}%`, background: s.color }} />
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* Traffic & Engagement */}
                    <div className="bg-white dark:bg-slate-900 rounded-2xl p-5 border border-slate-100 dark:border-slate-800 shadow-sm">
                      <h3 className="text-sm font-black mb-4 flex items-center gap-2 text-slate-800 dark:text-white">
                        <span className="w-7 h-7 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg,#3b82f6,#6366f1)' }}>
                          <EyeIcon size={14} className="text-slate-800 dark:text-white" />
                        </span>
                        Traffic & Engagement
                      </h3>
                      <div className="space-y-3">
                        {[
                          { label: 'Page Views', value: pageViews.toLocaleString(), sub: `+${todayPageViews} today`, color: '#3b82f6' },
                          { label: 'Product Views', value: contentViews.toLocaleString(), sub: `${products.length} products`, color: '#7c3aed' },
                          { label: 'Checkouts Started', value: initiatedCheckouts.toLocaleString(), sub: `${totalLeads} incomplete`, color: '#059669' },
                        ].map(t => (
                          <div key={t.label} className="flex items-center justify-between rounded-xl px-3 py-2.5 bg-slate-50 dark:bg-slate-800">
                            <div>
                              <p className="text-xs font-bold text-slate-700 dark:text-slate-200">{t.label}</p>
                              <p className="text-[10px] text-slate-500 dark:text-slate-400 mt-0.5">{t.sub}</p>
                            </div>
                            <p className="text-lg font-black" style={{ color: t.color }}>{t.value}</p>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* Catalogue */}
                    <div className="bg-white dark:bg-slate-900 rounded-2xl p-5 border border-slate-100 dark:border-slate-800 shadow-sm">
                      <h3 className="text-sm font-black mb-4 flex items-center gap-2 text-slate-800 dark:text-white">
                        <span className="w-7 h-7 rounded-lg flex items-center justify-center" style={{ background: 'linear-gradient(135deg,#7c3aed,#4f46e5)' }}>
                          <ShoppingBag size={14} className="text-slate-800 dark:text-white" />
                        </span>
                        Catalogue
                      </h3>
                      <div className="grid grid-cols-2 gap-2">
                        {[
                          { label: 'Products', value: products.length, color: '#3b82f6' },
                          { label: 'Featured', value: products.filter(p => p.isFeatured).length, color: '#7c3aed' },
                          { label: 'Reviews', value: testimonials.length, color: '#f59e0b' },
                          { label: 'Free Delivery', value: products.filter(p => p.freeDeliveryEnabled).length, color: '#059669' },
                        ].map(s => (
                          <div key={s.label} className="rounded-xl p-3 text-center bg-slate-50 dark:bg-slate-800">
                            <p className="text-xl font-black" style={{ color: s.color }}>{s.value}</p>
                            <p className="text-[10px] text-slate-500 dark:text-slate-400 font-medium mt-0.5">{s.label}</p>
                          </div>
                        ))}
                      </div>
                    </div>

                  </div>


                  {/* ── Analytics Report ─────────────────────────────────── */}
                  {(() => {
                    // ── Date range bounds for selected period ──────────────
                    const now = new Date();
                    const todayStr = now.toISOString().slice(0, 10);
                    let rangeStart: Date, rangeEnd: Date;

                    if (analyticsPeriod === 'today') {
                      rangeStart = new Date(todayStr);
                      rangeEnd = new Date(todayStr + 'T23:59:59');
                    } else if (analyticsPeriod === 'week') {
                      const dow = now.getDay();
                      rangeStart = new Date(now); rangeStart.setDate(now.getDate() - dow);
                      rangeEnd = new Date(now); rangeEnd.setDate(rangeStart.getDate() + 6);
                    } else if (analyticsPeriod === 'month') {
                      rangeStart = new Date(now.getFullYear(), now.getMonth(), 1);
                      rangeEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);
                    } else if (analyticsPeriod === 'year') {
                      rangeStart = new Date(now.getFullYear(), 0, 1);
                      rangeEnd = new Date(now.getFullYear(), 11, 31, 23, 59, 59);
                    } else {
                      rangeStart = analyticsStart ? new Date(analyticsStart) : new Date(now.getFullYear(), 0, 1);
                      rangeEnd = analyticsEnd ? new Date(analyticsEnd + 'T23:59:59') : new Date();
                    }

                    // ── Helper: get Date from order ────────────────────────
                    const getDate = (o: Order) => new Date((o as any).date || (o as any).created_at || '');

                    // ── Filtered orders for selected period ────────────────
                    const filtered = orders.filter(o => {
                      const d = getDate(o);
                      return !isNaN(d.getTime()) && d >= rangeStart && d <= rangeEnd;
                    });

                    // ── KPI Stats ──────────────────────────────────────────
                    const totalAmt = filtered.reduce((s, o) => s + Number(o.total || 0), 0);
                    const avgVal = filtered.length ? totalAmt / filtered.length : 0;
                    const cancelled = filtered.filter(o => o.status === 'cancelled').length;

                    // ── Daily breakdown (for bar chart) ───────────────────
                    const dayMap: Record<string, { orders: number; revenue: number }> = {};
                    filtered.forEach(o => {
                      const d = getDate(o);
                      if (isNaN(d.getTime())) return;
                      const key = d.toISOString().slice(0, 10);
                      if (!dayMap[key]) dayMap[key] = { orders: 0, revenue: 0 };
                      dayMap[key].orders++;
                      dayMap[key].revenue += Number(o.total || 0);
                    });
                    const days = Object.keys(dayMap).sort();
                    const maxDayOrders = Math.max(...days.map(d => dayMap[d].orders), 1);

                    // ── Monthly breakdown table ────────────────────────────
                    const monthMap: Record<string, { orders: number; revenue: number }> = {};
                    orders.forEach(o => {
                      const d = getDate(o);
                      if (isNaN(d.getTime())) return;
                      const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
                      if (!monthMap[key]) monthMap[key] = { orders: 0, revenue: 0 };
                      monthMap[key].orders++;
                      monthMap[key].revenue += Number(o.total || 0);
                    });
                    const months = Object.keys(monthMap).sort().reverse().slice(0, 12);
                    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

                    // ── Yearly breakdown table ─────────────────────────────
                    const yearMap: Record<string, { orders: number; revenue: number }> = {};
                    orders.forEach(o => {
                      const d = getDate(o);
                      if (isNaN(d.getTime())) return;
                      const key = String(d.getFullYear());
                      if (!yearMap[key]) yearMap[key] = { orders: 0, revenue: 0 };
                      yearMap[key].orders++;
                      yearMap[key].revenue += Number(o.total || 0);
                    });
                    const years = Object.keys(yearMap).sort().reverse();

                    // ── SVG bar chart constants ────────────────────────────
                    const W = 900; const H = 180;
                    const pL = 38; const pR = 12; const pT = 14; const pB = 36;
                    const iW = W - pL - pR; const iH = H - pT - pB;
                    const numBars = Math.max(days.length, 1);
                    const slot = iW / numBars;
                    const bW = Math.min(slot * 0.7, 40);

                    const PERIODS: { key: typeof analyticsPeriod; label: string }[] = [
                      { key: 'today', label: 'Today' },
                      { key: 'week', label: 'This Week' },
                      { key: 'month', label: 'This Month' },
                      { key: 'year', label: 'This Year' },
                      { key: 'custom', label: 'Custom' },
                    ];

                    return (
                      <div className="bg-white dark:bg-slate-900 rounded-[32px] border shadow-sm overflow-hidden">
                        {/* Header */}
                        <div className="p-6 border-b border-slate-100 dark:border-slate-800">
                          <div className="flex flex-wrap items-center justify-between gap-4">
                            <div>
                              <h3 className="text-xl font-black flex items-center gap-2">
                                <span className="w-9 h-9 bg-blue-50 rounded-xl flex items-center justify-center">
                                  <TrendingUp size={20} className="text-blue-600" />
                                </span>
                                Sales Analytics
                              </h3>
                              <p className="text-xs text-slate-500 dark:text-slate-400 mt-1 ml-11">
                                Orders & revenue report — {filtered.length} orders in selected period
                              </p>
                            </div>
                            {/* Period tabs */}
                            <div className="flex gap-1 bg-slate-100 dark:bg-slate-800 p-1 rounded-2xl">
                              {PERIODS.map(p => (
                                <button key={p.key}
                                  onClick={() => setAnalyticsPeriod(p.key)}
                                  className={`px-4 py-2 rounded-xl text-xs font-black transition-all ${analyticsPeriod === p.key
                                    ? 'bg-white dark:bg-slate-700 text-blue-600 shadow-sm'
                                    : 'text-slate-500 hover:text-slate-700'
                                    }`}>
                                  {p.label}
                                </button>
                              ))}
                            </div>
                          </div>

                          {/* Custom date pickers */}
                          {analyticsPeriod === 'custom' && (
                            <div className="flex items-center gap-3 mt-4 flex-wrap">
                              <div className="flex items-center gap-2">
                                <Calendar size={14} className="text-slate-500 dark:text-slate-400" />
                                <span className="text-xs font-black text-slate-500">From</span>
                                <input type="date" value={analyticsStart}
                                  onChange={e => setAnalyticsStart(e.target.value)}
                                  className="border border-slate-200 rounded-xl px-3 py-1.5 text-sm font-bold text-slate-700 focus:ring-2 focus:ring-blue-500 outline-none" />
                              </div>
                              <div className="flex items-center gap-2">
                                <span className="text-xs font-black text-slate-500">To</span>
                                <input type="date" value={analyticsEnd}
                                  onChange={e => setAnalyticsEnd(e.target.value)}
                                  min={analyticsStart}
                                  className="border border-slate-200 rounded-xl px-3 py-1.5 text-sm font-bold text-slate-700 focus:ring-2 focus:ring-blue-500 outline-none" />
                              </div>
                              <span className="text-xs text-slate-500 dark:text-slate-400 font-medium">
                                {analyticsStart && analyticsEnd ? `${filtered.length} orders found` : 'Select a date range'}
                              </span>
                            </div>
                          )}
                        </div>

                        <div className="p-6 space-y-8">
                          {/* KPI Cards */}
                          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                            {[
                              { label: 'Orders', value: String(filtered.length), icon: ClipboardList, color: 'blue', bg: 'bg-blue-50', text: 'text-blue-600' },
                              { label: 'Revenue', value: `৳${totalAmt.toLocaleString()}`, icon: CreditCard, color: 'green', bg: 'bg-green-50', text: 'text-green-600' },
                              { label: 'Avg Order', value: `৳${Math.round(avgVal).toLocaleString()}`, icon: TrendingUp, color: 'purple', bg: 'bg-purple-50', text: 'text-purple-600' },
                              { label: 'Cancelled', value: String(cancelled), icon: XCircle, color: 'red', bg: 'bg-red-50', text: 'text-red-600' },
                            ].map(c => (
                              <div key={c.label} className={`${c.bg} rounded-[20px] p-5`}>
                                <c.icon size={20} className={`${c.text} mb-3`} />
                                <p className={`text-2xl font-black ${c.text}`}>{c.value}</p>
                                <p className="text-xs text-slate-500 font-bold mt-1">{c.label}</p>
                              </div>
                            ))}
                          </div>

                          {/* Daily Orders Bar Chart */}
                          <div>
                            <h4 className="text-sm font-black text-slate-600 mb-3 flex items-center gap-2">
                              <BarChart2 size={15} className="text-blue-500" />
                              Daily Orders — {analyticsPeriod === 'today' ? 'Today' : analyticsPeriod === 'week' ? 'This Week' : analyticsPeriod === 'month' ? 'This Month' : analyticsPeriod === 'year' ? 'This Year' : 'Custom Range'}
                            </h4>
                            {days.length === 0 ? (
                              <div className="h-32 flex items-center justify-center text-slate-500 dark:text-slate-300 text-sm font-bold bg-slate-50 rounded-[20px]">
                                No orders in this period
                              </div>
                            ) : (
                              <div className="w-full overflow-x-auto">
                                <svg viewBox={`0 0 ${W} ${H}`} className="w-full" style={{ minWidth: Math.max(400, numBars * 30) }}>
                                  <defs>
                                    <linearGradient id="dg1" x1="0" y1="0" x2="0" y2="1">
                                      <stop offset="0%" stopColor="#3b82f6" stopOpacity="0.9" />
                                      <stop offset="100%" stopColor="#6366f1" stopOpacity="0.6" />
                                    </linearGradient>
                                  </defs>
                                  {[0, 0.5, 1].map(r => {
                                    const y = pT + iH * (1 - r);
                                    return (
                                      <g key={r}>
                                        <line x1={pL} y1={y} x2={W - pR} y2={y} stroke="#f1f5f9" strokeWidth="1" />
                                        <text x={pL - 5} y={y + 3} textAnchor="end" fontSize="9" fill="#94a3b8" fontWeight="700">
                                          {Math.round(maxDayOrders * r)}
                                        </text>
                                      </g>
                                    );
                                  })}
                                  {days.map((day, i) => {
                                    const cnt = dayMap[day].orders;
                                    const bH = Math.max((cnt / maxDayOrders) * iH, 4);
                                    const x = pL + i * slot + (slot - bW) / 2;
                                    const y = pT + iH - bH;
                                    const isToday = day === todayStr;
                                    const d = new Date(day);
                                    const label = analyticsPeriod === 'year'
                                      ? monthNames[d.getMonth()]
                                      : `${d.getDate()}/${d.getMonth() + 1}`;
                                    return (
                                      <g key={day}>
                                        <rect x={x} y={y} width={bW} height={bH} rx={4}
                                          fill={isToday ? '#7c3aed' : 'url(#dg1)'} />
                                        <text x={x + bW / 2} y={y - 4} textAnchor="middle" fontSize="8.5"
                                          fontWeight="800" fill={isToday ? '#7c3aed' : '#3b82f6'}>
                                          {cnt}
                                        </text>
                                        {(numBars <= 31 || i % 4 === 0) && (
                                          <text x={x + bW / 2} y={H - 4} textAnchor="middle" fontSize="8" fill="#94a3b8" fontWeight="700">
                                            {label}
                                          </text>
                                        )}
                                        <rect x={x - 2} y={pT} width={bW + 4} height={iH} fill="transparent">
                                          <title>{`${day}: ${cnt} orders · ৳${dayMap[day].revenue.toLocaleString()}`}</title>
                                        </rect>
                                      </g>
                                    );
                                  })}
                                  <line x1={pL} y1={pT + iH} x2={W - pR} y2={pT + iH} stroke="#e2e8f0" strokeWidth="1.5" />
                                </svg>
                              </div>
                            )}
                          </div>

                          {/* Monthly + Yearly tables side by side */}
                          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            {/* Monthly Breakdown */}
                            <div>
                              <h4 className="text-sm font-black text-slate-600 mb-3 flex items-center gap-2">
                                <Calendar size={15} className="text-green-500" />
                                Monthly Breakdown
                              </h4>
                              <div className="rounded-[20px] border overflow-hidden">
                                <table className="w-full text-sm">
                                  <thead>
                                    <tr className="bg-slate-50 dark:bg-slate-800 text-[10px] font-black uppercase text-slate-500 dark:text-slate-400">
                                      <th className="px-4 py-3 text-left">Month</th>
                                      <th className="px-4 py-3 text-right">Orders</th>
                                      <th className="px-4 py-3 text-right">Revenue</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                    {months.length === 0 ? (
                                      <tr><td colSpan={3} className="text-center py-6 text-slate-500 dark:text-slate-300 font-bold text-xs">No data</td></tr>
                                    ) : months.map((m, idx) => {
                                      const [yr, mo] = m.split('-');
                                      const isThisMonth = m === `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
                                      return (
                                        <tr key={m} className={`border-t ${idx % 2 === 0 ? '' : 'bg-slate-50/50'} ${isThisMonth ? 'ring-1 ring-inset ring-blue-200' : ''}`}>
                                          <td className="px-4 py-3 font-bold text-slate-700">
                                            {monthNames[parseInt(mo) - 1]} {yr}
                                            {isThisMonth && <span className="ml-2 text-[9px] bg-blue-100 text-blue-600 px-1.5 py-0.5 rounded-full font-black">Current</span>}
                                          </td>
                                          <td className="px-4 py-3 text-right font-black text-blue-600">{monthMap[m].orders}</td>
                                          <td className="px-4 py-3 text-right font-black text-green-600">৳{monthMap[m].revenue.toLocaleString()}</td>
                                        </tr>
                                      );
                                    })}
                                  </tbody>
                                  {months.length > 0 && (
                                    <tfoot>
                                      <tr className="bg-slate-50 border-t-2 border-slate-200">
                                        <td className="px-4 py-3 font-black text-slate-700 text-xs">Total ({months.length} months)</td>
                                        <td className="px-4 py-3 text-right font-black text-blue-700">{months.reduce((s, m) => s + monthMap[m].orders, 0)}</td>
                                        <td className="px-4 py-3 text-right font-black text-green-700">৳{months.reduce((s, m) => s + monthMap[m].revenue, 0).toLocaleString()}</td>
                                      </tr>
                                    </tfoot>
                                  )}
                                </table>
                              </div>
                            </div>

                            {/* Yearly Breakdown */}
                            <div>
                              <h4 className="text-sm font-black text-slate-600 mb-3 flex items-center gap-2">
                                <Activity size={15} className="text-purple-500" />
                                Yearly Summary
                              </h4>
                              <div className="rounded-[20px] border overflow-hidden">
                                <table className="w-full text-sm">
                                  <thead>
                                    <tr className="bg-slate-50 dark:bg-slate-800 text-[10px] font-black uppercase text-slate-500 dark:text-slate-400">
                                      <th className="px-4 py-3 text-left">Year</th>
                                      <th className="px-4 py-3 text-right">Orders</th>
                                      <th className="px-4 py-3 text-right">Revenue</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                    {years.length === 0 ? (
                                      <tr><td colSpan={3} className="text-center py-6 text-slate-500 dark:text-slate-300 font-bold text-xs">No data</td></tr>
                                    ) : years.map((yr, idx) => {
                                      const isThisYear = yr === String(now.getFullYear());
                                      const maxOrd = Math.max(...years.map(y => yearMap[y].orders), 1);
                                      const pct = (yearMap[yr].orders / maxOrd) * 100;
                                      return (
                                        <tr key={yr} className={`border-t ${idx % 2 === 0 ? '' : 'bg-slate-50/50'}`}>
                                          <td className="px-4 py-3 font-bold text-slate-700">
                                            <div className="flex items-center gap-2">
                                              {yr}
                                              {isThisYear && <span className="text-[9px] bg-purple-100 text-purple-600 px-1.5 py-0.5 rounded-full font-black">Current</span>}
                                            </div>
                                            <div className="w-full bg-slate-100 rounded-full h-1.5 mt-1.5">
                                              <div className="bg-purple-400 h-1.5 rounded-full" style={{ width: `${pct}%` }} />
                                            </div>
                                          </td>
                                          <td className="px-4 py-3 text-right font-black text-blue-600">{yearMap[yr].orders}</td>
                                          <td className="px-4 py-3 text-right font-black text-green-600">৳{yearMap[yr].revenue.toLocaleString()}</td>
                                        </tr>
                                      );
                                    })}
                                  </tbody>
                                </table>
                              </div>
                            </div>
                          </div>
                          {/* ── Profit & Loss Card ───────────────────────── */}
                          {(() => {
                            // Build a lookup map: productId → priceConfigs
                            const productMap: Record<string, any> = {};
                            products.forEach(p => { productMap[p.id] = p; });

                            let totalRevenue = 0;
                            let totalCost = 0;
                            let itemsWithCost = 0;
                            let itemsTotal = 0;

                            filtered.forEach(o => {
                              const orderTotal = Number(o.total || 0);
                              const deliveryCost = Number((o as any).deliveryCharge || (o as any).delivery_charge || 0);

                              totalRevenue += orderTotal;
                              totalCost += deliveryCost; // Add delivery cost to total cost

                              const items = Array.isArray(o.items) ? o.items : [];
                              items.forEach((item: any) => {
                                itemsTotal++;
                                const pId = item.productId || item.product_id;
                                const prod = productMap[pId];
                                if (!prod) return;

                                // Parse priceConfigs if it's a string
                                let configs: Record<string, any> = {};
                                try {
                                  configs = (typeof prod.priceConfigs === 'string')
                                    ? JSON.parse(prod.priceConfigs)
                                    : (prod.priceConfigs ?? prod.price_configs ?? {});
                                } catch (e) {
                                  configs = prod.price_configs ?? {};
                                }

                                // Find matching size key
                                const sizeKey = item.selectedSize || item.size
                                  ? Object.keys(configs).find(k => k === (item.selectedSize || item.size) || k.includes(item.selectedSize || item.size))
                                  : Object.keys(configs)[0];

                                const cfg = sizeKey ? configs[sizeKey] : null;
                                const mainBal = cfg?.mainBalance ?? 0;

                                if (mainBal > 0) {
                                  totalCost += Number(mainBal) * Number(item.quantity || 1);
                                  itemsWithCost++;
                                }
                              });
                            });

                            const grossProfit = totalRevenue - totalCost;
                            const profitPct = totalRevenue > 0 ? (grossProfit / totalRevenue) * 100 : 0;
                            const isProfit = grossProfit >= 0;
                            const costPct = totalRevenue > 0 ? Math.min((totalCost / totalRevenue) * 100, 100) : 0;
                            const noCostItems = itemsTotal - itemsWithCost;

                            return (
                              <div className={`rounded-[24px] border-2 p-6 ${isProfit ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'}`}>
                                <div className="flex flex-wrap items-start justify-between gap-4 mb-6">
                                  <div>
                                    <h4 className="text-base font-black flex items-center gap-2">
                                      {isProfit
                                        ? <TrendingUp size={18} className="text-green-600" />
                                        : <TrendingDownIcon size={18} className="text-red-600" />}
                                      <span className={isProfit ? 'text-green-700' : 'text-red-700'}>
                                        Profit & Loss Report
                                      </span>
                                    </h4>
                                    <p className="text-xs text-slate-500 dark:text-slate-400 mt-1 ml-7">
                                      Based on Main Balance (cost) vs MRP revenue · {filtered.length} orders
                                    </p>
                                  </div>
                                  <div className={`px-4 py-2 rounded-2xl font-black text-sm ${isProfit ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                                    {isProfit ? '📈 Profit' : '📉 Loss'} {Math.abs(profitPct).toFixed(1)}%
                                  </div>
                                </div>

                                {/* 4 P&L stat cards */}
                                <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
                                  {[
                                    { label: 'Total Revenue', val: `৳${totalRevenue.toLocaleString()}`, sub: 'From orders (MRP)', color: 'bg-blue-100 text-blue-700' },
                                    { label: 'Total Cost', val: `৳${totalCost.toLocaleString()}`, sub: 'Main Balance × Qty + Delivery', color: 'bg-slate-100 text-slate-700' },
                                    { label: isProfit ? 'Gross Profit' : 'Gross Loss', val: `৳${Math.abs(grossProfit).toLocaleString()}`, sub: 'Revenue − Cost', color: isProfit ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700' },
                                    { label: 'Profit Margin', val: `${profitPct >= 0 ? '+' : ''}${profitPct.toFixed(1)}%`, sub: 'Profit ÷ Revenue', color: isProfit ? 'bg-emerald-100 text-emerald-700' : 'bg-orange-100 text-orange-700' },
                                  ].map(c => (
                                    <div key={c.label} className={`${c.color} rounded-[16px] p-4`}>
                                      <p className="text-xl font-black">{c.val}</p>
                                      <p className="text-[11px] font-black mt-1 opacity-80">{c.label}</p>
                                      <p className="text-[9px] opacity-60 mt-0.5">{c.sub}</p>
                                    </div>
                                  ))}
                                </div>

                                {/* Revenue vs Cost breakdown bar */}
                                <div className="mb-3">
                                  <div className="flex justify-between text-xs font-black text-slate-500 mb-1.5">
                                    <span>Cost ({costPct.toFixed(0)}%)</span>
                                    <span>Profit ({(100 - costPct).toFixed(0)}%)</span>
                                  </div>
                                  <div className="w-full h-3 bg-slate-200 rounded-full overflow-hidden flex">
                                    <div className="h-full bg-slate-500 transition-all" style={{ width: `${costPct}%` }} />
                                    <div className={`h-full flex-1 ${isProfit ? 'bg-green-400' : 'bg-red-400'}`} />
                                  </div>
                                  <div className="flex justify-between text-[10px] text-slate-500 dark:text-slate-400 mt-1">
                                    <span>৳{totalCost.toLocaleString()} (Cost + Delivery)</span>
                                    <span>৳{Math.abs(grossProfit).toLocaleString()} {isProfit ? 'profit' : 'loss'}</span>
                                  </div>
                                </div>

                                {noCostItems > 0 && (
                                  <p className="text-[10px] text-amber-600 bg-amber-50 border border-amber-200 rounded-xl px-3 py-2 mt-2">
                                    ⚠️ {noCostItems} item{noCostItems > 1 ? 's' : ''} have no Main Balance set — cost may be understated. Go to Products → Variations to set Main Balance.
                                  </p>
                                )}
                              </div>
                            );
                          })()}
                        </div>
                      </div>
                    );
                  })()}




                  {(() => {
                    const hourly = Array(24).fill(0);
                    orders.forEach(o => {
                      const raw = (o as any).date || (o as any).created_at || (o as any).confirmedAt;
                      if (!raw) return;
                      const d = new Date(raw);
                      if (!isNaN(d.getTime())) hourly[d.getHours()]++;
                    });
                    const maxVal = Math.max(...hourly, 1);
                    const total24 = hourly.reduce((a, b) => a + b, 0);
                    const peakHr = hourly.indexOf(Math.max(...hourly));
                    const W = 900; const H = 200;
                    const pL = 38; const pR = 12; const pT = 14; const pB = 38;
                    const iW = W - pL - pR; const iH = H - pT - pB;
                    const slot = iW / 24; const bW = slot * 0.62;
                    const fmt = (h: number) => {
                      const s = h < 12 ? 'AM' : 'PM';
                      return `${h === 0 ? 12 : h > 12 ? h - 12 : h}${s}`;
                    };
                    return (
                      <div className="bg-white dark:bg-slate-900 p-6 rounded-[32px] border shadow-sm">
                        <div className="flex flex-wrap items-start justify-between gap-3 mb-5">
                          <div>
                            <h3 className="text-lg font-black flex items-center gap-2">
                              <span className="w-8 h-8 bg-red-50 rounded-xl flex items-center justify-center">
                                <BarChart2 size={18} className="text-red-600" />
                              </span>
                              24-Hour Orders Timeline
                            </h3>
                            <p className="text-xs text-slate-500 dark:text-slate-400 mt-1 ml-10">
                              {total24} total order{total24 !== 1 ? 's' : ''} · Peak: {fmt(peakHr)}–{fmt((peakHr + 1) % 24)} ({hourly[peakHr]} orders)
                            </p>
                          </div>
                          <div className="flex items-center gap-4 text-[10px] text-slate-500 font-bold shrink-0">
                            <span className="flex items-center gap-1"><span className="w-2.5 h-2.5 rounded-full bg-purple-500 inline-block" />Peak</span>
                            <span className="flex items-center gap-1"><span className="w-2.5 h-2.5 rounded-full bg-red-400 inline-block" />Active</span>
                            <span className="flex items-center gap-1"><span className="w-2.5 h-2.5 rounded-full bg-slate-200 inline-block" />Empty</span>
                          </div>
                        </div>

                        <div className="w-full overflow-x-auto">
                          <svg viewBox={`0 0 ${W} ${H}`} className="w-full" style={{ minWidth: 520 }}>
                            <defs>
                              <linearGradient id="g1" x1="0" y1="0" x2="0" y2="1">
                                <stop offset="0%" stopColor="#ef4444" stopOpacity="0.9" />
                                <stop offset="100%" stopColor="#f97316" stopOpacity="0.6" />
                              </linearGradient>
                              <linearGradient id="g2" x1="0" y1="0" x2="0" y2="1">
                                <stop offset="0%" stopColor="#7c3aed" />
                                <stop offset="100%" stopColor="#db2777" stopOpacity="0.8" />
                              </linearGradient>
                            </defs>

                            {/* Grid lines + Y labels */}
                            {[0, 0.25, 0.5, 0.75, 1].map(r => {
                              const y = pT + iH * (1 - r);
                              return (
                                <g key={r}>
                                  <line x1={pL} y1={y} x2={W - pR} y2={y} stroke="#f1f5f9" strokeWidth={r === 0 ? 1.5 : 1} />
                                  <text x={pL - 5} y={y + 4} textAnchor="end" fontSize="9" fill="#94a3b8" fontWeight="700">
                                    {Math.round(maxVal * r)}
                                  </text>
                                </g>
                              );
                            })}

                            {/* Bars + labels */}
                            {hourly.map((cnt, h) => {
                              const bH = cnt > 0 ? Math.max((cnt / maxVal) * iH, 6) : 0;
                              const x = pL + h * slot + (slot - bW) / 2;
                              const y = pT + iH - bH;
                              const pk = h === peakHr && cnt > 0;
                              return (
                                <g key={h}>
                                  {cnt === 0
                                    ? <rect x={x} y={pT + iH - 3} width={bW} height={3} rx={2} fill="#e2e8f0" />
                                    : <rect x={x} y={y} width={bW} height={bH} rx={4} fill={pk ? 'url(#g2)' : 'url(#g1)'} />
                                  }
                                  {cnt > 0 && (
                                    <text x={x + bW / 2} y={y - 4} textAnchor="middle" fontSize="9" fontWeight="800" fill={pk ? '#7c3aed' : '#dc2626'}>
                                      {cnt}
                                    </text>
                                  )}
                                  {h % 3 === 0 && (
                                    <text x={x + bW / 2} y={H - 5} textAnchor="middle" fontSize="8.5" fill="#94a3b8" fontWeight="700">
                                      {fmt(h)}
                                    </text>
                                  )}
                                  <rect x={x - 2} y={pT} width={bW + 4} height={iH + 2} fill="transparent">
                                    <title>{`${fmt(h)} – ${fmt((h + 1) % 24)}: ${cnt} order${cnt !== 1 ? 's' : ''}`}</title>
                                  </rect>
                                </g>
                              );
                            })}

                            {/* X axis baseline */}
                            <line x1={pL} y1={pT + iH} x2={W - pR} y2={pT + iH} stroke="#e2e8f0" strokeWidth="1.5" />
                          </svg>
                        </div>

                        {/* Mini color-coded hour strip */}
                        <div className="mt-3 flex gap-0.5">
                          {hourly.map((cnt, h) => (
                            <div key={h} title={`${fmt(h)}: ${cnt} orders`}
                              className={`flex-1 h-2 rounded-sm transition-transform hover:scale-y-150 origin-bottom cursor-default ${cnt === 0 ? 'bg-slate-100'
                                : h === peakHr ? 'bg-purple-500'
                                  : cnt >= maxVal * 0.6 ? 'bg-red-500'
                                    : cnt >= maxVal * 0.3 ? 'bg-orange-400' : 'bg-orange-200'
                                }`} />
                          ))}
                        </div>
                      </div>
                    );
                  })()}

                </div>
              
    </>
  );
}
