import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  LayoutDashboard, ShoppingBag, ShoppingCart, BookOpen, Settings,
  Target, LogOut, Plus, Trash2, ArrowLeft, Phone, Mail, Package, ClipboardList, CheckCircle, Share2, Facebook, Instagram, Twitter, Youtube, ImageIcon, Image as LucideImage,
  Star, MessageSquare, Layers, Sparkles, Award, Zap, Utensils, Shield, Palette, Eye, Edit3, HelpCircle, List,
  Heart, ThumbsUp, Leaf, Flame, Clock, Info, MapPin, Grid, X, Download, Calendar, ChevronDown, Activity, CreditCard, Truck, TrendingUp, Code, Users, UserPlus, UserCheck, UserX, Check, XCircle, AlertCircle, TrendingUp as TrendingUpIcon, TrendingDown as TrendingDownIcon, Eye as EyeIcon, MousePointer,
  Printer, Send, RefreshCw, FileText, Archive, BarChart2, ShieldCheck, ListTree, Gift, Upload, Globe, Type, LayoutTemplate, Camera, Tag, QrCode, Infinity
} from 'lucide-react';
import { Product, SiteSettings, PriceConfig, Order, OrderItem, Testimonial, User, Permission } from '../types';
import ProductLandingPage from './ProductLandingPage';
import ProductLandingPage01 from './ProductLandingPage01';
import ProductLandingPage02 from './ProductLandingPage02';
import ProductLandingPage03 from './ProductLandingPage03';
import ProductLandingPage04 from './ProductLandingPage04';
import ProductLandingPage05 from './ProductLandingPage05';
import ProductLandingPage06 from './ProductLandingPage06';
import ModeratorManagement from './ModeratorManagement';
import CourierSettings from './CourierSettings';
import LeadsManager from './admin/LeadsManager';

import POSSystem from './POSSystem';
import CourierManager from './CourierManager';
import DeliveryLocationsEditor from './DeliveryLocationsEditor';
import HomePageEditor from './HomePageEditor';
import CategoryManager from './CategoryManager';
import CustomPagesEditor from './CustomPagesEditor';
import UbaidiChat from './UbaidiChat';
import FacebookAdsPanel from './FacebookAdsPanel';
import UbaidiAdsMarketer from './UbaidiAdsMarketer';
import MarketingManager from './admin/MarketingManager';
import AppearanceManager from './admin/AppearanceManager';
import ProductManager from './admin/ProductManager';
import DomainTab from './admin/DomainTab';
import StoreSettingsManager from './admin/StoreSettingsManager';
import StockTab from './admin/StockTab';
import TestimonialsManager from './admin/TestimonialsManager';
import DashboardOverview from './admin/DashboardOverview';
import OrdersManager from './admin/OrdersManager';
import MyPlanTab from './admin/MyPlanTab';
import MessengerAIAgentPanel from './admin/MessengerAIAgentPanel';

// API Base URL
const API_BASE = '/api';

// ── Store slug from subdomain ─────────────────────────────────────────────────
const getStoreSlug = (): string => {
  const hostname = window.location.hostname; // e.g. ubiadir.localhost
  const parts = hostname.split('.');
  if (parts.length >= 2 && parts[0] !== 'www' && parts[0] !== 'localhost' && !/^\d+$/.test(parts[0])) {
    return parts[0];
  }
  // Also check if admin modal was opened from tenant localStorage
  try {
    const td = localStorage.getItem('tenant_data');
    if (td) { const parsed = JSON.parse(td); return parsed.business_slug || parsed.slug || ''; }
  } catch { /* noop */ }
  return '';
};

// ── Tenant auth header helper ─────────────────────────────────────────────────
// সব API call-এ এই header পাঠাতে হবে যাতে শুধু এই store-এর data আসে
const getTenantHeaders = (extra: Record<string, string> = {}): Record<string, string> => {
  const token = localStorage.getItem('tenant_token') || '';
  const h: Record<string, string> = { 'Content-Type': 'application/json', ...extra };
  if (token) h['X-Tenant-Token'] = token;
  return h;
};

// Form upload headers (no Content-Type — browser sets boundary automatically)
const getTenantUploadHeaders = (): Record<string, string> => {
  const token = localStorage.getItem('tenant_token') || '';
  const h: Record<string, string> = { 'Accept': 'application/json' };
  if (token) h['X-Tenant-Token'] = token;
  return h;
};

// Lead interface
interface Lead {
  phone: string;
  name?: string;            // production DB column
  customer_name?: string;   // alias
  address?: string;
  product?: string;         // production DB column
  product_context?: string; // alias
  status?: string;
  updated_at?: string;
}

interface AdminDashboardProps {
  products: Product[];
  settings: SiteSettings;
  orders: Order[];
  leads: Lead[];
  testimonials: Testimonial[];
  updateProducts: (products: Product[]) => void;
  updateSettings: (settings: SiteSettings) => void;
  updateOrders: (orders: Order[]) => void;
  updateLeads: (leads: Lead[]) => void;
  updateTestimonials: (testimonials: Testimonial[]) => void;
  onLogout: () => void;
}


const SectionHeader = ({ icon: Icon, title, subtitle, id, color = "red" }: any) => (
  <div id={id} className={`pt-12 mb-8 scroll-mt-32 group/sec`}>
    <div className="flex items-center gap-4 mb-3">
      <div className={`p-3 rounded-2xl shadow-sm bg-${color}-50 dark:bg-${color}-950/30 text-${color}-600 ring-1 ring-${color}-100 dark:ring-${color}-900/50 group-hover/sec:scale-110 transition-transform`}>
        <Icon size={24} />
      </div>
      <div>
        <h3 className="text-2xl font-black text-slate-900 dark:text-white uppercase tracking-tight">{title}</h3>
        <p className="text-xs text-slate-500 dark:text-slate-400 font-bold uppercase tracking-widest flex items-center gap-2">
          <Info size={12} className={`text-${color}-500`} /> {subtitle}
        </p>
      </div>
    </div>
    <div className={`h-1 w-20 bg-${color}-600 rounded-full ml-16`}></div>
  </div>
);

const FieldGroup = ({ label, help, children, icon: Icon }: any) => (
  <div className="bg-white dark:bg-slate-900 p-8 rounded-[40px] border border-slate-100 dark:border-slate-800 shadow-sm hover:shadow-md transition-shadow relative overflow-hidden">
    {Icon && <div className="absolute top-6 right-6 opacity-5"><Icon size={80} /></div>}
    <div className="flex items-start gap-4 mb-6 relative z-10">
      <div className="space-y-1">
        <label className="text-xs font-black uppercase text-slate-950 dark:text-slate-200 tracking-wider flex items-center gap-2">
          {label}
        </label>
        {help && <p className="text-[11px] font-medium text-slate-600 dark:text-slate-400 leading-relaxed italic">{help}</p>}
      </div>
    </div>
    <div className="relative z-10">{children}</div>
  </div>
);

