import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useState, useMemo, useCallback, useEffect, useRef } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useReceiptPrint } from "@/components/ReceiptPrint";
import { useAuth } from "@/hooks/use-auth";
import { toast } from "sonner";
import {
  Search,
  Trash2,
  Plus,
  Minus,
  Save,
  X,
  Printer,
  ShoppingCart,
  User,
  Phone,
  MapPin,
  CalendarDays,
  CreditCard,
  FileText,
  RotateCcw,
  ChevronDown,
  Package,
  RefreshCw,
  AlertTriangle,
  Banknote,
  Loader2,
  Replace,
  Gift,
} from "lucide-react";

export const Route = createFileRoute("/_authenticated/sales/create")({
  head: () => ({
    meta: [
      { title: "নতুন বিক্রয় — Niyamah ERP" },
      { name: "description", content: "নতুন বিক্রয় যোগ করুন" },
    ],
  }),
  component: SalesCreatePage,
});

type PricingRule = {
  id: string;
  unit_name: string;
  unit_name_bn: string;
  conversion_factor: number;
  price_type: string;
  min_qty: number;
  regular_price: number;
  purchase_price: number;
  offer_price: number | null;
  offer_percent: number | null;
  offer_start: string | null;
  offer_end: string | null;
  is_base_unit: boolean;
};

type AdvancedCartItem = {
  id: string;
  productId: string;
  name: string;
  nameBn: string;
  barcode: string;
  stock: number;
  unit: string;
  category: string;
  price: number;
  basePrice: number;
  purchasePrice: number; // base-unit cost price
  quantity: number;
  unitDiscount: number;
  warranty: string;
  priceType: string;
  selectedUnit: string;
  conversionFactor: number;
  pricingRules: PricingRule[];
  subcategoryId: string | null;
  subcategoryName: string;
  isFree?: boolean;
};


// Effective net selling price (after row discount) for the selected unit
function getNetUnitPrice(item: AdvancedCartItem): number {
  return item.price - item.unitDiscount;
}
// Effective cost price for the selected unit (base cost × conversion)
function getEffectiveCost(item: AdvancedCartItem): number {
  return (item.purchasePrice || 0) * (item.conversionFactor || 1);
}
// True when selling below cost
function isBelowCost(item: AdvancedCartItem): boolean {
  if (item.isFree) return false;
  const cost = getEffectiveCost(item);
  return cost > 0 && getNetUnitPrice(item) < cost;
}


function getEffectivePrice(rule: PricingRule): number {
  const now = new Date();
  const startOk = !rule.offer_start || new Date(rule.offer_start) <= now;
  const endOk = !rule.offer_end || new Date(rule.offer_end) >= now;
  if (startOk && endOk) {
    if (rule.offer_price && rule.offer_price > 0) return rule.offer_price;
    if (rule.offer_percent && rule.offer_percent > 0) return rule.regular_price * (1 - rule.offer_percent / 100);
  }
  return rule.regular_price;
}

function getBestPriceFromRules(rules: PricingRule[], qty: number, pType: string, unitName: string): number | null {
  const matching = rules
    .filter((r) => r.price_type === pType && r.unit_name === unitName && qty >= r.min_qty)
    .sort((a, b) => b.min_qty - a.min_qty);
  if (matching.length > 0) return getEffectivePrice(matching[0]);
  return null;
}

const WARRANTY_OPTIONS = ["No", "3 Month", "6 Month", "1 Year", "2 Year", "3 Year"];

