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

import React, { useState, useEffect, useMemo } from 'react';
import {
  Layers,
  Search,
  Plus,
  RefreshCw,
  AlertTriangle,
  TrendingUp,
  Sparkles,
  Check,
  Package,
  ChevronRight,
  TrendingDown,
  Trash2,
  PackageCheck,
  ShieldCheck,
  Tag,
  UploadCloud,
  FileSpreadsheet,
  Palette,
  Info,
  X,
  Server,
  ChevronDown,
  ChevronUp,
  CheckCircle,
  ShoppingCart,
  Inbox,
  Store,
  Activity,
  Award
} from 'lucide-react';
import { ProductMatrixItem } from '../types';
import {
  useFiestaTenantLocations,
  useFiestaStoresStock,
  useFiestaProductCategories,
  useFiestaMasterCatalog,
  useFiestaUpdateStockRequest,
} from '../services/fiestaQueries';
import { FIESTA_TENANT_ID, str as fstr } from '../services/fiestaApi';
import { stockRowToProduct, stockRowToInventory } from '../services/fiestaMappers';
import { useStoreCatalogue } from '../services/storeCatalogue';
import BulkCartDrawer from './BulkCartDrawer';
import AwaitingApi from './AwaitingApi';
import { SlideDrawer, Skeleton, TH_STYLE, SURFACE_ALT, TEXT, TEXT_2, TEXT_3, BORDER, BRAND, tint, edge, StatusChip } from './consoleUi';
import FMCGHoverOverlay from './FMCGHoverOverlay';
import { useCompare } from '../contexts/CompareContext';
import TrialBatchDrawer, { TrialProduct } from './TrialBatchDrawer';

const MOCK_GLOBAL_CATALOG: ProductMatrixItem[] = [
  {
    id: 'gc-1', name: 'Aavin Pure Cow Milk 500ml', sku: 'GC-AAV-500', category: 'Dairy / Milk', 
    unitsSold: 0, revenue: 0, stockStatus: 'Healthy', trend: 'flat', exposure: 'All Outlets', verified: true, isNew: false,
    image: 'https://images.unsplash.com/photo-1550583724-b2692b85b150?auto=format&fit=crop&q=80&w=200'
  },
  {
    id: 'gc-2', name: 'Britannia Whole Wheat Bread', sku: 'GC-BRI-BREAD', category: 'Bakery / Bread',
    unitsSold: 0, revenue: 0, stockStatus: 'Healthy', trend: 'flat', exposure: 'All Outlets', verified: true, isNew: false,
    image: 'https://images.unsplash.com/photo-1509440159596-0249088772ff?auto=format&fit=crop&q=80&w=200'
  },
  {
    id: 'gc-3', name: 'Heritage Farm Fresh Curd 400g', sku: 'GC-HER-CURD', category: 'Dairy / Curd',
    unitsSold: 0, revenue: 0, stockStatus: 'Healthy', trend: 'flat', exposure: 'All Outlets', verified: true, isNew: false,
    image: 'https://images.unsplash.com/photo-1588669527025-a131238ba4fb?auto=format&fit=crop&q=80&w=200'
  },
  {
    id: 'gc-4', name: 'Tata Salt Vacuum Evaporated 1kg', sku: 'GC-TAT-SALT', category: 'Staples / Spices',
    unitsSold: 0, revenue: 0, stockStatus: 'Healthy', trend: 'flat', exposure: 'All Outlets', verified: true, isNew: false,
    image: 'https://images.unsplash.com/photo-1621245039234-f81d113daef4?auto=format&fit=crop&q=80&w=200'
  },
  {
    id: 'gc-5', name: 'Sunfeast Dark Fantasy Choco Fills', sku: 'GC-SUN-CHOC', category: 'Snacks / Biscuits',
    unitsSold: 0, revenue: 0, stockStatus: 'Healthy', trend: 'flat', exposure: 'All Outlets', verified: true, isNew: false,
    image: 'https://images.unsplash.com/photo-1558961363-fa8fdf82db35?auto=format&fit=crop&q=80&w=200'
  },
  {
    id: 'gc-6', name: 'Nandini GoodLife UHT Milk 500ml', sku: 'GC-NAN-UHT', category: 'Dairy / Milk',
    unitsSold: 0, revenue: 0, stockStatus: 'Healthy', trend: 'flat', exposure: 'All Outlets', verified: true, isNew: true,
    image: 'https://images.unsplash.com/photo-1563636619-e9143da7973b?auto=format&fit=crop&q=80&w=200'
  },
  {
    id: 'gc-7', name: 'Maggi 2-Minute Noodles Masala 70g', sku: 'GC-MAG-NOO', category: 'Snacks / Instant',
    unitsSold: 0, revenue: 0, stockStatus: 'Healthy', trend: 'flat', exposure: 'All Outlets', verified: true, isNew: true,
    image: 'https://images.unsplash.com/photo-1612817288484-6f916006741a?auto=format&fit=crop&q=80&w=200'
  },
  {
    id: 'gc-8', name: 'Dettol Original Bathing Soap 75g', sku: 'GC-DET-SOAP', category: 'Personal Care / Soap',
    unitsSold: 0, revenue: 0, stockStatus: 'Healthy', trend: 'flat', exposure: 'All Outlets', verified: true, isNew: true,
    image: 'https://images.unsplash.com/photo-1584824486509-112e4181ff6b?auto=format&fit=crop&q=80&w=200'
  },
  {
    id: 'gc-9', name: 'Surf Excel Easy Wash Detergent 1kg', sku: 'GC-SUR-WASH', category: 'Home Care / Laundry',
    unitsSold: 0, revenue: 0, stockStatus: 'Healthy', trend: 'flat', exposure: 'All Outlets', verified: true, isNew: true,
    image: 'https://images.unsplash.com/photo-1583947215259-38e31be8751f?auto=format&fit=crop&q=80&w=200'
  },
  {
    id: 'gc-10', name: 'MTR Rava Idli Mix 500g', sku: 'GC-MTR-IDL', category: 'Staples / Ready to Cook',
    unitsSold: 0, revenue: 0, stockStatus: 'Healthy', trend: 'flat', exposure: 'All Outlets', verified: true, isNew: true,
    image: 'https://images.unsplash.com/photo-1589301760014-d929f39ce9b0?auto=format&fit=crop&q=80&w=200'
  },
];

type StockRow = Record<string, unknown>;
const rowId = (r: StockRow) => String(r.productid ?? '') || String(r.productname ?? '');


interface InventoryViewProps {
  searchQuery: string;
  isCoimbatoreView: boolean;
  tenantId?: number;
}