// Fixed input component
const Input = ({ label, value, onChange, type = "text", icon, placeholder, help, className = '', disabled }: any) => {
  const safeValue = value !== null && value !== undefined ? String(value) : '';

  return (
    <div className="space-y-1.5 w-full">
      <label className="text-[10px] font-black uppercase text-slate-950 dark:text-slate-300 ml-2 flex items-center gap-1.5">
        {label} {help && <span title={help} className="cursor-help text-red-500"><HelpCircle size={12} /></span>}
      </label>
      <div className="relative">
        {icon && <div className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-500 dark:text-slate-400">{icon}</div>}
        <input
          type={type}
          className={`w-full ${icon ? 'pl-14' : 'px-6'} py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border border-transparent font-bold focus:ring-2 focus:ring-red-600 focus:bg-white text-slate-950 dark:text-white transition-all shadow-inner placeholder-slate-950 ${className}`}
          value={safeValue}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          disabled={disabled}
        />
      </div>
    </div>
  );
};

// CSV Download Function
const downloadCSV = (data: any[], filename: string, headers: string[]) => {
  const csvRows = [];
  csvRows.push(headers.join(','));

  for (const row of data) {
    const values = headers.map(header => {
      let value = '';

      if (header === 'Order ID') value = row.id || '';
      else if (header === 'Date') value = row.date ? new Date(row.date).toLocaleString('bn-BD') : '';
      else if (header === 'Customer') value = row.customerName || '';
      else if (header === 'Phone') value = row.phone || '';
      else if (header === 'Address') value = row.address || '';
      else if (header === 'Items') value = row.items ? row.items.map((i: any) => `${i.name} (${i.size || ''})`).join(' | ') : '';
      else if (header === 'Subtotal') value = row.subtotal?.toString() || '0';
      else if (header === 'Delivery') value = row.deliveryCharge?.toString() || '0';
      else if (header === 'Total') value = row.total?.toString() || '0';
      else if (header === 'Status') value = row.status || '';
      else if (header === 'Source') value = row.source || '';
      else if (header === 'Name') value = row.name || row.customer_name || '';
      else if (header === 'Product Context') value = row.product || row.product_context || '';
      else if (header === 'Last Updated') value = row.updated_at ? new Date(row.updated_at).toLocaleString('bn-BD') : '';

      return `"${String(value).replace(/"/g, '""')}"`;
    });
    csvRows.push(values.join(','));
  }

  const csvString = csvRows.join('\n');
  const blob = new Blob(["\uFEFF" + csvString], { type: 'text/csv;charset=utf-8;' });
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.setAttribute('href', url);
  a.setAttribute('download', filename);
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(url);
};

// Image upload function using PHP API
const uploadImageToPHP = async (file: File): Promise<string | null> => {
  const formData = new FormData();
  formData.append('image', file);

  try {
    console.log('📤 Uploading image:', file.name);

    const response = await fetch('/api/admin/upload', {
      method: 'POST',
      headers: getTenantUploadHeaders(),
      body: formData
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('Upload failed:', response.status, errorText);
      throw new Error(`Upload failed: ${response.status}`);
    }

    const data = await response.json();
    console.log('✅ Upload success:', data);

    if (!data.success) {
      throw new Error(data.error || 'Upload failed');
    }

    return data.url;
  } catch (error) {
    console.error('Upload error:', error);
    return null;
  }
};

// ── Admin Banner Carousel ──────────────────────────────────────────────────




const getBanglaName = (nameBangla?: string, nameEn?: string): string => {
  if (nameBangla && nameBangla.trim() !== '') return nameBangla;
  if (nameEn && nameEn.trim() !== '') return nameEn;
  return 'Unnamed';
};

const VARIATION_OPTIONS = {
  weight: ["৫০ গ্রাম", "১০০ গ্রাম", "২৫০ গ্রাম", "৫০০ গ্রাম", "১ কেজি", "২ কেজি", "৫ কেজি"],
  pieces: ["1 Pc", "2 Pcs", "3 Pcs", "1 Set"],
  clothing: ["S", "M", "L", "XL", "XXL", "Free Size"]
};

const NavItem = ({ active, onClick, icon, label, count, disabled = false }: any) => (
  <button
    onClick={onClick}
    disabled={disabled}
    style={active ? {
      background: 'linear-gradient(135deg, rgba(139,92,246,0.25), rgba(99,102,241,0.15))',
      borderLeft: '2.5px solid #a78bfa',
      boxShadow: '0 0 20px rgba(139,92,246,0.12)'
    } : {}}
    className={`w-full flex items-center justify-between px-4 py-2.5 rounded-xl transition-all duration-200 text-sm group border border-transparent ${disabled
      ? 'opacity-20 cursor-not-allowed'
      : active
        ? 'text-slate-800 dark:text-white'
        : 'text-slate-500 dark:text-slate-400 hover:text-white hover:bg-white/5 hover:border-white/8'
      }`}
  >
    <div className="flex items-center gap-3">
      <span
        className="w-7 h-7 rounded-lg flex items-center justify-center transition-all"
        style={active ? {
          background: 'linear-gradient(135deg, #8b5cf6, #6366f1)',
          boxShadow: '0 0 12px rgba(139,92,246,0.4)',
          color: '#fff'
        } : {}}
      >
        <span className={active ? '' : 'text-slate-500 group-hover:text-violet-400 transition-colors'}>
          {icon}
        </span>
      </span>
      <span className={`font-bold font-bangla ${active ? 'tracking-wide text-violet-700 dark:text-violet-300' : 'group-hover:translate-x-1 transition-transform duration-200'}`}>{label}</span>
    </div>
    {count !== undefined && count > 0 && (
      <span className={`px-2 py-0.5 text-xs font-black rounded-lg ${active ? 'bg-violet-100 text-violet-700 dark:bg-violet-900/50 dark:text-violet-300' : 'bg-red-50 text-red-600 dark:bg-red-500/10'}`}>
        {count > 99 ? '99+' : count}
      </span>
    )}
  </button>
);

const AdminDashboard: React.FC<AdminDashboardProps> = ({
  products, settings, orders, leads, testimonials,
  updateProducts, updateSettings, updateOrders,
  updateLeads, updateTestimonials, onLogout
}) => {
  // =====================================================
  // USER & PERMISSIONS STATE
  // =====================================================
  const [currentUser, setCurrentUser] = useState<User | null>(() => {
    // ── Tenant login: localStorage-এ tenant_data থাকলে full admin access ──
    const tenantData = localStorage.getItem('tenant_data');
    if (tenantData) {
      try {
        const t = JSON.parse(tenantData);
        // Create a synthetic admin user from tenant data
        const syntheticAdmin: User = {
          id: parseInt(String(t.id || 0), 10) || 0,
          name: t.name || t.business_name || 'Admin',
          email: t.phone || '',
          role: 'admin',
          permissions: {} as any,
          created_at: t.created_at || new Date().toISOString(),
        };
        // Save to sessionStorage so it persists
        sessionStorage.setItem('admin_user', JSON.stringify(syntheticAdmin));
        return syntheticAdmin;
      } catch { /* fall through */ }
    }
    // ── Legacy: sessionStorage-এ admin_user থাকলে ──
    const userStr = sessionStorage.getItem('admin_user');
    if (userStr) {
      try { return JSON.parse(userStr); } catch { return null; }
    }
    // ── শেষ fallback: logged-in হলে default admin role দাও ──
    if (sessionStorage.getItem('shophyfast_admin_auth') === 'true') {
      const fallback: User = {
        id: 0, name: 'Admin', email: '',
        role: 'admin', permissions: {} as any, created_at: new Date().toISOString(),
      };
      sessionStorage.setItem('admin_user', JSON.stringify(fallback));
      return fallback;
    }
    return null;
  });

  const [selectedOrders, setSelectedOrders] = useState<string[]>([]);

  // ── Plan Feature Gating (tenant subscription) ─────────────────────────────
  // Default: all true (non-tenant admin sees everything)
  const [planFeatures, setPlanFeatures] = useState<Record<string, boolean>>({
    products: true, categories: true, orders: true, leads: true,
    reviews: true, stock: true, marketing: true, courier: true,
    home_editor: true, landing_editor: true, messenger_ai: true,
  });
  const [planFeaturesLoaded, setPlanFeaturesLoaded] = useState(false);
  const [trialDaysRemaining, setTrialDaysRemaining] = useState<number | null>(null);
  const [trialEndsAt, setTrialEndsAt] = useState<string | null>(null);
  const [tenantSubscriptionStatus, setTenantSubscriptionStatus] = useState<string>('');
  const [adminBanners, setAdminBanners] = useState<any[]>([]);

  // Fetch plan features if tenant is logged in
  useEffect(() => {
    const tenantToken = localStorage.getItem('tenant_token') || '';
    if (!tenantToken) { setPlanFeaturesLoaded(true); return; }
    fetch('/api/admin/tenant/me', {
      headers: { 'X-Tenant-Token': tenantToken },
    })
      .then(r => r.json())
      .then(d => {
        if (d.plan_features && typeof d.plan_features === 'object') {
          setPlanFeatures(d.plan_features as Record<string, boolean>);
        }
        if (typeof d.trial_days_remaining === 'number') {
          setTrialDaysRemaining(d.trial_days_remaining);
        }
        if (d.trial_ends_at) setTrialEndsAt(d.trial_ends_at);
        if (d.subscription_status) setTenantSubscriptionStatus(d.subscription_status);
        setPlanFeaturesLoaded(true);
      })
      .catch(() => setPlanFeaturesLoaded(true));

    fetch('/api/landing-data')
      .then(r => r.json())
      .then(d => {
        if (d.admin_dashboard_banners) {
          setAdminBanners(d.admin_dashboard_banners);
        }
      })
      .catch(() => {});
  }, []);

  // Map tab/section names to plan feature keys
  const hasPlanAccess = (tabOrSection: string): boolean => {
    const isTenant = !!localStorage.getItem('tenant_token');
    if (!isTenant) return true; // regular admin: no plan restriction
    const keyMap: Record<string, string> = {
      products: 'products',
      categories: 'categories',
      orders: 'orders',
      leads: 'leads',
      reviews: 'reviews',
      testimonials: 'reviews',
      stock: 'stock',
      marketing: 'marketing',
      'courier-settings': 'courier',
      courier: 'courier',
      'delivery-locations': 'courier',   // ✅ shares courier plan key
      'home-editor': 'home_editor',
      'landing-editor': 'landing_editor',
      'messenger-ai': 'messenger_ai',
      dashboard: undefined as any,  // always accessible
      appearance: undefined as any,  // always accessible
      moderators: undefined as any,  // always accessible
      'my-plan': undefined as any,  // always accessible
      domain: undefined as any,  // always accessible
    };
    const planKey = keyMap[tabOrSection];
    if (!planKey) return true; // no restriction for this tab
    return !!planFeatures[planKey];
  };

  // Permission check function
  const canAccess = (section: string, action: 'view' | 'edit' | 'delete' = 'view'): boolean => {
    if (currentUser?.role === 'admin') return true;

    if (currentUser?.role === 'moderator' && currentUser?.permissions) {
      const perm = currentUser.permissions[section];
      if (!perm) return false;

      switch (action) {
        case 'view': return perm.canView;
        case 'edit': return perm.canEdit;
        case 'delete': return perm.canDelete;
        default: return false;
      }
    }

    return false;
  };

  const canEditItem = (item: any): boolean => {
    if (!item) return false;

    let section = '';
    if (item.price !== undefined) section = 'products';
    else if (item.rating !== undefined) section = 'testimonials';
    else if (item.landingTitle !== undefined) section = 'landing-editor';

    return canAccess(section, 'edit');
  };

  const canDeleteItem = (item: any): boolean => {
    if (!item) return false;

    let section = '';
    if (item.price !== undefined) section = 'products';
    else if (item.rating !== undefined) section = 'testimonials';

    return canAccess(section, 'delete');
  };

  const [activeTab, setActiveTab] = useState<'dashboard' | 'products' | 'categories' | 'orders' | 'leads' | 'reviews' | 'hero' | 'social' | 'appearance' | 'contact' | 'pixel' | 'landing-editor' | 'home-editor' | 'moderators' | 'courier-settings' | 'delivery-locations' | 'stock' | 'marketing' | 'messenger-ai' | 'pos' | 'my-plan' | 'facebook-ads' | 'ubaidi-ads-marketer' | 'pages' | 'domain'>('dashboard');
  const [editingItem, setEditingItem] = useState<any>(null);
  const [qrProduct, setQrProduct] = useState<any>(null); // ✅ QR code modal
  const [editingOrder, setEditingOrder] = useState<Order | null>(null);
  const [isCreatingOrder, setIsCreatingOrder] = useState(false);
  const [tempPriceList, setTempPriceList] = useState<{ size: string, config: PriceConfig }[]>([]);
  const [isSaving, setIsSaving] = useState(false);
  const [previewMode, setPreviewMode] = useState(true);
  const [isLoading, setIsLoading] = useState(false);

  // ── Webcam capture state ─────────────────────────────────────────────
  const [showWebcam, setShowWebcam] = useState(false);
  const webcamVideoRef = useRef<HTMLVideoElement>(null);
  const webcamStreamRef = useRef<MediaStream | null>(null);
  const webcamTargetField = useRef<string>('itemImage');

  const [notification, setNotification] = useState<{ message: string, type: 'success' | 'error' } | null>(null);
  const [showNotification, setShowNotification] = useState(false);

  // ── Branding local form state (prevents per-keystroke API calls) ───────────
  const [fbGraphAccessKey, setFbGraphAccessKey] = useState('');
  const [fbAdAccountId, setFbAdAccountId] = useState('');

  // ── Analytics: Real data from DB ──────────────────────────────────────────
  const [pageViews, setPageViews] = useState<number>(0);
  const [contentViews, setContentViews] = useState<number>(0);
  const [initiatedCheckouts, setInitiatedCheckouts] = useState<number>(0);
  const [todayPageViews, setTodayPageViews] = useState<number>(0);
  const [analyticsLoading, setAnalyticsLoading] = useState(false);

  // Analytics filter state (must be before useEffect that uses it)
  const [analyticsPeriod, setAnalyticsPeriod] = useState<'today' | 'week' | 'month' | 'year' | 'custom'>('month');
  const [analyticsStart, setAnalyticsStart] = useState('');
  const [analyticsEnd, setAnalyticsEnd] = useState('');

  const fetchAnalyticsData = async (period = 'month') => {
    setAnalyticsLoading(true);
    try {
      const res = await fetch(`/api/analytics?action=summary&period=${period}`, {
        headers: getTenantHeaders(),
      });
      const data = await res.json();
      if (data.success) {
        setPageViews(data.summary.page_views || 0);
        setContentViews(data.summary.product_views || 0);
        setInitiatedCheckouts(data.summary.checkout_starts || 0);
        setTodayPageViews(data.summary.today_page_views || 0);
      }
    } catch (e) {
      console.warn('Analytics fetch failed', e);
    } finally {
      setAnalyticsLoading(false);
    }
  };

  useEffect(() => {
    fetchAnalyticsData(analyticsPeriod === 'custom' ? 'month' : analyticsPeriod);
  }, [analyticsPeriod]);

  const [orderStartDate, setOrderStartDate] = useState('');
  const [orderEndDate, setOrderEndDate] = useState('');
  const [orderStatusFilter, setOrderStatusFilter] = useState('all');
  const [leadStatusFilter, setLeadStatusFilter] = useState('all');
  const [leadSearch, setLeadSearch] = useState('');


  // =====================================================
  // HELPER FUNCTIONS
  // =====================================================

  const showToast = (message: string, type: 'success' | 'error' = 'success') => {
    setNotification({ message, type });
    setShowNotification(true);
    setTimeout(() => setShowNotification(false), 3000);
  };

  const getSortedOrders = (ordersToSort: Order[]) => {
    const statusOrder: Record<string, number> = {
      'pending': 1,
      'Confirmed Order': 2,
      'completed': 3,
      'cancelled': 4
    };

    // Deduplicate by ID (keep first occurrence) to prevent React duplicate key warnings
    const seen = new Set<string>();
    const unique = ordersToSort.filter(o => {
      if (seen.has(o.id)) return false;
      seen.add(o.id);
      return true;
    });

    return unique.sort((a, b) => {
      const orderA = statusOrder[a.status] || 5;
      const orderB = statusOrder[b.status] || 5;
      return orderA - orderB;
    });
  };

  const getSortedLeads = (leadsToSort: Lead[]) => {
    const statusOrder: Record<string, number> = {
      'partial_entry': 1,
      'Lead': 2,
      'Lead - In Progress': 3,
      'converted': 4,
      'Abandoned Lead': 5
    };

    return [...leadsToSort].sort((a, b) => {
      const orderA = statusOrder[a.status || 'Lead'] || 6;
      const orderB = statusOrder[b.status || 'Lead'] || 6;
      return orderA - orderB;
    });
  };

  const handleSelectAllOrders = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.checked) {
      setSelectedOrders(orders.map(o => o.id));
    } else {
      setSelectedOrders([]);
    }
  };

  const handleSelectOrder = (orderId: string, checked: boolean) => {
    if (checked) {
      setSelectedOrders(prev => [...prev, orderId]);
    } else {
      setSelectedOrders(prev => prev.filter(id => id !== orderId));
    }
  };

  // =====================================================
  // DATA FETCHING EFFECTS
  // =====================================================

  useEffect(() => {
    if (!canAccess('orders', 'view') && !canAccess('leads', 'view')) return;

    const token = localStorage.getItem('tenant_token') || '';
    if (!token) {
      // No token — force re-login
      console.warn('⚠️ No tenant_token found, redirecting to login...');
      sessionStorage.removeItem('shophyfast_admin_auth');
      sessionStorage.removeItem('admin_user');
      window.location.reload();
      return;
    }

    const fetchOrdersAndLeads = async () => {
      setIsLoading(true);
      try {
        console.log('📡 Fetching orders from API...');

        const ordersResponse = await fetch('/api/admin/orders', { headers: getTenantHeaders() });

        // ── 401: token expired or invalid — force re-login ────────────────
        if (ordersResponse.status === 401) {
          console.warn('⚠️ Token invalid (401). Clearing auth and redirecting to login...');
          localStorage.removeItem('tenant_token');
          localStorage.removeItem('tenant_data');
          sessionStorage.removeItem('shophyfast_admin_auth');
          sessionStorage.removeItem('admin_user');
          window.location.reload();
          return;
        }

        if (!ordersResponse.ok) throw new Error('Failed to fetch orders');
        const ordersData = await ordersResponse.json();

        if (ordersData.success && ordersData.data) {
          console.log('✅ Orders fetched from API:', ordersData.data.length);

          const mappedOrders = ordersData.data.map((order: any) => ({
            id: order.id,
            session_id: order.session_id,
            customerName: order.customer_name || 'Anonymous',
            phone: order.phone || '',
            address: order.address || '',
            items: order.items || [],
            subtotal: order.subtotal || 0,
            deliveryCharge: order.delivery_charge || 0,
            total: order.total || 0,
            status: order.status || 'pending',
            source: order.source || 'Website',
            date: order.created_at || new Date().toISOString(),
            confirmed_at: order.confirmed_at,
            courier_status: order.courier_status,
            courier_consignment_id: order.courier_consignment_id,
            courier_invoice: order.courier_invoice,
            label_generated: order.label_generated || 0,
            steadfast_info: order.steadfast_info || null
          }));

          console.log('✅ Mapped orders for display:', mappedOrders);
          updateOrders(mappedOrders);
        } else {
          console.error('Orders fetch failed:', ordersData.error);
          updateOrders([]);
        }

        console.log('📡 Fetching leads from API...');
        const leadsResponse = await fetch('/api/admin/leads', { headers: getTenantHeaders() });
        if (leadsResponse.status === 401) { updateLeads([]); return; }
        if (!leadsResponse.ok) throw new Error('Failed to fetch leads');
        const leadsData = await leadsResponse.json();

        if (leadsData.success && leadsData.data) {
          console.log('✅ Leads fetched:', leadsData.data.length);
          updateLeads(leadsData.data);
        } else {
          console.error('Leads fetch failed:', leadsData.error);
          updateLeads([]);
        }

      } catch (err) {
        console.error('Error fetching orders/leads:', err);
        showToast('Failed to load data', 'error');
      } finally {
        setIsLoading(false);
      }
    };

    fetchOrdersAndLeads();
  }, []);

  useEffect(() => {
    if (settings) {
      // ── Sync branding form from tenant settings ────────────────────────────

      const cleanGtmId = (settings?.gtm_id || settings?.gtmId)?.replace(/\s+/g, '') || '';
      setFbGraphAccessKey(settings.fbGraphAccessKey || '');
      setFbAdAccountId(settings.fbAdAccountId || '');
    }
  }, [settings]);

  useEffect(() => {
    const checkoutCount = leads.length + orders.filter(o =>
      o.status === 'Lead' || o.status === 'Lead - In Progress'
    ).length;
    setInitiatedCheckouts(checkoutCount);
  }, [orders, leads]);

  const validLeads = leads.filter((lead: Lead) => {
    const phone = lead.phone?.replace(/\D/g, '');
    return phone && phone.length === 11;
  });

  const uniqueLeads = Array.from(
    new Map(validLeads.map(lead => [lead.phone, lead])).values()
  );

  useEffect(() => {
    if (editingItem?.priceConfigs) {
      try {
        // ✅ FIX: PHP DB returns priceConfigs as a JSON string — parse it first
        const parsed = typeof editingItem.priceConfigs === 'string'
          ? JSON.parse(editingItem.priceConfigs)
          : editingItem.priceConfigs;

        if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
          setTempPriceList(
            Object.entries(parsed).map(([size, config]) => ({
              size,
              config: config as PriceConfig
            }))
          );
        } else {
          setTempPriceList([]);
        }
      } catch {
        setTempPriceList([]);
      }
    } else {
      setTempPriceList([]);
    }
  }, [editingItem?.priceConfigs, editingItem?.id]);

  // =====================================================
  // API FUNCTIONS
  // =====================================================

  // ✅ FIXED: saveSiteSettings with proper field mapping for database
  const saveSiteSettings = async (updates: any) => {
    if (!canAccess('appearance', 'edit') && !canAccess('hero', 'edit') && !canAccess('contact', 'edit') && !canAccess('social', 'edit') && !canAccess('pixel', 'edit')) {
      showToast('You do not have permission to edit settings', 'error');
      return;
    }

    setIsSaving(true);
    try {
      // Remove double mapping, use the original fields to match the PHP API expectations
      const payload: any = { ...updates };

      console.log('📡 Saving settings with payload:', payload);

      // Build URL — always include slug so server can resolve tenant even w/o token
      const slug = getStoreSlug();
      const settingsUrl = '/api/admin/settings';
      const response = await fetch(settingsUrl, {
        method: 'POST',
        headers: getTenantHeaders({ 'Accept': 'application/json' }),
        body: JSON.stringify(payload)
      });

      if (!response.ok) {
        const errorText = await response.text();
        console.error('Settings save failed:', response.status, errorText);
        throw new Error(`Failed to save settings: ${response.status}`);
      }

      const data = await response.json();
      console.log('✅ Settings save response:', data);

      if (!data.success) {
        throw new Error(data.error || 'Unknown error');
      }

      updateSettings({ ...settings, ...updates });

      if (updates.fbGraphAccessKey !== undefined) setFbGraphAccessKey(updates.fbGraphAccessKey);
      if (updates.fbAdAccountId !== undefined) setFbAdAccountId(updates.fbAdAccountId);
      showToast('Settings Published!', 'success');
    } catch (err: any) {
      console.error('Save error:', err);
      showToast(err.message, 'error');
    } finally {
      setIsSaving(false);
    }
  };

  // ── Webcam helpers ───────────────────────────────────────────────────────────
  const openWebcam = async (field: string = 'itemImage') => {
    webcamTargetField.current = field;
    setShowWebcam(true);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: { ideal: 'environment' }, width: { ideal: 1280 }, height: { ideal: 720 } },
        audio: false,
      });
      webcamStreamRef.current = stream;
      // Wait for modal to mount, then attach stream
      setTimeout(() => {
        if (webcamVideoRef.current) {
          webcamVideoRef.current.srcObject = stream;
          webcamVideoRef.current.play();
        }
      }, 150);
    } catch (err) {
      console.error('Camera access denied:', err);
      showToast('ক্যামেরা অ্যাক্সেস নেই বা ব্লক করা আছে', 'error');
      setShowWebcam(false);
    }
  };

  const captureFromWebcam = async () => {
    if (!webcamVideoRef.current) return;
    const video = webcamVideoRef.current;
    const canvas = document.createElement('canvas');
    canvas.width = video.videoWidth || 1280;
    canvas.height = video.videoHeight || 720;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    canvas.toBlob(async (blob) => {
      if (!blob) return;
      const file = new File([blob], `webcam_${Date.now()}.jpg`, { type: 'image/jpeg' });
      closeWebcam();
      try {
        setIsSaving(true);
        const imageUrl = await uploadImageToPHP(file);
        if (!imageUrl) { showToast('Upload failed', 'error'); return; }
        const field = webcamTargetField.current;
        if (field === 'itemImage') setEditingItem((prev: any) => ({ ...prev, image: imageUrl }));
        showToast('ছবি সফলভাবে যোগ হয়েছে! ✅', 'success');
      } catch (e) {
        showToast('Upload failed', 'error');
      } finally {
        setIsSaving(false);
      }
    }, 'image/jpeg', 0.92);
  };

  const closeWebcam = () => {
    if (webcamStreamRef.current) {
      webcamStreamRef.current.getTracks().forEach(t => t.stop());
      webcamStreamRef.current = null;
    }
    if (webcamVideoRef.current) webcamVideoRef.current.srcObject = null;
    setShowWebcam(false);
  };


  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>, field: any) => {
    const file = e.target.files?.[0];
    if (!file) return;

    try {
      setIsSaving(true);

      const imageUrl = await uploadImageToPHP(file);

      if (!imageUrl) {
        showToast('Image upload failed', 'error');
        return;
      }

      console.log(`✅ Image uploaded for ${field}:`, imageUrl);

      if (field === 'itemImage') setEditingItem({ ...editingItem, image: imageUrl });
      else if (field === 'landingProductImage') setEditingItem({ ...editingItem, landingProductImage: imageUrl });
      else if (field === 'landingSolutionImage') setEditingItem({ ...editingItem, landingSolutionImage: imageUrl });

      else if (field === 'packageSectionImage') setEditingItem({ ...editingItem, packageSectionImage: imageUrl });
      else if (field === 'reviewAvatar') setEditingItem({ ...editingItem, avatar: imageUrl });
      else if (field === 'logo' || field === 'footerLogo' || field === 'favicon') {
        await saveSiteSettings({ [field]: imageUrl });
      }

      showToast('Image uploaded successfully!', 'success');
    } catch (err) {
      console.error('Upload error:', err);
      showToast('Upload failed.', 'error');
    } finally {
      setIsSaving(false);
    }
  };

  const calculateSalePrice = (original: number, discValue: number, discType: 'fixed' | 'percentage'): number => {
    if (!original) return 0;
    if (discType === 'percentage') return Math.max(0, Math.round(original - (original * (discValue / 100))));
    return Math.max(0, original - discValue);
  };

  const saveContent = async () => {
    if (isSaving) return;

    if (!canEditItem(editingItem)) {
      showToast('You do not have permission to edit this item', 'error');
      return;
    }

    setIsSaving(true);
    let itemToSave = { ...editingItem };

    try {
      if (itemToSave.rating !== undefined) {
        const testimonialData: any = {
          id: itemToSave.id,
          customer_name: itemToSave.name || itemToSave.customer_name,
          content: itemToSave.text || itemToSave.content,
          rating: itemToSave.rating,
          image: itemToSave.avatar || itemToSave.image,
          is_active: true
        };

        const isNewTestimonial = !itemToSave.id || String(itemToSave.id).startsWith('T-');
        const url = isNewTestimonial ? '/api/admin/testimonials' : `/api/admin/testimonials/${itemToSave.id}`;
        const method = isNewTestimonial ? 'POST' : 'PUT';

        // Remove the temporary ID from the payload if it's new
        if (isNewTestimonial) {
          delete testimonialData.id;
        }

        const response = await fetch(url, {
          method,
          headers: getTenantHeaders({ 'Accept': 'application/json' }),
          body: JSON.stringify(testimonialData)
        });

        if (!response.ok) {
          throw new Error('Failed to save testimonial');
        }

        const data = await response.json();

        if (!data.success) {
          throw new Error(data.error || 'Unknown error');
        }

        updateTestimonials(testimonials.find(t => t.id === itemToSave.id)
          ? testimonials.map(t => t.id === itemToSave.id ? itemToSave : t)
          : [...testimonials, itemToSave]
        );
      } else if (itemToSave.category !== undefined) {
        // Handle product save
        const configs: any = {};
        const sizes: string[] = [];
        
        tempPriceList.forEach((it: any) => {
          if (it.size) {
            sizes.push(it.size);
            configs[it.size] = {
              originalPrice: Number(it.config.originalPrice),
              discountValue: Number(it.config.discountValue),
              discountType: it.config.discountType,
              salePrice: it.config.discountType === 'percentage' 
                ? Math.max(0, Math.round(it.config.originalPrice - (it.config.originalPrice * (it.config.discountValue / 100))))
                : Math.max(0, it.config.originalPrice - it.config.discountValue),
              mainBalance: Number(it.config.mainBalance || 0),
              freeDelivery: it.config.freeDelivery || false
            };
          }
        });
        
        if (sizes.length > 0) {
          itemToSave.sizes = sizes;
          itemToSave.priceConfigs = configs;
          itemToSave.price = configs[sizes[0]].salePrice;
        }

        const isNew = itemToSave.id && String(itemToSave.id).startsWith('P-');
        const payloadId = isNew ? undefined : itemToSave.id;
        const method = isNew ? 'POST' : 'PUT';
        const url = isNew ? '/api/admin/products' : `/api/admin/products/${itemToSave.id}`;

        const productData = { ...itemToSave, id: payloadId };

        const response = await fetch(url, {
          method,
          headers: getTenantHeaders({ 'Accept': 'application/json' }),
          body: JSON.stringify(productData)
        });

        if (!response.ok) {
          throw new Error('Failed to save product');
        }

        const data = await response.json();

        if (!data.success) {
          throw new Error(data.error || 'Unknown error');
        }
        
        const savedProduct = data.data || { ...itemToSave, id: data.id || itemToSave.id };
        
        if (isNew) {
           updateProducts([...products, savedProduct]);
        } else {
           updateProducts(products.map(p => p.id === itemToSave.id ? savedProduct : p));
        }
      }

      setEditingItem(null);
      showToast('Content Published!', 'success');

    } catch (err: any) {
      console.error('Save error:', err);
      showToast('Error: ' + err.message, 'error');
    } finally {
      setIsSaving(false);
    }
  };

  const deleteItem = async (table: string, id: string) => {
    let section = '';
    if (table === 'products') section = 'products';
    else if (table === 'testimonials') section = 'testimonials';
    else if (table === 'orders') section = 'orders';
    else if (table === 'leads') section = 'leads';

    if (!canAccess(section, 'delete')) {
      showToast('You do not have permission to delete this item', 'error');
      return;
    }

    try {
      let url = '';
      if (table === 'products') url = `/api/admin/products/${id}`;
      else if (table === 'testimonials') url = `/api/admin/testimonials/${id}`;
      else if (table === 'orders') url = `/api/admin/orders/${id}`;
      else if (table === 'leads') url = `/api/admin/leads/${encodeURIComponent(id)}`;

      const response = await fetch(url, {
        method: 'DELETE',
        headers: getTenantHeaders(),
      });

      if (!response.ok) {
        throw new Error('Failed to delete');
      }

      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || 'Unknown error');
      }

      if (table === 'products') updateProducts(products.filter(p => p.id !== id));
      if (table === 'testimonials') updateTestimonials(testimonials.filter(t => t.id !== id));
      if (table === 'orders') updateOrders(orders.filter(o => o.id !== id));
      if (table === 'leads') updateLeads(leads.filter((l: Lead) => l.phone !== id));

      showToast('Deleted successfully!', 'success');
    } catch (err: any) {
      showToast(err.message, 'error');
    }
  };


  const scrollToSection = (id: string) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth' });
  };

  const filteredOrders = orders.filter(o => {
    const orderDate = new Date(o.date);
    const isValidDate = !isNaN(orderDate.getTime());

    const inStartDate = (orderStartDate && isValidDate) ? orderDate >= new Date(orderStartDate) : true;
    const inEndDate = (orderEndDate && isValidDate) ? orderDate <= new Date(orderEndDate + 'T23:59:59') : true;
    const inStatus = orderStatusFilter === 'all' ? true : o.status === orderStatusFilter;

    return inStartDate && inEndDate && inStatus;
  });

  const sortedOrders = getSortedOrders(filteredOrders);

  const filteredLeads = uniqueLeads.filter((lead: Lead) => {
    const phone = lead.phone?.replace(/\D/g, '');
    if (!phone || phone.length !== 11) return false;

    const inStatus = leadStatusFilter === 'all' ? true : lead.status === leadStatusFilter;
    const inSearch = leadSearch === '' ? true :
      (lead.phone && lead.phone.includes(leadSearch)) ||
      ((lead.name || lead.customer_name || '') && (lead.name || lead.customer_name || '').toLowerCase().includes(leadSearch.toLowerCase()));

    return inStatus && inSearch;
  });

  const sortedLeads: Lead[] = getSortedLeads(filteredLeads as Lead[]);

  const totalOrders = orders.length;
  const totalLeads = uniqueLeads.length;
  const totalInitiatedCheckouts = orders.filter(o => o.status === 'Lead' || o.status === 'Lead - In Progress').length;

  const totalLeadValue = (uniqueLeads.reduce((acc: number, lead: Lead) => {
    return acc + (lead.product || lead.product_context ? 1 : 0);
  }, 0) as number) * 500;

  const totalOrderValue = orders.reduce((acc: number, o: Order) => acc + Number(o.total || 0), 0);
  const confirmedOrderValue = orders.filter(o => (o.status as string) === 'Confirmed Order' || (o.status as string) === 'completed')
    .reduce((acc: number, o: Order) => acc + Number(o.total || 0), 0);

  // ── Financial Breakdown Calculations ──────────────────────────────────────────

  const orderGrowth = totalOrders > 0 ? 23.5 : 0;
  const leadGrowth = totalLeads > 0 ? 45.2 : 0;
  const revenueGrowth = totalOrderValue > 0 ? 18.7 : 0;

  const activeTheme = editingItem?.landingTheme || 'primary';
  const themeSections: Record<string, string[]> = {
    'primary': ['sec-theme', 'sec-hero', 'sec-features', 'sec-tips', 'sec-packages', 'sec-faq', 'sec-problem', 'sec-solution', 'sec-benefits-title', 'sec-why-us', 'sec-authority', 'sec-guarantee', 'sec-process', 'sec-cta'],
    '01': ['sec-theme', 'sec-hero', 'sec-benefits-title', 'sec-features', 'sec-problem', 'sec-why-us', 'sec-authority', 'sec-reviews', 'sec-faq', 'sec-packages', 'sec-cta'],
    '02': ['sec-theme', 'sec-hero', 'sec-problem', 'sec-why-us', 'sec-benefits-title', 'sec-features', 'sec-reviews', 'sec-offer', 'sec-packages', 'sec-trust', 'sec-faq', 'sec-cta'],
    '03': ['sec-theme', 'sec-hero', 'sec-problem', 'sec-solution', 'sec-benefits-title', 'sec-features', 'sec-reviews', 'sec-offer', 'sec-packages', 'sec-trust', 'sec-faq', 'sec-cta'],
    '04': ['sec-theme', 'sec-hero', 'sec-problem', 'sec-solution', 'sec-benefits-title', 'sec-features', 'sec-reviews', 'sec-offer', 'sec-packages', 'sec-trust', 'sec-faq', 'sec-cta'],
    '05': ['sec-theme', 'sec-hero', 'sec-problem', 'sec-solution', 'sec-benefits-title', 'sec-features', 'sec-reviews', 'sec-offer', 'sec-packages', 'sec-trust', 'sec-faq', 'sec-cta'],
    '06': ['sec-theme', 'sec-hero', 'sec-problem', 'sec-solution', 'sec-benefits-title', 'sec-features', 'sec-reviews', 'sec-offer', 'sec-packages', 'sec-trust', 'sec-faq', 'sec-cta'],
  };
  const showSection = (secId: string) => (themeSections[activeTheme] || themeSections['primary']).includes(secId);

  // =====================================================
  // RENDER
  // =====================================================
  // ── Mobile tab config (bottom nav) ─────────────────────────────
  const mobileTabs = [
    { id: 'dashboard', label: 'Overview', icon: <LayoutDashboard size={20} /> },
    { id: 'orders', label: 'Orders', icon: <ClipboardList size={20} />, badge: orders.filter(o => o.status === 'pending').length },
    { id: 'products', label: 'Products', icon: <ShoppingBag size={20} /> },
    { id: 'home-editor', label: 'Design', icon: <Palette size={20} /> },
    { id: 'appearance', label: 'Settings', icon: <Settings size={20} /> },
  ];

  const [mobileDrawerOpen, setMobileDrawerOpen] = useState(false);
  // Auto-close drawer when tab changes
  useEffect(() => { setMobileDrawerOpen(false); }, [activeTab]);

  const mobileTabLabel = mobileTabs.find(t => t.id === activeTab)?.label
    || activeTab.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());

  return (
    <div className="h-screen bg-slate-50 dark:bg-slate-950 flex flex-col md:flex-row font-sans overflow-hidden relative">
      {/* Notification Toast */}
      {showNotification && notification && (
        <div className={`fixed top-4 left-1/2 -translate-x-1/2 md:top-6 md:right-6 md:left-auto md:translate-x-0 z-[9999] px-5 py-3 rounded-2xl shadow-2xl text-sm font-bold max-w-[90vw] ${notification.type === 'success' ? 'bg-green-600 text-white' : 'bg-red-600 text-white'}`}>
          <div className="flex items-center gap-2">
            {notification.type === 'success' ? <CheckCircle size={16} /> : <AlertCircle size={16} />}
            <span>{notification.message}</span>
          </div>
        </div>
      )}

      {/* ── MOBILE TOP HEADER (md:hidden) ─────────────────────── */}
      <header
        className="md:hidden flex items-center justify-between px-4 py-3 z-[100] shrink-0"
        style={{ background: 'linear-gradient(135deg, #0d0b18, #13111f)', borderBottom: '1px solid rgba(139,92,246,0.2)' }}
      >
        {/* Hamburger button */}
        <button
          onClick={() => setMobileDrawerOpen(true)}
          className="w-9 h-9 rounded-xl flex items-center justify-center active:scale-95 transition-all"
          style={{ background: 'rgba(139,92,246,0.15)', border: '1px solid rgba(139,92,246,0.25)' }}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#c4b5fd" strokeWidth="2.5" strokeLinecap="round">
            <line x1="3" y1="6" x2="21" y2="6" /><line x1="3" y1="12" x2="21" y2="12" /><line x1="3" y1="18" x2="21" y2="18" />
          </svg>
        </button>

        <div className="flex items-center gap-2">
          <div
            className="w-7 h-7 rounded-lg flex items-center justify-center shrink-0"
            style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', boxShadow: '0 0 12px rgba(124,58,237,0.45)' }}
          >
            <Package size={13} className="text-white" />
          </div>
          <div>
            <p className="text-[13px] font-black text-white leading-none">shophyfast</p>
            <p className="text-[9px] font-medium mt-0.5" style={{ color: '#9f7aea' }}>{mobileTabLabel}</p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          {currentUser && (
            <div
              className="w-7 h-7 rounded-lg flex items-center justify-center text-white font-black text-xs shrink-0"
              style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}
            >
              {(currentUser.name || currentUser.email || 'A')[0].toUpperCase()}
            </div>
          )}
          <button
            onClick={onLogout}
            className="w-8 h-8 rounded-xl flex items-center justify-center active:opacity-60 transition-opacity"
            style={{ background: 'rgba(239,68,68,0.15)' }}
          >
            <LogOut size={14} className="text-red-400" />
          </button>
        </div>
      </header>

      {/* ── MOBILE DRAWER (slide-in sidebar) ─────────────────────── */}
      {/* Backdrop */}
      {mobileDrawerOpen && (
        <div
          className="fixed inset-0 z-[200] bg-black/60 md:hidden"
          style={{ backdropFilter: 'blur(2px)' }}
          onClick={() => setMobileDrawerOpen(false)}
        />
      )}
      {/* Drawer panel */}
      <div
        className="fixed top-0 left-0 h-full z-[201] md:hidden flex flex-col overflow-hidden transition-transform duration-300"
        style={{
          width: 280,
          background: 'linear-gradient(160deg, #0d0b18 0%, #13111f 35%, #0f0d1e 70%, #0a0814 100%)',
          borderRight: '1px solid rgba(139,92,246,0.2)',
          transform: mobileDrawerOpen ? 'translateX(0)' : 'translateX(-100%)',
          boxShadow: mobileDrawerOpen ? '8px 0 40px rgba(0,0,0,0.6)' : 'none',
        }}
      >
        {/* Drawer header */}
        <div className="px-5 pt-5 pb-4 flex items-center justify-between" style={{ borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', boxShadow: '0 0 18px rgba(124,58,237,0.5)' }}>
              <Package size={18} className="text-white" />
            </div>
            <div>
              <h1 className="text-[15px] font-black text-white leading-none">shophyfast</h1>
              <p className="text-[10px] font-medium mt-0.5" style={{ color: '#9f7aea' }}>Admin Panel</p>
            </div>
          </div>
          <button onClick={() => setMobileDrawerOpen(false)}
            className="w-8 h-8 rounded-xl flex items-center justify-center"
            style={{ background: 'rgba(255,255,255,0.06)' }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#9f7aea" strokeWidth="2.5" strokeLinecap="round">
              <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
            </svg>
          </button>
        </div>
        {/* User info */}
        {currentUser && (
          <div className="px-4 py-3" style={{ borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
            <div className="flex items-center gap-3 px-3 py-3 rounded-xl" style={{ background: 'rgba(139,92,246,0.08)', border: '1px solid rgba(139,92,246,0.15)' }}>
              <div className="w-8 h-8 rounded-lg flex items-center justify-center text-slate-800 dark:text-white font-black text-sm" style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}>
                {(currentUser.name || currentUser.email || 'A')[0].toUpperCase()}
              </div>
              <div className="min-w-0">
                <p className="font-bold text-xs text-slate-800 dark:text-white truncate">{currentUser.name || currentUser.email}</p>
                <span className="text-[9px] uppercase font-black px-1.5 py-0.5 rounded-md" style={{ background: 'rgba(139,92,246,0.2)', color: '#c4b5fd' }}>{currentUser.role}</span>
              </div>
            </div>
          </div>
        )}
        {/* Drawer Nav — same items as desktop sidebar */}
        <nav className="flex-grow px-3 py-3 overflow-y-auto space-y-0.5" style={{ scrollbarWidth: 'none' }}>
          <p className="px-3 pt-1 pb-2 text-[9px] font-black uppercase tracking-[0.18em]" style={{ color: '#f59e0b' }}>Main</p>
          <NavItem active={activeTab === 'dashboard'} onClick={() => canAccess('dashboard') ? setActiveTab('dashboard') : showToast('Access denied', 'error')} icon={<LayoutDashboard size={17} />} label="Overview" disabled={!canAccess('dashboard')} />
          <NavItem active={activeTab === 'orders'} onClick={() => { if (!canAccess('orders')) return showToast('Access denied', 'error'); if (!hasPlanAccess('orders')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('orders'); }} icon={<ClipboardList size={17} />} label={!hasPlanAccess('orders') ? 'Orders 🔒' : 'Orders'} count={orders.filter(o => o.status === 'pending').length} disabled={!canAccess('orders')} />
          <NavItem active={activeTab === 'leads'} onClick={() => { if (!canAccess('leads')) return showToast('Access denied', 'error'); if (!hasPlanAccess('leads')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('leads'); }} icon={<Users size={17} />} label={!hasPlanAccess('leads') ? 'Incomplete Orders 🔒' : 'Incomplete Orders'} count={uniqueLeads.length} disabled={!canAccess('leads')} />
          <p className="px-4 pt-5 pb-2 text-[9px] font-black uppercase text-slate-500 dark:text-slate-400">Inventory & Content</p>
          <NavItem active={activeTab === 'pos'} onClick={() => { if (!hasPlanAccess('products')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('pos'); }} icon={<span className="text-base">🏪</span>} label="POS" />
          <NavItem active={activeTab === 'products'} onClick={() => { if (!canAccess('products')) return showToast('Access denied', 'error'); if (!hasPlanAccess('products')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('products'); }} icon={<ShoppingBag size={17} />} label={!hasPlanAccess('products') ? 'Products 🔒' : 'Products'} disabled={!canAccess('products')} />
          <NavItem active={activeTab === 'categories'} onClick={() => { if (!canAccess('products')) return showToast('Access denied', 'error'); if (!hasPlanAccess('categories')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('categories'); }} icon={<ListTree size={17} />} label={!hasPlanAccess('categories') ? 'Categories 🔒' : 'Categories'} disabled={!canAccess('products')} />
          <NavItem active={activeTab === 'reviews'} onClick={() => { if (!canAccess('testimonials')) return showToast('Access denied', 'error'); if (!hasPlanAccess('reviews')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('reviews'); }} icon={<MessageSquare size={17} />} label={!hasPlanAccess('reviews') ? 'Testimonials 🔒' : 'Testimonials'} disabled={!canAccess('testimonials')} />
          <p className="px-4 pt-5 pb-2 text-[9px] font-black uppercase text-slate-500 dark:text-slate-400">Content Management</p>
          <NavItem active={activeTab === 'pages'} onClick={() => canAccess('pages') ? setActiveTab('pages') : showToast('Access denied', 'error')} icon={<FileText size={17} />} label="Custom Pages" disabled={!canAccess('pages')} />
          <p className="px-4 pt-5 pb-2 text-[9px] font-black uppercase text-slate-500 dark:text-slate-400">Design & Layout</p>
          <NavItem active={activeTab === 'home-editor'} onClick={() => { if (!canAccess('landing-editor')) return showToast('Access denied', 'error'); if (!hasPlanAccess('home-editor')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('home-editor'); }} icon={<Layers size={17} />} label={!hasPlanAccess('home-editor') ? 'Home Page Editor 🔒' : 'Home Page Editor'} disabled={!canAccess('landing-editor')} />
          <NavItem active={activeTab === 'landing-editor'} onClick={() => { if (!canAccess('landing-editor')) return showToast('Access denied', 'error'); if (!hasPlanAccess('landing-editor')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('landing-editor'); }} icon={<Layers size={17} />} label={!hasPlanAccess('landing-editor') ? 'Landing Page Editor 🔒' : 'Landing Page Editor'} disabled={!canAccess('landing-editor')} />
          <NavItem active={activeTab === 'appearance'} onClick={() => canAccess('appearance') ? setActiveTab('appearance') : showToast('Access denied', 'error')} icon={<LucideImage size={17} />} label="Branding & Appearance" disabled={!canAccess('appearance')} />
          <p className="px-4 pt-5 pb-2 text-[9px] font-black uppercase text-slate-500 dark:text-slate-400">Subscription</p>
          <NavItem active={activeTab === 'my-plan'} onClick={() => setActiveTab('my-plan')} icon={<span className="text-base">📦</span>} label="My Plan" />
          <NavItem active={activeTab === 'domain'} onClick={() => setActiveTab('domain')} icon={<span className="text-base">🌐</span>} label="Domain Name" />
          <p className="px-4 pt-5 pb-2 text-[9px] font-black uppercase text-slate-500 dark:text-slate-400">Courier Service</p>
          <NavItem active={activeTab === 'courier-settings'} onClick={() => { if (!canAccess('appearance')) return showToast('Access denied', 'error'); if (!hasPlanAccess('courier-settings')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('courier-settings'); }} icon={<Truck size={17} />} label={!hasPlanAccess('courier-settings') ? 'SteadFast Settings 🔒' : 'SteadFast Settings'} disabled={!canAccess('appearance')} />
          <NavItem active={activeTab === 'delivery-locations'} onClick={() => { if (!canAccess('appearance')) return showToast('Access denied', 'error'); if (!hasPlanAccess('delivery-locations')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('delivery-locations'); }} icon={<MapPin size={17} />} label={!hasPlanAccess('delivery-locations') ? 'Delivery Locations 🔒' : 'Delivery Locations'} disabled={!canAccess('appearance')} />
          <p className="px-4 pt-5 pb-2 text-[9px] font-black uppercase text-slate-500 dark:text-slate-400">Inventory</p>
          <NavItem active={activeTab === 'stock'} onClick={() => { if (!hasPlanAccess('stock')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('stock'); }} icon={<Package size={17} />} label={!hasPlanAccess('stock') ? 'Stock 🔒' : 'Stock'} count={products.filter(p => (p.stock ?? 0) < (p.lowStockThreshold ?? 20)).length || undefined} />
          <p className="px-4 pt-5 pb-2 text-[9px] font-black uppercase text-slate-500 dark:text-slate-400">Settings</p>
          <NavItem active={activeTab === 'contact'} onClick={() => canAccess('contact') ? setActiveTab('contact') : showToast('Access denied', 'error')} icon={<Phone size={17} />} label="Contact Info" disabled={!canAccess('contact')} />
          <NavItem active={activeTab === 'social'} onClick={() => canAccess('social') ? setActiveTab('social') : showToast('Access denied', 'error')} icon={<Share2 size={17} />} label="Social Media" disabled={!canAccess('social')} />
          <NavItem active={activeTab === 'pixel'} onClick={() => canAccess('pixel') ? setActiveTab('pixel') : showToast('Access denied', 'error')} icon={<Code size={17} />} label="GTM Settings" disabled={!canAccess('pixel')} />
          <p className="px-4 pt-5 pb-2 text-[9px] font-black uppercase text-slate-500 dark:text-slate-400">Marketing & Sales</p>
          <NavItem active={activeTab === 'marketing'} onClick={() => { if (!hasPlanAccess('marketing')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('marketing'); }} icon={<Gift size={17} />} label={!hasPlanAccess('marketing') ? 'Marketing 🔒' : 'Marketing'} />
          <NavItem active={activeTab === 'messenger-ai'} onClick={() => { if (!hasPlanAccess('messenger-ai')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('messenger-ai'); }} icon={<MessageSquare size={17} />} label={!hasPlanAccess('messenger-ai') ? 'Messenger AI Agent 🔒' : 'Messenger AI Agent'} />
          <NavItem active={activeTab === 'facebook-ads'} onClick={() => { if (!hasPlanAccess('marketing')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('facebook-ads'); }} icon={<Facebook size={17} />} label="Facebook Ads" />
          <NavItem active={activeTab === 'ubaidi-ads-marketer'} onClick={() => { if (!hasPlanAccess('ubaidi_ads_marketer')) return showToast('🔒 Plan upgrade করুন।', 'error'); setActiveTab('ubaidi-ads-marketer'); }} icon={<Infinity size={17} />} label={!hasPlanAccess('ubaidi_ads_marketer') ? 'Ubaidi Ads Marketer 🔒' : 'Ubaidi Ads Marketer'} />
          {currentUser?.role === 'admin' && (
            <><div className="my-3 border-t border-slate-800" />
              <NavItem active={activeTab === 'moderators'} onClick={() => setActiveTab('moderators')} icon={<Shield size={17} />} label="Moderators" /></>)}
        </nav>
        {/* Drawer logout */}
        <div className="p-4" style={{ borderTop: '1px solid rgba(255,255,255,0.06)' }}>
          <button onClick={onLogout} className="w-full flex items-center gap-3 px-4 py-3.5 text-slate-500 dark:text-slate-400 hover:text-red-400 font-black text-sm transition-colors rounded-2xl" style={{ background: 'rgba(239,68,68,0.08)' }}>
            <LogOut size={18} /> Logout
          </button>
        </div>
      </div>

      {/* ── DESKTOP SIDEBAR (hidden on mobile) ─────────────────── */}
      <aside
        className="hidden md:flex w-64 md:h-screen flex-col z-[100] overflow-hidden"
        style={{ background: 'linear-gradient(160deg, #0d0b18 0%, #13111f 35%, #0f0d1e 70%, #0a0814 100%)', borderRight: '1px solid rgba(139,92,246,0.15)' }}
      >
        {/* Logo / Brand */}
        <div className="px-5 pt-6 pb-5" style={{ borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
          <div className="flex items-center gap-3 mb-5">
            <div
              className="w-9 h-9 rounded-xl flex items-center justify-center shadow-xl shrink-0"
              style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', boxShadow: '0 0 20px rgba(124,58,237,0.5)' }}
            >
              <Package size={18} className="text-white" />
            </div>
            <div>
              <h1 className="text-[15px] font-black text-white tracking-tight leading-none">shophyfast</h1>
              <p className="text-[10px] font-medium mt-0.5" style={{ color: '#9f7aea' }}>Admin Panel</p>
            </div>
          </div>
          {currentUser && (
            <div
              className="flex items-center gap-3 px-3 py-3 rounded-xl"
              style={{ background: 'rgba(139,92,246,0.08)', border: '1px solid rgba(139,92,246,0.15)' }}
            >
              <div
                className="w-8 h-8 rounded-lg flex items-center justify-center text-white font-black text-sm shrink-0"
                style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}
              >
                {(currentUser.name || currentUser.email || 'A')[0].toUpperCase()}
              </div>
              <div className="min-w-0">
                <p className="font-bold text-xs text-white truncate">{currentUser.name || currentUser.email}</p>
                <span
                  className="text-[9px] uppercase font-black px-1.5 py-0.5 rounded-md"
                  style={{ background: 'rgba(139,92,246,0.2)', color: '#c4b5fd' }}
                >
                  {currentUser.role}
                </span>
              </div>
            </div>
          )}
        </div>

        {/* Navigation */}
        <nav className="flex-grow px-3 py-3 overflow-y-auto space-y-0.5" style={{ scrollbarWidth: 'none' }}>
          {/* Section: Main */}
          <p className="px-3 pt-1 pb-2 text-[9px] font-black uppercase tracking-[0.18em]" style={{ color: '#f59e0b' }}>Main</p>
          <NavItem
            active={activeTab === 'dashboard'}
            onClick={() => canAccess('dashboard') ? setActiveTab('dashboard') : showToast('Access denied', 'error')}
            icon={<LayoutDashboard size={17} />}
            label="Overview"
            disabled={!canAccess('dashboard')}
          />

          <NavItem
            active={activeTab === 'orders'}
            onClick={() => {
              if (!canAccess('orders')) return showToast('Access denied', 'error');
              if (!hasPlanAccess('orders')) return showToast('🔒 আপনার plan-এ Orders feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('orders');
            }}
            icon={<ClipboardList size={20} />}
            label={!hasPlanAccess('orders') ? 'Orders 🔒' : 'Orders'}
            count={orders.filter(o => o.status === 'pending').length}
            disabled={!canAccess('orders')}
          />

          <NavItem
            active={activeTab === 'leads'}
            onClick={() => {
              if (!canAccess('leads')) return showToast('Access denied', 'error');
              if (!hasPlanAccess('leads')) return showToast('🔒 আপনার plan-এ Leads feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('leads');
            }}
            icon={<Users size={20} />}
            label={!hasPlanAccess('leads') ? 'Incomplete Orders 🔒' : 'Incomplete Orders'}
            count={uniqueLeads.length}
            disabled={!canAccess('leads')}
          />

          <p className="px-4 pt-6 pb-2 text-[10px] font-black uppercase text-slate-500 dark:text-slate-400">Inventory & Content</p>

          <NavItem
            active={activeTab === 'pos'}
            onClick={() => {
              if (!hasPlanAccess('products')) return showToast('🔒 Plan upgrade করুন।', 'error');
              setActiveTab('pos');
              setMobileDrawerOpen(false);
            }}
            icon={<span className="text-xl">🏪</span>}
            label="POS — Point of Sale"
          />


          <NavItem
            active={activeTab === 'products'}
            onClick={() => {
              if (!canAccess('products')) return showToast('Access denied', 'error');
              if (!hasPlanAccess('products')) return showToast('🔒 আপনার plan-এ Products feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('products');
            }}
            icon={<ShoppingBag size={20} />}
            label={!hasPlanAccess('products') ? 'Products 🔒' : 'Products'}
            disabled={!canAccess('products')}
          />

          <NavItem
            active={activeTab === 'categories'}
            onClick={() => {
              if (!canAccess('products')) return showToast('Access denied', 'error');
              if (!hasPlanAccess('categories')) return showToast('🔒 আপনার plan-এ Categories feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('categories');
            }}
            icon={<ListTree size={20} />}
            label={!hasPlanAccess('categories') ? 'Categories 🔒' : 'Categories'}
            disabled={!canAccess('products')}
          />

          <NavItem
            active={activeTab === 'reviews'}
            onClick={() => {
              if (!canAccess('testimonials')) return showToast('Access denied', 'error');
              if (!hasPlanAccess('reviews')) return showToast('🔒 আপনার plan-এ Reviews feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('reviews');
            }}
            icon={<MessageSquare size={20} />}
            label={!hasPlanAccess('reviews') ? 'Testimonials 🔒' : 'Testimonials'}
            disabled={!canAccess('testimonials')}
          />

          <p className="px-4 pt-6 pb-2 text-[10px] font-black uppercase text-slate-500 dark:text-slate-400">Content Management</p>

          <NavItem
            active={activeTab === 'pages'}
            onClick={() => canAccess('pages') ? setActiveTab('pages') : showToast('Access denied', 'error')}
            icon={<FileText size={20} />}
            label="Custom Pages"
            disabled={!canAccess('pages')}
          />

          <p className="px-4 pt-6 pb-2 text-[10px] font-black uppercase text-slate-500 dark:text-slate-400">Design & Layout</p>

          <NavItem
            active={activeTab === 'home-editor'}
            onClick={() => {
              if (!canAccess('landing-editor')) return showToast('Access denied', 'error');
              if (!hasPlanAccess('home-editor')) return showToast('🔒 আপনার plan-এ Home Editor নেই। Plan upgrade করুন।', 'error');
              setActiveTab('home-editor');
            }}
            icon={<Layers size={20} />}
            label={!hasPlanAccess('home-editor') ? 'Home Page Editor 🔒' : 'Home Page Editor'}
            disabled={!canAccess('landing-editor')}
          />

          <NavItem
            active={activeTab === 'landing-editor'}
            onClick={() => {
              if (!canAccess('landing-editor')) return showToast('Access denied', 'error');
              if (!hasPlanAccess('landing-editor')) return showToast('🔒 আপনার plan-এ Landing Editor নেই। Plan upgrade করুন।', 'error');
              setActiveTab('landing-editor');
            }}
            icon={<Layers size={20} />}
            label={!hasPlanAccess('landing-editor') ? 'Landing Page Editor 🔒' : 'Landing Page Editor'}
            disabled={!canAccess('landing-editor')}
          />

          <NavItem
            active={activeTab === 'appearance'}
            onClick={() => canAccess('appearance') ? setActiveTab('appearance') : showToast('Access denied', 'error')}
            icon={<LucideImage size={20} />}
            label="Branding & Appearance"
            disabled={!canAccess('appearance')}
          />

          {/* ── Subscription Plan ── */}
          <p className="px-4 pt-6 pb-2 text-[10px] font-black uppercase text-slate-500 dark:text-slate-400">Subscription</p>
          <NavItem
            active={activeTab === 'my-plan'}
            onClick={() => setActiveTab('my-plan')}
            icon={<span className="text-base">📦</span>}
            label="My Plan"
          />
          <NavItem
            active={activeTab === 'domain'}
            onClick={() => setActiveTab('domain')}
            icon={<span className="text-base">🌐</span>}
            label="Domain Name"
          />


          <p className="px-4 pt-6 pb-2 text-[10px] font-black uppercase text-slate-500 dark:text-slate-400">Courier Service</p>

          <NavItem
            active={activeTab === 'courier-settings'}
            onClick={() => {
              if (!canAccess('appearance')) return showToast('Access denied', 'error');
              if (!hasPlanAccess('courier-settings')) return showToast('🔒 আপনার plan-এ Courier feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('courier-settings');
            }}
            icon={<Truck size={20} />}
            label={!hasPlanAccess('courier-settings') ? 'SteadFast Settings 🔒' : 'SteadFast Settings'}
            disabled={!canAccess('appearance')}
          />

          {/* ✅ Delivery Locations */}
          <NavItem
            active={activeTab === 'delivery-locations'}
            onClick={() => {
              if (!canAccess('appearance')) return showToast('Access denied', 'error');
              if (!hasPlanAccess('delivery-locations')) return showToast('🔒 আপনার plan-এ Delivery Locations feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('delivery-locations');
            }}
            icon={<MapPin size={20} />}
            label={!hasPlanAccess('delivery-locations') ? 'Delivery Locations 🔒' : 'Delivery Locations'}
            disabled={!canAccess('appearance')}
          />

          <p className="px-4 pt-6 pb-2 text-[10px] font-black uppercase text-slate-500 dark:text-slate-400">Inventory</p>

          <NavItem
            active={activeTab === 'stock'}
            onClick={() => {
              if (!hasPlanAccess('stock')) return showToast('🔒 আপনার plan-এ Stock feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('stock');
            }}
            icon={<Package size={20} />}
            label={!hasPlanAccess('stock') ? 'Stock 🔒' : 'Stock'}
            count={products.filter(p => (p.stock ?? 0) < (p.lowStockThreshold ?? 20)).length || undefined}
          />

          <p className="px-4 pt-6 pb-2 text-[10px] font-black uppercase text-slate-500 dark:text-slate-400">Settings</p>

          <NavItem
            active={activeTab === 'contact'}
            onClick={() => canAccess('contact') ? setActiveTab('contact') : showToast('Access denied', 'error')}
            icon={<Phone size={20} />}
            label="Contact Info"
            disabled={!canAccess('contact')}
          />

          <NavItem
            active={activeTab === 'social'}
            onClick={() => canAccess('social') ? setActiveTab('social') : showToast('Access denied', 'error')}
            icon={<Share2 size={20} />}
            label="Social Media"
            disabled={!canAccess('social')}
          />

          <NavItem
            active={activeTab === 'pixel'}
            onClick={() => canAccess('pixel') ? setActiveTab('pixel') : showToast('Access denied', 'error')}
            icon={<Code size={20} />}
            label="GTM Settings"
            disabled={!canAccess('pixel')}
          />

          <p className="px-4 pt-6 pb-2 text-[10px] font-black uppercase text-slate-500 dark:text-slate-400">Marketing & Sales</p>

          <NavItem
            active={activeTab === 'marketing'}
            onClick={() => {
              if (!hasPlanAccess('marketing')) return showToast('🔒 আপনার plan-এ Marketing feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('marketing');
            }}
            icon={<Gift size={20} />}
            label={!hasPlanAccess('marketing') ? 'Marketing 🔒' : 'Marketing'}
          />

          <NavItem
            active={activeTab === 'messenger-ai'}
            onClick={() => {
              if (!hasPlanAccess('messenger-ai')) return showToast('🔒 আপনার plan-এ Messenger AI feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('messenger-ai');
            }}
            icon={<MessageSquare size={20} />}
            label={!hasPlanAccess('messenger-ai') ? 'Messenger AI Agent 🔒' : 'Messenger AI Agent'}
          />

          <NavItem
            active={activeTab === 'facebook-ads'}
            onClick={() => {
              if (!hasPlanAccess('marketing')) return showToast('🔒 আপনার plan-এ Marketing feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('facebook-ads');
            }}
            icon={<Facebook size={20} />}
            label="Facebook Ads"
          />

          <NavItem
            active={activeTab === 'ubaidi-ads-marketer'}
            onClick={() => {
              if (!hasPlanAccess('ubaidi_ads_marketer')) return showToast('🔒 আপনার plan-এ Ubaidi Ads Marketer feature নেই। Plan upgrade করুন।', 'error');
              setActiveTab('ubaidi-ads-marketer');
            }}
            icon={<Infinity size={20} />}
            label={!hasPlanAccess('ubaidi_ads_marketer') ? 'Ubaidi Ads Marketer 🔒' : 'Ubaidi Ads Marketer'}
          />

          {currentUser?.role === 'admin' && (
            <>
              <div className="my-4 border-t border-slate-200 dark:border-slate-700"></div>
              <NavItem
                active={activeTab === 'moderators'}
                onClick={() => setActiveTab('moderators')}
                icon={<Shield size={20} />}
                label="Moderators"
              />
            </>
          )}
        </nav>
        <div className="p-6 border-t dark:border-slate-800">
          <button onClick={onLogout} className="w-full flex items-center gap-3 px-4 py-4 text-slate-500 dark:text-slate-400 hover:text-red-600 font-black transition-colors rounded-xl">
            <LogOut size={20} /> Logout
          </button>
        </div>
      </aside>

      {/* Main Content */}
      <main className="flex-grow h-screen overflow-y-auto custom-scrollbar relative">
        <div className="admin-main-inner max-w-[1600px] mx-auto p-4 md:p-10 transition-all duration-300 relative z-10 w-full">

          {/* ✅ Free Trial Banner */}
          {tenantSubscriptionStatus === 'trial' && trialDaysRemaining !== null && (
            <div style={{
              background: trialDaysRemaining <= 3
                ? 'linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%)'
                : 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              borderRadius: '16px',
              padding: '14px 20px',
              marginBottom: '20px',
              color: '#fff',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              flexWrap: 'wrap' as const,
              gap: '10px',
              boxShadow: '0 4px 20px rgba(102,126,234,0.25)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                <span style={{ fontSize: '26px' }}>🎯</span>
                <div>
                  <div style={{ fontWeight: 800, fontSize: '15px' }}>
                    Free Trial মোড — <strong>{trialDaysRemaining}</strong> দিন বাকি
                  </div>
                  <div style={{ fontSize: '12px', opacity: 0.85 }}>
                    সব features এখন unlocked আছে। Trial শেষে subscribe করুন।
                  </div>
                </div>
              </div>
              <button onClick={() => setActiveTab('my-plan')} style={{
                background: 'rgba(255,255,255,0.22)',
                border: '1.5px solid rgba(255,255,255,0.5)',
                color: '#fff',
                borderRadius: '10px',
                padding: '8px 18px',
                fontWeight: 700,
                fontSize: '13px',
                cursor: 'pointer',
              }}>
                Plan দেখুন →
              </button>
            </div>
          )}

          {/* ✅ Trial Expired Banner */}
          {(tenantSubscriptionStatus === 'trial_expired') && (
            <div style={{
              background: 'linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%)',
              borderRadius: '16px',
              padding: '14px 20px',
              marginBottom: '20px',
              color: '#fff',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              flexWrap: 'wrap' as const,
              gap: '10px',
              boxShadow: '0 4px 20px rgba(238,90,36,0.3)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                <span style={{ fontSize: '26px' }}>⏰</span>
                <div>
                  <div style={{ fontWeight: 800, fontSize: '15px' }}>Free Trial শেষ হয়ে গেছে</div>
                  <div style={{ fontSize: '12px', opacity: 0.85 }}>Features অব্যাহত রাখতে এখনই subscribe করুন।</div>
                </div>
              </div>
              <button onClick={() => setActiveTab('my-plan')} style={{
                background: 'rgba(255,255,255,0.22)',
                border: '1.5px solid rgba(255,255,255,0.5)',
                color: '#fff',
                borderRadius: '10px',
                padding: '8px 18px',
                fontWeight: 700,
                fontSize: '13px',
                cursor: 'pointer',
              }}>
                এখনই Subscribe →
              </button>
            </div>
          )}

          {isLoading && (
            <div className="fixed inset-0 bg-white/50 flex items-center justify-center z-50">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-red-600"></div>
            </div>
          )}

          {activeTab === 'moderators' && currentUser?.role === 'admin' && (
            <ModeratorManagement />
          )}

          {activeTab === 'pos' && (
            <POSSystem
              products={products}
              settings={{
                siteName: settings.siteName || (settings as any).site_name,
                logo: settings.logo,
                phone: settings.phone,
                address: settings.address,
              }}
              showToast={showToast}
            />
          )}

          {activeTab === 'courier-settings' && canAccess('appearance') && (
            <CourierSettings settings={settings} />
          )}

          {activeTab === 'delivery-locations' && canAccess('appearance') && (
            <DeliveryLocationsEditor
              settings={settings}
              updateSettings={updateSettings}
              showToast={showToast}
            />
          )}

          {activeTab === 'messenger-ai' && (
            <MessengerAIAgentPanel
              settings={settings}
              products={products}
              showToast={showToast}
            />
          )}

          {activeTab === 'facebook-ads' && (
            <FacebookAdsPanel products={products} showToast={showToast} />
          )}

          {activeTab === 'ubaidi-ads-marketer' && (
            <UbaidiAdsMarketer showToast={showToast} />
          )}

          {activeTab === 'marketing' && (
            <MarketingManager
              settings={settings}
              updateSettings={updateSettings}
              isSaving={isSaving}
              saveSiteSettings={saveSiteSettings}
            />
          )}
          {editingItem ? (
            <div className="flex flex-col h-full animate-fade-in-up">
              <div className="sticky top-0 z-[60] mb-8 bg-white/95 dark:bg-slate-900/95 backdrop-blur-xl p-5 rounded-[32px] border border-slate-200 flex justify-between items-center shadow-xl">
                <button onClick={() => setEditingItem(null)} className="font-black text-[10px] uppercase flex items-center gap-2 px-4 py-2 bg-slate-100 dark:bg-slate-800 rounded-xl text-slate-500 hover:text-red-600 transition-all">
                  <ArrowLeft size={14} /> Close Editor
                </button>
                <div className="flex items-center gap-4">
                  {activeTab === 'landing-editor' && canAccess('landing-editor', 'edit') && (
                    <button onClick={() => setPreviewMode(!previewMode)} className={`px-6 py-2.5 rounded-2xl font-black text-[10px] uppercase flex items-center gap-2 transition-all ${previewMode ? 'bg-amber-100 text-amber-700 shadow-sm' : 'bg-slate-100 text-slate-500'}`}>
                      {previewMode ? <Edit3 size={14} /> : <Eye size={14} />} {previewMode ? 'Exit Preview' : 'Split Preview'}
                    </button>
                  )}
                  {canEditItem(editingItem) && (
                    <button onClick={saveContent} className="px-10 py-3.5 bg-red-600 text-white rounded-2xl font-black text-sm shadow-xl shadow-red-600/20 disabled:opacity-50 hover:bg-red-700 transition-all active:scale-95 flex items-center gap-2" disabled={isSaving}>
                      {isSaving ? 'Syncing...' : <><CheckCircle size={18} /> Publish Changes</>}
                    </button>
                  )}
                </div>
              </div>

              {activeTab === 'landing-editor' ? (
                <div className="grid grid-cols-1 xl:grid-cols-12 gap-10">
                  <div className="hidden xl:block xl:col-span-2">
                    <div className="sticky top-32 bg-white dark:bg-slate-900 p-6 rounded-[32px] border shadow-sm space-y-1">
                      <p className="text-[10px] font-black uppercase text-slate-500 dark:text-slate-400 mb-4 tracking-widest px-2">Page Structure</p>
                      {showSection('sec-hero') && <button onClick={() => scrollToSection('sec-hero')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Sparkles size={16} /> ০১. Hero Section</button>}
                      {showSection('sec-problem') && <button onClick={() => scrollToSection('sec-problem')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Flame size={16} /> ০২. Problem</button>}
                      {showSection('sec-solution') && <button onClick={() => scrollToSection('sec-solution')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Leaf size={16} /> ০৩. Solution</button>}
                      {showSection('sec-benefits-title') && <button onClick={() => scrollToSection('sec-benefits-title')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Sparkles size={16} /> ০৪. Benefits Title</button>}
                      {showSection('sec-features') && <button onClick={() => scrollToSection('sec-features')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Palette size={16} /> ০৫. Features/Benefits</button>}
                      {showSection('sec-reviews') && <button onClick={() => scrollToSection('sec-reviews')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Star size={16} /> ০৬. Social Proof</button>}
                      {showSection('sec-offer') && <button onClick={() => scrollToSection('sec-offer')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Zap size={16} /> ০৭. Offer/Pricing</button>}
                      {showSection('sec-packages') && <button onClick={() => scrollToSection('sec-packages')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <ShoppingCart size={16} /> ০৮. Packages</button>}
                      {showSection('sec-trust') && <button onClick={() => scrollToSection('sec-trust')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <ShieldCheck size={16} /> ০৯. Trust Elements</button>}
                      {showSection('sec-faq') && <button onClick={() => scrollToSection('sec-faq')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <HelpCircle size={16} /> ১০. FAQ</button>}
                      {showSection('sec-cta') && <button onClick={() => scrollToSection('sec-cta')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Target size={16} /> ১১. Final CTA</button>}
                      {showSection('sec-tips') && <button onClick={() => scrollToSection('sec-tips')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Utensils size={16} /> Tips</button>}
                      {showSection('sec-why-us') && <button onClick={() => scrollToSection('sec-why-us')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Shield size={16} /> Why Us</button>}
                      {showSection('sec-authority') && <button onClick={() => scrollToSection('sec-authority')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Award size={16} /> Authority</button>}
                      {showSection('sec-guarantee') && <button onClick={() => scrollToSection('sec-guarantee')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <ShieldCheck size={16} /> Guarantee</button>}
                      {showSection('sec-process') && <button onClick={() => scrollToSection('sec-process')} className="w-full text-left px-3 py-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 font-bold text-xs flex items-center gap-3 text-slate-500 hover:text-red-600 transition-all"> <Zap size={16} /> Process</button>}
                    </div>
                  </div>

                  <div className={`${previewMode ? 'xl:col-span-5' : 'xl:col-span-10'} space-y-12 pb-60`}>
                    <div id="sec-theme" className="mb-12 border-b-2 border-red-600/10 pb-12" style={{ display: showSection('sec-theme') ? 'block' : 'none' }}>
                      <SectionHeader icon={Palette} title="Display Theme" subtitle="Choose which landing page layout to show." color="red" />
                      <div className="space-y-6">
                        <FieldGroup label="Landing Page Theme">
                          <select
                            value={editingItem.landingTheme || 'primary'}
                            onChange={(e) => setEditingItem({ ...editingItem, landingTheme: e.target.value })}
                            className="w-full h-14 px-6 bg-slate-50 dark:bg-slate-800 rounded-2xl outline-none font-bold text-sm tracking-wide text-slate-700 dark:text-slate-200 font-bangla"
                            disabled={!canAccess('landing-editor', 'edit')}
                          >
                            <option value="primary">Primary (Default Red)</option>
                            <option value="01">Landing Page 01 (Minimal Apple-Style)</option>
                            <option value="02">Landing Page 02 (Dark Mode Elite)</option>
                            <option value="03">Landing Page 03</option>
                            <option value="04">Landing Page 04 (Golden Gradient)</option>
                            <option value="05">Landing Page 05</option>
                            <option value="06">Landing Page 06</option>
                          </select>
                        </FieldGroup>
                      </div>
                    </div>

                    <div id="sec-hero" style={{ display: showSection('sec-hero') ? 'block' : 'none' }}>
                      <SectionHeader icon={Sparkles} title="Hero Section" subtitle="Landing page entry point." color="red" />
                      <div className="space-y-6">
                        <FieldGroup label="Headline Title" help="HTML allowed.">
                          <Input
                            value={editingItem.landingTitle}
                            onChange={(v: any) => setEditingItem({ ...editingItem, landingTitle: v })}
                            disabled={!canAccess('landing-editor', 'edit')}
                          />
                        </FieldGroup>
                        <FieldGroup label="Persuasive Subtitle">
                          <textarea
                            value={editingItem.landingSubtitle || ''}
                            onChange={(e) => setEditingItem({ ...editingItem, landingSubtitle: e.target.value })}
                            className="w-full p-6 bg-slate-50 dark:bg-slate-800 rounded-3xl font-bangla min-h-[120px] focus:ring-2 focus:ring-red-600 font-bold"
                            disabled={!canAccess('landing-editor', 'edit')}
                          />
                        </FieldGroup>
                        <FieldGroup label="Hero Visual">
                          <div className="aspect-video bg-slate-100 rounded-2xl border-2 border-dashed flex flex-col items-center justify-center relative overflow-hidden group">
                            {editingItem.landingProductImage ? <img src={editingItem.landingProductImage} className="w-full h-full object-contain" /> : <ImageIcon size={48} className="text-slate-500 dark:text-slate-300" />}
                            {canAccess('landing-editor', 'edit') && (
                              <label className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 flex items-center justify-center cursor-pointer transition-opacity">
                                <span className="bg-white px-6 py-2 rounded-xl font-black text-xs">Upload Lifestyle Photo</span>
                                <input type="file" className="hidden" accept="image/*" onChange={(e) => handleFileUpload(e, 'landingProductImage')} />
                              </label>
                            )}
                          </div>
                        </FieldGroup>
                      </div>
                    </div>

                    <div id="sec-features" style={{ display: showSection('sec-features') ? 'block' : 'none' }}>
                      <SectionHeader icon={Palette} title="Core Features" subtitle="3 USPs of this product." color="amber" />
                      <div className="space-y-4">
                        {(editingItem.features || []).map((f: any, i: number) => (
                          <div key={i} className="bg-white p-8 rounded-[40px] border relative group">
                            <button onClick={() => setEditingItem({ ...editingItem, features: editingItem.features.filter((_: any, idx: any) => idx !== i) })} className="absolute top-6 right-6 text-red-400 opacity-0 group-hover:opacity-100 transition-all"><Trash2 size={16} /></button>
                            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                              <div className="space-y-4">
                                <Input label="Label" value={f.title} onChange={(v: any) => { let n = [...editingItem.features]; n[i].title = v; setEditingItem({ ...editingItem, features: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                              </div>
                              <textarea value={f.desc || ''} placeholder="Feature Description" onChange={(e) => { let n = [...editingItem.features]; n[i].desc = e.target.value; setEditingItem({ ...editingItem, features: n }) }} className="w-full p-4 bg-slate-50 rounded-2xl font-bangla text-xs font-bold" disabled={!canAccess('landing-editor', 'edit')} />
                            </div>
                          </div>
                        ))}
                        {canAccess('landing-editor', 'edit') && (
                          <button onClick={() => setEditingItem({ ...editingItem, features: [...(editingItem.features || []), { icon: 'sun', title: '', desc: '' }] })} className="w-full py-6 border-2 border-dashed rounded-[32px] text-slate-500 dark:text-slate-400 font-black">+ Add Feature</button>
                        )}
                      </div>
                    </div>

                    <div id="sec-tips" style={{ display: showSection('sec-tips') ? 'block' : 'none' }}>
                      <SectionHeader icon={Utensils} title="Usage Tips" color="green" />
                      <div className="space-y-6">
                        <FieldGroup label="Section Headline">
                          <Input value={editingItem.landingUsageTitle} onChange={(v: any) => setEditingItem({ ...editingItem, landingUsageTitle: v })} disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <div className="space-y-4">
                          {(editingItem.usageTips || []).map((tip: any, i: number) => (
                            <div key={i} className="p-8 bg-white rounded-[32px] border relative group space-y-4">
                              <button onClick={() => setEditingItem({ ...editingItem, usageTips: editingItem.usageTips.filter((_: any, idx: any) => idx !== i) })} className="absolute top-6 right-6 text-red-400 opacity-0 group-hover:opacity-100 transition-all"><Trash2 size={16} /></button>
                              <Input label="Tip Topic" value={tip.title} onChange={(v: any) => { let n = [...editingItem.usageTips]; n[i].title = v; setEditingItem({ ...editingItem, usageTips: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                              <textarea value={tip.desc || ''} placeholder="Tip Details" onChange={(e) => { let n = [...editingItem.usageTips]; n[i].desc = e.target.value; setEditingItem({ ...editingItem, usageTips: n }) }} className="w-full p-4 bg-slate-50 rounded-2xl font-bangla text-xs font-bold" disabled={!canAccess('landing-editor', 'edit')} />
                            </div>
                          ))}
                          {canAccess('landing-editor', 'edit') && (
                            <button onClick={() => setEditingItem({ ...editingItem, usageTips: [...(editingItem.usageTips || []), { title: '', desc: '' }] })} className="w-full py-6 border-2 border-dashed rounded-[32px] text-slate-500 dark:text-slate-400 font-black">+ Add Tip</button>
                          )}
                        </div>
                      </div>
                    </div>

                    <div id="sec-packages" style={{ display: showSection('sec-packages') ? 'block' : 'none' }}>
                      <SectionHeader icon={ShoppingCart} title="Package Visuals" color="blue" />
                      <FieldGroup label="Section Image" help="Image shown next to the package selector.">
                        <div className="aspect-square bg-slate-100 rounded-3xl border-2 border-dashed flex flex-col items-center justify-center relative overflow-hidden group max-w-sm mx-auto">
                          {editingItem.packageSectionImage ? <img src={editingItem.packageSectionImage} className="w-full h-full object-contain" /> : <ImageIcon size={48} className="text-slate-500 dark:text-slate-300" />}
                          {canAccess('landing-editor', 'edit') && (
                            <label className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 flex items-center justify-center cursor-pointer transition-opacity">
                              <span className="bg-white px-6 py-2 rounded-xl font-black text-xs">Update Photo</span>
                              <input type="file" className="hidden" accept="image/*" onChange={(e) => handleFileUpload(e, 'packageSectionImage')} />
                            </label>
                          )}
                        </div>
                      </FieldGroup>

                      <FieldGroup label="Per-Package Images" help="Upload a unique image for each package card. Leave blank to use the product image.">
                        <div className="grid grid-cols-3 gap-4">
                          {[0, 1, 2].map((idx) => {
                            const pkgImages = editingItem.landingPackageImages || [];
                            const imgUrl = pkgImages[idx] || '';
                            const labels = ['প্যাকেজ ১', 'প্যাকেজ ২', 'প্যাকেজ ৩'];
                            return (
                              <div key={idx} className="space-y-2">
                                <p className="text-xs font-black text-slate-500 text-center">{labels[idx]}</p>
                                <div className="aspect-square bg-slate-100 rounded-2xl border-2 border-dashed flex flex-col items-center justify-center relative overflow-hidden group">
                                  {imgUrl ? <img src={imgUrl} className="w-full h-full object-contain" /> : <ImageIcon size={28} className="text-slate-500 dark:text-slate-300" />}
                                  {canAccess('landing-editor', 'edit') && (
                                    <label className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 flex items-center justify-center cursor-pointer transition-opacity">
                                      <span className="bg-white px-2 py-1 rounded-lg font-black text-[10px]">Upload</span>
                                      <input type="file" className="hidden" accept="image/*" onChange={async (e) => {
                                        const file = e.target.files?.[0];
                                        if (!file) return;
                                        try {
                                          setIsSaving(true);
                                          const url = await uploadImageToPHP(file);
                                          if (url) {
                                            const newImages = [...(editingItem.landingPackageImages || ['', '', ''])];
                                            newImages[idx] = url;
                                            setEditingItem({ ...editingItem, landingPackageImages: newImages });
                                            showToast('Package image uploaded successfully', 'success');
                                          }
                                        } catch (err: any) {
                                          showToast('Upload failed: ' + err.message, 'error');
                                        } finally {
                                          setIsSaving(false);
                                        }
                                      }} />
                                    </label>
                                  )}
                                </div>
                                {imgUrl && canAccess('landing-editor', 'edit') && (
                                  <button onClick={() => {
                                    const newImages = [...(editingItem.landingPackageImages || ['', '', ''])];
                                    newImages[idx] = '';
                                    setEditingItem({ ...editingItem, landingPackageImages: newImages });
                                  }} className="w-full text-xs text-red-400 font-bold hover:text-red-600">× Remove</button>
                                )}
                              </div>
                            );
                          })}
                        </div>
                      </FieldGroup>
                    </div>

                    <div id="sec-faq" style={{ display: showSection('sec-faq') ? 'block' : 'none' }}>
                      <SectionHeader icon={HelpCircle} title="Frequently Asked Questions" subtitle="Add FAQs for this product." color="purple" />
                      <div className="space-y-4">
                        {(editingItem.faqs || []).map((faq: any, i: number) => (
                          <div key={i} className="bg-white p-8 rounded-[40px] border relative group space-y-4">
                            <button onClick={() => setEditingItem({ ...editingItem, faqs: editingItem.faqs.filter((_: any, idx: any) => idx !== i) })} className="absolute top-6 right-6 text-red-400 opacity-0 group-hover:opacity-100 transition-all"><Trash2 size={16} /></button>
                            <div className="space-y-4">
                              <Input label={`Question #${i + 1}`} value={faq.q} onChange={(v: any) => { let n = [...editingItem.faqs]; n[i].q = v; setEditingItem({ ...editingItem, faqs: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                              <FieldGroup label="Answer">
                                <textarea value={faq.a || ''} onChange={(e) => { let n = [...editingItem.faqs]; n[i].a = e.target.value; setEditingItem({ ...editingItem, faqs: n }) }} className="w-full p-4 bg-slate-50 rounded-2xl font-bangla text-sm font-bold min-h-[100px]" disabled={!canAccess('landing-editor', 'edit')} />
                              </FieldGroup>
                            </div>
                          </div>
                        ))}
                        {canAccess('landing-editor', 'edit') && (
                          <button onClick={() => setEditingItem({ ...editingItem, faqs: [...(editingItem.faqs || []), { q: '', a: '' }] })} className="w-full py-6 border-2 border-dashed rounded-[32px] text-slate-500 dark:text-slate-400 font-black">+ Add New FAQ Item</button>
                        )}
                      </div>
                    </div>

                    {/* ===== TESTIMONIAL IMAGES ===== */}
                    <div id="sec-testimonial-image">
                      <SectionHeader icon={ImageIcon} title="Testimonial Section Images" subtitle="Multiple images shown in a row below customer reviews. Add as many as you like." color="purple" />
                      <FieldGroup label="Images (একটি row-এ দেখাবে)">
                        <div className="space-y-3">
                          <div className="grid grid-cols-3 gap-3">
                            {(editingItem.landingTestimonialImages || []).map((imgUrl: string, idx: number) => (
                              <div key={idx} className="relative group">
                                <div className="aspect-square bg-slate-100 rounded-xl overflow-hidden border">
                                  <img src={imgUrl} className="w-full h-full object-cover" />
                                </div>
                                {canAccess('landing-editor', 'edit') && (
                                  <button onClick={() => {
                                    const imgs = [...(editingItem.landingTestimonialImages || [])];
                                    imgs.splice(idx, 1);
                                    setEditingItem({ ...editingItem, landingTestimonialImages: imgs });
                                  }} className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full text-xs font-black flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all">×</button>
                                )}
                              </div>
                            ))}
                            {canAccess('landing-editor', 'edit') && (
                              <label className="aspect-square bg-slate-100 rounded-xl border-2 border-dashed flex flex-col items-center justify-center cursor-pointer hover:bg-slate-200 transition-colors">
                                <Plus size={24} className="text-slate-500 dark:text-slate-400" />
                                <span className="text-xs text-slate-500 dark:text-slate-400 mt-1 font-bold">Add Image</span>
                                <input type="file" className="hidden" accept="image/*" onChange={async (e) => {
                                  const file = e.target.files?.[0];
                                  if (!file) return;
                                  try {
                                    setIsSaving(true);
                                    const url = await uploadImageToPHP(file);
                                    if (url) {
                                      setEditingItem({ ...editingItem, landingTestimonialImages: [...(editingItem.landingTestimonialImages || []), url] });
                                      showToast('Testimonial image uploaded successfully', 'success');
                                    }
                                  } catch (err: any) {
                                    showToast('Upload failed: ' + err.message, 'error');
                                  } finally {
                                    setIsSaving(false);
                                  }
                                }} />
                              </label>
                            )}
                          </div>
                          <p className="text-xs text-slate-500 dark:text-slate-400 italic">Images will appear in a horizontal scrollable row below the reviews.</p>
                        </div>
                      </FieldGroup>
                    </div>

                    {/* ===== ০২. PROBLEM SECTION ===== */}
                    <div id="sec-problem" style={{ display: showSection('sec-problem') ? 'block' : 'none' }}>
                      <SectionHeader icon={Flame} title="০২. Problem Section" subtitle="ইউজারের pain points দেখান। Section title + icon+text+subtext কার্ড।" color="red" />
                      <div className="space-y-6">
                        <FieldGroup label="Section Heading (যেমন: আপনি কি এই কষ্টে ভুগছেন?)">
                          <Input value={editingItem.landingProblemTitle || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingProblemTitle: v })} disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <div className="space-y-4">
                          {(editingItem.landingProblems || []).map((p: any, i: number) => (
                            <div key={i} className="bg-white p-6 rounded-[32px] border relative group">
                              <button onClick={() => setEditingItem({ ...editingItem, landingProblems: (editingItem.landingProblems || []).filter((_: any, idx: any) => idx !== i) })} className="absolute top-4 right-4 text-red-400 opacity-0 group-hover:opacity-100 transition-all"><Trash2 size={16} /></button>
                              <div className="grid grid-cols-3 gap-4">
                                <Input label="Icon (flame/pill/activity)" value={p.icon || ''} onChange={(v: any) => { let n = [...(editingItem.landingProblems || [])]; n[i].icon = v; setEditingItem({ ...editingItem, landingProblems: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                                <Input label="শিরোনাম (Problem Title)" value={p.text || ''} onChange={(v: any) => { let n = [...(editingItem.landingProblems || [])]; n[i].text = v; setEditingItem({ ...editingItem, landingProblems: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                                <Input label="বিবরণ (Sub-text)" value={p.subtext || ''} onChange={(v: any) => { let n = [...(editingItem.landingProblems || [])]; n[i].subtext = v; setEditingItem({ ...editingItem, landingProblems: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                              </div>
                            </div>
                          ))}
                          {canAccess('landing-editor', 'edit') && (
                            <button onClick={() => setEditingItem({ ...editingItem, landingProblems: [...(editingItem.landingProblems || []), { icon: 'flame', text: '', subtext: '' }] })} className="w-full py-6 border-2 border-dashed rounded-[32px] text-slate-500 dark:text-slate-400 font-black">+ সমস্যা যোগ করুন</button>
                          )}
                        </div>
                      </div>
                    </div>

                    {/* ===== SECTION 3: SOLUTION ===== */}
                    <div id="sec-solution" style={{ display: showSection('sec-solution') ? 'block' : 'none' }}>
                      <SectionHeader icon={Leaf} title="Solution Section" subtitle="Describe your product as the solution." color="green" />
                      <div className="space-y-6">
                        <FieldGroup label="Solution Name / Heading">
                          <Input value={editingItem.landingSolutionName || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingSolutionName: v })} disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <FieldGroup label="Solution Description">
                          <textarea value={editingItem.landingSolutionDesc || ''} onChange={(e) => setEditingItem({ ...editingItem, landingSolutionDesc: e.target.value })} className="w-full p-4 bg-slate-50 dark:bg-slate-800 rounded-3xl font-bangla min-h-[120px] focus:ring-2 focus:ring-red-600 font-bold" disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <FieldGroup label="Benefits (one per line)">
                          <textarea value={(editingItem.landingSolutionBenefits || []).join('\n')} onChange={(e) => setEditingItem({ ...editingItem, landingSolutionBenefits: e.target.value.split('\n') })} className="w-full p-4 bg-slate-50 dark:bg-slate-800 rounded-3xl font-bangla min-h-[120px] font-bold" disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <FieldGroup label="Solution Image">
                          <div className="aspect-video bg-slate-100 rounded-2xl border-2 border-dashed flex flex-col items-center justify-center relative overflow-hidden group">
                            {editingItem.landingSolutionImage ? <img src={editingItem.landingSolutionImage} className="w-full h-full object-contain" /> : <ImageIcon size={48} className="text-slate-500 dark:text-slate-300" />}
                            {canAccess('landing-editor', 'edit') && (
                              <label className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 flex items-center justify-center cursor-pointer transition-opacity">
                                <span className="bg-white px-6 py-2 rounded-xl font-black text-xs">Upload Image</span>
                                <input type="file" className="hidden" accept="image/*" onChange={(e) => handleFileUpload(e, 'landingSolutionImage')} />
                              </label>
                            )}
                          </div>
                        </FieldGroup>
                      </div>
                    </div>

                    {/* ===== ০৩. SOLUTION SECTION (Why Choose Us) ===== */}
                    <div id="sec-why-us" style={{ display: showSection('sec-why-us') ? 'block' : 'none' }}>
                      <SectionHeader icon={Shield} title="Solution Benefits (Why Choose Us)" subtitle="Solution section এর ডানে যে সুবিধাগুলো দেখায়।" color="blue" />
                      <div className="space-y-4">
                        {(editingItem.landingWhyChooseUs || []).map((w: any, i: number) => (
                          <div key={i} className="bg-white p-6 rounded-[32px] border relative group">
                            <button onClick={() => setEditingItem({ ...editingItem, landingWhyChooseUs: (editingItem.landingWhyChooseUs || []).filter((_: any, idx: any) => idx !== i) })} className="absolute top-4 right-4 text-red-400 opacity-0 group-hover:opacity-100 transition-all"><Trash2 size={16} /></button>
                            <div className="grid grid-cols-3 gap-4">
                              <Input label="Icon (sprout/check/zap)" value={w.icon || ''} onChange={(v: any) => { let n = [...(editingItem.landingWhyChooseUs || [])]; n[i].icon = v; setEditingItem({ ...editingItem, landingWhyChooseUs: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                              <Input label="শিরোনাম (Title)" value={w.text || w.title || ''} onChange={(v: any) => { let n = [...(editingItem.landingWhyChooseUs || [])]; n[i].text = v; n[i].title = v; setEditingItem({ ...editingItem, landingWhyChooseUs: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                              <Input label="বিবরণ (Sub-text)" value={w.subtext || w.desc || ''} onChange={(v: any) => { let n = [...(editingItem.landingWhyChooseUs || [])]; n[i].subtext = v; n[i].desc = v; setEditingItem({ ...editingItem, landingWhyChooseUs: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                            </div>
                          </div>
                        ))}
                        {canAccess('landing-editor', 'edit') && (
                          <button onClick={() => setEditingItem({ ...editingItem, landingWhyChooseUs: [...(editingItem.landingWhyChooseUs || []), { icon: 'sprout', text: '', subtext: '' }] })} className="w-full py-6 border-2 border-dashed rounded-[32px] text-slate-500 dark:text-slate-400 font-black">+ সুবিধা যোগ করুন</button>
                        )}
                      </div>
                    </div>

                    {/* ===== SECTION 4: BENEFITS TITLE ===== */}
                    <div id="sec-benefits-title" style={{ display: showSection('sec-benefits-title') ? 'block' : 'none' }}>
                      <SectionHeader icon={Sparkles} title="Benefits Section" subtitle="Title for the benefits/features section." color="amber" />
                      <div className="space-y-6">
                        <FieldGroup label="Section Title">
                          <Input value={editingItem.landingBenefitsTitle || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingBenefitsTitle: v })} disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <FieldGroup label="Section Subtitle">
                          <Input value={editingItem.landingBenefitsSubtitle || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingBenefitsSubtitle: v })} disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                      </div>
                    </div>

                    {/* ===== ০৬. SOCIAL PROOF / REVIEWS ===== */}
                    <div id="sec-reviews" style={{ display: showSection('sec-reviews') ? 'block' : 'none' }}>
                      <SectionHeader icon={Star} title="০৬. Social Proof (Reviews)" subtitle="গ্রাহকের রিভিউ সেকশন। Testimonials থেকে স্বয়ংক্রিয়ভাবে দেখাবে। এখানে section এর heading কাস্টমাইজ করুন।" color="amber" />
                      <div className="space-y-6">
                        <FieldGroup label="Section Heading (যেমন: গ্রাহকের মন্তব্য)">
                          <Input value={editingItem.landingReviewsTitle || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingReviewsTitle: v })} placeholder="গ্রাহকের মন্তব্য" disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <FieldGroup label="Section Subtitle">
                          <Input value={editingItem.landingReviewsSubtitle || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingReviewsSubtitle: v })} placeholder="হাজারো মানুষের আস্থার প্রতীক" disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <div className="bg-blue-50 border border-blue-200 rounded-2xl p-4">
                          <p className="text-blue-700 text-xs font-bold">💡 Reviews স্বয়ংক্রিয়ভাবে Testimonials section থেকে আসে। Testimonials যোগ করতে Product এর Testimonials ট্যাব ব্যবহার করুন।</p>
                        </div>
                      </div>
                    </div>

                    {/* ===== ০৭. OFFER / PRICING ===== */}
                    <div id="sec-offer" style={{ display: showSection('sec-offer') ? 'block' : 'none' }}>
                      <SectionHeader icon={Zap} title="০৭. Offer / Pricing Section" subtitle="Urgency তৈরি করতে এই section ব্যবহার করুন।" color="red" />
                      <div className="space-y-6">
                        <FieldGroup label="Offer Section Heading (যেমন: অফার শেষ হওয়ার আগেই নিন!)">
                          <Input value={editingItem.landingOfferTitle || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingOfferTitle: v })} placeholder="অফার শেষ হওয়ার আগেই নিন!" disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <FieldGroup label="Offer Badge Text (যেমন: সীমিত সময়ের অফার!)">
                          <Input value={editingItem.landingOfferBadge || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingOfferBadge: v })} placeholder="⚡ সীমিত সময়ের অফার!" disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <div className="bg-amber-50 border border-amber-200 rounded-2xl p-4">
                          <p className="text-amber-700 text-xs font-bold">⏱️ Countdown timer স্বয়ংক্রিয়ভাবে চলে। দাম Product এর price/sale price থেকে আসে।</p>
                        </div>
                      </div>
                    </div>

                    {/* ===== ০৯. TRUST ELEMENTS ===== */}
                    <div id="sec-trust" style={{ display: showSection('sec-trust') ? 'block' : 'none' }}>
                      <SectionHeader icon={ShieldCheck} title="০৯. Trust Elements" subtitle="Order form এর পাশে trust badges। Risk remove করে।" color="green" />
                      <div className="space-y-6">
                        <FieldGroup label="Section Heading (যেমন: কেন নিশ্চিন্তে অর্ডার করবেন?)">
                          <Input value={editingItem.landingTrustTitle || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingTrustTitle: v })} placeholder="কেন নিশ্চিন্তে অর্ডার করবেন?" disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <div className="space-y-4">
                          {(editingItem.landingTrustElements || []).map((t: any, i: number) => (
                            <div key={i} className="bg-white p-6 rounded-[32px] border relative group">
                              <button onClick={() => setEditingItem({ ...editingItem, landingTrustElements: (editingItem.landingTrustElements || []).filter((_: any, idx: any) => idx !== i) })} className="absolute top-4 right-4 text-red-400 opacity-0 group-hover:opacity-100 transition-all"><Trash2 size={16} /></button>
                              <div className="grid grid-cols-2 gap-4">
                                <Input label="শিরোনাম (Title)" value={t.title || ''} onChange={(v: any) => { let n = [...(editingItem.landingTrustElements || [])]; n[i].title = v; setEditingItem({ ...editingItem, landingTrustElements: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                                <Input label="বিবরণ (Description)" value={t.desc || ''} onChange={(v: any) => { let n = [...(editingItem.landingTrustElements || [])]; n[i].desc = v; setEditingItem({ ...editingItem, landingTrustElements: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                              </div>
                            </div>
                          ))}
                          {canAccess('landing-editor', 'edit') && (
                            <button onClick={() => setEditingItem({ ...editingItem, landingTrustElements: [...(editingItem.landingTrustElements || []), { title: '', desc: '' }] })} className="w-full py-6 border-2 border-dashed rounded-[32px] text-slate-500 dark:text-slate-400 font-black">+ Trust Element যোগ করুন</button>
                          )}
                        </div>
                      </div>
                    </div>

                    {/* ===== SECTION 9: GUARANTEE ===== */}
                    <div id="sec-guarantee" style={{ display: showSection('sec-guarantee') ? 'block' : 'none' }}>
                      <SectionHeader icon={ShieldCheck} title="Money-Back Guarantee" subtitle="Build trust with a guarantee." color="green" />
                      <div className="space-y-6">
                        <FieldGroup label="Guarantee Title">
                          <Input value={editingItem.landingGuaranteeTitle || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingGuaranteeTitle: v })} disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <FieldGroup label="Guarantee Text">
                          <textarea value={editingItem.landingGuaranteeText || ''} onChange={(e) => setEditingItem({ ...editingItem, landingGuaranteeText: e.target.value })} className="w-full p-4 bg-slate-50 dark:bg-slate-800 rounded-3xl font-bangla min-h-[100px] font-bold" disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                      </div>
                    </div>

                    {/* ===== SECTION 10: PROCESS STEPS ===== */}
                    <div id="sec-process" style={{ display: showSection('sec-process') ? 'block' : 'none' }}>
                      <SectionHeader icon={Zap} title="Process Steps" subtitle="How does it work?" color="amber" />
                      <div className="space-y-4">
                        {(editingItem.landingProcessSteps || []).map((step: any, i: number) => (
                          <div key={i} className="bg-white p-6 rounded-[32px] border relative group">
                            <button onClick={() => setEditingItem({ ...editingItem, landingProcessSteps: (editingItem.landingProcessSteps || []).filter((_: any, idx: any) => idx !== i) })} className="absolute top-4 right-4 text-red-400 opacity-0 group-hover:opacity-100 transition-all"><Trash2 size={16} /></button>
                            <div className="grid grid-cols-3 gap-4">
                              <Input label="Icon Name" value={step.icon || ''} onChange={(v: any) => { let n = [...(editingItem.landingProcessSteps || [])]; n[i].icon = v; setEditingItem({ ...editingItem, landingProcessSteps: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                              <Input label="Title" value={step.title || ''} onChange={(v: any) => { let n = [...(editingItem.landingProcessSteps || [])]; n[i].title = v; setEditingItem({ ...editingItem, landingProcessSteps: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                              <Input label="Description" value={step.desc || ''} onChange={(v: any) => { let n = [...(editingItem.landingProcessSteps || [])]; n[i].desc = v; setEditingItem({ ...editingItem, landingProcessSteps: n }) }} disabled={!canAccess('landing-editor', 'edit')} />
                            </div>
                          </div>
                        ))}
                        {canAccess('landing-editor', 'edit') && (
                          <button onClick={() => setEditingItem({ ...editingItem, landingProcessSteps: [...(editingItem.landingProcessSteps || []), { icon: 'calendar', title: '', desc: '' }] })} className="w-full py-6 border-2 border-dashed rounded-[32px] text-slate-500 dark:text-slate-400 font-black">+ Add Step</button>
                        )}
                      </div>
                    </div>

                    {/* ===== ১১. FINAL CTA ===== */}
                    <div id="sec-cta" style={{ display: showSection('sec-cta') ? 'block' : 'none' }}>
                      <SectionHeader icon={Target} title="১১. Final CTA (Last Push)" subtitle="শেষবারের call to action। Urgency message দিন।" color="red" />
                      <div className="space-y-6">
                        <FieldGroup label="CTA Button Text (যেমন: এখনই অর্ডার করুন)">
                          <Input value={editingItem.landingCtaTitle || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingCtaTitle: v })} placeholder="এখনই অর্ডার করুন" disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                        <FieldGroup label="Urgency Message / Subtitle">
                          <Input value={editingItem.landingCtaSubtitle || ''} onChange={(v: any) => setEditingItem({ ...editingItem, landingCtaSubtitle: v })} placeholder="স্টক সীমিত — এই সুযোগ হাতছাড়া করবেন না" disabled={!canAccess('landing-editor', 'edit')} />
                        </FieldGroup>
                      </div>
                    </div>
                  </div>

                  {previewMode && (
                    <div className="hidden xl:block xl:col-span-5 relative h-full">
                      <div className="sticky top-8 w-full">
                        {/* Laptop/Browser Mockup */}
                        <div className="bg-slate-200 rounded-2xl shadow-2xl overflow-hidden border border-slate-300" style={{ boxShadow: '0 25px 60px rgba(0,0,0,0.25)' }}>
                          {/* Browser Chrome / Top Bar */}
                          <div className="bg-slate-700 px-4 py-3 flex items-center gap-3">
                            {/* Traffic lights */}
                            <div className="flex items-center gap-1.5">
                              <div className="w-3 h-3 rounded-full bg-red-500"></div>
                              <div className="w-3 h-3 rounded-full bg-amber-400"></div>
                              <div className="w-3 h-3 rounded-full bg-green-500"></div>
                            </div>
                            {/* Address bar */}
                            <div className="flex-1 bg-slate-600 rounded-md px-3 py-1.5 flex items-center gap-2">
                              <div className="w-3 h-3 rounded-full border border-slate-400 opacity-60"></div>
                              <span className="text-[11px] text-slate-500 dark:text-slate-300 font-mono truncate">
                                {editingItem?.slug ? `yoursite.com/${editingItem.slug}` : 'yoursite.com/landing'}
                              </span>
                            </div>
                            {/* Refresh icon */}
                            <div className="text-slate-500 dark:text-slate-400 opacity-60">
                              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M23 4v6h-6" /><path d="M1 20v-6h6" /><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" /></svg>
                            </div>
                          </div>
                          {/* Browser Content Area */}
                          <div className="w-full overflow-y-auto bg-white custom-scrollbar" style={{ height: '75vh' }}>
                            {(() => {
                              const props = { product: editingItem, settings, addOrder: () => { }, onNavigate: () => { } };
                              switch (editingItem.landingTheme) {
                                case '01': return <ProductLandingPage01 {...props} />;
                                case '02': return <ProductLandingPage02 {...props} />;
                                case '03': return <ProductLandingPage03 {...props} />;
                                case '04': return <ProductLandingPage04 {...props} />;
                                case '05': return <ProductLandingPage05 {...props} />;
                                case '06': return <ProductLandingPage06 {...props} />;
                                default: return <ProductLandingPage {...props} />;
                              }
                            })()}
                          </div>
                          {/* Bottom bar (status bar) */}
                          <div className="bg-slate-700 px-4 py-1.5 flex items-center justify-between">
                            <span className="text-[10px] text-slate-500 dark:text-slate-400 font-mono">Live Preview</span>
                            <span className="text-[10px] text-green-400 font-mono flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-green-400 inline-block"></span> Ready</span>
                          </div>
                        </div>
                        {/* Laptop base/stand shadow */}
                        <div className="mx-auto mt-0 h-3 bg-slate-300 rounded-b-xl" style={{ width: '92%' }}></div>
                        <div className="mx-auto h-2 bg-slate-400 rounded-b-full shadow-lg" style={{ width: '60%' }}></div>
                      </div>
                    </div>
                  )}
                </div>
              ) : activeTab === 'reviews' ? (
                <div className="max-w-2xl mx-auto space-y-8">
                  <FieldGroup label="Reviewer Info" icon={Star}>
                    <Input
                      label="Customer Name"
                      value={editingItem.name}
                      onChange={(v: any) => setEditingItem({ ...editingItem, name: v })}
                      disabled={!canAccess('testimonials', 'edit')}
                    />
                    <div className="mt-6 flex items-center gap-6">
                      <div className="w-20 h-20 bg-slate-100 rounded-full overflow-hidden relative group">
                        {editingItem.avatar ? <img src={editingItem.avatar} className="w-full h-full object-cover" /> : <Grid size={40} className="m-5 text-slate-500 dark:text-slate-300" />}
                        {canAccess('testimonials', 'edit') && (
                          <label className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 flex items-center justify-center cursor-pointer transition-opacity">
                            <Edit3 size={16} className="text-slate-800 dark:text-white" />
                            <input type="file" className="hidden" accept="image/*" onChange={(e) => handleFileUpload(e, 'reviewAvatar')} />
                          </label>
                        )}
                      </div>
                      <div className="flex-grow">
                        <label className="text-[10px] font-black uppercase text-slate-500 dark:text-slate-400 mb-2 block">Rating</label>
                        <div className="flex gap-2">
                          {[1, 2, 3, 4, 5].map(s => (
                            <button
                              key={s}
                              onClick={() => setEditingItem({ ...editingItem, rating: s })}
                              className={`p-3 rounded-xl ${editingItem.rating >= s ? 'bg-amber-100 text-amber-600' : 'bg-slate-50 text-slate-500 dark:text-slate-300'}`}
                              disabled={!canAccess('testimonials', 'edit')}
                            >
                              <Star size={20} fill={editingItem.rating >= s ? 'currentColor' : 'none'} />
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>
                  </FieldGroup>
                  <FieldGroup label="Testimonial Text">
                    <textarea
                      value={editingItem.text || ''}
                      onChange={(e) => setEditingItem({ ...editingItem, text: e.target.value })}
                      className="w-full p-6 bg-slate-50 rounded-3xl font-bangla min-h-[150px] font-bold"
                      disabled={!canAccess('testimonials', 'edit')}
                    />
                  </FieldGroup>
                </div>
                            ) : activeTab === 'products' ? (
                <div className="pb-10 animate-fade-in-up max-w-xl mx-auto md:max-w-5xl md:grid md:grid-cols-[340px_1fr] md:gap-6 md:items-start space-y-4 md:space-y-0">
                  <div
                    className="w-full rounded-3xl overflow-hidden shadow-sm border border-violet-100"
                    style={{ background: 'linear-gradient(135deg, #f5f3ff, #ede9fe)' }}
                  >
                    {/* Image Preview */}
                    <div className="relative w-full aspect-[4/3] bg-gradient-to-br from-violet-100 to-indigo-100">
                      {editingItem.image
                        ? <img src={editingItem.image} className="w-full h-full object-cover" alt="Product" />
                        : (
                          <div className="absolute inset-0 flex flex-col items-center justify-center gap-3">
                            <div className="w-20 h-20 rounded-full bg-white/70 flex items-center justify-center shadow-inner">
                              <ImageIcon size={36} className="text-violet-400" />
                            </div>
                            <p className="text-sm font-black text-violet-500">প্রোডাক্টের ছবি যোগ করুন</p>
                          </div>
                        )
                      }
                      {editingItem.image && (
                        <div className="absolute top-3 right-3 bg-black/50 backdrop-blur-sm text-white text-[10px] font-black px-3 py-1.5 rounded-full flex items-center gap-1.5">
                          <Edit3 size={10} /> পরিবর্তন করুন
                        </div>
                      )}
                    </div>
                    {/* Upload buttons */}
                    {canAccess('products', 'edit') && (
                      <div className="grid grid-cols-2 divide-x divide-violet-100 border-t border-violet-100">
                        <button
                          type="button"
                          onClick={() => openWebcam('itemImage')}
                          className="flex flex-col items-center gap-2 py-4 hover:bg-violet-100 transition-colors group w-full"
                        >
                          <div className="w-10 h-10 rounded-full bg-violet-200 flex items-center justify-center group-hover:scale-110 transition-transform">
                            <Camera size={20} className="text-violet-700" />
                          </div>
                          <span className="text-[11px] font-black text-violet-700 uppercase tracking-wide">ক্যামেরা</span>
                        </button>
                        <label className="flex flex-col items-center gap-2 py-4 cursor-pointer hover:bg-indigo-100 transition-colors group">
                          <div className="w-10 h-10 rounded-full bg-indigo-200 flex items-center justify-center group-hover:scale-110 transition-transform">
                            <ImageIcon size={20} className="text-indigo-700" />
                          </div>
                          <span className="text-[11px] font-black text-indigo-700 uppercase tracking-wide">গ্যালারি</span>
                          <input type="file" accept="image/*" className="hidden" onChange={(e) => handleFileUpload(e, 'itemImage')} />
                        </label>
                      </div>
                    )}
                  </div>
                  {/* ── Right column: all form fields ── */}
                  <div className="space-y-4">
                    {/* Section 1: Product Info */}
                    <div className="bg-white rounded-3xl p-6 shadow-sm border border-slate-100 space-y-5">
                      <div className="flex items-center gap-3 pb-3 border-b border-slate-100">
                        <div className="w-9 h-9 rounded-2xl flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}>
                          <Tag size={16} className="text-white" />
                        </div>
                        <div>
                          <h3 className="font-black text-base text-slate-900">Product Info</h3>
                          <p className="text-[10px] text-slate-400 font-bold">Basic product details</p>
                        </div>
                      </div>
                      <div className="space-y-4">
                        <Input
                          label="Name (EN)"
                          value={editingItem.name}
                          onChange={(v: any) => setEditingItem({ ...editingItem, name: v })}
                          disabled={!canAccess('products', 'edit')}
                        />
                        {/* Name BN with Bengali font + warning if no Bengali chars */}
                        <div className="space-y-1.5 w-full">
                          <label className="text-[10px] font-black uppercase text-slate-950 dark:text-slate-300 ml-2 flex items-center gap-1.5">
                            Name (BN)
                            {editingItem.nameBangla && !/[\u0980-\u09FF]/.test(editingItem.nameBangla) && (
                              <span className="text-amber-500 text-[9px] font-black bg-amber-50 px-2 py-0.5 rounded-full border border-amber-200">⚠ বাংলা নাম দিন</span>
                            )}
                          </label>
                          <input
                            type="text"
                            className={`w-full px-6 py-4 bg-slate-50 dark:bg-slate-800 rounded-2xl border font-bold focus:ring-2 focus:ring-red-600 focus:bg-white text-slate-950 dark:text-white transition-all shadow-inner font-bangla placeholder-slate-950 ${editingItem.nameBangla && !/[\u0980-\u09FF]/.test(editingItem.nameBangla)
                              ? 'border-amber-400 bg-amber-50'
                              : 'border-transparent'
                              }`}
                            value={editingItem.nameBangla || ''}
                            onChange={(e) => setEditingItem({ ...editingItem, nameBangla: e.target.value })}
                            placeholder="যেমন: দেশি জিরা গুঁড়া"
                            disabled={!canAccess('products', 'edit')}
                          />
                        </div>
                      </div>
                      <div className="grid grid-cols-2 gap-3">
                        <div className="space-y-2">
                          <label className="text-[10px] font-black uppercase text-slate-950 dark:text-slate-300 ml-2">Category</label>
                          <select
                            value={editingItem.category}
                            onChange={(e: any) => setEditingItem({ ...editingItem, category: e.target.value })}
                            disabled={!canAccess('products', 'edit')}
                            className="w-full px-6 py-4 bg-slate-50 dark:bg-slate-800 border-2 border-transparent focus:border-red-600 rounded-2xl outline-none font-bold appearance-none cursor-pointer text-slate-950"
                          >
                            <option value="">Select Category</option>
                            {(() => {
                              let cats = ['Basic', 'Premium'];
                              if (settings.categoriesJson) {
                                try { cats = JSON.parse(settings.categoriesJson); } catch (e) { }
                              }
                              return cats.map((cat: any, idx: number) => {
                                const catName = typeof cat === 'string' ? cat : cat.name;
                                return <option key={idx} value={catName}>{catName}</option>;
                              });
                            })()}
                          </select>
                        </div>
                        <Input
                          label="Quick Highlight"
                          value={editingItem.highlight}
                          onChange={(v: any) => setEditingItem({ ...editingItem, highlight: v })}
                          disabled={!canAccess('products', 'edit')}
                        />
                      </div>

                      {canAccess('products', 'edit') && (
                        <div className="pt-5 border-t border-slate-100 space-y-4">
                          {/* Header */}
                          <div className="flex justify-between items-center">
                            <div className="flex items-center gap-2.5">
                              <div className="w-8 h-8 rounded-xl bg-orange-500 flex items-center justify-center">
                                <List size={15} className="text-white" />
                              </div>
                              <div>
                                <h4 className="font-black text-sm text-black">Variations & Pricing</h4>
                                <p className="text-[10px] text-slate-400">Per-size price & cost setup</p>
                              </div>
                            </div>
                            <button
                              onClick={() => setTempPriceList([...tempPriceList, {
                                size: '',
                                config: { originalPrice: 0, discountValue: 0, discountType: 'percentage', salePrice: 0, mainBalance: 0, freeDelivery: false }
                              }])}
                              className="flex items-center gap-1.5 px-4 py-2 bg-orange-500 hover:bg-orange-600 text-white rounded-xl text-xs font-black transition-all"
                            >
                              <Plus size={13} /> Add Variation
                            </button>
                          </div>

                          {/* Empty state */}
                          {tempPriceList.length === 0 && (
                            <div className="flex flex-col items-center py-8 border-2 border-dashed border-slate-200 rounded-2xl">
                              <List size={24} className="text-slate-300 mb-2" />
                              <p className="text-sm font-black text-black">No variations added</p>
                              <p className="text-[10px] text-slate-400 mt-0.5">Click "Add Variation" to begin</p>
                            </div>
                          )}

                          {/* Variation Cards */}
                          <div className="space-y-3">
                            {tempPriceList.map((it, idx) => (
                              <div key={idx} className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-sm">
                                {/* Card Header */}
                                <div className="flex items-center justify-between px-4 py-2.5 bg-orange-50 border-b border-orange-100">
                                  <span className="text-[11px] font-black text-orange-700 uppercase tracking-wider">Variation #{idx + 1}</span>
                                  <button
                                    onClick={() => setTempPriceList(tempPriceList.filter((_, i) => i !== idx))}
                                    className="flex items-center gap-1 text-red-500 hover:text-white hover:bg-red-500 px-2.5 py-1 rounded-lg text-[10px] font-black transition-all bg-red-50 border border-red-100"
                                  >
                                    <Trash2 size={11} /> Remove
                                  </button>
                                </div>
                                {/* 4 Fields in a row */}
                                <div className="p-4 grid grid-cols-2 md:grid-cols-4 gap-3">
                                  {/* Size */}
                                  <div className="col-span-2 md:col-span-1 space-y-1.5">
                                    <label className="text-[10px] font-black uppercase text-slate-500 tracking-wider block">Size / Name</label>
                                    <input
                                      list={`variations-list-${idx}`}
                                      value={it.size}
                                      placeholder="e.g. 500g, L"
                                      onChange={(e) => { let n=[...tempPriceList]; n[idx].size=e.target.value; setTempPriceList(n); }}
                                      className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-sm font-black text-black placeholder-slate-300 outline-none focus:ring-2 focus:ring-orange-400 transition-all"
                                    />
                                    <datalist id={`variations-list-${idx}`}>
                                      {VARIATION_OPTIONS.weight.map((v) => <option key={v} value={v} />)}
                                      {VARIATION_OPTIONS.pieces.map((v) => <option key={v} value={v} />)}
                                      {VARIATION_OPTIONS.clothing.map((v) => <option key={v} value={v} />)}
                                    </datalist>
                                  </div>
                                  {/* MRP */}
                                  <div className="space-y-1.5">
                                    <label className="text-[10px] font-black uppercase text-slate-500 tracking-wider block">MRP (৳)</label>
                                    <input
                                      type="number"
                                      value={it.config.originalPrice}
                                      onChange={(e) => { let n=[...tempPriceList]; n[idx].config.originalPrice=Number(e.target.value); setTempPriceList(n); }}
                                      className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-sm font-black text-black outline-none focus:ring-2 focus:ring-orange-400 transition-all"
                                    />
                                  </div>
                                  {/* Discount + Type */}
                                  <div className="space-y-1.5">
                                    <label className="text-[10px] font-black uppercase text-slate-500 tracking-wider block">Discount</label>
                                    <div className="flex gap-1.5">
                                      <input
                                        type="number"
                                        value={it.config.discountValue}
                                        onChange={(e) => { let n=[...tempPriceList]; n[idx].config.discountValue=Number(e.target.value); setTempPriceList(n); }}
                                        className="flex-1 min-w-0 bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-sm font-black text-black outline-none focus:ring-2 focus:ring-orange-400 transition-all"
                                      />
                                      <select
                                        value={it.config.discountType}
                                        onChange={(e) => { let n=[...tempPriceList]; n[idx].config.discountType=e.target.value as any; setTempPriceList(n); }}
                                        className="w-12 bg-slate-50 border border-slate-200 rounded-xl px-1 py-2.5 text-xs font-black text-black outline-none focus:ring-2 focus:ring-orange-400 cursor-pointer text-center"
                                      >
                                        <option value="percentage">%</option>
                                        <option value="fixed">৳</option>
                                      </select>
                                    </div>
                                  </div>
                                  {/* Cost */}
                                  <div className="space-y-1.5">
                                    <label className="text-[10px] font-black uppercase text-slate-500 tracking-wider block">Cost Price (৳)</label>
                                    <input
                                      type="number"
                                      value={it.config.mainBalance ?? 0}
                                      onChange={(e) => { let n=[...tempPriceList]; n[idx].config.mainBalance=Number(e.target.value); setTempPriceList(n); }}
                                      className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-sm font-black text-black outline-none focus:ring-2 focus:ring-orange-400 transition-all"
                                    />
                                  </div>
                                </div>
                                {/* Free Delivery toggle */}
                                <div className="px-4 pb-4 border-t border-slate-100 pt-3">
                                  <label className="flex items-center gap-3 cursor-pointer w-fit">
                                    <div className="relative shrink-0">
                                      <input
                                        type="checkbox"
                                        checked={it.config.freeDelivery || false}
                                        onChange={(e) => { let n=[...tempPriceList]; n[idx].config.freeDelivery=e.target.checked; setTempPriceList(n); }}
                                        className="sr-only peer"
                                      />
                                      <div className="w-9 h-5 bg-slate-200 peer-checked:bg-green-500 rounded-full transition-colors" />
                                      <div className="absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow-sm transition-transform peer-checked:translate-x-4" />
                                    </div>
                                    <span className="text-xs font-black text-black">🚚 এই variation এ Free Delivery দিন</span>
                                  </label>
                                </div>
                              </div>
                            ))}
                          </div>

                        </div>
                      )}

                      {/* NEW: Product Detail Page Content Inputs */}
                      {canAccess('products', 'edit') && (
                        <div className="pt-5 border-t border-slate-100 space-y-5">
                          <div className="flex items-center gap-2">
                            <div className="w-7 h-7 rounded-xl bg-blue-100 flex items-center justify-center">
                              <FileText size={14} className="text-blue-600" />
                            </div>
                            <h4 className="font-black text-slate-900">Product Page Details</h4>
                          </div>

                          <FieldGroup label="Detailed Description" help="The main paragraph describing the product on the detail page.">
                            <textarea
                              value={editingItem.description || ''}
                              onChange={(e) => setEditingItem({ ...editingItem, description: e.target.value })}
                              className="w-full p-4 bg-slate-50 dark:bg-slate-800 rounded-2xl font-bangla text-sm font-bold min-h-[120px] outline-none focus:ring-2 focus:ring-red-600 placeholder-slate-950 text-slate-950"
                              placeholder="Type product description..."
                            />
                          </FieldGroup>

                          <FieldGroup label="Assurance & Benefits (খাঁটিত্বের নিশ্চয়তা)" help="Bullet points shown with green checkmarks.">
                            <div className="space-y-3">
                              {(editingItem.usage || []).map((point: string, i: number) => (
                                <div key={i} className="flex items-center gap-3">
                                  <input
                                    type="text"
                                    value={point}
                                    onChange={(e) => {
                                      let n = [...(editingItem.usage || [])];
                                      n[i] = e.target.value;
                                      setEditingItem({ ...editingItem, usage: n });
                                    }}
                                    className="flex-1 bg-slate-50 dark:bg-slate-800 rounded-xl px-4 py-3 font-bold text-sm outline-none focus:ring-2 focus:ring-red-600 font-bangla text-slate-950 placeholder-slate-950"
                                    placeholder="E.g. ১০০% ন্যাচারাল"
                                  />
                                  <button onClick={() => {
                                    let n = [...(editingItem.usage || [])];
                                    n.splice(i, 1);
                                    setEditingItem({ ...editingItem, usage: n });
                                  }} className="p-3 bg-red-50 text-red-600 rounded-xl hover:bg-red-100"><Trash2 size={16} /></button>
                                </div>
                              ))}
                              <button
                                onClick={() => setEditingItem({ ...editingItem, usage: [...(editingItem.usage || []), ""] })}
                                className="w-full p-4 border-2 border-dashed border-slate-200 dark:border-slate-700 rounded-xl font-bold text-slate-950 hover:text-red-600 hover:border-red-200"
                              >
                                + Add Point
                              </button>
                            </div>
                          </FieldGroup>

                          <FieldGroup label="Glassmorphism Features (USPs)" help="The 4 floating benefit cards.">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                              {(editingItem.features || []).map((f: any, i: number) => (
                                <div key={i} className="p-4 border rounded-2xl bg-white dark:bg-slate-800 relative group">
                                  <button onClick={() => {
                                    let n = [...(editingItem.features || [])];
                                    n.splice(i, 1);
                                    setEditingItem({ ...editingItem, features: n });
                                  }} className="absolute top-2 right-2 text-red-400 opacity-0 group-hover:opacity-100 transition-opacity"><Trash2 size={14} /></button>
                                  <div className="space-y-3">
                                    <input
                                      type="text"
                                      value={f.title || ""}
                                      onChange={(e) => {
                                        let n = [...(editingItem.features || [])];
                                        n[i] = { ...n[i], title: e.target.value };
                                        setEditingItem({ ...editingItem, features: n });
                                      }}
                                      className="w-full bg-slate-50 dark:bg-slate-900 rounded-lg px-3 py-2 text-sm font-bold font-bangla text-slate-950 placeholder-slate-950"
                                      placeholder="Card Title (e.g. সেরা কোয়ালিটি)"
                                    />
                                  </div>
                                </div>
                              ))}
                            </div>
                            {(editingItem.features || []).length < 4 && (
                              <button
                                onClick={() => setEditingItem({ ...editingItem, features: [...(editingItem.features || []), { title: "", icon: "check" }] })}
                                className="mt-4 px-6 py-3 bg-slate-100 dark:bg-slate-800 text-slate-950 rounded-xl font-bold text-sm w-full hover:bg-slate-200"
                              >
                                + Add Feature Card
                              </button>
                            )}
                          </FieldGroup>

                        </div>
                      )}

                    </div>
                  </div>
                </div>
              ) : null}
            </div>
          ) : (
            <div className="animate-fade-in-up space-y-12">
              {activeTab === 'dashboard' && canAccess('dashboard') && (
                <DashboardOverview
                  orders={orders}
                  leads={uniqueLeads}
                  products={products}
                  currentUser={currentUser}
                  settings={settings}
                  activeTab={activeTab}
                  adminBanners={adminBanners}
                  testimonials={testimonials}
                  todayPageViews={todayPageViews}
                  initiatedCheckouts={initiatedCheckouts}
                  analyticsPeriod={analyticsPeriod}
                  setAnalyticsPeriod={setAnalyticsPeriod}
                  analyticsStart={analyticsStart}
                  setAnalyticsStart={setAnalyticsStart}
                  analyticsEnd={analyticsEnd}
                  setAnalyticsEnd={setAnalyticsEnd}
                />
              )}

              {activeTab === 'orders' && canAccess('orders') && (
                <OrdersManager
                  orders={orders}
                  updateOrders={updateOrders}
                  products={products}
                  canAccess={canAccess}
                  showToast={showToast}
                  deleteItem={deleteItem}
                  getTenantHeaders={getTenantHeaders}
                  getBanglaName={getBanglaName}
                />
              )}
              {activeTab === 'leads' && canAccess('leads') && (
                <LeadsManager
                  leads={leads}
                  updateLeads={updateLeads}
                  orders={orders}
                  updateOrders={updateOrders}
                  canAccess={canAccess}
                  showToast={showToast}
                  deleteItem={deleteItem}
                  getTenantHeaders={getTenantHeaders}
                  setActiveTab={setActiveTab}
                />
              )}

              {activeTab === 'pages' && canAccess('pages') && (
                <CustomPagesEditor settings={settings} updateSettings={async (updates) => { updateSettings({ ...settings, ...updates }); }} />
              )}

              {activeTab === 'landing-editor' && canAccess('landing-editor') && (
                <div className="space-y-12">
                  <div className="bg-white dark:bg-slate-900 p-12 rounded-[48px] border shadow-sm relative overflow-hidden">
                    <div className="absolute top-0 right-0 w-96 h-96 bg-red-50 dark:bg-red-950/20 rounded-full translate-x-1/2 -translate-y-1/2 blur-3xl -z-10"></div>
                    <h2 className="text-5xl font-black mb-4">Landing Designer</h2>
                    <p className="text-lg text-slate-500 dark:text-slate-400 max-w-2xl font-medium">Select a product to design its high-conversion custom sales page with split preview.</p>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                    {products.map(p => (
                      <button
                        key={p.id}
                        onClick={() => canAccess('landing-editor', 'edit') ? setEditingItem(p) : showToast('Access denied', 'error')}
                        className="flex items-center gap-6 p-8 bg-white dark:bg-slate-900 rounded-[32px] border-2 border-transparent hover:border-red-600 transition-all text-left shadow-sm group"
                      >
                        <img src={p.image || undefined} className="w-20 h-20 rounded-2xl object-cover ring-4 ring-slate-50" />
                        <div>
                          <p className="font-black text-lg font-bangla group-hover:text-red-600 transition-colors">{getBanglaName(p.nameBangla, p.name)}</p>
                          <p className="text-[10px] font-medium text-slate-500 dark:text-slate-400 uppercase tracking-widest mt-0.5">{p.name}</p>
                          <span className="inline-block mt-3 px-4 py-1.5 bg-slate-50 dark:bg-slate-800 rounded-full text-[8px] font-black uppercase tracking-widest text-slate-500 dark:text-slate-400 group-hover:text-red-600 transition-all">Edit Page</span>
                        </div>
                      </button>
                    ))}
                  </div>
                </div>
              )}



              {activeTab === 'home-editor' && canAccess('landing-editor') && (
                <HomePageEditor
                  settings={settings}
                  products={products}
                  onSave={saveSiteSettings}
                  onUploadImage={uploadImageToPHP}
                />
              )}

              {['contact', 'social', 'pixel'].includes(activeTab) && (
                <StoreSettingsManager
                  activeTab={activeTab}
                  settings={settings}
                  canAccess={canAccess}
                  saveSiteSettings={saveSiteSettings}
                  isSaving={isSaving}
                />
              )}
              {/* ── MY PLAN TAB ─────────────────────────────────────────────── */}
              {activeTab === 'my-plan' && (
                <MyPlanTab tenantToken={localStorage.getItem('tenant_token') || ''} />
              )}

              {/* ── DOMAIN NAME TAB ──────────────────────────────────────────── */}
              {activeTab === 'domain' && (
                <DomainTab tenantToken={localStorage.getItem('tenant_token') || ''} />
              )}

              {activeTab === 'appearance' && canAccess('appearance') && (
                <AppearanceManager
                  settings={settings}
                  saveSiteSettings={saveSiteSettings}
                  isSaving={isSaving}
                  canAccess={canAccess}
                  uploadImageToPHP={uploadImageToPHP}
                  updateSettings={updateSettings}
                />
              )}
              {activeTab === 'categories' && canAccess('products') && (
                <CategoryManager settings={settings} onSave={saveSiteSettings} onUploadImage={uploadImageToPHP} />
              )}

              {activeTab === 'products' && canAccess('products') && (
                <ProductManager
                  products={products}
                  setEditingItem={setEditingItem}
                  canAccess={canAccess}
                  showToast={showToast}
                  deleteItem={deleteItem}
                  getBanglaName={getBanglaName}
                />
              )}
              {activeTab === 'reviews' && canAccess('testimonials') && (
                <TestimonialsManager
                  testimonials={testimonials}
                  setEditingItem={setEditingItem}
                  canAccess={canAccess}
                  deleteItem={deleteItem}
                  showToast={showToast}
                />
              )}
            </div>
          )}
        </div>
        {/* ── Stock Management ─────────────────────────────────── */}
        {activeTab === 'stock' && (
          <StockTab
            products={products}
            updateProducts={updateProducts}
            API_BASE={API_BASE}
            showToast={showToast}
          />
        )}

      </main>

      {/* Ubaidi AI — Admin shop assistant */}
      {(() => {
        const todayStr = new Date().toISOString().split('T')[0];
        const todayOrders = (orders || []).filter((o: any) => o.date && o.date.startsWith(todayStr));
        const todaySales = todayOrders.reduce((sum: number, o: any) => sum + (Number(o.total) || 0), 0);
        const totalSales = (orders || []).reduce((sum: number, o: any) => sum + (Number(o.total) || 0), 0);
        
        const adminAiExtra = {
          todaySales: todaySales,
          todayOrdersCount: todayOrders.length,
          totalSales: totalSales,
          totalOrdersCount: (orders || []).length
        };

        return (
          <UbaidiChat 
            context="admin" 
            tenantToken={localStorage.getItem('tenant_token') || undefined} 
            apiBase={API_BASE} 
            extra={adminAiExtra}
          />
        );
      })()}
      {/* Edit / Create Order Modal */}

      {/* ── MOBILE BOTTOM NAV (md:hidden) ──────────────────── */}
      <nav className="md:hidden fixed bottom-0 left-0 right-0 z-[100] bg-white border-t border-slate-200 shadow-[0_-10px_20px_rgba(0,0,0,0.03)] pb-safe">
        <div className="flex items-center justify-around h-16">
          {mobileTabs.map((tab) => {
            const isActive = activeTab === tab.id || (tab.id === 'products' && (activeTab === 'categories' || activeTab === 'stock' || activeTab === 'reviews' || activeTab === 'marketing')) || (tab.id === 'home-editor' && (activeTab === 'landing-editor' || activeTab === 'pages')) || (tab.id === 'appearance' && (activeTab === 'social' || activeTab === 'pixel' || activeTab === 'courier-settings'));

            return (
              <button
                key={tab.id}
                onClick={() => canAccess(tab.id === 'home-editor' ? 'landing-editor' : tab.id) ? setActiveTab(tab.id as any) : showToast('Access denied', 'error')}
                className="relative flex flex-col items-center justify-center w-full h-full space-y-1"
              >
                <div className={`p-1.5 rounded-xl transition-all duration-300 ${isActive ? 'bg-purple-100/50 text-purple-600 scale-110' : 'text-slate-500 dark:text-slate-400 hover:text-slate-600'}`}>
                  {tab.icon}
                  {tab.badge && tab.badge > 0 && (
                    <span className="absolute top-1.5 right-6 w-4 h-4 bg-red-500 text-white text-[9px] font-black rounded-full flex items-center justify-center border-2 border-white shadow-sm">
                      {tab.badge}
                    </span>
                  )}
                </div>
                <span className={`text-[9px] font-bold transition-all duration-300 ${isActive ? 'text-purple-600' : 'text-slate-500 dark:text-slate-400'}`}>
                  {tab.label}
                </span>
                {isActive && (
                  <div className="absolute top-0 w-8 h-0.5 bg-purple-600 rounded-b-full shadow-[0_2px_8px_rgba(147,51,234,0.5)]" />
                )}
              </button>
            )
          })}
        </div>
      </nav>

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 6px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 10px; }
        
        @keyframes slide-in-right {
          0% { transform: translateX(100%); opacity: 0; }
          100% { transform: translateX(0); opacity: 1; }
        }
        .animate-slide-in-right {
          animation: slide-in-right 0.3s ease-out forwards;
        }
        
        @keyframes fade-in-up {
          0% { opacity: 0; transform: translateY(20px); }
          100% { opacity: 1; transform: translateY(0); }
        }
        .animate-fade-in-up {
          animation: fade-in-up 0.5s ease-out forwards;
        }

        .pb-safe { padding-bottom: env(safe-area-inset-bottom); }
        /* Admin mobile: main content starts below top header */
        @media (max-width: 767px) {
          .admin-main-inner { padding-bottom: 0 !important; }
        }
        @media (min-width: 768px) {
          .admin-main-inner { padding-bottom: 40px !important; }
        }
      `}</style>

      {/* ── Webcam Capture Modal ────────────────────────────── */}
      {showWebcam && (
        <div className="fixed inset-0 z-[9999] bg-black/95 flex flex-col items-center justify-center">
          <div className="w-full max-w-xl flex flex-col items-center gap-4 px-4">
            <div className="flex items-center justify-between w-full">
              <div className="flex items-center gap-2 text-slate-800 dark:text-white">
                <Camera size={20} className="text-violet-400" />
                <span className="font-black text-sm">ছবি তুলুন</span>
              </div>
              <button onClick={closeWebcam} className="w-9 h-9 bg-white/10 hover:bg-white/20 rounded-full flex items-center justify-center text-slate-800 dark:text-white transition-all">
                <X size={18} />
              </button>
            </div>
            <div className="relative w-full rounded-2xl overflow-hidden bg-slate-900 aspect-video shadow-2xl border border-white/10">
              <video ref={webcamVideoRef} autoPlay playsInline muted className="w-full h-full object-cover" />
              <div className="absolute top-3 left-3 w-6 h-6 border-l-2 border-t-2 border-violet-400 rounded-tl" />
              <div className="absolute top-3 right-3 w-6 h-6 border-r-2 border-t-2 border-violet-400 rounded-tr" />
              <div className="absolute bottom-3 left-3 w-6 h-6 border-l-2 border-b-2 border-violet-400 rounded-bl" />
              <div className="absolute bottom-3 right-3 w-6 h-6 border-r-2 border-b-2 border-violet-400 rounded-br" />
            </div>
            <button
              onClick={captureFromWebcam}
              disabled={isSaving}
              className="w-16 h-16 rounded-full bg-white border-4 border-violet-500 shadow-xl hover:scale-110 active:scale-95 transition-all flex items-center justify-center text-2xl disabled:opacity-60"
            >
              {isSaving ? '⏳' : '📸'}
            </button>
            <p className="text-slate-800 dark:text-white/50 text-xs text-center">বড় বোতামে ট্যাপ করুন — ছবি সরাসরি প্রোডাক্টে যোগ হবে</p>
          </div>
        </div>
      )}

    </div>

  );
};

// ─── MessengerAIAgentPanel Component ─────────────────────────────────────────
export default AdminDashboard;