function SalesCreatePage() {
  const { tr, lang } = useLanguage();
  const { printReceipt } = useReceiptPrint();
  const { user } = useAuth();

  // Admin check — controls whether below-cost sales can be overridden
  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 [customer, setCustomer] = useState("");
  const [customerId, setCustomerId] = useState<string | null>(null);
  const [referenceCustomerId, setReferenceCustomerId] = useState<string | null>(null);
  const [customerType, setCustomerType] = useState<string>("retail");
  const [customerSearch, setCustomerSearch] = useState("");
  const [customerResults, setCustomerResults] = useState<any[]>([]);
  const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
  const customerDropdownRef = useRef<HTMLDivElement>(null);
  const [phone, setPhone] = useState("");
  const [address, setAddress] = useState("");
  const [saleMan, setSaleMan] = useState("");
  const [saleStatus, setSaleStatus] = useState("completed");
  const [saleDate, setSaleDate] = useState<string>(new Date().toLocaleDateString("en-GB"));
  // Customer search from database
  useEffect(() => {
    if (customerSearch.length < 2) {
      setCustomerResults([]);
      return;
    }
    const timer = setTimeout(async () => {
      const q = customerSearch.trim();
      const { data } = await supabase
        .from("customers")
        .select("id, name, name_bn, mobile, address, customer_type, reference_customer_id")
        .or(`name.ilike.%${q}%,name_bn.ilike.%${q}%,mobile.ilike.%${q}%`)
        .eq("status", "active")
        .is("deleted_at", null)
        .limit(8);
      setCustomerResults(data || []);
      setShowCustomerDropdown(true);
    }, 300);
    return () => clearTimeout(timer);
  }, [customerSearch]);

  // Close dropdown on outside click
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (customerDropdownRef.current && !customerDropdownRef.current.contains(e.target as Node)) {
        setShowCustomerDropdown(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const selectCustomer = (c: any) => {
    setCustomer(lang === "bn" ? c.name_bn || c.name : c.name);
    setCustomerId(c.id);
    setReferenceCustomerId(c.reference_customer_id || null);
    setPhone(c.mobile || "");
    setAddress(c.address || "");
    setCustomerSearch("");
    setShowCustomerDropdown(false);
    const ctype = c.customer_type === "wholesale" ? "wholesale" : "retail";
    setCustomerType(ctype);
    // Re-apply price for all cart items based on new customer type
    setCart((prev) => prev.map((item) => {
      if (item.isFree) return item;
      const newPrice = getBestPriceFromRules(item.pricingRules, item.quantity, ctype, item.selectedUnit) ?? item.basePrice * item.conversionFactor;
      return { ...item, priceType: ctype, price: newPrice };
    }));

  };

  const [searchTerm, setSearchTerm] = useState("");
  const [cart, setCart] = useState<AdvancedCartItem[]>([]);
  const [discountPercent, setDiscountPercent] = useState(0);
  const [discountFlat, setDiscountFlat] = useState(0);
  const [showPayment, setShowPayment] = useState(false);
  const [showNotes, setShowNotes] = useState(false);
  const [showReturn, setShowReturn] = useState(false);
  const [paidAmount, setPaidAmount] = useState<number>(() => {
    if (typeof window === "undefined") return 0;
    const v = Number(window.localStorage.getItem("sales.create.paidAmount"));
    return Number.isFinite(v) && v >= 0 ? v : 0;
  });
  useEffect(() => {
    if (typeof window !== "undefined") {
      window.localStorage.setItem("sales.create.paidAmount", String(paidAmount));
    }
  }, [paidAmount]);
  const [paymentMethod, setPaymentMethod] = useState<string>(() => {
    if (typeof window === "undefined") return "নগদ";
    return window.localStorage.getItem("sales.create.paymentMethod") || "নগদ";
  });
  useEffect(() => {
    if (typeof window !== "undefined") {
      window.localStorage.setItem("sales.create.paymentMethod", paymentMethod);
    }
  }, [paymentMethod]);
  const [notes, setNotes] = useState<string>(() => {
    if (typeof window === "undefined") return "";
    return window.localStorage.getItem("sales.create.notes") || "";
  });
  useEffect(() => {
    if (typeof window !== "undefined") {
      window.localStorage.setItem("sales.create.notes", notes);
    }
  }, [notes]);

  const [expense, setExpense] = useState(0);

  const [subcatSearch, setSubcatSearch] = useState("");
  const [subcatHighlightIdx, setSubcatHighlightIdx] = useState(0);
  const [selectedSubcatKey, setSelectedSubcatKey] = useState<string | null>(null);
  const [showSubcatDropdown, setShowSubcatDropdown] = useState(false);
  // Per sub-category discount percentage (key -> %). Calculated in Order Summary, NOT shown on invoice.
  const [subcategoryDiscounts, setSubcategoryDiscounts] = useState<Record<string, number>>({});

  // Free Product Cost Distribution
  // Total monetary value of all free items (based on their original retail price).
  const freeCostTotal = useMemo(
    () => cart.reduce((s, it) => (it.isFree ? s + it.basePrice * it.quantity : s), 0),
    [cart]
  );
  // Total of paid (non-free) line amounts BEFORE distribution.
  const paidBaseTotal = useMemo(
    () => cart.reduce((s, it) => (it.isFree ? s : s + (it.price - it.unitDiscount) * it.quantity), 0),
    [cart]
  );
  // Per-cart-item extra amount distributed from free items, proportional to each
  // paid line's share of the paid base total.
  const freeShareMap = useMemo(() => {
    const map: Record<string, number> = {};
    if (freeCostTotal <= 0 || paidBaseTotal <= 0) return map;
    cart.forEach((it) => {
      if (it.isFree) { map[it.id] = 0; return; }
      const lineBase = (it.price - it.unitDiscount) * it.quantity;
      map[it.id] = (lineBase / paidBaseTotal) * freeCostTotal;
    });
    return map;
  }, [cart, freeCostTotal, paidBaseTotal]);

  // Sub-total now includes the free cost — it gets baked into paid items.
  const subTotal = useMemo(() => paidBaseTotal + freeCostTotal, [paidBaseTotal, freeCostTotal]);

  // Group cart by sub-category with per-group discount % / amount / final amount.
  const subcategoryGroups = useMemo(() => {
    const groups = new Map<string, { key: string; name: string; total: number; discountPercent: number; discountAmount: number; finalAmount: number }>();
    cart.forEach((item) => {
      if (item.isFree) return; // free items contribute via distribution to paid lines
      const key = item.subcategoryId || "__none__";
      const lineTotal = (item.price - item.unitDiscount) * item.quantity + (freeShareMap[item.id] || 0);
      const existing = groups.get(key);
      if (existing) {
        existing.total += lineTotal;
      } else {
        groups.set(key, { key, name: item.subcategoryName, total: lineTotal, discountPercent: 0, discountAmount: 0, finalAmount: 0 });
      }
    });
    // Apply per-group discount %
    groups.forEach((g) => {
      const pct = Math.max(0, Math.min(100, subcategoryDiscounts[g.key] || 0));
      g.discountPercent = pct;
      g.discountAmount = (g.total * pct) / 100;
      g.finalAmount = g.total - g.discountAmount;
    });
    return Array.from(groups.values());
  }, [cart, subcategoryDiscounts, freeShareMap]);

  const subcategoryDiscountTotal = useMemo(
    () => subcategoryGroups.reduce((s, g) => s + g.discountAmount, 0),
    [subcategoryGroups]
  );

  // Search-filtered groups for the table view
  const visibleSubcategoryGroups = useMemo(() => {
    let groups = subcategoryGroups;
    if (selectedSubcatKey) {
      groups = groups.filter((g) => g.key === selectedSubcatKey);
    } else if (subcatSearch.trim()) {
      const q = subcatSearch.trim().toLowerCase();
      groups = groups.filter((g) => g.name.toLowerCase().includes(q));
    }
    return groups;
  }, [subcategoryGroups, subcatSearch, selectedSubcatKey]);

  // Dropdown suggestion list (matches typed query, ignores the locked selection)
  const subcatSuggestions = useMemo(() => {
    const q = subcatSearch.trim().toLowerCase();
    if (!q) return subcategoryGroups;
    return subcategoryGroups.filter((g) => g.name.toLowerCase().includes(q));
  }, [subcategoryGroups, subcatSearch]);

  useEffect(() => {
    setSubcatHighlightIdx(0);
  }, [subcatSearch, subcategoryGroups.length]);

  const totalDiscount = useMemo(
    () => discountFlat + (subTotal * discountPercent) / 100 + subcategoryDiscountTotal,
    [subTotal, discountFlat, discountPercent, subcategoryDiscountTotal]
  );
  const grandTotal = useMemo(() => Math.max(0, subTotal - totalDiscount + expense), [subTotal, totalDiscount, expense]);
  const effectivePaid = useMemo(() => Math.min(Math.max(0, paidAmount), grandTotal), [paidAmount, grandTotal]);
  const dueAmount = useMemo(() => Math.max(0, grandTotal - effectivePaid), [grandTotal, effectivePaid]);

  // Filters
  const [filterTypeId, setFilterTypeId] = useState("");
  const [filterCategoryId, setFilterCategoryId] = useState("");
  const [filterSubcategoryId, setFilterSubcategoryId] = useState("");

  // Fetch filter options
  const { data: productTypes = [] } = useQuery({
    queryKey: ["product-types-filter"],
    queryFn: async () => {
      const { data } = await supabase.from("product_types").select("id, name, name_bn").eq("status", "active").order("name");
      return data || [];
    },
  });

  const { data: categories = [] } = useQuery({
    queryKey: ["categories-filter"],
    queryFn: async () => {
      const { data } = await supabase.from("categories").select("id, name, name_bn").eq("status", "active").is("deleted_at", null).order("name");
      return data || [];
    },
  });

  const { data: subcategories = [] } = useQuery({
    queryKey: ["subcategories-filter", filterCategoryId],
    queryFn: async () => {
      let query = supabase.from("subcategories").select("id, name, name_bn, category_id").eq("status", "active").is("deleted_at", null).order("name");
      if (filterCategoryId) query = query.eq("category_id", filterCategoryId);
      const { data } = await query;
      return data || [];
    },
  });

  // All subcategories (for cart name lookup, regardless of filter)
  const { data: allSubcategories = [] } = useQuery({
    queryKey: ["all-subcategories"],
    queryFn: async () => {
      const { data } = await supabase.from("subcategories").select("id, name, name_bn").is("deleted_at", null);
      return data || [];
    },
  });
  const subcategoryNameMap = useMemo(() => {
    const m = new Map<string, { name: string; name_bn: string }>();
    (allSubcategories as any[]).forEach((s) => m.set(s.id, { name: s.name, name_bn: s.name_bn || s.name }));
    return m;
  }, [allSubcategories]);

  // Product search from DB with filters
  const [dbProducts, setDbProducts] = useState<any[]>([]);
  useEffect(() => {
    const hasFilter = filterTypeId || filterCategoryId || filterSubcategoryId;
    if (!searchTerm && !hasFilter) { setDbProducts([]); return; }
    const timer = setTimeout(async () => {
      let query = supabase.from("products").select("*").eq("is_deleted", false);
      if (searchTerm) {
        const q = searchTerm.trim();
        query = query.or(`name.ilike.%${q}%,name_bn.ilike.%${q}%,sku.ilike.%${q}%,barcode.ilike.%${q}%`);
      }
      if (filterTypeId) query = query.eq("product_type_id", filterTypeId);
      if (filterCategoryId) query = query.eq("category_id", filterCategoryId);
      if (filterSubcategoryId) query = query.eq("subcategory_id", filterSubcategoryId);
      query = query.limit(12);
      const { data } = await query;
      setDbProducts(data || []);
    }, 300);
    return () => clearTimeout(timer);
  }, [searchTerm, filterTypeId, filterCategoryId, filterSubcategoryId]);

  // Free product search (separate, doesn't depend on filters)
  const [freeSearchTerm, setFreeSearchTerm] = useState("");
  const [freeDbProducts, setFreeDbProducts] = useState<any[]>([]);
  useEffect(() => {
    if (!freeSearchTerm) { setFreeDbProducts([]); return; }
    const timer = setTimeout(async () => {
      const q = freeSearchTerm.trim();
      const { data } = await supabase
        .from("products")
        .select("*")
        .eq("is_deleted", false)
        .or(`name.ilike.%${q}%,name_bn.ilike.%${q}%,sku.ilike.%${q}%,barcode.ilike.%${q}%`)
        .limit(10);
      setFreeDbProducts(data || []);
    }, 300);
    return () => clearTimeout(timer);
  }, [freeSearchTerm]);


  const filteredProducts = dbProducts;

  const addToCart = async (product: any, opts?: { asFree?: boolean }) => {
    const asFree = !!opts?.asFree;
    // Fetch unified pricing rules
    const { data: pricing } = await supabase
      .from("product_pricing")
      .select("*")
      .eq("product_id", product.id)
      .eq("is_active", true)
      .order("min_qty");
    const pricingRules: PricingRule[] = (pricing || []).map((r: any) => ({
      id: r.id,
      unit_name: r.unit_name,
      unit_name_bn: r.unit_name_bn,
      conversion_factor: Number(r.conversion_factor),
      price_type: r.price_type,
      min_qty: Number(r.min_qty),
      regular_price: Number(r.regular_price),
      purchase_price: Number(r.purchase_price),
      offer_price: r.offer_price ? Number(r.offer_price) : null,
      offer_percent: r.offer_percent ? Number(r.offer_percent) : null,
      offer_start: r.offer_start,
      offer_end: r.offer_end,
      is_base_unit: r.is_base_unit,
    }));

    // Also pull dedicated multi-unit definitions (PCS/BOX/...) and merge as retail+wholesale rules
    const { data: units } = await supabase
      .from("product_units")
      .select("unit_name, unit_name_bn, conversion_factor, price, retail_price, wholesale_price")
      .eq("product_id", product.id)
      .eq("is_active", true);
    const basePriceForFallback = Number(product.retail_price) || 0;
    const baseWholesaleForFallback = Number(product.wholesale_price) || 0;
    ((units as any[]) || []).forEach((u) => {
      const unitName = u.unit_name;
      const cf = Number(u.conversion_factor) || 1;
      const retail = Number(u.retail_price) || Number(u.price) || basePriceForFallback * cf;
      const wholesale = Number(u.wholesale_price) || baseWholesaleForFallback * cf || retail;
      if (!pricingRules.some((r) => r.unit_name === unitName && r.price_type === "retail")) {
        pricingRules.push({
          id: `unit-${unitName}-retail`, unit_name: unitName, unit_name_bn: u.unit_name_bn || unitName,
          conversion_factor: cf, price_type: "retail", min_qty: 1,
          regular_price: retail, purchase_price: 0,
          offer_price: null, offer_percent: null, offer_start: null, offer_end: null, is_base_unit: false,
        });
      }
      if (!pricingRules.some((r) => r.unit_name === unitName && r.price_type === "wholesale")) {
        pricingRules.push({
          id: `unit-${unitName}-wholesale`, unit_name: unitName, unit_name_bn: u.unit_name_bn || unitName,
          conversion_factor: cf, price_type: "wholesale", min_qty: 1,
          regular_price: wholesale, purchase_price: 0,
          offer_price: null, offer_percent: null, offer_start: null, offer_end: null, is_base_unit: false,
        });
      }
    });

    const fallbackBase = customerType === "wholesale"
      ? (Number(product.wholesale_price) || Number(product.retail_price) || 0)
      : (Number(product.retail_price) || 0);
    const initialUnit = "Piece";
    const regularInitialPrice = getBestPriceFromRules(pricingRules, 1, customerType, initialUnit) ?? fallbackBase;
    const initialPrice = asFree ? 0 : regularInitialPrice;
    // For free items keep the original retail value in basePrice so we can
    // distribute its cost across other paid items proportionally.
    const basePrice = asFree ? regularInitialPrice : initialPrice;

    const cartId = asFree ? `${product.id}::free` : product.id;
    const p: AdvancedCartItem = {
      id: cartId,
      productId: product.id,
      name: product.name,
      nameBn: product.name_bn || product.name,
      barcode: product.barcode || product.sku || "",
      stock: Number(product.stock_quantity) || 0,
      unit: product.unit || "pcs",
      category: "",
      price: initialPrice,
      basePrice,
      purchasePrice: Number(product.purchase_price) || 0,
      quantity: 1,
      unitDiscount: 0,
      warranty: "No",
      priceType: asFree ? "free" : customerType,
      selectedUnit: "Piece",
      conversionFactor: 1,
      pricingRules,
      subcategoryId: product.subcategory_id || null,
      subcategoryName: product.subcategory_id
        ? (lang === "bn"
            ? subcategoryNameMap.get(product.subcategory_id)?.name_bn || subcategoryNameMap.get(product.subcategory_id)?.name || "অন্যান্য"
            : subcategoryNameMap.get(product.subcategory_id)?.name || "Other")
        : (lang === "bn" ? "অন্যান্য" : "Uncategorized"),
      isFree: asFree,
    };
    setCart((prev) => {
      const existing = prev.find((item) => item.id === p.id);
      if (existing) {
        return prev.map((item) => item.id === p.id ? { ...item, quantity: item.quantity + 1 } : item);
      }
      return [...prev, p];
    });
    if (asFree) {
      setFreeSearchTerm("");
      setFreeDbProducts([]);
    } else {
      setSearchTerm("");
    }
  };


  const getBestPrice = (item: AdvancedCartItem, qty: number, pType: string) => {
    const result = getBestPriceFromRules(item.pricingRules, qty, pType, item.selectedUnit);
    return result ?? item.basePrice;
  };

  const updateQuantity = (id: string, delta: number) => {
    setCart((prev) =>
      prev.map((item) => {
        if (item.id !== id) return item;
        const newQty = Math.max(1, item.quantity + delta);
        if (item.isFree) return { ...item, quantity: newQty };
        const newPrice = getBestPrice(item, newQty, item.priceType);
        return { ...item, quantity: newQty, price: newPrice };
      })
    );
  };

  const updateUnitDiscount = (id: string, value: number) => {
    setCart((prev) =>
      prev.map((item) => {
        if (item.id !== id) return item;
        if (item.isFree) return item;
        return { ...item, unitDiscount: Math.max(0, Math.min(item.price, value)) };
      })
    );
  };

  const updateUnitDiscountPercent = (id: string, percent: number) => {
    setCart((prev) =>
      prev.map((item) => {
        if (item.id !== id) return item;
        if (item.isFree) return item;
        const p = Math.max(0, Math.min(100, percent));
        const tk = +(item.price * p / 100).toFixed(2);
        return { ...item, unitDiscount: tk };
      })
    );
  };

  const updateWarranty = (id: string, value: string) => {
    setCart((prev) =>
      prev.map((item) => item.id === id ? { ...item, warranty: value } : item)
    );
  };

  const updateQtyDirect = (id: string, value: number) => {
    setCart((prev) =>
      prev.map((item) => {
        if (item.id !== id) return item;
        const newQty = Math.max(1, value);
        if (item.isFree) return { ...item, quantity: newQty };
        const newPrice = getBestPrice(item, newQty, item.priceType);
        return { ...item, quantity: newQty, price: newPrice };
      })
    );
  };


  const updatePriceType = (id: string, pType: string) => {
    setCart((prev) =>
      prev.map((item) => {
        if (item.id !== id) return item;
        const newPrice = getBestPrice(item, item.quantity, pType);
        return { ...item, priceType: pType, price: newPrice };
      })
    );
  };

  const updateSelectedUnit = (id: string, unitName: string) => {
    setCart((prev) =>
      prev.map((item) => {
        if (item.id !== id) return item;
        const unitRules = item.pricingRules.filter((r) => r.unit_name === unitName);
        const cf = unitRules.length > 0 ? unitRules[0].conversion_factor : 1;
        const newPrice = getBestPriceFromRules(item.pricingRules, item.quantity, item.priceType, unitName) ?? item.basePrice * cf;
        return { ...item, selectedUnit: unitName, conversionFactor: cf, price: newPrice };
      })
    );
  };

  const removeFromCart = (id: string) => {
    setCart((prev) => prev.filter((item) => item.id !== id));
  };

  const handleSaveAndPrint = async () => {
    // Low Sale Price Alert — block non-admin or confirm with admin override
    const belowCostItems = cart.filter((it) => isBelowCost(it));
    if (belowCostItems.length > 0) {
      const names = belowCostItems.map((it) => (lang === "bn" ? it.nameBn : it.name)).join(", ");
      if (!isAdmin) {
        toast.error(
          isBn
            ? `⚠️ অনুমতি নেই! এই পণ্য ক্রয়মূল্যের নিচে বিক্রি করা যাবে না: ${names}। অ্যাডমিনের অনুমতি প্রয়োজন।`
            : `⚠️ Not allowed! Selling below purchase price requires admin override: ${names}.`,
          { duration: 6000 }
        );
        return;
      }
      const ok = window.confirm(
        isBn
          ? `⚠️ সতর্কতা!\nনিম্নলিখিত পণ্য ক্রয়মূল্যের নিচে বিক্রি হচ্ছে:\n${names}\n\nএতে লোকসান হতে পারে। চালিয়ে যেতে চান?`
          : `⚠️ Warning!\nSelling below purchase price for:\n${names}\n\nYou may incur a loss. Continue?`
      );
      if (!ok) return;
    }
    let invoiceNo: string;
    try {
      const { data: nextNo, error: nErr } = await supabase.rpc("next_invoice_no" as any);
      if (nErr || !nextNo) throw nErr || new Error("no number");
      invoiceNo = String(nextNo);
    } catch {
      invoiceNo = String(Date.now()).slice(-8).padStart(8, "0");
    }

    // Persist sale to DB
    try {
      const { data: saleRow, error: saleErr } = await supabase
        .from("sales" as any)
        .insert({
          invoice_no: invoiceNo,
          customer_id: customerId,
          customer_name: customer || "",
          customer_mobile: phone || "",
          customer_address: address || "",
          sale_man: saleMan || "",
          sale_date: new Date().toISOString().slice(0, 10),
          subtotal: subTotal,
          discount: totalDiscount,
          expense,
          total_amount: grandTotal,
          paid_amount: effectivePaid,
          due_amount: dueAmount,
          payment_method: paymentMethod,
          note: notes || "",
          created_by: user?.id ?? null,
        })
        .select("id")
        .single();
      if (saleErr) throw saleErr;
      if (saleRow && cart.length > 0) {
        const items = cart.map((item) => {
          const share = freeShareMap[item.id] || 0;
          const adjUnitPrice = item.isFree
            ? 0
            : item.price + (item.quantity > 0 ? share / item.quantity : 0);
          return {
            sale_id: (saleRow as any).id,
            product_id: item.productId,
            name: item.name,
            name_bn: item.nameBn || "",
            barcode: item.barcode || "",
            unit: item.selectedUnit || "",
            quantity: item.quantity,
            unit_price: adjUnitPrice,
            unit_discount: item.isFree ? 0 : item.unitDiscount,
            total: item.isFree ? 0 : (adjUnitPrice - item.unitDiscount) * item.quantity,
          };
        });
        await supabase.from("sale_items" as any).insert(items);
      }
    } catch (e: any) {
      console.error("Sale persist error", e);
      toast.error(isBn ? `সেভ করতে সমস্যা: ${e.message}` : `Save failed: ${e.message}`);
    }

    printReceipt({
      invoiceNo,
      date: saleDate || new Date().toLocaleDateString(lang === "bn" ? "bn-BD" : "en-GB"),
      customer,
      phone,
      address,
      saleMan,
      items: cart.map((item) => {
        const share = freeShareMap[item.id] || 0;
        const adjUnitPrice = item.isFree
          ? 0
          : item.price + (item.quantity > 0 ? share / item.quantity : 0);
        return {
          name: (lang === "bn" ? item.nameBn : item.name) + (item.isFree ? (lang === "bn" ? " (ফ্রী)" : " (FREE)") : ""),
          code: item.barcode,
          quantity: item.quantity,
          unit: item.selectedUnit,
          unitPrice: adjUnitPrice,
          discount: item.isFree ? 0 : item.unitDiscount * item.quantity,
        };
      }),

      subTotal,
      discount: totalDiscount,
      expense,
      grandTotal,
      paid: effectivePaid,
      due: dueAmount,
    });

    // Referral commission — always resolve fresh from DB so any portal-side
    // referral link set after customer selection is honored.
    let refCustomerIdForCommission: string | null = referenceCustomerId;
    if (customerId) {
      const { data: freshCust } = await supabase
        .from("customers")
        .select("reference_customer_id, reference_mobile")
        .eq("id", customerId)
        .maybeSingle();
      if (freshCust?.reference_customer_id) {
        refCustomerIdForCommission = freshCust.reference_customer_id;
      } else if (freshCust?.reference_mobile) {
        // Legacy: resolve mobile -> id and persist the link
        const { data: refByMobile } = await supabase
          .from("customers")
          .select("id")
          .eq("mobile", freshCust.reference_mobile)
          .is("deleted_at", null)
          .maybeSingle();
        if (refByMobile?.id && refByMobile.id !== customerId) {
          refCustomerIdForCommission = refByMobile.id;
          await supabase.from("customers").update({ reference_customer_id: refByMobile.id } as any).eq("id", customerId);
        }
      } else {
        refCustomerIdForCommission = null;
      }
    }
    if (refCustomerIdForCommission && customerId && refCustomerIdForCommission !== customerId && grandTotal > 0) {
      try {
        const { data: settings } = await supabase
          .from("business_settings")
          .select("setting_key, setting_value")
          .in("setting_key", ["referral_enabled", "referral_commission_percent", "referral_commission_type"]);
        const map = new Map((settings || []).map((s) => [s.setting_key, s.setting_value]));
        const enabled = (map.get("referral_enabled") || "true") === "true";
        if (enabled) {
          const type = map.get("referral_commission_type") || "percentage";
          const rate = parseFloat(map.get("referral_commission_percent") || "5") || 0;
          const amount = type === "fixed" ? rate : (grandTotal * rate) / 100;
          if (amount > 0) {
            await supabase.from("commissions").insert({
              customer_id: refCustomerIdForCommission!,
              referred_customer_id: customerId,
              sale_id: invoiceNo,
              commission_rate: rate,
              commission_type: type === "fixed" ? "fixed" : "percentage",
              amount,
              status: "pending",
            });
            // Upsert wallet
            const { data: wallet } = await supabase
              .from("referral_wallets")
              .select("id, total_commission, paid_amount, balance")
              .eq("customer_id", refCustomerIdForCommission!)
              .maybeSingle();
            let newBalance = amount;
            if (wallet) {
              newBalance = Number(wallet.balance) + amount;
              await supabase
                .from("referral_wallets")
                .update({
                  total_commission: Number(wallet.total_commission) + amount,
                  balance: newBalance,
                })
                .eq("id", wallet.id);
            } else {
              await supabase.from("referral_wallets").insert({
                customer_id: refCustomerIdForCommission!,
                total_commission: amount,
                paid_amount: 0,
                balance: amount,
              });
            }
            await supabase.from("wallet_transactions").insert({
              customer_id: refCustomerIdForCommission!,
              type: "commission_credit",
              amount,
              balance_after: newBalance,
              reference_id: invoiceNo,
              note: "Referral commission",
            });
            toast.success(isBn ? `রেফারেন্স কমিশন: ৳${amount.toFixed(2)}` : `Referral commission: ৳${amount.toFixed(2)}`);
          }
        }
      } catch (e) {
        console.error("Commission error", e);
      }
    }
  };

  const isBn = lang === "bn";

  return (
    <PageLayout>
      {/* Header */}
      <div className="mb-6 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <ShoppingCart className="h-6 w-6 text-primary" />
            {tr("addNewSale")}
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            {isBn ? "নতুন বিক্রয় এন্ট্রি করুন" : "Create a new sale entry"}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <span className="inline-flex items-center rounded-full bg-primary/10 px-3 py-1 text-xs font-medium text-primary">
            {isBn ? "ইনভয়েস" : "Invoice"}: #INV-{new Date().toISOString().slice(0, 10).replace(/-/g, "")}
          </span>
        </div>
      </div>

      <div className="flex flex-col gap-6">
        {/* Top — Main Form Area (Customer, Products, Free Products, Cart Table) */}
        <div className="space-y-5">
          {/* Customer & Sale Info */}
          <div className="rounded-2xl border border-border bg-card shadow-sm overflow-hidden">
            <div className="border-b border-border bg-muted/30 px-5 py-3">
              <h2 className="text-sm font-semibold text-foreground flex items-center gap-2">
                <User className="h-4 w-4 text-primary" />
                {isBn ? "কাস্টমার ও বিক্রয় তথ্য" : "Customer & Sale Info"}
              </h2>
            </div>
            <div className="p-5">
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                <div className="space-y-1.5">
                  <label className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                    <CalendarDays className="h-3.5 w-3.5" />
                    {tr("date")}
                  </label>
                  <input
                    type="text"
                    placeholder="DD/MM/YYYY"
                    value={saleDate}
                    onChange={(e) => setSaleDate(e.target.value)}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 transition-all outline-none"
                  />
                </div>
                <div className="space-y-1.5 relative" ref={customerDropdownRef}>
                  <label className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                    <User className="h-3.5 w-3.5" />
                    {tr("customer")}
                  </label>
                  <input
                    value={customer || customerSearch}
                    onChange={(e) => {
                      setCustomerSearch(e.target.value);
                      setCustomer("");
                      setCustomerId(null);
                    }}
                    placeholder={isBn ? "কাস্টমার নাম বা মোবাইল দিয়ে খুঁজুন" : "Search by name or mobile"}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:ring-1 focus:ring-primary/30 transition-all outline-none"
                  />
                  {showCustomerDropdown && customerResults.length > 0 && (
                    <div className="absolute left-0 right-0 top-full z-40 mt-1 max-h-56 overflow-y-auto rounded-xl border border-border bg-card shadow-xl">
                      {customerResults.map((c) => (
                        <button
                          key={c.id}
                          onClick={() => selectCustomer(c)}
                          className="flex w-full items-center justify-between px-4 py-2.5 text-sm hover:bg-primary/5 transition-colors border-b border-border/50 last:border-0"
                        >
                          <div className="text-left">
                            <p className="font-medium text-foreground">{isBn ? c.name_bn || c.name : c.name}</p>
                            <p className="text-xs text-muted-foreground">{c.mobile}</p>
                          </div>
                          {c.address && <p className="text-xs text-muted-foreground max-w-[120px] truncate">{c.address}</p>}
                        </button>
                      ))}
                    </div>
                  )}
                  {showCustomerDropdown && customerSearch.length >= 2 && customerResults.length === 0 && (
                    <div className="absolute left-0 right-0 top-full z-40 mt-1 rounded-xl border border-border bg-card shadow-xl px-4 py-3 text-sm text-muted-foreground">
                      {isBn ? "কোনো কাস্টমার পাওয়া যায়নি" : "No customer found"}
                    </div>
                  )}
                </div>
                <div className="space-y-1.5">
                  <label className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                    <User className="h-3.5 w-3.5" />
                    {isBn ? "সেলস ম্যান" : "Sales Person"}
                  </label>
                  <input
                    value={saleMan}
                    onChange={(e) => setSaleMan(e.target.value)}
                    placeholder={isBn ? "সেলস ম্যান নাম" : "Sales person name"}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:ring-1 focus:ring-primary/30 transition-all outline-none"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                    <Phone className="h-3.5 w-3.5" />
                    {isBn ? "মোবাইল নম্বর" : "Phone"}
                  </label>
                  <input
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    placeholder="01XXXXXXXXX"
                    className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:ring-1 focus:ring-primary/30 transition-all outline-none"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                    <MapPin className="h-3.5 w-3.5" />
                    {isBn ? "ঠিকানা" : "Address"}
                  </label>
                  <input
                    value={address}
                    onChange={(e) => setAddress(e.target.value)}
                    placeholder={isBn ? "ঠিকানা লিখুন" : "Enter address"}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:ring-1 focus:ring-primary/30 transition-all outline-none"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                    <ChevronDown className="h-3.5 w-3.5" />
                    {isBn ? "সেল স্ট্যাটাস" : "Sale Status"}
                  </label>
                  <select
                    value={saleStatus}
                    onChange={(e) => setSaleStatus(e.target.value)}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 transition-all outline-none appearance-none cursor-pointer"
                  >
                    <option value="pending">{isBn ? "অপেক্ষমাণ" : "Pending"}</option>
                    <option value="confirmed">{isBn ? "নিশ্চিত" : "Confirmed"}</option>
                    <option value="processing">{isBn ? "প্রক্রিয়াধীন" : "Processing"}</option>
                    <option value="completed">{isBn ? "সম্পন্ন" : "Completed"}</option>
                    <option value="delivered">{isBn ? "ডেলিভার্ড" : "Delivered"}</option>
                  </select>
                </div>
              </div>
            </div>
          </div>

          {/* Product Search & Cart */}
          <div className="rounded-2xl border border-border bg-card shadow-sm overflow-hidden">
            <div className="border-b border-border bg-muted/30 px-5 py-3 flex items-center justify-between">
              <h2 className="text-sm font-semibold text-foreground flex items-center gap-2">
                <Package className="h-4 w-4 text-primary" />
                {isBn ? "পণ্য নির্বাচন করুন" : "Select Products"}
              </h2>
              {cart.length > 0 && (
                <span className="inline-flex items-center rounded-full bg-primary/10 px-2.5 py-0.5 text-xs font-semibold text-primary">
                  {cart.length} {isBn ? "টি আইটেম" : "items"}
                </span>
              )}
            </div>
            <div className="p-5">
              {/* Search bar */}
              <div className="relative mb-5">
                <Search className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <input
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  placeholder={isBn ? "🔍 পণ্যের নাম বা বারকোড দিয়ে খুঁজুন..." : "🔍 Search by product name or barcode..."}
                  className="w-full rounded-xl border border-border bg-background pl-10 pr-4 py-3 text-sm text-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all outline-none"
                />
                {filteredProducts.length > 0 && (
                  <div className="absolute left-0 right-0 top-full z-30 mt-1 max-h-64 overflow-y-auto rounded-xl border border-border bg-card shadow-xl">
                    {filteredProducts.map((p: any) => (
                      <button
                        key={p.id}
                        onClick={() => addToCart(p)}
                        className="flex w-full items-center justify-between px-4 py-3 text-sm hover:bg-primary/5 transition-colors border-b border-border/50 last:border-0"
                      >
                        <div className="flex items-center gap-3">
                          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10 text-primary">
                            <Package className="h-4 w-4" />
                          </div>
                          <div className="text-left">
                            <p className="font-medium text-foreground">{lang === "bn" ? (p.name_bn || p.name) : p.name}</p>
                            <p className="text-xs text-muted-foreground">{p.sku} {p.barcode ? `· ${p.barcode}` : ""}</p>
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="font-semibold text-foreground">৳{p.retail_price}</p>
                          <p className="text-xs text-muted-foreground">{isBn ? "স্টক" : "Stock"}: {p.stock_quantity}</p>
                        </div>
                      </button>
                    ))}
                  </div>
                )}
              </div>





              {/* Filter Dropdowns */}
              <div className="grid grid-cols-3 gap-3 mb-5">
                <select
                  value={filterTypeId}
                  onChange={(e) => setFilterTypeId(e.target.value)}
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none appearance-none cursor-pointer"
                >
                  <option value="">{isBn ? "সকল টাইপ" : "All Types"}</option>
                  {productTypes.map((t: any) => (
                    <option key={t.id} value={t.id}>{lang === "bn" ? (t.name_bn || t.name) : t.name}</option>
                  ))}
                </select>
                <select
                  value={filterCategoryId}
                  onChange={(e) => { setFilterCategoryId(e.target.value); setFilterSubcategoryId(""); }}
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none appearance-none cursor-pointer"
                >
                  <option value="">{isBn ? "সকল ক্যাটাগরি" : "All Categories"}</option>
                  {categories.map((c: any) => (
                    <option key={c.id} value={c.id}>{lang === "bn" ? (c.name_bn || c.name) : c.name}</option>
                  ))}
                </select>
                <select
                  value={filterSubcategoryId}
                  onChange={(e) => setFilterSubcategoryId(e.target.value)}
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none appearance-none cursor-pointer"
                  disabled={!filterCategoryId}
                >
                  <option value="">{isBn ? "সকল সাব-ক্যাটাগরি" : "All Sub-Categories"}</option>
                  {subcategories.map((sc: any) => (
                    <option key={sc.id} value={sc.id}>{lang === "bn" ? (sc.name_bn || sc.name) : sc.name}</option>
                  ))}
                </select>
              </div>
              {/* Cart table */}
              {cart.length > 0 ? (
                <div className="overflow-x-auto rounded-xl border border-border">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="bg-muted/50 text-left text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                        <th className="px-3 py-3 w-10">SL</th>
                        <th className="px-3 py-3 min-w-[150px]">{isBn ? "পণ্য" : "PRODUCT"}</th>
                        <th className="px-3 py-3 text-center w-[100px]">{isBn ? "প্রাইস টাইপ" : "PRICE TYPE"}</th>
                        <th className="px-3 py-3 text-center w-[100px]">{isBn ? "ইউনিট" : "UNIT"}</th>
                        <th className="px-3 py-3 text-center w-[120px]">{isBn ? "পরিমাণ" : "QTY"}</th>
                        <th className="px-3 py-3 text-right w-[100px]">{isBn ? "মূল্য" : "PRICE"}</th>
                        <th className="px-3 py-3 text-right w-[100px]">{isBn ? "টোটাল" : "TOTAL"}</th>
                        <th className="px-3 py-3 text-center w-[90px]">{isBn ? "ছাড় %" : "DISC %"}</th>
                        <th className="px-3 py-3 text-center w-[100px]">{isBn ? "ছাড় ৳" : "DISC TK"}</th>
                        <th className="px-3 py-3 text-center w-[110px]">{isBn ? "ওয়ারেন্টি" : "WARRANTY"}</th>
                        <th className="px-3 py-3 text-right w-[110px]">{isBn ? "ফাইনাল" : "FINAL"}</th>
                        <th className="px-3 py-3 w-10"></th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {cart.map((item, i) => {
                        const unitTotal = item.price - item.unitDiscount;
                        const lineGross = item.price * item.quantity;
                        const share = freeShareMap[item.id] || 0;
                        const amount = item.isFree ? 0 : unitTotal * item.quantity + share;
                        const discPercent = item.price > 0 ? (item.unitDiscount / item.price) * 100 : 0;
                        const belowCost = isBelowCost(item);
                        const effCost = getEffectiveCost(item);
                        return (
                          <tr key={item.id} className={`hover:bg-muted/20 transition-colors ${belowCost ? "bg-destructive/5" : ""}`}>
                            <td className="px-3 py-2.5 text-muted-foreground font-medium">
                              {i + 1}
                              {belowCost && (
                                <AlertTriangle className="inline-block h-3.5 w-3.5 text-destructive ml-1" aria-label={isBn ? "ক্রয়মূল্যের নিচে বিক্রি" : "Below cost"} />
                              )}
                            </td>
                            <td className="px-3 py-2.5">
                              <p className="font-medium text-foreground leading-tight flex items-center gap-1.5">
                                {lang === "bn" ? item.nameBn : item.name}
                                {item.isFree && (
                                  <span className="text-[10px] font-bold px-1.5 py-0.5 rounded bg-emerald-100 text-emerald-700">
                                    {isBn ? "ফ্রী" : "FREE"}
                                  </span>
                                )}
                              </p>

                              <p className="text-[11px] text-muted-foreground">{item.barcode} · {isBn ? "স্টক" : "Stock"}: {item.stock} {item.unit}{item.conversionFactor > 1 ? ` (${Math.floor(item.stock / item.conversionFactor)} ${item.selectedUnit})` : ""}</p>
                            </td>
                            <td className="px-3 py-2.5 text-center">
                              {item.pricingRules.length > 0 ? (
                                <select
                                  value={item.priceType}
                                  onChange={(e) => updatePriceType(item.id, e.target.value)}
                                  className="w-full max-w-[90px] mx-auto text-center text-xs border border-border rounded-md bg-background px-1 py-1.5 text-foreground outline-none focus:border-primary cursor-pointer"
                                >
                                  {[...new Set(item.pricingRules.map((p) => p.price_type))].map((pt) => (
                                    <option key={pt} value={pt}>{pt.charAt(0).toUpperCase() + pt.slice(1)}</option>
                                  ))}
                                </select>
                              ) : (
                                <span className="text-xs text-muted-foreground">Retail</span>
                              )}
                            </td>
                            <td className="px-3 py-2.5 text-center">
                              {(() => {
                                const uniqueUnits = [...new Map(item.pricingRules.map((r) => [r.unit_name, r])).values()];
                                return (
                                  <select
                                    value={item.selectedUnit}
                                    onChange={(e) => updateSelectedUnit(item.id, e.target.value)}
                                    className="w-full max-w-[90px] mx-auto text-center text-xs border border-border rounded-md bg-background px-1 py-1.5 text-foreground outline-none focus:border-primary cursor-pointer"
                                  >
                                    <option value="Piece">{item.unit} ({isBn ? "বেস" : "Base"})</option>
                                    {uniqueUnits.filter((u) => !u.is_base_unit).map((u) => (
                                      <option key={u.unit_name} value={u.unit_name}>{lang === "bn" ? (u.unit_name_bn || u.unit_name) : u.unit_name} (×{u.conversion_factor})</option>
                                    ))}
                                  </select>
                                );
                              })()}
                            </td>
                            <td className="px-3 py-2.5">
                              <div className="flex items-center justify-center gap-0.5">
                                <button
                                  onClick={() => updateQuantity(item.id, -1)}
                                  className="flex h-7 w-7 items-center justify-center rounded-md border border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
                                >
                                  <Minus className="h-3 w-3" />
                                </button>
                                <input
                                  type="number"
                                  value={item.quantity}
                                  onChange={(e) => updateQtyDirect(item.id, parseInt(e.target.value) || 1)}
                                  min={1}
                                  className="w-12 text-center font-semibold text-foreground border border-border rounded-md bg-background py-1 text-sm outline-none focus:border-primary [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
                                />
                                <button
                                  onClick={() => updateQuantity(item.id, 1)}
                                  className="flex h-7 w-7 items-center justify-center rounded-md border border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
                                >
                                  <Plus className="h-3 w-3" />
                                </button>
                              </div>
                            </td>
                            <td className={`px-3 py-2.5 text-right font-medium ${belowCost ? "text-destructive" : "text-foreground"}`}>
                              ৳{item.price.toLocaleString()}
                              {belowCost && (
                                <div className="text-[10px] font-normal text-destructive/80 mt-0.5">
                                  {isBn ? "ক্রয়মূল্য" : "Cost"}: ৳{effCost.toLocaleString()}
                                </div>
                              )}
                            </td>
                            <td className="px-3 py-2.5 text-right font-semibold text-foreground">৳{lineGross.toLocaleString()}</td>
                            <td className="px-3 py-2.5">
                              <input
                                type="number"
                                value={Number(discPercent.toFixed(2))}
                                onChange={(e) => updateUnitDiscountPercent(item.id, parseFloat(e.target.value) || 0)}
                                min={0}
                                max={100}
                                step="0.01"
                                className="w-full text-right font-medium text-foreground border border-border rounded-md bg-background px-2 py-1 text-sm outline-none focus:border-primary [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
                              />
                            </td>
                            <td className="px-3 py-2.5">
                              <input
                                type="number"
                                value={item.unitDiscount}
                                onChange={(e) => updateUnitDiscount(item.id, parseFloat(e.target.value) || 0)}
                                min={0}
                                max={item.price}
                                className="w-full text-right font-medium text-foreground border border-border rounded-md bg-background px-2 py-1 text-sm outline-none focus:border-primary [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
                              />
                            </td>
                            <td className="px-3 py-2.5 text-center">
                              <select
                                value={item.warranty}
                                onChange={(e) => updateWarranty(item.id, e.target.value)}
                                className="w-full max-w-[100px] mx-auto text-center text-xs border border-border rounded-md bg-background px-1 py-1.5 text-foreground outline-none focus:border-primary cursor-pointer appearance-none"
                              >
                                {WARRANTY_OPTIONS.map((w) => (
                                  <option key={w} value={w}>{w}</option>
                                ))}
                              </select>
                            </td>
                            <td className="px-3 py-2.5 text-right font-bold text-primary">
                              {item.isFree ? (
                                <span className="text-emerald-600">{isBn ? "ফ্রী" : "FREE"}</span>
                              ) : (
                                <>
                                  ৳{amount.toLocaleString(undefined, { maximumFractionDigits: 2 })}
                                  {share > 0 && (
                                    <div className="text-[10px] font-normal text-emerald-600 mt-0.5">
                                      +৳{share.toLocaleString(undefined, { maximumFractionDigits: 2 })} {isBn ? "ফ্রী শেয়ার" : "free share"}
                                    </div>
                                  )}
                                </>
                              )}
                            </td>
                            <td className="px-3 py-2.5 text-center">
                              <button
                                onClick={() => removeFromCart(item.id)}
                                className="flex h-7 w-7 items-center justify-center rounded-md text-destructive/60 hover:bg-destructive/10 hover:text-destructive transition-colors mx-auto"
                              >
                                <X className="h-4 w-4" />
                              </button>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                    <tfoot>
                      <tr className="bg-muted/30 font-semibold text-sm">
                        <td colSpan={10} className="px-3 py-3 text-right text-foreground">{isBn ? "মোট অ্যামাউন্ট" : "Total Amount"}</td>
                        <td className="px-3 py-3 text-right text-primary font-bold text-base">৳{subTotal.toLocaleString()}</td>
                        <td></td>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
                  <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-muted/50 mb-4">
                    <ShoppingCart className="h-8 w-8 text-muted-foreground/50" />
                  </div>
                  <p className="text-sm font-medium">{isBn ? "কার্ট খালি" : "Cart is empty"}</p>
                  <p className="text-xs mt-1">{isBn ? "উপরে সার্চ করে পণ্য যোগ করুন" : "Search above to add products"}</p>
                </div>
              )}

              {/* Free Product Search — sits below the Order Summary table */}
              <div className="relative mt-3">
                <div className="rounded-2xl border-2 border-dashed border-emerald-300 bg-gradient-to-br from-emerald-50/80 via-emerald-50/40 to-transparent p-3 sm:p-4 shadow-sm">
                  <div className="flex items-center justify-between mb-2 gap-2 flex-wrap">
                    <div className="flex items-center gap-2">
                      <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-emerald-600 text-white shadow-sm">
                        <Gift className="h-3.5 w-3.5" />
                      </div>
                      <div>
                        <p className="text-xs font-bold text-emerald-800 leading-tight">
                          {isBn ? "ফ্রী পণ্য যোগ করুন" : "Add Free Product"}
                        </p>
                        <p className="text-[10px] text-emerald-700/70 leading-tight">
                          {isBn ? "মূল্য ০ · স্টক থেকে কাটা যাবে" : "Price 0 · Stock will be deducted"}
                        </p>
                      </div>
                    </div>
                    <span className="text-[9px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full bg-emerald-600 text-white">
                      FREE
                    </span>
                  </div>
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-emerald-600" />
                    <input
                      value={freeSearchTerm}
                      onChange={(e) => setFreeSearchTerm(e.target.value)}
                      placeholder={isBn ? "নাম / বারকোড / SKU দিয়ে খুঁজুন..." : "Search by name / barcode / SKU..."}
                      className="w-full rounded-xl border border-emerald-300 bg-white pl-9 pr-3 py-2.5 text-sm text-foreground placeholder:text-emerald-700/50 focus:border-emerald-500 focus:ring-2 focus:ring-emerald-200 transition-all outline-none"
                    />
                    {freeSearchTerm && (
                      <button
                        type="button"
                        onClick={() => { setFreeSearchTerm(""); setFreeDbProducts([]); }}
                        className="absolute right-2 top-1/2 -translate-y-1/2 flex h-6 w-6 items-center justify-center rounded-md text-emerald-700/60 hover:bg-emerald-100 hover:text-emerald-800"
                        aria-label="Clear"
                      >
                        <X className="h-3.5 w-3.5" />
                      </button>
                    )}
                    {freeDbProducts.length > 0 && (
                      <div className="absolute left-0 right-0 top-full z-40 mt-1.5 max-h-72 overflow-y-auto rounded-xl border-2 border-emerald-300 bg-card shadow-2xl">
                        {freeDbProducts.map((p: any) => (
                          <button
                            key={p.id}
                            onClick={() => addToCart(p, { asFree: true })}
                            className="flex w-full items-center justify-between px-3 py-2.5 text-sm hover:bg-emerald-50 transition-colors border-b border-border/40 last:border-0 text-left"
                          >
                            <div className="flex items-center gap-2.5 min-w-0">
                              <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-emerald-100 text-emerald-700">
                                <Gift className="h-4 w-4" />
                              </div>
                              <div className="min-w-0">
                                <p className="font-medium text-foreground truncate">{lang === "bn" ? (p.name_bn || p.name) : p.name}</p>
                                <p className="text-[11px] text-muted-foreground truncate">{p.sku}{p.barcode ? ` · ${p.barcode}` : ""}</p>
                              </div>
                            </div>
                            <div className="text-right shrink-0 ml-2">
                              <span className="inline-block text-[10px] font-bold px-2 py-0.5 rounded bg-emerald-600 text-white">
                                {isBn ? "ফ্রী" : "FREE"}
                              </span>
                              <p className="text-[10px] text-muted-foreground mt-0.5">{isBn ? "স্টক" : "Stock"}: {p.stock_quantity}</p>
                            </div>
                          </button>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Toggle Sections */}
          <div className="flex flex-wrap gap-2">
            <button
              onClick={() => setShowPayment(!showPayment)}
              className={`inline-flex items-center gap-2 rounded-xl px-4 py-2.5 text-xs font-semibold transition-all ${
                showPayment
                  ? "bg-primary text-primary-foreground shadow-md shadow-primary/25"
                  : "border border-border bg-card text-foreground hover:bg-muted hover:border-primary/30"
              }`}
            >
              <CreditCard className="h-3.5 w-3.5" />
              {isBn ? "পেমেন্ট যোগ" : "Add Payment"}
            </button>
            <button
              onClick={() => setShowNotes(!showNotes)}
              className={`inline-flex items-center gap-2 rounded-xl px-4 py-2.5 text-xs font-semibold transition-all ${
                showNotes
                  ? "bg-primary text-primary-foreground shadow-md shadow-primary/25"
                  : "border border-border bg-card text-foreground hover:bg-muted hover:border-primary/30"
              }`}
            >
              <FileText className="h-3.5 w-3.5" />
              {isBn ? "নোট" : "Notes"}
            </button>
            <button
              onClick={() => setShowReturn(!showReturn)}
              className={`inline-flex items-center gap-2 rounded-xl px-4 py-2.5 text-xs font-semibold transition-all ${
                showReturn
                  ? "bg-primary text-primary-foreground shadow-md shadow-primary/25"
                  : "border border-border bg-card text-foreground hover:bg-muted hover:border-primary/30"
              }`}
            >
              <RotateCcw className="h-3.5 w-3.5" />
              {isBn ? "রিটার্ন" : "Return"}
            </button>
          </div>

          {/* Payment Section */}
          {showPayment && (
            <div className="rounded-2xl border border-border bg-card shadow-sm overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200">
              <div className="border-b border-border bg-muted/30 px-5 py-3">
                <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
                  <CreditCard className="h-4 w-4 text-primary" />
                  {isBn ? "পেমেন্ট তথ্য" : "Payment Information"}
                </h3>
              </div>
              <div className="p-5">
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-muted-foreground">{isBn ? "পরিশোধিত পরিমাণ" : "Paid Amount"}</label>
                    <input
                      type="number"
                      value={paidAmount}
                      onChange={(e) => setPaidAmount(Number(e.target.value))}
                      className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 transition-all outline-none"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-muted-foreground">{isBn ? "পেমেন্ট মেথড" : "Payment Method"}</label>
                    <select
                      value={paymentMethod}
                      onChange={(e) => setPaymentMethod(e.target.value)}
                      className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 transition-all outline-none appearance-none cursor-pointer"
                    >
                      <option value="নগদ">{isBn ? "নগদ" : "Cash"}</option>
                      <option value="বিকাশ">{isBn ? "বিকাশ" : "bKash"}</option>
                      <option value="নগদ অ্যাপ">{isBn ? "নগদ অ্যাপ" : "Nagad"}</option>
                      <option value="ব্যাংক">{isBn ? "ব্যাংক" : "Bank"}</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Notes Section */}
          {showNotes && (
            <div className="rounded-2xl border border-border bg-card shadow-sm overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200">
              <div className="border-b border-border bg-muted/30 px-5 py-3">
                <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
                  <FileText className="h-4 w-4 text-primary" />
                  {isBn ? "নোট" : "Notes"}
                </h3>
              </div>
              <div className="p-5">
                <textarea
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  rows={3}
                  placeholder={isBn ? "অতিরিক্ত নোট লিখুন..." : "Write additional notes..."}
                  className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:ring-1 focus:ring-primary/30 transition-all outline-none resize-none"
                />
              </div>
            </div>
          )}

          {/* Return Section */}
          {/* Return Modal */}
          {showReturn && (
            <ReturnModal
              isBn={isBn}
              lang={lang}
              onClose={() => setShowReturn(false)}
            />
          )}
        </div>

        {/* Bottom — Order Summary (Full Width below product table) */}
        <div className="space-y-5">
          {/* Summary Card */}
          <div className="rounded-2xl border border-border/60 bg-card shadow-[0_4px_24px_-8px_rgba(0,0,0,0.08)] hover:shadow-[0_8px_32px_-8px_rgba(0,0,0,0.12)] transition-shadow overflow-hidden">
            <div className="border-b border-border/60 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-5 sm:px-6 py-4 flex items-center justify-between">
              <h3 className="text-sm sm:text-base font-bold text-foreground flex items-center gap-2.5">
                <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/15 text-primary">
                  <ShoppingCart className="h-4 w-4" />
                </span>
                {isBn ? "অর্ডার সামারি" : "Order Summary"}
              </h3>
              <span className="text-[11px] font-semibold text-muted-foreground bg-muted/60 px-2.5 py-1 rounded-full">
                {cart.length} {isBn ? "আইটেম" : "items"}
              </span>
            </div>
            <div className="p-5 sm:p-6 space-y-5">
              {/* Discount & Expense fields */}
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div className="space-y-1.5">
                  <label className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">{isBn ? "ডিসকাউন্ট (%)" : "Discount (%)"}</label>
                  <input
                    type="number"
                    value={discountPercent}
                    onChange={(e) => setDiscountPercent(Number(e.target.value))}
                    min={0}
                    max={100}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all outline-none"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">{isBn ? "ডিসকাউন্ট (৳)" : "Discount (BDT)"}</label>
                  <input
                    type="number"
                    value={discountFlat}
                    onChange={(e) => setDiscountFlat(Number(e.target.value))}
                    min={0}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all outline-none"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">{isBn ? "অতিরিক্ত খরচ" : "Extra Expense"}</label>
                  <input
                    type="number"
                    value={expense}
                    onChange={(e) => setExpense(Number(e.target.value))}
                    min={0}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all outline-none"
                  />
                </div>
              </div>


              {/* Sub-Category Search & Summary */}
              {subcategoryGroups.length > 0 && (
                <div className="rounded-xl border border-border bg-background overflow-hidden">
                  <div className="bg-primary/5 px-3 py-2 text-xs font-bold text-foreground border-b border-border flex items-center justify-between">
                    <span>{isBn ? "সাব-ক্যাটাগরি" : "Sub-Category"}</span>
                    <span className="text-[10px] font-normal text-muted-foreground">
                      {subcategoryGroups.length} {isBn ? "টি" : "found"}
                    </span>
                  </div>

                  {/* Search box */}
                  <div className="p-2 border-b border-border bg-muted/10">
                    <div className="relative">
                      <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none" />
                      <input
                        type="text"
                        value={subcatSearch}
                        onChange={(e) => {
                          setSubcatSearch(e.target.value);
                          setSelectedSubcatKey(null);
                          setShowSubcatDropdown(true);
                        }}
                        onFocus={() => setShowSubcatDropdown(true)}
                        onBlur={() => setTimeout(() => setShowSubcatDropdown(false), 150)}
                        onKeyDown={(e) => {
                          if (e.key === "ArrowDown") {
                            e.preventDefault();
                            setShowSubcatDropdown(true);
                            setSubcatHighlightIdx((i) => Math.min(subcatSuggestions.length - 1, i + 1));
                          } else if (e.key === "ArrowUp") {
                            e.preventDefault();
                            setSubcatHighlightIdx((i) => Math.max(0, i - 1));
                          } else if (e.key === "Enter") {
                            e.preventDefault();
                            const pick = subcatSuggestions[subcatHighlightIdx];
                            if (pick) {
                              setSelectedSubcatKey(pick.key);
                              setSubcatSearch(pick.name);
                              setShowSubcatDropdown(false);
                            }
                          } else if (e.key === "Escape") {
                            setShowSubcatDropdown(false);
                            setSubcatSearch("");
                            setSelectedSubcatKey(null);
                          }
                        }}
                        placeholder={isBn ? "সাব-ক্যাটাগরি খুঁজুন..." : "Search sub-category..."}
                        className="w-full rounded-md border border-border bg-background pl-7 pr-16 py-1.5 text-[11px] sm:text-xs focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none"
                      />
                      {(subcatSearch || selectedSubcatKey) && (
                        <button
                          type="button"
                          onClick={() => { setSubcatSearch(""); setSelectedSubcatKey(null); setShowSubcatDropdown(false); }}
                          className="absolute right-2 top-1/2 -translate-y-1/2 text-[10px] text-muted-foreground hover:text-foreground px-1.5 py-0.5 rounded hover:bg-muted"
                        >
                          {isBn ? "মুছুন" : "Clear"}
                        </button>
                      )}
                      {showSubcatDropdown && subcatSuggestions.length > 0 && (
                        <div className="absolute z-30 left-0 right-0 mt-1 max-h-44 overflow-y-auto rounded-md border border-border bg-popover shadow-lg">
                          {subcatSuggestions.map((g, idx) => (
                            <button
                              type="button"
                              key={g.key}
                              onMouseDown={(e) => e.preventDefault()}
                              onClick={() => {
                                setSelectedSubcatKey(g.key);
                                setSubcatSearch(g.name);
                                setShowSubcatDropdown(false);
                              }}
                              onMouseEnter={() => setSubcatHighlightIdx(idx)}
                              className={`w-full text-left px-2.5 py-1.5 text-[11px] flex justify-between items-center ${idx === subcatHighlightIdx ? "bg-accent text-accent-foreground" : "hover:bg-accent/50"}`}
                            >
                              <span className="font-medium truncate pr-2">{g.name}</span>
                              <span className="text-muted-foreground whitespace-nowrap">৳{g.total.toFixed(0)}</span>
                            </button>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Selected sub-category summary + product list */}
                  {selectedSubcatKey && (() => {
                    const group = subcategoryGroups.find((g) => g.key === selectedSubcatKey);
                    const products = cart.filter((it) => (it.subcategoryId || "__none__") === selectedSubcatKey);
                    if (!group) return null;
                    const totalQty = products.reduce((s, p) => s + p.quantity, 0);
                    return (
                      <div className="p-3 space-y-2">
                        <div className="grid grid-cols-3 gap-2 text-center">
                          <div className="rounded-md bg-muted/40 p-2">
                            <div className="text-[10px] text-muted-foreground">{isBn ? "পণ্য" : "Items"}</div>
                            <div className="text-sm font-bold text-foreground">{products.length}</div>
                          </div>
                          <div className="rounded-md bg-muted/40 p-2">
                            <div className="text-[10px] text-muted-foreground">{isBn ? "পরিমাণ" : "Qty"}</div>
                            <div className="text-sm font-bold text-foreground">{totalQty}</div>
                          </div>
                          <div className="rounded-md bg-primary/10 p-2">
                            <div className="text-[10px] text-muted-foreground">{isBn ? "টোটাল" : "Total"}</div>
                            <div className="text-sm font-bold text-primary">৳{group.total.toFixed(0)}</div>
                          </div>
                        </div>
                        {/* Sub-Category Discount Input */}
                        <div className="grid grid-cols-3 gap-2 items-center rounded-md border border-border p-2 bg-muted/20">
                          <label className="text-[10px] font-medium text-muted-foreground col-span-1">{isBn ? "ডিসকাউন্ট %" : "Discount %"}</label>
                          <input
                            type="number"
                            min={0}
                            max={100}
                            value={group.discountPercent || ""}
                            onChange={(e) => {
                              const v = Math.max(0, Math.min(100, Number(e.target.value) || 0));
                              setSubcategoryDiscounts((prev) => ({ ...prev, [group.key]: v }));
                            }}
                            placeholder="0"
                            className="col-span-1 rounded border border-border bg-background px-2 py-1 text-[11px] outline-none focus:border-primary focus:ring-1 focus:ring-primary/30"
                          />
                          <div className="col-span-1 text-right">
                            <div className="text-[9px] text-muted-foreground">{isBn ? "ফাইনাল" : "Final"}</div>
                            <div className="text-xs font-bold text-primary">৳{group.finalAmount.toFixed(0)}</div>
                          </div>
                        </div>
                        <div className="rounded-md border border-border overflow-hidden">
                          <div className="bg-muted/30 px-2 py-1 text-[10px] font-semibold text-muted-foreground">
                            {isBn ? "পণ্যসমূহ" : "Products"}
                          </div>
                          <ul className="max-h-40 overflow-y-auto divide-y divide-border">
                            {products.map((p) => (
                              <li key={p.id} className="px-2 py-1.5 flex justify-between items-center text-[11px]">
                                <div className="min-w-0 pr-2">
                                  <div className="truncate font-medium text-foreground">{lang === "bn" ? p.nameBn : p.name}</div>
                                  <div className="text-[10px] text-muted-foreground">{p.quantity} × ৳{(p.price - p.unitDiscount).toFixed(0)}</div>
                                </div>
                                <div className="font-semibold text-primary whitespace-nowrap">৳{((p.price - p.unitDiscount) * p.quantity).toFixed(0)}</div>
                              </li>
                            ))}
                          </ul>
                        </div>
                      </div>
                    );
                  })()}

                  {/* When no selection, show all groups list (filtered by search) */}
                  {!selectedSubcatKey && (
                    <ul className="max-h-44 overflow-y-auto divide-y divide-border">
                      {visibleSubcategoryGroups.length === 0 && (
                        <li className="px-3 py-2 text-center text-[11px] text-muted-foreground">
                          {isBn ? "কোনো মিল পাওয়া যায়নি" : "No matches"}
                        </li>
                      )}
                      {visibleSubcategoryGroups.map((g) => {
                        const itemCount = cart.filter((it) => (it.subcategoryId || "__none__") === g.key).length;
                        return (
                          <li key={g.key} className="px-3 py-2 hover:bg-accent/30">
                            <div className="flex justify-between items-center gap-2">
                              <button
                                type="button"
                                onClick={() => { setSelectedSubcatKey(g.key); setSubcatSearch(g.name); }}
                                className="text-left min-w-0 pr-2 flex-1"
                              >
                                <div className="truncate font-medium text-foreground text-[11px]">{g.name}</div>
                                <div className="text-[10px] text-muted-foreground">{itemCount} {isBn ? "পণ্য" : "items"} · ৳{g.total.toFixed(0)}</div>
                              </button>
                              <div className="flex items-center gap-1.5 whitespace-nowrap">
                                <input
                                  type="number"
                                  min={0}
                                  max={100}
                                  value={subcategoryDiscounts[g.key] || ""}
                                  onChange={(e) => {
                                    const v = Math.max(0, Math.min(100, Number(e.target.value) || 0));
                                    setSubcategoryDiscounts((prev) => ({ ...prev, [g.key]: v }));
                                  }}
                                  placeholder="0"
                                  title={isBn ? "ডিসকাউন্ট %" : "Discount %"}
                                  className="w-12 rounded border border-border bg-background px-1.5 py-0.5 text-[11px] text-center outline-none focus:border-primary focus:ring-1 focus:ring-primary/30"
                                />
                                <span className="text-[10px] text-muted-foreground">%</span>
                                <div className="text-right ml-1">
                                  <div className="text-[9px] text-muted-foreground">{isBn ? "ফাইনাল" : "Final"}</div>
                                  <div className="text-[11px] font-bold text-primary">৳{g.finalAmount.toFixed(0)}</div>
                                </div>
                              </div>
                            </div>
                          </li>
                        );
                      })}
                    </ul>
                  )}
                </div>
              )}

              {/* Totals */}
              <div className="rounded-xl border border-border/50 bg-gradient-to-br from-muted/40 to-muted/10 p-4 sm:p-5 space-y-3 shadow-inner">
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">{isBn ? "সাবটোটাল" : "Subtotal"}</span>
                  <span className="font-semibold text-foreground tabular-nums">৳{subTotal.toLocaleString()}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">{isBn ? "ডিসকাউন্ট" : "Discount"}</span>
                  <span className="font-semibold text-destructive tabular-nums">−৳{totalDiscount.toFixed(0)}</span>
                </div>
                {expense > 0 && (
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">{isBn ? "খরচ" : "Expense"}</span>
                    <span className="font-semibold text-foreground tabular-nums">৳{expense.toLocaleString()}</span>
                  </div>
                )}
                <div className="border-t border-border/70 pt-3 flex justify-between items-baseline">
                  <span className="text-sm font-bold text-foreground">{isBn ? "গ্র্যান্ড টোটাল" : "Grand Total"}</span>
                  <span className="text-2xl font-extrabold text-primary tabular-nums tracking-tight">৳{grandTotal.toLocaleString()}</span>
                </div>
                <div className="border-t border-border/70 pt-3 flex items-center justify-between gap-3">
                  <label className="text-sm font-semibold text-foreground whitespace-nowrap">{isBn ? "ক্যাশ প্রাপ্ত" : "Cash Received"}</label>
                  <input
                    type="text"
                    inputMode="decimal"
                    value={paidAmount || ""}
                    onChange={(e) => {
                      const raw = e.target.value.trim();
                      if (raw === "") { setPaidAmount(0); return; }
                      if (!/^\d*\.?\d*$/.test(raw)) {
                        toast.error(isBn ? "শুধুমাত্র সংখ্যা ইনপুট করুন" : "Numbers only");
                        return;
                      }
                      const n = Number(raw);
                      if (!Number.isFinite(n) || n < 0) {
                        toast.error(isBn ? "মান অবশ্যই ০ বা তার বেশি হতে হবে" : "Value must be 0 or greater");
                        return;
                      }
                      if (n > grandTotal && grandTotal > 0) {
                        toast.warning(isBn ? "ক্যাশ প্রাপ্ত গ্র্যান্ড টোটাল অপেক্ষা বেশি" : "Cash Received exceeds Grand Total");
                      }
                      setPaidAmount(n);
                    }}
                    placeholder="0"
                    className="w-32 rounded-lg border border-border bg-background px-3 py-2 text-right text-sm font-bold text-green-700 dark:text-green-400 tabular-nums focus:outline-none focus:ring-2 focus:ring-primary/40"
                  />
                </div>
                <div className="flex justify-between text-sm pt-1">
                  <span className="font-medium text-foreground">{isBn ? "পরিশোধিত (Paid)" : "Paid"}</span>
                  <span className="font-semibold text-green-600 dark:text-green-400 tabular-nums">৳{effectivePaid.toLocaleString()}</span>
                </div>
                <div className="flex justify-between items-baseline">
                  <span className="font-bold text-foreground">{isBn ? "বকেয়া (Due)" : "Due"}</span>
                  <span className={`font-extrabold text-xl tabular-nums transition-colors ${dueAmount > 0 ? "text-destructive" : "text-green-600 dark:text-green-400"}`}>
                    ৳{dueAmount.toLocaleString()}
                  </span>
                </div>
                <div className="border-t border-dashed border-border/70 pt-3 mt-1 flex justify-between text-sm">
                  <span className="font-semibold text-muted-foreground">{isBn ? "বিক্রয় প্রতিনিধি" : "Sales Representative"}</span>
                  <span className="font-bold text-foreground">{saleMan || "—"}</span>
                </div>
              </div>
            </div>

            {/* Action Buttons — Sticky on mobile for quick POS billing */}
            <div className="sticky bottom-0 z-30 border-t border-border/60 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 p-3 sm:p-5 grid grid-cols-2 gap-3 shadow-[0_-4px_24px_-8px_rgba(0,0,0,0.12)] lg:static lg:z-auto lg:shadow-none lg:bg-muted/20 lg:backdrop-blur-none">
              <button className="flex w-full items-center justify-center gap-2 rounded-xl border border-border bg-background px-3 py-3 text-sm font-semibold text-foreground hover:bg-muted hover:border-primary/40 transition-all">
                <Save className="h-4 w-4" />
                {isBn ? "সেভ করুন" : "Save"}
              </button>
              <button
                onClick={handleSaveAndPrint}
                disabled={cart.length === 0}
                className="flex w-full items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-primary to-primary/90 px-3 py-3 text-sm font-bold text-primary-foreground shadow-lg shadow-primary/30 hover:shadow-primary/40 hover:opacity-95 active:scale-[0.98] transition-all disabled:opacity-40 disabled:shadow-none disabled:cursor-not-allowed"
              >
                <Printer className="h-4 w-4" />
                {isBn ? "সেভ & প্রিন্ট" : "Save & Print"}
              </button>
            </div>

          </div>
        </div>
      </div>
    </PageLayout>
  );
}

/* ─── Return Modal Component ─── */
function ReturnModal({ isBn, lang, onClose }: { isBn: boolean; lang: string; onClose: () => void }) {
  const { user } = useAuth();
  const queryClient = useQueryClient();

  // Step management
  const [step, setStep] = useState(1);

  // Step 1: Invoice search
  const [invoiceSearch, setInvoiceSearch] = useState("");
  const [invoiceResults, setInvoiceResults] = useState<any[]>([]);
  const [selectedInvoice, setSelectedInvoice] = useState<any>(null);
  const [invoiceItems, setInvoiceItems] = useState<any[]>([]);

  // Step 2: Product selection
  const [selectedItem, setSelectedItem] = useState<any>(null);
  const [returnQty, setReturnQty] = useState(1);

  // Step 3: Return type & condition
  const [returnType, setReturnType] = useState<"fresh" | "normal" | "replacement">("fresh");
  const [condition, setCondition] = useState<"good" | "damaged">("good");

  // Step 4: Refund
  const [refundOption, setRefundOption] = useState<"full" | "partial" | "none">("none");
  const [refundAmount, setRefundAmount] = useState(0);
  const [refundMethod, setRefundMethod] = useState("cash");

  // Replacement product
  const [replSearch, setReplSearch] = useState("");
  const [replResults, setReplResults] = useState<any[]>([]);
  const [selectedRepl, setSelectedRepl] = useState<any>(null);

  // Search invoices (sales) - searching by a simple text match
  useEffect(() => {
    if (invoiceSearch.length < 2) { setInvoiceResults([]); return; }
    const t = setTimeout(async () => {
      // Search sales_returns won't work, we need to search some invoice reference
      // For now search customer_transactions or use a pattern
      // Since we don't have a sales table with invoice_no, let's search by customer or just allow manual entry
      const { data } = await supabase
        .from("customers")
        .select("id, name, name_bn, mobile")
        .or(`name.ilike.%${invoiceSearch}%,name_bn.ilike.%${invoiceSearch}%,mobile.ilike.%${invoiceSearch}%`)
        .eq("status", "active")
        .limit(5);
      setInvoiceResults(data || []);
    }, 300);
    return () => clearTimeout(t);
  }, [invoiceSearch]);

  // Search replacement products
  useEffect(() => {
    if (replSearch.length < 2) { setReplResults([]); return; }
    const t = setTimeout(async () => {
      const { data } = await supabase
        .from("products")
        .select("id, name, name_bn, sku, stock_quantity, retail_price")
        .or(`name.ilike.%${replSearch}%,name_bn.ilike.%${replSearch}%,sku.ilike.%${replSearch}%`)
        .eq("is_deleted", false)
        .limit(5);
      setReplResults(data || []);
    }, 300);
    return () => clearTimeout(t);
  }, [replSearch]);

  // Auto-detect return type based on condition
  useEffect(() => {
    if (condition === "good") setReturnType("fresh");
    else setReturnType("normal");
  }, [condition]);

  // Auto-calc refund
  useEffect(() => {
    if (refundOption === "full" && selectedItem) {
      setRefundAmount(selectedItem.retail_price * returnQty);
    } else if (refundOption === "none") {
      setRefundAmount(0);
    }
  }, [refundOption, selectedItem, returnQty]);

  // Product search for return (search all products)
  const [prodSearch, setProdSearch] = useState("");
  const [prodResults, setProdResults] = useState<any[]>([]);
  useEffect(() => {
    if (prodSearch.length < 2) { setProdResults([]); return; }
    const t = setTimeout(async () => {
      const { data } = await supabase
        .from("products")
        .select("id, name, name_bn, sku, barcode, stock_quantity, retail_price")
        .or(`name.ilike.%${prodSearch}%,name_bn.ilike.%${prodSearch}%,sku.ilike.%${prodSearch}%,barcode.ilike.%${prodSearch}%`)
        .eq("is_deleted", false)
        .limit(8);
      setProdResults(data || []);
    }, 300);
    return () => clearTimeout(t);
  }, [prodSearch]);

  const submitReturn = useMutation({
    mutationFn: async () => {
      if (!selectedItem) throw new Error("Product required");
      if (returnType === "replacement" && !selectedRepl) throw new Error("Replacement product required");

      const customerId = selectedInvoice?.id || null;
      const invoiceId = invoiceSearch || "";

      // 1. Insert sales_return
      const { data: returnData, error: returnErr } = await supabase
        .from("sales_returns")
        .insert({
          invoice_id: invoiceId,
          customer_id: customerId,
          product_id: selectedItem.id,
          quantity: returnQty,
          return_type: returnType,
          replacement_product_id: returnType === "replacement" ? selectedRepl.id : null,
          refund_amount: refundAmount,
          reason: `${condition === "damaged" ? "Damaged" : "Good condition"} return from POS`,
          status: "completed",
          processed_by: user?.id,
        })
        .select()
        .single();
      if (returnErr) throw returnErr;

      // 2. Stock adjustments
      if (returnType === "fresh") {
        await supabase.from("stock_adjustments").insert({
          product_id: selectedItem.id,
          quantity_change: returnQty,
          reason: `Fresh return from POS`,
          adjusted_by: user?.id,
        });
        await supabase.from("products").update({
          stock_quantity: (selectedItem.stock_quantity || 0) + returnQty,
        }).eq("id", selectedItem.id);
      } else if (returnType === "normal") {
        await supabase.from("damage_stock").insert({
          product_id: selectedItem.id,
          quantity: returnQty,
          source: "return",
          reference_id: returnData.id,
          note: "Damage/Normal return from POS",
        });
      } else if (returnType === "replacement") {
        await supabase.from("damage_stock").insert({
          product_id: selectedItem.id,
          quantity: returnQty,
          source: "replacement",
          reference_id: returnData.id,
          note: `Replaced with ${selectedRepl.name}`,
        });
        await supabase.from("stock_adjustments").insert({
          product_id: selectedRepl.id,
          quantity_change: -returnQty,
          reason: `Replacement issued from POS`,
          adjusted_by: user?.id,
        });
        await supabase.from("products").update({
          stock_quantity: (selectedRepl.stock_quantity || 0) - returnQty,
        }).eq("id", selectedRepl.id);
      }

      // 3. Refund
      if (refundAmount > 0 && customerId) {
        await supabase.from("refunds").insert({
          customer_id: customerId,
          return_id: returnData.id,
          amount: refundAmount,
          payment_method: refundMethod,
          status: "completed",
          processed_by: user?.id,
        });
        await supabase.from("customer_transactions").insert({
          customer_id: customerId,
          type: "refund",
          amount: refundAmount,
          method: refundMethod,
          reference_id: returnData.id,
          note: `Refund from POS return`,
        });
      }

      // 4. Activity log
      await supabase.from("activity_log").insert({
        user_id: user?.id!,
        action: "pos_return",
        entity_type: "sales_returns",
        entity_id: returnData.id,
        details: { return_type: returnType, product: selectedItem.name, quantity: returnQty, refund: refundAmount },
      });
    },
    onSuccess: () => {
      toast.success(isBn ? "রিটার্ন সফলভাবে সম্পন্ন হয়েছে!" : "Return processed successfully!");
      queryClient.invalidateQueries({ queryKey: ["sales_returns"] });
      onClose();
    },
    onError: (err: any) => {
      toast.error(err.message || (isBn ? "কিছু ভুল হয়েছে" : "Something went wrong"));
    },
  });

  const canSubmit = selectedItem && returnQty > 0 && (returnType !== "replacement" || selectedRepl);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm animate-in fade-in duration-200">
      <div className="relative w-full max-w-2xl max-h-[90vh] overflow-y-auto rounded-2xl border border-border bg-card shadow-2xl mx-4 animate-in zoom-in-95 duration-200">
        {/* Header */}
        <div className="sticky top-0 z-10 flex items-center justify-between border-b border-border bg-card px-6 py-4 rounded-t-2xl">
          <h2 className="text-lg font-bold text-foreground flex items-center gap-2">
            <RotateCcw className="h-5 w-5 text-primary" />
            {isBn ? "রিটার্ন / রিপ্লেস / রিফান্ড" : "Return / Replace / Refund"}
          </h2>
          <button onClick={onClose} className="flex h-8 w-8 items-center justify-center rounded-lg hover:bg-muted transition-colors">
            <X className="h-5 w-5 text-muted-foreground" />
          </button>
        </div>

        <div className="p-6 space-y-5">
          {/* Step Indicators */}
          <div className="flex items-center gap-2 overflow-x-auto pb-1">
            {[
              { n: 1, label: isBn ? "ইনভয়েস" : "Invoice" },
              { n: 2, label: isBn ? "পণ্য" : "Product" },
              { n: 3, label: isBn ? "রিটার্ন ধরন" : "Return Type" },
              { n: 4, label: isBn ? "রিফান্ড" : "Refund" },
            ].map((s) => (
              <button
                key={s.n}
                onClick={() => setStep(s.n)}
                className={`flex-shrink-0 inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-semibold transition-all ${
                  step === s.n
                    ? "bg-primary text-primary-foreground shadow-md"
                    : step > s.n
                    ? "bg-green-500/10 text-green-600"
                    : "bg-muted text-muted-foreground"
                }`}
              >
                <span className="flex h-5 w-5 items-center justify-center rounded-full bg-white/20 text-[10px] font-bold">
                  {step > s.n ? "✓" : s.n}
                </span>
                {s.label}
              </button>
            ))}
          </div>

          {/* Step 1: Invoice / Customer */}
          {step === 1 && (
            <div className="space-y-4 animate-in fade-in duration-150">
              <div>
                <label className="text-xs font-medium text-muted-foreground mb-1.5 block">
                  {isBn ? "ইনভয়েস নম্বর / কাস্টমার খুঁজুন" : "Invoice No / Search Customer"}
                </label>
                <div className="relative">
                  <Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                  <input
                    value={selectedInvoice ? `${selectedInvoice.name} (${selectedInvoice.mobile})` : invoiceSearch}
                    onChange={(e) => { setInvoiceSearch(e.target.value); setSelectedInvoice(null); }}
                    placeholder={isBn ? "কাস্টমার নাম, মোবাইল বা ইনভয়েস নম্বর" : "Customer name, mobile or invoice no"}
                    className="w-full rounded-lg border border-border bg-background pl-9 pr-3 py-2.5 text-sm focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none"
                  />
                </div>
                {invoiceResults.length > 0 && !selectedInvoice && (
                  <div className="mt-1 rounded-lg border border-border bg-card shadow-lg max-h-40 overflow-y-auto">
                    {invoiceResults.map((c) => (
                      <button key={c.id} onClick={() => { setSelectedInvoice(c); setInvoiceResults([]); }}
                        className="w-full px-3 py-2 text-left text-sm hover:bg-accent/50 flex justify-between border-b border-border/50 last:border-0">
                        <span>{lang === "bn" ? c.name_bn || c.name : c.name}</span>
                        <span className="text-xs text-muted-foreground">{c.mobile}</span>
                      </button>
                    ))}
                  </div>
                )}
                {selectedInvoice && (
                  <div className="mt-2 rounded-lg border border-green-500/30 bg-green-500/5 p-3 flex items-center justify-between">
                    <div>
                      <p className="text-sm font-medium text-foreground">{selectedInvoice.name}</p>
                      <p className="text-xs text-muted-foreground">{selectedInvoice.mobile}</p>
                    </div>
                    <button onClick={() => setSelectedInvoice(null)} className="text-xs text-destructive hover:underline">
                      {isBn ? "পরিবর্তন" : "Change"}
                    </button>
                  </div>
                )}
              </div>
              <button onClick={() => setStep(2)}
                className="w-full rounded-lg bg-primary py-2.5 text-sm font-semibold text-primary-foreground hover:opacity-90 transition-opacity">
                {isBn ? "পরবর্তী →" : "Next →"}
              </button>
            </div>
          )}

          {/* Step 2: Product Selection */}
          {step === 2 && (
            <div className="space-y-4 animate-in fade-in duration-150">
              <div>
                <label className="text-xs font-medium text-muted-foreground mb-1.5 block">
                  {isBn ? "রিটার্ন পণ্য খুঁজুন" : "Search Return Product"}
                </label>
                <div className="relative">
                  <Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                  <input
                    value={selectedItem ? `${selectedItem.name} (${selectedItem.sku})` : prodSearch}
                    onChange={(e) => { setProdSearch(e.target.value); setSelectedItem(null); }}
                    placeholder={isBn ? "পণ্যের নাম, SKU বা বারকোড" : "Product name, SKU or barcode"}
                    className="w-full rounded-lg border border-border bg-background pl-9 pr-3 py-2.5 text-sm focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none"
                  />
                </div>
                {prodResults.length > 0 && !selectedItem && (
                  <div className="mt-1 rounded-lg border border-border bg-card shadow-lg max-h-48 overflow-y-auto">
                    {prodResults.map((p) => (
                      <button key={p.id} onClick={() => { setSelectedItem(p); setProdResults([]); setProdSearch(""); }}
                        className="w-full px-3 py-2.5 text-left text-sm hover:bg-accent/50 flex justify-between border-b border-border/50 last:border-0">
                        <div>
                          <p className="font-medium">{lang === "bn" ? p.name_bn || p.name : p.name}</p>
                          <p className="text-xs text-muted-foreground">SKU: {p.sku} {p.barcode ? `· ${p.barcode}` : ""}</p>
                        </div>
                        <div className="text-right">
                          <p className="font-semibold">৳{p.retail_price}</p>
                          <p className="text-xs text-muted-foreground">{isBn ? "স্টক" : "Stock"}: {p.stock_quantity}</p>
                        </div>
                      </button>
                    ))}
                  </div>
                )}
              </div>

              {selectedItem && (
                <div className="rounded-lg border border-primary/30 bg-primary/5 p-3">
                  <div className="flex items-center justify-between mb-2">
                    <div>
                      <p className="text-sm font-semibold text-foreground">{selectedItem.name}</p>
                      <p className="text-xs text-muted-foreground">৳{selectedItem.retail_price} | SKU: {selectedItem.sku}</p>
                    </div>
                    <button onClick={() => setSelectedItem(null)} className="text-xs text-destructive hover:underline">
                      {isBn ? "পরিবর্তন" : "Change"}
                    </button>
                  </div>
                  <div>
                    <label className="text-xs font-medium text-muted-foreground">{isBn ? "রিটার্ন পরিমাণ" : "Return Quantity"}</label>
                    <div className="flex items-center gap-2 mt-1">
                      <button onClick={() => setReturnQty(Math.max(1, returnQty - 1))}
                        className="h-8 w-8 rounded-md border border-border flex items-center justify-center hover:bg-muted">
                        <Minus className="h-3 w-3" />
                      </button>
                      <input type="number" min={1} value={returnQty} onChange={(e) => setReturnQty(Math.max(1, Number(e.target.value)))}
                        className="w-16 text-center rounded-md border border-border bg-background py-1 text-sm font-semibold outline-none focus:border-primary" />
                      <button onClick={() => setReturnQty(returnQty + 1)}
                        className="h-8 w-8 rounded-md border border-border flex items-center justify-center hover:bg-muted">
                        <Plus className="h-3 w-3" />
                      </button>
                    </div>
                  </div>
                </div>
              )}

              <div className="flex gap-2">
                <button onClick={() => setStep(1)} className="flex-1 rounded-lg border border-border py-2.5 text-sm font-medium hover:bg-muted transition-colors">
                  {isBn ? "← পূর্ববর্তী" : "← Back"}
                </button>
                <button onClick={() => setStep(3)} disabled={!selectedItem}
                  className="flex-1 rounded-lg bg-primary py-2.5 text-sm font-semibold text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-40">
                  {isBn ? "পরবর্তী →" : "Next →"}
                </button>
              </div>
            </div>
          )}

          {/* Step 3: Return Type & Condition */}
          {step === 3 && (
            <div className="space-y-4 animate-in fade-in duration-150">
              {/* Condition */}
              <div>
                <label className="text-xs font-semibold text-muted-foreground mb-2 block">{isBn ? "পণ্যের অবস্থা" : "Product Condition"}</label>
                <div className="grid grid-cols-2 gap-3">
                  {([
                    { v: "good" as const, label: isBn ? "ভালো" : "Good", color: "text-green-600 border-green-500 bg-green-500/10" },
                    { v: "damaged" as const, label: isBn ? "ক্ষতিগ্রস্ত" : "Damaged", color: "text-red-600 border-red-500 bg-red-500/10" },
                  ]).map((opt) => (
                    <button key={opt.v} onClick={() => setCondition(opt.v)}
                      className={`rounded-lg border-2 p-3 text-sm font-semibold transition-all ${condition === opt.v ? opt.color : "border-border"}`}>
                      {opt.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* Return Type */}
              <div>
                <label className="text-xs font-semibold text-muted-foreground mb-2 block">{isBn ? "রিটার্ন ধরন" : "Return Type"}</label>
                <div className="grid grid-cols-3 gap-2">
                  {([
                    { v: "fresh" as const, icon: RefreshCw, label: isBn ? "ফ্রেশ রিটার্ন" : "Fresh Return", desc: isBn ? "মেইন স্টকে যাবে" : "Back to main stock", color: "text-green-500 border-green-500 bg-green-500/10" },
                    { v: "normal" as const, icon: AlertTriangle, label: isBn ? "ড্যামেজ রিটার্ন" : "Damage Return", desc: isBn ? "ড্যামেজ স্টকে যাবে" : "Goes to damage stock", color: "text-red-500 border-red-500 bg-red-500/10" },
                    { v: "replacement" as const, icon: Replace, label: isBn ? "রিপ্লেসমেন্ট" : "Replacement", desc: isBn ? "নতুন পণ্য দেওয়া হবে" : "Issue new product", color: "text-blue-500 border-blue-500 bg-blue-500/10" },
                  ]).map((opt) => {
                    const Icon = opt.icon;
                    const sel = returnType === opt.v;
                    return (
                      <button key={opt.v} onClick={() => setReturnType(opt.v)}
                        className={`rounded-lg border-2 p-3 text-left transition-all ${sel ? opt.color : "border-border hover:border-muted-foreground/30"}`}>
                        <Icon className={`h-4 w-4 mb-1 ${sel ? "" : "text-muted-foreground"}`} />
                        <p className="text-xs font-semibold">{opt.label}</p>
                        <p className="text-[10px] text-muted-foreground mt-0.5">{opt.desc}</p>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Replacement product search */}
              {returnType === "replacement" && (
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">
                    {isBn ? "রিপ্লেসমেন্ট পণ্য খুঁজুন" : "Search Replacement Product"}
                  </label>
                  <div className="relative">
                    <Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                    <input
                      value={selectedRepl ? `${selectedRepl.name} (${selectedRepl.sku})` : replSearch}
                      onChange={(e) => { setReplSearch(e.target.value); setSelectedRepl(null); }}
                      placeholder={isBn ? "পণ্যের নাম বা SKU" : "Product name or SKU"}
                      className="w-full rounded-lg border border-border bg-background pl-9 pr-3 py-2.5 text-sm focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none"
                    />
                  </div>
                  {replResults.length > 0 && !selectedRepl && (
                    <div className="mt-1 rounded-lg border border-border bg-card shadow-lg max-h-40 overflow-y-auto">
                      {replResults.map((p) => (
                        <button key={p.id} onClick={() => { setSelectedRepl(p); setReplResults([]); setReplSearch(""); }}
                          className="w-full px-3 py-2 text-left text-sm hover:bg-accent/50 flex justify-between border-b border-border/50 last:border-0">
                          <span>{lang === "bn" ? p.name_bn || p.name : p.name}</span>
                          <span className="text-xs text-muted-foreground">৳{p.retail_price} | {isBn ? "স্টক" : "Stock"}: {p.stock_quantity}</span>
                        </button>
                      ))}
                    </div>
                  )}
                  {selectedRepl && (
                    <div className="mt-2 rounded-lg border border-blue-500/30 bg-blue-500/5 p-3 flex items-center justify-between">
                      <div>
                        <p className="text-sm font-medium">{selectedRepl.name}</p>
                        <p className="text-xs text-muted-foreground">৳{selectedRepl.retail_price} | {isBn ? "স্টক" : "Stock"}: {selectedRepl.stock_quantity}</p>
                      </div>
                      <button onClick={() => setSelectedRepl(null)} className="text-xs text-destructive hover:underline">
                        {isBn ? "পরিবর্তন" : "Change"}
                      </button>
                    </div>
                  )}
                </div>
              )}

              <div className="flex gap-2">
                <button onClick={() => setStep(2)} className="flex-1 rounded-lg border border-border py-2.5 text-sm font-medium hover:bg-muted transition-colors">
                  {isBn ? "← পূর্ববর্তী" : "← Back"}
                </button>
                <button onClick={() => setStep(4)} disabled={returnType === "replacement" && !selectedRepl}
                  className="flex-1 rounded-lg bg-primary py-2.5 text-sm font-semibold text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-40">
                  {isBn ? "পরবর্তী →" : "Next →"}
                </button>
              </div>
            </div>
          )}

          {/* Step 4: Refund & Confirm */}
          {step === 4 && (
            <div className="space-y-4 animate-in fade-in duration-150">
              {/* Refund Option */}
              <div>
                <label className="text-xs font-semibold text-muted-foreground mb-2 block">{isBn ? "রিফান্ড অপশন" : "Refund Option"}</label>
                <div className="grid grid-cols-3 gap-2">
                  {([
                    { v: "full" as const, label: isBn ? "সম্পূর্ণ রিফান্ড" : "Full Refund" },
                    { v: "partial" as const, label: isBn ? "আংশিক রিফান্ড" : "Partial Refund" },
                    { v: "none" as const, label: isBn ? "রিফান্ড নেই" : "No Refund" },
                  ]).map((opt) => (
                    <button key={opt.v} onClick={() => setRefundOption(opt.v)}
                      className={`rounded-lg border-2 p-2.5 text-xs font-semibold transition-all ${
                        refundOption === opt.v ? "border-primary bg-primary/10 text-primary" : "border-border"
                      }`}>
                      {opt.label}
                    </button>
                  ))}
                </div>
              </div>

              {refundOption !== "none" && (
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-xs font-medium text-muted-foreground">{isBn ? "রিফান্ড পরিমাণ" : "Refund Amount"}</label>
                    <input type="number" min={0} value={refundAmount} onChange={(e) => setRefundAmount(Number(e.target.value))}
                      className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-primary"
                      readOnly={refundOption === "full"} />
                  </div>
                  <div>
                    <label className="text-xs font-medium text-muted-foreground">{isBn ? "রিফান্ড মাধ্যম" : "Refund Method"}</label>
                    <select value={refundMethod} onChange={(e) => setRefundMethod(e.target.value)}
                      className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-primary">
                      <option value="cash">{isBn ? "নগদ" : "Cash"}</option>
                      <option value="bank">{isBn ? "ব্যাংক" : "Bank"}</option>
                      <option value="mobile">{isBn ? "বিকাশ/নগদ" : "bKash/Nagad"}</option>
                    </select>
                  </div>
                </div>
              )}

              {/* Summary */}
              <div className="rounded-xl bg-muted/30 p-4 space-y-2">
                <h4 className="text-xs font-bold text-foreground mb-2">{isBn ? "সারাংশ" : "Summary"}</h4>
                {selectedInvoice && (
                  <div className="flex justify-between text-xs">
                    <span className="text-muted-foreground">{isBn ? "কাস্টমার" : "Customer"}</span>
                    <span className="font-medium">{selectedInvoice.name}</span>
                  </div>
                )}
                {selectedItem && (
                  <div className="flex justify-between text-xs">
                    <span className="text-muted-foreground">{isBn ? "পণ্য" : "Product"}</span>
                    <span className="font-medium">{selectedItem.name} × {returnQty}</span>
                  </div>
                )}
                <div className="flex justify-between text-xs">
                  <span className="text-muted-foreground">{isBn ? "ধরন" : "Type"}</span>
                  <span className={`font-semibold ${returnType === "fresh" ? "text-green-600" : returnType === "replacement" ? "text-blue-600" : "text-red-600"}`}>
                    {returnType === "fresh" ? (isBn ? "ফ্রেশ রিটার্ন" : "Fresh Return") :
                     returnType === "replacement" ? (isBn ? "রিপ্লেসমেন্ট" : "Replacement") :
                     (isBn ? "ড্যামেজ রিটার্ন" : "Damage Return")}
                  </span>
                </div>
                {selectedRepl && (
                  <div className="flex justify-between text-xs">
                    <span className="text-muted-foreground">{isBn ? "রিপ্লেসমেন্ট পণ্য" : "Replacement"}</span>
                    <span className="font-medium">{selectedRepl.name}</span>
                  </div>
                )}
                {refundAmount > 0 && (
                  <div className="flex justify-between text-xs border-t border-border pt-2 mt-1">
                    <span className="font-semibold text-foreground">{isBn ? "রিফান্ড" : "Refund"}</span>
                    <span className="font-bold text-primary">৳{refundAmount.toLocaleString()}</span>
                  </div>
                )}
              </div>

              <div className="flex gap-2">
                <button onClick={() => setStep(3)} className="flex-1 rounded-lg border border-border py-2.5 text-sm font-medium hover:bg-muted transition-colors">
                  {isBn ? "← পূর্ববর্তী" : "← Back"}
                </button>
                <button onClick={() => submitReturn.mutate()} disabled={!canSubmit || submitReturn.isPending}
                  className="flex-1 rounded-lg bg-primary py-2.5 text-sm font-bold text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-40">
                  {submitReturn.isPending ? <Loader2 className="h-4 w-4 animate-spin mx-auto" /> : (isBn ? "✓ রিটার্ন সম্পন্ন করুন" : "✓ Process Return")}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