export default function InventoryView({
  searchQuery,
  isCoimbatoreView,
  tenantId = FIESTA_TENANT_ID
}: InventoryViewProps) {
  const { selectedProducts, toggleProduct, setIsComparing, clearSelection, setHideCompareBar } = useCompare();
  const [trialProducts, setTrialProducts] = useState<TrialProduct[]>([]);

  // ── Live stock across every outlet (Fiesta) ───────────────────────────────
  // This page is the admin's command surface. The GLOBAL CATALOG is the deduped
  // union of products across all outlets the tenant owns (admin-only import adds
  // to it); the STORE STOCK section shows each outlet's live stock so the admin
  // can see all the stores under them at a glance.
  const locationsQ = useFiestaTenantLocations(tenantId);
  const locations = useMemo(
    () =>
      (locationsQ.data ?? []).map((l) => ({
        locationid: Number(l.locationid),
        locationname: fstr(l.locationname) || `Outlet ${fstr(l.locationid)}`,
        status: fstr(l.status) || 'Active',
      })),
    [locationsQ.data],
  );

  const storesStock = useFiestaStoresStock(
    tenantId,
    locations.map(({ locationid, locationname }) => ({ locationid, locationname })),
  );
  const storesLoading = locationsQ.isLoading || storesStock.some((s) => s.isLoading);
  const storesError =
    locationsQ.isError || (storesStock.length > 0 && storesStock.every((s) => s.isError));

  // Global catalog = deduped union of every outlet's products, plus anything the
  // admin adds/imports in-session. Seeded once from the live data.
  const [products, setProducts] = useState<ProductMatrixItem[]>([]);
  const [seeded, setSeeded] = useState(false);
  const [selectedAdminProduct, setSelectedAdminProduct] = useState<ProductMatrixItem | null>(null);
  const [selectedRequest, setSelectedRequest] = useState<any>(null);

  const allStoreRows = storesStock.flatMap((s) => s.rows);
  useEffect(() => {
    if (seeded || allStoreRows.length === 0) return;
    const byId = new Map<string, StockRow>();
    allStoreRows.forEach((r) => {
      const id = rowId(r);
      if (id && !byId.has(id)) byId.set(id, r);
    });
    
    const initialProducts = Array.from(byId.values()).map(stockRowToProduct);
    
    setProducts(initialProducts);
    setSeeded(true);
  }, [allStoreRows, seeded]);

  const masterCatalogQ = useFiestaMasterCatalog({ tenantid: tenantId });
  const liveMasterCatalog = useMemo(() => masterCatalogQ.data ?? [], [masterCatalogQ.data]);

  const [activeTab, setActiveTab] = useState<'catalog' | 'import_branding' | 'requests'>('catalog');
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [hoveredAdminProduct, setHoveredAdminProduct] = useState<ProductMatrixItem | null>(null);
  const [localSearch, setLocalSearch] = useState('');
  const storeCat = useStoreCatalogue();
  const [globalCatalogSearch, setGlobalCatalogSearch] = useState('');
  const [globalCatalogPicks, setGlobalCatalogPicks] = useState<Set<string>>(new Set());
  const [csvText, setCsvText] = useState('');

  const [requestStoreFilter, setRequestStoreFilter] = useState('All Stores');

  const [storeRequests, setStoreRequests] = useState<{ locationid: number, locationname: string, picks: Record<string, { qty: number; status: 'Pending' | 'Approved' | 'Rejected' | 'Cancelled'; requestedAt: string; resolvedAt?: string }> }[]>([]);

  useEffect(() => {
    if (activeTab === 'requests') {
      const reqs: any[] = [];
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key && key.startsWith('nearledaily.catalogue.request.')) {
          const locIdStr = key.split('.').pop();
          if (locIdStr && locIdStr !== 'na') {
            const locId = parseInt(locIdStr);
            const raw = localStorage.getItem(key);
            if (raw) {
              try {
                const parsed = JSON.parse(raw);
                const picks: Record<string, any> = {};
                for (const [k, v] of Object.entries(parsed)) {
                  if (typeof v === 'number') picks[k] = { qty: v, status: 'Pending', requestedAt: new Date().toISOString() };
                  else {
                    picks[k] = v;
                    if (picks[k].status === 'Approve') picks[k].status = 'Approved';
                    if (picks[k].status === 'Reject') picks[k].status = 'Rejected';
                  }
                }
                if (Object.keys(picks).length > 0) {
                  const loc = locations.find(l => l.locationid === locId);
                  reqs.push({
                    locationid: locId,
                    locationname: loc ? loc.locationname : `Outlet #${locId}`,
                    picks
                  });
                }
              } catch (e) {}
            }
          }
        }
      }
      setStoreRequests(reqs);
    }
  }, [activeTab, locations]);

  const updateStockRequestMutation = useFiestaUpdateStockRequest();

  const updateProductRequestStatus = (locationid: number, productid: string, status: 'Approved' | 'Rejected' | 'Pending') => {
    // Optimistic API update
    updateStockRequestMutation.mutate({
      tenantid: tenantId,
      locationid,
      productid: Number(productid),
      status
    });

    const key = `nearledaily.catalogue.request.${locationid}`;
    const raw = localStorage.getItem(key);
    if (raw) {
      try {
        const picks = JSON.parse(raw);
        if (picks[productid] != null) {
          const existing = typeof picks[productid] === 'number'
            ? { qty: picks[productid], status: 'Pending', requestedAt: new Date().toISOString() }
            : picks[productid];

          picks[productid] = { ...existing, status, resolvedAt: status === 'Pending' ? undefined : new Date().toISOString() };
          localStorage.setItem(key, JSON.stringify(picks));
          
          if (status === 'Approved') {
            const prod = products.find(p => String(p.id) === String(productid)) || MOCK_GLOBAL_CATALOG.find(p => String(p.id) === String(productid));
            if (prod) {
              if (storeCat.has(productid)) {
                storeCat.setQty(productid, storeCat.getQty(productid) + existing.qty);
              } else {
                storeCat.add({
                  productid: String(prod.id),
                  name: prod.name,
                  image: prod.image,
                  category: prod.category,
                  sku: prod.sku,
                  price: prod.unitsSold > 0 ? Math.round(prod.revenue / prod.unitsSold) : 10,
                  unit: prod.exposure || 'Piece',
                  qty: existing.qty
                });
              }
            }
          }

          setStoreRequests(prev => prev.map(r => {
            if (r.locationid === locationid) {
              return { ...r, picks: { ...r.picks, [productid]: picks[productid] } };
            }
            return r;
          }));
        }
      } catch (e) {}
    }
  };

  // Hide compare bar when not in Global Catalogue
  useEffect(() => {
    setHideCompareBar(activeTab !== 'import_branding');
  }, [activeTab, setHideCompareBar]);

  // Live product categories (for the Add-Product modal dropdown).
  const productCategoriesQ = useFiestaProductCategories();
  const productCategoryNames = useMemo(
    () =>
      (productCategoriesQ.data ?? [])
        .map((c) => fstr(c.categoryname))
        .filter((name): name is string => Boolean(name)),
    [productCategoriesQ.data],
  );

  // Categories derived from the live catalog (falls back to ALL only).
  const categories = useMemo(() => {
    const cats = Array.from(new Set(products.map((p) => p.category.split(' / ')[0])));
    return cats.sort();
  }, [products]);

  // Filter criteria
  const filteredProducts = useMemo(() => {
    let result = products;
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      result = result.filter(
        (p) =>
          p.name.toLowerCase().includes(q) ||
          p.sku.toLowerCase().includes(q) ||
          p.category.toLowerCase().includes(q),
      );
    }
    if (localSearch) {
      const q = localSearch.toLowerCase();
      result = result.filter(
        (p) =>
          p.name.toLowerCase().includes(q) ||
          p.sku.toLowerCase().includes(q) ||
          p.category.toLowerCase().includes(q),
      );
    }
    if (selectedCategories.length > 0) {
      result = result.filter((p) => selectedCategories.includes(p.category.split(' / ')[0]));
    }
    return result;
  }, [products, searchQuery, localSearch, selectedCategories]);

  const toggleCategory = (cat: string) => {
    setSelectedCategories((prev) =>
      prev.includes(cat) ? [] : [cat],
    );
  };

  const [globalSelectedCategories, setGlobalSelectedCategories] = useState<string[]>([]);
  
  const globalCategories = useMemo(() => {
    const cats = Array.from(new Set(MOCK_GLOBAL_CATALOG.map((p) => p.category.split(' / ')[0])));
    return cats.sort();
  }, []);

  const filteredGlobalProducts = useMemo(() => {
    let result = MOCK_GLOBAL_CATALOG;
    if (globalCatalogSearch) {
      const q = globalCatalogSearch.toLowerCase();
      result = result.filter(
        (p) => p.name.toLowerCase().includes(q) || p.sku.toLowerCase().includes(q) || p.category.toLowerCase().includes(q)
      );
    }
    if (globalSelectedCategories.length > 0) {
      result = result.filter((p) => globalSelectedCategories.includes(p.category.split(' / ')[0]));
    }
    return result;
  }, [globalCatalogSearch, globalSelectedCategories]);

  const toggleGlobalCategory = (cat: string) => {
    setGlobalSelectedCategories((prev) =>
      prev.includes(cat) ? [] : [cat],
    );
  };



  const handleToggleProductExposure = (id: string) => {
    setProducts(prev => 
      prev.map(p => p.id === id ? { ...p, verified: !p.verified } : p)
    );
  };

  // Custom Raw CSV import
  const handleCSVImport = () => {
    const lines = csvText.split('\n').map(l => l.trim()).filter(l => l.length > 0 && !l.startsWith('Name'));
    if (lines.length === 0) {
      alert('CSV sequence contains no importable entries.');
      return;
    }

    let parsedCount = 0;
    const newProds: ProductMatrixItem[] = [];

    lines.forEach(line => {
      const parts = line.split(',').map(p => p.trim());
      if (parts.length >= 2) {
        const name = parts[0];
        const sku = parts[1];
        const category = parts[2] || 'Staples / Rice';

        if (!products.some(p => p.sku === sku)) {
          newProds.push({
            id: String(products.length + newProds.length + 1),
            name,
            sku,
            unitsSold: 0,
            revenue: 0,
            stockStatus: 'Healthy',
            trend: 'flat',
            image: 'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&q=80&w=200',
            category,
            exposure: 'All Outlets',
            verified: true,
            isNew: true
          });
          parsedCount++;
        }
      }
    });

    if (parsedCount > 0) {
      setProducts(prev => [...newProds, ...prev]);
      alert(`Synchronized ${parsedCount} regional products into Catalogue database successfully!`);
    } else {
      alert('All the specified SKU codes are already active in the catalogue ledger.');
    }
  };
  const flattenedRequests = useMemo(() => {
    const list: any[] = [];
    storeRequests.forEach(req => {
      Object.entries(req.picks).forEach(([productid, pickData]) => {
        let product = products.find(p => String(p.id) === String(productid));
        if (!product) {
          const liveMatch = liveMasterCatalog.find((r: any) => String(r.productid) === String(productid));
          if (liveMatch) {
            product = {
              id: String(liveMatch.productid),
              name: String(liveMatch.productname || 'Unknown'),
              sku: String(liveMatch.sku || `SKU-${liveMatch.productid}`),
              image: String(liveMatch.productimage || 'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&q=80&w=200'),
              category: String(liveMatch.categoryname || 'Uncategorized'),
            } as any;
          } else {
            product = MOCK_GLOBAL_CATALOG.find(p => String(p.id) === String(productid)) as any;
          }
        }
        list.push({
          locationid: req.locationid,
          locationname: req.locationname,
          productid,
          product,
          pickData
        });
      });
    });
    // Sort by requestedAt desc
    let sortedList = list.sort((a, b) => new Date(b.pickData.requestedAt).getTime() - new Date(a.pickData.requestedAt).getTime());
    if (requestStoreFilter !== 'All Stores') {
      sortedList = sortedList.filter(req => req.locationname === requestStoreFilter);
    }
    return sortedList;
  }, [storeRequests, products, requestStoreFilter]);

  const requestingStores = useMemo(() => {
    return Array.from(new Set(locations.map(l => l.locationname))).sort();
  }, [locations]);

  return (
    <div className="flex flex-col h-full animate-in fade-in duration-500 font-sans relative overflow-hidden">
      
      {/* Immersive Background Blur Blobs */}
      <div className="absolute top-10 left-1/4 w-96 h-96 bg-purple-400/5 rounded-full blur-[120px] pointer-events-none -z-10 animate-pulse" />
      <div className="absolute top-40 right-1/4 w-[28rem] h-[28rem] bg-indigo-400/5 rounded-full blur-[140px] pointer-events-none -z-10 animate-pulse" style={{ animationDuration: '8s' }} />

      {/* Header and Metrics */}
      {activeTab === 'catalog' && (
        <div className="mb-8 z-40 relative">
          {/* Small card metrics grid */}
          <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
            {/* Card 1: Total SKUs */}
            <div className="bg-white rounded-xl p-3 border border-slate-200 shadow-sm hover:border-purple-200 transition-all group">
              <div className="flex justify-between items-start">
                <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">Total SKUs</span>
                <div className="p-1.5 rounded-lg bg-purple-50 text-purple-600 group-hover:scale-110 transition-transform">
                  <Package className="w-3.5 h-3.5" />
                </div>
              </div>
              <div className="mt-1">
                <h3 className="text-lg font-extrabold tracking-tight font-mono text-slate-900">
                  {products.length}
                </h3>
                <p className="text-[10px] text-slate-400 font-semibold mt-0.5">Master catalogue</p>
              </div>
            </div>

            {/* Card 2: Synced Outlets */}
            <div className="bg-white rounded-xl p-3 border border-slate-200 shadow-sm hover:border-indigo-200 transition-all group">
              <div className="flex justify-between items-start">
                <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">Active Outlets</span>
                <div className="p-1.5 rounded-lg bg-indigo-50 text-indigo-600 group-hover:scale-110 transition-transform">
                  <Layers className="w-3.5 h-3.5" />
                </div>
              </div>
              <div className="mt-1">
                <h3 className="text-lg font-extrabold tracking-tight font-mono text-slate-900">
                  {locations.length}
                </h3>
                <p className="text-[10px] text-slate-400 font-semibold mt-0.5">Synced locations</p>
              </div>
            </div>

            {/* Card 3: Total On-Hand Volume */}
            <div className="bg-white rounded-xl p-3 border border-slate-200 shadow-sm hover:border-emerald-200 transition-all group">
              <div className="flex justify-between items-start">
                <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">Total Stock</span>
                <div className="p-1.5 rounded-lg bg-emerald-50 text-emerald-600 group-hover:scale-110 transition-transform">
                  <Check className="w-3.5 h-3.5" />
                </div>
              </div>
              <div className="mt-1">
                <h3 className="text-lg font-extrabold tracking-tight font-mono text-slate-900">
                  {storesStock.reduce((total, store) => {
                    return total + (store.rows || []).reduce((subTotal, r) => {
                      const inv = stockRowToInventory(r, store.locationname);
                      return subTotal + (inv.stockLevel || 0);
                    }, 0);
                  }, 0).toLocaleString('en-IN')}
                </h3>
                <p className="text-[10px] text-slate-400 font-semibold mt-0.5">Units on hand</p>
              </div>
            </div>

            {/* Card 4: Catalog Health */}
            <div className="bg-white rounded-xl p-3 border border-slate-200 shadow-sm hover:border-amber-200 transition-all group">
              <div className="flex justify-between items-start">
                <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">Catalogue Sync Ratio</span>
                <div className="p-1.5 rounded-lg bg-amber-50 text-amber-600 group-hover:scale-110 transition-transform">
                  <ShieldCheck className="w-3.5 h-3.5" />
                </div>
              </div>
              <div className="mt-1">
                <h3 className="text-lg font-extrabold tracking-tight font-mono text-slate-900">
                  {products.length > 0 ? `${Math.round((products.filter(p => p.verified).length / products.length) * 100)}%` : '100%'}
                </h3>
                <p className="text-[10px] text-slate-400 font-semibold mt-0.5">Active Portfolio</p>
              </div>
            </div>
          </div>
        </div>
      )}

      {activeTab === 'catalog' ? (
        <>
          <div className="flex flex-col xl:flex-row gap-6 mt-2 flex-1 min-h-0 overflow-hidden pb-4">
            {/* ── Sticky Sidebar (Filters) ── */}
            <div className="w-full xl:w-64 shrink-0 flex flex-col gap-5 overflow-y-auto custom-scrollbar pr-2 pb-2">
            <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
              <div className="p-4 bg-slate-50 border-b border-slate-100">
                <h3 className="font-bold text-slate-800 flex items-center gap-2">
                  <Search size={16} className="text-[#662582]" /> Filter Product
                </h3>
              </div>
              <div className="p-4 space-y-5">
                {/* Search Input */}
                <div className="relative">
                  <input
                    type="text"
                    placeholder="Search products..."
                    value={localSearch}
                    onChange={(e) => setLocalSearch(e.target.value)}
                    className="w-full pl-9 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-800 placeholder-slate-400 focus:outline-none focus:border-[#662582] focus:bg-white focus:ring-1 focus:ring-[#662582]/20 transition-all font-medium"
                  />
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 w-4 h-4" />
                  {localSearch && (
                    <button
                      onClick={() => setLocalSearch('')}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 bg-transparent border-none cursor-pointer"
                    >
                      <X size={12} />
                    </button>
                  )}
                </div>

                <div className="border-t border-slate-100"></div>
                <div>
                  <h3 className="text-[11px] font-extrabold text-slate-400 uppercase tracking-widest mb-3 flex items-center gap-1.5">
                    <Layers size={14} className="text-[#662582]" /> Categories
                  </h3>
                  <div className="space-y-1.5 max-h-[400px] overflow-y-auto pr-2 custom-scrollbar">
                    {categories.map((cat) => (
                      <label key={cat} className="flex items-center gap-3 p-2 rounded-xl hover:bg-slate-50 cursor-pointer group transition-colors">
                        <div className="relative flex items-center justify-center">
                          <input
                            type="checkbox"
                            checked={selectedCategories.includes(cat)}
                            onChange={() => toggleCategory(cat)}
                            className="peer appearance-none w-5 h-5 border-2 border-slate-300 rounded-lg checked:border-[#662582] checked:bg-[#662582] transition-colors cursor-pointer"
                          />
                          <Check size={12} className="absolute text-white opacity-0 peer-checked:opacity-100 pointer-events-none" strokeWidth={3} />
                        </div>
                        <span className={`text-xs font-semibold select-none transition-colors ${selectedCategories.includes(cat) ? 'text-[#662582]' : 'text-slate-600 group-hover:text-slate-900'}`}>
                          {cat}
                        </span>
                      </label>
                    ))}
                  </div>
                </div>

                {(selectedCategories.length > 0 || localSearch) && (
                  <button 
                    onClick={() => { setSelectedCategories([]); setLocalSearch(''); }}
                    className="w-full py-2 bg-slate-100 text-slate-600 rounded-xl text-[10px] font-bold uppercase tracking-wider hover:bg-slate-200 transition-colors cursor-pointer border-none mt-4"
                  >
                    Clear All Filters
                  </button>
                )}
              </div>
            </div>
          </div>

          {/* ── Main Content Area ── */}
          <div className="flex-1 min-w-0 overflow-y-auto custom-scrollbar bg-white/40 backdrop-blur-md border border-[#e2e8f0] p-5 rounded-2xl shadow-sm flex flex-col">
            <div className="flex items-start justify-between mb-5 shrink-0">
              <div>
                <h3 className="font-sans font-bold text-sm text-[#0f172a] flex items-center gap-1.5 flex-wrap">
                  <Package size={15} className="text-[#662582]" /> Product Catalogue Assortment
                  <div className="flex items-center gap-2 ml-2">
                    <span className="text-[10px] text-emerald-700 font-bold bg-emerald-50 px-2 py-0.5 rounded-lg border border-emerald-100">
                      {storeCat.items.length} in store catalogue
                    </span>
                    <span className="text-[10px] text-[#662582] font-bold bg-purple-50 px-2 py-0.5 rounded-lg border border-purple-100/50">
                      {filteredProducts.length} item{filteredProducts.length === 1 ? '' : 's'} loaded
                    </span>
                  </div>
                </h3>
                <p className="text-[10px] text-zinc-400 font-medium mt-1">Pick products & set quantities — selected items appear in every store's catalogue.</p>
              </div>

              <div className="flex items-center gap-3">

                <button 
                  onClick={() => setActiveTab('requests')}
                  className="flex items-center gap-1.5 bg-slate-50 hover:bg-slate-100 border border-slate-200 text-slate-700 px-3 py-1.5 rounded-lg text-xs font-bold transition-colors shadow-sm cursor-pointer"
                >
                  <Inbox size={14} /> Stock Requests
                  {storeRequests.length > 0 && (
                    <span className="ml-1 bg-rose-500 text-white text-[9px] px-1.5 py-0.5 rounded-full">{storeRequests.length}</span>
                  )}
                </button>
                <button 
                  onClick={() => setActiveTab('import_branding')}
                  className="flex items-center gap-1.5 bg-[#662582] hover:bg-purple-800 text-white px-3 py-1.5 rounded-lg text-xs font-bold transition-colors shadow-sm cursor-pointer"
                >
                  <Plus size={14} /> Import Product
                </button>
              </div>
            </div>

            {storesLoading && products.length === 0 ? (
              <div className="grid grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-4">
                {Array.from({ length: 10 }).map((_, i) => (
                  <div key={i} className="bg-white border border-slate-200 rounded-2xl flex flex-col p-2 gap-2 h-64">
                    <Skeleton className="w-full h-28 rounded-xl" />
                    <Skeleton className="w-3/4 h-4 mt-2" />
                    <Skeleton className="w-1/2 h-3" />
                    <div className="grid grid-cols-2 gap-2 mt-auto">
                       <Skeleton className="w-full h-8 rounded-lg" />
                       <Skeleton className="w-full h-8 rounded-lg" />
                    </div>
                    <Skeleton className="w-full h-8 rounded-xl mt-2" />
                  </div>
                ))}
              </div>
            ) : filteredProducts.length === 0 ? (
              <div className="text-center py-xl text-zinc-400 text-xs font-bold">No catalogue products match your selection.</div>
            ) : (
              <div className="flex flex-col xl:flex-row gap-6">
                {/* Left Side: Normal Catalogue */}
                <div className="flex-1 min-w-0">
                  <div className="grid grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-4">
                    {filteredProducts.map((prod) => (
                      <div key={prod.id} onClick={() => setSelectedAdminProduct(prod)} className="cursor-pointer bg-white/80 backdrop-blur-md border border-[#e2e8f0] rounded-2xl flex flex-col shadow-sm hover:shadow-[0_12px_24px_rgba(99,102,241,0.06)] hover:border-[#662582]/40 hover:-translate-y-1 transition-all duration-300 relative group overflow-hidden">
                        {/* Image Section - Top */}
                        <div className="w-full h-28 bg-zinc-50 relative overflow-hidden shrink-0">
                          <img 
                            src={prod.image} 
                            alt={prod.name} 
                            referrerPolicy="no-referrer" 
                            className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700 ease-in-out" 
                          />
                          <div className="absolute inset-0 bg-gradient-to-t from-slate-900/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
                          <div className="absolute top-2 left-2 flex flex-col items-start gap-1">
                            <div className="flex items-center gap-2">
                              <span className={`px-1.5 py-0.5 rounded text-[8px] font-extrabold uppercase shadow-sm ${
                                prod.category.startsWith('Staples') ? 'bg-amber-100 text-amber-800' :
                                prod.category.startsWith('Groceries') ? 'bg-emerald-100 text-emerald-800' :
                                prod.category.startsWith('Beverages') ? 'bg-sky-100 text-sky-800' :
                                'bg-rose-100 text-rose-800'
                              }`}>
                                {prod.category.split(' / ')[0]}
                              </span>
                              {prod.isSample && (
                                <span className="px-1.5 py-0.5 rounded bg-indigo-100 text-indigo-800 text-[8px] font-extrabold uppercase shadow-sm flex items-center gap-1 border border-indigo-200">
                                  <Package size={10} /> SAMPLE
                                </span>
                              )}
                            </div>
                          </div>
                        </div>
                        {/* Cannot be removed from local catalogue if it is active in the store catalogue */}
                        {!storeCat.has(prod.id) && (
                          <button 
                            onClick={(e) => {
                              e.stopPropagation();
                              setProducts(prev => prev.filter(p => p.id !== prod.id));
                            }}
                            className="absolute top-2 right-2 w-7 h-7 bg-white/90 border border-slate-200 rounded-lg flex items-center justify-center text-slate-400 hover:text-rose-500 hover:border-rose-200 hover:bg-rose-50 shadow-sm z-20 opacity-0 group-hover:opacity-100 transition-all cursor-pointer"
                            title="Remove from Product Catalogue"
                          >
                            <Trash2 size={14} />
                          </button>
                        )}

                        {/* Content Section */}
                        <div className="p-3 flex flex-col flex-1 gap-2">
                          <div className="flex items-start justify-between gap-2">
                            <div className="flex-1 min-w-0 pb-2">
                              <h4 className="font-bold text-[#0f172a] text-xs leading-snug group-hover:text-[#662582] transition-colors line-clamp-2">{prod.name}</h4>
                              <p className="text-[10px] text-zinc-500 font-bold font-mono tracking-tight mt-1">{prod.sku}</p>
                            </div>
                          </div>

                          <div className="grid grid-cols-2 gap-1.5 p-2 bg-slate-50/80 rounded-xl border border-slate-100 mt-auto">
                            <div>
                              <span className="text-[9px] text-zinc-400 block uppercase tracking-wider font-extrabold mb-0.5">Units Sold</span>
                              <span className="font-extrabold text-slate-800 font-mono text-xs">{prod.unitsSold.toLocaleString()}</span>
                            </div>
                            <div className="text-right">
                              <span className="text-[9px] text-zinc-400 block uppercase tracking-wider font-extrabold mb-0.5">Revenue</span>
                              <span className="font-black text-emerald-600 font-mono text-xs">₹{prod.revenue.toLocaleString()}</span>
                            </div>
                          </div>

                          <div className="space-y-2 pt-1 border-t border-slate-100">
                            {storeCat.has(prod.id) ? (
                              <div className="flex flex-wrap items-center justify-between gap-2 p-2 bg-emerald-50 rounded-xl border border-emerald-100/50">
                                <span className="inline-flex items-center gap-1.5 text-[10px] font-bold text-emerald-700 whitespace-nowrap"><CheckCircle size={13} /> In Store Catalogue</span>
                                <button onClick={(e) => { e.stopPropagation(); storeCat.remove(prod.id); }} title="Remove from store catalogue" className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg bg-white text-rose-600 hover:bg-rose-50 shadow-sm border border-rose-100 font-bold text-[10px] cursor-pointer transition-colors whitespace-nowrap">
                                  <X size={12} /> Remove
                                </button>
                              </div>
                            ) : (
                              <button
                                onClick={(e) => { e.stopPropagation(); storeCat.add({ productid: prod.id, name: prod.name, image: prod.image, category: prod.category, sku: prod.sku, price: prod.unitsSold > 0 ? Math.round(prod.revenue / prod.unitsSold) : 0, unit: prod.exposure, qty: 1 }); }}
                                className="w-full flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-[11px] font-bold transition-all bg-[#662582]/5 text-[#662582] hover:bg-[#662582] hover:text-white cursor-pointer shadow-sm border border-[#662582]/20"
                                title="Add to Store Catalogue"
                              >
                                <Plus size={14} /> Add to Store Catalogue
                              </button>
                            )}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
        </>
      ) : activeTab === 'import_branding' ? (
        <div className="flex flex-col xl:flex-row gap-6 mt-2 animate-in fade-in duration-300 flex-1 min-h-0 overflow-hidden pb-4">
          
          {/* ── Sticky Sidebar (Filters) ── */}
          <div className="w-full xl:w-64 shrink-0 flex flex-col gap-5 overflow-y-auto custom-scrollbar pr-2 pb-2">
            
            <button
              onClick={() => setActiveTab('catalog')}
              className="flex items-center gap-1.5 bg-white border border-slate-200 text-slate-600 hover:bg-slate-50 hover:text-slate-900 px-4 py-2 rounded-xl text-sm font-bold transition-colors shadow-sm cursor-pointer"
            >
              ← Back to Product Catalogue
            </button>

            <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
              <div className="p-4 bg-slate-50 border-b border-slate-100">
                <h3 className="font-bold text-slate-800 flex items-center gap-2">
                  <Search size={16} className="text-[#662582]" /> Filter Global Product
                </h3>
              </div>
              <div className="p-4 space-y-5">
                {/* Search Input */}
                <div className="relative">
                  <input
                    type="text"
                    placeholder="Search global catalogue..."
                    value={globalCatalogSearch}
                    onChange={(e) => setGlobalCatalogSearch(e.target.value)}
                    className="w-full pl-9 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-800 placeholder-slate-400 focus:outline-none focus:border-[#662582] focus:bg-white focus:ring-1 focus:ring-[#662582]/20 transition-all font-medium"
                  />
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 w-4 h-4" />
                  {globalCatalogSearch && (
                    <button
                      onClick={() => setGlobalCatalogSearch('')}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 bg-transparent border-none cursor-pointer"
                    >
                      <X size={12} />
                    </button>
                  )}
                </div>

                <div className="border-t border-slate-100"></div>
                <div>
                  <h3 className="text-[11px] font-extrabold text-slate-400 uppercase tracking-widest mb-3 flex items-center gap-1.5">
                    <Layers size={14} className="text-[#662582]" /> Categories
                  </h3>
                  <div className="space-y-1.5 max-h-[400px] overflow-y-auto pr-2 custom-scrollbar">
                    {globalCategories.map((cat) => (
                      <label key={cat} className="flex items-center gap-3 p-2 rounded-xl hover:bg-slate-50 cursor-pointer group transition-colors">
                        <div className="relative flex items-center justify-center">
                          <input
                            type="checkbox"
                            checked={globalSelectedCategories.includes(cat)}
                            onChange={() => toggleGlobalCategory(cat)}
                            className="peer appearance-none w-5 h-5 border-2 border-slate-300 rounded-lg checked:border-[#662582] checked:bg-[#662582] transition-colors cursor-pointer"
                          />
                          <Check size={12} className="absolute text-white opacity-0 peer-checked:opacity-100 pointer-events-none" strokeWidth={3} />
                        </div>
                        <span className={`text-xs font-semibold select-none transition-colors ${globalSelectedCategories.includes(cat) ? 'text-[#662582]' : 'text-slate-600 group-hover:text-slate-900'}`}>
                          {cat}
                        </span>
                      </label>
                    ))}
                  </div>
                </div>

                {(globalSelectedCategories.length > 0 || globalCatalogSearch) && (
                  <button 
                    onClick={() => { setGlobalSelectedCategories([]); setGlobalCatalogSearch(''); }}
                    className="w-full py-2 bg-slate-100 text-slate-600 rounded-xl text-[10px] font-bold uppercase tracking-wider hover:bg-slate-200 transition-colors cursor-pointer border-none mt-4"
                  >
                    Clear All Filters
                  </button>
                )}
              </div>
            </div>
          </div>

          {/* ── Main Content Area ── */}
          <div className="flex-1 min-w-0 overflow-y-auto custom-scrollbar bg-white/40 backdrop-blur-md border border-[#e2e8f0] p-5 rounded-2xl shadow-sm flex flex-col">
            <div className="flex items-start justify-between mb-5 shrink-0">
              <div>
                <h3 className="font-sans font-bold text-sm text-[#0f172a] flex items-center gap-1.5 flex-wrap">
                  <Sparkles size={15} className="text-amber-500 animate-pulse" /> Global Catalogue
                  <div className="flex items-center gap-2 ml-2">
                    <span className="text-[10px] text-[#662582] font-bold bg-purple-50 px-2 py-0.5 rounded-lg border border-purple-100/50">
                      {filteredGlobalProducts.length} items available
                    </span>
                  </div>
                </h3>
                <p className="text-[10px] text-zinc-400 font-medium mt-1">Select products from the global ledger to import them into your own catalogue.</p>
              </div>

              <div className="flex items-center gap-3">
                {globalCatalogPicks.size > 0 && (
                  <button
                    onClick={() => {
                      const newProds = MOCK_GLOBAL_CATALOG.filter(p => globalCatalogPicks.has(p.id) && !products.some(ext => ext.sku === p.sku));
                      if (newProds.length > 0) {
                        setProducts(prev => [...newProds, ...prev]);
                        setGlobalCatalogPicks(new Set());
                        setActiveTab('catalog');
                      }
                    }}
                    className="flex items-center gap-1.5 bg-[#662582] hover:bg-purple-800 text-white px-4 py-2 rounded-lg text-xs font-bold transition-colors shadow-sm cursor-pointer animate-in zoom-in-95"
                  >
                    <UploadCloud size={14} /> Import Selected ({globalCatalogPicks.size})
                  </button>
                )}
                {filteredGlobalProducts.filter(p => p.isNew).length > 0 && (
                  <div className="hidden xl:flex items-center gap-2 bg-[#f8fafc] px-3 py-1.5 rounded-lg border border-purple-100/50 mt-1">
                    <Sparkles size={14} className="text-purple-600" />
                    <h4 className="text-[10px] font-bold text-purple-900 uppercase tracking-widest">Recently Added</h4>
                  </div>
                )}
              </div>
            </div>

            <div className="flex flex-col xl:flex-row gap-6">
              {/* Left Side: Normal Catalogue */}
              <div className="flex-1 min-w-0">
                <div className="grid grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-3 pb-8">
                  {filteredGlobalProducts.filter(p => !p.isNew).map((prod) => {
                    const isSelected = globalCatalogPicks.has(prod.id);
                    const isAlreadyInCatalog = products.some(p => p.sku === prod.sku);
                    
                    const wholesalePrice = prod.unitsSold > 0 ? Math.max(1, Math.round(prod.revenue / prod.unitsSold)) : Math.floor(Math.random() * 50) + 20;
                    const mrp = Math.round(wholesalePrice * 1.35);
                    const profit = mrp - wholesalePrice;
                    const profitMargin = Math.round((profit / mrp) * 100);
                    const globalSales = Math.floor(Math.random() * 5000) + 1000;
                    const rating = Number((4.0 + Math.random()).toFixed(1));

                    const premiumTagSeed = (prod.name.length + prod.sku.length) % 3;
                    const premiumTag = premiumTagSeed === 0 ? 'Great Deal' : premiumTagSeed === 1 ? 'High Margin' : 'Trending';
                    const tagColor = premiumTag === 'Great Deal' ? 'bg-emerald-100 text-emerald-800 border-emerald-200' :
                                     premiumTag === 'High Margin' ? 'bg-amber-100 text-amber-800 border-amber-200' :
                                     'bg-indigo-100 text-indigo-800 border-indigo-200';
                    const tagIcon = premiumTag === 'Great Deal' ? <CheckCircle size={10} /> :
                                    premiumTag === 'High Margin' ? <Sparkles size={10} /> :
                                    <TrendingUp size={10} />;
                    const sparklineColor = premiumTag === 'Great Deal' ? 'text-emerald-500' :
                                           premiumTag === 'High Margin' ? 'text-amber-500' :
                                           'text-indigo-500';

                    return (
                      <div 
                        key={prod.id} 
                        onClick={() => setSelectedAdminProduct(prod)}
                        className={`cursor-pointer bg-white/80 backdrop-blur-md border border-[#e2e8f0] rounded-2xl flex flex-col min-h-[340px] shadow-sm transition-all duration-300 relative group overflow-hidden ${
                          isSelected ? 'border-[#662582] shadow-[0_0_0_2px_#662582]' : 'hover:shadow-[0_12px_24px_rgba(99,102,241,0.06)] hover:border-[#662582]/40 hover:-translate-y-1'
                        } ${isAlreadyInCatalog ? 'opacity-60 grayscale-[50%]' : ''}`}
                      >
                        {/* Image Section - Top */}
                        <div className="w-full h-28 bg-zinc-50 relative overflow-hidden shrink-0">
                          <img 
                            src={prod.image} 
                            alt={prod.name} 
                            referrerPolicy="no-referrer" 
                            className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700 ease-in-out" 
                          />
                          <div className="absolute inset-0 bg-gradient-to-t from-slate-900/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
                          <div className="absolute top-2 left-2 flex items-center gap-2">
                            <span className={`px-1.5 py-0.5 rounded text-[8px] font-extrabold uppercase shadow-sm ${
                              prod.category.startsWith('Staples') ? 'bg-amber-100 text-amber-800' :
                              prod.category.startsWith('Groceries') ? 'bg-emerald-100 text-emerald-800' :
                              prod.category.startsWith('Beverages') ? 'bg-sky-100 text-sky-800' :
                              'bg-rose-100 text-rose-800'
                            }`}>
                              {prod.category.split(' / ')[0]}
                            </span>
                          </div>
                          {isAlreadyInCatalog && (
                            <div className="absolute top-2 right-2 z-10 bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded-md text-[9px] font-black tracking-widest shadow-sm flex items-center gap-1 border border-emerald-200 backdrop-blur-md">
                              <CheckCircle size={10} /> IN CATALOGUE
                            </div>
                          )}
                        </div>

                        {/* Content Section */}
                        <div className="p-3 flex flex-col flex-1 gap-2">
                          <div className="flex items-start justify-between gap-2">
                            <div className="grow shrink-0 min-w-0 pb-2">
                              <h4 className="font-bold text-[#0f172a] text-xs leading-snug group-hover:text-[#662582] transition-colors line-clamp-2">{prod.name}</h4>
                              <p className="text-[10px] text-zinc-500 font-bold font-mono tracking-tight mt-1 mb-2">{prod.sku}</p>
                              <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[9px] font-black uppercase tracking-widest shadow-sm border ${tagColor}`}>
                                {tagIcon} {premiumTag}
                              </span>
                            </div>
                            
                            <div 
                              className="shrink-0 z-10"
                              onClick={(e) => {
                                e.stopPropagation();
                                toggleProduct({
                                  id: prod.id,
                                  name: prod.name,
                                  sku: prod.sku,
                                  category: prod.category.split(' / ')[0],
                                  price: mrp,
                                  image: prod.image,
                                  wholesalePrice,
                                  mrp,
                                  profitMargin,
                                  rating,
                                  globalSales,
                                  isGlobal: true,
                                  verified: prod.verified
                                });
                              }}
                            >
                              <label className="relative flex items-center justify-center cursor-pointer group/cb">
                                <input 
                                  type="checkbox" 
                                  className="peer appearance-none w-5 h-5 bg-slate-50 border border-slate-300 rounded-md checked:bg-[#662582] checked:border-[#662582] transition-all"
                                  checked={selectedProducts.some(p => String(p.id) === String(prod.id))}
                                  readOnly
                                />
                                <Check size={12} className="absolute text-white opacity-0 peer-checked:opacity-100 pointer-events-none" strokeWidth={3} />
                              </label>
                            </div>
                          </div>

                              <div className="flex items-center justify-between p-2 bg-indigo-50/50 rounded-xl border border-indigo-100/50 mt-auto">
                                <div>
                                  <span className="text-[8px] text-slate-500 block uppercase tracking-wider font-extrabold mb-0.5">Wholesale</span>
                                  <span className="font-black text-indigo-900 font-mono text-xs">₹{wholesalePrice}</span>
                                </div>
                                <div className="text-center">
                                  <span className="text-[8px] text-emerald-600 block uppercase tracking-wider font-extrabold mb-0.5">Margin</span>
                                  <span className="font-black text-emerald-600 font-mono text-xs bg-emerald-100 px-1.5 py-0.5 rounded-md">+{profitMargin}%</span>
                                </div>
                                <div className="text-right">
                                  <span className="text-[8px] text-slate-500 block uppercase tracking-wider font-extrabold mb-0.5">Retail</span>
                                  <span className="font-black text-slate-900 font-mono text-xs">₹{mrp}</span>
                                </div>
                              </div>


                          <div className="space-y-2 pt-1 border-t border-slate-100">
                            <div className="flex justify-between items-center select-none">
                              <span className={`inline-flex items-center gap-1.5 text-[10px] font-bold tracking-tight ${isAlreadyInCatalog ? 'text-emerald-600' : 'text-zinc-500'}`}>
                                <span className={`w-1.5 h-1.5 rounded-full ${isAlreadyInCatalog ? 'bg-emerald-500 animate-pulse' : 'bg-zinc-300'}`} />
                                {isAlreadyInCatalog ? 'Synced to Local' : 'Available for Import'}
                              </span>
                            </div>

                            {isAlreadyInCatalog ? (
                              <div className="flex flex-wrap items-center justify-center gap-2 p-2 bg-emerald-50 rounded-xl border border-emerald-100/50">
                                <span className="inline-flex items-center gap-1.5 text-[10px] font-bold text-emerald-700 whitespace-nowrap"><CheckCircle size={13} /> Already in Catalogue</span>
                              </div>
                            ) : (
                              <button
                                onClick={(e) => {
                                  e.stopPropagation();
                                  setProducts(prev => [prod, ...prev]);
                                  setActiveTab('catalog');
                                }}
                                className="w-full flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-[11px] font-bold transition-all bg-[#662582]/5 text-[#662582] hover:bg-[#662582] hover:text-white cursor-pointer shadow-sm border border-[#662582]/20"
                              >
                                <Plus size={14} /> Import to Catalogue
                              </button>
                            )}
                            <button
                              onClick={(e) => { 
                                e.stopPropagation(); 
                                setTrialProducts([{
                                  id: prod.id,
                                  name: prod.name,
                                  sku: prod.sku,
                                  category: prod.category.split(' / ')[0],
                                  price: prod.revenue / Math.max(1, prod.unitsSold),
                                  image: prod.image
                                }]);
                              }}
                              className="w-full flex items-center justify-center gap-1.5 py-2 rounded-xl text-[11px] font-bold transition-all bg-indigo-50 text-indigo-700 hover:bg-indigo-600 hover:text-white cursor-pointer border border-indigo-100 hover:border-indigo-600"
                            >
                              <Package size={14} /> Request Sample
                            </button>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Right Side: Recently Added Items */}
              {filteredGlobalProducts.filter(p => p.isNew).length > 0 && (
                <div className="w-full xl:w-72 shrink-0 xl:border-l xl:border-purple-100/50 xl:pl-6 relative">
                  <div className="flex flex-col gap-md">
                    {filteredGlobalProducts.filter(p => p.isNew).map((prod) => {
                      const isAlreadyInCatalog = products.some(p => p.sku === prod.sku);
                      
                      const wholesalePrice = prod.unitsSold > 0 ? Math.max(1, Math.round(prod.revenue / prod.unitsSold)) : Math.floor(Math.random() * 50) + 20;
                      const mrp = Math.round(wholesalePrice * 1.35);
                      const profitMargin = Math.round(((mrp - wholesalePrice) / mrp) * 100);
                      const globalSales = Math.floor(Math.random() * 5000) + 1000;
                      const rating = Number((4.0 + Math.random()).toFixed(1));

                      const premiumTagSeed = (prod.name.length + prod.sku.length) % 3;
                      const premiumTag = premiumTagSeed === 0 ? 'Great Deal' : premiumTagSeed === 1 ? 'High Margin' : 'Trending';
                      const tagColor = premiumTag === 'Great Deal' ? 'bg-emerald-100 text-emerald-800 border-emerald-200' :
                                       premiumTag === 'High Margin' ? 'bg-amber-100 text-amber-800 border-amber-200' :
                                       'bg-indigo-100 text-indigo-800 border-indigo-200';
                      const tagIcon = premiumTag === 'Great Deal' ? <CheckCircle size={10} /> :
                                      premiumTag === 'High Margin' ? <Sparkles size={10} /> :
                                      <TrendingUp size={10} />;
                      const sparklineColor = premiumTag === 'Great Deal' ? 'text-emerald-500' :
                                             premiumTag === 'High Margin' ? 'text-amber-500' :
                                             'text-indigo-500';

                      return (
                        <div 
                          key={prod.id} 
                        onClick={() => setSelectedAdminProduct(prod)}
                          className={`bg-white/80 backdrop-blur-md border border-[#e2e8f0] rounded-2xl flex flex-col min-h-[340px] shadow-sm transition-all duration-300 relative group overflow-hidden hover:shadow-[0_12px_24px_rgba(99,102,241,0.06)] hover:border-[#662582]/40 hover:-translate-y-1 ${isAlreadyInCatalog ? 'opacity-60 grayscale-[50%]' : ''}`}
                        >
                          {/* Image Section - Top */}
                          <div className="w-full h-28 bg-zinc-50 relative overflow-hidden shrink-0">
                            <img 
                              src={prod.image} 
                              alt={prod.name} 
                              referrerPolicy="no-referrer" 
                              className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700 ease-in-out" 
                            />
                            <div className="absolute inset-0 bg-gradient-to-t from-slate-900/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
                            <div className="absolute top-2 left-2 flex items-center gap-2">
                              <span className={`px-1.5 py-0.5 rounded text-[8px] font-extrabold uppercase shadow-sm ${
                                prod.category.startsWith('Staples') ? 'bg-amber-100 text-amber-800' :
                                prod.category.startsWith('Groceries') ? 'bg-emerald-100 text-emerald-800' :
                                prod.category.startsWith('Beverages') ? 'bg-sky-100 text-sky-800' :
                                'bg-rose-100 text-rose-800'
                              }`}>
                                {prod.category.split(' / ')[0]}
                              </span>
                            </div>
                            {isAlreadyInCatalog && (
                              <div className="absolute top-2 right-2 z-10 bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded-md text-[9px] font-black tracking-widest shadow-sm flex items-center gap-1 border border-emerald-200 backdrop-blur-md">
                                <CheckCircle size={10} /> IN CATALOGUE
                              </div>
                            )}
                          </div>

                          {/* Content Section */}
                          <div className="p-3 flex flex-col flex-1 gap-2">
                            <div className="flex items-start justify-between gap-2">
                              <div className="grow shrink-0 min-w-0 pb-2">
                                <h4 className="font-bold text-[#0f172a] text-xs leading-snug group-hover:text-[#662582] transition-colors line-clamp-2">{prod.name}</h4>
                                <p className="text-[10px] text-zinc-500 font-bold font-mono tracking-tight mt-1 mb-2">{prod.sku}</p>
                                <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[9px] font-black uppercase tracking-widest shadow-sm border ${tagColor}`}>
                                  {tagIcon} {premiumTag}
                                </span>
                              </div>
                              
                              <div 
                                className="shrink-0 z-10"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  toggleProduct({
                                    id: prod.id,
                                    name: prod.name,
                                    sku: prod.sku,
                                    category: prod.category.split(' / ')[0],
                                    price: mrp,
                                    image: prod.image,
                                    wholesalePrice,
                                    mrp,
                                    profitMargin,
                                    rating,
                                    globalSales,
                                    isGlobal: true,
                                    verified: prod.verified
                                  });
                                }}
                              >
                                <label className="relative flex items-center justify-center cursor-pointer group/cb">
                                  <input 
                                    type="checkbox" 
                                    className="peer appearance-none w-5 h-5 bg-slate-50 border border-slate-300 rounded-md checked:bg-[#662582] checked:border-[#662582] transition-all"
                                    checked={selectedProducts.some(p => String(p.id) === String(prod.id))}
                                    readOnly
                                  />
                                  <Check size={12} className="absolute text-white opacity-0 peer-checked:opacity-100 pointer-events-none" strokeWidth={3} />
                                </label>
                              </div>
                            </div>

                                <div className="flex items-center justify-between p-2 bg-indigo-50/50 rounded-xl border border-indigo-100/50 mt-auto">
                                  <div>
                                    <span className="text-[8px] text-slate-500 block uppercase tracking-wider font-extrabold mb-0.5">Wholesale</span>
                                    <span className="font-black text-indigo-900 font-mono text-xs">₹{wholesalePrice}</span>
                                  </div>
                                  <div className="text-center">
                                    <span className="text-[8px] text-emerald-600 block uppercase tracking-wider font-extrabold mb-0.5">Margin</span>
                                    <span className="font-black text-emerald-600 font-mono text-xs bg-emerald-100 px-1.5 py-0.5 rounded-md">+{profitMargin}%</span>
                                  </div>
                                  <div className="text-right">
                                    <span className="text-[8px] text-slate-500 block uppercase tracking-wider font-extrabold mb-0.5">Retail</span>
                                    <span className="font-black text-slate-900 font-mono text-xs">₹{mrp}</span>
                                  </div>
                                </div>


                            <div className="space-y-2 pt-1 border-t border-slate-100">
                              <div className="flex justify-between items-center select-none">
                                <span className={`inline-flex items-center gap-1.5 text-[10px] font-bold tracking-tight ${isAlreadyInCatalog ? 'text-emerald-600' : 'text-zinc-500'}`}>
                                  <span className={`w-1.5 h-1.5 rounded-full ${isAlreadyInCatalog ? 'bg-emerald-500 animate-pulse' : 'bg-zinc-300'}`} />
                                  {isAlreadyInCatalog ? 'Synced to Local' : 'Available for Import'}
                                </span>
                              </div>

                              {isAlreadyInCatalog ? (
                                <div className="flex flex-wrap items-center justify-center gap-2 p-2 bg-emerald-50 rounded-xl border border-emerald-100/50">
                                  <span className="inline-flex items-center gap-1.5 text-[10px] font-bold text-emerald-700 whitespace-nowrap"><CheckCircle size={13} /> Already in Catalogue</span>
                                </div>
                              ) : (
                                <button
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    setProducts(prev => [prod, ...prev]);
                                    setActiveTab('catalog');
                                  }}
                                  className="w-full flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-[11px] font-bold transition-all bg-[#662582]/5 text-[#662582] hover:bg-[#662582] hover:text-white cursor-pointer shadow-sm border border-[#662582]/20"
                                >
                                  <Plus size={14} /> Import to Catalogue
                                </button>
                              )}
                              <button
                                onClick={(e) => { 
                                  e.stopPropagation(); 
                                  setTrialProducts([{
                                    id: prod.id,
                                    name: prod.name,
                                    sku: prod.sku,
                                    category: prod.category.split(' / ')[0],
                                    price: prod.revenue / Math.max(1, prod.unitsSold),
                                    image: prod.image
                                  }]);
                                }}
                                className="w-full flex items-center justify-center gap-1.5 py-2 rounded-xl text-[11px] font-bold transition-all bg-indigo-50 text-indigo-700 hover:bg-indigo-600 hover:text-white cursor-pointer border border-indigo-100 hover:border-indigo-600"
                              >
                                <Package size={14} /> Request Sample
                              </button>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      ) : activeTab === 'requests' ? (
        <div className="flex-1 overflow-y-auto mt-4 pr-2 custom-scrollbar animate-in fade-in duration-300">
          <div className="flex justify-between items-center mb-6">
            <div>
              <h2 className="text-xl font-black text-slate-900 tracking-tight flex items-center gap-2">
                <Inbox size={22} className="text-[#662582]" /> Pending Stock Requests
              </h2>
              <p className="text-xs font-bold text-slate-500 mt-1 uppercase tracking-widest">Store Branch Inventory Requests</p>
            </div>
            <div className="flex items-center gap-3">
              <select 
                value={requestStoreFilter}
                onChange={(e) => setRequestStoreFilter(e.target.value)}
                className="bg-white border border-slate-200 text-slate-700 px-4 py-2 rounded-xl text-xs font-bold shadow-sm outline-none cursor-pointer focus:border-purple-300 transition-colors"
              >
                <option value="All Stores">All Stores</option>
                {requestingStores.map(store => (
                  <option key={store} value={store}>{store}</option>
                ))}
              </select>
              <button
                onClick={() => setActiveTab('catalog')}
                className="flex items-center gap-1.5 bg-white border border-slate-200 text-slate-600 hover:bg-slate-50 px-4 py-2 rounded-xl text-sm font-bold shadow-sm cursor-pointer transition-colors"
              >
                ← Back to Catalogue
              </button>
            </div>
          </div>
          {flattenedRequests.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-64 bg-white/40 border border-slate-200 rounded-2xl">
              <Inbox size={48} className="text-slate-300 mb-4" />
              <h3 className="text-lg font-bold text-slate-500">No Pending Requests</h3>
              <p className="text-xs text-slate-400">All store stock requests have been processed.</p>
            </div>
          ) : (
            <div className="bg-white border rounded-2xl overflow-hidden" style={{ borderColor: BORDER }}>
              <div className="overflow-x-auto">
                <table className="w-full" style={{ minWidth: 960 }}>
                  <thead>
                    <tr>
                      {['Requested At', 'Store', 'Product', 'Qty', 'Status', 'Resolved At', ''].map((h, i) => (
                        <th key={i} className="px-3 py-2.5 text-left" style={TH_STYLE}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {flattenedRequests.map((req, idx) => {
                      const isApproved = req.pickData.status === 'Approved';
                      const isRejected = req.pickData.status === 'Rejected';
                      const isPending = req.pickData.status === 'Pending';
                      const isCancelled = req.pickData.status === 'Cancelled';
                      const color = isApproved ? '#10b981' : isRejected ? '#f43f5e' : isCancelled ? '#94a3b8' : '#f59e0b';
                      const DIVIDER_C = '#f1f5f9';
                      
                      return (
                        <tr key={`${req.locationid}-${req.productid}-${idx}`} className="transition-colors" style={{ borderBottom: `1px solid ${DIVIDER_C}`, background: 'transparent' }}
                          onMouseEnter={(e) => { e.currentTarget.style.background = SURFACE_ALT; }} onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}>
                          <td className="px-3 py-2.5">
                            <span className="text-xs font-mono" style={{ color: TEXT_3 }}>
                              {req.pickData.requestedAt ? new Date(req.pickData.requestedAt).toLocaleString('en-IN', { dateStyle: 'medium', timeStyle: 'short' }) : '—'}
                            </span>
                          </td>
                          <td className="px-3 py-2.5">
                            <span className="inline-flex items-center gap-1 font-bold text-[12px]" style={{ color: BRAND }}>
                              <Store size={11} /> {req.locationname}
                            </span>
                          </td>
                          <td className="px-3 py-2.5">
                            <div className="flex items-center gap-3">
                              <img src={req.product?.image} alt={req.product?.name} className="w-8 h-8 rounded-md object-cover border" style={{ borderColor: BORDER }} />
                              <div>
                                <p className="font-bold text-[12px] truncate max-w-[200px]" style={{ color: TEXT }}>{req.product?.name}</p>
                                <p className="text-[10px] truncate max-w-[200px]" style={{ color: TEXT_2 }}>{req.product?.sku}</p>
                              </div>
                            </div>
                          </td>
                          <td className="px-3 py-2.5 font-mono text-[12px]" style={{ color: TEXT }}>
                            {req.pickData.qty || '—'}
                          </td>
                          <td className="px-3 py-2.5">
                            <StatusChip label={req.pickData.status || '—'} color={color} />
                          </td>
                          <td className="px-3 py-2.5">
                            <span className="text-xs font-mono" style={{ color: TEXT_3 }}>
                              {req.pickData.resolvedAt ? new Date(req.pickData.resolvedAt).toLocaleString('en-IN', { dateStyle: 'medium', timeStyle: 'short' }) : '—'}
                            </span>
                          </td>
                          <td className="px-3 py-2.5 text-right">
                            {isPending ? (
                              <div className="flex items-center justify-end gap-2">
                                <button 
                                  onClick={(e) => { e.stopPropagation(); updateProductRequestStatus(req.locationid, req.productid, 'Approved'); }}
                                  className="rounded-full font-extrabold cursor-pointer transition-colors text-white"
                                  style={{ padding: '4px 12px', fontSize: 11, background: '#10b981', border: '1px solid #059669' }}
                                  title="Approve"
                                >
                                  Approve
                                </button>
                                <button 
                                  onClick={(e) => { e.stopPropagation(); updateProductRequestStatus(req.locationid, req.productid, 'Rejected'); }}
                                  className="rounded-full font-extrabold cursor-pointer transition-colors"
                                  style={{ padding: '4px 12px', fontSize: 11, color: '#f43f5e', background: tint('#f43f5e'), border: `1px solid ${edge('#f43f5e')}` }}
                                  title="Reject"
                                >
                                  Reject
                                </button>
                              </div>
                            ) : (
                              <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                                Processed
                              </span>
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      ) : null}

      {/* ── Slide Drawer ── */}
      <SlideDrawer
        isOpen={selectedAdminProduct !== null}
        onClose={() => setSelectedAdminProduct(null)}
        title="Administrative Product Details"
      >
        {selectedAdminProduct && (() => {
          const wholesalePrice = selectedAdminProduct.unitsSold > 0 ? Math.max(1, Math.round(selectedAdminProduct.revenue / selectedAdminProduct.unitsSold)) : Math.floor(Math.random() * 50) + 20;
          const mrp = Math.round(wholesalePrice * 1.35);
          const profit = mrp - wholesalePrice;
          const profitMargin = Math.round((profit / mrp) * 100);
          const isAlreadyInCatalog = products.some(p => p.sku === selectedAdminProduct.sku);

          return (
          <div className="flex flex-col gap-8 pb-8">
            
            {/* Clean Image Container */}
            <div className="w-full h-64 bg-white rounded-2xl border border-slate-200 overflow-hidden relative flex items-center justify-center p-4">
              <img src={selectedAdminProduct.image} alt={selectedAdminProduct.name} className="w-auto h-full max-w-full object-contain mix-blend-multiply" />
            </div>

            {/* Title & Basics */}
            <div>
              <p className="text-xs font-semibold text-slate-500 tracking-wider mb-1">SKU: {selectedAdminProduct.sku}</p>
              <h3 className="text-2xl font-bold text-slate-900 leading-tight mb-3">{selectedAdminProduct.name}</h3>
              <div className="flex flex-wrap items-center gap-2">
                <span className="px-2.5 py-1 rounded bg-slate-100 text-slate-600 text-[10px] font-semibold uppercase tracking-widest border border-slate-200">
                  {String(selectedAdminProduct.category || '').split(' / ')[0]}
                </span>
                {isAlreadyInCatalog && (
                  <span className="px-2.5 py-1 rounded bg-emerald-50 text-emerald-700 text-[10px] font-semibold uppercase tracking-widest border border-emerald-200 flex items-center gap-1.5">
                    <CheckCircle size={12} strokeWidth={2.5} /> In Catalogue
                  </span>
                )}
              </div>
            </div>

            {/* Clean Margin Engine */}
            <div className="bg-slate-50 rounded-2xl border border-slate-200 p-6 space-y-5">
              <h4 className="text-sm font-semibold text-slate-800 flex items-center gap-2">
                <TrendingUp size={16} className="text-slate-400" /> Margin Summary
              </h4>
              
              <div className="flex items-center justify-between">
                <div className="space-y-1">
                  <span className="text-xs font-semibold text-slate-500">Wholesale Price</span>
                  <div className="text-xl font-bold text-slate-900">₹{wholesalePrice}</div>
                </div>
                
                <div className="h-8 w-px bg-slate-200" />
                
                <div className="space-y-1">
                  <span className="text-xs font-semibold text-slate-500">Retail (MRP)</span>
                  <div className="text-xl font-bold text-slate-900">₹{mrp}</div>
                </div>

                <div className="h-8 w-px bg-slate-200" />
                
                <div className="space-y-1 text-right">
                  <span className="text-xs font-semibold text-emerald-600">Your Profit</span>
                  <div className="text-xl font-bold text-emerald-700">₹{profit} <span className="text-sm text-emerald-600 font-medium">({profitMargin}%)</span></div>
                </div>
              </div>
            </div>

            {/* Minimal Global Stats */}
            <div className="flex gap-4">
               <div className="flex-1 bg-white p-4 rounded-2xl border border-slate-200 flex items-center justify-between">
                  <span className="text-xs font-semibold text-slate-500 flex items-center gap-1.5">
                    <Store size={14} className="text-slate-400" /> Monthly Sales
                  </span>
                  <span className="text-base font-bold text-slate-900">
                    {Math.floor(Math.random() * 5000) + 1000} <span className="text-xs font-semibold text-slate-500">Units</span>
                  </span>
               </div>
               <div className="flex-1 bg-white p-4 rounded-2xl border border-slate-200 flex items-center justify-between">
                  <span className="text-xs font-semibold text-slate-500 flex items-center gap-1.5">
                    <Award size={14} className="text-slate-400" /> Global Rating
                  </span>
                  <span className="text-base font-bold text-slate-900 flex items-center gap-1">
                    {(4.0 + Math.random()).toFixed(1)} <span className="text-amber-500 text-lg leading-none">★</span>
                  </span>
               </div>
            </div>

              {/* Action Area */}
              <div className="space-y-3 pt-4 border-t border-slate-100">
                {isAlreadyInCatalog ? (
                  <div className="space-y-3">
                    <div className="flex items-center justify-center gap-2 p-4 bg-emerald-50 rounded-xl border border-emerald-200">
                      <CheckCircle size={18} className="text-emerald-600" />
                      <span className="text-sm font-semibold text-emerald-800">Synced to Local Catalogue</span>
                    </div>
                    {storeCat.has(selectedAdminProduct.id) ? (
                      <button onClick={() => storeCat.remove(selectedAdminProduct.id)} className="w-full flex items-center justify-center gap-2 py-3.5 rounded-xl bg-white text-rose-600 border border-slate-200 font-semibold text-sm transition-colors hover:bg-slate-50">
                        <X size={18} strokeWidth={2} /> Remove from Store Catalogue
                      </button>
                    ) : (
                      <button onClick={() => storeCat.add({ productid: selectedAdminProduct.id, name: selectedAdminProduct.name, image: selectedAdminProduct.image, category: selectedAdminProduct.category, sku: selectedAdminProduct.sku, price: selectedAdminProduct.unitsSold > 0 ? Math.round(selectedAdminProduct.revenue / selectedAdminProduct.unitsSold) : 0, unit: selectedAdminProduct.exposure, qty: 1 })} className="w-full flex items-center justify-center gap-2 py-3.5 rounded-xl text-sm font-semibold transition-colors bg-[#662582] text-white hover:bg-[#531e6a]">
                        <Plus size={18} strokeWidth={2} /> Add to Store Catalogue
                      </button>
                    )}
                    {!storeCat.has(selectedAdminProduct.id) && (
                      <button
                        onClick={() => {
                          setProducts(prev => prev.filter(p => p.id !== selectedAdminProduct.id));
                          setSelectedAdminProduct(null);
                        }}
                        className="w-full flex items-center justify-center gap-2 py-3.5 rounded-xl bg-white text-rose-600 border border-slate-200 font-semibold text-sm transition-colors hover:bg-slate-50 mt-2"
                      >
                        <Trash2 size={18} strokeWidth={2} /> Delete from Local Catalogue
                      </button>
                    )}
                  </div>
                ) : (
                  <div className="flex gap-3">
                    <button
                      onClick={() => {
                        setProducts(prev => [selectedAdminProduct, ...prev]);
                        setSelectedAdminProduct(null);
                        setActiveTab('catalog');
                      }}
                      className="flex-1 flex items-center justify-center gap-2 py-3.5 rounded-xl text-sm font-semibold transition-colors bg-[#662582] text-white hover:bg-[#531e6a]"
                    >
                      <Plus size={18} strokeWidth={2} /> Import Local
                    </button>
                    <button
                      onClick={() => { 
                        setTrialProducts([{
                          id: selectedAdminProduct.id,
                          name: selectedAdminProduct.name,
                          sku: selectedAdminProduct.sku,
                          category: String(selectedAdminProduct.category || '').split(' / ')[0],
                          price: selectedAdminProduct.revenue / Math.max(1, selectedAdminProduct.unitsSold),
                          image: selectedAdminProduct.image
                        }]);
                      }}
                      className="w-auto px-6 flex items-center justify-center gap-2 py-3.5 rounded-xl text-sm font-semibold transition-colors bg-white text-slate-700 border border-slate-200 hover:bg-slate-50"
                      title="Request Sample"
                    >
                      <Package size={18} strokeWidth={2} /> Sample
                    </button>
                  </div>
                )}

                <div className="flex gap-3 pt-2">
                  {!isAlreadyInCatalog && (
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        toggleProduct({
                          id: selectedAdminProduct.id,
                          name: selectedAdminProduct.name,
                          sku: selectedAdminProduct.sku,
                          category: String(selectedAdminProduct.category || '').split(' / ')[0],
                          price: mrp,
                          image: selectedAdminProduct.image,
                          wholesalePrice,
                          mrp,
                          profitMargin,
                          rating: 4.5,
                          globalSales: 1000,
                          isGlobal: true,
                          verified: selectedAdminProduct.verified
                        });
                      }}
                      className={`flex-1 flex items-center justify-center gap-2 py-3.5 rounded-xl text-sm font-semibold transition-colors border ${selectedProducts.some(p => String(p.id) === String(selectedAdminProduct.id)) ? 'bg-purple-50 text-purple-700 border-purple-200' : 'bg-white text-slate-700 border-slate-200 hover:bg-slate-50'}`}
                    >
                      {selectedProducts.some(p => String(p.id) === String(selectedAdminProduct.id)) ? <Check size={18} strokeWidth={2} /> : <CheckCircle size={18} strokeWidth={2} />}
                      {selectedProducts.some(p => String(p.id) === String(selectedAdminProduct.id)) ? 'Selected for Bulk' : 'Select for Bulk'}
                    </button>
                  )}
                </div>
              </div>

            <p className="text-sm text-slate-500 leading-relaxed mt-2 border-t border-slate-100 pt-5">
              This product is part of the Global Catalogue. Importing it will add it to your local inventory where you can manage pricing and availability.
            </p>
            
            <div className="mt-2">
              <h4 className="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-2">Retail Packaging Info</h4>
              <FMCGHoverOverlay productId={selectedAdminProduct.id} category={selectedAdminProduct.category} productName={selectedAdminProduct.name} />
            </div>
          </div>
          );
        })()}
      </SlideDrawer>

      {/* ── Slide Drawer for Stock Requests ── */}
      <SlideDrawer
        isOpen={selectedRequest !== null}
        onClose={() => setSelectedRequest(null)}
        title="Stock Request Details"
      >
        {selectedRequest && (() => {
          const req = selectedRequest;
          const isPending = req.pickData.status === 'Pending';
          const isApproved = req.pickData.status === 'Approved';
          const isRejected = req.pickData.status === 'Rejected';
          const isCancelled = req.pickData.status === 'Cancelled';
          const prod = req.product;
          
          return (
            <div className="flex flex-col gap-5">
              {prod ? (
                <div className="w-full h-64 bg-slate-50 rounded-2xl overflow-hidden border border-slate-100 relative">
                  <img src={prod.image} alt={prod.name} className="w-full h-full object-cover" />
                  <div className="absolute top-3 left-3 flex flex-col gap-2">
                    <span className="px-2.5 py-1.5 rounded-lg bg-white/90 text-slate-800 text-[10px] font-black uppercase shadow-sm tracking-wider">
                      {String(prod.category || '').split(' / ')[0]}
                    </span>
                  </div>
                </div>
              ) : (
                <div className="w-full h-32 bg-slate-100 rounded-2xl flex items-center justify-center border border-slate-200">
                  <span className="text-slate-400 font-bold">Product Image Not Found</span>
                </div>
              )}

              <div>
                <h3 className="text-xl font-black text-slate-900 leading-tight mb-2">{prod?.name || 'Unknown Product'}</h3>
                <p className="text-xs font-bold text-slate-400 font-mono tracking-wider">{prod?.sku || `SKU-${req.productid}`}</p>
                
                <div className="mt-4 flex flex-col gap-2 p-4 bg-slate-50 rounded-xl border border-slate-100">
                   <div className="flex justify-between items-center">
                     <span className="text-[10px] font-extrabold uppercase tracking-widest text-slate-400">Requesting Store</span>
                     <span className="text-sm font-bold text-slate-800">{req.locationname}</span>
                   </div>
                   <div className="flex justify-between items-center">
                     <span className="text-[10px] font-extrabold uppercase tracking-widest text-slate-400">Requested Qty</span>
                     <span className="text-sm font-black font-mono text-[#662582]">{req.pickData.qty} Units</span>
                   </div>
                   <div className="flex justify-between items-center">
                     <span className="text-[10px] font-extrabold uppercase tracking-widest text-slate-400">Status</span>
                     <span className={`text-xs font-black uppercase tracking-wider ${isApproved ? 'text-emerald-600' : isRejected ? 'text-rose-600' : 'text-amber-600'}`}>
                       {req.pickData.status}
                     </span>
                   </div>
                </div>
              </div>

              {/* Action Area */}
              <div className="space-y-3 pt-3 border-t border-slate-100">
                <h4 className="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-2">Process Request</h4>
                
                {isPending ? (
                  <div className="flex gap-3">
                    <button 
                      onClick={() => { updateProductRequestStatus(req.locationid, req.productid, 'Approved'); setSelectedRequest(null); }}
                      className="flex-1 py-3 rounded-xl font-extrabold cursor-pointer transition-colors text-white flex items-center justify-center gap-2 shadow-sm"
                      style={{ background: '#10b981', border: '1px solid #059669' }}
                    >
                      <CheckCircle size={18} /> Approve Stock
                    </button>
                    <button 
                      onClick={() => { updateProductRequestStatus(req.locationid, req.productid, 'Rejected'); setSelectedRequest(null); }}
                      className="flex-1 py-3 rounded-xl font-extrabold cursor-pointer transition-colors text-rose-600 flex items-center justify-center gap-2 shadow-sm"
                      style={{ background: tint('#f43f5e'), border: `1px solid ${edge('#f43f5e')}` }}
                    >
                      <X size={18} /> Reject
                    </button>
                  </div>
                ) : (
                  <div className="flex items-center justify-center gap-2 p-3 bg-slate-50 rounded-xl border border-slate-200 shadow-sm text-center">
                    <span className="text-sm font-bold text-slate-500">
                      This request has been {req.pickData.status.toLowerCase()}.
                    </span>
                  </div>
                )}
              </div>
              
              {prod && (
                <div className="mt-2">
                  <h4 className="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-2">Retail Packaging Info</h4>
                  <FMCGHoverOverlay productId={prod.id} category={prod.category} productName={prod.name} />
                </div>
              )}
            </div>
          );
        })()}
      </SlideDrawer>

      <TrialBatchDrawer 
        isOpen={trialProducts.length > 0} 
        onClose={() => setTrialProducts([])} 
        product={trialProducts[0] || null} 
        tenantId={tenantId}
        onSuccess={(tp) => {
          const globalProd = MOCK_GLOBAL_CATALOG.find(p => p.id === tp.id);
          if (globalProd) {
            setProducts(prev => {
              if (prev.some(p => p.id === globalProd.id)) return prev;
              return [{ ...globalProd, isSample: true, isNew: true }, ...prev];
            });
            setActiveTab('catalog');
          }
        }}
      />

      {/* ── Floating Import Button ── */}
      {activeTab === 'import_branding' && selectedProducts.length > 0 && (
        <button 
          onClick={() => {
            setProducts(prev => {
              const newProducts = selectedProducts.map(sp => ({
                id: sp.id,
                name: sp.name,
                sku: sp.sku,
                category: sp.category,
                price: sp.price,
                image: sp.image,
                isNew: true
              }));
              const filteredNew = newProducts.filter(np => !prev.some(p => p.id === np.id));
              return [...filteredNew, ...prev];
            });
            clearSelection();
            setActiveTab('catalog');
          }}
          className="fixed bottom-8 right-8 z-[100] px-6 h-14 bg-[#662582] text-white rounded-full shadow-[0_10px_25px_rgba(102,37,130,0.5)] flex items-center justify-center gap-2.5 hover:scale-105 hover:bg-purple-800 transition-all duration-300 animate-in slide-in-from-bottom-10 group"
        >
          <Plus size={20} />
          <span className="font-bold text-sm">Import {selectedProducts.length} Product{selectedProducts.length > 1 ? 's' : ''}</span>
        </button>
      )}



    </div>
  );
}
