import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useAuth } from "@/hooks/use-auth";
import { supabase } from "@/integrations/supabase/client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useState, useMemo } from "react";
import { toast } from "sonner";
import {
  Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from "@/components/ui/dialog";
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import {
  Plus, Search, Pencil, Trash2, Eye, Phone, MapPin, Mail,
  ArrowLeft, CreditCard, DollarSign, TrendingDown, Users, AlertTriangle,
  Download, ChevronLeft, ChevronRight, Upload, X,
} from "lucide-react";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { CustomerOrderStats } from "@/components/sales/CustomerOrderStats";
import { SegmentBadge, computeSegment, DEFAULT_THRESHOLDS, type SegmentThresholds } from "@/components/customers/SegmentBadge";

export const Route = createFileRoute("/_authenticated/customers")({
  head: () => ({
    meta: [{ title: "Customers — Niyamah Electric & Hardware" }],
  }),
  component: CustomersPage,
});

type Customer = {
  id: string; name: string; name_bn: string; mobile: string; email: string;
  address: string; customer_type: string; opening_balance: number;
  current_balance: number; total_due: number; reference_mobile: string;
  reference_customer_id: string | null; status: string; created_at: string;
  image_url?: string | null;
};

type CustomerTransaction = {
  id: string; customer_id: string; type: string; amount: number;
  reference_id: string; note: string; method: string; created_at: string;
};

const emptyForm = {
  name: "", name_bn: "", mobile: "", email: "", address: "",
  customer_type: "retail", opening_balance: 0, reference_mobile: "", status: "active",
  image_url: "" as string,
};

const emptyPayment = { amount: 0, method: "cash", note: "" };

function CustomersPage() {
  const { tr, lang } = useLanguage();
  const { user } = useAuth();
  const qc = useQueryClient();
  const [search, setSearch] = useState("");
  const [typeFilter, setTypeFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");
  const [dueFilter, setDueFilter] = useState("all");
  const [modalOpen, setModalOpen] = useState(false);
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [editId, setEditId] = useState<string | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [viewCustomer, setViewCustomer] = useState<Customer | null>(null);
  const [paymentModalOpen, setPaymentModalOpen] = useState(false);
  const [paymentForm, setPaymentForm] = useState(emptyPayment);
  const [txFilter, setTxFilter] = useState("all");
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(20);
  const [uploadingImage, setUploadingImage] = useState(false);

  // Extract the storage path from a public URL pointing to customer-images bucket
  const extractCustomerImagePath = (url?: string | null): string | null => {
    if (!url) return null;
    const marker = "/customer-images/";
    const idx = url.indexOf(marker);
    if (idx === -1) return null;
    try {
      return decodeURIComponent(url.slice(idx + marker.length).split("?")[0]);
    } catch {
      return url.slice(idx + marker.length).split("?")[0];
    }
  };

  const removeCustomerImageFile = async (url?: string | null) => {
    const path = extractCustomerImagePath(url);
    if (!path) return;
    try {
      await supabase.storage.from("customer-images").remove([path]);
    } catch (e) {
      console.warn("Failed to delete old customer image:", e);
    }
  };

  const handleImageUpload = async (file: File) => {
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) {
      toast.error(lang === "bn" ? "ছবির আকার ৫ MB এর কম হতে হবে" : "Image must be under 5MB");
      return;
    }
    setUploadingImage(true);
    const previousUrl = form.image_url;
    try {
      const ext = (file.name.split(".").pop() || "jpg").toLowerCase();
      const path = `${user?.id || "anon"}/${Date.now()}.${ext}`;
      const { error } = await supabase.storage.from("customer-images").upload(path, file, {
        cacheControl: "3600", upsert: false, contentType: file.type,
      });
      if (error) throw error;
      const { data: signed, error: signErr } = await supabase.storage.from("customer-images").createSignedUrl(path, 60 * 60 * 24 * 365 * 10);
      if (signErr) throw signErr;
      setForm((f) => ({ ...f, image_url: signed.signedUrl }));
      // Best-effort delete of the previously stored file
      await removeCustomerImageFile(previousUrl);
    } catch (e: any) {
      console.error("Image upload error:", e);
      toast.error(tr("somethingWrong"));
    } finally {
      setUploadingImage(false);
    }
  };

  const { data: customers = [], isLoading } = useQuery({
    queryKey: ["customers"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("customers").select("id,name,name_bn,mobile,email,address,customer_type,opening_balance,current_balance,total_due,status,deleted_at,reference_mobile,reference_customer_id,portal_enabled,portal_last_login_at,image_url,created_at,updated_at").is("deleted_at", null)
        .order("created_at", { ascending: false });
      if (error) throw error;
      return data as Customer[];
    },
  });

  const { data: transactions = [] } = useQuery({
    queryKey: ["customer_transactions", viewCustomer?.id],
    enabled: !!viewCustomer,
    queryFn: async () => {
      const { data, error } = await supabase
        .from("customer_transactions").select("*")
        .eq("customer_id", viewCustomer!.id)
        .order("created_at", { ascending: false });
      if (error) throw error;
      return data as CustomerTransaction[];
    },
  });

  const { data: customerCommissions = [] } = useQuery({
    queryKey: ["commissions", viewCustomer?.id],
    enabled: !!viewCustomer,
    queryFn: async () => {
      const { data, error } = await supabase
        .from("commissions").select("*")
        .eq("customer_id", viewCustomer!.id)
        .order("created_at", { ascending: false });
      if (error) throw error;
      return data as any[];
    },
  });

  const { data: isAdmin = false } = useQuery({
    queryKey: ["is-admin", user?.id],
    enabled: !!user?.id,
    queryFn: async () => {
      const { data } = await supabase.from("user_roles").select("role").eq("user_id", user!.id).eq("role", "admin").maybeSingle();
      return !!data;
    },
  });

  const { data: customerWallet } = useQuery({
    queryKey: ["wallet-summary", viewCustomer?.id],
    enabled: !!viewCustomer,
    queryFn: async () => {
      const { data } = await supabase.from("referral_wallets").select("balance, adjusted_amount").eq("customer_id", viewCustomer!.id).maybeSingle();
      return data || { balance: 0, adjusted_amount: 0 };
    },
  });

  const { data: dueAdjustments = [] } = useQuery({
    queryKey: ["due-adjustments-summary", viewCustomer?.id],
    enabled: !!viewCustomer,
    queryFn: async () => {
      const { data } = await supabase.from("customer_due_adjustments").select("amount").eq("customer_id", viewCustomer!.id);
      return data || [];
    },
  });

  const { data: segmentLogs = [] } = useQuery({
    queryKey: ["segment-logs", viewCustomer?.id],
    enabled: !!viewCustomer,
    queryFn: async () => {
      const { data, error } = await supabase
        .from("customer_segment_logs" as any)
        .select("id, old_segment, new_segment, reason, created_at")
        .eq("customer_id", viewCustomer!.id)
        .order("created_at", { ascending: false })
        .limit(50);
      if (error) return [];
      return (data as any[]) || [];
    },
  });



  // Summary stats
  const stats = useMemo(() => {
    const total = customers.length;
    const totalDue = customers.reduce((s, c) => s + Number(c.total_due), 0);
    const dueCustomers = customers.filter(c => Number(c.total_due) > 0).length;
    const totalBalance = customers.reduce((s, c) => s + Number(c.current_balance), 0);
    const totalReferrals = customers.filter(c => c.reference_customer_id || c.reference_mobile).length;
    const topReferrers = customers
      .map(c => ({
        ...c,
        referralCount: customers.filter(cu => cu.reference_customer_id === c.id || (cu.reference_mobile === c.mobile && cu.id !== c.id)).length,
      }))
      .filter(c => c.referralCount > 0)
      .sort((a, b) => b.referralCount - a.referralCount)
      .slice(0, 5);
    return { total, totalDue, dueCustomers, totalBalance, totalReferrals, topReferrers };
  }, [customers]);

  const saveMutation = useMutation({
    mutationFn: async () => {
      if (!form.name.trim() || !form.mobile.trim()) {
        throw new Error(tr("nameAndMobileRequired"));
      }
      // Resolve reference_customer_id from reference_mobile
      let reference_customer_id: string | null = null;
      if (form.reference_mobile.trim()) {
        const { data: refCustomer } = await supabase
          .from("customers").select("id").eq("mobile", form.reference_mobile.trim()).is("deleted_at", null).maybeSingle();
        if (refCustomer) {
          reference_customer_id = refCustomer.id;
        }
      }
      if (editId) {
        const updatePayload: any = {
          name: form.name.trim(), name_bn: form.name_bn.trim(),
          mobile: form.mobile.trim(), email: form.email.trim(),
          address: form.address.trim(), customer_type: form.customer_type,
          reference_mobile: form.reference_mobile.trim(),
          reference_customer_id, status: form.status,
          image_url: form.image_url || null,
        };
        if (isAdmin) updatePayload.opening_balance = Number(form.opening_balance) || 0;
        const { error } = await supabase.from("customers").update(updatePayload).eq("id", editId);
        if (error) throw error;
      } else {
        const { error } = await supabase.from("customers").insert({
          name: form.name.trim(), name_bn: form.name_bn.trim(),
          mobile: form.mobile.trim(), email: form.email.trim(),
          address: form.address.trim(), customer_type: form.customer_type,
          opening_balance: Number(form.opening_balance) || 0,
          current_balance: Number(form.opening_balance) || 0,
          reference_mobile: form.reference_mobile.trim(),
          reference_customer_id, status: form.status,
          image_url: form.image_url || null,
        });
        if (error) throw error;
      }
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["customers"] });
      toast.success(editId ? tr("customerUpdated") : tr("customerAdded"));
      closeModal();
    },
    onError: (e: any) => { console.error("Customer save error:", e); toast.error(tr("somethingWrong")); },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      // Check for transactions
      const { count } = await supabase
        .from("customer_transactions").select("id", { count: "exact", head: true })
        .eq("customer_id", id);
      if (count && count > 0) {
        throw new Error("HAS_TRANSACTIONS");
      }
      const { error } = await supabase.from("customers")
        .update({ deleted_at: new Date().toISOString() }).eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["customers"] });
      toast.success(tr("customerDeleted"));
      setDeleteId(null);
    },
    onError: (e: any) => {
      if (e.message === "HAS_TRANSACTIONS") {
        toast.error(tr("cannotDeleteCustomerWithTransactions"));
      } else {
        console.error("Customer delete error:", e);
        toast.error(tr("somethingWrong"));
      }
      setDeleteId(null);
    },
  });

  const paymentMutation = useMutation({
    mutationFn: async () => {
      if (!viewCustomer || paymentForm.amount <= 0) {
        throw new Error("Invalid payment");
      }
      const { error: txError } = await supabase.from("customer_transactions").insert({
        customer_id: viewCustomer.id,
        type: "payment",
        amount: paymentForm.amount,
        method: paymentForm.method,
        note: paymentForm.note.trim(),
      });
      if (txError) throw txError;

      // Update customer balance
      const newBalance = Number(viewCustomer.current_balance) + paymentForm.amount;
      const newDue = Math.max(0, Number(viewCustomer.total_due) - paymentForm.amount);
      const { error: updError } = await supabase.from("customers").update({
        current_balance: newBalance,
        total_due: newDue,
      }).eq("id", viewCustomer.id);
      if (updError) throw updError;
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["customers"] });
      qc.invalidateQueries({ queryKey: ["customer_transactions", viewCustomer?.id] });
      // Refresh viewCustomer
      if (viewCustomer) {
        const updated = {
          ...viewCustomer,
          current_balance: Number(viewCustomer.current_balance) + paymentForm.amount,
          total_due: Math.max(0, Number(viewCustomer.total_due) - paymentForm.amount),
        };
        setViewCustomer(updated);
      }
      toast.success(tr("paymentRecorded"));
      setPaymentModalOpen(false);
      setPaymentForm(emptyPayment);
    },
    onError: (e: any) => { console.error("Payment error:", e); toast.error(tr("somethingWrong")); },
  });

  const openEdit = (c: Customer) => {
    setEditId(c.id);
    setForm({
      name: c.name, name_bn: c.name_bn, mobile: c.mobile, email: c.email || "",
      address: c.address || "", customer_type: c.customer_type,
      opening_balance: c.opening_balance, reference_mobile: c.reference_mobile || "",
      status: c.status, image_url: c.image_url || "",
    });
    setModalOpen(true);
  };

  const closeModal = () => { setModalOpen(false); setEditId(null); setForm(emptyForm); };

  const filtered = useMemo(() => {
    return customers.filter((c) => {
      const q = search.toLowerCase();
      const matchSearch = !q || c.name.toLowerCase().includes(q) || c.mobile.includes(q) || (c.name_bn && c.name_bn.includes(q));
      const matchType = typeFilter === "all" || c.customer_type === typeFilter;
      const matchStatus = statusFilter === "all" || c.status === statusFilter;
      const matchDue = dueFilter === "all" || (dueFilter === "due" && Number(c.total_due) > 0) || (dueFilter === "noDue" && Number(c.total_due) === 0);
      return matchSearch && matchType && matchStatus && matchDue;
    });
  }, [customers, search, typeFilter, statusFilter, dueFilter]);

  const filteredTx = useMemo(() => {
    if (txFilter === "all") return transactions;
    return transactions.filter(t => t.type === txFilter);
  }, [transactions, txFilter]);

  const displayName = (c: Customer) => lang === "bn" && c.name_bn ? c.name_bn : c.name;

  const getReferralDisplay = (c: Customer) => {
    if (!c.reference_mobile) return null;
    const referrer = customers.find(cu => cu.mobile === c.reference_mobile && cu.id !== c.id);
    return referrer ? displayName(referrer) : c.reference_mobile;
  };

  const totalPages = Math.max(1, Math.ceil(filtered.length / perPage));
  const paginatedCustomers = filtered.slice((page - 1) * perPage, page * perPage);
  const setSearchAndReset = (v: string) => { setSearch(v); setPage(1); };

  const toggleStatusMutation = useMutation({
    mutationFn: async ({ id, newStatus }: { id: string; newStatus: string }) => {
      const { error } = await supabase.from("customers").update({ status: newStatus }).eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["customers"] }); },
    onError: () => { toast.error(tr("somethingWrong")); },
  });

  const exportToCSV = () => {
    const headers = [tr("name"), tr("mobile"), tr("customerType"), tr("referenceMobile"), tr("currentBalance"), tr("totalDue"), tr("status")];
    const rows = filtered.map(c => [
      c.name, c.mobile, c.customer_type, c.reference_mobile || "", String(c.current_balance), String(c.total_due), c.status,
    ]);
    const csv = [headers, ...rows].map(r => r.map(v => `"${v}"`).join(",")).join("\n");
    const blob = new Blob(["\uFEFF" + csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = "customers.csv"; a.click();
    URL.revokeObjectURL(url);
  };

  // ===== PROFILE VIEW =====
  if (viewCustomer) {
    const c = viewCustomer;
    const saleTxs = transactions.filter(t => t.type === "sale");
    const totalPurchase = saleTxs.reduce((s, t) => s + Number(t.amount), 0);
    const totalPaid = transactions.filter(t => t.type === "payment").reduce((s, t) => s + Number(t.amount), 0);
    const now = Date.now();
    const monthAgo = now - 30 * 86400000;
    const monthlyOrders = saleTxs.filter(t => new Date(t.created_at).getTime() >= monthAgo).length;
    const lastPurchaseDate = saleTxs.length
      ? saleTxs.reduce((m, t) => (new Date(t.created_at).getTime() > new Date(m).getTime() ? t.created_at : m), saleTxs[0].created_at)
      : null;
    let thresholds: SegmentThresholds = DEFAULT_THRESHOLDS;
    try {
      const raw = typeof window !== "undefined" ? localStorage.getItem("customer-segment-thresholds") : null;
      if (raw) thresholds = { ...DEFAULT_THRESHOLDS, ...JSON.parse(raw) };
    } catch {}
    const segment = computeSegment(
      { created_at: c.created_at, totalPurchase, monthlyOrders, lastPurchaseDate },
      thresholds,
    );
    
    

    // Find referrer from loaded customers
    const referrer = c.reference_customer_id ? customers.find(cu => cu.id === c.reference_customer_id) : (c.reference_mobile ? customers.find(cu => cu.mobile === c.reference_mobile) : null);
    // Find customers referred by this customer
    const referrals = customers.filter(cu => cu.reference_customer_id === c.id || (cu.reference_mobile === c.mobile && cu.id !== c.id));

    return (
      <PageLayout>
        <div className="flex flex-wrap items-center justify-between gap-3 mb-6">
          <Button variant="ghost" className="gap-2" onClick={() => { setViewCustomer(null); setTxFilter("all"); }}>
            <ArrowLeft className="h-4 w-4" /> {tr("backToList")}
          </Button>
          <div className="flex gap-2">
            <Button variant="outline" className="gap-2" onClick={() => { setPaymentForm(emptyPayment); setPaymentModalOpen(true); }}>
              <CreditCard className="h-4 w-4" /> {tr("recordPayment")}
            </Button>
            <Button variant="outline" className="gap-2" onClick={() => openEdit(c)}>
              <Pencil className="h-4 w-4" /> {tr("editCustomer")}
            </Button>
          </div>
        </div>

        {/* Basic Info + Account Summary */}
        <div className="grid gap-6 md:grid-cols-2">
          <div className="rounded-xl border border-border bg-card p-5">
            <h2 className="mb-4 text-lg font-bold text-foreground">🧾 {tr("basicInfo")}</h2>
            <div className="mb-4 flex items-center gap-4">
              <Avatar className="h-20 w-20 border border-border">
                {c.image_url ? <AvatarImage src={c.image_url} alt={displayName(c)} /> : null}
                <AvatarFallback className="text-xl">{(c.name || "?").charAt(0).toUpperCase()}</AvatarFallback>
              </Avatar>
              <div>
                <p className="text-base font-semibold text-foreground">{displayName(c)}</p>
                <p className="text-xs text-muted-foreground">{c.mobile}</p>
              </div>
            </div>
            <div className="space-y-2.5 text-sm">
              <p><span className="text-muted-foreground">{tr("name")}:</span> <strong className="text-foreground">{displayName(c)}</strong></p>
              <p className="flex items-center gap-1.5"><Phone className="h-3.5 w-3.5 text-muted-foreground" /> {c.mobile}</p>
              {c.email && <p className="flex items-center gap-1.5"><Mail className="h-3.5 w-3.5 text-muted-foreground" /> {c.email}</p>}
              {c.address && <p className="flex items-center gap-1.5"><MapPin className="h-3.5 w-3.5 text-muted-foreground" /> {c.address}</p>}
              <p><span className="text-muted-foreground">{tr("customerType")}:</span>{" "}
                <Badge variant={c.customer_type === "wholesale" ? "default" : "secondary"}>
                  {c.customer_type === "wholesale" ? tr("wholesale") : tr("retail")}
                </Badge>
              </p>
              {c.reference_mobile && (
                <p><span className="text-muted-foreground">{tr("referenceMobile")}:</span> {c.reference_mobile}
                  {referrer && <span className="ml-1 text-primary">({displayName(referrer)})</span>}
                </p>
              )}
              <p className="flex items-center gap-2"><span className="text-muted-foreground">{lang === "bn" ? "কাস্টমার সেগমেন্ট" : "Customer Segment"}:</span> <SegmentBadge segment={segment} isBn={lang === "bn"} size="md" /></p>
              <p><span className="text-muted-foreground">{tr("status")}:</span>{" "}
                <Badge variant={c.status === "active" ? "default" : "secondary"}>
                  {c.status === "active" ? tr("active") : tr("inactive")}
                </Badge>
              </p>
              <p className="text-xs text-muted-foreground">{tr("memberSince")}: {new Date(c.created_at).toLocaleDateString(lang === "bn" ? "bn-BD" : "en-US")}</p>
            </div>
          </div>

          <div className="rounded-xl border border-border bg-card p-5">
            <h2 className="mb-4 text-lg font-bold text-foreground">💰 {tr("accountSummary")}</h2>
            {(() => {
              const opening = Number(c.opening_balance) || 0;
              const walletBal = Number((customerWallet as any)?.balance || 0);
              const walletAdj = (dueAdjustments as any[]).reduce((s, d) => s + Number(d.amount || 0), 0);
              const currentDue = Math.max(0, opening + totalPurchase - totalPaid - walletAdj);
              const netBalance = walletBal - currentDue;
              return (
                <div className="grid grid-cols-2 gap-3">
                  <SummaryCard label={lang === "bn" ? "ওপেনিং ব্যালেন্স" : "Opening Balance"} value={opening} />
                  <SummaryCard label={tr("totalPurchase")} value={totalPurchase} />
                  <SummaryCard label={tr("totalPaid")} value={totalPaid} color="text-green-600" />
                  <SummaryCard label={lang === "bn" ? "ওয়ালেট সমন্বয়" : "Wallet Adjustment"} value={walletAdj} color="text-amber-600" />
                  <SummaryCard label={lang === "bn" ? "রেফারেল ওয়ালেট" : "Referral Wallet"} value={walletBal} color="text-blue-600" />
                  <SummaryCard label={lang === "bn" ? "বর্তমান ডিউ" : "Current Due"} value={currentDue} color="text-red-500" />
                  <div className="col-span-2 rounded-lg bg-primary/10 p-3 text-center">
                    <p className="text-xs text-muted-foreground">{lang === "bn" ? "নেট ব্যালেন্স" : "Net Balance"}</p>
                    <p className={`text-xl font-bold ${netBalance >= 0 ? "text-primary" : "text-red-500"}`}>৳{netBalance.toLocaleString()}</p>
                    <p className="text-[10px] text-muted-foreground mt-1">{lang === "bn" ? "ফর্মুলা" : "Formula"}: (Opening + Purchase) − Paid − Wallet Adj</p>
                  </div>
                </div>
              );
            })()}
          </div>
        </div>

        {/* Order Status Stats */}
        <CustomerOrderStats customerId={c.id} isBn={lang === "bn"} />

        {/* Segment History */}
        <div className="mt-6 rounded-xl border border-border bg-card p-5">
          <h2 className="mb-3 text-base font-bold text-foreground">📜 {lang === "bn" ? "সেগমেন্ট ইতিহাস" : "Segment History"}</h2>
          {segmentLogs.length === 0 ? (
            <p className="text-sm text-muted-foreground">{lang === "bn" ? "কোনো পরিবর্তন রেকর্ড হয়নি" : "No segment changes recorded yet"}</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-border text-left text-xs text-muted-foreground">
                    <th className="px-3 py-2 font-medium">{lang === "bn" ? "তারিখ" : "Date"}</th>
                    <th className="px-3 py-2 font-medium">{lang === "bn" ? "পূর্বের" : "Previous"}</th>
                    <th className="px-3 py-2 font-medium">{lang === "bn" ? "নতুন" : "New"}</th>
                    <th className="px-3 py-2 font-medium">{lang === "bn" ? "কারণ" : "Reason"}</th>
                  </tr>
                </thead>
                <tbody>
                  {(segmentLogs as any[]).map((l) => (
                    <tr key={l.id} className="border-b border-border last:border-0">
                      <td className="px-3 py-2 text-xs text-muted-foreground">
                        {new Date(l.created_at).toLocaleString(lang === "bn" ? "bn-BD" : "en-GB")}
                      </td>
                      <td className="px-3 py-2">
                        {l.old_segment ? <SegmentBadge segment={l.old_segment} isBn={lang === "bn"} /> : <span className="text-xs text-muted-foreground">—</span>}
                      </td>
                      <td className="px-3 py-2">
                        <SegmentBadge segment={l.new_segment} isBn={lang === "bn"} />
                      </td>
                      <td className="px-3 py-2 text-xs text-muted-foreground">{l.reason}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>



        {/* Referral Info Section */}
        <div className="mt-6 rounded-xl border border-border bg-card p-5">
          <h2 className="mb-3 text-base font-bold text-foreground">🔗 {tr("referralSection")}</h2>

          {/* Referred By */}
          {referrer && (
            <div className="mb-4 rounded-lg bg-muted/50 px-3 py-2">
              <p className="text-xs text-muted-foreground mb-1">{tr("referredBy")}</p>
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium text-sm">{displayName(referrer)}</p>
                  <p className="text-xs text-muted-foreground">{referrer.mobile}</p>
                </div>
                <Button size="sm" variant="ghost" onClick={() => setViewCustomer(referrer)}>
                  <Eye className="h-3.5 w-3.5" />
                </Button>
              </div>
            </div>
          )}

          {/* Commission Summary */}
          {customerCommissions.length > 0 && (
            <div className="mb-4 grid grid-cols-2 gap-3">
              <div className="rounded-lg bg-green-500/10 p-3 text-center">
                <p className="text-xs text-muted-foreground">{tr("totalCommissionEarned")}</p>
                <p className="text-lg font-bold text-green-600">৳{customerCommissions.reduce((s: number, c: any) => s + Number(c.amount), 0).toLocaleString()}</p>
              </div>
              <div className="rounded-lg bg-primary/10 p-3 text-center">
                <p className="text-xs text-muted-foreground">{tr("totalReferrals")}</p>
                <p className="text-lg font-bold text-primary">{referrals.length}</p>
              </div>
            </div>
          )}

          {/* Referred Customers List */}
          {referrals.length > 0 ? (
            <>
              <h3 className="mb-2 text-sm font-semibold text-foreground">{tr("referredCustomers")} ({referrals.length})</h3>
              <div className="space-y-2">
                {referrals.map(r => {
                  const rTotalPurchase = Number(r.total_due) + Number(r.current_balance) - Number(r.opening_balance);
                  return (
                    <div key={r.id} className="flex items-center justify-between rounded-lg bg-muted/50 px-3 py-2 text-sm">
                      <div>
                        <p className="font-medium">{displayName(r)}</p>
                        <p className="text-xs text-muted-foreground">{r.mobile}</p>
                      </div>
                      <div className="flex items-center gap-3">
                        <span className="text-xs text-muted-foreground">{tr("totalPurchase")}: ৳{Math.abs(rTotalPurchase).toLocaleString()}</span>
                        <Button size="sm" variant="ghost" onClick={() => setViewCustomer(r)}>
                          <Eye className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          ) : (
            <p className="text-sm text-muted-foreground">{tr("noReferrals")}</p>
          )}
        </div>

        {/* Transaction / Ledger History */}
        <div className="mt-6 rounded-xl border border-border bg-card">
          <div className="border-b border-border px-5 py-3 flex flex-wrap items-center justify-between gap-3">
            <h2 className="text-base font-bold text-foreground">📊 {tr("transactionHistory")}</h2>
            <Select value={txFilter} onValueChange={setTxFilter}>
              <SelectTrigger className="w-[140px] h-8 text-xs"><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">{tr("allTypes")}</SelectItem>
                <SelectItem value="sale">{tr("saleBtn")}</SelectItem>
                <SelectItem value="payment">{tr("paymentLabel")}</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{tr("date")}</TableHead>
                <TableHead>{tr("type")}</TableHead>
                <TableHead>{tr("amount")}</TableHead>
                <TableHead>{tr("paymentMethod")}</TableHead>
                <TableHead>{tr("note")}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredTx.length === 0 ? (
                <TableRow><TableCell colSpan={5} className="text-center text-muted-foreground py-8">{tr("noTransactions")}</TableCell></TableRow>
              ) : filteredTx.map((t) => (
                <TableRow key={t.id}>
                  <TableCell className="text-xs">{new Date(t.created_at).toLocaleDateString(lang === "bn" ? "bn-BD" : "en-US")}</TableCell>
                  <TableCell>
                    <Badge variant={t.type === "payment" ? "default" : "destructive"}>
                      {t.type === "sale" ? tr("saleBtn") : tr("paymentLabel")}
                    </Badge>
                  </TableCell>
                  <TableCell className={`font-semibold ${t.type === "payment" ? "text-green-600" : "text-red-500"}`}>
                    {t.type === "payment" ? "+" : "-"}৳{Number(t.amount).toLocaleString()}
                  </TableCell>
                  <TableCell className="text-xs capitalize">{t.method || "-"}</TableCell>
                  <TableCell className="text-xs text-muted-foreground max-w-[200px] truncate">{t.note || "-"}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>

        {/* Payment Modal */}
        <Dialog open={paymentModalOpen} onOpenChange={(o) => { if (!o) setPaymentModalOpen(false); }}>
          <DialogContent className="max-w-md">
            <DialogHeader>
              <DialogTitle>💳 {tr("recordPayment")} — {displayName(c)}</DialogTitle>
            </DialogHeader>
            <div className="grid gap-4 py-2">
              <div>
                <label className="text-xs font-medium text-muted-foreground">{tr("amount")} (৳) *</label>
                <Input type="number" min={1} value={paymentForm.amount || ""} onChange={(e) => setPaymentForm({ ...paymentForm, amount: Number(e.target.value) })} />
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground">{tr("paymentMethod")}</label>
                <Select value={paymentForm.method} onValueChange={(v) => setPaymentForm({ ...paymentForm, method: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="cash">{tr("cash")}</SelectItem>
                    <SelectItem value="bkash">{tr("bkash")}</SelectItem>
                    <SelectItem value="card">{tr("card")}</SelectItem>
                    <SelectItem value="bank_transfer">{tr("bankTransfer")}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground">{tr("note")}</label>
                <Textarea rows={2} value={paymentForm.note} onChange={(e) => setPaymentForm({ ...paymentForm, note: e.target.value })} placeholder={tr("paymentNotePlaceholder")} />
              </div>
              <div className="rounded-lg bg-muted/50 p-3 text-sm">
                <p>{tr("currentDue")}: <strong className="text-red-500">৳{Number(c.total_due).toLocaleString()}</strong></p>
                {paymentForm.amount > 0 && (
                  <p className="mt-1">{tr("afterPayment")}: <strong className="text-green-600">৳{Math.max(0, Number(c.total_due) - paymentForm.amount).toLocaleString()}</strong></p>
                )}
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setPaymentModalOpen(false)}>{tr("cancel")}</Button>
              <Button onClick={() => paymentMutation.mutate()} disabled={paymentMutation.isPending || paymentForm.amount <= 0}>
                {paymentMutation.isPending ? tr("saving") : tr("recordPayment")}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </PageLayout>
    );
  }

  // ===== LIST VIEW =====
  return (
    <PageLayout>
      <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-xl font-bold text-foreground">{tr("customers")}</h1>
          <p className="text-sm text-muted-foreground">{tr("customerSubtitle")}</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" className="gap-2" onClick={exportToCSV}>
            <Download className="h-4 w-4" /> {tr("export")}
          </Button>
          <Button className="gap-2" onClick={() => { setForm(emptyForm); setEditId(null); setModalOpen(true); }}>
            <Plus className="h-4 w-4" /> {tr("addCustomer")}
          </Button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="mb-5 grid grid-cols-2 md:grid-cols-4 gap-3">
        <StatCard icon={<Users className="h-5 w-5 text-primary" />} label={tr("totalCustomers")} value={stats.total} />
        <StatCard icon={<DollarSign className="h-5 w-5 text-green-600" />} label={tr("totalBalanceLabel")} value={`৳${stats.totalBalance.toLocaleString()}`} />
        <StatCard icon={<TrendingDown className="h-5 w-5 text-red-500" />} label={tr("totalDue")} value={`৳${stats.totalDue.toLocaleString()}`} />
        <StatCard icon={<AlertTriangle className="h-5 w-5 text-amber-500" />} label={tr("dueCustomers")} value={stats.dueCustomers} />
      </div>

      {/* Filters */}
      <div className="mb-4 flex flex-wrap gap-3">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input className="pl-9" placeholder={tr("searchCustomer")} value={search} onChange={(e) => setSearchAndReset(e.target.value)} />
        </div>
        <Select value={typeFilter} onValueChange={setTypeFilter}>
          <SelectTrigger className="w-[140px]"><SelectValue /></SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{tr("allTypes")}</SelectItem>
            <SelectItem value="retail">{tr("retail")}</SelectItem>
            <SelectItem value="wholesale">{tr("wholesale")}</SelectItem>
          </SelectContent>
        </Select>
        <Select value={dueFilter} onValueChange={setDueFilter}>
          <SelectTrigger className="w-[140px]"><SelectValue /></SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{tr("allDue")}</SelectItem>
            <SelectItem value="due">{tr("hasDue")}</SelectItem>
            <SelectItem value="noDue">{tr("noDue")}</SelectItem>
          </SelectContent>
        </Select>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-[140px]"><SelectValue /></SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{tr("allStatus")}</SelectItem>
            <SelectItem value="active">{tr("active")}</SelectItem>
            <SelectItem value="inactive">{tr("inactive")}</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Table */}
      <div className="rounded-xl border border-border bg-card">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{tr("name")}</TableHead>
              <TableHead>{tr("mobile")}</TableHead>
              <TableHead>{tr("customerType")}</TableHead>
              <TableHead>{tr("referenceMobile")}</TableHead>
              <TableHead className="text-right">{tr("currentBalance")}</TableHead>
              <TableHead className="text-right">{tr("totalDue")}</TableHead>
              <TableHead>{tr("status")}</TableHead>
              <TableHead>{tr("action")}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <TableRow><TableCell colSpan={8} className="text-center py-8 text-muted-foreground">{tr("loading")}</TableCell></TableRow>
            ) : paginatedCustomers.length === 0 ? (
              <TableRow><TableCell colSpan={8} className="text-center py-8 text-muted-foreground">{tr("noCustomers")}</TableCell></TableRow>
            ) : paginatedCustomers.map((c) => (
              <TableRow key={c.id} className={Number(c.total_due) > 0 ? "bg-red-500/5" : ""}>
                <TableCell>
                  <button className="flex items-center gap-2 text-left hover:underline" onClick={() => setViewCustomer(c)}>
                    <Avatar className="h-8 w-8 border border-border shrink-0">
                      {c.image_url ? <AvatarImage src={c.image_url} alt={displayName(c)} /> : null}
                      <AvatarFallback className="text-xs">{(c.name || "?").charAt(0).toUpperCase()}</AvatarFallback>
                    </Avatar>
                    <div className="min-w-0">
                      <p className="font-medium text-primary truncate">{displayName(c)}</p>
                      {c.address && <p className="text-xs text-muted-foreground truncate max-w-[150px]">{c.address}</p>}
                    </div>
                  </button>
                </TableCell>
                <TableCell className="text-sm">{c.mobile}</TableCell>
                <TableCell>
                  <Badge variant={c.customer_type === "wholesale" ? "default" : "secondary"}>
                    {c.customer_type === "wholesale" ? tr("wholesale") : tr("retail")}
                  </Badge>
                </TableCell>
                <TableCell className="text-sm text-muted-foreground">{getReferralDisplay(c) || "-"}</TableCell>
                <TableCell className="text-right font-semibold">৳{Number(c.current_balance).toLocaleString()}</TableCell>
                <TableCell className={`text-right font-semibold ${Number(c.total_due) > 0 ? "text-red-500" : ""}`}>
                  {Number(c.total_due) > 0 ? `৳${Number(c.total_due).toLocaleString()}` : "-"}
                </TableCell>
                <TableCell>
                  <Switch
                    checked={c.status === "active"}
                    onCheckedChange={(checked) => toggleStatusMutation.mutate({ id: c.id, newStatus: checked ? "active" : "inactive" })}
                  />
                </TableCell>
                <TableCell>
                  <div className="flex gap-1">
                    <Button size="icon" variant="ghost" title={tr("viewProfile")} onClick={() => setViewCustomer(c)}><Eye className="h-4 w-4" /></Button>
                    <Button size="icon" variant="ghost" onClick={() => openEdit(c)}><Pencil className="h-4 w-4" /></Button>
                    <Button size="icon" variant="ghost" className="text-destructive" onClick={() => setDeleteId(c.id)}><Trash2 className="h-4 w-4" /></Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <span>{tr("showing")} {((page - 1) * perPage) + 1}-{Math.min(page * perPage, filtered.length)} / {filtered.length}</span>
          <Select value={String(perPage)} onValueChange={(v) => { setPerPage(Number(v)); setPage(1); }}>
            <SelectTrigger className="w-[80px] h-8 text-xs"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="10">10</SelectItem>
              <SelectItem value="20">20</SelectItem>
              <SelectItem value="50">50</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="flex items-center gap-1">
          <Button size="icon" variant="outline" className="h-8 w-8" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <span className="px-3 text-sm">{page} / {totalPages}</span>
          <Button size="icon" variant="outline" className="h-8 w-8" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>
            <ChevronRight className="h-4 w-4" />
          </Button>
        </div>
      </div>

      <Dialog open={modalOpen} onOpenChange={(o) => { if (!o) closeModal(); }}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>{editId ? tr("editCustomer") : tr("addCustomer")}</DialogTitle>
          </DialogHeader>
          <div className="grid gap-4 py-2">
            <div className="flex items-center gap-4">
              <Avatar className="h-20 w-20 border border-border">
                {form.image_url ? <AvatarImage src={form.image_url} alt="customer" /> : null}
                <AvatarFallback className="text-lg">
                  {(form.name || "?").charAt(0).toUpperCase()}
                </AvatarFallback>
              </Avatar>
              <div className="flex flex-col gap-2">
                <label className="text-xs font-medium text-muted-foreground">
                  {lang === "bn" ? "কাস্টমার ছবি" : "Customer Photo"}
                </label>
                <div className="flex gap-2">
                  <label className="inline-flex items-center gap-1.5 cursor-pointer rounded-md border border-input bg-background px-3 py-1.5 text-xs hover:bg-muted">
                    <Upload className="h-3.5 w-3.5" />
                    {uploadingImage
                      ? (lang === "bn" ? "আপলোড হচ্ছে..." : "Uploading...")
                      : (lang === "bn" ? "ছবি আপলোড" : "Upload Image")}
                    <input
                      type="file"
                      accept="image/*"
                      className="hidden"
                      disabled={uploadingImage}
                      onChange={(e) => {
                        const f = e.target.files?.[0];
                        if (f) handleImageUpload(f);
                        e.target.value = "";
                      }}
                    />
                  </label>
                  {form.image_url && (
                    <Button type="button" size="sm" variant="ghost" className="h-8 gap-1 text-destructive"
                      onClick={async () => { const prev = form.image_url; setForm({ ...form, image_url: "" }); await removeCustomerImageFile(prev); }}>
                      <X className="h-3.5 w-3.5" /> {tr("remove") || (lang === "bn" ? "মুছুন" : "Remove")}
                    </Button>
                  )}
                </div>
                <p className="text-[10px] text-muted-foreground">JPG / PNG, max 5MB</p>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="text-xs font-medium text-muted-foreground">{tr("name")} (English) *</label>
                <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground">{tr("name")} (বাংলা)</label>
                <Input value={form.name_bn} onChange={(e) => setForm({ ...form, name_bn: e.target.value })} />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="text-xs font-medium text-muted-foreground">{tr("mobile")} *</label>
                <Input value={form.mobile} onChange={(e) => setForm({ ...form, mobile: e.target.value })} />
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground">{tr("email")}</label>
                <Input value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
              </div>
            </div>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{tr("address")}</label>
              <Input value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="text-xs font-medium text-muted-foreground">{tr("customerType")}</label>
                <Select value={form.customer_type} onValueChange={(v) => setForm({ ...form, customer_type: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="retail">{tr("retail")}</SelectItem>
                    <SelectItem value="wholesale">{tr("wholesale")}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground">{tr("status")}</label>
                <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">{tr("active")}</SelectItem>
                    <SelectItem value="inactive">{tr("inactive")}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              {(!editId || isAdmin) && (
                <div>
                  <label className="text-xs font-medium text-muted-foreground">
                    {tr("openingBalance")} {editId && isAdmin && <span className="text-amber-600">({lang === "bn" ? "এডমিন" : "Admin"})</span>}
                  </label>
                  <Input type="number" value={form.opening_balance} onChange={(e) => setForm({ ...form, opening_balance: Number(e.target.value) })} />
                </div>
              )}
              <div className={(!editId || isAdmin) ? "" : "col-span-2"}>
                <label className="text-xs font-medium text-muted-foreground">{tr("referenceMobile")}</label>
                <Input value={form.reference_mobile} onChange={(e) => setForm({ ...form, reference_mobile: e.target.value })} placeholder="01XXXXXXXXX" />
                {form.reference_mobile.trim().length >= 5 && (() => {
                  const match = customers.find(cu => cu.mobile === form.reference_mobile.trim() && cu.id !== editId);
                  if (match) return <p className="text-xs text-green-600 mt-1">✅ {tr("referrerFound")}: {displayName(match)}</p>;
                  if (form.reference_mobile.trim().length >= 11) return <p className="text-xs text-amber-500 mt-1">⚠️ {tr("referrerNotFound")}</p>;
                  return null;
                })()}
                {form.reference_mobile.trim().length >= 3 && form.reference_mobile.trim().length < 11 && (() => {
                  const suggestions = customers.filter(cu => cu.mobile.includes(form.reference_mobile.trim()) && cu.id !== editId).slice(0, 5);
                  if (suggestions.length === 0) return null;
                  return (
                    <div className="mt-1 rounded-md border border-border bg-popover shadow-sm max-h-32 overflow-auto">
                      {suggestions.map(s => (
                        <button key={s.id} type="button" className="w-full text-left px-3 py-1.5 text-xs hover:bg-muted/50 flex justify-between"
                          onClick={() => setForm({ ...form, reference_mobile: s.mobile })}>
                          <span className="font-medium">{displayName(s)}</span>
                          <span className="text-muted-foreground">{s.mobile}</span>
                        </button>
                      ))}
                    </div>
                  );
                })()}
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={closeModal}>{tr("cancel")}</Button>
            <Button onClick={() => saveMutation.mutate()} disabled={saveMutation.isPending}>
              {saveMutation.isPending ? tr("saving") : tr("save")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirm */}
      <AlertDialog open={!!deleteId} onOpenChange={(o) => { if (!o) setDeleteId(null); }}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{tr("confirmDelete")}</AlertDialogTitle>
            <AlertDialogDescription>{tr("deleteCustomerWarning")}</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{tr("cancel")}</AlertDialogCancel>
            <AlertDialogAction onClick={() => deleteId && deleteMutation.mutate(deleteId)} className="bg-destructive text-destructive-foreground">
              {tr("delete")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}

function SummaryCard({ label, value, color }: { label: string; value: number; color?: string }) {
  return (
    <div className="rounded-lg bg-muted/50 p-3 text-center">
      <p className="text-xs text-muted-foreground">{label}</p>
      <p className={`text-lg font-bold ${color || "text-foreground"}`}>৳{value.toLocaleString()}</p>
    </div>
  );
}

function StatCard({ icon, label, value }: { icon: React.ReactNode; label: string; value: string | number }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4 flex items-center gap-3">
      <div className="rounded-lg bg-muted/50 p-2">{icon}</div>
      <div>
        <p className="text-xs text-muted-foreground">{label}</p>
        <p className="text-lg font-bold text-foreground">{value}</p>
      </div>
    </div>
  );
}
