import React, { useState } from 'react';
import { normalizeUrl, normalizeFacebookUrl } from '../../utils/urlValidation';
import {
  X,
  LayoutDashboard,
  ListOrdered,
  FolderTree,
  CreditCard,
  Palette,
  Type,
  Languages,
  Menu as MenuIcon,
  FileText,
  Settings,
  Download,
  Lock,
  LogOut,
  Plus,
  Trash2,
  Edit2,
  Check,
  AlertTriangle,
  Search,
  Eye,
  EyeOff,
  ExternalLink,
  Shield,
  RefreshCw,
  Sparkles,
  DollarSign,
  MousePointerClick,
  Heart,
  Users,
  RotateCcw,
  Globe,
  ArrowUp,
  ArrowDown,
  ChevronUp,
  ChevronDown,
  ArrowUpDown,
  Layers,
  MoveUp,
  MoveDown,
  Upload,
  Image as ImageIcon,
  Code,
  Link as LinkIcon,
  Receipt,
  Activity
} from 'lucide-react';
import { useApp } from '../../context/AppContext';
import { Listing, Category, MenuItem, GatewayConfig, ContentPage, TranslationDictionary, FloatingScrollPopup } from '../../types';
import { INITIAL_GATEWAYS } from '../../data/initialData';
import { getCategoryIcon } from '../CategoryNav';

