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

import React, { useState, useEffect } from 'react';
import {
  ArrowLeft,
  Calendar,
  TrendingUp,
  Layers,
  Users,
  Phone,
  MapPin,
  AlertTriangle,
  Clock,
  Activity,
  CheckCircle2,
  Package,
  Search,
  ShoppingCart,
  Send,
  Download,
  X,
  ShieldCheck,
  Globe,
  UploadCloud,
  FileText,
  Mail,
  CreditCard,
  History,
  Building,
  Award,
  ShoppingBag,
  QrCode,
  ChevronRight,
  AtSign
} from 'lucide-react';
import {
  useFiestaStockStatement,
  useFiestaTenantCustomers,
  useFiestaCustomerOrders,
  useFiestaRiders,
  useFiestaRevenueSummary,
  useFiestaAllOrders,
  FIESTA_TENANT_ID
} from '../services/fiestaQueries';
import { str as fstr, num as fnum, ymd } from '../services/fiestaApi';
import { mapOrderStatus, shortTime } from '../services/fiestaMappers';
import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, Tooltip as RechartsTooltip, CartesianGrid } from 'recharts';
import ragulStoreCover from '../assets/images/store_front_view_1780299351800.png';
import OrdersDeliveriesView from './OrdersDeliveriesView';
import StoreQRView from './StoreQRView';
import AwaitingApi from './AwaitingApi';

interface StoreDetailViewProps {
  store: {
    locationid?: number;
    name: string;
    zone: string;
    deliveries: number;
    sales: string;
    orders?: number;
    staff: string;
    color: string;
    status: string;
  };
  /** Returns to the stores registry. Omitted when the view stands alone (e.g. a
   *  single user is scoped to just this store), in which case no back button shows. */
  onBack?: () => void;
  /** Whether to show write/management actions (replenish, broadcast, import,
   *  catalogue, promo/credit). Admins get true; plain store users get false so
   *  the console is view-only. */
  canManage?: boolean;
  /** Render a single section only (no tab bar). The user store console splits
   *  Overview, Inventory & Catalogue, and Customers into separate pages. When
   *  omitted, the full tabbed console renders (admin store detail). */
  only?: 'overview' | 'inventory' | 'customers';
  /** Merchant tenant to scope to; defaults to the shared constant. */
  tenantId?: number;
}

// Fallback cover images
const DETAIL_STORE_COVERS = [
  'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&w=800&q=80',
  'https://images.unsplash.com/photo-1578916171728-46686eac8d58?auto=format&fit=crop&w=800&q=80',
  'https://images.unsplash.com/photo-1604719312566-8912e9227c6a?auto=format&fit=crop&w=800&q=80',
  'https://images.unsplash.com/photo-1534723452862-4c874018d66d?auto=format&fit=crop&w=800&q=80',
  'https://images.unsplash.com/photo-1582408929130-98a2c2640b8a?auto=format&fit=crop&w=800&q=80',
  'https://images.unsplash.com/photo-1516594798947-e65505dbb29d?auto=format&fit=crop&w=800&q=80',
  'https://images.unsplash.com/photo-1601599561263-60a4e4e083cd?auto=format&fit=crop&w=800&q=80',
  'https://images.unsplash.com/photo-1441986300917-64674bd600d8?auto=format&fit=crop&w=800&q=80',
  'https://images.unsplash.com/photo-1528698827591-e19ccd7bc23d?auto=format&fit=crop&w=800&q=80',
  'https://images.unsplash.com/photo-1536697246787-1f7ae568d89a?auto=format&fit=crop&w=800&q=80',
  'https://images.unsplash.com/photo-1506617498306-bd97b3663b65?auto=format&fit=crop&w=800&q=80',
  'https://images.unsplash.com/photo-1579621970563-ebec7560ff3e?auto=format&fit=crop&w=800&q=80'
];

