/**
 * @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
} from 'lucide-react';
import { ProductMatrixItem } from '../types';
import {
  useFiestaTenantLocations,
  useFiestaStoresStock,
  useFiestaProductCategories,
} 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 AwaitingApi from './AwaitingApi';

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) {
  // ── 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 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);
    });
    setProducts(Array.from(byId.values()).map(stockRowToProduct));
    setSeeded(true);
  }, [allStoreRows, seeded]);

  const [activeTab, setActiveTab] = useState<'catalog' | 'import_branding'>('catalog');
  const [selectedCategory, setSelectedCategory] = useState<string>('ALL');
  // The store catalogue the admin curates from the global catalogue (shown to users).
  const storeCat = useStoreCatalogue();
  const [showAddProductModal, setShowAddProductModal] = useState(false);
  const [outletFilter, setOutletFilter] = useState<'all' | 'alerts'>('all');
  const [outletSearch, setOutletSearch] = useState('');
  // Regional Hub Stocks is read-only for admins — overrides remain empty (no restock actions).
  const [restockedOverrides] = useState<Record<number, Record<string, number>>>({});
  const [expandedHubs, setExpandedHubs] = useState<Record<number, boolean>>({});

  // Memoize storesStock query results merged with simulated restock overrides
  const storesStockWithOverrides = useMemo(() => {
    return storesStock.map(store => {
      const overrides = restockedOverrides[store.locationid];
      if (!overrides) return store;
      
      const newRows = store.rows.map(row => {
        const sku = `SKU-${String(row.productid ?? '') || String(row.productname ?? '')}`;
        if (overrides[sku] !== undefined) {
          return {
            ...row,
            closing: overrides[sku],
            opening: Math.max(Number(row.opening || 0), overrides[sku])
          };
        }
        return row;
      });
      
      return {
        ...store,
        rows: newRows
      };
    });
  }, [storesStock, restockedOverrides]);

  // Memoized alerts analysis for all stores, using overridden data
  const storeAlertsData = useMemo(() => {
    let alertOutletsCount = 0;
    let criticalCount = 0;
    let lowStockCount = 0;
    const outletsWithAlerts: number[] = [];

    storesStockWithOverrides.forEach(store => {
      const items = store.rows.map(r => stockRowToInventory(r, store.locationname));
      const hasCritical = items.some(it => it.status === 'Critical');
      const hasLow = items.some(it => it.status === 'Low Stock');

      if (hasCritical || hasLow) {
        alertOutletsCount++;
        outletsWithAlerts.push(store.locationid);
      }
      criticalCount += items.filter(it => it.status === 'Critical').length;
      lowStockCount += items.filter(it => it.status === 'Low Stock').length;
    });

    return {
      alertOutletsCount,
      criticalCount,
      lowStockCount,
      outletsWithAlerts
    };
  }, [storesStockWithOverrides]);

  // CSV Textarea input
  const [csvText, setCsvText] = useState(
    "Name, SKU, Category, Price, InitialStock\nAmma Ghee Pure Butter, GHEE-AMMA-1L, Groceries / Oils, 640, 200\nBhavani Ponni Sona Rice, ST-SONA-25K, Staples / Rice, 1350, 150"
  );

  // Form state for individual adding
  const [newProduct, setNewProduct] = useState({
    name: '',
    sku: '',
    category: 'Staples / Rice',
    price: 150,
    initialStock: 250,
    image: 'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&q=80&w=200'
  });

  // 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 categorySet = new Set<string>();
  products.forEach((p) => categorySet.add(p.category));
  const categories: string[] = ['ALL', ...Array.from(categorySet)];

  // Filter criteria
  const filteredProducts = products.filter(p => {
    const matchesSearch = p.name.toLowerCase().includes(searchQuery.toLowerCase()) || 
                          p.sku.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          p.category.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCat = selectedCategory === 'ALL' || p.category.startsWith(selectedCategory.split(' / ')[0]);
    return matchesSearch && matchesCat;
  });

  const handleAddNewProduct = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newProduct.name || !newProduct.sku) {
      alert('Kindly supply correct product specifications and catalogue SKU code.');
      return;
    }

    const createdProd: ProductMatrixItem = {
      id: String(products.length + 1),
      name: newProduct.name,
      sku: newProduct.sku,
      unitsSold: 0,
      revenue: 0,
      stockStatus: 'Healthy',
      trend: 'flat',
      image: newProduct.image,
      category: newProduct.category,
      exposure: 'All Outlets',
      verified: true
    };

    setProducts([createdProd, ...products]);
    setShowAddProductModal(false);
    alert(`Fresh product "${createdProd.name}" added to the Global Catalogue. It is now available to roll out to all outlets.`);

    setNewProduct({
      name: '',
      sku: '',
      category: 'Staples / Rice',
      price: 150,
      initialStock: 250,
      image: 'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&q=80&w=200'
    });
  };

  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
          });
          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.');
    }
  };

  return (
    <div className="space-y-lg animate-in fade-in duration-500 font-sans relative">
      
      {/* 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' }} />

      {/* ── Immersive Analytics Banner (With Catalog Cover Image & Slate Gradient Overlay) ── */}
      <div className="relative rounded-2xl p-6 md:p-8 text-white shadow-xl border border-purple-500/20 mb-8 animate-in fade-in duration-300 z-40">
        {/* Cover Image Background & Decor */}
        <div className="absolute inset-0 z-0 overflow-hidden rounded-2xl">
          <img
            src="https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&w=1200&q=80"
            alt="Catalogue Command Center Banner"
            className="w-full h-full object-cover object-center opacity-30"
          />
          <div className="absolute inset-0 bg-gradient-to-r from-slate-950 via-slate-900/95 to-purple-950/85" />
          
          {/* Background decorative glowing circles */}
          <div className="absolute top-0 right-0 w-72 h-72 bg-purple-500/10 rounded-full blur-3xl -mr-20 -mt-20 pointer-events-none z-0" />
          <div className="absolute bottom-0 left-0 w-56 h-56 bg-slate-500/5 rounded-full blur-2xl -ml-20 -mb-20 pointer-events-none z-0" />
        </div>

        {/* Content Row */}
        <div className="relative z-20 flex flex-col md:flex-row md:items-center justify-between gap-6">
          <div>
            <h1 className="font-sans font-bold text-2xl tracking-tight text-white flex items-center gap-2">
              <Layers size={24} className="text-purple-300" />
              Product Catalogue
              <span className="text-[10px] text-purple-200 font-bold bg-purple-900/60 border border-purple-500/30 px-2 py-0.5 rounded-full uppercase tracking-wider animate-pulse">
                Global Sync
              </span>
            </h1>
            <p className="text-purple-250 font-sans text-xs mt-1.5 font-medium max-w-2xl">
              Master catalogue registry with regional assortment presets, brand styling studio, and live stock synchronization feeds.
            </p>
          </div>

          {/* Navigation Tab pills styled like a modern control unit */}
          <div className="flex items-center gap-1.5 bg-slate-950/60 backdrop-blur-md border border-white/10 p-1.5 rounded-xl shrink-0">
            <button
              onClick={() => setActiveTab('catalog')}
              className={`px-4 py-2 rounded-lg text-xs font-bold transition-all duration-300 flex items-center gap-2 cursor-pointer ${
                activeTab === 'catalog'
                  ? 'bg-purple-900/50 text-purple-200 border border-purple-500/40 shadow-[0_0_15px_rgba(168,85,247,0.2)]'
                  : 'text-zinc-400 hover:text-white border border-transparent'
              }`}
            >
              <Package size={13} />
              <span>Catalogue & Stocks</span>
            </button>
            
            <button
              onClick={() => setActiveTab('import_branding')}
              className={`px-4 py-2 rounded-lg text-xs font-bold transition-all duration-300 flex items-center gap-2 cursor-pointer ${
                activeTab === 'import_branding'
                  ? 'bg-purple-900/50 text-purple-200 border border-purple-500/40 shadow-[0_0_15px_rgba(168,85,247,0.2)]'
                  : 'text-zinc-400 hover:text-white border border-transparent'
              }`}
            >
              <UploadCloud size={13} />
              <span>Import & Brand Studio</span>
            </button>
          </div>
        </div>

        {/* Small card metrics grid - 4 dynamic columns inside the banner */}
        <div className="grid grid-cols-1 sm:grid-cols-4 gap-4 mt-8 pt-6 border-t border-slate-800/80 relative z-10">
          
          {/* Card 1: Total SKUs */}
          <div className="bg-slate-900/40 backdrop-blur-sm rounded-xl p-4 border border-slate-800/80 hover:border-purple-500/30 transition-all group">
            <div className="flex justify-between items-start">
              <span className="text-[10px] text-slate-400 uppercase tracking-widest font-bold">Total SKUs</span>
              <div className="p-2 rounded-lg bg-purple-500/10 text-purple-400 border border-purple-500/20 group-hover:scale-110 transition-transform">
                <Package className="w-4 h-4" />
              </div>
            </div>
            <div className="mt-2">
              <h3 className="text-xl font-extrabold tracking-tight font-mono">
                {products.length}
              </h3>
              <p className="text-[10px] text-purple-400 font-semibold mt-1">Master catalogue</p>
            </div>
          </div>

          {/* Card 2: Synced Outlets */}
          <div className="bg-slate-900/40 backdrop-blur-sm rounded-xl p-4 border border-slate-800/80 hover:border-purple-500/30 transition-all group">
            <div className="flex justify-between items-start">
              <span className="text-[10px] text-slate-400 uppercase tracking-widest font-bold">Active Outlets</span>
              <div className="p-2 rounded-lg bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 group-hover:scale-110 transition-transform">
                <Layers className="w-4 h-4" />
              </div>
            </div>
            <div className="mt-2">
              <h3 className="text-xl font-extrabold tracking-tight font-mono">
                {locations.length}
              </h3>
              <p className="text-[10px] text-indigo-400 font-semibold mt-1">Synced locations</p>
            </div>
          </div>

          {/* Card 3: Total On-Hand Volume */}
          <div className="bg-slate-900/40 backdrop-blur-sm rounded-xl p-4 border border-slate-800/80 hover:border-purple-500/30 transition-all group">
            <div className="flex justify-between items-start">
              <span className="text-[10px] text-slate-400 uppercase tracking-widest font-bold">Total Stock</span>
              <div className="p-2 rounded-lg bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 group-hover:scale-110 transition-transform">
                <Check className="w-4 h-4" />
              </div>
            </div>
            <div className="mt-2">
              <h3 className="text-xl font-extrabold tracking-tight font-mono">
                {storesStockWithOverrides.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-emerald-400 font-semibold mt-1">Units on hand</p>
            </div>
          </div>

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

        </div>
      </div>

      {activeTab === 'catalog' ? (
        <>
          {/* Category filter + admin import actions */}
          <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between py-2">
            
            {/* Themed Category Badges */}
            <div className="flex flex-wrap gap-2">
              {categories.map((cat) => {
                const isSelected = selectedCategory === cat;
                let badgeTheme = '';
                
                if (cat === 'ALL') {
                  badgeTheme = isSelected
                    ? 'bg-indigo-600 border-indigo-600 text-white shadow-sm'
                    : 'bg-white text-indigo-700 border-indigo-100 hover:bg-indigo-50';
                } else if (cat.startsWith('Staples')) {
                  badgeTheme = isSelected
                    ? 'bg-amber-600 border-amber-600 text-white shadow-sm'
                    : 'bg-white text-amber-700 border-amber-100 hover:bg-amber-50';
                } else if (cat.startsWith('Groceries')) {
                  badgeTheme = isSelected
                    ? 'bg-emerald-600 border-emerald-600 text-white shadow-sm'
                    : 'bg-white text-emerald-700 border-emerald-100 hover:bg-emerald-50';
                } else if (cat.startsWith('Beverages')) {
                  badgeTheme = isSelected
                    ? 'bg-sky-600 border-sky-600 text-white shadow-sm'
                    : 'bg-white text-sky-700 border-sky-100 hover:bg-sky-50';
                } else {
                  badgeTheme = isSelected
                    ? 'bg-rose-600 border-rose-600 text-white shadow-sm'
                    : 'bg-white text-rose-700 border-rose-100 hover:bg-rose-50';
                }

                return (
                  <button
                    key={cat}
                    onClick={() => setSelectedCategory(cat)}
                    className={`px-3 py-1.5 rounded-xl font-sans text-xs font-bold tracking-wide transition-all duration-200 border cursor-pointer outline-none ${badgeTheme}`}
                  >
                    {cat === 'ALL'
                      ? '🌐 All Items'
                      : cat.replace('Groceries / ', '').replace('Staples / ', '').replace('Beverages / ', '').replace('Fresh Produce / ', '')}
                  </button>
                );
              })}
            </div>

            <div className="flex items-center gap-sm">
              <button
                onClick={() => setActiveTab('import_branding')}
                className="bg-white text-[#581c87] border border-purple-200 px-4 py-2 rounded-lg text-xs font-bold uppercase tracking-wider flex items-center justify-center gap-xs cursor-pointer hover:bg-[#faf5ff] transition shadow-sm"
              >
                <UploadCloud size={14} />
                Import SKUs
              </button>
              <button
                onClick={() => setShowAddProductModal(true)}
                className="bg-[#581c87] text-white px-xl py-2 rounded-lg text-xs font-bold uppercase tracking-wider flex items-center justify-center gap-xs cursor-pointer hover:bg-purple-800 transition shadow-sm"
              >
                <Plus size={14} />
                Add SKU
              </button>
            </div>
          </div>

          {/* Global Catalog — master assortment grid (full width) */}
          <div className="bg-white/40 backdrop-blur-md border border-[#e2e8f0] p-md rounded-2xl text-xs font-sans shadow-sm">
            <div className="flex items-center justify-between mb-sm">
              <div>
                <h3 className="font-sans font-bold text-sm text-[#0f172a] flex items-center gap-1.5">
                  <Package size={15} className="text-[#581c87]" /> Global Catalogue Assortment
                </h3>
                <p className="text-[10px] text-zinc-400 font-medium mt-0.5">Pick products & set quantities — selected items appear in every store's catalogue.</p>
              </div>
              <div className="flex items-center gap-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-[#581c87] 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>
            </div>

            {storesLoading && products.length === 0 ? (
              <div className="text-center py-xl text-zinc-400 text-xs font-bold">Synchronizing regional database...</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="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-md">
                {filteredProducts.map((prod) => (
                  <div key={prod.id} className="bg-white/80 backdrop-blur-md border border-[#e2e8f0] rounded-2xl p-md flex flex-col justify-between gap-sm shadow-sm hover:shadow-[0_12px_24px_rgba(99,102,241,0.06)] hover:border-purple-200 hover:-translate-y-0.5 transition-all duration-300 relative group">
                    <div className="flex gap-md">
                      {/* Image zoom effect on hover */}
                      <div className="w-16 h-16 rounded-xl border border-zinc-100 shrink-0 overflow-hidden bg-zinc-50 relative">
                        <img 
                          src={prod.image} 
                          alt={prod.name} 
                          referrerPolicy="no-referrer" 
                          className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" 
                        />
                      </div>
                      <div className="flex-1 space-y-1 min-w-0">
                        <div className="flex items-start justify-between gap-2">
                          <div className="min-w-0">
                            <h4 className="font-bold text-[#0f172a] leading-tight text-xs truncate group-hover:text-[#581c87] transition-colors">{prod.name}</h4>
                            <span className="text-[10px] text-zinc-400 font-bold font-mono tracking-tight">{prod.sku}</span>
                          </div>
                          
                          {/* Categorized pill badge */}
                          <span className={`px-1.5 py-0.5 rounded text-[8px] font-extrabold uppercase shrink-0 ${
                            prod.category.startsWith('Staples') ? 'bg-amber-50 text-amber-600 border border-amber-100' :
                            prod.category.startsWith('Groceries') ? 'bg-emerald-50 text-emerald-600 border border-emerald-100' :
                            prod.category.startsWith('Beverages') ? 'bg-sky-50 text-sky-600 border border-sky-100' :
                            'bg-rose-50 text-rose-600 border border-rose-100'
                          }`}>
                            {prod.category.split(' / ')[0]}
                          </span>
                        </div>

                        <div className="flex justify-between items-center pt-2">
                          <div>
                            <span className="text-[8px] text-zinc-400 block uppercase tracking-wider font-extrabold">Units Sold</span>
                            <span className="font-extrabold text-zinc-755 font-mono text-xs">{prod.unitsSold.toLocaleString()}</span>
                          </div>
                          <div className="text-right">
                            <span className="text-[8px] text-zinc-400 block uppercase tracking-wider font-extrabold">Revenue</span>
                            <span className="font-black text-emerald-600 font-mono text-xs">₹{prod.revenue.toLocaleString()}</span>
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* Exposure toggle row */}
                    <div className="flex justify-between items-center pt-2.5 border-t border-[#f1f5f9] mt-1 select-none">
                      <span className={`inline-flex items-center gap-1.5 text-[10px] font-bold tracking-tight ${
                        prod.verified ? 'text-emerald-600' : 'text-zinc-400'
                      }`}>
                        <span className={`w-1.5 h-1.5 rounded-full ${prod.verified ? 'bg-emerald-500 animate-pulse' : 'bg-zinc-300'}`} />
                        {prod.verified ? 'Active Portfolio' : 'Under Inspection'}
                      </span>
                      
                      <label className="relative inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={prod.verified}
                          onChange={() => handleToggleProductExposure(prod.id)}
                          className="sr-only peer"
                        />
                        <div className="w-8 h-4.5 bg-slate-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-350 after:border after:rounded-full after:h-3.5 after:w-3.5 after:transition-all peer-checked:bg-emerald-500 shadow-inner"></div>
                      </label>
                    </div>

                    {/* Store-catalogue curation: pick the product + quantity to show to store users */}
                    {storeCat.has(prod.id) ? (
                      <div className="flex items-center justify-between gap-2 pt-2.5 border-t border-[#f1f5f9] mt-1">
                        <span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-600"><CheckCircle size={12} /> In Store Catalogue</span>
                        <div className="flex items-center gap-1">
                          <button onClick={() => storeCat.setQty(prod.id, storeCat.getQty(prod.id) - 1)} className="w-6 h-6 rounded-lg border border-[#e2e8f0] text-zinc-500 hover:bg-zinc-50 font-bold cursor-pointer leading-none">−</button>
                          <span className="w-8 text-center font-mono font-bold text-xs text-[#0f172a]">{storeCat.getQty(prod.id)}</span>
                          <button onClick={() => storeCat.setQty(prod.id, storeCat.getQty(prod.id) + 1)} className="w-6 h-6 rounded-lg border border-[#e2e8f0] text-zinc-500 hover:bg-zinc-50 font-bold cursor-pointer leading-none">+</button>
                          <button onClick={() => storeCat.remove(prod.id)} title="Remove from store catalogue" className="ml-1 w-6 h-6 rounded-lg text-rose-500 hover:bg-rose-50 flex items-center justify-center cursor-pointer"><X size={13} /></button>
                        </div>
                      </div>
                    ) : (
                      <button
                        onClick={() => 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 pt-2.5 mt-1 border-t border-[#f1f5f9] text-[11px] font-bold text-[#581c87] hover:text-purple-800 cursor-pointer"
                      >
                        <Plus size={13} /> Add to Store Catalogue
                      </button>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Store Stock — live per-outlet breakdown for every store under the admin */}
          <div className="space-y-md text-xs font-sans">
            
            {/* Elegant Header Row */}
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-slate-100 pb-4 mt-8 select-none">
              <div className="flex items-start gap-3 font-sans">
                <div className="h-10 w-10 shrink-0 rounded-xl bg-gradient-to-br from-purple-500 to-indigo-500 text-white flex items-center justify-center shadow-sm">
                  <Server size={18} />
                </div>
                <div className="space-y-1">
                  <div className="flex items-center gap-2 flex-wrap">
                    <h3 className="font-bold text-base text-slate-900 tracking-tight">Regional Hub Stocks</h3>
                    <span className="inline-flex items-center gap-1 text-[9px] font-bold bg-emerald-50 text-emerald-600 border border-emerald-100/50 px-2 py-0.5 rounded-full">
                      <span className="w-1 h-1 rounded-full bg-emerald-500 animate-pulse" />
                      Live Sync
                    </span>
                  </div>
                  <p className="text-slate-400 text-[11px] font-medium">
                    Real-time inventory levels and capacity balance across {locations.length} regional outlets.
                  </p>
                </div>
              </div>

              {/* Controls: Search + Filters */}
              <div className="flex flex-wrap items-center gap-3">
                {/* Search */}
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 w-3.5 h-3.5" />
                  <input
                    type="text"
                    placeholder="Search regional hubs..."
                    value={outletSearch}
                    onChange={(e) => setOutletSearch(e.target.value)}
                    className="pl-8 pr-7 py-1.5 bg-slate-50 border border-slate-200 rounded-full text-xs text-slate-800 placeholder-slate-400 focus:outline-none focus:border-purple-500 focus:bg-white focus:ring-1 focus:ring-purple-500/20 transition-all w-48 font-medium"
                  />
                  {outletSearch && (
                    <button
                      onClick={() => setOutletSearch('')}
                      className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 border-none bg-transparent cursor-pointer text-xs"
                    >
                      ✕
                    </button>
                  )}
                </div>

                {/* Filter buttons */}
                <div className="flex bg-slate-100 border border-slate-200 p-0.5 rounded-full">
                  <button
                    onClick={() => setOutletFilter('all')}
                    className={`px-3 py-1 rounded-full text-[10px] font-bold uppercase transition-all duration-200 cursor-pointer border-none ${
                      outletFilter === 'all'
                        ? 'bg-white text-purple-700 shadow-sm border border-purple-100/30'
                        : 'text-slate-500 hover:text-slate-850 bg-transparent'
                    }`}
                  >
                    All ({locations.length})
                  </button>
                  <button
                    onClick={() => setOutletFilter('alerts')}
                    className={`px-3 py-1 rounded-full text-[10px] font-bold uppercase transition-all duration-200 cursor-pointer border-none flex items-center gap-1 ${
                      outletFilter === 'alerts'
                        ? 'bg-white text-amber-700 shadow-sm border border-amber-100/30'
                        : 'text-slate-500 hover:text-slate-850 bg-transparent'
                    }`}
                  >
                    <span>Alerts Only</span>
                    {storeAlertsData.alertOutletsCount > 0 && (
                      <span className="bg-amber-500 text-white text-[8px] font-extrabold w-3.5 h-3.5 rounded-full flex items-center justify-center">
                        {storeAlertsData.alertOutletsCount}
                      </span>
                    )}
                  </button>
                </div>
              </div>
            </div>

            {/* Quick Metrics Strip */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 font-sans">
              {[
                { label: 'Active Outlets', value: locations.length, icon: Server, chip: 'bg-purple-50 text-purple-650 ring-purple-100', value_cls: 'text-slate-900' },
                { label: 'Optimal Hubs', value: locations.length - storeAlertsData.alertOutletsCount, icon: CheckCircle, chip: 'bg-emerald-50 text-emerald-600 ring-emerald-100', value_cls: 'text-emerald-600' },
                { label: 'Low Stock Items', value: storeAlertsData.lowStockCount, icon: TrendingDown, chip: 'bg-amber-50 text-amber-600 ring-amber-100', value_cls: 'text-amber-600' },
                { label: 'Critical Alerts', value: storeAlertsData.criticalCount, icon: AlertTriangle, chip: 'bg-rose-50 text-rose-600 ring-rose-100', value_cls: 'text-rose-600' },
              ].map((m) => {
                const MIcon = m.icon;
                return (
                  <div
                    key={m.label}
                    className="bg-white border border-slate-200/70 rounded-2xl p-4 shadow-[0_1px_2px_rgba(16,24,40,0.04)] hover:shadow-[0_8px_22px_rgba(16,24,40,0.08)] hover:border-purple-200 transition-all duration-300 flex items-center gap-3"
                  >
                    <div className={`h-10 w-10 shrink-0 rounded-xl flex items-center justify-center ring-1 ${m.chip}`}>
                      <MIcon size={18} />
                    </div>
                    <div className="min-w-0">
                      <span className="block text-[9px] text-slate-400 uppercase tracking-wider font-extrabold truncate">{m.label}</span>
                      <span className={`block font-extrabold text-2xl leading-tight font-sans tracking-tight ${m.value_cls}`}>{m.value}</span>
                    </div>
                  </div>
                );
              })}
            </div>

            {(() => {
              const filteredStores = storesStockWithOverrides.filter(store => {
                const matchesSearch = !outletSearch || store.locationname.toLowerCase().includes(outletSearch.toLowerCase());
                const matchesFilter = outletFilter === 'all' || storeAlertsData.outletsWithAlerts.includes(store.locationid);
                return matchesSearch && matchesFilter;
              });

              if (filteredStores.length === 0) {
                return (
                  <div className="text-center py-xl text-zinc-400 text-xs border border-dashed border-[#e2e8f0] rounded-2xl bg-white/40 font-bold">
                    {outletFilter === 'alerts' 
                      ? '🎉 Outstanding! No outlets have critical or low stock alerts at this time.' 
                      : 'No outlets matched current search criteria.'}
                  </div>
                );
              }

              return (
                <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-md">
                  {filteredStores.map((store) => {
                    const items = store.rows.map((r) => stockRowToInventory(r, store.locationname));
                    const displayItems = items.filter((it) => !searchQuery || it.name.toLowerCase().includes(searchQuery.toLowerCase()));
                    const totalUnits = items.reduce((a, it) => a + it.stockLevel, 0);
                    const maxCapacity = items.reduce((a, it) => a + it.maxCapacity, 0);
                    const capacityPct = Math.min(100, maxCapacity > 0 ? (totalUnits / maxCapacity) * 100 : 0);
                    
                    const totalItems = items.length;
                    const optimalCount = items.filter(it => it.status === 'Optimal').length;
                    const lowCount = items.filter(it => it.status === 'Low Stock').length;
                    const criticalItemsCount = items.filter(it => it.status === 'Critical').length;
                    const hasAlert = lowCount > 0 || criticalItemsCount > 0;
                    
                    const meta = locations.find((l) => l.locationid === store.locationid);
                    const status = meta?.status ?? 'Active';
                    
                    const statusDotColor = hasAlert
                      ? criticalItemsCount > 0 ? 'bg-rose-500' : 'bg-amber-500'
                      : 'bg-emerald-500';

                    const statusChip = hasAlert
                      ? criticalItemsCount > 0 ? 'bg-rose-50 text-rose-600 ring-rose-100' : 'bg-amber-50 text-amber-600 ring-amber-100'
                      : 'bg-emerald-50 text-emerald-600 ring-emerald-100';

                    const optimalPct = totalItems > 0 ? (optimalCount / totalItems) * 100 : 0;
                    const lowPct = totalItems > 0 ? (lowCount / totalItems) * 100 : 0;
                    const criticalPct = totalItems > 0 ? (criticalItemsCount / totalItems) * 100 : 0;

                    // Sort items: Critical first, then Low Stock, then Optimal
                    const sortedItems = [...displayItems].sort((a, b) => {
                      const severity: Record<string, number> = { 'Critical': 0, 'Low Stock': 1, 'Optimal': 2 };
                      return (severity[a.status] ?? 2) - (severity[b.status] ?? 2);
                    });

                    return (
                      <div key={store.locationid} className="bg-white border border-slate-200/70 rounded-2xl shadow-[0_1px_3px_rgba(16,24,40,0.05)] hover:shadow-[0_16px_36px_rgba(16,24,40,0.10)] hover:border-purple-200 hover:-translate-y-0.5 transition-all duration-300 relative flex flex-col justify-between overflow-hidden min-h-[300px]">

                        {/* Card Header */}
                        <div className="p-4 pb-3 flex justify-between items-start gap-2">
                          <div className="flex items-start gap-2.5 min-w-0">
                            <div className={`h-9 w-9 shrink-0 rounded-lg flex items-center justify-center ring-1 ${statusChip}`}>
                              <Server size={15} />
                            </div>
                            <div className="min-w-0">
                              <h4 className="font-bold text-slate-900 text-[13px] truncate leading-tight">
                                {store.locationname}
                              </h4>
                              <p className="text-[10px] text-slate-400 mt-0.5 font-medium">
                                {totalItems} items · {totalUnits.toLocaleString('en-IN')} units
                              </p>
                            </div>
                          </div>
                          <span className={`shrink-0 inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[8px] font-black uppercase tracking-wider ${
                            hasAlert
                              ? criticalItemsCount > 0
                                ? 'text-rose-600 bg-rose-50 border border-rose-100'
                                : 'text-amber-700 bg-amber-50 border border-amber-100'
                              : 'text-emerald-600 bg-emerald-50 border border-emerald-100'
                          }`}>
                            <span className={`w-1.5 h-1.5 rounded-full ${statusDotColor}`} />
                            {hasAlert ? criticalItemsCount > 0 ? 'Critical' : 'Low Stock' : 'Optimal'}
                          </span>
                        </div>

                        {/* Card Body */}
                        <div className="px-4 py-2 space-y-3.5 flex-1">

                          {/* Segmented Stock Health Distribution */}
                          <div className="space-y-1.5">
                            <div className="flex justify-between items-center text-[9px] font-bold text-slate-400 uppercase tracking-wider">
                              <span>Stock Health</span>
                              <span className="flex items-center gap-2 normal-case font-semibold">
                                {criticalItemsCount > 0 && <span className="text-rose-600">{criticalItemsCount} crit</span>}
                                {lowCount > 0 && <span className="text-amber-600">{lowCount} low</span>}
                                <span className="text-emerald-600">{optimalCount} ok</span>
                              </span>
                            </div>
                            <div className="w-full h-1.5 bg-slate-100 rounded-full overflow-hidden flex select-none">
                              {criticalPct > 0 && (
                                <div className="h-full bg-rose-500" style={{ width: `${criticalPct}%` }} />
                              )}
                              {lowPct > 0 && (
                                <div className="h-full bg-amber-500" style={{ width: `${lowPct}%` }} />
                              )}
                              {optimalPct > 0 && (
                                <div className="h-full bg-emerald-500" style={{ width: `${optimalPct}%` }} />
                              )}
                            </div>
                          </div>

                          {/* Capacity utilization indicator */}
                          <div className="space-y-1.5">
                            <div className="flex justify-between items-center text-[9px] font-bold text-slate-400 uppercase tracking-wider">
                              <span>Capacity Utilised</span>
                              <span className="font-mono text-slate-600 normal-case font-bold">{Math.round(capacityPct)}%</span>
                            </div>
                            <div className="w-full bg-slate-100 h-1.5 rounded-full overflow-hidden">
                              <div
                                className={`h-full rounded-full transition-all duration-500 ${
                                  capacityPct > 85 ? 'bg-rose-500' : 'bg-gradient-to-r from-purple-500 to-indigo-500'
                                }`}
                                style={{ width: `${capacityPct}%` }}
                              />
                            </div>
                          </div>

                          {/* SKU lists */}
                          <div className="pt-2.5 border-t border-slate-100/60 space-y-2">
                            {store.isLoading ? (
                              <div className="text-center text-slate-400 text-[10px] py-4">Syncing live balances…</div>
                            ) : store.isError ? (
                              <div className="text-center text-rose-500 text-[10px] py-4 font-bold">Offline.</div>
                            ) : sortedItems.length === 0 ? (
                              <div className="text-center text-slate-405 text-[10px] py-4">No active stock items.</div>
                            ) : (
                              <div className="space-y-2 max-h-40 overflow-y-auto pr-0.5 scrollbar-thin">
                                {sortedItems.map((it, idx) => {
                                  const isLow = it.status !== 'Optimal';

                                  return (
                                    <div key={idx} className="flex justify-between items-center gap-3 py-0.5">
                                      <div className="min-w-0 flex items-center gap-2">
                                        <span className={`w-1 h-1 rounded-full shrink-0 ${
                                          it.status === 'Critical' ? 'bg-rose-500 animate-pulse' : it.status === 'Low Stock' ? 'bg-amber-500 animate-pulse' : 'bg-emerald-500'
                                        }`} />
                                        <span className={`text-[10px] font-semibold truncate ${
                                          isLow ? 'text-slate-900 font-bold' : 'text-slate-650'
                                        }`}>
                                          {it.name}
                                        </span>
                                      </div>

                                      <span className={`font-mono text-[10px] font-bold shrink-0 ${
                                        it.status === 'Critical' ? 'text-rose-600' : it.status === 'Low Stock' ? 'text-amber-700' : 'text-slate-500'
                                      }`}>
                                        {it.stockLevel}
                                      </span>
                                    </div>
                                  );
                                })}
                              </div>
                            )}
                          </div>

                        </div>

                        {/* Card Footer — read-only status (admins cannot edit hub stock) */}
                        <div className="px-4 py-3 border-t border-slate-100 bg-slate-50/50 flex items-center justify-between gap-2 shrink-0">
                          <span className="text-[9px] font-mono text-slate-400 uppercase tracking-wide">
                            {hasAlert ? `${criticalItemsCount + lowCount} items need attention` : 'All items optimal'}
                          </span>

                          {hasAlert ? (
                            <span className={`text-[9px] font-black flex items-center gap-1 select-none pr-1 uppercase tracking-wide ${
                              criticalItemsCount > 0 ? 'text-rose-600' : 'text-amber-700'
                            }`}>
                              <AlertTriangle size={11} /> {criticalItemsCount > 0 ? 'Critical' : 'Low Stock'}
                            </span>
                          ) : (
                            <span className="text-[9px] font-black text-emerald-600 flex items-center gap-1 select-none pr-1">
                              <CheckCircle size={11} /> Stocked
                            </span>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              );
            })()}
          </div>
        </>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-gutter text-xs font-sans items-start">
          
          {/* Left Column: Catalogue Import & Batch Console (7 Cols) */}
          <div className="lg:col-span-7 space-y-lg">
            
            {/* Fast Imports presets Card */}
            <div className="bg-white/80 backdrop-blur-md border border-[#e2e8f0] p-md rounded-2xl shadow-sm space-y-md">
              <div className="flex items-center gap-xs text-[#0f172a] font-bold text-sm">
                <Sparkles className="text-amber-500 animate-pulse" size={18} />
                <h3>Cooperative Catalogue Presets</h3>
              </div>

              <AwaitingApi label="Catalogue presets" api="[R5]" compact />
            </div>

            {/* Custom CSV Parsing Box */}
            <div className="bg-white/80 backdrop-blur-md border border-[#e2e8f0] p-md rounded-2xl shadow-sm space-y-md">
              <div className="flex items-center gap-xs text-[#0f172a] font-bold text-sm">
                <FileSpreadsheet className="text-[#581c87]" size={18} />
                <h3>Manual CSV Direct-Entry Console</h3>
              </div>

              <div className="space-y-sm">
                <div className="border border-slate-200 rounded-xl overflow-hidden shadow-inner">
                  {/* Visual Editor Header */}
                  <div className="bg-slate-100 px-md py-1.5 border-b border-slate-200 flex justify-between items-center text-[10px] font-bold text-slate-500 font-mono">
                    <span>CSV_IMPORT_STREAM</span>
                    <span className="w-2 h-2 rounded-full bg-amber-400 animate-pulse" />
                  </div>
                  <textarea
                    value={csvText}
                    onChange={(e) => setCsvText(e.target.value)}
                    className="w-full h-28 p-sm font-mono text-[11px] bg-slate-50/50 outline-none focus:bg-white focus:ring-1 focus:ring-[#581c87] leading-relaxed border-none"
                  />
                </div>

                <div className="flex justify-between items-center pt-2">
                  <span className="text-[9px] text-zinc-400 font-extrabold uppercase">Header row ignored on parse</span>
                  <button
                    onClick={handleCSVImport}
                    className="bg-[#581c87] text-white px-xl py-2 rounded-lg text-xs font-bold uppercase tracking-wider cursor-pointer hover:bg-purple-800 transition shadow-sm"
                  >
                    Parse CSV Data & Sync
                  </button>
                </div>
              </div>
            </div>

            {/* Realtime Import Logs list styled like terminal */}
            <div className="bg-zinc-950 border border-zinc-800 p-md rounded-2xl shadow-2xl space-y-sm font-mono text-[11px]">
              <div className="flex justify-between items-center border-b border-zinc-900 pb-2 mb-2">
                <h3 className="font-bold text-zinc-300 flex items-center gap-2">
                  <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                  Live Sync Audit Stream
                </h3>
                <span className="text-[9px] text-zinc-500 font-bold">COIMBATORE_ERP_V4</span>
              </div>

              <AwaitingApi label="Import / sync audit log" api="[R4]" compact className="bg-zinc-900/40 border-zinc-800" />
            </div>

          </div>

          {/* Right Column: Beautiful Interactive Brand Design Studio (5 Cols) */}
          <div className="lg:col-span-5 space-y-lg">
            
            <div className="bg-white/80 backdrop-blur-md border border-[#e2e8f0] p-md rounded-2xl shadow-sm space-y-md">
              <div className="flex items-center gap-xs text-[#0f172a] font-bold text-sm">
                <Palette className="text-[#581c87]" size={18} />
                <h3>Packaging Branding Studio</h3>
              </div>

              <AwaitingApi label="Brand & packaging config" api="[R6]" />
            </div>

          </div>

        </div>
      )}

      {/* CREATE NEW PRODUCT MODAL PORTAL */}
      {showAddProductModal && (
        <div 
          className="fixed inset-0 bg-[#0f172a]/40 backdrop-blur-sm z-[200] flex items-center justify-center p-md"
          onClick={(e) => { if (e.target === e.currentTarget) setShowAddProductModal(false); }}
        >
          <div className="bg-white border border-[#e2e8f0] rounded-xl w-full max-w-[28rem] max-h-[90vh] flex flex-col shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 text-xs font-sans cursor-default">
            <div className="p-md border-b border-[#e2e8f0] bg-[#f8fafc] flex justify-between items-center shrink-0">
              <h4 className="font-bold text-[#0f172a] flex items-center gap-xs">
                <Package size={15} className="text-[#581c87]" />
                Introduce New Grocery Catalogue SKU
              </h4>
              <button 
                onClick={() => setShowAddProductModal(false)}
                className="p-1 hover:bg-zinc-200 rounded-full text-zinc-400 cursor-pointer transition-colors"
              >
                <X size={16} />
              </button>
            </div>

            <form onSubmit={handleAddNewProduct} className="flex-1 flex flex-col min-h-0 overflow-hidden">
              <div className="p-md space-y-md overflow-y-auto flex-1">
                <div className="space-y-sm">
                  
                  <div className="space-y-1">
                    <label className="font-bold text-zinc-500 uppercase tracking-widest text-[9px]">PRODUCT BRAND NAME (*)</label>
                    <input 
                      type="text" 
                      placeholder="e.g. Aavin Pure Cow Ghee" 
                      value={newProduct.name}
                      onChange={(e) => setNewProduct({ ...newProduct, name: e.target.value })}
                      className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f8fafc] focus:bg-white outline-none focus:ring-1 focus:ring-[#581c87]"
                      required
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-sm">
                    <div className="space-y-1">
                      <label className="font-bold text-zinc-500 uppercase tracking-widest text-[9px]">SKU CODE IDENTIFIER (*)</label>
                      <input 
                        type="text" 
                        placeholder="e.g. GHEE-AAV-500" 
                        value={newProduct.sku}
                        onChange={(e) => setNewProduct({ ...newProduct, sku: e.target.value })}
                        className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f8fafc] focus:bg-white outline-none focus:ring-1 focus:ring-[#581c87] font-mono"
                        required
                      />
                    </div>
                    
                    <div className="space-y-1">
                      <label className="font-bold text-zinc-500 uppercase tracking-widest text-[9px]">CATEGORY SEGMENT</label>
                      <select
                        value={newProduct.category}
                        onChange={(e) => setNewProduct({ ...newProduct, category: e.target.value })}
                        className="w-full border border-[#e2e8f0] rounded-lg p-2 bg-[#f8fafc] focus:bg-white outline-none"
                      >
                        {/* Keep the form's default selection valid even if it isn't in the live list. */}
                        {!productCategoryNames.includes(newProduct.category) && (
                          <option value={newProduct.category}>{newProduct.category}</option>
                        )}
                        {productCategoryNames.map((name) => (
                          <option key={name} value={name}>{name}</option>
                        ))}
                      </select>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-sm">
                    <div className="space-y-1">
                      <label className="font-bold text-zinc-500 uppercase tracking-widest text-[9px]">ESTIMATED price (₹)</label>
                      <input 
                        type="number" 
                        value={newProduct.price}
                        onChange={(e) => setNewProduct({ ...newProduct, price: Number(e.target.value) })}
                        className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f8fafc] focus:bg-white outline-none focus:ring-1 focus:ring-[#581c87]"
                        required
                      />
                    </div>

                    <div className="space-y-1">
                      <label className="font-bold text-zinc-500 uppercase tracking-widest text-[9px]">INITIAL ALLOCATED BALANCES</label>
                      <input 
                        type="number" 
                        value={newProduct.initialStock}
                        onChange={(e) => setNewProduct({ ...newProduct, initialStock: Number(e.target.value) })}
                        className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f8fafc] focus:bg-white outline-none focus:ring-1 focus:ring-[#581c87]"
                        required
                      />
                    </div>
                  </div>

                  <div className="space-y-1">
                    <label className="font-bold text-zinc-500 uppercase tracking-widest text-[9px]">PRODUCT IMAGE PATH OR LINK</label>
                    <input 
                      type="text" 
                      value={newProduct.image}
                      onChange={(e) => setNewProduct({ ...newProduct, image: e.target.value })}
                      className="w-full border border-[#e2e8f0] rounded-lg p-sm bg-[#f8fafc] focus:bg-white outline-none focus:ring-1 focus:ring-[#581c87]"
                    />
                  </div>

                </div>
              </div>

              <div className="p-md border-t border-[#f1f5f9] flex justify-end gap-sm bg-[#f8fafc] shrink-0">
                <button
                  type="button"
                  onClick={() => setShowAddProductModal(false)}
                  className="px-4 py-2 border border-[#e2e8f0] rounded-lg font-semibold text-zinc-500 hover:bg-zinc-50 cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-[#581c87] text-white rounded-lg font-bold hover:bg-purple-800 cursor-pointer shadow-sm"
                >
                  Commit Product Design SKU
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

    </div>
  );
}