export const AdminPanel: React.FC = () => {
  const {
    state,
    listings,
    categories,
    payments,
    menuItems,
    settings,
    design,
    texts,
    developer,
    scrollPopup,
    gateways,
    pages,
    totalGeneratedMoney,
    isAdminLoggedIn,
    language,
    translations,
    setLanguage,
    adminSaveTranslations,
    adminResetTranslations,
    closeAdmin,
    adminLogin,
    adminLogout,
    adminSaveListing,
    adminDeleteListing,
    adminToggleListingStatus,
    adminSaveCategory,
    adminDeleteCategory,
    adminReorderCategories,
    adminMoveCategory,
    adminToggleCategoryStatus,
    adminSetCategoryOrder,
    adminSaveDesign,
    adminSaveTexts,
    adminSaveSettings,
    adminSaveDeveloper,
    adminSaveScrollPopup,
    adminSaveGateways,
    adminSaveMenuItems,
    adminSavePage,
    adminResetData,
    visitorSettings,
    adminUpdateVisitorSettings,
    adminResetVisitorStats,
    adminDeleteTransaction,
    adminClearAllTransactions,
    adminResetListingStats,
    adminDeleteUserTransactions,
  } = useApp();

  const [activeTab, setActiveTab] = useState<
    'dashboard' | 'listings' | 'categories' | 'payments' | 'transactions' | 'visitors' | 'reset_center' | 'design' | 'texts' | 'translations' | 'popup' | 'menu' | 'pages' | 'settings' | 'download'
  >('dashboard');

  // Login form state
  const [loginPassword, setLoginPassword] = useState('');
  const [loginError, setLoginError] = useState('');

  // Editing states
  const [editingListing, setEditingListing] = useState<Partial<Listing> | null>(null);
  const [listingSearch, setListingSearch] = useState('');
  const [editingCategory, setEditingCategory] = useState<Partial<Category> | null>(null);
  const [categorySearch, setCategorySearch] = useState('');
  const [editingMenu, setEditingMenu] = useState<Partial<MenuItem> | null>(null);
  const [menuFilter, setMenuFilter] = useState<'all' | 'header' | 'footer' | 'both'>('all');
  const [isAddingMenu, setIsAddingMenu] = useState(false);
  const [newMenuTitle, setNewMenuTitle] = useState('');
  const [newMenuUrl, setNewMenuUrl] = useState('');
  const [newMenuDesc, setNewMenuDesc] = useState('');
  const [newMenuLocation, setNewMenuLocation] = useState<'header' | 'footer' | 'both'>('both');
  const [newMenuTarget, setNewMenuTarget] = useState<'_self' | '_blank'>('_self');
  const [newMenuOpenAs, setNewMenuOpenAs] = useState<'link' | 'modal'>('link');

  // Transaction Filters
  const [transactionSearch, setTransactionSearch] = useState('');
  const [transactionGatewayFilter, setTransactionGatewayFilter] = useState('all');
  const [transactionStatusFilter, setTransactionStatusFilter] = useState('all');

  // Visitor Settings Local State
  const [tempVisitorSettings, setTempVisitorSettings] = useState(visitorSettings);
  const [customBaselineActive, setCustomBaselineActive] = useState(visitorSettings.baseline_active || 0);
  const [customBaselineTotal, setCustomBaselineTotal] = useState(visitorSettings.baseline_total || 1317970);

  // Sync temp visitor settings when context updates
  React.useEffect(() => {
    setTempVisitorSettings(visitorSettings);
    setCustomBaselineActive(visitorSettings.baseline_active || 0);
    setCustomBaselineTotal(visitorSettings.baseline_total || 1317970);
  }, [visitorSettings]);

  // Local copy for forms
  const [tempDesign, setTempDesign] = useState(design);
  const [tempTexts, setTempTexts] = useState(texts);
  const [tempSettings, setTempSettings] = useState(settings);
  const [tempGateways, setTempGateways] = useState(gateways);
  const [tempDev, setTempDev] = useState(developer);
  const [tempScrollPopup, setTempScrollPopup] = useState<FloatingScrollPopup>(scrollPopup);
  const [activePageEdit, setActivePageEdit] = useState<'rules' | 'terms' | 'privacy' | 'stats'>('rules');
  const [tempPageContent, setTempPageContent] = useState('');
  const [showUddoktaPayApiKey, setShowUddoktaPayApiKey] = useState(false);
  const [testingGatewayId, setTestingGatewayId] = useState<string | null>(null);
  const [testConnectionResult, setTestConnectionResult] = useState<{ gatewayId: string; success: boolean; message: string } | null>(null);

  const handleTestConnection = async (gw: GatewayConfig) => {
    setTestingGatewayId(gw.id);
    setTestConnectionResult(null);
    try {
      const res = await fetch('/api/admin/payments/test-connection', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ gatewayId: gw.id, config: gw }),
      });
      const data = await res.json();
      if (data.success) {
        setTestConnectionResult({ gatewayId: gw.id, success: true, message: data.message || 'Connection successful!' });
        showToast(data.message || 'Test Connection Successful!');
      } else {
        setTestConnectionResult({ gatewayId: gw.id, success: false, message: data.message || 'Connection failed.' });
        showToast(data.message || 'Test Connection Failed');
      }
    } catch (err: any) {
      setTestConnectionResult({ gatewayId: gw.id, success: false, message: err.message || 'Network error' });
      showToast('Test Connection Error: ' + err.message);
    } finally {
      setTestingGatewayId(null);
    }
  };

  const moveMenuItem = (index: number, direction: 'up' | 'down') => {
    const sorted = [...menuItems].sort((a, b) => a.display_order - b.display_order);
    const targetIndex = direction === 'up' ? index - 1 : index + 1;
    if (targetIndex < 0 || targetIndex >= sorted.length) return;
    const temp = sorted[index];
    sorted[index] = sorted[targetIndex];
    sorted[targetIndex] = temp;
    const updated = sorted.map((item, idx) => ({ ...item, display_order: idx + 1 }));
    adminSaveMenuItems(updated);
    showToast('Menu order updated');
  };

  // Translation manager states
  const [tempTranslations, setTempTranslations] = useState<TranslationDictionary>(translations);
  const [translationSearch, setTranslationSearch] = useState('');
  const [translationCategoryFilter, setTranslationCategoryFilter] = useState('all');
  const [isAddingTranslation, setIsAddingTranslation] = useState(false);
  const [newTransKey, setNewTransKey] = useState('');
  const [newTransCategory, setNewTransCategory] = useState('General');
  const [newTransEn, setNewTransEn] = useState('');
  const [newTransBn, setNewTransBn] = useState('');

  const [toastMessage, setToastMessage] = useState('');

  const showToast = (msg: string) => {
    setToastMessage(msg);
    setTimeout(() => setToastMessage(''), 3000);
  };

  // Sync temp state when global context state updates
  React.useEffect(() => {
    setTempDesign(design);
  }, [design]);

  React.useEffect(() => {
    setTempTexts(texts);
  }, [texts]);

  React.useEffect(() => {
    setTempSettings(settings);
  }, [settings]);

  React.useEffect(() => {
    setTempDev(developer);
  }, [developer]);

  React.useEffect(() => {
    setTempScrollPopup(scrollPopup);
  }, [scrollPopup]);

  React.useEffect(() => {
    // Ensure all initial gateways are merged so newly added gateways like aamarpay are never omitted
    const map = new Map<string, GatewayConfig>();
    INITIAL_GATEWAYS.forEach(ig => map.set(ig.id, { ...ig }));
    gateways.forEach(g => map.set(g.id, { ...(map.get(g.id) || {}), ...g }));
    setTempGateways(Array.from(map.values()));
  }, [gateways]);

  React.useEffect(() => {
    if (state.isAdminOpen && isAdminLoggedIn) {
      fetch('/api/admin/gateways')
        .then(res => res.json())
        .then(data => {
          if (data.success && Array.isArray(data.gateways) && data.gateways.length > 0) {
            const map = new Map<string, GatewayConfig>();
            INITIAL_GATEWAYS.forEach(ig => map.set(ig.id, { ...ig }));
            gateways.forEach(g => map.set(g.id, { ...(map.get(g.id) || {}), ...g }));
            data.gateways.forEach((sg: any) => {
              const cur = map.get(sg.id);
              map.set(sg.id, {
                ...(cur || sg),
                ...sg,
              });
            });
            setTempGateways(Array.from(map.values()));
          }
        })
        .catch(() => {});
    }
  }, [state.isAdminOpen, isAdminLoggedIn]);

  // Sync temp translations when global translations change
  React.useEffect(() => {
    setTempTranslations(translations);
  }, [translations]);

  const handleScrollPopupImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 3 * 1024 * 1024) {
      alert('Image size exceeds 3MB. Please choose a smaller image.');
      return;
    }
    const reader = new FileReader();
    reader.onload = (event) => {
      if (typeof event.target?.result === 'string') {
        setTempScrollPopup(prev => ({
          ...prev,
          avatar_image_url: event.target?.result as string
        }));
        showToast('Image uploaded successfully!');
      }
    };
    reader.readAsDataURL(file);
  };

  if (!state.isAdminOpen) return null;

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    if (adminLogin(loginPassword)) {
      setLoginError('');
      setLoginPassword('');
    } else {
      setLoginError('Invalid password. (Default: admin123)');
    }
  };

  // If not logged in, render Admin Login Modal
  if (!isAdminLoggedIn) {
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/85 backdrop-blur-md animate-in fade-in">
        <div className="w-full max-w-md rounded-2xl border border-[#2A3440] bg-[#11161B] p-6 sm:p-8 shadow-2xl space-y-5">
          <div className="flex items-center justify-between border-b border-[#222A33] pb-4">
            <div className="flex items-center gap-2.5">
              <div className="w-9 h-9 rounded-xl bg-emerald-600/20 border border-emerald-500/40 flex items-center justify-center text-emerald-400">
                <Shield className="w-5 h-5" />
              </div>
              <div>
                <h3 className="font-bold text-lg text-white">TOPBD Admin Portal</h3>
                <p className="text-xs text-slate-400">Enter administrator password</p>
              </div>
            </div>
            <button onClick={closeAdmin} className="text-slate-400 hover:text-white p-1">
              <X className="w-5 h-5" />
            </button>
          </div>

          <form onSubmit={handleLogin} className="space-y-4">
            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-slate-300">Password</label>
              <div className="relative">
                <Lock className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
                <input
                  type="password"
                  required
                  autoFocus
                  value={loginPassword}
                  onChange={e => setLoginPassword(e.target.value)}
                  placeholder="Enter admin password (admin123)"
                  className="w-full pl-9 pr-4 py-2.5 bg-[#0A0D0F] border border-[#222A33] focus:border-emerald-500 rounded-xl text-sm text-white focus:outline-none"
                />
              </div>
              <p className="text-[11px] text-slate-500">Default demo password is: <code className="text-emerald-400">admin123</code></p>
            </div>

            {loginError && (
              <div className="p-2.5 rounded-lg bg-rose-950/50 border border-rose-800/60 text-rose-300 text-xs">
                {loginError}
              </div>
            )}

            <button
              type="submit"
              className="w-full py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-sm shadow-md transition-all cursor-pointer"
            >
              Sign In to Admin
            </button>
          </form>
        </div>
      </div>
    );
  }

  // Active listings count & metrics
  const activeListingsCount = listings.filter(l => l.is_active).length;
  const totalClicks = listings.reduce((acc, l) => acc + l.clicks, 0);
  const totalHearts = listings.reduce((acc, l) => acc + l.hearts, 0);
  const verifiedPaymentsCount = payments.filter(p => p.status === 'success').length;

  return (
    <div className="fixed inset-0 z-50 flex bg-black/90 backdrop-blur-md overflow-hidden animate-in fade-in">
      {/* Admin Sidebar */}
      <aside className="w-64 border-r border-[#222A33] bg-[#0E1216] flex flex-col shrink-0">
        {/* Brand Header */}
        <div className="p-4 border-b border-[#222A33] flex items-center justify-between">
          <div className="flex items-center gap-2">
            <div className="w-7 h-7 rounded-lg bg-emerald-600 flex items-center justify-center text-white font-bold text-xs">
              BD
            </div>
            <div>
              <span className="font-extrabold text-sm text-white font-mono">TOPBD ADMIN</span>
              <span className="text-[10px] text-emerald-400 block font-mono">v1.0 Production</span>
            </div>
          </div>
          <button onClick={closeAdmin} className="text-slate-400 hover:text-white sm:hidden">
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Sidebar Nav Items */}
        <nav className="flex-1 p-3 space-y-1 overflow-y-auto text-xs font-semibold">
          {[
            { id: 'dashboard', label: 'Dashboard', icon: LayoutDashboard },
            { id: 'listings', label: 'Listings Manager', icon: ListOrdered },
            { id: 'categories', label: 'Categories CRUD', icon: FolderTree },
            { id: 'payments', label: 'Payment Gateways', icon: CreditCard },
            { id: 'transactions', label: 'Transactions & Logs', icon: Receipt },
            { id: 'visitors', label: 'Visitor Counters & Traffic', icon: Activity },
            { id: 'reset_center', label: 'Data Reset & Wipe Center', icon: RotateCcw },
            { id: 'design', label: 'Design Customizer', icon: Palette },
            { id: 'texts', label: 'Frontend Texts', icon: Type },
            { id: 'translations', label: 'Translations (EN/BN)', icon: Languages },
            { id: 'popup', label: 'Scroll Popup (Built by)', icon: Sparkles },
            { id: 'menu', label: 'Navigation Menu', icon: MenuIcon },
            { id: 'pages', label: 'Content Pages', icon: FileText },
            { id: 'settings', label: 'General & SEO / Reset', icon: Settings },
            { id: 'download', label: 'Export Standalone ZIP', icon: Download },
          ].map(tab => {
            const Icon = tab.icon;
            const isActive = activeTab === tab.id;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-xl transition-all text-left ${
                  isActive
                    ? 'bg-emerald-600 text-white shadow-sm'
                    : 'text-slate-400 hover:text-slate-200 hover:bg-[#151C22]'
                }`}
              >
                <Icon className="w-4 h-4 shrink-0" />
                <span>{tab.label}</span>
              </button>
            );
          })}
        </nav>

        {/* User / Logout */}
        <div className="p-3 border-t border-[#222A33] flex items-center justify-between">
          <div className="text-xs">
            <span className="text-white font-bold block">Administrator</span>
            <span className="text-[10px] text-slate-500 font-mono">admin@topbd.app</span>
          </div>
          <button
            onClick={adminLogout}
            title="Log Out"
            className="p-1.5 rounded-lg bg-[#141A20] text-rose-400 hover:bg-rose-950/50 transition-colors"
          >
            <LogOut className="w-4 h-4" />
          </button>
        </div>
      </aside>

      {/* Main Admin Content Area */}
      <main className="flex-1 flex flex-col bg-[#0A0D0F] overflow-hidden">
        {/* Top bar */}
        <header className="h-14 border-b border-[#222A33] bg-[#0E1216] px-6 flex items-center justify-between gap-4 shrink-0">
          <div className="flex items-center gap-2">
            <h2 className="font-bold text-sm sm:text-base text-white capitalize font-mono">
              {activeTab.replace('_', ' ')} Management
            </h2>
            {toastMessage && (
              <span className="text-xs px-2.5 py-1 rounded-full bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 animate-in fade-in">
                {toastMessage}
              </span>
            )}
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={() => {
                window.open('/', '_blank');
              }}
              className="text-xs text-slate-400 hover:text-white flex items-center gap-1 bg-[#141A20] px-3 py-1.5 rounded-lg border border-[#222A33]"
            >
              <span>View Frontend</span>
              <ExternalLink className="w-3 h-3" />
            </button>
            <button
              onClick={closeAdmin}
              className="p-1.5 rounded-lg bg-[#141A20] text-slate-400 hover:text-white"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </header>

        {/* Tab Content Panels */}
        <div className="flex-1 p-6 overflow-y-auto space-y-6">
          {/* TAB 1: DASHBOARD */}
          {activeTab === 'dashboard' && (
            <div className="space-y-6">
              {/* Metrics Grid */}
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                <div className="p-4 rounded-2xl bg-[#13181D] border border-[#222A33]">
                  <div className="flex items-center justify-between text-slate-400 text-xs mb-1">
                    <span>Total Revenue</span>
                    <DollarSign className="w-4 h-4 text-emerald-400" />
                  </div>
                  <div className="text-2xl font-black font-mono text-emerald-400">
                    ৳{totalGeneratedMoney.toLocaleString()}
                  </div>
                  <span className="text-[10px] text-slate-500">Verified successful payments</span>
                </div>

                <div className="p-4 rounded-2xl bg-[#13181D] border border-[#222A33]">
                  <div className="flex items-center justify-between text-slate-400 text-xs mb-1">
                    <span>Active Listings</span>
                    <ListOrdered className="w-4 h-4 text-amber-400" />
                  </div>
                  <div className="text-2xl font-black font-mono text-white">
                    {activeListingsCount} <span className="text-xs text-slate-500 font-normal">/ {listings.length}</span>
                  </div>
                  <span className="text-[10px] text-slate-500">On live leaderboard</span>
                </div>

                <div className="p-4 rounded-2xl bg-[#13181D] border border-[#222A33]">
                  <div className="flex items-center justify-between text-slate-400 text-xs mb-1">
                    <span>Live Visitors</span>
                    <Users className="w-4 h-4 text-sky-400" />
                  </div>
                  <div className="text-2xl font-black font-mono text-sky-400">
                    {state.activeVisitors}
                  </div>
                  <span className="text-[10px] text-slate-500">Heartbeat active sessions</span>
                </div>

                <div className="p-4 rounded-2xl bg-[#13181D] border border-[#222A33]">
                  <div className="flex items-center justify-between text-slate-400 text-xs mb-1">
                    <span>Total Clicks & Hearts</span>
                    <MousePointerClick className="w-4 h-4 text-rose-400" />
                  </div>
                  <div className="text-2xl font-black font-mono text-white">
                    {totalClicks + totalHearts}
                  </div>
                  <span className="text-[10px] text-slate-500">{totalClicks} clicks · {totalHearts} hearts</span>
                </div>
              </div>

              {/* Recent Bids & Payments Table */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Recent Payments */}
                <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-3">
                  <h3 className="font-bold text-sm text-white flex items-center justify-between">
                    <span>Recent Verified Payments</span>
                    <span className="text-xs font-mono text-emerald-400">{verifiedPaymentsCount} total</span>
                  </h3>

                  <div className="divide-y divide-[#222A33] max-h-64 overflow-y-auto">
                    {payments.slice(0, 8).map(pay => (
                      <div key={pay.id} className="py-2.5 flex items-center justify-between text-xs">
                        <div>
                          <div className="font-bold text-white truncate max-w-[160px]">{pay.listing_name}</div>
                          <div className="text-[10px] text-slate-500 font-mono">{pay.transaction_id} · {pay.gateway.toUpperCase()}</div>
                        </div>
                        <div className="text-right">
                          <div className="font-mono font-bold text-emerald-400">৳{pay.amount.toLocaleString()}</div>
                          <span className={`text-[9px] px-1.5 py-0.2 rounded uppercase font-mono ${pay.status === 'success' ? 'bg-emerald-950 text-emerald-400' : 'bg-amber-950 text-amber-400'}`}>
                            {pay.status}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Top Listings */}
                <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-3">
                  <h3 className="font-bold text-sm text-white flex items-center justify-between">
                    <span>Current Top Ranked Listings</span>
                    <button
                      onClick={() => setActiveTab('listings')}
                      className="text-xs text-emerald-400 hover:underline"
                    >
                      Manage all
                    </button>
                  </h3>

                  <div className="divide-y divide-[#222A33] max-h-64 overflow-y-auto">
                    {listings.slice(0, 8).map((list, idx) => (
                      <div key={list.id} className="py-2.5 flex items-center justify-between text-xs">
                        <div className="flex items-center gap-2.5">
                          <span className="font-mono font-bold text-slate-500 w-5">#{idx + 1}</span>
                          <img src={list.image_url} alt="" className="w-7 h-7 rounded-lg object-cover" />
                          <div className="truncate max-w-[140px]">
                            <div className="font-bold text-white truncate">{list.name}</div>
                            <div className="text-[10px] text-slate-500">{list.category_name}</div>
                          </div>
                        </div>
                        <div className="text-right font-mono font-bold text-emerald-400">
                          ৳{list.current_bid.toLocaleString()}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* TAB 2: LISTINGS CRUD */}
          {activeTab === 'listings' && (
            <div className="space-y-4">
              <div className="flex flex-col sm:flex-row items-center justify-between gap-3">
                <div className="relative w-full sm:w-72">
                  <Search className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
                  <input
                    type="text"
                    placeholder="Search listings..."
                    value={listingSearch}
                    onChange={e => setListingSearch(e.target.value)}
                    className="w-full pl-9 pr-3 py-2 bg-[#13181D] border border-[#222A33] rounded-xl text-xs text-white focus:outline-none focus:border-emerald-500"
                  />
                </div>
                <div className="flex items-center gap-2 w-full sm:w-auto">
                  <button
                    onClick={() => {
                      if (confirm('Reset clicks & hearts on ALL listings to 0?')) {
                        adminResetListingStats('all', 'all');
                        showToast('All listing clicks & hearts reset to 0');
                      }
                    }}
                    className="px-3 py-2 rounded-xl bg-sky-950 hover:bg-sky-900 border border-sky-800 text-sky-300 font-bold text-xs flex items-center justify-center gap-1.5 cursor-pointer"
                  >
                    <RotateCcw className="w-3.5 h-3.5" />
                    <span>Reset All Clicks</span>
                  </button>
                  <button
                    onClick={() => setEditingListing({ is_active: true, current_bid: 1000, category_id: categories[0]?.id || 'cat_biz' })}
                    className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs flex items-center justify-center gap-1.5 cursor-pointer"
                  >
                    <Plus className="w-4 h-4" />
                    <span>Add Listing Manually</span>
                  </button>
                </div>
              </div>

              {/* Listings Table */}
              <div className="rounded-2xl border border-[#222A33] bg-[#13181D] overflow-hidden">
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-xs">
                    <thead className="bg-[#0E1216] text-slate-400 font-mono text-[11px] border-b border-[#222A33]">
                      <tr>
                        <th className="p-3">Rank & Entity</th>
                        <th className="p-3">Category</th>
                        <th className="p-3">Current Bid</th>
                        <th className="p-3">Engagement</th>
                        <th className="p-3">Status</th>
                        <th className="p-3 text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-[#222A33] text-slate-300">
                      {listings
                        .filter(l => l.name.toLowerCase().includes(listingSearch.toLowerCase()) || l.url.toLowerCase().includes(listingSearch.toLowerCase()))
                        .map((listing, idx) => (
                          <tr key={listing.id} className="hover:bg-[#171E24] transition-colors">
                            <td className="p-3">
                              <div className="flex items-center gap-3">
                                <span className="font-mono font-bold text-slate-500 w-5">#{idx + 1}</span>
                                <img src={listing.image_url} alt="" className="w-9 h-9 rounded-lg object-cover shrink-0" />
                                <div className="min-w-0">
                                  <div className="font-bold text-white truncate max-w-xs">{listing.name}</div>
                                  <a href={listing.url} target="_blank" rel="noreferrer" className="text-[10px] text-emerald-400 hover:underline truncate block max-w-xs">
                                    {listing.url}
                                  </a>
                                </div>
                              </div>
                            </td>
                            <td className="p-3">
                              <span className="px-2 py-0.5 rounded bg-[#0A0D0F] border border-[#222A33] text-[10px]">
                                {listing.category_name}
                              </span>
                            </td>
                            <td className="p-3 font-mono font-bold text-emerald-400">
                              ৳{listing.current_bid.toLocaleString()}
                            </td>
                            <td className="p-3 text-[11px] text-slate-400 font-mono">
                              {listing.clicks} clicks · {listing.hearts} hearts
                            </td>
                            <td className="p-3">
                              <button
                                onClick={() => adminToggleListingStatus(listing.id)}
                                className={`px-2 py-0.5 rounded text-[10px] font-bold ${
                                  listing.is_active ? 'bg-emerald-950 text-emerald-400 border border-emerald-800' : 'bg-rose-950 text-rose-400 border border-rose-800'
                                }`}
                              >
                                {listing.is_active ? 'ACTIVE' : 'INACTIVE'}
                              </button>
                            </td>
                            <td className="p-3 text-right">
                              <div className="flex items-center justify-end gap-1.5">
                                <button
                                  onClick={() => {
                                    if (confirm(`Reset clicks & hearts for "${listing.name}" to 0?`)) {
                                      adminResetListingStats(listing.id, 'all');
                                      showToast(`Clicks & hearts reset for ${listing.name}`);
                                    }
                                  }}
                                  className="p-1.5 rounded-lg bg-sky-950/70 hover:bg-sky-900 border border-sky-800 text-sky-300"
                                  title="Reset Clicks & Hearts"
                                >
                                  <RotateCcw className="w-3.5 h-3.5" />
                                </button>
                                <button
                                  onClick={() => setEditingListing(listing)}
                                  className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-200"
                                  title="Edit Listing"
                                >
                                  <Edit2 className="w-3.5 h-3.5" />
                                </button>
                                <button
                                  onClick={() => {
                                    if (confirm(`Delete listing "${listing.name}"?`)) {
                                      adminDeleteListing(listing.id);
                                      showToast('Listing deleted');
                                    }
                                  }}
                                  className="p-1.5 rounded-lg bg-rose-950/60 hover:bg-rose-900 text-rose-300"
                                >
                                  <Trash2 className="w-3.5 h-3.5" />
                                </button>
                              </div>
                            </td>
                          </tr>
                        ))}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Edit / Add Modal */}
              {editingListing && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
                  <div className="w-full max-w-lg rounded-2xl bg-[#13181D] border border-[#2A3440] p-6 space-y-4 shadow-2xl">
                    <div className="flex items-center justify-between border-b border-[#222A33] pb-3">
                      <h3 className="font-bold text-white">
                        {editingListing.id ? 'Edit Listing' : 'Add New Listing'}
                      </h3>
                      <button onClick={() => setEditingListing(null)} className="text-slate-400 hover:text-white">
                        <X className="w-4 h-4" />
                      </button>
                    </div>

                    <div className="space-y-3 text-xs">
                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Name</label>
                        <input
                          type="text"
                          value={editingListing.name || ''}
                          onChange={e => setEditingListing({ ...editingListing, name: e.target.value })}
                          className="w-full px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white focus:outline-none focus:border-emerald-500"
                        />
                      </div>

                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">
                          Facebook Page or Profile URL <span className="text-emerald-500">*</span>
                        </label>
                        <input
                          type="text"
                          value={editingListing.facebook_url || editingListing.url || ''}
                          onChange={e => setEditingListing({ ...editingListing, facebook_url: e.target.value, url: e.target.value })}
                          placeholder="https://facebook.com/yourpage"
                          className="w-full px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white focus:outline-none focus:border-emerald-500"
                        />
                      </div>

                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">
                          Website URL <span className="text-slate-400 font-normal">(Optional)</span>
                        </label>
                        <input
                          type="text"
                          value={editingListing.website_url || ''}
                          onChange={e => setEditingListing({ ...editingListing, website_url: e.target.value })}
                          placeholder="https://yourwebsite.com or toolyfie.com"
                          className="w-full px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white focus:outline-none focus:border-emerald-500"
                        />
                      </div>

                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Profile Image URL</label>
                        <input
                          type="text"
                          value={editingListing.image_url || ''}
                          onChange={e => setEditingListing({ ...editingListing, image_url: e.target.value })}
                          className="w-full px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white focus:outline-none focus:border-emerald-500"
                        />
                      </div>

                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <label className="block text-slate-300 font-semibold mb-1">Category</label>
                          <select
                            value={editingListing.category_id || ''}
                            onChange={e => setEditingListing({ ...editingListing, category_id: e.target.value })}
                            className="w-full px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white focus:outline-none"
                          >
                            {categories.filter(c => c.slug !== 'all').map(c => (
                              <option key={c.id} value={c.id}>{c.name}</option>
                            ))}
                          </select>
                        </div>

                        <div>
                          <label className="block text-slate-300 font-semibold mb-1">Current Bid (৳)</label>
                          <input
                            type="number"
                            value={editingListing.current_bid || 0}
                            onChange={e => setEditingListing({ ...editingListing, current_bid: Number(e.target.value) })}
                            className="w-full px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:outline-none"
                          />
                        </div>
                      </div>
                    </div>

                    <div className="flex justify-end gap-2 pt-3 border-t border-[#222A33]">
                      <button
                        onClick={() => setEditingListing(null)}
                        className="px-4 py-2 rounded-xl bg-slate-800 text-slate-300 font-semibold text-xs"
                      >
                        Cancel
                      </button>
                      <button
                        onClick={() => {
                          if (editingListing) {
                            const normalizedFb = normalizeFacebookUrl(editingListing.facebook_url || editingListing.url || 'https://facebook.com');
                            const normalizedWeb = editingListing.website_url ? normalizeUrl(editingListing.website_url) : '';
                            adminSaveListing({
                              ...editingListing,
                              facebook_url: normalizedFb,
                              website_url: normalizedWeb,
                              url: normalizedWeb || normalizedFb,
                            });
                            setEditingListing(null);
                            showToast('Listing saved successfully');
                          }
                        }}
                        className="px-5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs"
                      >
                        Save Listing
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* TAB 3: CATEGORIES CRUD & SEQUENCE REORDERING */}
          {activeTab === 'categories' && (
            <div className="space-y-4">
              {/* Informative Header / Guide */}
              <div className="p-4 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-2">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                  <div>
                    <h3 className="font-bold text-sm text-white flex items-center gap-2">
                      <FolderTree className="w-4 h-4 text-emerald-400" />
                      <span>Category Sequence & Display Hierarchy</span>
                    </h3>
                    <p className="text-xs text-slate-400 mt-0.5">
                      Reorder categories using <strong className="text-white">Up/Down arrows</strong>, direct <strong className="text-white">sequence numbers</strong>, or toggle <strong className="text-white">Active/Hidden</strong> status. The changes apply in real-time across the application.
                    </p>
                  </div>

                  <div className="flex items-center gap-2 shrink-0">
                    <button
                      onClick={() => {
                        const sortedNonAll = categories
                          .filter(c => c.slug !== 'all')
                          .sort((a, b) => a.display_order - b.display_order);
                        adminReorderCategories(sortedNonAll);
                        showToast('Sequence re-indexed 1..N');
                      }}
                      title="Normalize sequence numbers sequentially 1, 2, 3..."
                      className="px-3 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 font-semibold text-xs flex items-center gap-1.5 transition-colors cursor-pointer"
                    >
                      <ArrowUpDown className="w-3.5 h-3.5 text-emerald-400" />
                      <span>Re-index (1..N)</span>
                    </button>

                    <button
                      onClick={() => setEditingCategory({ is_active: true, display_order: categories.filter(c => c.slug !== 'all').length + 1, icon: 'Sparkles' })}
                      className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs flex items-center gap-1.5 shadow-lg shadow-emerald-950/40 transition-colors cursor-pointer"
                    >
                      <Plus className="w-4 h-4" />
                      <span>Add Category</span>
                    </button>
                  </div>
                </div>

                {/* Legend badges */}
                <div className="flex flex-wrap items-center gap-2 pt-2 border-t border-[#222A33] text-[11px]">
                  <span className="text-slate-400 font-medium">Display Slots:</span>
                  <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-emerald-950/60 border border-emerald-800/60 text-emerald-300 font-semibold">
                    <Sparkles className="w-3 h-3 text-emerald-400" /> Slots 1–7: Primary Horizontal Bar
                  </span>
                  <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-sky-950/60 border border-sky-800/60 text-sky-300 font-semibold">
                    <Layers className="w-3 h-3 text-sky-400" /> Slots 8+: Dynamic '+ More' Menu
                  </span>
                  <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-stone-900 border border-stone-800 text-stone-400 font-semibold">
                    <EyeOff className="w-3 h-3 text-stone-500" /> Hidden: Excluded from frontend
                  </span>
                </div>
              </div>

              {/* Search Bar */}
              <div className="flex items-center gap-3">
                <div className="relative flex-1">
                  <Search className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
                  <input
                    type="text"
                    placeholder="Search category by name, slug, or icon..."
                    value={categorySearch}
                    onChange={e => setCategorySearch(e.target.value)}
                    className="w-full pl-9 pr-3 py-2 bg-[#13181D] border border-[#222A33] rounded-xl text-white text-xs placeholder:text-slate-500 focus:outline-none focus:border-emerald-500"
                  />
                </div>
                {categorySearch && (
                  <button
                    onClick={() => setCategorySearch('')}
                    className="px-3 py-2 rounded-xl bg-slate-800 text-slate-300 text-xs font-semibold hover:bg-slate-700"
                  >
                    Clear Filter
                  </button>
                )}
              </div>

              {/* Category Sequence List / Table */}
              <div className="rounded-2xl bg-[#13181D] border border-[#222A33] overflow-hidden">
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-xs text-slate-300">
                    <thead className="bg-[#0E1317] border-b border-[#222A33] text-slate-400 font-bold uppercase tracking-wider text-[10px]">
                      <tr>
                        <th className="p-3 w-28 text-center">Move / Order</th>
                        <th className="p-3">Category</th>
                        <th className="p-3">Frontend Location</th>
                        <th className="p-3 text-center">Status</th>
                        <th className="p-3 text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-[#1D252E]">
                      {/* Pinned 'ALL' row */}
                      {categories.filter(c => c.slug === 'all').map(allCat => (
                        <tr key={allCat.id} className="bg-emerald-950/20">
                          <td className="p-3 text-center">
                            <span className="px-2.5 py-1 rounded-lg bg-emerald-900/60 border border-emerald-700/60 font-mono font-bold text-emerald-300 text-[11px]">
                              PINNED #0
                            </span>
                          </td>
                          <td className="p-3">
                            <div className="flex items-center gap-2.5">
                              <div className="w-8 h-8 rounded-lg bg-emerald-600/30 border border-emerald-500/40 flex items-center justify-center text-emerald-400 shrink-0">
                                <Sparkles className="w-4 h-4" />
                              </div>
                              <div>
                                <span className="font-bold text-white text-sm">{allCat.name}</span>
                                <span className="text-[11px] text-slate-400 block font-mono">slug: all · Master Overview</span>
                              </div>
                            </div>
                          </td>
                          <td className="p-3">
                            <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-emerald-950 border border-emerald-700/80 text-emerald-300 text-[10px] font-bold">
                              ✨ Permanent First Slot
                            </span>
                          </td>
                          <td className="p-3 text-center">
                            <span className="px-2.5 py-1 rounded-full bg-emerald-950 text-emerald-400 border border-emerald-800 text-[10px] font-bold">
                              ACTIVE (LOCKED)
                            </span>
                          </td>
                          <td className="p-3 text-right text-slate-500 text-[11px]">
                            Default Root
                          </td>
                        </tr>
                      ))}

                      {/* Dynamic User Categories sorted by display_order */}
                      {(() => {
                        const sortedNonAll = categories
                          .filter(c => c.slug !== 'all')
                          .sort((a, b) => a.display_order - b.display_order);

                        const filtered = sortedNonAll.filter(cat =>
                          cat.name.toLowerCase().includes(categorySearch.toLowerCase()) ||
                          cat.slug.toLowerCase().includes(categorySearch.toLowerCase()) ||
                          (cat.icon && cat.icon.toLowerCase().includes(categorySearch.toLowerCase()))
                        );

                        if (filtered.length === 0) {
                          return (
                            <tr>
                              <td colSpan={5} className="p-8 text-center text-slate-500">
                                No categories matching your search.
                              </td>
                            </tr>
                          );
                        }

                        // Calculate active indices for slot placement
                        let activeCounter = 0;

                        return filtered.map((cat) => {
                          const actualIndexInSorted = sortedNonAll.findIndex(c => c.id === cat.id);
                          const isFirst = actualIndexInSorted === 0;
                          const isLast = actualIndexInSorted === sortedNonAll.length - 1;

                          let activeSlotNumber = -1;
                          if (cat.is_active) {
                            activeCounter += 1;
                            activeSlotNumber = activeCounter;
                          }

                          return (
                            <tr key={cat.id} className="hover:bg-[#171E24] transition-colors">
                              {/* Reorder Buttons & Numeric Sequence Column */}
                              <td className="p-3">
                                <div className="flex items-center justify-center gap-1.5">
                                  {/* Up Arrow button */}
                                  <button
                                    type="button"
                                    disabled={isFirst}
                                    onClick={() => {
                                      adminMoveCategory(cat.id, 'up');
                                      showToast(`Moved "${cat.name}" UP`);
                                    }}
                                    className={`p-1.5 rounded-lg transition-colors cursor-pointer ${
                                      isFirst
                                        ? 'opacity-25 cursor-not-allowed text-slate-600 bg-[#0A0D0F]'
                                        : 'bg-slate-800 hover:bg-emerald-600 text-slate-200 hover:text-white'
                                    }`}
                                    title={isFirst ? 'Already top category' : 'Move Up in Sequence (1 slot higher)'}
                                  >
                                    <ChevronUp className="w-4 h-4 stroke-[2.5]" />
                                  </button>

                                  {/* Down Arrow button */}
                                  <button
                                    type="button"
                                    disabled={isLast}
                                    onClick={() => {
                                      adminMoveCategory(cat.id, 'down');
                                      showToast(`Moved "${cat.name}" DOWN`);
                                    }}
                                    className={`p-1.5 rounded-lg transition-colors cursor-pointer ${
                                      isLast
                                        ? 'opacity-25 cursor-not-allowed text-slate-600 bg-[#0A0D0F]'
                                        : 'bg-slate-800 hover:bg-emerald-600 text-slate-200 hover:text-white'
                                    }`}
                                    title={isLast ? 'Already bottom category' : 'Move Down in Sequence (1 slot lower)'}
                                  >
                                    <ChevronDown className="w-4 h-4 stroke-[2.5]" />
                                  </button>

                                  {/* Direct Numeric Position Input */}
                                  <input
                                    type="number"
                                    min={1}
                                    max={sortedNonAll.length}
                                    value={cat.display_order}
                                    onChange={e => {
                                      const val = parseInt(e.target.value, 10);
                                      if (!isNaN(val) && val >= 1) {
                                        adminSetCategoryOrder(cat.id, val);
                                      }
                                    }}
                                    className="w-11 px-1.5 py-1 text-center font-mono font-bold text-white bg-[#0A0D0F] border border-[#222A33] focus:border-emerald-500 rounded-lg text-xs"
                                    title="Edit sequence number directly (1..N)"
                                  />
                                </div>
                              </td>

                              {/* Category Identity */}
                              <td className="p-3">
                                <div className="flex items-center gap-3">
                                  <div className="w-8 h-8 rounded-lg bg-[#0A0D0F] border border-[#222A33] flex items-center justify-center text-emerald-400 shrink-0">
                                    {getCategoryIcon(cat.icon)}
                                  </div>
                                  <div>
                                    <div className="font-bold text-white text-sm flex items-center gap-2">
                                      <span>{cat.name}</span>
                                    </div>
                                    <div className="text-[11px] text-slate-400 font-mono flex items-center gap-2">
                                      <span>slug: {cat.slug}</span>
                                      <span>·</span>
                                      <span className="text-slate-500">icon: {cat.icon || 'Sparkles'}</span>
                                    </div>
                                  </div>
                                </div>
                              </td>

                              {/* Frontend Location Indicator */}
                              <td className="p-3">
                                {cat.is_active ? (
                                  activeSlotNumber <= 7 ? (
                                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-emerald-950/70 border border-emerald-700/60 text-emerald-300 text-[10px] font-bold">
                                      <Sparkles className="w-3 h-3 text-emerald-400" />
                                      Primary Bar (Slot #{activeSlotNumber})
                                    </span>
                                  ) : (
                                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-sky-950/70 border border-sky-700/60 text-sky-300 text-[10px] font-bold">
                                      <Layers className="w-3 h-3 text-sky-400" />
                                      More Menu (Slot #{activeSlotNumber})
                                    </span>
                                  )
                                ) : (
                                  <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-stone-900 border border-stone-800 text-stone-400 text-[10px] font-medium">
                                    <EyeOff className="w-3 h-3 text-stone-500" />
                                    Hidden (Inactive)
                                  </span>
                                )}
                              </td>

                              {/* Active / Inactive Toggle Switch */}
                              <td className="p-3 text-center">
                                <button
                                  type="button"
                                  onClick={() => {
                                    adminToggleCategoryStatus(cat.id);
                                    showToast(`Category "${cat.name}" is now ${cat.is_active ? 'HIDDEN' : 'ACTIVE'}`);
                                  }}
                                  className={`px-3 py-1 rounded-full text-[10px] font-bold transition-all cursor-pointer select-none inline-flex items-center gap-1.5 ${
                                    cat.is_active
                                      ? 'bg-emerald-950 text-emerald-300 border border-emerald-700 hover:bg-emerald-900'
                                      : 'bg-stone-900 text-stone-400 border border-stone-800 hover:bg-stone-800 hover:text-stone-300'
                                  }`}
                                  title="Click to toggle Active / Hidden on frontend"
                                >
                                  <span className={`w-1.5 h-1.5 rounded-full ${cat.is_active ? 'bg-emerald-400 animate-pulse' : 'bg-stone-500'}`} />
                                  <span>{cat.is_active ? 'ACTIVE' : 'HIDDEN'}</span>
                                </button>
                              </td>

                              {/* Actions */}
                              <td className="p-3 text-right">
                                <div className="flex items-center justify-end gap-1.5">
                                  <button
                                    onClick={() => setEditingCategory(cat)}
                                    className="p-1.5 rounded-lg bg-slate-800 text-slate-200 hover:bg-slate-700 transition-colors cursor-pointer"
                                    title="Edit name, icon, slug, order"
                                  >
                                    <Edit2 className="w-3.5 h-3.5" />
                                  </button>
                                  <button
                                    onClick={() => {
                                      if (confirm(`Delete category "${cat.name}"? This action cannot be undone.`)) {
                                        adminDeleteCategory(cat.id);
                                        showToast('Category deleted');
                                      }
                                    }}
                                    className="p-1.5 rounded-lg bg-rose-950/60 text-rose-300 hover:bg-rose-900 transition-colors cursor-pointer"
                                    title="Delete Category"
                                  >
                                    <Trash2 className="w-3.5 h-3.5" />
                                  </button>
                                </div>
                              </td>
                            </tr>
                          );
                        });
                      })()}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Category Edit / Add Modal */}
              {editingCategory && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
                  <div className="w-full max-w-md rounded-2xl bg-[#13181D] border border-[#2A3440] p-6 space-y-4 shadow-2xl">
                    <div className="flex items-center justify-between border-b border-[#222A33] pb-3">
                      <h3 className="font-bold text-white text-sm flex items-center gap-2">
                        <FolderTree className="w-4 h-4 text-emerald-400" />
                        <span>{editingCategory.id ? 'Edit Category' : 'Create New Category'}</span>
                      </h3>
                      <button onClick={() => setEditingCategory(null)} className="text-slate-400 hover:text-white">
                        <X className="w-4 h-4" />
                      </button>
                    </div>

                    <div className="space-y-3.5 text-xs">
                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Category Name</label>
                        <input
                          type="text"
                          placeholder="e.g. AI & Tech"
                          value={editingCategory.name || ''}
                          onChange={e => setEditingCategory({ ...editingCategory, name: e.target.value })}
                          className="w-full px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white focus:outline-none focus:border-emerald-500"
                        />
                      </div>

                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <label className="block text-slate-300 font-semibold mb-1">Sequence Order Number</label>
                          <input
                            type="number"
                            min={1}
                            value={editingCategory.display_order ?? 1}
                            onChange={e => setEditingCategory({ ...editingCategory, display_order: parseInt(e.target.value, 10) || 1 })}
                            className="w-full px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:outline-none focus:border-emerald-500"
                          />
                        </div>

                        <div>
                          <label className="block text-slate-300 font-semibold mb-1">Status</label>
                          <label className="flex items-center gap-2 px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] cursor-pointer text-xs h-[38px]">
                            <input
                              type="checkbox"
                              checked={editingCategory.is_active !== false}
                              onChange={e => setEditingCategory({ ...editingCategory, is_active: e.target.checked })}
                              className="rounded border-slate-700 text-emerald-600 focus:ring-emerald-500"
                            />
                            <span className="text-slate-200 font-semibold">Active on site</span>
                          </label>
                        </div>
                      </div>

                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Icon Keyword</label>
                        <input
                          type="text"
                          placeholder="Sparkles, Briefcase, Video, Rocket, Code, ShoppingBag..."
                          value={editingCategory.icon || ''}
                          onChange={e => setEditingCategory({ ...editingCategory, icon: e.target.value })}
                          className="w-full px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white focus:outline-none focus:border-emerald-500"
                        />

                        {/* Quick preset icon chips */}
                        <div className="mt-2 flex flex-wrap gap-1.5 items-center">
                          <span className="text-[10px] text-slate-500">Presets:</span>
                          {[
                            'Sparkles',
                            'Briefcase',
                            'Video',
                            'Rocket',
                            'ShoppingBag',
                            'Code',
                            'Building',
                            'Cpu',
                            'Gamepad2',
                            'Newspaper',
                            'GraduationCap',
                            'Award',
                            'Share2'
                          ].map(iconKey => (
                            <button
                              key={iconKey}
                              type="button"
                              onClick={() => setEditingCategory({ ...editingCategory, icon: iconKey })}
                              className={`px-2 py-0.5 rounded text-[10px] flex items-center gap-1 cursor-pointer transition-colors ${
                                editingCategory.icon === iconKey
                                  ? 'bg-emerald-600 text-white font-bold'
                                  : 'bg-[#0A0D0F] border border-[#222A33] text-slate-400 hover:text-slate-200'
                              }`}
                            >
                              {getCategoryIcon(iconKey)}
                              <span>{iconKey}</span>
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>

                    <div className="flex justify-end gap-2 pt-3 border-t border-[#222A33]">
                      <button
                        onClick={() => setEditingCategory(null)}
                        className="px-4 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-semibold"
                      >
                        Cancel
                      </button>
                      <button
                        onClick={() => {
                          if (!editingCategory.name) {
                            alert('Please enter a category name');
                            return;
                          }
                          adminSaveCategory(editingCategory);
                          setEditingCategory(null);
                          showToast('Category saved successfully');
                        }}
                        className="px-5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs shadow-lg shadow-emerald-950/40"
                      >
                        Save Category
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* TAB 4: PAYMENT GATEWAYS CONFIGURATION */}
          {activeTab === 'payments' && (
            <div className="space-y-6">
              <div className="p-4 rounded-2xl bg-emerald-950/40 border border-emerald-700/40 text-xs text-emerald-300 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                <div>
                  <strong className="text-emerald-400 block sm:inline">Production-Ready Payment Architecture:</strong> Secure server-side verification with Sandbox (Test) &amp; Live production modes for bKash, Nagad, Rocket, SSLCommerz, shurjoPay, and aamarPay.
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  <span className="text-[11px] text-slate-300 font-semibold">Default Gateway:</span>
                  <select
                    value={tempSettings.default_payment_gateway || 'bkash'}
                    onChange={e => setTempSettings({ ...tempSettings, default_payment_gateway: e.target.value as any })}
                    className="px-2.5 py-1 rounded-lg bg-[#0A0D0F] border border-emerald-500/40 text-white font-mono text-xs focus:ring-1 focus:ring-emerald-500"
                  >
                    {tempGateways.map(g => (
                      <option key={g.id} value={g.id}>
                        {g.name}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="space-y-4">
                {tempGateways.map((gw, idx) => (
                  <div key={gw.id} className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4">
                    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-[#222A33] pb-3">
                      <div className="flex items-center gap-2.5">
                        <CreditCard className="w-5 h-5 text-emerald-400" />
                        <div>
                          <h4 className="font-bold text-sm text-white flex items-center gap-2">
                            {gw.name}
                            {tempSettings.default_payment_gateway === gw.id && (
                              <span className="px-1.5 py-0.5 rounded bg-emerald-500/20 text-emerald-400 text-[10px] font-mono">DEFAULT</span>
                            )}
                          </h4>
                          <span className="text-[10px] text-slate-500 font-mono">{gw.id}</span>
                        </div>
                      </div>

                      <div className="flex items-center gap-3">
                        {/* Mode switch */}
                        <div className="flex items-center gap-1.5 p-1 bg-[#0A0D0F] border border-[#222A33] rounded-lg text-xs">
                          <button
                            type="button"
                            onClick={() => {
                              const updated = [...tempGateways];
                              updated[idx].mode = 'test';
                              setTempGateways(updated);
                            }}
                            className={`px-2.5 py-1 rounded font-mono font-bold transition-colors ${gw.mode === 'test' ? 'bg-amber-600 text-white' : 'text-slate-400 hover:text-white'}`}
                          >
                            SANDBOX
                          </button>
                          <button
                            type="button"
                            onClick={() => {
                              const updated = [...tempGateways];
                              updated[idx].mode = 'live';
                              setTempGateways(updated);
                            }}
                            className={`px-2.5 py-1 rounded font-mono font-bold transition-colors ${gw.mode === 'live' ? 'bg-emerald-600 text-white' : 'text-slate-400 hover:text-white'}`}
                          >
                            LIVE
                          </button>
                        </div>

                        {/* Enable toggle */}
                        <label className="flex items-center gap-2 cursor-pointer text-xs">
                          <input
                            type="checkbox"
                            checked={gw.is_enabled}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].is_enabled = e.target.checked;
                              setTempGateways(updated);
                            }}
                            className="rounded border-slate-700 text-emerald-600 focus:ring-emerald-500 w-4 h-4 cursor-pointer"
                          />
                          <span className="text-slate-300 font-semibold">Enabled</span>
                        </label>
                      </div>
                    </div>

                    {/* Specific Gateway Config Fields */}
                    {gw.id === 'bkash' && (
                      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
                        <div>
                          <label className="block text-slate-400 mb-1">bKash App Key</label>
                          <input
                            type="text"
                            placeholder="e.g. 4fxxxxxxxxxx"
                            value={gw.app_key || ''}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].app_key = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                        <div>
                          <label className="block text-slate-400 mb-1">bKash App Secret</label>
                          <input
                            type="password"
                            placeholder="••••••••••••"
                            value={gw.app_secret || ''}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].app_secret = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                        <div>
                          <label className="block text-slate-400 mb-1">Merchant Username</label>
                          <input
                            type="text"
                            placeholder="sandbox / merchant user"
                            value={gw.merchant_id || gw.username || ''}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].merchant_id = e.target.value;
                              updated[idx].username = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                      </div>
                    )}

                    {gw.id === 'nagad' && (
                      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
                        <div>
                          <label className="block text-slate-400 mb-1">Nagad Merchant ID</label>
                          <input
                            type="text"
                            placeholder="e.g. 68xxxxxxxx"
                            value={gw.merchant_id || ''}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].merchant_id = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                        <div>
                          <label className="block text-slate-400 mb-1">Public Key / PG Public Key</label>
                          <input
                            type="password"
                            placeholder="Public Key"
                            value={gw.public_key || ''}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].public_key = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                        <div>
                          <label className="block text-slate-400 mb-1">Private Key (Merchant Private)</label>
                          <input
                            type="password"
                            placeholder="Private Key"
                            value={gw.private_key || ''}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].private_key = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                      </div>
                    )}

                    {gw.id === 'sslcommerz' && (
                      <div className="space-y-3 text-xs">
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                          <div>
                            <label className="block text-slate-400 mb-1">SSLCommerz Store ID</label>
                            <input
                              type="text"
                              placeholder="e.g. testbox_live / store_id"
                              value={gw.store_id || gw.app_key || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].store_id = e.target.value;
                                updated[idx].app_key = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                            />
                          </div>
                          <div>
                            <label className="block text-slate-400 mb-1">SSLCommerz Store Password</label>
                            <input
                              type="password"
                              placeholder="••••••••••••"
                              value={gw.password || gw.app_secret || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].password = e.target.value;
                                updated[idx].app_secret = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                            />
                          </div>
                        </div>

                        {/* Supported Payment Channels */}
                        <div>
                          <label className="block text-slate-400 mb-1.5 font-semibold">Enabled Payment Channels (multi_card_name)</label>
                          <div className="flex flex-wrap gap-2">
                            {[
                              { key: 'cards', label: 'Visa / Mastercard / Amex' },
                              { key: 'bkash', label: 'bKash' },
                              { key: 'nagad', label: 'Nagad' },
                              { key: 'rocket', label: 'Rocket' },
                              { key: 'internet_banking', label: 'Internet Banking' },
                            ].map(ch => {
                              const channels = gw.allowed_channels || ['cards', 'bkash', 'nagad', 'rocket', 'internet_banking'];
                              const isChecked = channels.includes(ch.key);
                              return (
                                <label
                                  key={ch.key}
                                  className={`px-2.5 py-1 rounded-lg border text-[11px] font-medium flex items-center gap-1.5 cursor-pointer transition-colors ${
                                    isChecked
                                      ? 'bg-emerald-950/60 border-emerald-600/60 text-emerald-300'
                                      : 'bg-[#0A0D0F] border-[#222A33] text-slate-500 hover:text-slate-400'
                                  }`}
                                >
                                  <input
                                    type="checkbox"
                                    checked={isChecked}
                                    onChange={e => {
                                      const updated = [...tempGateways];
                                      const cur = new Set(channels);
                                      if (e.target.checked) cur.add(ch.key);
                                      else cur.delete(ch.key);
                                      updated[idx].allowed_channels = Array.from(cur);
                                      setTempGateways(updated);
                                    }}
                                    className="hidden"
                                  />
                                  <span className={`w-1.5 h-1.5 rounded-full ${isChecked ? 'bg-emerald-400' : 'bg-slate-600'}`} />
                                  <span>{ch.label}</span>
                                </label>
                              );
                            })}
                          </div>
                        </div>
                      </div>
                    )}

                    {gw.id === 'rocket' && (
                      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
                        <div>
                          <label className="block text-slate-400 mb-1">DBBL Rocket Merchant Account</label>
                          <input
                            type="text"
                            placeholder="e.g. 017xxxxxxxx0"
                            value={gw.merchant_id || ''}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].merchant_id = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                        <div>
                          <label className="block text-slate-400 mb-1">Terminal ID</label>
                          <input
                            type="text"
                            placeholder="e.g. TRM001"
                            value={gw.terminal_id || ''}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].terminal_id = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                        <div>
                          <label className="block text-slate-400 mb-1">Secret Key / PIN</label>
                          <input
                            type="password"
                            placeholder="••••••••••••"
                            value={gw.app_secret || ''}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].app_secret = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                      </div>
                    )}

                    {gw.id === 'shurjopay' && (
                      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
                        <div>
                          <label className="block text-slate-400 mb-1">shurjoPay Merchant User</label>
                          <input
                            type="text"
                            placeholder="e.g. sp_merchant"
                            value={gw.username || gw.merchant_id || ''}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].username = e.target.value;
                              updated[idx].merchant_id = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                        <div>
                          <label className="block text-slate-400 mb-1">shurjoPay Password</label>
                          <input
                            type="password"
                            placeholder="••••••••••••"
                            value={gw.password || gw.app_secret || ''}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].password = e.target.value;
                              updated[idx].app_secret = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                        <div>
                          <label className="block text-slate-400 mb-1">Order Prefix</label>
                          <input
                            type="text"
                            placeholder="e.g. TOPBD"
                            value={gw.order_prefix || 'TOPBD'}
                            onChange={e => {
                              const updated = [...tempGateways];
                              updated[idx].order_prefix = e.target.value;
                              setTempGateways(updated);
                            }}
                            className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono"
                          />
                        </div>
                      </div>
                    )}

                    {gw.id === 'aamarpay' && (
                      <div className="space-y-3 text-xs">
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">1. Store ID / Merchant ID</label>
                            <input
                              type="text"
                              placeholder="e.g. aamarpaytest (Sandbox) or your_store_id"
                              value={gw.store_id || gw.app_key || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].store_id = e.target.value;
                                updated[idx].app_key = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                          </div>
                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">2. Signature Key (Secret)</label>
                            <input
                              type="password"
                              placeholder="••••••••••••••••••••••••••••••••"
                              value={gw.signature_key || gw.app_secret || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].signature_key = e.target.value;
                                updated[idx].app_secret = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                          </div>
                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">3. API / Gateway URL</label>
                            <input
                              type="text"
                              placeholder={gw.mode === 'live' ? 'https://secure.aamarpay.com' : 'https://sandbox.aamarpay.com'}
                              value={gw.api_url || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].api_url = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                          </div>
                        </div>

                        {/* URLs & Session Timeout */}
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">4. Success URL</label>
                            <input
                              type="text"
                              placeholder="/api/payments/aamarpay/callback"
                              value={gw.success_url || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].success_url = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                          </div>
                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">5. Fail URL</label>
                            <input
                              type="text"
                              placeholder="/api/payments/aamarpay/callback"
                              value={gw.fail_url || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].fail_url = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                          </div>
                          <div>
                            <label className="block text-slate-400 mb-1 font-medium font-mono">6. Cancel URL</label>
                            <input
                              type="text"
                              placeholder="/api/payments/aamarpay/callback"
                              value={gw.cancel_url || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].cancel_url = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                          </div>
                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">7. IPN / Callback URL</label>
                            <input
                              type="text"
                              placeholder="/api/payments/aamarpay/ipn"
                              value={gw.ipn_url || gw.callback_url || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].ipn_url = e.target.value;
                                updated[idx].callback_url = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                          </div>
                        </div>

                        {/* Payment Session Timeout & Info */}
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 items-center pt-1">
                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">8. Payment Session Timeout (Minutes)</label>
                            <input
                              type="number"
                              min="1"
                              max="120"
                              placeholder="15"
                              value={gw.session_timeout || 15}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].session_timeout = Number(e.target.value) || 15;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                          </div>
                          <div className="text-[11px] text-slate-400 bg-[#0A0D0F] p-2.5 rounded-xl border border-[#222A33]">
                            <span className="text-emerald-400 font-semibold block">Server-to-Server Verification Active</span>
                            <span>All payments undergo rigorous cryptographic verification against the official aamarPay validation endpoint.</span>
                          </div>
                        </div>

                        {/* Supported Payment Channels */}
                        <div>
                          <label className="block text-slate-400 mb-1.5 font-semibold">Enabled Payment Channels (Hosted Checkout)</label>
                          <div className="flex flex-wrap gap-2">
                            {[
                              { key: 'cards', label: 'Visa / Mastercard / Amex' },
                              { key: 'bkash', label: 'bKash' },
                              { key: 'nagad', label: 'Nagad' },
                              { key: 'rocket', label: 'Rocket' },
                              { key: 'internet_banking', label: 'Internet Banking' },
                            ].map(ch => {
                              const channels = gw.allowed_channels || ['cards', 'bkash', 'nagad', 'rocket', 'internet_banking'];
                              const isChecked = channels.includes(ch.key);
                              return (
                                <label
                                  key={ch.key}
                                  className={`px-2.5 py-1 rounded-lg border text-[11px] font-medium flex items-center gap-1.5 cursor-pointer transition-colors ${
                                    isChecked
                                      ? 'bg-emerald-950/60 border-emerald-600/60 text-emerald-300'
                                      : 'bg-[#0A0D0F] border-[#222A33] text-slate-500 hover:text-slate-400'
                                  }`}
                                >
                                  <input
                                    type="checkbox"
                                    checked={isChecked}
                                    onChange={e => {
                                      const updated = [...tempGateways];
                                      const cur = new Set(channels);
                                      if (e.target.checked) cur.add(ch.key);
                                      else cur.delete(ch.key);
                                      updated[idx].allowed_channels = Array.from(cur);
                                      setTempGateways(updated);
                                    }}
                                    className="hidden"
                                  />
                                  <span className={`w-1.5 h-1.5 rounded-full ${isChecked ? 'bg-emerald-400' : 'bg-slate-600'}`} />
                                  <span>{ch.label}</span>
                                </label>
                              );
                            })}
                          </div>
                        </div>
                      </div>
                    )}

                    {gw.id === 'uddoktapay' && (
                      <div className="space-y-4 text-xs pt-1">
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">UddoktaPay API Key</label>
                            <div className="relative">
                              <input
                                type={showUddoktaPayApiKey ? 'text' : 'password'}
                                placeholder="e.g. 982d381360a69d419689740d9f2e26ce36fb7a50"
                                value={gw.api_key || gw.app_key || ''}
                                onChange={e => {
                                  const updated = [...tempGateways];
                                  updated[idx].api_key = e.target.value;
                                  updated[idx].app_key = e.target.value;
                                  setTempGateways(updated);
                                }}
                                className="w-full px-3 py-1.5 pr-12 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                              />
                              <button
                                type="button"
                                onClick={() => setShowUddoktaPayApiKey(!showUddoktaPayApiKey)}
                                className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white px-1.5 py-0.5 rounded text-[10px] bg-[#13181D] border border-[#222A33]"
                              >
                                {showUddoktaPayApiKey ? 'HIDE' : 'SHOW'}
                              </button>
                            </div>
                          </div>

                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">API Base URL</label>
                            <input
                              type="text"
                              placeholder={gw.mode === 'live' ? 'https://pay.yourdomain.com (Required for Live)' : 'https://sandbox.uddoktapay.com'}
                              value={gw.api_url || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].api_url = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                            <span className="text-[10px] text-slate-500 mt-0.5 block">
                              {gw.mode === 'live'
                                ? 'Domain provided by UddoktaPay panel (e.g. https://pay.example.com)'
                                : 'Default Sandbox: https://sandbox.uddoktapay.com'}
                            </span>
                          </div>
                        </div>

                        {/* URLs Configuration */}
                        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">Callback URL</label>
                            <input
                              type="text"
                              placeholder="/api/payments/uddoktapay/callback"
                              value={gw.callback_url || gw.success_url || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].callback_url = e.target.value;
                                updated[idx].success_url = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                          </div>

                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">Cancel URL</label>
                            <input
                              type="text"
                              placeholder="/api/payments/uddoktapay/callback?status=cancelled"
                              value={gw.cancel_url || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].cancel_url = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                          </div>

                          <div>
                            <label className="block text-slate-400 mb-1 font-medium">Webhook / IPN URL</label>
                            <input
                              type="text"
                              placeholder="/api/payments/uddoktapay/ipn"
                              value={gw.webhook_url || gw.ipn_url || ''}
                              onChange={e => {
                                const updated = [...tempGateways];
                                updated[idx].webhook_url = e.target.value;
                                updated[idx].ipn_url = e.target.value;
                                setTempGateways(updated);
                              }}
                              className="w-full px-3 py-1.5 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-white font-mono focus:border-emerald-500 focus:outline-none"
                            />
                          </div>
                        </div>

                        {/* Payment Channels */}
                        <div>
                          <label className="block text-slate-400 mb-1.5 font-semibold">Enabled Payment Channels</label>
                          <div className="flex flex-wrap gap-2">
                            {[
                              { key: 'bkash', label: 'bKash' },
                              { key: 'nagad', label: 'Nagad' },
                              { key: 'rocket', label: 'Rocket' },
                              { key: 'upay', label: 'Upay' },
                              { key: 'cards', label: 'Cards' },
                            ].map(ch => {
                              const channels = gw.allowed_channels || ['bkash', 'nagad', 'rocket', 'upay', 'cards'];
                              const isChecked = channels.includes(ch.key);
                              return (
                                <label
                                  key={ch.key}
                                  className={`px-2.5 py-1 rounded-lg border text-[11px] font-medium flex items-center gap-1.5 cursor-pointer transition-colors ${
                                    isChecked
                                      ? 'bg-emerald-950/60 border-emerald-600/60 text-emerald-300'
                                      : 'bg-[#0A0D0F] border-[#222A33] text-slate-500 hover:text-slate-400'
                                  }`}
                                >
                                  <input
                                    type="checkbox"
                                    checked={isChecked}
                                    onChange={e => {
                                      const updated = [...tempGateways];
                                      const cur = new Set(channels);
                                      if (e.target.checked) cur.add(ch.key);
                                      else cur.delete(ch.key);
                                      updated[idx].allowed_channels = Array.from(cur);
                                      setTempGateways(updated);
                                    }}
                                    className="hidden"
                                  />
                                  <span className={`w-1.5 h-1.5 rounded-full ${isChecked ? 'bg-emerald-400' : 'bg-slate-600'}`} />
                                  <span>{ch.label}</span>
                                </label>
                              );
                            })}
                          </div>
                        </div>

                        {/* Test Connection Button & Status */}
                        <div className="pt-2 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 border-t border-[#222A33]">
                          <button
                            type="button"
                            onClick={() => handleTestConnection(gw)}
                            disabled={testingGatewayId === gw.id}
                            className="px-3.5 py-1.5 rounded-lg bg-emerald-950 border border-emerald-700/60 text-emerald-300 hover:bg-emerald-900 font-medium text-xs flex items-center gap-1.5 cursor-pointer disabled:opacity-50"
                          >
                            {testingGatewayId === gw.id ? (
                              <>
                                <span className="w-3 h-3 rounded-full border-2 border-emerald-400 border-t-transparent animate-spin" />
                                <span>Testing Connection...</span>
                              </>
                            ) : (
                              <span>Test Connection</span>
                            )}
                          </button>

                          {testConnectionResult && testConnectionResult.gatewayId === gw.id && (
                            <div className={`px-3 py-1.5 rounded-lg border text-xs font-mono ${
                              testConnectionResult.success
                                ? 'bg-emerald-950/80 border-emerald-600 text-emerald-300'
                                : 'bg-rose-950/80 border-rose-600 text-rose-300'
                            }`}>
                              {testConnectionResult.message}
                            </div>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                ))}

                <div className="flex justify-end">
                  <button
                    onClick={() => {
                      adminSaveGateways(tempGateways);
                      adminSaveSettings(tempSettings);
                      showToast('Payment settings and gateways saved');
                    }}
                    className="px-6 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs shadow-lg cursor-pointer"
                  >
                    Save Payment Gateways
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* TAB: TRANSACTIONS & AUDIT LOGS */}
          {activeTab === 'transactions' && (
            <div className="space-y-6">
              {/* Transactions Header Summary */}
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div className="p-4 rounded-2xl bg-[#13181D] border border-[#222A33]">
                  <div className="text-slate-400 text-xs mb-1">Total Verified Revenue</div>
                  <div className="text-2xl font-black font-mono text-emerald-400">
                    ৳{payments.filter(p => p.status === 'success').reduce((sum, p) => sum + (Number(p.amount) || 0), 0).toLocaleString()}
                  </div>
                  <span className="text-[10px] text-slate-500">From all processed gateway bids</span>
                </div>

                <div className="p-4 rounded-2xl bg-[#13181D] border border-[#222A33]">
                  <div className="text-slate-400 text-xs mb-1">Successful Payments</div>
                  <div className="text-2xl font-black font-mono text-white">
                    {payments.filter(p => p.status === 'success').length} <span className="text-xs text-slate-500 font-normal">/ {payments.length} total</span>
                  </div>
                  <span className="text-[10px] text-emerald-400 font-medium">100% verified server-side</span>
                </div>

                <div className="p-4 rounded-2xl bg-[#13181D] border border-[#222A33] flex flex-col justify-between">
                  <div className="text-slate-400 text-xs mb-1">Transaction Actions</div>
                  <div className="flex gap-2">
                    <button
                      onClick={async () => {
                        if (payments.length === 0) {
                          showToast('No transactions to clear');
                          return;
                        }
                        if (confirm('Are you sure you want to permanently DELETE ALL payment transactions? This action cannot be undone.')) {
                          await adminClearAllTransactions();
                          showToast('All transactions cleared successfully');
                        }
                      }}
                      className="px-3 py-2 rounded-xl bg-rose-950/60 hover:bg-rose-900 border border-rose-800 text-rose-300 text-xs font-bold flex items-center gap-1.5 cursor-pointer"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                      <span>Clear All Transactions</span>
                    </button>
                  </div>
                  <span className="text-[10px] text-slate-500">Manage transaction audit trail</span>
                </div>
              </div>

              {/* Transactions Table & Filters */}
              <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4">
                <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3">
                  <div className="relative flex-1">
                    <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
                    <input
                      type="text"
                      placeholder="Search by Txn ID, Listing Name, Contact..."
                      value={transactionSearch}
                      onChange={e => setTransactionSearch(e.target.value)}
                      className="w-full pl-9 pr-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white text-xs font-mono focus:border-emerald-500 focus:outline-none"
                    />
                  </div>

                  <div className="flex items-center gap-2">
                    <select
                      value={transactionGatewayFilter}
                      onChange={e => setTransactionGatewayFilter(e.target.value)}
                      className="px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-slate-300 text-xs font-medium focus:border-emerald-500 focus:outline-none"
                    >
                      <option value="all">All Gateways</option>
                      <option value="bkash">bKash</option>
                      <option value="nagad">Nagad</option>
                      <option value="rocket">Rocket</option>
                      <option value="sslcommerz">SSLCommerz</option>
                      <option value="shurjopay">shurjoPay</option>
                      <option value="aamarpay">aamarPay</option>
                      <option value="uddoktapay">UddoktaPay</option>
                      <option value="sandbox">Sandbox / Demo</option>
                    </select>

                    <select
                      value={transactionStatusFilter}
                      onChange={e => setTransactionStatusFilter(e.target.value)}
                      className="px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-slate-300 text-xs font-medium focus:border-emerald-500 focus:outline-none"
                    >
                      <option value="all">All Statuses</option>
                      <option value="success">Success</option>
                      <option value="pending">Pending</option>
                      <option value="failed">Failed</option>
                    </select>
                  </div>
                </div>

                {/* Table */}
                <div className="overflow-x-auto rounded-xl border border-[#222A33]">
                  <table className="w-full text-left text-xs">
                    <thead className="bg-[#0A0D0F] text-slate-400 uppercase font-mono text-[10px] border-b border-[#222A33]">
                      <tr>
                        <th className="p-3">Date & Time</th>
                        <th className="p-3">Txn ID & Gateway</th>
                        <th className="p-3">Listing Name</th>
                        <th className="p-3">User / Contact</th>
                        <th className="p-3 text-right">Amount (৳)</th>
                        <th className="p-3 text-center">Status</th>
                        <th className="p-3 text-right">Action</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-[#222A33] text-slate-300 font-mono">
                      {payments
                        .filter(p => {
                          const matchesSearch =
                            !transactionSearch ||
                            p.transaction_id.toLowerCase().includes(transactionSearch.toLowerCase()) ||
                            p.listing_name.toLowerCase().includes(transactionSearch.toLowerCase()) ||
                            (p.contact_number && p.contact_number.includes(transactionSearch)) ||
                            (p.user_email && p.user_email.toLowerCase().includes(transactionSearch.toLowerCase()));
                          const matchesGateway =
                            transactionGatewayFilter === 'all' || p.gateway.toLowerCase() === transactionGatewayFilter.toLowerCase();
                          const matchesStatus =
                            transactionStatusFilter === 'all' || p.status.toLowerCase() === transactionStatusFilter.toLowerCase();
                          return matchesSearch && matchesGateway && matchesStatus;
                        })
                        .map(p => (
                          <tr key={p.id || p.transaction_id} className="hover:bg-[#151C22] transition-colors">
                            <td className="p-3 text-slate-400 whitespace-nowrap text-[11px]">
                              {new Date(p.created_at).toLocaleString('en-US', {
                                month: 'short',
                                day: 'numeric',
                                hour: '2-digit',
                                minute: '2-digit',
                              })}
                            </td>
                            <td className="p-3">
                              <div className="font-bold text-white text-xs">{p.transaction_id}</div>
                              <span className="text-[10px] px-1.5 py-0.5 rounded bg-[#1C242C] text-emerald-400 uppercase font-bold border border-[#2A3440]">
                                {p.gateway}
                              </span>
                            </td>
                            <td className="p-3 font-sans font-medium text-white max-w-[200px] truncate">
                              {p.listing_name}
                            </td>
                            <td className="p-3 text-slate-400 text-[11px]">
                              {p.contact_number || p.user_email || 'Direct bidder'}
                            </td>
                            <td className="p-3 text-right font-bold text-emerald-400 text-xs">
                              ৳{Number(p.amount).toLocaleString()}
                            </td>
                            <td className="p-3 text-center">
                              <span
                                className={`text-[10px] px-2 py-0.5 rounded-full font-bold uppercase ${
                                  p.status === 'success'
                                    ? 'bg-emerald-950 text-emerald-300 border border-emerald-800'
                                    : 'bg-amber-950 text-amber-300 border border-amber-800'
                                }`}
                              >
                                {p.status}
                              </span>
                            </td>
                            <td className="p-3 text-right">
                              <button
                                onClick={async () => {
                                  if (confirm(`Delete transaction ${p.transaction_id}?`)) {
                                    await adminDeleteTransaction(p.transaction_id || p.id);
                                    showToast(`Transaction ${p.transaction_id} deleted`);
                                  }
                                }}
                                className="p-1.5 rounded-lg bg-rose-950/50 hover:bg-rose-900 border border-rose-900 text-rose-400 hover:text-white transition-colors cursor-pointer"
                                title="Delete Transaction"
                              >
                                <Trash2 className="w-3.5 h-3.5" />
                              </button>
                            </td>
                          </tr>
                        ))}
                    </tbody>
                  </table>

                  {payments.length === 0 && (
                    <div className="p-8 text-center text-slate-500 text-xs">
                      No payment transactions recorded yet. Completed bids will appear here automatically.
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* TAB: VISITOR COUNTERS & TRAFFIC CONTROLLER */}
          {activeTab === 'visitors' && (
            <div className="space-y-6">
              {/* Traffic Metrics Card */}
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div className="p-5 rounded-2xl bg-[#13181D] border border-sky-500/30">
                  <div className="flex items-center justify-between text-slate-400 text-xs mb-1">
                    <span>Live Online Visitors</span>
                    <span className="relative flex h-2 w-2">
                      <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                      <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
                    </span>
                  </div>
                  <div className="text-3xl font-black font-mono text-sky-400">
                    {state.activeVisitors.toLocaleString()}
                  </div>
                  <span className="text-[10px] text-slate-500">Active browser sessions with heartbeat ping</span>
                </div>

                <div className="p-5 rounded-2xl bg-[#13181D] border border-emerald-500/30">
                  <div className="flex items-center justify-between text-slate-400 text-xs mb-1">
                    <span>Total Visitors Since Launch</span>
                    <Globe className="w-4 h-4 text-emerald-400" />
                  </div>
                  <div className="text-3xl font-black font-mono text-emerald-400">
                    {state.totalVisitors.toLocaleString()}
                  </div>
                  <span className="text-[10px] text-slate-500">Total unique client sessions + baseline</span>
                </div>

                <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] flex flex-col justify-between">
                  <div className="text-slate-400 text-xs mb-1">Top Bar Display Status</div>
                  <div className="text-sm font-bold text-white flex items-center gap-2">
                    <span className={`w-2.5 h-2.5 rounded-full ${tempVisitorSettings.is_enabled ? 'bg-emerald-400' : 'bg-rose-500'}`} />
                    <span>{tempVisitorSettings.is_enabled ? 'Active on Frontend' : 'Hidden from Frontend'}</span>
                  </div>
                  <span className="text-[10px] text-slate-500">Top sticky live traffic status bar</span>
                </div>
              </div>

              {/* Visitor Counter Configuration Form */}
              <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-5 text-xs">
                <div className="flex items-center justify-between border-b border-[#222A33] pb-3">
                  <div>
                    <h3 className="font-bold text-sm text-white">Visitor Counter Settings & Baseline Adjustments</h3>
                    <p className="text-[11px] text-slate-400">Configure what visitors see in the top stats bar and calibrate traffic baselines.</p>
                  </div>
                  <button
                    onClick={async () => {
                      await adminUpdateVisitorSettings({
                        ...tempVisitorSettings,
                        baseline_active: customBaselineActive,
                        baseline_total: customBaselineTotal,
                      });
                      showToast('Visitor counter settings updated & synchronized');
                    }}
                    className="px-5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs shadow-lg cursor-pointer"
                  >
                    Save Counter Settings
                  </button>
                </div>

                {/* Display Toggles */}
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                  <div className="p-4 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-2">
                    <label className="flex items-center justify-between cursor-pointer">
                      <span className="font-semibold text-white">Master Enable Stats Bar</span>
                      <input
                        type="checkbox"
                        checked={tempVisitorSettings.is_enabled !== false}
                        onChange={e => setTempVisitorSettings({ ...tempVisitorSettings, is_enabled: e.target.checked })}
                        className="w-4 h-4 accent-emerald-500 rounded cursor-pointer"
                      />
                    </label>
                    <p className="text-[11px] text-slate-500">Toggle whether the top stats bar is rendered on the site.</p>
                  </div>

                  <div className="p-4 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-2">
                    <label className="flex items-center justify-between cursor-pointer">
                      <span className="font-semibold text-white">Show Live Online Counter</span>
                      <input
                        type="checkbox"
                        checked={tempVisitorSettings.show_active_visitors !== false}
                        onChange={e => setTempVisitorSettings({ ...tempVisitorSettings, show_active_visitors: e.target.checked })}
                        className="w-4 h-4 accent-emerald-500 rounded cursor-pointer"
                      />
                    </label>
                    <p className="text-[11px] text-slate-500">Show pulse dot and "X online" counter.</p>
                  </div>

                  <div className="p-4 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-2">
                    <label className="flex items-center justify-between cursor-pointer">
                      <span className="font-semibold text-white">Show Total Visitors Counter</span>
                      <input
                        type="checkbox"
                        checked={tempVisitorSettings.show_total_visitors !== false}
                        onChange={e => setTempVisitorSettings({ ...tempVisitorSettings, show_total_visitors: e.target.checked })}
                        className="w-4 h-4 accent-emerald-500 rounded cursor-pointer"
                      />
                    </label>
                    <p className="text-[11px] text-slate-500">Show "X visitors since launch" counter.</p>
                  </div>
                </div>

                {/* Baseline Inputs */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2">
                  <div className="space-y-1.5">
                    <label className="block text-slate-300 font-semibold">Baseline Active Sessions Offset</label>
                    <input
                      type="number"
                      value={customBaselineActive}
                      onChange={e => setCustomBaselineActive(Number(e.target.value) || 0)}
                      className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                    />
                    <span className="text-[10px] text-slate-500 block">Added to real-time detected browser sessions.</span>
                  </div>

                  <div className="space-y-1.5">
                    <label className="block text-slate-300 font-semibold">Baseline Total Visitors Count</label>
                    <input
                      type="number"
                      value={customBaselineTotal}
                      onChange={e => setCustomBaselineTotal(Number(e.target.value) || 0)}
                      className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                    />
                    <span className="text-[10px] text-slate-500 block">Default is 1,317,970 (or your custom starting count).</span>
                  </div>
                </div>

                {/* Reset & Calibration Tools */}
                <div className="p-4 rounded-xl bg-[#0A0D0F] border border-rose-950/60 space-y-3 pt-3">
                  <h4 className="font-bold text-xs text-rose-300 uppercase tracking-wider flex items-center gap-1.5 font-mono">
                    <RotateCcw className="w-3.5 h-3.5" />
                    <span>Visitor Traffic Reset & Calibration Tools</span>
                  </h4>
                  <div className="flex flex-wrap gap-3">
                    <button
                      onClick={async () => {
                        if (confirm('Reset active sessions pool back to baseline?')) {
                          await adminResetVisitorStats('active', customBaselineActive);
                          showToast('Active visitor sessions reset');
                        }
                      }}
                      className="px-3.5 py-2 rounded-lg bg-[#141A20] hover:bg-rose-950 border border-slate-700 hover:border-rose-700 text-slate-300 hover:text-rose-200 text-xs font-semibold cursor-pointer"
                    >
                      Reset Active Online Count
                    </button>

                    <button
                      onClick={async () => {
                        if (confirm('Reset total visitor counter back to baseline?')) {
                          await adminResetVisitorStats('total', undefined, customBaselineTotal);
                          showToast('Total visitors counter reset');
                        }
                      }}
                      className="px-3.5 py-2 rounded-lg bg-[#141A20] hover:bg-rose-950 border border-slate-700 hover:border-rose-700 text-slate-300 hover:text-rose-200 text-xs font-semibold cursor-pointer"
                    >
                      Reset Total Visitors Count
                    </button>

                    <button
                      onClick={async () => {
                        if (confirm('Reset ALL visitor statistics back to default starting state?')) {
                          await adminResetVisitorStats('all', 0, 1317970);
                          setCustomBaselineActive(0);
                          setCustomBaselineTotal(1317970);
                          showToast('All visitor statistics reset to factory defaults');
                        }
                      }}
                      className="px-3.5 py-2 rounded-lg bg-rose-950/70 hover:bg-rose-900 border border-rose-700 text-rose-200 text-xs font-bold cursor-pointer"
                    >
                      Reset All Traffic Stats (Factory)
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* TAB: DATA RESET & WIPE CENTER */}
          {activeTab === 'reset_center' && (
            <div className="space-y-6">
              <div className="p-5 rounded-2xl bg-[#13181D] border border-rose-900/40">
                <div className="flex items-center gap-3 text-rose-400 mb-1">
                  <RotateCcw className="w-6 h-6 shrink-0" />
                  <div>
                    <h2 className="text-lg font-bold text-white">Data Reset & Wipe Control Center</h2>
                    <p className="text-xs text-slate-400">Manage, reset, and calibrate specific user data, transactions, clicks, revenue metrics, and visitor traffic.</p>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* 1. RESET SPECIFIC USER TRANSACTIONS & REVENUE */}
                <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4">
                  <div className="flex items-center gap-2 text-amber-400 font-bold text-sm">
                    <Receipt className="w-4 h-4" />
                    <span>Reset User Transactions & Revenue</span>
                  </div>
                  <p className="text-xs text-slate-400">
                    Delete transaction logs belonging to a specific user (by phone number, email address, or listing name) to wipe their revenue contribution.
                  </p>
                  <div className="space-y-2">
                    <label className="text-xs text-slate-300 font-medium">User Identifier (Phone, Email, or Listing Name):</label>
                    <div className="flex gap-2">
                      <input
                        type="text"
                        id="userResetInput"
                        placeholder="e.g. 01700000000 or user@mail.com"
                        className="flex-1 px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white text-xs font-mono focus:border-amber-500 focus:outline-none"
                      />
                      <button
                        onClick={async () => {
                          const input = (document.getElementById('userResetInput') as HTMLInputElement)?.value;
                          if (!input || !input.trim()) {
                            showToast('Please enter a user phone, email, or listing name');
                            return;
                          }
                          if (confirm(`Delete ALL transactions matching "${input.trim()}"?`)) {
                            await adminDeleteUserTransactions(input.trim());
                            showToast(`Transactions matching "${input.trim()}" cleared`);
                            (document.getElementById('userResetInput') as HTMLInputElement).value = '';
                          }
                        }}
                        className="px-4 py-2 rounded-xl bg-amber-600 hover:bg-amber-500 text-white font-bold text-xs shrink-0 cursor-pointer"
                      >
                        Wipe User Txns
                      </button>
                    </div>
                  </div>
                  <div className="pt-2 border-t border-[#222A33] flex items-center justify-between">
                    <span className="text-xs text-slate-400">Total System Transactions: <strong className="text-white">{payments.length}</strong></span>
                    <button
                      onClick={async () => {
                        if (payments.length === 0) {
                          showToast('No transactions to reset');
                          return;
                        }
                        if (confirm('Permanently RESET ALL transactions & clear total revenue back to ৳0?')) {
                          await adminClearAllTransactions();
                          showToast('Total system revenue and transactions reset to ৳0');
                        }
                      }}
                      className="px-3 py-1.5 rounded-lg bg-rose-950/80 hover:bg-rose-900 border border-rose-800 text-rose-300 font-bold text-xs cursor-pointer"
                    >
                      Reset All Revenue (৳0)
                    </button>
                  </div>
                </div>

                {/* 2. RESET LISTING CLICKS & USER ENGAGEMENT */}
                <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4">
                  <div className="flex items-center gap-2 text-sky-400 font-bold text-sm">
                    <MousePointerClick className="w-4 h-4" />
                    <span>Reset Specific User / Listing Clicks & Hearts</span>
                  </div>
                  <p className="text-xs text-slate-400">
                    Reset click counters or heart counts for individual listings or reset all user click statistics across the entire directory.
                  </p>

                  <div className="space-y-2">
                    <label className="text-xs text-slate-300 font-medium">Select Specific Listing to Reset:</label>
                    <div className="flex gap-2">
                      <select
                        id="listingResetSelect"
                        className="flex-1 px-3 py-2 rounded-xl bg-[#0A0D0F] border border-[#222A33] text-white text-xs font-mono focus:border-sky-500 focus:outline-none"
                      >
                        <option value="all">-- All Listings --</option>
                        {listings.map(l => (
                          <option key={l.id} value={l.id}>
                            {l.name} ({l.clicks} clicks, {l.hearts} hearts)
                          </option>
                        ))}
                      </select>
                      <button
                        onClick={() => {
                          const val = (document.getElementById('listingResetSelect') as HTMLSelectElement)?.value;
                          const selectedListing = listings.find(l => l.id === val);
                          const name = selectedListing ? selectedListing.name : 'All Listings';
                          if (confirm(`Reset clicks and hearts count for ${name}?`)) {
                            adminResetListingStats(val, 'all');
                            showToast(`Clicks & hearts reset for ${name}`);
                          }
                        }}
                        className="px-4 py-2 rounded-xl bg-sky-600 hover:bg-sky-500 text-white font-bold text-xs shrink-0 cursor-pointer"
                      >
                        Reset Clicks
                      </button>
                    </div>
                  </div>

                  <div className="pt-2 border-t border-[#222A33] flex items-center justify-between">
                    <span className="text-xs text-slate-400">Total User Clicks: <strong className="text-white">{listings.reduce((sum, l) => sum + (l.clicks || 0), 0)}</strong></span>
                    <button
                      onClick={() => {
                        if (confirm('Reset clicks & hearts on ALL listings back to 0?')) {
                          adminResetListingStats('all', 'all');
                          showToast('All listing clicks and hearts reset');
                        }
                      }}
                      className="px-3 py-1.5 rounded-lg bg-sky-950/80 hover:bg-sky-900 border border-sky-800 text-sky-300 font-bold text-xs cursor-pointer"
                    >
                      Reset All Clicks to 0
                    </button>
                  </div>
                </div>

                {/* 3. RESET VISITOR STATISTICS & TRAFFIC */}
                <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4">
                  <div className="flex items-center gap-2 text-emerald-400 font-bold text-sm">
                    <Activity className="w-4 h-4" />
                    <span>Reset Visitor Counters & Traffic</span>
                  </div>
                  <p className="text-xs text-slate-400">
                    Reset active online visitors session memory or clear/calibrate total visitors count shown in the top header bar.
                  </p>

                  <div className="grid grid-cols-2 gap-3">
                    <div className="p-3 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-2">
                      <div className="text-[11px] text-slate-400">Current Online Active</div>
                      <div className="text-xl font-black font-mono text-emerald-400">{state.activeVisitors}</div>
                      <button
                        onClick={async () => {
                          if (confirm('Reset active online visitors counter?')) {
                            await adminResetVisitorStats('active', 0);
                            showToast('Active online visitors count reset');
                          }
                        }}
                        className="w-full py-1.5 rounded-lg bg-emerald-950 hover:bg-emerald-900 border border-emerald-800 text-emerald-300 font-bold text-[11px] cursor-pointer"
                      >
                        Reset Active Count
                      </button>
                    </div>

                    <div className="p-3 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-2">
                      <div className="text-[11px] text-slate-400">Current Total Visitors</div>
                      <div className="text-xl font-black font-mono text-emerald-400">{state.totalVisitors.toLocaleString()}</div>
                      <button
                        onClick={async () => {
                          if (confirm('Reset total visitors counter back to baseline?')) {
                            await adminResetVisitorStats('total', undefined, 1317970);
                            showToast('Total visitors counter reset');
                          }
                        }}
                        className="w-full py-1.5 rounded-lg bg-emerald-950 hover:bg-emerald-900 border border-emerald-800 text-emerald-300 font-bold text-[11px] cursor-pointer"
                      >
                        Reset Total Counter
                      </button>
                    </div>
                  </div>
                </div>

                {/* 4. FULL SYSTEM FACTORY RESET */}
                <div className="p-5 rounded-2xl bg-[#13181D] border border-rose-900/60 space-y-4">
                  <div className="flex items-center gap-2 text-rose-400 font-bold text-sm">
                    <RotateCcw className="w-4 h-4" />
                    <span>Master Factory System Reset</span>
                  </div>
                  <p className="text-xs text-slate-400">
                    Wipe all custom modifications, local storage data, transaction logs, and restore the initial default TOPBD demo state.
                  </p>

                  <div className="p-3 rounded-xl bg-rose-950/30 border border-rose-900/50 text-[11px] text-rose-300 space-y-1">
                    <div>⚠️ <strong>Warning:</strong> Factory reset clears custom listings, custom category order, saved design themes, custom gateway keys, and visitor counters.</div>
                  </div>

                  <button
                    onClick={async () => {
                      if (confirm('CRITICAL ACTION: Are you sure you want to perform a FULL FACTORY RESET? All custom listings, categories, and transactions will be cleared.')) {
                        adminResetData();
                        await adminClearAllTransactions();
                        await adminResetVisitorStats('all', 0, 1317970);
                        showToast('System reset to initial factory state');
                      }
                    }}
                    className="w-full py-2.5 rounded-xl bg-rose-600 hover:bg-rose-500 text-white font-bold text-xs shadow-lg cursor-pointer"
                  >
                    Perform Full Factory Reset
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* TAB 5: DESIGN CUSTOMIZER */}
          {activeTab === 'design' && (
            <div className="space-y-6">
              <div className="p-4 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4">
                <h3 className="font-bold text-sm text-white">Dynamic Color Theme & CSS Variables</h3>
                <p className="text-xs text-slate-400">Changes update live in your browser and will be loaded from the database in the standalone PHP version.</p>

                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4 text-xs">
                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Primary Color</label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={tempDesign.primary_color}
                        onChange={e => setTempDesign({ ...tempDesign, primary_color: e.target.value })}
                        className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer"
                      />
                      <input
                        type="text"
                        value={tempDesign.primary_color}
                        onChange={e => setTempDesign({ ...tempDesign, primary_color: e.target.value })}
                        className="w-full px-2 py-1 bg-[#0A0D0F] border border-[#222A33] rounded text-white font-mono text-xs"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Background Color</label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={tempDesign.background_color}
                        onChange={e => setTempDesign({ ...tempDesign, background_color: e.target.value })}
                        className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer"
                      />
                      <input
                        type="text"
                        value={tempDesign.background_color}
                        onChange={e => setTempDesign({ ...tempDesign, background_color: e.target.value })}
                        className="w-full px-2 py-1 bg-[#0A0D0F] border border-[#222A33] rounded text-white font-mono text-xs"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Card Color</label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={tempDesign.card_color}
                        onChange={e => setTempDesign({ ...tempDesign, card_color: e.target.value })}
                        className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer"
                      />
                      <input
                        type="text"
                        value={tempDesign.card_color}
                        onChange={e => setTempDesign({ ...tempDesign, card_color: e.target.value })}
                        className="w-full px-2 py-1 bg-[#0A0D0F] border border-[#222A33] rounded text-white font-mono text-xs"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Rank #1 Background</label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={tempDesign.rank1_bg}
                        onChange={e => setTempDesign({ ...tempDesign, rank1_bg: e.target.value })}
                        className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer"
                      />
                      <input
                        type="text"
                        value={tempDesign.rank1_bg}
                        onChange={e => setTempDesign({ ...tempDesign, rank1_bg: e.target.value })}
                        className="w-full px-2 py-1 bg-[#0A0D0F] border border-[#222A33] rounded text-white font-mono text-xs"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Footer Background</label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={tempDesign.footer_bg || '#07090B'}
                        onChange={e => setTempDesign({ ...tempDesign, footer_bg: e.target.value })}
                        className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer"
                      />
                      <input
                        type="text"
                        value={tempDesign.footer_bg || '#07090B'}
                        onChange={e => setTempDesign({ ...tempDesign, footer_bg: e.target.value })}
                        className="w-full px-2 py-1 bg-[#0A0D0F] border border-[#222A33] rounded text-white font-mono text-xs"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Footer Text Color</label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={tempDesign.footer_text_color || '#A8A29E'}
                        onChange={e => setTempDesign({ ...tempDesign, footer_text_color: e.target.value })}
                        className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer"
                      />
                      <input
                        type="text"
                        value={tempDesign.footer_text_color || '#A8A29E'}
                        onChange={e => setTempDesign({ ...tempDesign, footer_text_color: e.target.value })}
                        className="w-full px-2 py-1 bg-[#0A0D0F] border border-[#222A33] rounded text-white font-mono text-xs"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Footer Link / Accent Color</label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={tempDesign.footer_link_color || '#E07A5F'}
                        onChange={e => setTempDesign({ ...tempDesign, footer_link_color: e.target.value })}
                        className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer"
                      />
                      <input
                        type="text"
                        value={tempDesign.footer_link_color || '#E07A5F'}
                        onChange={e => setTempDesign({ ...tempDesign, footer_link_color: e.target.value })}
                        className="w-full px-2 py-1 bg-[#0A0D0F] border border-[#222A33] rounded text-white font-mono text-xs"
                      />
                    </div>
                  </div>
                </div>

                {/* Custom CSS Injector & Stylesheet Override */}
                <div className="pt-4 border-t border-[#222A33] space-y-3">
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                    <div className="flex items-center gap-2">
                      <div className="p-1.5 rounded-lg bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
                        <Code className="w-4 h-4" />
                      </div>
                      <div>
                        <label className="font-bold text-white text-xs block">Custom CSS Stylesheet (Backend Injector)</label>
                        <p className="text-[11px] text-slate-400">
                          Add your own custom CSS code to customize fonts, colors, animations, borders, or any element. Injected live into the website.
                        </p>
                      </div>
                    </div>

                    {/* Quick Snippet Buttons */}
                    <div className="flex items-center gap-1.5 flex-wrap">
                      <span className="text-[10px] text-slate-400 font-semibold uppercase">Presets:</span>
                      <button
                        type="button"
                        onClick={() => {
                          const snippet = `\n/* Glowing #1 Rank Card */\n#listing-rank-1 {\n  box-shadow: 0 0 25px rgba(245, 158, 11, 0.35) !important;\n  border-color: rgba(245, 158, 11, 0.6) !important;\n}\n`;
                          setTempDesign({ ...tempDesign, custom_css: (tempDesign.custom_css || '') + snippet });
                          showToast('Glow snippet added');
                        }}
                        className="px-2 py-1 rounded bg-[#0A0D0F] border border-[#222A33] text-[10px] text-amber-300 hover:border-amber-500/50 transition-colors"
                      >
                        + Rank 1 Glow
                      </button>
                      <button
                        type="button"
                        onClick={() => {
                          const snippet = `\n/* Rounded Pill Cards */\n.ranking-card {\n  border-radius: 20px !important;\n}\n`;
                          setTempDesign({ ...tempDesign, custom_css: (tempDesign.custom_css || '') + snippet });
                          showToast('Pill snippet added');
                        }}
                        className="px-2 py-1 rounded bg-[#0A0D0F] border border-[#222A33] text-[10px] text-sky-300 hover:border-sky-500/50 transition-colors"
                      >
                        + Smooth Cards
                      </button>
                      <button
                        type="button"
                        onClick={() => {
                          const snippet = `\n/* Custom Emerald Scrollbar */\n::-webkit-scrollbar {\n  width: 6px;\n}\n::-webkit-scrollbar-thumb {\n  background: #006A4E;\n  border-radius: 4px;\n}\n`;
                          setTempDesign({ ...tempDesign, custom_css: (tempDesign.custom_css || '') + snippet });
                          showToast('Scrollbar snippet added');
                        }}
                        className="px-2 py-1 rounded bg-[#0A0D0F] border border-[#222A33] text-[10px] text-emerald-300 hover:border-emerald-500/50 transition-colors"
                      >
                        + Green Scrollbar
                      </button>
                      <button
                        type="button"
                        onClick={() => {
                          setTempDesign({ ...tempDesign, custom_css: '' });
                          showToast('Custom CSS cleared');
                        }}
                        className="px-2 py-1 rounded bg-rose-950/40 border border-rose-900/50 text-[10px] text-rose-300 hover:bg-rose-900/50 transition-colors"
                      >
                        Clear
                      </button>
                    </div>
                  </div>

                  <div className="relative">
                    <textarea
                      rows={9}
                      value={tempDesign.custom_css || ''}
                      onChange={e => setTempDesign({ ...tempDesign, custom_css: e.target.value })}
                      placeholder={`/* Enter custom CSS rules here (e.g. classes, ids, animations, overrides) */\n\n#topbd-header {\n  /* backdrop-filter: blur(16px); */\n}\n\n.ranking-card:hover {\n  /* transform: translateY(-2px); */\n}`}
                      className="w-full p-3.5 bg-[#07090B] border border-[#222A33] focus:border-emerald-500/60 rounded-xl text-emerald-400 font-mono text-xs leading-relaxed focus:outline-none transition-colors selection:bg-emerald-900/60"
                      spellCheck={false}
                    />
                    <div className="absolute top-2 right-3 pointer-events-none text-[10px] font-mono text-slate-400 uppercase tracking-wider">
                      CSS Editor
                    </div>
                  </div>
                </div>

                <div className="flex justify-end gap-3 pt-3 border-t border-[#222A33]">
                  <button
                    onClick={() => {
                      adminSaveDesign(tempDesign);
                      showToast('Design & Custom CSS saved & applied!');
                    }}
                    className="px-6 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs flex items-center gap-1.5 shadow-lg shadow-emerald-950/50"
                  >
                    <Check className="w-4 h-4" />
                    <span>Save & Apply Design & CSS</span>
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* TAB 6: FRONTEND TEXTS */}
          {activeTab === 'texts' && (
            <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4">
              <h3 className="font-bold text-sm text-white">Frontend Text Management</h3>
              <p className="text-xs text-slate-400">Edit any frontend headline, button, or label without touching code.</p>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-xs">
                <div>
                  <label className="block text-slate-300 font-semibold mb-1">Logo Text</label>
                  <input
                    type="text"
                    value={tempTexts.site_logo_text}
                    onChange={e => setTempTexts({ ...tempTexts, site_logo_text: e.target.value })}
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white"
                  />
                </div>

                <div>
                  <label className="block text-slate-300 font-semibold mb-1">Claim Hero Title Prefix</label>
                  <input
                    type="text"
                    value={tempTexts.claim_hero_title}
                    onChange={e => setTempTexts({ ...tempTexts, claim_hero_title: e.target.value })}
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white"
                  />
                </div>

                <div className="sm:col-span-2">
                  <label className="block text-slate-300 font-semibold mb-1">Hero Description</label>
                  <textarea
                    rows={3}
                    value={tempTexts.claim_hero_desc}
                    onChange={e => setTempTexts({ ...tempTexts, claim_hero_desc: e.target.value })}
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white"
                  />
                </div>

                <div>
                  <label className="block text-slate-300 font-semibold mb-1">Outbid Button Text</label>
                  <input
                    type="text"
                    value={tempTexts.outbid_btn_text}
                    onChange={e => setTempTexts({ ...tempTexts, outbid_btn_text: e.target.value })}
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white"
                  />
                </div>

                <div>
                  <label className="block text-slate-300 font-semibold mb-1">Live Ranking Badge</label>
                  <input
                    type="text"
                    value={tempTexts.live_ranking_badge}
                    onChange={e => setTempTexts({ ...tempTexts, live_ranking_badge: e.target.value })}
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white"
                  />
                </div>
              </div>

              {/* Dedicated Footer Customizer Section */}
              <div className="pt-4 border-t border-[#222A33] space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="font-bold text-xs text-white uppercase tracking-wider text-emerald-400 font-mono">
                      Footer & Domain Rating Customizer
                    </h4>
                    <p className="text-[11px] text-slate-400">
                      Configure the author attribution, sponsor partner link, and the certified domain rating badge in the footer.
                    </p>
                  </div>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3 text-xs">
                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Author Name / Handle</label>
                    <input
                      type="text"
                      placeholder="@jonathan_wilke"
                      value={tempTexts.footer_author_name ?? ''}
                      onChange={e => setTempTexts({ ...tempTexts, footer_author_name: e.target.value })}
                      className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                    />
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Author Custom URL (optional)</label>
                    <input
                      type="text"
                      placeholder="Leave empty for developer modal"
                      value={tempTexts.footer_author_url ?? ''}
                      onChange={e => setTempTexts({ ...tempTexts, footer_author_url: e.target.value })}
                      className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                    />
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Sponsor / Partner Name</label>
                    <input
                      type="text"
                      placeholder="supastarter.dev"
                      value={tempTexts.footer_sponsor_text ?? ''}
                      onChange={e => setTempTexts({ ...tempTexts, footer_sponsor_text: e.target.value })}
                      className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                    />
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Sponsor / Partner URL</label>
                    <input
                      type="url"
                      placeholder="https://supastarter.dev"
                      value={tempTexts.footer_sponsor_url ?? ''}
                      onChange={e => setTempTexts({ ...tempTexts, footer_sponsor_url: e.target.value })}
                      className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                    />
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Domain Name on Badge</label>
                    <input
                      type="text"
                      placeholder="outbid.lol"
                      value={tempTexts.footer_domain_name ?? ''}
                      onChange={e => setTempTexts({ ...tempTexts, footer_domain_name: e.target.value })}
                      className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                    />
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Domain Rating Score (e.g. 32)</label>
                    <input
                      type="text"
                      placeholder="32"
                      value={tempTexts.footer_domain_rating ?? ''}
                      onChange={e => setTempTexts({ ...tempTexts, footer_domain_rating: e.target.value })}
                      className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                    />
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Domain Sub-Label</label>
                    <input
                      type="text"
                      placeholder="CERTIFIED DOMAIN RATING"
                      value={tempTexts.footer_domain_label ?? ''}
                      onChange={e => setTempTexts({ ...tempTexts, footer_domain_label: e.target.value })}
                      className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                    />
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Domain Badge Custom URL (optional)</label>
                    <input
                      type="text"
                      placeholder="Leave empty for live stats modal"
                      value={tempTexts.footer_domain_url ?? ''}
                      onChange={e => setTempTexts({ ...tempTexts, footer_domain_url: e.target.value })}
                      className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                    />
                  </div>

                  <div className="flex items-center pt-5">
                    <label className="flex items-center gap-2 cursor-pointer text-xs">
                      <input
                        type="checkbox"
                        checked={tempTexts.footer_show_rating_badge !== false}
                        onChange={e => setTempTexts({ ...tempTexts, footer_show_rating_badge: e.target.checked })}
                        className="rounded border-slate-700 text-emerald-600 focus:ring-emerald-500"
                      />
                      <span className="text-slate-300 font-semibold">Show Certified Rating Badge</span>
                    </label>
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Footer Text Color</label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={tempDesign.footer_text_color || '#A8A29E'}
                        onChange={e => {
                          const updated = { ...tempDesign, footer_text_color: e.target.value };
                          setTempDesign(updated);
                          adminSaveDesign(updated);
                        }}
                        className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer"
                      />
                      <input
                        type="text"
                        value={tempDesign.footer_text_color || '#A8A29E'}
                        onChange={e => {
                          const updated = { ...tempDesign, footer_text_color: e.target.value };
                          setTempDesign(updated);
                          adminSaveDesign(updated);
                        }}
                        className="w-full px-2 py-1.5 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono text-xs"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Footer Link Color</label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={tempDesign.footer_link_color || '#E07A5F'}
                        onChange={e => {
                          const updated = { ...tempDesign, footer_link_color: e.target.value };
                          setTempDesign(updated);
                          adminSaveDesign(updated);
                        }}
                        className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer"
                      />
                      <input
                        type="text"
                        value={tempDesign.footer_link_color || '#E07A5F'}
                        onChange={e => {
                          const updated = { ...tempDesign, footer_link_color: e.target.value };
                          setTempDesign(updated);
                          adminSaveDesign(updated);
                        }}
                        className="w-full px-2 py-1.5 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono text-xs"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-slate-300 font-semibold mb-1">Footer Background Color</label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={tempDesign.footer_bg || '#07090B'}
                        onChange={e => {
                          const updated = { ...tempDesign, footer_bg: e.target.value };
                          setTempDesign(updated);
                          adminSaveDesign(updated);
                        }}
                        className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer"
                      />
                      <input
                        type="text"
                        value={tempDesign.footer_bg || '#07090B'}
                        onChange={e => {
                          const updated = { ...tempDesign, footer_bg: e.target.value };
                          setTempDesign(updated);
                          adminSaveDesign(updated);
                        }}
                        className="w-full px-2 py-1.5 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono text-xs"
                      />
                    </div>
                  </div>
                </div>
              </div>

              <div className="flex justify-end pt-3 border-t border-[#222A33]">
                <button
                  onClick={() => {
                    adminSaveTexts(tempTexts);
                    showToast('Frontend texts updated!');
                  }}
                  className="px-6 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs cursor-pointer"
                >
                  Save Text Changes
                </button>
              </div>
            </div>
          )}

          {/* TAB 6.5: TRANSLATION MANAGEMENT (EN / BN) */}
          {activeTab === 'translations' && (
            <div className="space-y-4">
              {/* Header & Global Settings Card */}
              <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                  <div className="space-y-1">
                    <div className="flex items-center gap-2">
                      <Languages className="w-5 h-5 text-emerald-400" />
                      <h3 className="font-bold text-base text-white font-mono">English / Bangla Translation Dictionary</h3>
                    </div>
                    <p className="text-xs text-slate-400">
                      Manage all English and Bangla UI texts without touching code. Edits apply immediately to the website.
                    </p>
                  </div>

                  <div className="flex items-center gap-2.5 flex-wrap">
                    {/* Live language toggle test */}
                    <div className="flex items-center p-1 rounded-xl bg-[#0A0D0F] border border-[#222A33]">
                      <button
                        onClick={() => setLanguage('en')}
                        className={`px-3 py-1 rounded-lg text-xs font-bold transition-all cursor-pointer ${
                          language === 'en' ? 'bg-emerald-600 text-white shadow-sm' : 'text-slate-400 hover:text-white'
                        }`}
                      >
                        ENG
                      </button>
                      <button
                        onClick={() => setLanguage('bn')}
                        className={`px-3 py-1 rounded-lg text-xs font-bold font-serif transition-all cursor-pointer ${
                          language === 'bn' ? 'bg-emerald-600 text-white shadow-sm' : 'text-slate-400 hover:text-white'
                        }`}
                      >
                        বাংলা
                      </button>
                    </div>

                    <button
                      onClick={() => setIsAddingTranslation(true)}
                      className="px-3.5 py-1.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-200 font-bold text-xs flex items-center gap-1.5 transition-colors cursor-pointer"
                    >
                      <Plus className="w-3.5 h-3.5 text-emerald-400" />
                      <span>Add String</span>
                    </button>

                    <button
                      onClick={() => {
                        if (confirm('Reset all translations back to factory default English & Bangla dictionaries?')) {
                          adminResetTranslations();
                          showToast('Translations reset to defaults!');
                        }
                      }}
                      className="px-3.5 py-1.5 rounded-xl bg-rose-950/40 hover:bg-rose-900/50 border border-rose-800/40 text-rose-300 text-xs font-semibold flex items-center gap-1.5 transition-colors cursor-pointer"
                    >
                      <RotateCcw className="w-3.5 h-3.5" />
                      <span>Reset Defaults</span>
                    </button>

                    <button
                      onClick={() => {
                        adminSaveTranslations(tempTranslations);
                        showToast('All translations saved successfully!');
                      }}
                      className="px-5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs flex items-center gap-1.5 shadow-lg shadow-emerald-950/60 transition-all cursor-pointer"
                    >
                      <Check className="w-3.5 h-3.5" />
                      <span>Save All Translations</span>
                    </button>
                  </div>
                </div>

                {/* Add String Modal / Expandable Box */}
                {isAddingTranslation && (
                  <div className="p-4 rounded-xl bg-[#0A0D0F] border border-emerald-500/40 space-y-3 animate-in fade-in">
                    <div className="flex items-center justify-between">
                      <span className="font-bold text-xs text-emerald-400 uppercase tracking-wider font-mono">
                        Add New Translation String
                      </span>
                      <button
                        onClick={() => setIsAddingTranslation(false)}
                        className="text-slate-400 hover:text-white"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3 text-xs">
                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Key Name (e.g. custom_button)</label>
                        <input
                          type="text"
                          value={newTransKey}
                          onChange={e => setNewTransKey(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, '_'))}
                          placeholder="my_custom_key"
                          className="w-full px-3 py-1.5 bg-[#141A20] border border-[#222A33] rounded-lg text-white font-mono"
                        />
                      </div>
                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Category Group</label>
                        <select
                          value={newTransCategory}
                          onChange={e => setNewTransCategory(e.target.value)}
                          className="w-full px-3 py-1.5 bg-[#141A20] border border-[#222A33] rounded-lg text-white"
                        >
                          <option value="General">General</option>
                          <option value="Header & Nav">Header & Nav</option>
                          <option value="Hero & Bid Section">Hero & Bid Section</option>
                          <option value="Leaderboard & Listings">Leaderboard & Listings</option>
                          <option value="Outbid & Checkout">Outbid & Checkout</option>
                          <option value="Categories">Categories</option>
                          <option value="Stats & Info">Stats & Info</option>
                          <option value="Footer & Legal">Footer & Legal</option>
                        </select>
                      </div>
                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">English Text</label>
                        <input
                          type="text"
                          value={newTransEn}
                          onChange={e => setNewTransEn(e.target.value)}
                          placeholder="English text"
                          className="w-full px-3 py-1.5 bg-[#141A20] border border-[#222A33] rounded-lg text-white"
                        />
                      </div>
                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Bangla Text (বাংলা)</label>
                        <input
                          type="text"
                          value={newTransBn}
                          onChange={e => setNewTransBn(e.target.value)}
                          placeholder="বাংলা টেক্সট"
                          className="w-full px-3 py-1.5 bg-[#141A20] border border-[#222A33] rounded-lg text-white"
                        />
                      </div>
                    </div>

                    <div className="flex justify-end gap-2 pt-2">
                      <button
                        onClick={() => setIsAddingTranslation(false)}
                        className="px-3 py-1.5 rounded-lg bg-slate-800 text-slate-300 text-xs font-semibold"
                      >
                        Cancel
                      </button>
                      <button
                        onClick={() => {
                          if (!newTransKey.trim() || !newTransEn.trim()) {
                            alert('Please enter a key name and English text');
                            return;
                          }
                          const updated = {
                            ...tempTranslations,
                            [newTransKey.trim()]: {
                              en: newTransEn.trim(),
                              bn: newTransBn.trim() || newTransEn.trim(),
                              category: newTransCategory
                            }
                          };
                          setTempTranslations(updated);
                          adminSaveTranslations(updated);
                          setIsAddingTranslation(false);
                          setNewTransKey('');
                          setNewTransEn('');
                          setNewTransBn('');
                          showToast(`Added "${newTransKey.trim()}"`);
                        }}
                        className="px-4 py-1.5 rounded-lg bg-emerald-600 text-white font-bold text-xs"
                      >
                        Add Key
                      </button>
                    </div>
                  </div>
                )}

                {/* Filter and Search Bar */}
                <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 pt-2 border-t border-[#222A33]">
                  {/* Category Filter Pills */}
                  <div className="flex items-center gap-1.5 overflow-x-auto pb-1 text-xs no-scrollbar">
                    {[
                      { id: 'all', label: 'All Strings' },
                      { id: 'Header & Nav', label: 'Header & Nav' },
                      { id: 'Hero & Bid Section', label: 'Hero & Bid' },
                      { id: 'Leaderboard & Listings', label: 'Leaderboard' },
                      { id: 'Outbid & Checkout', label: 'Checkout & Modal' },
                      { id: 'Categories', label: 'Categories' },
                      { id: 'Stats & Info', label: 'Stats & Info' },
                      { id: 'Footer & Legal', label: 'Footer & Legal' },
                    ].map(cat => (
                      <button
                        key={cat.id}
                        onClick={() => setTranslationCategoryFilter(cat.id)}
                        className={`px-3 py-1.5 rounded-xl whitespace-nowrap text-xs font-semibold transition-all cursor-pointer ${
                          translationCategoryFilter === cat.id
                            ? 'bg-emerald-600 text-white shadow-sm'
                            : 'bg-[#0A0D0F] text-slate-400 hover:text-slate-200 border border-[#222A33]'
                        }`}
                      >
                        {cat.label}
                      </button>
                    ))}
                  </div>

                  {/* Search Input */}
                  <div className="relative w-full sm:w-64 shrink-0">
                    <Search className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
                    <input
                      type="text"
                      value={translationSearch}
                      onChange={e => setTranslationSearch(e.target.value)}
                      placeholder="Search key or text..."
                      className="w-full pl-9 pr-3 py-1.5 bg-[#0A0D0F] border border-[#222A33] focus:border-emerald-500 rounded-xl text-xs text-white placeholder-slate-500 focus:outline-none"
                    />
                  </div>
                </div>
              </div>

              {/* Translation Dictionary Table / Card Grid */}
              <div className="space-y-3">
                {(() => {
                  const entries = (Object.entries(tempTranslations) as [string, { en: string; bn: string; category?: string }][]).filter(([key, data]) => {
                    const matchCategory =
                      translationCategoryFilter === 'all' ||
                      data.category === translationCategoryFilter ||
                      (!data.category && translationCategoryFilter === 'General');

                    const matchSearch =
                      !translationSearch.trim() ||
                      key.toLowerCase().includes(translationSearch.toLowerCase()) ||
                      data.en.toLowerCase().includes(translationSearch.toLowerCase()) ||
                      data.bn.toLowerCase().includes(translationSearch.toLowerCase()) ||
                      (data.category && data.category.toLowerCase().includes(translationSearch.toLowerCase()));

                    return matchCategory && matchSearch;
                  });

                  if (entries.length === 0) {
                    return (
                      <div className="p-8 text-center bg-[#13181D] border border-[#222A33] rounded-2xl text-slate-400 text-xs">
                        No translation entries match your search or filter.
                      </div>
                    );
                  }

                  return (
                    <div className="space-y-2">
                      <div className="flex items-center justify-between px-2 text-[11px] text-slate-500 font-mono">
                        <span>Showing {entries.length} translation strings</span>
                        <span>Auto-interpolated parameters: <code className="text-amber-400">{'{count}'}</code>, <code className="text-amber-400">{'{amount}'}</code>, <code className="text-amber-400">{'{rank}'}</code></span>
                      </div>

                      {entries.map(([key, data]) => (
                        <div
                          key={key}
                          className="p-3.5 sm:p-4 rounded-xl bg-[#13181D] border border-[#222A33] hover:border-[#2F3D4C] transition-colors space-y-2.5"
                        >
                          <div className="flex items-center justify-between gap-2 flex-wrap">
                            <div className="flex items-center gap-2">
                              <span className="px-2 py-0.5 rounded-md bg-[#0A0D0F] border border-slate-800 text-emerald-400 font-mono text-xs font-semibold">
                                {key}
                              </span>
                              {data.category && (
                                <span className="px-2 py-0.5 rounded-md bg-slate-800 text-slate-400 text-[10px] font-semibold">
                                  {data.category}
                                </span>
                              )}
                            </div>
                            <span className="text-[10px] text-slate-500 font-mono">
                              Key ID: {key}
                            </span>
                          </div>

                          <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-xs">
                            {/* English Field */}
                            <div className="space-y-1">
                              <label className="block text-[11px] font-bold text-slate-400 uppercase tracking-wider flex items-center justify-between">
                                <span>English (EN)</span>
                              </label>
                              <textarea
                                rows={data.en.length > 60 ? 2 : 1}
                                value={data.en}
                                onChange={e => {
                                  setTempTranslations(prev => ({
                                    ...prev,
                                    [key]: {
                                      ...prev[key],
                                      en: e.target.value
                                    }
                                  }));
                                }}
                                className="w-full px-3 py-1.5 bg-[#0A0D0F] border border-[#222A33] focus:border-emerald-500 rounded-lg text-white focus:outline-none transition-colors text-xs resize-y"
                              />
                            </div>

                            {/* Bangla Field */}
                            <div className="space-y-1">
                              <label className="block text-[11px] font-bold text-emerald-400 uppercase tracking-wider flex items-center justify-between">
                                <span>Bangla (বাংলা)</span>
                              </label>
                              <textarea
                                rows={data.bn.length > 60 ? 2 : 1}
                                value={data.bn}
                                onChange={e => {
                                  setTempTranslations(prev => ({
                                    ...prev,
                                    [key]: {
                                      ...prev[key],
                                      bn: e.target.value
                                    }
                                  }));
                                }}
                                className="w-full px-3 py-1.5 bg-[#0A0D0F] border border-[#222A33] focus:border-emerald-500 rounded-lg text-white focus:outline-none transition-colors text-xs resize-y font-sans"
                              />
                            </div>
                          </div>
                        </div>
                      ))}

                      {/* Sticky / Bottom Save Bar */}
                      <div className="sticky bottom-4 p-4 rounded-2xl bg-[#0E1216]/95 backdrop-blur-md border border-emerald-500/40 shadow-2xl flex items-center justify-between gap-4 mt-6">
                        <div className="text-xs text-slate-300">
                          <span className="font-bold text-white block">Ready to update website translations?</span>
                          <span className="text-[11px] text-slate-400">All changes will take effect immediately across the app without refresh.</span>
                        </div>
                        <button
                          onClick={() => {
                            adminSaveTranslations(tempTranslations);
                            showToast('All translation changes saved!');
                          }}
                          className="px-6 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs flex items-center gap-2 shadow-lg shadow-emerald-950/60 transition-all cursor-pointer shrink-0"
                        >
                          <Check className="w-4 h-4" />
                          <span>Save All Translations</span>
                        </button>
                      </div>
                    </div>
                  );
                })()}
              </div>
            </div>
          )}

          {/* TAB: SCROLL POPUP (BUILT BY) */}
          {activeTab === 'popup' && (
            <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-6 text-xs">
              <div className="flex items-center justify-between gap-4 flex-wrap pb-4 border-b border-[#222A33]">
                <div>
                  <h3 className="font-bold text-sm text-white flex items-center gap-2">
                    <Sparkles className="w-4 h-4 text-amber-400" />
                    <span>Floating Scroll Popup ("Built by") Customizer</span>
                  </h3>
                  <p className="text-xs text-slate-400 mt-0.5">
                    Controls the bottom-right capsule pill that automatically displays when visitors scroll down the page.
                  </p>
                </div>

                <div className="flex items-center gap-3">
                  <span className="text-xs font-semibold text-slate-300">Popup Status:</span>
                  <button
                    type="button"
                    onClick={() => setTempScrollPopup(prev => ({ ...prev, is_enabled: !prev.is_enabled }))}
                    className={`px-4 py-1.5 rounded-full font-bold text-xs transition-all cursor-pointer flex items-center gap-1.5 ${
                      tempScrollPopup.is_enabled
                        ? 'bg-emerald-600 text-white shadow-md shadow-emerald-950'
                        : 'bg-slate-800 text-slate-400 hover:text-white'
                    }`}
                  >
                    {tempScrollPopup.is_enabled ? (
                      <>
                        <Eye className="w-3.5 h-3.5" />
                        <span>Enabled (Active)</span>
                      </>
                    ) : (
                      <>
                        <EyeOff className="w-3.5 h-3.5" />
                        <span>Disabled (Turned Off)</span>
                      </>
                    )}
                  </button>
                </div>
              </div>

              {/* Grid of Settings */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Column 1: Configuration Controls */}
                <div className="space-y-4">
                  {/* Scroll Threshold Slider */}
                  <div className="p-4 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-2">
                    <div className="flex justify-between items-center">
                      <label className="font-semibold text-slate-200">Scroll Trigger Threshold (%)</label>
                      <span className="px-2 py-0.5 rounded bg-emerald-950/80 border border-emerald-800/80 text-emerald-400 font-mono font-bold">
                        {tempScrollPopup.scroll_threshold_percent ?? 20}% of page
                      </span>
                    </div>
                    <input
                      type="range"
                      min={5}
                      max={90}
                      step={5}
                      value={tempScrollPopup.scroll_threshold_percent ?? 20}
                      onChange={e => setTempScrollPopup({ ...tempScrollPopup, scroll_threshold_percent: Number(e.target.value) })}
                      className="w-full accent-emerald-500 cursor-pointer"
                    />
                    <p className="text-[11px] text-slate-500">
                      Popup triggers smoothly when user scrolls past this percentage of the total page height (Recommended: 20%–30%).
                    </p>
                  </div>

                  {/* Text Inputs & Colors */}
                  <div className="p-4 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-4">
                    <h4 className="font-bold text-white text-xs">Text & Typography Colors</h4>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Prefix Text</label>
                        <input
                          type="text"
                          value={tempScrollPopup.prefix_text}
                          onChange={e => setTempScrollPopup({ ...tempScrollPopup, prefix_text: e.target.value })}
                          placeholder="e.g. Built by"
                          className="w-full px-3 py-2 bg-[#141A20] border border-[#222A33] focus:border-emerald-500 rounded-xl text-white"
                        />
                      </div>

                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Prefix Color</label>
                        <div className="flex items-center gap-2">
                          <input
                            type="color"
                            value={tempScrollPopup.prefix_color || '#64748B'}
                            onChange={e => setTempScrollPopup({ ...tempScrollPopup, prefix_color: e.target.value })}
                            className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer shrink-0"
                          />
                          <input
                            type="text"
                            value={tempScrollPopup.prefix_color || '#64748B'}
                            onChange={e => setTempScrollPopup({ ...tempScrollPopup, prefix_color: e.target.value })}
                            className="w-full px-2.5 py-1.5 bg-[#141A20] border border-[#222A33] rounded-lg text-white font-mono text-xs"
                          />
                        </div>
                      </div>

                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Author / Handle Text</label>
                        <input
                          type="text"
                          value={tempScrollPopup.author_text}
                          onChange={e => setTempScrollPopup({ ...tempScrollPopup, author_text: e.target.value })}
                          placeholder="e.g. @jonathanwilke"
                          className="w-full px-3 py-2 bg-[#141A20] border border-[#222A33] focus:border-emerald-500 rounded-xl text-white"
                        />
                      </div>

                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Author Color</label>
                        <div className="flex items-center gap-2">
                          <input
                            type="color"
                            value={tempScrollPopup.author_color || '#E07A5F'}
                            onChange={e => setTempScrollPopup({ ...tempScrollPopup, author_color: e.target.value })}
                            className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer shrink-0"
                          />
                          <input
                            type="text"
                            value={tempScrollPopup.author_color || '#E07A5F'}
                            onChange={e => setTempScrollPopup({ ...tempScrollPopup, author_color: e.target.value })}
                            className="w-full px-2.5 py-1.5 bg-[#141A20] border border-[#222A33] rounded-lg text-white font-mono text-xs"
                          />
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Capsule Container Colors & Click Target */}
                  <div className="p-4 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-4">
                    <h4 className="font-bold text-white text-xs">Capsule Container Styling & Link Target</h4>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Capsule Background</label>
                        <div className="flex items-center gap-2">
                          <input
                            type="color"
                            value={tempScrollPopup.bg_color || '#FFFFFF'}
                            onChange={e => setTempScrollPopup({ ...tempScrollPopup, bg_color: e.target.value })}
                            className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer shrink-0"
                          />
                          <input
                            type="text"
                            value={tempScrollPopup.bg_color || '#FFFFFF'}
                            onChange={e => setTempScrollPopup({ ...tempScrollPopup, bg_color: e.target.value })}
                            className="w-full px-2.5 py-1.5 bg-[#141A20] border border-[#222A33] rounded-lg text-white font-mono text-xs"
                          />
                        </div>
                      </div>

                      <div>
                        <label className="block text-slate-300 font-semibold mb-1">Capsule Border</label>
                        <div className="flex items-center gap-2">
                          <input
                            type="color"
                            value={tempScrollPopup.border_color || '#F4ECE7'}
                            onChange={e => setTempScrollPopup({ ...tempScrollPopup, border_color: e.target.value })}
                            className="w-8 h-8 rounded border-0 bg-transparent cursor-pointer shrink-0"
                          />
                          <input
                            type="text"
                            value={tempScrollPopup.border_color || '#F4ECE7'}
                            onChange={e => setTempScrollPopup({ ...tempScrollPopup, border_color: e.target.value })}
                            className="w-full px-2.5 py-1.5 bg-[#141A20] border border-[#222A33] rounded-lg text-white font-mono text-xs"
                          />
                        </div>
                      </div>
                    </div>

                    <div>
                      <label className="block text-slate-300 font-semibold mb-1">
                        Target URL on Click (Optional)
                      </label>
                      <input
                        type="text"
                        value={tempScrollPopup.target_url || ''}
                        onChange={e => setTempScrollPopup({ ...tempScrollPopup, target_url: e.target.value })}
                        placeholder="e.g. https://x.com/jonathan_wilke (Leave empty to open built-in developer bio popup)"
                        className="w-full px-3 py-2 bg-[#141A20] border border-[#222A33] focus:border-emerald-500 rounded-xl text-white font-mono text-xs"
                      />
                      <p className="text-[11px] text-slate-500 mt-1">
                        If left blank, clicking the floating pill automatically opens the interactive Developer profile modal!
                      </p>
                    </div>

                    <div className="flex items-center gap-2 pt-2 border-t border-[#1C242C]">
                      <input
                        type="checkbox"
                        id="check-show-close-btn"
                        checked={tempScrollPopup.show_close_button !== false}
                        onChange={e => setTempScrollPopup({ ...tempScrollPopup, show_close_button: e.target.checked })}
                        className="rounded accent-emerald-500 w-4 h-4 cursor-pointer"
                      />
                      <label htmlFor="check-show-close-btn" className="text-slate-300 cursor-pointer font-medium">
                        Show hover dismiss button (allows visitor to temporarily hide the popup)
                      </label>
                    </div>
                  </div>
                </div>

                {/* Column 2: Image Upload & Live Real-Time Preview */}
                <div className="space-y-4">
                  {/* Image Uploader Card */}
                  <div className="p-4 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-4">
                    <div className="flex items-center justify-between">
                      <h4 className="font-bold text-white text-xs flex items-center gap-1.5">
                        <Upload className="w-4 h-4 text-emerald-400" />
                        <span>Avatar Image Upload & Selector</span>
                      </h4>
                      {tempScrollPopup.avatar_image_url && (
                        <button
                          type="button"
                          onClick={() => setTempScrollPopup(prev => ({ ...prev, avatar_image_url: '' }))}
                          className="text-[11px] text-rose-400 hover:text-rose-300 font-semibold cursor-pointer"
                        >
                          Remove Image
                        </button>
                      )}
                    </div>

                    {/* Drag & Drop File Upload Area */}
                    <div className="relative border-2 border-dashed border-[#222A33] hover:border-emerald-500/80 transition-colors rounded-2xl p-4 text-center group bg-[#11161C]">
                      <input
                        type="file"
                        accept="image/*"
                        onChange={handleScrollPopupImageUpload}
                        className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"
                        title="Upload Avatar Image"
                      />
                      <div className="flex flex-col items-center justify-center gap-2">
                        <div className="w-12 h-12 rounded-full bg-emerald-600/10 border border-emerald-500/30 flex items-center justify-center text-emerald-400 group-hover:scale-110 transition-transform">
                          <Upload className="w-5 h-5" />
                        </div>
                        <div>
                          <p className="font-semibold text-slate-200 text-xs">
                            Click to upload or drag & drop avatar image
                          </p>
                          <p className="text-[11px] text-slate-500">
                            PNG, JPG, WebP, or GIF (Instant base64 conversion)
                          </p>
                        </div>
                      </div>
                    </div>

                    {/* Direct URL Input */}
                    <div>
                      <label className="block text-slate-300 font-semibold mb-1">Or Direct Image URL</label>
                      <input
                        type="text"
                        value={tempScrollPopup.avatar_image_url || ''}
                        onChange={e => setTempScrollPopup({ ...tempScrollPopup, avatar_image_url: e.target.value })}
                        placeholder="https://images.unsplash.com/... or /avatar.png"
                        className="w-full px-3 py-2 bg-[#141A20] border border-[#222A33] focus:border-emerald-500 rounded-xl text-white font-mono text-xs"
                      />
                    </div>

                    {/* One-Click Preset Avatar Options */}
                    <div>
                      <label className="block text-slate-400 text-[11px] font-semibold mb-2">
                        Quick Preset Avatars:
                      </label>
                      <div className="flex items-center gap-2.5 flex-wrap">
                        {[
                          { label: 'Founder A', url: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200&auto=format&fit=crop&q=80' },
                          { label: 'Founder B', url: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=200&auto=format&fit=crop&q=80' },
                          { label: 'Engineer', url: 'https://images.unsplash.com/photo-1539571696357-5a69c17a67c6?w=200&auto=format&fit=crop&q=80' },
                          { label: 'Creative', url: 'https://images.unsplash.com/photo-1517841905240-472988babdf9?w=200&auto=format&fit=crop&q=80' },
                          { label: 'BD Flag', url: 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=200&auto=format&fit=crop&q=80' },
                        ].map((preset, idx) => (
                          <button
                            key={idx}
                            type="button"
                            onClick={() => setTempScrollPopup(prev => ({ ...prev, avatar_image_url: preset.url }))}
                            className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-[#141A20] border border-[#222A33] hover:border-emerald-500 transition-all text-[11px] text-slate-300 hover:text-white cursor-pointer"
                          >
                            <img src={preset.url} alt={preset.label} className="w-4 h-4 rounded-full object-cover" />
                            <span>{preset.label}</span>
                          </button>
                        ))}
                      </div>
                    </div>
                  </div>

                  {/* Live Real-Time Interactive Preview Card */}
                  <div className="p-4 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-3">
                    <div className="flex items-center justify-between">
                      <h4 className="font-bold text-white text-xs flex items-center gap-1.5">
                        <Eye className="w-4 h-4 text-amber-400" />
                        <span>Interactive Real-Time Preview</span>
                      </h4>
                      <span className="text-[11px] text-slate-500">Simulated Display</span>
                    </div>

                    <div className="p-8 rounded-xl bg-[#11161C] border border-[#222A33] flex flex-col items-center justify-center min-h-[120px] relative overflow-hidden">
                      {/* Grid background effect */}
                      <div className="absolute inset-0 opacity-20 bg-[radial-gradient(#222A33_1px,transparent_1px)] [background-size:12px_12px]" />

                      {/* Simulated Capsule Popup */}
                      <div
                        className="flex items-center gap-2.5 px-5 py-2.5 rounded-full shadow-2xl hover:scale-105 active:scale-95 transition-all duration-200 cursor-pointer border relative select-none z-10"
                        style={{
                          backgroundColor: tempScrollPopup.bg_color || '#FFFFFF',
                          borderColor: tempScrollPopup.border_color || '#F4ECE7',
                        }}
                      >
                        {tempScrollPopup.show_close_button !== false && (
                          <div className="absolute -top-1.5 -left-1.5 w-5 h-5 rounded-full bg-slate-800 text-white flex items-center justify-center shadow-md text-xs">
                            <X className="w-3 h-3" />
                          </div>
                        )}
                        <div className="flex items-center gap-1.5 font-medium text-sm tracking-tight whitespace-nowrap">
                          <span style={{ color: tempScrollPopup.prefix_color || '#64748B' }}>
                            {tempScrollPopup.prefix_text || 'Built by'}
                          </span>
                          <span
                            style={{ color: tempScrollPopup.author_color || '#E07A5F' }}
                            className="font-semibold hover:underline"
                          >
                            {tempScrollPopup.author_text || '@jonathanwilke'}
                          </span>
                        </div>
                        {tempScrollPopup.avatar_image_url && (
                          <img
                            src={tempScrollPopup.avatar_image_url}
                            alt="Avatar"
                            className="w-8 h-8 rounded-full object-cover shrink-0 border border-black/10 shadow-sm"
                          />
                        )}
                      </div>

                      <p className="text-[10px] text-slate-500 mt-4 z-10 font-mono">
                        Status: {tempScrollPopup.is_enabled ? 'Active on scroll ≥ ' + (tempScrollPopup.scroll_threshold_percent || 20) + '%' : 'Currently Disabled'}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              {/* Action Buttons Bar */}
              <div className="pt-4 border-t border-[#222A33] flex items-center justify-between flex-wrap gap-3">
                <button
                  type="button"
                  onClick={() => {
                    setTempScrollPopup({
                      is_enabled: true,
                      scroll_threshold_percent: 20,
                      prefix_text: 'Built by',
                      prefix_color: '#64748B',
                      author_text: '@jonathanwilke',
                      author_color: '#E07A5F',
                      bg_color: '#FFFFFF',
                      border_color: '#F4ECE7',
                      avatar_image_url: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200&auto=format&fit=crop&q=80',
                      target_url: '',
                      show_close_button: true,
                    });
                    showToast('Popup reset to defaults');
                  }}
                  className="px-4 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 font-semibold cursor-pointer"
                >
                  Reset Defaults
                </button>

                <button
                  type="button"
                  onClick={() => {
                    adminSaveScrollPopup(tempScrollPopup);
                    showToast('Scroll popup settings saved & live!');
                  }}
                  className="px-6 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold flex items-center gap-2 shadow-lg shadow-emerald-950/60 cursor-pointer"
                >
                  <Check className="w-4 h-4" />
                  <span>Save & Apply Popup Settings</span>
                </button>
              </div>
            </div>
          )}

          {/* TAB 7: NAVIGATION & FOOTER MENU MANAGEMENT */}
          {activeTab === 'menu' && (
            <div className="space-y-6">
              {/* Top Banner & Actions */}
              <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                  <div>
                    <h3 className="font-bold text-sm text-white flex items-center gap-2">
                      <MenuIcon className="w-4 h-4 text-emerald-400" />
                      <span>Header & Footer Menu Management</span>
                    </h3>
                    <p className="text-xs text-slate-400 mt-0.5">
                      Create, edit, remove, and reorder links for Header navigation, Footer links, or popup modals with custom descriptions.
                    </p>
                  </div>

                  <button
                    onClick={() => {
                      setIsAddingMenu(true);
                      setNewMenuTitle('');
                      setNewMenuUrl('');
                      setNewMenuDesc('');
                      setNewMenuLocation('both');
                      setNewMenuTarget('_self');
                      setNewMenuOpenAs('link');
                    }}
                    className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs flex items-center gap-1.5 shadow-lg shadow-emerald-950/40 cursor-pointer self-start sm:self-auto"
                  >
                    <Plus className="w-4 h-4" />
                    <span>Add New Menu Item</span>
                  </button>
                </div>

                {/* Footer Admin Button Fast Toggle Card */}
                <div className="p-3.5 rounded-xl bg-[#0A0D0F] border border-[#222A33] flex items-center justify-between gap-4">
                  <div className="flex items-center gap-2.5">
                    <div className="p-2 rounded-lg bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
                      <Shield className="w-4 h-4" />
                    </div>
                    <div>
                      <span className="font-bold text-xs text-white block">Footer "Admin Panel" Menu Button</span>
                      <span className="text-[11px] text-slate-400 block">
                        Turn ON/OFF the public Admin Panel link in the footer. (Always accessible via shortcut <code className="text-emerald-400 font-mono">Ctrl+Shift+A</code>).
                      </span>
                    </div>
                  </div>

                  <button
                    type="button"
                    onClick={() => {
                      const updatedState = !(tempSettings.show_footer_admin_button !== false);
                      const updated = { ...tempSettings, show_footer_admin_button: updatedState };
                      setTempSettings(updated);
                      adminSaveSettings(updated);
                      showToast(`Footer Admin button ${updatedState ? 'Turned ON' : 'Turned OFF'}`);
                    }}
                    className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-all cursor-pointer flex items-center gap-1.5 ${
                      tempSettings.show_footer_admin_button !== false
                        ? 'bg-emerald-600 text-white shadow-sm'
                        : 'bg-slate-800 text-slate-400 hover:text-slate-200'
                    }`}
                  >
                    {tempSettings.show_footer_admin_button !== false ? (
                      <>
                        <Eye className="w-3.5 h-3.5" />
                        <span>ON (Visible)</span>
                      </>
                    ) : (
                      <>
                        <EyeOff className="w-3.5 h-3.5" />
                        <span>OFF (Hidden)</span>
                      </>
                    )}
                  </button>
                </div>

                {/* Quick Presets Bar */}
                <div className="pt-2 flex items-center gap-1.5 flex-wrap text-xs">
                  <span className="text-[11px] text-slate-400 font-semibold uppercase">Quick Add Templates:</span>
                  <button
                    type="button"
                    onClick={() => {
                      const item: MenuItem = {
                        id: `menu_${Date.now()}`,
                        title: 'Rules',
                        url: '#rules',
                        description: 'Official bidding regulations, outbid mechanics, and listing guidelines for TOPBD.',
                        location: 'both',
                        target: '_self',
                        open_as: 'modal',
                        display_order: menuItems.length + 1,
                        is_active: true
                      };
                      adminSaveMenuItems([...menuItems, item]);
                      showToast('Added Rules Modal menu');
                    }}
                    className="px-2.5 py-1 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-emerald-400 hover:border-emerald-500/50 text-[11px] font-medium"
                  >
                    + Rules Modal
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      const item: MenuItem = {
                        id: `menu_${Date.now()}`,
                        title: 'Live stats',
                        url: '#stats',
                        description: 'Real-time transaction volume, active visitors, and verified listings dashboard.',
                        location: 'both',
                        target: '_self',
                        open_as: 'modal',
                        display_order: menuItems.length + 1,
                        is_active: true
                      };
                      adminSaveMenuItems([...menuItems, item]);
                      showToast('Added Live Stats Modal menu');
                    }}
                    className="px-2.5 py-1 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-purple-400 hover:border-purple-500/50 text-[11px] font-medium"
                  >
                    + Live Stats
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      const item: MenuItem = {
                        id: `menu_${Date.now()}`,
                        title: 'Discord Community',
                        url: 'https://discord.gg/topbd',
                        description: 'Join our official community server for live auction alerts and support.',
                        location: 'both',
                        target: '_blank',
                        open_as: 'link',
                        display_order: menuItems.length + 1,
                        is_active: true
                      };
                      adminSaveMenuItems([...menuItems, item]);
                      showToast('Added Discord Link');
                    }}
                    className="px-2.5 py-1 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-indigo-400 hover:border-indigo-500/50 text-[11px] font-medium"
                  >
                    + Discord Community
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      const item: MenuItem = {
                        id: `menu_${Date.now()}`,
                        title: 'Facebook Group',
                        url: 'https://facebook.com/groups/topbd',
                        description: 'Bangladesh official entrepreneur network & top bidder discussion forum.',
                        location: 'footer',
                        target: '_blank',
                        open_as: 'link',
                        display_order: menuItems.length + 1,
                        is_active: true
                      };
                      adminSaveMenuItems([...menuItems, item]);
                      showToast('Added Facebook Link');
                    }}
                    className="px-2.5 py-1 rounded-lg bg-[#0A0D0F] border border-[#222A33] text-sky-400 hover:border-sky-500/50 text-[11px] font-medium"
                  >
                    + Facebook Group
                  </button>
                </div>
              </div>

              {/* Add New Menu Modal / Inline Form */}
              {isAddingMenu && (
                <div className="p-5 rounded-2xl bg-[#141A20] border-2 border-emerald-500/50 shadow-2xl space-y-4 animate-in fade-in duration-200">
                  <div className="flex items-center justify-between border-b border-[#222A33] pb-3">
                    <h4 className="font-bold text-sm text-white flex items-center gap-2">
                      <Plus className="w-4 h-4 text-emerald-400" />
                      <span>Create New Menu Link / Modal</span>
                    </h4>
                    <button
                      onClick={() => setIsAddingMenu(false)}
                      className="p-1 rounded-lg text-slate-400 hover:text-white"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3 text-xs">
                    <div>
                      <label className="block text-slate-300 font-semibold mb-1">Menu Text / Title *</label>
                      <input
                        type="text"
                        placeholder="e.g. VIP Telegram, About Us, Contact"
                        value={newMenuTitle}
                        onChange={e => setNewMenuTitle(e.target.value)}
                        className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-medium"
                      />
                    </div>

                    <div>
                      <label className="block text-slate-300 font-semibold mb-1">Target URL / Anchor *</label>
                      <input
                        type="text"
                        placeholder="e.g. https://t.me/..., #rules, /about"
                        value={newMenuUrl}
                        onChange={e => setNewMenuUrl(e.target.value)}
                        className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-slate-200 font-mono"
                      />
                    </div>

                    <div>
                      <label className="block text-slate-300 font-semibold mb-1">Menu Placement Location</label>
                      <select
                        value={newMenuLocation}
                        onChange={e => setNewMenuLocation(e.target.value as 'header' | 'footer' | 'both')}
                        className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-medium"
                      >
                        <option value="both">Both Header & Footer</option>
                        <option value="header">Header Navigation Only</option>
                        <option value="footer">Footer Bar Only</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-slate-300 font-semibold mb-1">Open Action Behavior</label>
                      <select
                        value={newMenuOpenAs}
                        onChange={e => setNewMenuOpenAs(e.target.value as 'link' | 'modal')}
                        className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-medium"
                      >
                        <option value="link">Standard Link / Website URL</option>
                        <option value="modal">Popup Content Dialog (Opens Modal)</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-slate-300 font-semibold mb-1">Browser Target Window</label>
                      <select
                        value={newMenuTarget}
                        onChange={e => setNewMenuTarget(e.target.value as '_self' | '_blank')}
                        className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-medium"
                      >
                        <option value="_self">Same Window / Tab (_self)</option>
                        <option value="_blank">New Tab (_blank)</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-slate-300 font-semibold mb-1">Display Order</label>
                      <input
                        type="number"
                        value={menuItems.length + 1}
                        readOnly
                        className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-slate-400 font-mono"
                      />
                    </div>

                    <div className="sm:col-span-2 md:col-span-3">
                      <label className="block text-slate-300 font-semibold mb-1">
                        Menu Description / Subtitle / Modal Content (Optional)
                      </label>
                      <textarea
                        rows={3}
                        placeholder="Brief description shown in header dropdown or full markdown content shown if opened as modal..."
                        value={newMenuDesc}
                        onChange={e => setNewMenuDesc(e.target.value)}
                        className="w-full p-2.5 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-slate-200 text-xs"
                      />
                    </div>
                  </div>

                  <div className="flex justify-end gap-2 pt-2 border-t border-[#222A33]">
                    <button
                      type="button"
                      onClick={() => setIsAddingMenu(false)}
                      className="px-4 py-2 rounded-xl bg-slate-800 text-slate-300 text-xs font-semibold cursor-pointer"
                    >
                      Cancel
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        if (!newMenuTitle.trim()) {
                          showToast('Please enter a menu title');
                          return;
                        }
                        const newItem: MenuItem = {
                          id: `menu_${Date.now()}`,
                          title: newMenuTitle.trim(),
                          url: newMenuUrl.trim() || '#',
                          description: newMenuDesc.trim() || undefined,
                          location: newMenuLocation,
                          target: newMenuTarget,
                          open_as: newMenuOpenAs,
                          display_order: menuItems.length + 1,
                          is_active: true
                        };
                        adminSaveMenuItems([...menuItems, newItem]);
                        setIsAddingMenu(false);
                        showToast('New menu item created!');
                      }}
                      className="px-5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs flex items-center gap-1.5 cursor-pointer shadow-lg shadow-emerald-950/40"
                    >
                      <Check className="w-4 h-4" />
                      <span>Save Menu Item</span>
                    </button>
                  </div>
                </div>
              )}

              {/* Menu Items Table / Cards */}
              <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4">
                {/* Location Filter Tabs */}
                <div className="flex items-center justify-between gap-2 border-b border-[#222A33] pb-3 flex-wrap">
                  <div className="flex items-center gap-1.5">
                    <button
                      onClick={() => setMenuFilter('all')}
                      className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${
                        menuFilter === 'all' ? 'bg-emerald-600 text-white' : 'text-slate-400 bg-[#0A0D0F] hover:text-white'
                      }`}
                    >
                      All Menus ({menuItems.length})
                    </button>
                    <button
                      onClick={() => setMenuFilter('header')}
                      className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${
                        menuFilter === 'header' ? 'bg-emerald-600 text-white' : 'text-slate-400 bg-[#0A0D0F] hover:text-white'
                      }`}
                    >
                      Header ({menuItems.filter(m => !m.location || m.location === 'header' || m.location === 'both').length})
                    </button>
                    <button
                      onClick={() => setMenuFilter('footer')}
                      className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${
                        menuFilter === 'footer' ? 'bg-emerald-600 text-white' : 'text-slate-400 bg-[#0A0D0F] hover:text-white'
                      }`}
                    >
                      Footer ({menuItems.filter(m => m.location === 'footer' || m.location === 'both').length})
                    </button>
                    <button
                      onClick={() => setMenuFilter('both')}
                      className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${
                        menuFilter === 'both' ? 'bg-emerald-600 text-white' : 'text-slate-400 bg-[#0A0D0F] hover:text-white'
                      }`}
                    >
                      Both Header & Footer ({menuItems.filter(m => m.location === 'both').length})
                    </button>
                  </div>

                  <span className="text-[11px] text-slate-400 font-mono">
                    Total: {menuItems.length} active menu links
                  </span>
                </div>

                {/* Items List */}
                <div className="space-y-3">
                  {menuItems
                    .map((item, originalIndex) => ({ item, originalIndex }))
                    .filter(({ item }) => {
                      if (menuFilter === 'header') return !item.location || item.location === 'header' || item.location === 'both';
                      if (menuFilter === 'footer') return item.location === 'footer' || item.location === 'both';
                      if (menuFilter === 'both') return item.location === 'both';
                      return true;
                    })
                    .sort((a, b) => a.item.display_order - b.item.display_order)
                    .map(({ item, originalIndex }, displayIdx) => (
                      <div
                        key={item.id}
                        className={`p-4 rounded-xl border transition-all ${
                          item.is_active ? 'bg-[#0A0D0F] border-[#222A33]' : 'bg-[#07090B] border-slate-800 opacity-60'
                        }`}
                      >
                        <div className="grid grid-cols-1 md:grid-cols-12 gap-3 items-center text-xs">
                          {/* Order and Reorder Buttons */}
                          <div className="md:col-span-1 flex items-center gap-1.5">
                            <span className="font-mono text-xs font-bold text-emerald-400 bg-emerald-950/60 px-2 py-1 rounded-md border border-emerald-900/50">
                              #{item.display_order}
                            </span>
                            <div className="flex flex-col">
                              <button
                                type="button"
                                disabled={displayIdx === 0}
                                onClick={() => moveMenuItem(originalIndex, 'up')}
                                className="p-0.5 text-slate-400 hover:text-white disabled:opacity-20 cursor-pointer"
                                title="Move Up"
                              >
                                <ChevronUp className="w-3.5 h-3.5" />
                              </button>
                              <button
                                type="button"
                                disabled={displayIdx === menuItems.length - 1}
                                onClick={() => moveMenuItem(originalIndex, 'down')}
                                className="p-0.5 text-slate-400 hover:text-white disabled:opacity-20 cursor-pointer"
                                title="Move Down"
                              >
                                <ChevronDown className="w-3.5 h-3.5" />
                              </button>
                            </div>
                          </div>

                          {/* Title & URL Inputs */}
                          <div className="md:col-span-4 space-y-1.5">
                            <div className="flex items-center gap-2">
                              <label className="text-[10px] uppercase font-bold text-slate-400 w-10">Text:</label>
                              <input
                                type="text"
                                value={item.title}
                                onChange={e => {
                                  const updated = [...menuItems];
                                  updated[originalIndex].title = e.target.value;
                                  adminSaveMenuItems(updated);
                                }}
                                className="w-full px-2.5 py-1.5 bg-[#141A20] border border-[#222A33] rounded-lg text-white font-bold"
                              />
                            </div>
                            <div className="flex items-center gap-2">
                              <label className="text-[10px] uppercase font-bold text-slate-400 w-10">URL:</label>
                              <input
                                type="text"
                                value={item.url}
                                onChange={e => {
                                  const updated = [...menuItems];
                                  updated[originalIndex].url = e.target.value;
                                  adminSaveMenuItems(updated);
                                }}
                                className="w-full px-2.5 py-1.5 bg-[#141A20] border border-[#222A33] rounded-lg text-slate-300 font-mono text-[11px]"
                              />
                            </div>
                          </div>

                          {/* Description Input */}
                          <div className="md:col-span-3 space-y-1">
                            <label className="text-[10px] uppercase font-bold text-slate-400 block">Description / Subtitle:</label>
                            <input
                              type="text"
                              placeholder="Subtitle or modal preview text..."
                              value={item.description || ''}
                              onChange={e => {
                                const updated = [...menuItems];
                                updated[originalIndex].description = e.target.value;
                                adminSaveMenuItems(updated);
                              }}
                              className="w-full px-2.5 py-1.5 bg-[#141A20] border border-[#222A33] rounded-lg text-slate-300 text-xs"
                            />
                          </div>

                          {/* Placement & Options Selects */}
                          <div className="md:col-span-2 space-y-1.5">
                            <select
                              value={item.location || 'both'}
                              onChange={e => {
                                const updated = [...menuItems];
                                updated[originalIndex].location = e.target.value as 'header' | 'footer' | 'both';
                                adminSaveMenuItems(updated);
                                showToast('Placement updated');
                              }}
                              className="w-full px-2 py-1 bg-[#141A20] border border-[#222A33] rounded-lg text-emerald-400 font-semibold text-[11px]"
                            >
                              <option value="both">Header & Footer</option>
                              <option value="header">Header Only</option>
                              <option value="footer">Footer Only</option>
                            </select>

                            <div className="flex gap-1">
                              <select
                                value={item.open_as || 'link'}
                                onChange={e => {
                                  const updated = [...menuItems];
                                  updated[originalIndex].open_as = e.target.value as 'link' | 'modal';
                                  adminSaveMenuItems(updated);
                                }}
                                className="w-1/2 px-1.5 py-1 bg-[#141A20] border border-[#222A33] rounded-lg text-slate-300 text-[10px]"
                              >
                                <option value="link">Link</option>
                                <option value="modal">Modal</option>
                              </select>
                              <select
                                value={item.target || '_self'}
                                onChange={e => {
                                  const updated = [...menuItems];
                                  updated[originalIndex].target = e.target.value as '_self' | '_blank';
                                  adminSaveMenuItems(updated);
                                }}
                                className="w-1/2 px-1.5 py-1 bg-[#141A20] border border-[#222A33] rounded-lg text-slate-300 text-[10px]"
                              >
                                <option value="_self">Same Tab</option>
                                <option value="_blank">New Tab</option>
                              </select>
                            </div>
                          </div>

                          {/* Toggle Active & Delete */}
                          <div className="md:col-span-2 flex items-center justify-end gap-2">
                            <button
                              type="button"
                              onClick={() => {
                                const updated = [...menuItems];
                                updated[originalIndex].is_active = !updated[originalIndex].is_active;
                                adminSaveMenuItems(updated);
                                showToast(`Item ${updated[originalIndex].is_active ? 'Activated' : 'Deactivated'}`);
                              }}
                              className={`p-1.5 rounded-lg border text-xs font-semibold cursor-pointer ${
                                item.is_active
                                  ? 'bg-emerald-950/60 border-emerald-800 text-emerald-400'
                                  : 'bg-slate-800 border-slate-700 text-slate-400'
                              }`}
                              title={item.is_active ? 'Active (Click to hide)' : 'Hidden (Click to show)'}
                            >
                              {item.is_active ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
                            </button>

                            <button
                              type="button"
                              onClick={() => {
                                if (confirm(`Delete menu item "${item.title}"?`)) {
                                  const updated = menuItems.filter(m => m.id !== item.id);
                                  adminSaveMenuItems(updated);
                                  showToast('Menu item deleted');
                                }
                              }}
                              className="p-1.5 rounded-lg bg-rose-950/50 border border-rose-900/50 text-rose-400 hover:text-rose-300 cursor-pointer"
                              title="Delete Menu Link"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        </div>
                      </div>
                    ))}
                </div>
              </div>
            </div>
          )}

          {/* TAB 8: CONTENT PAGES & SEO */}
          {activeTab === 'pages' && (
            <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4">
              <div className="flex items-center gap-2 border-b border-[#222A33] pb-3">
                {(['rules', 'terms', 'privacy', 'stats'] as const).map(p => (
                  <button
                    key={p}
                    onClick={() => setActivePageEdit(p)}
                    className={`px-3 py-1.5 rounded-lg text-xs font-bold uppercase font-mono ${
                      activePageEdit === p ? 'bg-emerald-600 text-white' : 'text-slate-400 bg-[#0A0D0F]'
                    }`}
                  >
                    {p}
                  </button>
                ))}
              </div>

              {(() => {
                const currentPage = pages.find(p => p.id === activePageEdit);
                if (!currentPage) return null;

                return (
                  <div className="space-y-3 text-xs">
                    <div>
                      <label className="block text-slate-300 font-semibold mb-1">Page Title</label>
                      <input
                        type="text"
                        value={currentPage.title}
                        onChange={e => {
                          adminSavePage({ ...currentPage, title: e.target.value });
                        }}
                        className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white"
                      />
                    </div>

                    <div>
                      <label className="block text-slate-300 font-semibold mb-1">Content (Markdown supported)</label>
                      <textarea
                        rows={10}
                        value={currentPage.content}
                        onChange={e => {
                          adminSavePage({ ...currentPage, content: e.target.value });
                        }}
                        className="w-full p-3 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-slate-200 font-mono text-xs"
                      />
                    </div>
                  </div>
                );
              })()}
            </div>
          )}

          {/* TAB 9: GENERAL SETTINGS */}
          {activeTab === 'settings' && (
            <div className="p-5 rounded-2xl bg-[#13181D] border border-[#222A33] space-y-4 text-xs">
              <h3 className="font-bold text-sm text-white">General & SEO Settings</h3>

              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-slate-300 font-semibold mb-1">Currency Symbol</label>
                  <input
                    type="text"
                    value={tempSettings.currency_symbol}
                    onChange={e => setTempSettings({ ...tempSettings, currency_symbol: e.target.value })}
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                  />
                </div>

                <div>
                  <label className="block text-slate-300 font-semibold mb-1">Minimum Bid Increment</label>
                  <input
                    type="number"
                    value={tempSettings.minimum_bid_increment}
                    onChange={e => setTempSettings({ ...tempSettings, minimum_bid_increment: Number(e.target.value) })}
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                  />
                </div>

                <div>
                  <label className="block text-slate-300 font-semibold mb-1">Initial Minimum Bid</label>
                  <input
                    type="number"
                    value={tempSettings.initial_minimum_bid}
                    onChange={e => setTempSettings({ ...tempSettings, initial_minimum_bid: Number(e.target.value) })}
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                  />
                </div>

                <div>
                  <label className="block text-slate-300 font-semibold mb-1">Multilingual System (EN/BN)</label>
                  <select
                    value={tempSettings.translation_enabled !== false ? 'enabled' : 'disabled'}
                    onChange={e => setTempSettings({ ...tempSettings, translation_enabled: e.target.value === 'enabled' })}
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                  >
                    <option value="enabled">Enabled (Show ENG / বাংলা switcher)</option>
                    <option value="disabled">Disabled (English Only)</option>
                  </select>
                </div>

                <div>
                  <label className="block text-slate-300 font-semibold mb-1">Default Site Language</label>
                  <select
                    value={tempSettings.default_language || 'en'}
                    onChange={e => setTempSettings({ ...tempSettings, default_language: e.target.value as 'en' | 'bn' })}
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                  >
                    <option value="en">English (Default)</option>
                    <option value="bn">Bangla (বাংলা)</option>
                  </select>
                </div>

                <div>
                  <label className="block text-slate-300 font-semibold mb-1">Footer "Admin Panel" Button</label>
                  <select
                    value={tempSettings.show_footer_admin_button !== false ? 'enabled' : 'disabled'}
                    onChange={e => setTempSettings({ ...tempSettings, show_footer_admin_button: e.target.value === 'enabled' })}
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white font-mono"
                  >
                    <option value="enabled">Enabled (Show in Footer links)</option>
                    <option value="disabled">Disabled (Hide from Footer)</option>
                  </select>
                </div>
              </div>

              <div className="pt-3 border-t border-[#222A33] flex justify-between items-center">
                <button
                  onClick={() => {
                    if (confirm('Reset all demo data back to default factory state?')) {
                      adminResetData();
                      showToast('Database reset to defaults');
                    }
                  }}
                  className="px-4 py-2 rounded-xl bg-rose-950/60 text-rose-300 border border-rose-900/60 font-bold"
                >
                  Reset Factory Data
                </button>

                <button
                  onClick={() => {
                    adminSaveSettings(tempSettings);
                    showToast('Settings saved!');
                  }}
                  className="px-6 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold"
                >
                  Save Settings
                </button>
              </div>
            </div>
          )}

          {/* TAB 10: DOWNLOAD STANDALONE ZIP & HOSTINGER DEPLOYMENT */}
          {activeTab === 'download' && (
            <div className="p-6 rounded-2xl bg-[#13181D] border border-emerald-500/30 space-y-6">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-2xl bg-emerald-600/20 border border-emerald-500/50 flex items-center justify-center text-emerald-400">
                  <Download className="w-6 h-6" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-white font-mono">Download TOPBD Standalone Package</h3>
                  <p className="text-xs text-slate-400">Complete Self-Hosted PHP 8+ & MySQL / cPanel Application</p>
                </div>
              </div>

              <div className="p-4 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-2 text-xs text-slate-300">
                <div className="font-bold text-white flex items-center gap-1.5">
                  <Check className="w-4 h-4 text-emerald-400" />
                  <span>Ready for Hostinger, cPanel, or standard Apache PHP hosting</span>
                </div>
                <p className="text-slate-400">
                  Contains all production PHP controllers, API endpoints, SQL schema migrations, installer.php wizard, responsive CSS/JS, .htaccess security rules, and gateway connectors for bKash, Nagad, Rocket, SSLCommerz & shurjoPay.
                </p>
              </div>

              <div className="flex flex-col sm:flex-row gap-3">
                <a
                  href="/TOPBD-STANDALONE.zip"
                  download="TOPBD-STANDALONE.zip"
                  className="flex-1 py-3 px-6 rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-white font-bold text-sm shadow-xl flex items-center justify-center gap-2 transition-all cursor-pointer"
                >
                  <Download className="w-4 h-4" />
                  <span>Download TOPBD-STANDALONE.zip</span>
                </a>
              </div>

              {/* Deployment Quick Guide */}
              <div className="p-4 rounded-xl bg-[#0E1216] border border-[#222A33] space-y-2 text-xs">
                <span className="font-bold text-amber-400 block font-mono">3-Step Hostinger / cPanel Installation:</span>
                <ol className="list-decimal list-inside space-y-1.5 text-slate-300">
                  <li>Upload <code className="text-emerald-400 font-mono">TOPBD-STANDALONE.zip</code> to your cPanel File Manager in <code className="text-slate-400">public_html</code> and Extract.</li>
                  <li>Create a MySQL Database & User in cPanel MySQL Databases.</li>
                  <li>Visit <code className="text-emerald-400 font-mono">https://yourdomain.com/installer.php</code> and complete the automated 30-second setup!</li>
                </ol>
              </div>
            </div>
          )}
        </div>
      </main>
    </div>
  );
};