export default function StoreDetailView({ store, onBack, canManage = true, only, tenantId = FIESTA_TENANT_ID }: StoreDetailViewProps) {
  const [activeTab, setActiveTab] = useState<'overview' | 'inventory' | 'customers' | 'orders' | 'qr'>('overview');
  // Which section to show: forced by `only` (separate-page mode) or the active tab.
  const section = only ?? activeTab;
  // The immersive store banner shows on Overview (and the admin tabbed console);
  // the standalone Inventory & Customers pages omit it.
  const showHero = !only || only === 'overview';

  const isRagul = store.name.toLowerCase().includes('ragul');
  const getStoreCover = () => {
    if (isRagul) return ragulStoreCover;
    let hash = 0;
    for (let j = 0; j < store.name.length; j++) {
      hash = store.name.charCodeAt(j) + ((hash << 5) - hash);
    }
    const idx = Math.abs(hash) % DETAIL_STORE_COVERS.length;
    return DETAIL_STORE_COVERS[idx];
  };
  const storeCoverImage = getStoreCover();
  const [stockSearch, setStockSearch] = useState('');
  const [customerSearch, setCustomerSearch] = useState('');

  // ── Toast Notification state ──────────────────────────────────────────────
  const [toast, setToast] = useState<{ show: boolean; message: string; type: 'success' | 'info' | 'warning' }>({
    show: false,
    message: '',
    type: 'success'
  });

  const showToast = (message: string, type: 'success' | 'info' | 'warning' = 'success') => {
    setToast({ show: true, message, type });
    setTimeout(() => {
      setToast(prev => ({ ...prev, show: false }));
    }, 4000);
  };

  // ── Replenishment Modal state ──────────────────────────────────────────────
  const [replenishModal, setReplenishModal] = useState<{ show: boolean; item: any | null }>({
    show: false,
    item: null
  });
  const [replenishQty, setReplenishQty] = useState(100);

  // ── Catalogue Local State & Modals ────────────────────────────────────────
  const [localInventory, setLocalInventory] = useState<any[]>([]);
  const [showImportModal, setShowImportModal] = useState(false);
  const [importState, setImportState] = useState<'idle' | 'reading' | 'parsing' | 'saving' | 'done'>('idle');

  // ── Customer CRM Profile Drawer state ──────────────────────────────────────
  const [selectedCustomer, setSelectedCustomer] = useState<any | null>(null);

  // ── API Queries with live locationid ───────────────────────────────────────
  const locationid = store.locationid || 1097;
  const stockQ = useFiestaStockStatement({
    tenantid: tenantId,
    locationid,
    pagesize: 100
  });
  const customersQ = useFiestaTenantCustomers({
    tenantid: tenantId,
    locationid,
    pagesize: 100
  });
  // Live active rider fleet for this tenant (powers KPI fleet count + fleet list)
  const ridersQ = useFiestaRiders({ tenantid: tenantId });
  // Past orders for the currently-open CRM drawer customer (disabled when no id)
  const customerOrdersQ = useFiestaCustomerOrders({
    customerid: selectedCustomer?.id ?? null,
    pagesize: 20
  });

  const todayStr = ymd(new Date());
  const revenueQ = useFiestaRevenueSummary({ tenantid: tenantId, locationid, fromdate: todayStr, todate: todayStr });
  const totalRevenue = revenueQ.data?.overallrevenue ?? 0;
  
  const monthStart = ymd(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
  const monthRevenueQ = useFiestaRevenueSummary({ tenantid: tenantId, locationid, fromdate: monthStart, todate: todayStr });
  const monthlyRevenue = monthRevenueQ.data?.overallrevenue ?? 0;
  
  // All orders for today to build the intraday chart
  const todayOrdersQ = useFiestaAllOrders({ tenantid: tenantId, locationid, fromdate: todayStr, todate: todayStr });

  const intradayChartData = React.useMemo(() => {
    const map = new Map<string, { hour: string; orders: number; revenue: number }>();
    // Pre-fill 8 AM to 10 PM
    for (let i = 8; i <= 22; i++) {
      const hStr = i.toString().padStart(2, '0') + ':00';
      map.set(hStr, { hour: hStr, orders: 0, revenue: 0 });
    }

    for (const r of (todayOrdersQ.data ?? [])) {
      const dateVal = fstr(r.orderdate) || fstr(r.deliverydate);
      if (!dateVal) continue;
      const timePart = dateVal.split('T')[1];
      if (!timePart) continue;
      
      const hourStr = timePart.substring(0, 2) + ':00';
      const ex = map.get(hourStr) || { hour: hourStr, orders: 0, revenue: 0 };
      ex.orders += 1;
      ex.revenue += (fnum(r.ordervalue) || fnum(r.orderamount) || fnum(r.deliveryamt) || 0);
      map.set(hourStr, ex);
    }
    return Array.from(map.values()).sort((a, b) => a.hour.localeCompare(b.hour));
  }, [todayOrdersQ.data]);
  const customerOrderHistory = (customerOrdersQ.data ?? []).map((row: any) => {
    const amount = fnum(row.orderamount) || fnum(row.amount);
    return {
      id: fstr(row.orderid) || `ORD-${fstr(row.orderheaderid)}`,
      date: shortTime(row.orderdate || row.createddate),
      amount: amount > 0 ? `₹${amount.toLocaleString('en-IN')}` : '—',
      status: mapOrderStatus(fstr(row.orderstatus))
    };
  });

  // Inventory mapping (live only)
  const getMergedInventory = () => {
    const rawStock = stockQ.data ?? [];
    
    // Cosmetic image fallback only — keyword → stock photo. This MUST NOT be
    // used to fabricate prices; a missing live price renders as "—".
    const resolveImage = (name: string) => {
      const nameLower = name.toLowerCase();
      if (nameLower.includes('rice')) return 'https://images.unsplash.com/photo-1586201375761-83865001e31c?auto=format&fit=crop&w=150&q=80';
      if (nameLower.includes('oil')) return 'https://images.unsplash.com/photo-1474979266404-7eaacbcd87c5?auto=format&fit=crop&w=150&q=80';
      if (nameLower.includes('coffee')) return 'https://images.unsplash.com/photo-1514432324607-a09d9b4aefdd?auto=format&fit=crop&w=150&q=80';
      if (nameLower.includes('carrot')) return 'https://images.unsplash.com/photo-1598170845058-32b9d6a5da37?auto=format&fit=crop&w=150&q=80';
      if (nameLower.includes('ghee') || nameLower.includes('butter')) return 'https://images.unsplash.com/photo-1589985270826-4b7bb135bc9d?auto=format&fit=crop&w=150&q=80';
      if (nameLower.includes('salt')) return 'https://images.unsplash.com/photo-1626132647523-66f5bf380027?auto=format&fit=crop&w=150&q=80';
      if (nameLower.includes('atta') || nameLower.includes('flour')) return 'https://images.unsplash.com/photo-1574316071802-0d684efa7bf5?auto=format&fit=crop&w=150&q=80';
      return 'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&w=150&q=80';
    };

    // Live stock only — no hardcoded fallback. Empty live data → empty state.
    return rawStock.map((item: any) => {
      const name = fstr(item.productname) || fstr(item.name) || 'Product Item';
      const livePrice = fnum(item.retailprice) || fnum(item.price) || fnum(item.productcost);
      return {
        sku: fstr(item.sku) || fstr(item.productsku) || `SKU-${fstr(item.productid)}` || 'SKU-UNKNOWN',
        name,
        category: fstr(item.subcategoryname) || fstr(item.categoryname) || 'Groceries / Staples',
        stockLevel: Number(item.physicalstock) || Number(item.stock) || fnum(item.closing) || 0,
        maxCapacity: Number(item.maxcapacity) || 500,
        status: (Number(item.physicalstock) || fnum(item.closing) || 0) < 50 ? 'Critical' : (Number(item.physicalstock) || fnum(item.closing) || 0) < 150 ? 'Low Stock' : 'Optimal',
        // Real price or null — never a guessed number.
        price: livePrice > 0 ? livePrice : null,
        image: fstr(item.productimage) || resolveImage(name)
      };
    });
  };

  // Sync loaded stock to state
  useEffect(() => {
    setLocalInventory(getMergedInventory());
  }, [stockQ.data, store.locationid]);

  const inventoryList = localInventory.filter(item => 
    item.name.toLowerCase().includes(stockSearch.toLowerCase()) ||
    item.sku.toLowerCase().includes(stockSearch.toLowerCase()) ||
    item.category.toLowerCase().includes(stockSearch.toLowerCase())
  );

  // Customer Directory mapping (live only — no hardcoded fallback)
  const getMergedCustomers = () => {
    const rawCustomers = customersQ.data ?? [];
    return rawCustomers.map((c: any) => {
      const id =
        fnum(c.customerid) ||
        fnum(c.customerheaderid) ||
        fnum(c.userid) ||
        fnum(c.id) ||
        null;
      const spent = fnum(c.totalspent);
      return {
        id,
        name: fstr(c.fullname) || `${fstr(c.firstname)} ${fstr(c.lastname)}`.trim() || 'Customer',
        phone: fstr(c.contactno) || '—',
        email: fstr(c.email),
        // Was `|| 'Coimbatore'`, which invented an address for every customer
        // whose record has none — and for every tenant outside Coimbatore.
        address: fstr(c.address) || '—',
        ordersCount: Number(c.orderscount) || 0,
        totalSpent: spent > 0 ? `₹${spent.toLocaleString('en-IN')}` : '—'
      };
    });
  };

  const customersList = getMergedCustomers().filter(c =>
    c.name.toLowerCase().includes(customerSearch.toLowerCase()) ||
    c.phone.includes(customerSearch) ||
    c.address.toLowerCase().includes(customerSearch.toLowerCase())
  );

  // ── Active rider fleet (live) ──────────────────────────────────────────────
  // Names + active/idle status come from getriders; battery % and last-ping
  // have no API ([R9]) so those fields are intentionally not shown.
  const activeRiders = (ridersQ.data ?? []).map((row: any) => {
    const name =
      fstr(row.fullname) ||
      `${fstr(row.firstname)} ${fstr(row.lastname)}`.trim() ||
      'Rider';
    const parts = name.split(' ').filter(Boolean);
    const initial = ((parts[0]?.[0] || '') + (parts.length > 1 ? parts[parts.length - 1][0] : '')).toUpperCase();
    return {
      name,
      initial: initial || 'R',
      status: fstr(row.starttime) ? 'Delivering' : 'Idle',
      orders: fnum(row.completed) || fnum(row.deliverycount) || 0
    };
  });

  // Actions simulation handles
  const handleReplenishSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!replenishModal.item) return;
    setLocalInventory(prev => prev.map(item => {
      if (item.sku === replenishModal.item.sku) {
        const newStock = Math.min(item.stockLevel + replenishQty, item.maxCapacity);
        return {
          ...item,
          stockLevel: newStock,
          status: newStock < 50 ? 'Critical' : newStock < 150 ? 'Low Stock' : 'Optimal'
        };
      }
      return item;
    }));
    showToast(`Replenishment batch ticket generated for ${replenishQty} units of ${replenishModal.item.name}.`, 'success');
    setReplenishModal({ show: false, item: null });
  };

  // CSV Import simulation trigger
  const handleStartCsvImport = () => {
    setImportState('reading');
    setTimeout(() => {
      setImportState('parsing');
      setTimeout(() => {
        setImportState('saving');
        setTimeout(() => {
          const newItems = [
            { sku: 'NOODLE-MAG-12', name: 'Maggi 2-Min Masala Noodles 280g', category: 'Snacks / Noodles', stockLevel: 80, maxCapacity: 250, status: 'Optimal', price: 45, image: 'https://images.unsplash.com/photo-1569718212165-3a8278d5f624?auto=format&fit=crop&w=150&q=80' },
            { sku: 'DET-SURF-1KG', name: 'Surf Excel Easy Wash Detergent 1kg', category: 'Household / Detergent', stockLevel: 14, maxCapacity: 100, status: 'Critical', price: 165, image: 'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&w=150&q=80' },
            { sku: 'SALT-TATA-1KG', name: 'Tata Salt Premium Iodized 1kg', category: 'Staples / Salt', stockLevel: 180, maxCapacity: 300, status: 'Optimal', price: 28, image: 'https://images.unsplash.com/photo-1626132647523-66f5bf380027?auto=format&fit=crop&w=150&q=80' }
          ];

          // Add to localInventory state preventing duplicates
          setLocalInventory(prev => {
            const filtered = prev.filter(item => !newItems.some(ni => ni.sku === item.sku));
            return [...filtered, ...newItems];
          });
          
          setImportState('done');
          showToast(`CSV Inventory manifest sync complete. 3 items added to local stocks.`, 'success');
        }, 800);
      }, 700);
    }, 700);
  };

  const handleExportLedger = () => {
    showToast(`Generating secure PDF ledger audit reports for ${store.name}...`, 'info');
    setTimeout(() => {
      showToast(`Ledger spreadsheet decrypted and downloaded successfully.`, 'success');
    }, 2000);
  };

  const handleStaffBroadcast = () => {
    const text = prompt('Type notification message to broadcast to all cashiers and staff at this store:');
    if (text) {
      showToast(`Broadcast notification dispatched to all active terminals at ${store.name}.`, 'success');
    }
  };

  return (
    <div className="space-y-lg animate-in fade-in duration-500 relative font-sans text-zinc-900 pb-xl">
      
      {/* ── Floating Alert Toast UI ── */}
      {toast.show && (
        <div className="fixed top-24 right-6 z-[300] bg-[#0f172a] text-white border border-[#334155] px-lg py-3 rounded-xl shadow-2xl flex items-center gap-md animate-in slide-in-from-top duration-300">
          {toast.type === 'success' && <CheckCircle2 size={16} className="text-emerald-400" />}
          {toast.type === 'info' && <Activity size={16} className="text-purple-400" />}
          {toast.type === 'warning' && <AlertTriangle size={16} className="text-amber-400" />}
          <span className="text-xs font-semibold">{toast.message}</span>
          <button onClick={() => setToast(prev => ({ ...prev, show: false }))} className="text-zinc-500 hover:text-zinc-300 cursor-pointer">
            <X size={14} />
          </button>
        </div>
      )}

      {/* ── Subheader Navigation Bar ── */}
      {/* ── Subheader Navigation Bar ── */}
      {onBack && (
        <div className="flex items-center justify-between mb-4">
          <button
            onClick={onBack}
            className="flex items-center gap-xs text-xs font-bold text-[#662582] hover:text-[#4c1d95] bg-purple-50 hover:bg-purple-100/80 px-xl py-2 rounded-lg transition-all shadow-sm border border-purple-100 cursor-pointer"
          >
            <ArrowLeft size={14} />
            <span>Back to Dashboard</span>
          </button>
        </div>
      )}

      {/* ── Immersive Analytics Banner — hidden on the standalone Inventory & Customers pages ── */}
      {showHero && (
      <div className="relative overflow-hidden p-6 md:p-8 text-white shadow-xl border border-purple-500/20 mb-8 animate-in fade-in duration-300">
        {/* Cover Image Background */}
        <div className="absolute inset-0 z-0">
          <img
            src={storeCoverImage}
            alt={store.name}
            className="w-full h-full object-cover object-center"
          />
          <div className="absolute inset-0 bg-gradient-to-r from-slate-950 via-slate-900/90 to-purple-950/80" />
        </div>
        
        {/* 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" />
        
        {/* System Sync Active Indicator */}
        <div className="absolute top-4 right-5 sm:top-6 sm:right-8 z-20 flex items-center gap-1.5 bg-slate-950/40 backdrop-blur-md px-3 py-1.5 rounded-full border border-white/5 shadow-sm">
          <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
          <span className="text-[9px] font-bold tracking-widest text-emerald-400 uppercase">System Sync Active</span>
        </div>

        <div className="relative flex flex-col md:flex-row md:items-center justify-between gap-6 z-10">
          <div className="space-y-2">
            <div className="inline-flex items-center gap-2 px-2.5 py-1 rounded-full bg-purple-500/20 border border-purple-400/30 text-purple-200 text-[10px] font-bold uppercase tracking-widest">
              <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
              Outlet Node #{locationid} Operations
            </div>
            <h2 className="font-sans font-bold text-3xl tracking-tight bg-gradient-to-r from-white via-slate-100 to-purple-200 bg-clip-text text-transparent">
              {store.name}
            </h2>
            <div className="flex flex-wrap gap-2 text-xs text-purple-200 mt-1">
              <span className="flex items-center gap-1">
                <MapPin size={13} className="text-purple-300" /> {store.zone}
              </span>
              <span className="flex items-center gap-1 ml-4">
                <Users size={13} className="text-purple-300" /> Node Lead: <strong>{store.staff}</strong>
              </span>
            </div>
          </div>
        </div>

        {/* Metrics grid */}
        <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">
          <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">Node Status</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">
                <Building className="w-4 h-4" />
              </div>
            </div>
            <div className="mt-2">
              <h3 className="text-2xl font-extrabold tracking-tight font-mono">{store.status}</h3>
              <p className="text-[10px] text-emerald-400 font-semibold mt-1">● Online Operations</p>
            </div>
          </div>

          <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">Today's Orders</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">
                <ShoppingCart className="w-4 h-4" />
              </div>
            </div>
            <div className="mt-2">
              <h3 className="text-2xl font-extrabold tracking-tight font-mono">{Math.max(store.deliveries, store.orders ?? 0)}</h3>
              <p className="text-[10px] text-slate-400 font-semibold mt-1">Incoming Volume</p>
            </div>
          </div>

          <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">Today's Dispatches</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">
                <TrendingUp className="w-4 h-4" />
              </div>
            </div>
            <div className="mt-2">
              <h3 className="text-2xl font-extrabold tracking-tight font-mono">{store.deliveries}</h3>
              <p className="text-[10px] text-slate-400 font-semibold mt-1">Dispatched Deliveries</p>
            </div>
          </div>

          <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">Fulfillment Rate</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">
                <Award className="w-4 h-4" />
              </div>
            </div>
            <div className="mt-2">
              <h3 className="text-2xl font-extrabold tracking-tight font-mono">
                {Math.max(store.deliveries, store.orders ?? 0) > 0 
                  ? `${Math.min(100, Math.round((store.deliveries / Math.max(store.deliveries, store.orders ?? 0)) * 100))}%`
                  : '100%'}
              </h3>
              <p className="text-[10px] text-indigo-400 font-semibold mt-1">Outlet OTIF Rate</p>
            </div>
          </div>
        </div>
      </div>
      )}

      {/* ── Visual Glass-look Tab Controls (full tabbed console only) ── */}
      {!only && (
      <div className="flex gap-2 border-b border-[#e2e8f0] pb-[1px] select-none overflow-x-auto">
        <button
          onClick={() => setActiveTab('overview')}
          className={`flex items-center gap-xs px-md pb-sm text-xs font-bold uppercase tracking-wider cursor-pointer border-b-2 transition-all ${
            activeTab === 'overview'
              ? 'border-b-[#662582] text-[#662582]'
              : 'border-b-transparent text-zinc-400 hover:text-zinc-600'
          }`}
        >
          <Activity size={14} />
          <span>Overview & Performance</span>
        </button>
        <button
          onClick={() => setActiveTab('inventory')}
          className={`flex items-center gap-xs px-md pb-sm text-xs font-bold uppercase tracking-wider cursor-pointer border-b-2 transition-all ${
            activeTab === 'inventory'
              ? 'border-b-[#662582] text-[#662582]'
              : 'border-b-transparent text-zinc-400 hover:text-zinc-600'
          }`}
        >
          <Layers size={14} />
          <span>Inventory ({inventoryList.length})</span>
          {inventoryList.some(item => item.status === 'Critical') && (
            <span className="px-1.5 py-0.5 rounded-full bg-rose-500 text-white text-[8px] font-black leading-none animate-pulse">!</span>
          )}
        </button>
        <button
          onClick={() => setActiveTab('customers')}
          className={`flex items-center gap-xs px-md pb-sm text-xs font-bold uppercase tracking-wider cursor-pointer border-b-2 transition-all ${
            activeTab === 'customers'
              ? 'border-b-[#662582] text-[#662582]'
              : 'border-b-transparent text-zinc-400 hover:text-zinc-600'
          }`}
        >
          <Users size={14} />
          <span>Customer CRM Base ({customersList.length})</span>
        </button>
        <button
          onClick={() => setActiveTab('orders')}
          className={`flex items-center gap-xs px-md pb-sm text-xs font-bold uppercase tracking-wider cursor-pointer border-b-2 transition-all ${
            activeTab === 'orders'
              ? 'border-b-[#662582] text-[#662582]'
              : 'border-b-transparent text-zinc-400 hover:text-zinc-600'
          }`}
        >
          <ShoppingBag size={14} />
          <span>Orders & Deliveries</span>
        </button>
        <button
          onClick={() => setActiveTab('qr')}
          className={`flex items-center gap-xs px-md pb-sm text-xs font-bold uppercase tracking-wider cursor-pointer border-b-2 transition-all ${
            activeTab === 'qr'
              ? 'border-b-[#662582] text-[#662582]'
              : 'border-b-transparent text-zinc-400 hover:text-zinc-600'
          }`}
        >
          <QrCode size={14} />
          <span>Store QR</span>
        </button>
      </div>
      )}

      {/* ── TAB PAYLOAD AREA ── */}
      {section === 'overview' && (
        <div className="space-y-lg animate-in fade-in duration-300">
          
          {/* Top Metric Cards */}
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-gutter">
            <div className="bg-white border border-[#eceef2] rounded-2xl p-md shadow-sm hover:shadow-md transition-all duration-200 hover:-translate-y-0.5 relative group overflow-hidden">
              <div className="w-8 h-8 rounded-xl bg-purple-50 text-[#662582] flex items-center justify-center mb-sm group-hover:scale-110 transition-transform">
                <Activity size={16} />
              </div>
              <span className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest block">Monthly Revenue</span>
              <div className="mt-xs">
                {monthRevenueQ.isLoading ? (
                  <span className="text-xs text-zinc-400 font-medium">Loading...</span>
                ) : (
                  <p className="text-2xl font-black text-[#0f172a]">₹{monthlyRevenue.toLocaleString('en-IN')}</p>
                )}
              </div>
            </div>

            <div className="bg-white border border-[#eceef2] rounded-2xl p-md shadow-sm hover:shadow-md transition-all duration-200 hover:-translate-y-0.5 relative group overflow-hidden">
              <div className="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center mb-sm group-hover:scale-110 transition-transform">
                <TrendingUp size={16} />
              </div>
              <span className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest block">Today's Revenue</span>
              <div className="mt-xs">
                {revenueQ.isLoading ? (
                  <span className="text-xs text-zinc-400 font-medium">Loading...</span>
                ) : (
                  <p className="text-2xl font-black text-[#0f172a]">₹{totalRevenue.toLocaleString('en-IN')}</p>
                )}
              </div>
            </div>

            <div className="bg-white border border-[#eceef2] rounded-2xl p-md shadow-sm hover:shadow-md transition-all duration-200 hover:-translate-y-0.5 relative group overflow-hidden">
              <div className="w-8 h-8 rounded-xl bg-sky-50 text-sky-600 flex items-center justify-center mb-sm group-hover:scale-110 transition-transform">
                <ShoppingCart size={16} />
              </div>
              <span className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest block">Total Dispatches</span>
              <p className="text-2xl font-black text-[#0f172a] mt-xs">{store.deliveries}</p>
              <div className="text-[10px] text-zinc-400 font-bold mt-1">
                <span>Daily cap quota: 200</span>
              </div>
            </div>

            <div className="bg-white border border-[#eceef2] rounded-2xl p-md shadow-sm hover:shadow-md transition-all duration-200 hover:-translate-y-0.5 relative group overflow-hidden">
              <div className="w-8 h-8 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center mb-sm group-hover:scale-110 transition-transform">
                <Users size={16} />
              </div>
              <span className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest block">Active Fleet</span>
              <p className="text-2xl font-black text-[#0f172a] mt-xs">{activeRiders.length} Riders</p>
              <div className="text-[10px] text-emerald-600 font-bold mt-1 flex items-center gap-xs">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
                <span>{activeRiders.filter(r => r.status !== 'Idle').length} dispatches live</span>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-gutter">
            
            {/* Interactive Timeline Pipeline Flow */}
            <div className={`${canManage ? 'lg:col-span-2' : 'lg:col-span-3'} bg-white border border-[#eceef2] rounded-2xl p-lg shadow-sm flex flex-col justify-between hover:shadow-md transition-shadow relative`}>
              <div>
                <div className="flex justify-between items-start">
                  <div>
                    <h3 className="font-sans font-bold text-sm text-[#0f172a] flex items-center gap-xs">
                      <Clock size={15} className="text-[#662582]" /> Dispatch Flow Pipeline
                    </h3>
                    <p className="text-zinc-450 text-[10px] font-sans mt-0.5">Audit orders & revenue progression by selecting nodes along the daily operational path.</p>
                  </div>
                  <span className="text-[9px] font-bold text-purple-600 bg-purple-50 px-2 py-0.5 rounded-lg border border-purple-100 uppercase tracking-wider">Time Flow</span>
                </div>
              </div>

              {/* Intraday dispatch breakdown */}
              <div className="my-md h-64">
                {todayOrdersQ.isLoading ? (
                  <div className="w-full h-full flex items-center justify-center text-xs text-zinc-400">Loading intraday data...</div>
                ) : (
                  <ResponsiveContainer width="100%" height="100%">
                    <AreaChart data={intradayChartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                      <defs>
                        <linearGradient id="intraRev" x1="0" y1="0" x2="0" y2="1">
                          <stop offset="5%" stopColor="#662582" stopOpacity={0.3} />
                          <stop offset="95%" stopColor="#662582" stopOpacity={0} />
                        </linearGradient>
                      </defs>
                      <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#eceef2" />
                      <XAxis dataKey="hour" axisLine={false} tickLine={false} tick={{ fontSize: 10, fill: '#94a3b8' }} dy={10} />
                      <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 10, fill: '#94a3b8' }} dx={-10} tickFormatter={(v) => `₹${v}`} />
                      <RechartsTooltip 
                        content={({ active, payload, label }: any) => {
                          if (active && payload && payload.length) {
                            return (
                              <div className="bg-white p-3 rounded-xl border border-zinc-200 shadow-lg">
                                <p className="text-[10px] font-bold text-zinc-400 uppercase tracking-wider mb-2">{label}</p>
                                <div className="flex flex-col gap-1">
                                  <span className="flex items-center gap-2 text-xs font-medium text-zinc-600">
                                    <span className="w-2 h-2 rounded-full bg-[#662582]"></span>
                                    Revenue: <strong className="text-zinc-900">₹{payload[0].value.toLocaleString('en-IN')}</strong>
                                  </span>
                                  <span className="flex items-center gap-2 text-xs font-medium text-zinc-600">
                                    <span className="w-2 h-2 rounded-full bg-sky-500"></span>
                                    Orders: <strong className="text-zinc-900">{payload[0].payload.orders}</strong>
                                  </span>
                                </div>
                              </div>
                            );
                          }
                          return null;
                        }}
                      />
                      <Area type="monotone" dataKey="revenue" stroke="#662582" strokeWidth={2} fillOpacity={1} fill="url(#intraRev)" activeDot={{ r: 4, strokeWidth: 2, stroke: '#fff', fill: '#662582' }} />
                    </AreaChart>
                  </ResponsiveContainer>
                )}
              </div>
            </div>

            {/* Quick Actions Console — management only */}
            {canManage && (
            <div className="bg-white border border-[#eceef2] rounded-2xl p-md shadow-sm space-y-md flex flex-col justify-between">
              <div>
                <h3 className="font-sans font-bold text-sm text-[#0f172a] flex items-center gap-xs">
                  <ShieldCheck size={15} className="text-[#662582]" /> Node Operations Command
                </h3>
                <p className="text-zinc-450 text-[10px] font-sans mt-0.5">Automated actions for local outlet hubs.</p>
              </div>

              <div className="space-y-sm">
                <button
                  onClick={() => setActiveTab('inventory')}
                  className="w-full flex items-center justify-between p-sm border border-[#e2e8f0] rounded-xl hover:border-purple-300 hover:bg-purple-50/20 text-left text-xs font-semibold text-zinc-700 hover:text-[#662582] transition cursor-pointer"
                >
                  <span className="flex items-center gap-sm">
                    <Layers size={14} className="text-[#662582]" /> Replenish Critical Stock
                  </span>
                  <span className="px-1.5 py-0.5 rounded text-[8px] bg-rose-100 text-rose-700 font-black animate-pulse">ALERTS</span>
                </button>

                <button
                  onClick={handleExportLedger}
                  className="w-full flex items-center justify-between p-sm border border-[#e2e8f0] rounded-xl hover:border-purple-300 hover:bg-purple-50/20 text-left text-xs font-semibold text-zinc-700 hover:text-[#662582] transition cursor-pointer"
                >
                  <span className="flex items-center gap-sm">
                    <Download size={14} className="text-zinc-500" /> Export Compliance Ledger
                  </span>
                  <span className="text-[8px] font-bold text-zinc-400">PDF / CSV</span>
                </button>

                <button
                  onClick={handleStaffBroadcast}
                  className="w-full flex items-center justify-between p-sm border border-[#e2e8f0] rounded-xl hover:border-purple-300 hover:bg-purple-50/20 text-left text-xs font-semibold text-zinc-700 hover:text-[#662582] transition cursor-pointer"
                >
                  <span className="flex items-center gap-sm">
                    <Send size={14} className="text-zinc-500" /> Broadcast Terminal SMS
                  </span>
                  <span className="text-[8px] font-bold text-[#662582] uppercase tracking-wider">SMS Blast</span>
                </button>
              </div>
            </div>
            )}

          </div>



        </div>
      )}

      {section === 'inventory' && (
        <div className="space-y-lg animate-in fade-in duration-300">
          
          {/* Inventory search, metrics & catalogue tools */}
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-md bg-white border border-[#eceef2] p-md rounded-2xl shadow-sm">
            <div className="relative w-full md:w-80 md:shrink-0">
              <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-450" />
              <input
                type="text"
                placeholder="Search inventory by product or SKU..."
                value={stockSearch}
                onChange={(e) => setStockSearch(e.target.value)}
                className="w-full pl-9 pr-4 py-2.5 border border-[#e2e8f0] rounded-xl text-xs outline-none bg-[#f8fafc] focus:bg-white focus:ring-1 focus:ring-[#662582] transition-all"
              />
            </div>

            {/* Actions for Store Catalogue Management */}
            <div className="flex flex-wrap items-center gap-sm text-xs shrink-0 select-none">
              {canManage && (
                <>
                  <button
                    onClick={() => { setImportState('idle'); setShowImportModal(true); }}
                    className="px-3 py-2 bg-purple-50 text-[#662582] hover:bg-purple-100/80 border border-purple-100 rounded-xl font-bold flex items-center gap-xs cursor-pointer transition shadow-sm"
                  >
                    <UploadCloud size={14} />
                    <span>Import Manual (CSV)</span>
                  </button>

                  <span className="h-6 w-[1px] bg-zinc-200 mx-xs hidden md:block" />
                </>
              )}

              <span className="px-3 py-2 bg-rose-50 border border-rose-100 rounded-lg text-rose-700 font-bold">
                {inventoryList.filter(item => item.status === 'Critical').length} Critical
              </span>
              <span className="px-3 py-2 bg-amber-50 border border-amber-100 rounded-lg text-amber-700 font-bold">
                {inventoryList.filter(item => item.status === 'Low Stock').length} Low
              </span>
            </div>
          </div>

          {/* Stocks statement Table */}
          <div className="bg-white border border-[#eceef2] rounded-2xl overflow-hidden shadow-sm">
            <div className="p-md border-b border-[#eceef2] bg-[#f8fafc] flex justify-between items-center">
              <h4 className="font-sans font-bold text-sm text-[#0f172a]">
                Product Stock Levels
              </h4>
              <span className="text-[10px] font-bold text-[#662582] bg-purple-50 px-2 py-0.5 rounded border border-purple-100 uppercase tracking-wide">Live list</span>
            </div>

            <div className="overflow-x-auto text-xs font-sans">
              <table className="w-full text-left">
                <thead className="bg-[#f8fafc] border-b border-[#e2e8f0] text-zinc-450 text-[10px] uppercase font-bold tracking-wider">
                  <tr>
                    <th className="px-md py-sm">Product Item</th>
                    <th className="px-md py-sm">SKU Ref</th>
                    <th className="px-md py-sm">Category</th>
                    <th className="px-md py-sm">Est. Price</th>
                    <th className="px-md py-sm">Capacity Load</th>
                    <th className="px-md py-sm">Status</th>
                    {canManage && <th className="px-md py-sm text-right">Replenish</th>}
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#f1f5f9] font-medium text-zinc-700">
                  {inventoryList.length === 0 ? (
                    <tr>
                      <td colSpan={canManage ? 7 : 6} className="text-center py-10 text-zinc-400 font-medium">
                        No product stocks found matching the search keyword.
                      </td>
                    </tr>
                  ) : (
                    inventoryList.map((item, index) => {
                      const capacityPct = Math.round((item.stockLevel / item.maxCapacity) * 100);
                      
                      // Pretty category badge mapping
                      const isStaples = item.category.toLowerCase().includes('staple') || item.category.toLowerCase().includes('rice');
                      const isBeverages = item.category.toLowerCase().includes('bev');
                      const isProduce = item.category.toLowerCase().includes('produce') || item.category.toLowerCase().includes('fresh') || item.category.toLowerCase().includes('carrot');
                      const isDairy = item.category.toLowerCase().includes('dairy');

                      return (
                        <tr key={index} className="hover:bg-[#f8fafc]/60 transition-colors">
                          <td className="px-md py-md">
                            <div className="flex items-center gap-sm">
                              <img 
                                src={item.image} 
                                alt={item.name}
                                className="w-10 h-10 object-cover rounded-lg border border-zinc-200 shadow-sm shrink-0" 
                              />
                              <span className="font-bold text-[#0f172a]">{item.name}</span>
                            </div>
                          </td>
                          <td className="px-md py-md font-mono text-[10px] text-zinc-400 font-bold uppercase">{item.sku}</td>
                          <td className="px-md py-md">
                            <span className={`px-2 py-0.5 rounded text-[8px] font-bold uppercase tracking-wider ${
                              isStaples ? 'bg-amber-50 text-amber-700 border border-amber-100' :
                              isBeverages ? 'bg-rose-50 text-rose-700 border border-rose-100' :
                              isProduce ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' :
                              isDairy ? 'bg-sky-50 text-sky-700 border border-sky-100' :
                              'bg-zinc-150 text-zinc-650'
                            }`}>
                              {item.category.split(' / ').slice(-1)[0]}
                            </span>
                          </td>
                          <td className="px-md py-md font-bold text-zinc-800">
                            {item.price != null ? `₹${item.price.toLocaleString('en-IN')}` : '—'}
                          </td>
                          <td className="px-md py-md w-44">
                            <div className="flex items-center gap-sm">
                              <span className="w-8 shrink-0 font-mono text-right font-bold text-[10px]">{item.stockLevel} / {item.maxCapacity}</span>
                              <div className="w-20 bg-[#f1f5f9] h-2 rounded-full overflow-hidden">
                                <div 
                                  className={`h-full ${
                                    item.status === 'Critical' ? 'bg-rose-500 animate-pulse' :
                                    item.status === 'Low Stock' ? 'bg-amber-500' :
                                    'bg-emerald-500'
                                  }`}
                                  style={{ width: `${Math.min(capacityPct, 100)}%` }}
                                />
                              </div>
                            </div>
                          </td>
                          <td className="px-md py-md">
                            <span className={`px-2 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider ${
                              item.status === 'Optimal' ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' :
                              item.status === 'Low Stock' ? 'bg-amber-50 text-amber-700 border border-amber-100' :
                              'bg-rose-50 text-rose-700 border border-rose-100'
                            }`}>
                              ● {item.status}
                            </span>
                          </td>
                          {canManage && (
                            <td className="px-md py-md text-right">
                              <button
                                onClick={() => setReplenishModal({ show: true, item })}
                                className={`px-3 py-1 rounded-lg text-[10px] font-bold hover:shadow-sm transition cursor-pointer ${
                                  item.status === 'Critical'
                                    ? 'bg-rose-500 text-white hover:bg-rose-600'
                                    : 'border border-zinc-200 text-zinc-700 hover:border-[#662582] hover:text-[#662582]'
                                }`}
                              >
                                Replenish
                              </button>
                            </td>
                          )}
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {section === 'customers' && (() => {
        const withPhone = customersList.filter((c: any) => c.phone && c.phone !== '—').length;
        const withEmail = customersList.filter((c: any) => c.email).length;
        // Jewel-tone identity per customer (deterministic by name) — a calm header
        // band gradient + a soft solid avatar tint drawn from the same hue.
        const tones = [
          { soft: '#f3effb', fg: '#6d28d9', band: 'linear-gradient(135deg,#6d28d9 0%,#9333ea 100%)' },
          { soft: '#e9f5f1', fg: '#0f766e', band: 'linear-gradient(135deg,#0f766e 0%,#14b8a6 100%)' },
          { soft: '#fdf0eb', fg: '#c2410c', band: 'linear-gradient(135deg,#c2410c 0%,#f97316 100%)' },
          { soft: '#ebeefb', fg: '#3a4fc4', band: 'linear-gradient(135deg,#3949c4 0%,#6366f1 100%)' },
          { soft: '#fceef4', fg: '#be185d', band: 'linear-gradient(135deg,#be185d 0%,#ec4899 100%)' },
          { soft: '#e9f3fb', fg: '#0369a1', band: 'linear-gradient(135deg,#0369a1 0%,#0ea5e9 100%)' },
        ];
        const toneFor = (name: string) => {
          let h = 0;
          for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;
          return tones[h % tones.length];
        };
        const initialsOf = (name: string) => (name || 'C').split(' ').filter(Boolean).map((n: string) => n[0]).slice(0, 2).join('').toUpperCase();
        // A short, human locality from the messy delivery address (skip door numbers).
        const localityOf = (addr: string) => {
          const parts = (addr || '').split(',').map((s) => s.trim()).filter(Boolean);
          return parts.find((p) => /[a-zA-Z]/.test(p) && !/^\d/.test(p)) || parts[1] || parts[0] || '';
        };

        return (
        <div className="animate-in fade-in duration-300">

          {/* Page heading - Immersive Banner (Light mode to match Reports) */}
          <div className="relative overflow-hidden rounded-2xl p-4 md:p-5 border mb-5 animate-in fade-in duration-300 shadow-[0_8px_24px_rgba(15,23,42,0.08)]" style={{ borderColor: '#e2e8f0', background: `linear-gradient(135deg, #66258208 0%, #9255AB08 100%)` }}>
            {/* Background glowing circles */}
            <div className="absolute top-0 right-0 w-80 h-80 bg-[#662582]/5 rounded-full blur-3xl -mr-20 -mt-20 pointer-events-none z-0" />
            <div className="absolute bottom-0 left-0 w-64 h-64 bg-[#9255AB]/5 rounded-full blur-2xl -ml-20 -mb-20 pointer-events-none z-0" />

            <div className="relative flex flex-col md:flex-row md:items-center justify-between gap-4 z-10">
              <div className="space-y-1">
                <div className="flex items-center gap-3 mb-1">
                  <div className="inline-flex items-center gap-2 px-2.5 py-0.5 rounded-full bg-[#662582]/10 border border-[#662582]/20 text-[#662582] text-[9px] font-bold uppercase tracking-widest">
                    Store Audience Registry
                  </div>
                  <div className="flex items-center gap-1.5">
                    <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
                    <span className="text-[9px] font-bold tracking-widest text-emerald-600 uppercase">System Sync Active</span>
                  </div>
                </div>
                <h2 className="font-sans font-extrabold text-2xl md:text-[28px] tracking-tight text-[#0f172a]">
                  Customer CRM
                </h2>
                <div className="flex flex-wrap items-center gap-2 text-[12px] text-zinc-500 mt-1 font-medium">
                  <span>
                    {customersList.length} {customersList.length === 1 ? 'customer orders' : 'customers order'} from <strong className="text-[#0f172a] font-bold">{store.name}</strong>
                  </span>
                  <span className="text-zinc-300 hidden sm:inline">·</span>
                  <span className="flex items-center gap-1.5"><Phone size={11} className="text-zinc-400" /> {withPhone} with phone</span>
                  <span className="text-zinc-300 hidden sm:inline">·</span>
                  <span className="flex items-center gap-1.5"><Mail size={11} className="text-zinc-400" /> {withEmail} with email</span>
                </div>
              </div>

              <div className="relative w-full md:w-64 shrink-0">
                <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-[#662582]" />
                <input
                  type="text"
                  placeholder="Search customers..."
                  value={customerSearch}
                  onChange={(e) => setCustomerSearch(e.target.value)}
                  className="w-full pl-8 pr-3 py-2 border border-[#662582]/20 rounded-xl text-[12px] text-[#0f172a] placeholder:text-zinc-400 outline-none bg-white/60 backdrop-blur-md focus:border-[#662582] focus:ring-4 focus:ring-[#662582]/10 transition-all shadow-[inset_0_2px_4px_rgba(0,0,0,0.02)]"
                />
              </div>
            </div>
          </div>

          {/* Profile cards */}
          {customersList.length === 0 ? (
            <div className="bg-white/60 backdrop-blur-md border border-[#e2e8f0] rounded-3xl py-24 flex flex-col items-center gap-4 text-center px-6 shadow-sm">
              <span className="flex items-center justify-center w-16 h-16 rounded-2xl bg-gradient-to-br from-[#f3e8ff] to-[#e9d5ff] text-[#6d28d9] shadow-sm"><Users size={28} /></span>
              <p className="text-[18px] font-bold text-[#0f172a]">No customers yet</p>
              <p className="text-[14px] text-zinc-500 max-w-[350px] leading-relaxed">
                {customerSearch ? 'Nothing matches your search criteria.' : 'Customers will appear here once they place their first order.'}
              </p>
              {customerSearch && (
                <button onClick={() => setCustomerSearch('')} className="mt-2 text-[13px] font-bold text-[#662582] hover:text-[#4c1d95] bg-purple-50 px-4 py-2 rounded-lg transition-colors cursor-pointer">Clear Search</button>
              )}
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 pb-8">
              {customersList.map((c: any, idx: number) => {
                const tone = toneFor(c.name || `c${idx}`);
                const locality = localityOf(c.address);
                return (
                  <div key={c.id ?? idx} className="group relative bg-white/70 backdrop-blur-md border border-[#e2e8f0] rounded-2xl p-5 hover:shadow-[0_12px_40px_rgba(88,28,135,0.08)] hover:border-[#662582]/30 transition-all duration-300 flex flex-col">
                    <div className="flex justify-between items-start mb-4">
                      <div className="flex items-center gap-3 min-w-0">
                        <span 
                          className="w-12 h-12 rounded-2xl flex items-center justify-center font-bold text-sm shrink-0 shadow-sm transition-transform group-hover:scale-105 border border-white/50" 
                          style={{ background: tone.soft, color: tone.fg }}
                        >
                          {initialsOf(c.name)}
                        </span>
                        <div className="min-w-0">
                          <h3 className="font-extrabold text-[#0f172a] text-[15px] leading-tight group-hover:text-[#662582] transition-colors truncate" title={c.name}>{c.name}</h3>
                          {locality && (
                            <p className="text-[11px] text-zinc-500 mt-0.5 flex items-center gap-1 font-medium truncate" title={locality}>
                              <MapPin size={10} className="shrink-0 text-zinc-400" /> {locality}
                            </p>
                          )}
                        </div>
                      </div>
                      {c.ordersCount > 5 && (
                        <span className="shrink-0 ml-2 px-2 py-1 bg-gradient-to-r from-amber-100 to-amber-50 text-amber-700 text-[9px] font-black uppercase tracking-widest rounded-lg border border-amber-200 flex items-center gap-1 shadow-sm">
                          <Award size={10} /> Loyal
                        </span>
                      )}
                    </div>

                    <div className="grid grid-cols-2 gap-3 mb-5">
                      <div className="bg-gradient-to-br from-[#f8fafc] to-white rounded-xl p-3 border border-[#f1f5f9] shadow-[inset_0_2px_4px_rgba(0,0,0,0.01)] group-hover:border-[#581c87]/10 transition-colors">
                        <span className="text-[9px] font-bold text-zinc-400 uppercase tracking-widest block">Dispatches</span>
                        <span className="font-black text-[16px] text-[#0f172a] mt-0.5 block">{c.ordersCount}</span>
                      </div>
                      <div className="bg-gradient-to-br from-[#f8fafc] to-white rounded-xl p-3 border border-[#f1f5f9] shadow-[inset_0_2px_4px_rgba(0,0,0,0.01)] group-hover:border-emerald-500/10 transition-colors">
                        <span className="text-[9px] font-bold text-zinc-400 uppercase tracking-widest block">Gross Spend</span>
                        <span className="font-black text-[16px] text-emerald-600 mt-0.5 block">{c.totalSpent}</span>
                      </div>
                    </div>

                    <div className="space-y-2.5 mb-6 flex-1">
                      <div className="flex items-center gap-2.5 text-[12px] text-zinc-600 font-medium">
                        <div className="w-6 h-6 rounded-lg bg-zinc-50 flex items-center justify-center shrink-0 border border-zinc-100"><Phone size={12} className="text-zinc-400" /></div>
                        <span className="tabular-nums">{c.phone}</span>
                      </div>
                      {c.email && c.email !== '—' && (
                        <div className="flex items-center gap-2.5 text-[12px] text-zinc-600 font-medium">
                          <div className="w-6 h-6 rounded-lg bg-zinc-50 flex items-center justify-center shrink-0 border border-zinc-100"><Mail size={12} className="text-zinc-400" /></div>
                          <span className="truncate" title={c.email}>{c.email}</span>
                        </div>
                      )}
                    </div>

                    <div className="pt-4 border-t border-[#f1f5f9] flex items-center justify-between gap-3 mt-auto">
                      {canManage && (
                        <button
                          onClick={(e) => { e.stopPropagation(); showToast(`Promo code sent to ${c.phone}.`, 'success'); }}
                          className="w-10 h-10 flex items-center justify-center rounded-xl bg-purple-50 border border-purple-100 text-[#581c87] hover:bg-[#581c87] hover:border-[#581c87] hover:text-white transition-all cursor-pointer shrink-0 shadow-sm"
                          title="Send promo SMS"
                        >
                          <Send size={15} />
                        </button>
                      )}
                      <button
                        onClick={() => setSelectedCustomer(c)}
                        className="flex-1 h-10 flex items-center justify-center gap-2 rounded-xl bg-white border border-[#e2e8f0] text-[12px] font-bold text-zinc-700 hover:border-[#581c87] hover:bg-purple-50/30 hover:text-[#581c87] transition-all cursor-pointer shadow-sm group/btn"
                      >
                        View Profile <ChevronRight size={14} className="group-hover/btn:translate-x-1 transition-transform" />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
        );
      })()}

      {/* Orders & Deliveries — admin full console only (user store pages use the
          dedicated Orders / Deliveries nav items instead). */}
      {section === 'orders' && (
        <OrdersDeliveriesView searchQuery="" isCoimbatoreView={false} locationid={locationid} tenantId={tenantId} />
      )}

      {/* Store QR — scannable storefront link for this outlet. */}
      {section === 'qr' && (
        <div className="w-full">
          <StoreQRView
            tenantId={tenantId}
            locationid={locationid}
            storeName={store.name}
            storeZone={store.zone}
          />
        </div>
      )}

      {/* ── Replenishment Modal Dialog Overlay ── */}
      {replenishModal.show && replenishModal.item && (
        <div 
          className="fixed inset-0 bg-[#0f172a]/40 backdrop-blur-sm z-[200] flex items-center justify-center p-md animate-in fade-in duration-200"
          onClick={(e) => { if (e.target === e.currentTarget) setReplenishModal({ show: false, item: null }); }}
        >
          <div className="bg-white border border-[#e2e8f0] rounded-2xl w-full max-w-[24rem] max-h-[90vh] flex flex-col shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 text-xs font-sans">
            <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">
                <ShoppingCart size={15} className="text-[#581c87]" />
                Replenish Inventory Stack
              </h4>
              <button 
                onClick={() => setReplenishModal({ show: false, item: null })}
                className="p-1 hover:bg-zinc-200 rounded-full text-zinc-400 cursor-pointer transition-colors"
              >
                <X size={16} />
              </button>
            </div>

            <form onSubmit={handleReplenishSubmit} className="flex-1 flex flex-col min-h-0">
              <div className="p-md space-y-md overflow-y-auto flex-1">
                <div className="p-sm bg-purple-50/50 border border-purple-100 rounded-xl space-y-xs">
                  <span className="text-[9px] font-black text-purple-600 uppercase tracking-wider">Replenishing Item</span>
                  <p className="font-bold text-sm text-[#0f172a]">{replenishModal.item.name}</p>
                  <p className="text-[10px] text-zinc-400 font-bold uppercase tracking-wider">SKU: {replenishModal.item.sku}</p>
                </div>

                <div className="space-y-sm">
                  <div className="space-y-1">
                    <label className="font-bold text-zinc-400 uppercase tracking-widest text-[9px]">Destination Store</label>
                    <input 
                      type="text" 
                      value={store.name} 
                      className="w-full border border-[#e2e8f0] rounded-xl p-sm bg-[#f8fafc] text-zinc-500 font-semibold outline-none border-dashed"
                      disabled
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="font-bold text-zinc-500 uppercase tracking-widest text-[9px]">Replenish Quantity (Units)</label>
                    <input 
                      type="number" 
                      value={replenishQty}
                      onChange={(e) => setReplenishQty(Number(e.target.value))}
                      className="w-full border border-[#e2e8f0] rounded-xl p-sm bg-[#f8fafc] focus:bg-white outline-none focus:ring-1 focus:ring-[#581c87] font-bold"
                      min={1}
                      required
                    />
                  </div>
                </div>
              </div>

              <div className="p-md border-t border-[#f1f5f9] flex justify-end gap-sm bg-[#f8fafc] shrink-0">
                <button
                  type="button"
                  onClick={() => setReplenishModal({ show: false, item: null })}
                  className="px-4 py-2 border border-[#e2e8f0] rounded-xl 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-xl font-bold hover:bg-purple-800 cursor-pointer shadow-sm"
                >
                  Confirm Batch Dispatch
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ── Manual CSV Import simulated Modal ── */}
      {showImportModal && (
        <div 
          className="fixed inset-0 bg-[#0f172a]/40 backdrop-blur-sm z-[200] flex items-center justify-center p-md animate-in fade-in duration-200"
          onClick={(e) => { if (e.target === e.currentTarget && importState !== 'reading' && importState !== 'parsing' && importState !== 'saving') setShowImportModal(false); }}
        >
          <div className="bg-white border border-[#e2e8f0] rounded-2xl w-full max-w-[26rem] max-h-[90vh] flex flex-col shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 text-xs font-sans">
            <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">
                <UploadCloud size={15} className="text-[#581c87]" />
                Import Catalogue Manifest
              </h4>
              <button 
                onClick={() => setShowImportModal(false)}
                disabled={['reading', 'parsing', 'saving'].includes(importState)}
                className="p-1 hover:bg-zinc-200 rounded-full text-zinc-400 cursor-pointer transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
              >
                <X size={16} />
              </button>
            </div>

            <div className="p-md space-y-md overflow-y-auto flex-1">
              <p className="text-zinc-500 leading-relaxed font-medium">
                Upload or drop your CSV stock ledger files below to commission new items into the <strong>{store.name}</strong> local registry database.
              </p>

              {importState === 'idle' && (
                <div 
                  onClick={handleStartCsvImport}
                  className="border-2 border-dashed border-[#e2e8f0] hover:border-purple-300 rounded-2xl p-xl text-center cursor-pointer transition-colors bg-[#f8fafc] hover:bg-purple-50/10 space-y-sm group"
                >
                  <UploadCloud size={28} className="mx-auto text-zinc-400 group-hover:text-[#581c87] transition-colors" />
                  <div>
                    <p className="font-bold text-[#0f172a]">Click here to import file</p>
                    <p className="text-[10px] text-zinc-400 font-semibold uppercase tracking-wider mt-0.5">Mock file: coimbatore_manifest_v2.csv</p>
                  </div>
                </div>
              )}

              {['reading', 'parsing', 'saving'].includes(importState) && (
                <div className="border border-[#e2e8f0] rounded-xl p-md bg-[#f8fafc] space-y-md text-center">
                  <div className="relative w-8 h-8 mx-auto">
                    <span className="absolute inset-0 rounded-full border-2 border-purple-100" />
                    <span className="absolute inset-0 rounded-full border-2 border-t-purple-600 animate-spin" />
                  </div>
                  <div>
                    <p className="font-bold text-[#0f172a] uppercase tracking-wide">
                      {importState === 'reading' && 'Reading uploaded CSV sheets...'}
                      {importState === 'parsing' && 'Scanning item SKU catalogue mapping...'}
                      {importState === 'saving' && 'Syncing manifest entries with local inventory...'}
                    </p>
                    <p className="text-[10px] text-zinc-400 font-semibold mt-1">Kindly keep this window open while processing dispatches.</p>
                  </div>
                </div>
              )}

              {importState === 'done' && (
                <div className="border border-emerald-100 rounded-xl p-md bg-emerald-50/50 space-y-md text-center animate-in zoom-in-95">
                  <CheckCircle2 size={32} className="mx-auto text-emerald-600" />
                  <div>
                    <p className="font-black text-emerald-800 uppercase tracking-wide text-xs">Ledger Imported Successfully</p>
                    <p className="text-[10px] text-emerald-700 font-bold mt-1">3 new SKU codes commissioned successfully into local registry.</p>
                  </div>
                </div>
              )}
            </div>

            <div className="p-md border-t border-[#f1f5f9] flex justify-end bg-[#f8fafc] shrink-0">
              <button
                type="button"
                onClick={() => setShowImportModal(false)}
                disabled={['reading', 'parsing', 'saving'].includes(importState)}
                className="px-4 py-2 border border-[#e2e8f0] rounded-xl font-bold text-zinc-650 hover:bg-zinc-50 cursor-pointer disabled:opacity-50"
              >
                {importState === 'done' ? 'Close Window' : 'Cancel'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── Customer CRM Profile Side Drawer Overlay ── */}
      {selectedCustomer && (
        <div 
          className="fixed inset-0 bg-[#0f172a]/40 backdrop-blur-sm z-[200] flex justify-end p-0 animate-in fade-in duration-200"
          onClick={(e) => { if (e.target === e.currentTarget) setSelectedCustomer(null); }}
        >
          <div className="bg-white border-l border-[#e2e8f0] w-full max-w-[28rem] h-full flex flex-col shadow-2xl overflow-hidden animate-in slide-in-from-right duration-300 text-xs font-sans">
            
            {/* Header info */}
            <div className="p-lg border-b border-[#e2e8f0] bg-[#f8fafc] flex justify-between items-start shrink-0">
              <div className="flex items-center gap-md">
                <div className="w-12 h-12 rounded-full bg-gradient-to-br from-purple-600 to-indigo-600 text-white flex items-center justify-center font-black text-sm shadow-md">
                  {selectedCustomer.name.split(' ').map((n: string) => n[0]).join('')}
                </div>
                <div>
                  <h4 className="font-sans font-black text-base text-[#0f172a]">{selectedCustomer.name}</h4>
                  <span className="text-[10px] text-zinc-400 font-semibold">
                    {selectedCustomer.ordersCount} orders · {selectedCustomer.totalSpent} spent
                  </span>
                </div>
              </div>
              <button 
                onClick={() => setSelectedCustomer(null)}
                className="p-1 hover:bg-zinc-200 rounded-full text-zinc-400 cursor-pointer transition-colors"
              >
                <X size={18} />
              </button>
            </div>

            {/* Profile Drawer Details Container */}
            <div className="p-lg overflow-y-auto flex-1 space-y-lg">
              
              {/* Contact info list card */}
              <div className="space-y-sm bg-white border border-[#eceef2] rounded-2xl p-md shadow-sm">
                <span className="text-[9px] font-black text-purple-600 uppercase tracking-wider block">Profile Registry Details</span>
                
                <div className="space-y-xs text-zinc-650">
                  <div className="flex items-center gap-sm py-1 border-b border-[#f1f5f9]">
                    <Phone size={13} className="text-zinc-400 shrink-0" />
                    <span className="font-mono font-semibold">{selectedCustomer.phone}</span>
                  </div>
                  <div className="flex items-center gap-sm py-1 border-b border-[#f1f5f9]">
                    <Mail size={13} className="text-zinc-400 shrink-0" />
                    <span>{selectedCustomer.email || '—'}</span>
                  </div>
                  <div className="flex items-start gap-sm py-1">
                    <MapPin size={13} className="text-zinc-400 shrink-0 mt-0.5" />
                    <span>{selectedCustomer.address}</span>
                  </div>
                </div>
              </div>

              {/* Metric grid info overlay */}
              <div className="space-y-sm select-none">
                <div className="grid grid-cols-2 gap-sm">
                  <div className="bg-[#faf5ff] border border-[#f3e8ff] p-sm rounded-xl text-center">
                    <span className="text-[8px] font-black text-purple-400 uppercase tracking-widest block">Dispatches</span>
                    <span className="font-black text-sm text-[#581c87] mt-xs block">{selectedCustomer.ordersCount} dispatches</span>
                  </div>
                  <div className="bg-sky-50/50 border border-sky-100 p-sm rounded-xl text-center">
                    <span className="text-[8px] font-black text-sky-500 uppercase tracking-widest block">Gross spend</span>
                    <span className="font-black text-sm text-sky-700 mt-xs block">{selectedCustomer.totalSpent}</span>
                  </div>
                </div>
                {/* CSAT / AOV / retention have no backend yet ([R11]). */}
                <AwaitingApi label="Customer analytics" api="[R11]" compact />
              </div>

              {/* Live Customer Order History ledger */}
              <div className="space-y-sm">
                <h5 className="font-sans font-bold text-xs text-[#0f172a] flex items-center gap-xs">
                  <History size={14} className="text-[#581c87]" /> Past Interactions & Orders
                </h5>

                {customerOrdersQ.isLoading ? (
                  <p className="py-4 text-center text-[10px] text-zinc-400 font-semibold uppercase tracking-wider">Loading order history…</p>
                ) : customerOrderHistory.length === 0 ? (
                  <p className="py-4 text-center text-[10px] text-zinc-400 font-semibold uppercase tracking-wider">No past orders for this customer.</p>
                ) : (
                  <div className="divide-y divide-[#f1f5f9] select-none text-[11px] font-semibold text-zinc-650">
                    {customerOrderHistory.map((order, index) => (
                      <div key={order.id || index} className="py-2.5 flex justify-between items-center">
                        <div className="space-y-0.5">
                          <span className="text-[#0f172a]">{order.id}</span>
                          <p className="text-[9px] text-zinc-400 font-medium">{order.date}</p>
                        </div>
                        <div className="text-right">
                          <span className="font-mono text-[#581c87] font-bold">{order.amount}</span>
                          <span className="px-1.5 py-0.2 bg-emerald-50 text-emerald-600 rounded text-[7px] font-black tracking-wider block mt-0.5 uppercase">{order.status.replace(/_/g, ' ')}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>

            {/* Quick Actions in Side Drawer — management only */}
            {canManage && (
              <div className="p-lg bg-[#f8fafc] border-t border-[#e2e8f0] grid grid-cols-2 gap-sm shrink-0">
                <button
                  onClick={() => {
                    showToast(`Promo voucher code SMS broadcasted to customer.`, 'success');
                    setSelectedCustomer(null);
                  }}
                  className="w-full py-2.5 bg-[#581c87] hover:bg-purple-800 text-white rounded-xl font-bold text-center cursor-pointer transition shadow-sm"
                >
                  Send Promo SMS
                </button>

                <button
                  onClick={() => {
                    showToast(`Refund credit index check initiated.`, 'info');
                    setSelectedCustomer(null);
                  }}
                  className="w-full py-2.5 border border-[#e2e8f0] bg-white hover:bg-zinc-50 rounded-xl font-bold text-center text-zinc-700 cursor-pointer transition"
                >
                  Issue Store Credit
                </button>
              </div>
            )}
          </div>
        </div>
      )}

    </div>
  );
}
