import re

with open("resources/js/components/admin/DashboardOverview.tsx", "r", encoding="utf-8") as f:
    content = f.read()

# Add Lucide icons
icons_to_add = "Facebook, ShoppingBag, TrendingUp, Calendar, XCircle, Eye as EyeIcon"
content = content.replace("TrendingUp as TrendingUpIcon, TrendingDown as TrendingDownIcon, Search", f"TrendingUp as TrendingUpIcon, TrendingDown as TrendingDownIcon, Search, {icons_to_add}")

# Update Props Interface
props_interface = """
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;
}
"""
content = re.sub(r'interface DashboardOverviewProps \{.*?\n\}', props_interface.strip(), content, flags=re.DOTALL)

# Update Component signature
old_sig = "export default function DashboardOverview({ orders, leads, products, currentUser, settings, activeTab, adminBanners }: DashboardOverviewProps) {"
new_sig = "export default function DashboardOverview({ orders, leads, products, currentUser, settings, activeTab, adminBanners, testimonials, todayPageViews, initiatedCheckouts, analyticsPeriod, setAnalyticsPeriod, analyticsStart, setAnalyticsStart, analyticsEnd, setAnalyticsEnd }: DashboardOverviewProps) {"
content = content.replace(old_sig, new_sig)

# Add computed variables inside DashboardOverview
computed_vars = """
  // ── 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;
    orders.forEach(o => {
      if ((o.status as string) === 'Confirmed Order' || (o.status as string) === 'completed') {
        o.items?.forEach((item: any) => {
          const p = products.find(prod => String(prod.id) === String(item.productId));
          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);
            }
          }
        });
      }
    });
    return cost;
  }, [orders, products]);

  const totalDeliveryCharges = React.useMemo(() => {
    return orders
      .filter(o => (o.status as string) === 'Confirmed Order' || (o.status as string) === 'completed')
      .reduce((acc, o) => acc + Number(o.deliveryCharge || 0), 0);
  }, [orders]);

  const confirmedOrdersCount = orders.filter(o =>
    (o.status as string) === 'Confirmed Order' || (o.status as string) === 'completed'
  ).length;
  
  const fbAdsCostBDT = fbAdsData.spend;
  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;
"""

content = content.replace("const estimatedGrossProfit = confirmedOrderValue * 0.30;", "const estimatedGrossProfit = confirmedOrderValue * 0.30;\n" + computed_vars)

with open("resources/js/components/admin/DashboardOverview.tsx", "w", encoding="utf-8") as f:
    f.write(content)

