'use client';

import { useState, useEffect, useCallback } from 'react';
import { useAppStore, ROLE_PRESETS, hydrateStoreFromStorage } from '@/lib/store';
import type { TeamMember as StoreTeamMember } from '@/lib/store';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger,
} from '@/components/ui/dialog';
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
  LayoutDashboard, Users, Building2, Store, ShoppingBag, Package,
  GraduationCap, MessageSquare, Settings, LogOut, Shield, Mail, Lock,
  BookOpen,
  TrendingUp, TrendingDown, DollarSign, Bell, Plus, Search, Trash2,
  CheckCircle, XCircle, Ban, Activity, BarChart3, ArrowLeft, Menu, X,
  UserPlus, Eye, EyeOff, ChevronRight, Crown, UserCog, PieChart,
  ArrowUpRight, ArrowDownRight, Globe, Zap, Clock, Star,
  Palette, Type, Layout, ToggleLeft, RotateCcw, Save, Monitor,
  Smartphone, Paintbrush, Image as ImageIcon, Wand2,
  Moon, Sun, Code, Navigation, Sparkles, Download, Upload, FileJson, AlertTriangle,
  Edit,
  CreditCard,
} from 'lucide-react';
import AdminMCQManager from '@/components/admin/AdminMCQManager';
import AdminPayments from '@/components/admin/AdminPayments';

// ============ TYPES ============
interface DashboardStats {
  totalUsers: number;
  totalHouses: number;
  totalShops: number;
  totalProducts: number;
  totalOrders: number;
  totalRevenue: number;
  recentActivity: { type: string; title: string; description: string; time: string }[];
}

interface TeamMemberData {
  id: string;
  name: string;
  email: string;
  phone?: string;
  role: string;
  isActive: boolean;
  canManageUsers: boolean;
  canManageHouses: boolean;
  canManageShops: boolean;
  canManageProducts: boolean;
  canManageOrders: boolean;
  canManageMCQ: boolean;
  canManageCommunity: boolean;
  canSendNotification: boolean;
  canViewAnalytics: boolean;
  canManageTeam: boolean;
  createdAt: string;
}

// Role badge config for display
const ROLE_BADGE_CONFIG: Record<string, { label: string; labelBn: string; color: string; icon: React.ElementType }> = {
  super_admin: { label: 'Super Admin', labelBn: 'সুপার অ্যাডমিন', color: 'bg-gradient-to-r from-orange-600 to-orange-500 text-white border-0', icon: Crown },
  admin: { label: 'Admin', labelBn: 'অ্যাডমিন', color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400 border-emerald-200', icon: Shield },
  moderator: { label: 'Moderator', labelBn: 'মডারেটর', color: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400 border-amber-200', icon: Shield },
  editor: { label: 'Editor', labelBn: 'সম্পাদক', color: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400 border-amber-200', icon: Edit },
  viewer: { label: 'Viewer', labelBn: 'দর্শক', color: 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400 border-gray-200', icon: Eye },
};

function getRoleBadge(role: string, language: string) {
  const config = ROLE_BADGE_CONFIG[role] || ROLE_BADGE_CONFIG.viewer;
  const Icon = config.icon;
  return (
    <Badge className={`text-[9px] gap-1 ${config.color}`}>
      <Icon className="h-3 w-3" />
      {language === 'en' ? config.label : config.labelBn}
    </Badge>
  );
}

const isSuperAdmin = (role: string) => role === 'super_admin';

// ============ CUSTOMIZATIONS DEFAULTS ============
interface AppCustomizations {
  // Theme & Colors
  primaryColor: string;
  accentColor: string;
  buttonColor: string;
  cardBgColor: string;
  sidebarColor: string;
  headerColor: string;
  gradientStart: string;
  gradientEnd: string;
  borderRadius: string;
  // App Branding
  appName: string;
  appTagline: string;
  appLogoUrl: string;
  faviconUrl: string;
  footerText: string;
  copyrightText: string;
  // Hero Section
  heroTitle: string;
  heroSubtitle: string;
  heroBgColor: string;
  heroButtonText: string;
  heroButtonLink: string;
  // Feature Toggles
  enableHouseRental: boolean;
  enableShopRental: boolean;
  enableMarketplace: boolean;
  enableMedicine: boolean;
  enableEducation: boolean;
  enableCommunity: boolean;
  enableMCQ: boolean;
  enableOrders: boolean;
  enableMessages: boolean;
  enableFavourites: boolean;
  // Text & Content
  welcomeMessage: string;
  homeTitle: string;
  exploreTitle: string;
  emptyStateMessage: string;
  errorMessage: string;
  successMessage: string;
  // Layout
  sidebarPosition: string;
  navigationStyle: string;
  cardStyle: string;
  showSearchBar: boolean;
  showNotificationsBell: boolean;
  // Font Settings
  fontFamily: string;
  headingFontFamily: string;
  baseFontSize: string;
  headingFontWeight: string;
  // Text Colors
  textColor: string;
  mutedTextColor: string;
  headingColor: string;
  linkColor: string;
  // Dark Mode Colors
  darkBgColor: string;
  darkCardColor: string;
  darkTextColor: string;
  darkAccentColor: string;
  // UI Effects
  enableAnimations: boolean;
  shadowIntensity: string;
  buttonBorderRadius: string;
  cardBorderRadius: string;
  inputBorderRadius: string;
  // Notification Settings
  notificationPosition: string;
  notificationStyle: string;
  // Bottom Nav Settings
  bottomNavBgColor: string;
  bottomNavActiveColor: string;
  bottomNavInactiveColor: string;
  bottomNavStyle: string;
  // Sidebar Settings
  sidebarWidth: string;
  sidebarBgOpacity: string;
  // Custom CSS
  customCSS: string;
}

const defaultCustomizations: AppCustomizations = {
  primaryColor: '#ea580c',
  accentColor: '#f97316',
  buttonColor: '#ea580c',
  cardBgColor: '#ffffff',
  sidebarColor: '#ffffff',
  headerColor: '#ffffff',
  gradientStart: '#ea580c',
  gradientEnd: '#f97316',
  borderRadius: 'rounded-xl',
  appName: 'Needyfy',
  appTagline: 'Your needs, fulfilled',
  appLogoUrl: '',
  faviconUrl: '',
  footerText: 'Powered by Needyfy',
  copyrightText: '© 2024 Needyfy. All rights reserved.',
  heroTitle: 'Welcome to Needyfy',
  heroSubtitle: 'Find houses, shops, products, and more',
  heroBgColor: '#ea580c',
  heroButtonText: 'Get Started',
  heroButtonLink: '/explore',
  enableHouseRental: true,
  enableShopRental: true,
  enableMarketplace: true,
  enableMedicine: true,
  enableEducation: true,
  enableCommunity: true,
  enableMCQ: true,
  enableOrders: true,
  enableMessages: true,
  enableFavourites: true,
  welcomeMessage: 'Welcome back!',
  homeTitle: 'Home',
  exploreTitle: 'Explore',
  emptyStateMessage: 'Nothing here yet',
  errorMessage: 'Something went wrong',
  successMessage: 'Success!',
  sidebarPosition: 'left',
  navigationStyle: 'both',
  cardStyle: 'default',
  showSearchBar: true,
  showNotificationsBell: true,
  // Font Settings
  fontFamily: 'Inter',
  headingFontFamily: 'Inter',
  baseFontSize: '16px',
  headingFontWeight: '700',
  // Text Colors
  textColor: '#1a1a1a',
  mutedTextColor: '#6b7280',
  headingColor: '#111827',
  linkColor: '#ea580c',
  // Dark Mode Colors
  darkBgColor: '#0f0f0f',
  darkCardColor: '#1a1a1a',
  darkTextColor: '#f5f5f5',
  darkAccentColor: '#fb923c',
  // UI Effects
  enableAnimations: true,
  shadowIntensity: 'medium',
  buttonBorderRadius: 'rounded-xl',
  cardBorderRadius: 'rounded-xl',
  inputBorderRadius: 'rounded-lg',
  // Notification Settings
  notificationPosition: 'top-right',
  notificationStyle: 'default',
  // Bottom Nav Settings
  bottomNavBgColor: '#ffffff',
  bottomNavActiveColor: '#ea580c',
  bottomNavInactiveColor: '#9ca3af',
  bottomNavStyle: 'default',
  // Sidebar Settings
  sidebarWidth: '280px',
  sidebarBgOpacity: '100',
  // Custom CSS
  customCSS: '',
};

// ============ PRESET THEMES ============
const presetThemes: { name: string; nameBn: string; description: string; descriptionBn: string; preview: string; values: Partial<AppCustomizations> }[] = [
  {
    name: 'Needyfy Default',
    nameBn: 'নিডিফাই ডিফল্ট',
    description: 'Professional orange & white palette',
    descriptionBn: 'পেশাদার কমলা ও সাদা প্যালেট',
    preview: 'from-orange-600 to-orange-500',
    values: {
      primaryColor: '#ea580c', accentColor: '#f97316', buttonColor: '#ea580c',
      gradientStart: '#ea580c', gradientEnd: '#f97316', heroBgColor: '#ea580c',
      linkColor: '#ea580c', bottomNavActiveColor: '#ea580c', darkAccentColor: '#fb923c',
    },
  },
  {
    name: 'Sunset Amber',
    nameBn: 'সানসেট অ্যাম্বার',
    description: 'Warm amber & orange tones',
    descriptionBn: 'উষ্ণ অ্যাম্বার ও কমলা টোন',
    preview: 'from-amber-600 to-orange-400',
    values: {
      primaryColor: '#d97706', accentColor: '#f97316', buttonColor: '#d97706',
      gradientStart: '#d97706', gradientEnd: '#f97316', heroBgColor: '#d97706',
      linkColor: '#d97706', bottomNavActiveColor: '#d97706', darkAccentColor: '#fbbf24',
    },
  },
  {
    name: 'Forest Green',
    nameBn: 'ফরেস্ট গ্রিন',
    description: 'Natural green & emerald vibes',
    descriptionBn: 'প্রাকৃতিক সবুজ ও পান্না ভাইব',
    preview: 'from-emerald-600 to-teal-400',
    values: {
      primaryColor: '#059669', accentColor: '#14b8a6', buttonColor: '#059669',
      gradientStart: '#059669', gradientEnd: '#14b8a6', heroBgColor: '#059669',
      linkColor: '#059669', bottomNavActiveColor: '#059669', darkAccentColor: '#34d399',
    },
  },
  {
    name: 'Warm Copper',
    nameBn: 'ওয়ার্ম কপার',
    description: 'Rich copper & amber hues',
    descriptionBn: 'ধনী কপার ও অ্যাম্বার রং',
    preview: 'from-orange-600 to-amber-400',
    values: {
      primaryColor: '#ea580c', accentColor: '#f59e0b', buttonColor: '#ea580c',
      gradientStart: '#ea580c', gradientEnd: '#f59e0b', heroBgColor: '#ea580c',
      linkColor: '#ea580c', bottomNavActiveColor: '#ea580c', darkAccentColor: '#fb923c',
    },
  },
  {
    name: 'Rose Garden',
    nameBn: 'রোজ গার্ডেন',
    description: 'Soft pink & rose tones',
    descriptionBn: 'নরম গোলাপি ও রোজ টোন',
    preview: 'from-pink-600 to-rose-400',
    values: {
      primaryColor: '#db2777', accentColor: '#f43f5e', buttonColor: '#db2777',
      gradientStart: '#db2777', gradientEnd: '#f43f5e', heroBgColor: '#db2777',
      linkColor: '#db2777', bottomNavActiveColor: '#db2777', darkAccentColor: '#fb7185',
    },
  },
  {
    name: 'Midnight Dark',
    nameBn: 'মিডনাইট ডার্ক',
    description: 'Dark mode focused theme',
    descriptionBn: 'ডার্ক মোড ফোকাসড থিম',
    preview: 'from-gray-800 to-gray-600',
    values: {
      primaryColor: '#f59e0b', accentColor: '#d97706', buttonColor: '#f59e0b',
      gradientStart: '#1f2937', gradientEnd: '#374151', heroBgColor: '#1f2937',
      cardBgColor: '#1f2937', sidebarColor: '#111827', headerColor: '#1f2937',
      darkBgColor: '#030712', darkCardColor: '#111827', darkTextColor: '#f9fafb',
      darkAccentColor: '#fbbf24', linkColor: '#f59e0b', bottomNavBgColor: '#111827',
      bottomNavActiveColor: '#f59e0b', bottomNavInactiveColor: '#6b7280',
    },
  },
];

// ============ AUTHENTICATED FETCH HELPER ============
function adminFetch(url: string, options: RequestInit = {}, token: string | null): Promise<Response> {
  const headers = new Headers(options.headers);
  if (token) {
    headers.set('x-admin-token', token);
  }
  if (!headers.has('Content-Type') && options.body) {
    headers.set('Content-Type', 'application/json');
  }
  return fetch(url, { ...options, headers });
}

// Safe JSON parse helper - prevents "Unexpected token '<'" errors
async function safeJsonParse<T>(response: Response): Promise<T | null> {
  try {
    const text = await response.text();
    if (!text || text.trim().startsWith('<!DOCTYPE') || text.trim().startsWith('<html')) {
      console.error('Received HTML instead of JSON from:', response.url);
      return null;
    }
    return JSON.parse(text) as T;
  } catch (err) {
    console.error('Failed to parse JSON response:', err);
    return null;
  }
}

// ============ ADMIN LOGIN ============
function AdminLoginPage({ onLogin }: { onLogin: (admin: Record<string, unknown>, token: string | null) => void }) {
  const { language } = useAppStore();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email || !password) return;
    setIsLoading(true);
    setError('');
    try {
      const res = await fetch('/api/admin/auth', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const data = await safeJsonParse<Record<string, unknown>>(res);
      if (data?.success) {
        onLogin(data.admin, (data.admin as Record<string, unknown>)?.token || null);
      } else {
        setError((data?.error as string) || 'Invalid credentials');
      }
    } catch {
      setError('Network error. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen">
      {/* Left - Branding */}
      <div className="hidden lg:flex lg:w-1/2 relative bg-gradient-to-br from-orange-700 via-orange-600 to-orange-500 items-center justify-center overflow-hidden">
        <div className="absolute inset-0 opacity-10">
          <div className="absolute top-20 left-20 h-64 w-64 rounded-full border-4 border-white" />
          <div className="absolute bottom-20 right-20 h-96 w-96 rounded-full border-4 border-white" />
          <div className="absolute top-1/2 left-1/3 h-40 w-40 rounded-full border-4 border-white" />
        </div>
        <div className="relative z-10 px-12 text-center text-white">
          <div className="mx-auto mb-8 flex h-28 w-28 items-center justify-center rounded-3xl bg-white/20 backdrop-blur-sm shadow-2xl">
            <Shield className="h-14 w-14 text-white" strokeWidth={1.5} />
          </div>
          <h1 className="text-5xl font-extrabold tracking-tight">Needyfy</h1>
          <p className="mt-2 text-2xl font-light text-white/90">Admin Portal</p>
          <p className="mt-6 max-w-md mx-auto text-base text-white/70">
            {language === 'en'
              ? 'Manage your platform, users, listings, and analytics from one powerful dashboard.'
              : 'একটি শক্তিশালী ড্যাশবোর্ড থেকে আপনার প্ল্যাটফর্ম, ব্যবহারকারী, তালিকা এবং অ্যানালিটিক্স পরিচালনা করুন।'}
          </p>
          <div className="mt-10 flex items-center justify-center gap-8 text-white/60 text-sm">
            <div className="flex items-center gap-2"><Globe className="h-4 w-4" />{language === 'en' ? 'Multi-language' : 'বহুভাষিক'}</div>
            <div className="flex items-center gap-2"><Zap className="h-4 w-4" />{language === 'en' ? 'Real-time' : 'রিয়েল-টাইম'}</div>
            <div className="flex items-center gap-2"><Shield className="h-4 w-4" />{language === 'en' ? 'Secure' : 'নিরাপদ'}</div>
          </div>
        </div>
      </div>

      {/* Right - Login Form */}
      <div className="flex w-full lg:w-1/2 items-center justify-center px-6 py-12 bg-background">
        <div className="w-full max-w-md">
          <a href="/" className="mb-8 inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors">
            <ArrowLeft className="h-4 w-4" />
            {language === 'en' ? 'Back to Needyfy' : 'Needyfy এ ফিরুন'}
          </a>

          <div className="lg:hidden mb-8 text-center">
            <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-orange-700 to-orange-500 shadow-xl">
              <Shield className="h-8 w-8 text-white" strokeWidth={1.5} />
            </div>
            <h1 className="text-2xl font-bold">Needyfy Admin</h1>
          </div>

          <h2 className="text-2xl font-bold tracking-tight">{language === 'en' ? 'Welcome back' : 'আবার স্বাগতম'}</h2>
          <p className="mt-1 text-sm text-muted-foreground">{language === 'en' ? 'Sign in to your admin account' : 'আপনার অ্যাডমিন অ্যাকাউন্টে সাইন ইন করুন'}</p>

          <form onSubmit={handleLogin} className="mt-8 space-y-5">
            {error && (
              <div className="rounded-xl border border-destructive/20 bg-destructive/5 p-4 text-center text-sm text-destructive">{error}</div>
            )}
            <div className="space-y-2">
              <Label htmlFor="email" className="text-sm font-medium">{language === 'en' ? 'Email Address' : 'ইমেইল ঠিকানা'}</Label>
              <div className="relative">
                <Mail className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input id="email" type="email" placeholder="admin@needyfy.com" value={email} onChange={(e) => setEmail(e.target.value)} className="pl-10 h-11" required />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="password" className="text-sm font-medium">{language === 'en' ? 'Password' : 'পাসওয়ার্ড'}</Label>
              <div className="relative">
                <Lock className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input id="password" type={showPassword ? 'text' : 'password'} placeholder="••••••••" value={password} onChange={(e) => setPassword(e.target.value)} className="pl-10 pr-10 h-11" required />
                <button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute right-3.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground">
                  {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>
            <Button type="submit" className="w-full h-11 bg-gradient-to-r from-orange-700 to-orange-500 font-semibold shadow-lg hover:from-orange-800 hover:to-orange-600 transition-all" disabled={isLoading}>
              {isLoading ? (
                <span className="flex items-center gap-2"><span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />{language === 'en' ? 'Signing in...' : 'সাইন ইন হচ্ছে...'}</span>
              ) : (
                <span className="flex items-center gap-2"><Shield className="h-4 w-4" />{language === 'en' ? 'Sign In' : 'সাইন ইন'}</span>
              )}
            </Button>
          </form>

          <div className="mt-6 rounded-xl border border-dashed bg-accent/30 p-4 text-center">
            <p className="text-xs text-muted-foreground">
              {language === 'en' ? 'Admin credentials:' : 'অ্যাডমিন ক্রেডেনশিয়াল:'}
            </p>
            <p className="mt-1 text-xs font-mono font-semibold text-foreground">
              admin@needyfy.com / Needyfy@2025
            </p>
            <p className="mt-1 text-xs text-muted-foreground">
              {language === 'en' ? 'Super Admin:' : 'সুপার অ্যাডমিন:'}
            </p>
            <p className="text-xs font-mono font-semibold text-foreground">
              superadmin@needyfy.com / SuperAdmin@2025
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============ PROFESSIONAL ANALYTICS DASHBOARD ============
function AnalyticsDashboard({ stats, onNavigate }: { stats: DashboardStats | null; onNavigate?: (tab: string) => void }) {
  const { language, adminUser } = useAppStore();
  const [animatedBars, setAnimatedBars] = useState(false);
  const [currentTime, setCurrentTime] = useState(new Date());

  useEffect(() => {
    const timer = setTimeout(() => setAnimatedBars(true), 150);
    return () => clearTimeout(timer);
  }, []);

  useEffect(() => {
    const interval = setInterval(() => setCurrentTime(new Date()), 1000);
    return () => clearInterval(interval);
  }, []);

  if (!stats) {
    return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>;
  }

  // Greeting based on time of day
  const hour = currentTime.getHours();
  const greeting = hour < 12
    ? (language === 'en' ? 'Good Morning' : 'শুভ সকাল')
    : hour < 17
    ? (language === 'en' ? 'Good Afternoon' : 'শুভ দুপুর')
    : (language === 'en' ? 'Good Evening' : 'শুভ সন্ধ্যা');

  const formattedDate = currentTime.toLocaleDateString(language === 'en' ? 'en-US' : 'bn-BD', {
    weekday: 'long', year: 'numeric', month: 'long', day: 'numeric',
  });

  const formattedTime = currentTime.toLocaleTimeString(language === 'en' ? 'en-US' : 'bn-BD', {
    hour: '2-digit', minute: '2-digit', second: '2-digit',
  });

  // Revenue chart data
  const revenueData = [1200, 1800, 1400, 2200, 1900, 2600, 2100];
  const totalRevenue = revenueData.reduce((a, b) => a + b, 0);
  const maxRevenue = Math.max(...revenueData);
  const days = language === 'en'
    ? ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    : ['সোম', 'মঙ্গল', 'বুধ', 'বৃহঃ', 'শুক্র', 'শনি', 'রবি'];

  // ===== TOP METRIC CARDS =====
  const metricCards = [
    {
      title: language === 'en' ? 'Total Users' : 'মোট ব্যবহারকারী',
      subtitle: language === 'en' ? 'Registered accounts' : 'নিবন্ধিত অ্যাকাউন্ট',
      value: stats.totalUsers.toLocaleString(),
      change: '+12.5%',
      trend: 'up' as const,
      icon: Users,
      gradient: 'from-orange-600 to-orange-500',
    },
    {
      title: language === 'en' ? 'Active Houses' : 'সক্রিয় বাড়ি',
      subtitle: language === 'en' ? 'Listed properties' : 'তালিকাভুক্ত সম্পত্তি',
      value: stats.totalHouses.toLocaleString(),
      change: '+8.2%',
      trend: 'up' as const,
      icon: Building2,
      gradient: 'from-emerald-500 to-emerald-400',
    },
    {
      title: language === 'en' ? 'Revenue (MRR)' : 'আয় (MRR)',
      subtitle: language === 'en' ? 'Monthly recurring' : 'মাসিক পুনরাবৃত্ত',
      value: `৳${stats.totalRevenue.toLocaleString()}`,
      change: '+22.1%',
      trend: 'up' as const,
      icon: DollarSign,
      gradient: 'from-amber-500 to-amber-400',
    },
    {
      title: language === 'en' ? 'Online Now' : 'এখন অনলাইন',
      subtitle: language === 'en' ? 'Active sessions' : 'সক্রিয় সেশন',
      value: Math.max(1, Math.floor(stats.totalUsers * 0.12)).toLocaleString(),
      change: '+5.3%',
      trend: 'up' as const,
      icon: Activity,
      gradient: 'from-rose-500 to-rose-400',
    },
  ];

  // ===== QUICK ACTIONS BAR =====
  const quickActions = [
    { icon: Users, label: language === 'en' ? 'Users' : 'ব্যবহারকারী', tab: 'users', color: 'text-orange-600 bg-orange-50 dark:bg-orange-950/30 dark:text-orange-400' },
    { icon: Plus, label: language === 'en' ? 'Add House' : 'বাড়ি যোগ', tab: 'houses', color: 'text-emerald-600 bg-emerald-50 dark:bg-emerald-950/30 dark:text-emerald-400' },
    { icon: ShoppingBag, label: language === 'en' ? 'Products' : 'পণ্য', tab: 'products', color: 'text-amber-600 bg-amber-50 dark:bg-amber-950/30 dark:text-amber-400' },
    { icon: CreditCard, label: language === 'en' ? 'Payments' : 'পেমেন্ট', tab: 'payment-gateways', color: 'text-rose-600 bg-rose-50 dark:bg-rose-950/30 dark:text-rose-400' },
    { icon: Bell, label: language === 'en' ? 'Notifications' : 'বিজ্ঞপ্তি', tab: 'notifications', color: 'text-violet-600 bg-violet-50 dark:bg-violet-950/30 dark:text-violet-400' },
    { icon: Globe, label: language === 'en' ? 'Website' : 'ওয়েবসাইট', tab: 'appearance', color: 'text-sky-600 bg-sky-50 dark:bg-sky-950/30 dark:text-sky-400' },
    { icon: Shield, label: language === 'en' ? 'Gateways' : 'গেটওয়ে', tab: 'payment-gateways', color: 'text-teal-600 bg-teal-50 dark:bg-teal-950/30 dark:text-teal-400' },
    { icon: Palette, label: language === 'en' ? 'Appearance' : 'রূপরেখা', tab: 'appearance', color: 'text-pink-600 bg-pink-50 dark:bg-pink-950/30 dark:text-pink-400' },
    { icon: AlertTriangle, label: language === 'en' ? 'Alerts' : 'সতর্কতা', tab: 'dashboard', color: 'text-yellow-600 bg-yellow-50 dark:bg-yellow-950/30 dark:text-yellow-400' },
    { icon: BarChart3, label: language === 'en' ? 'Menus' : 'মেনু', tab: 'dashboard', color: 'text-indigo-600 bg-indigo-50 dark:bg-indigo-950/30 dark:text-indigo-400' },
    { icon: Sparkles, label: language === 'en' ? 'AI' : 'এআই', tab: 'dashboard', color: 'text-fuchsia-600 bg-fuchsia-50 dark:bg-fuchsia-950/30 dark:text-fuchsia-400' },
  ];

  // ===== DEMOGRAPHICS =====
  const demographics = [
    { icon: Users, label: language === 'en' ? 'Users' : 'ব্যবহারকারী', value: stats.totalUsers, color: 'text-orange-600', bg: 'bg-orange-50 dark:bg-orange-950/30' },
    { icon: Building2, label: language === 'en' ? 'Houses' : 'বাড়ি', value: stats.totalHouses, color: 'text-emerald-600', bg: 'bg-emerald-50 dark:bg-emerald-950/30' },
    { icon: Store, label: language === 'en' ? 'Shops' : 'দোকান', value: stats.totalShops, color: 'text-amber-600', bg: 'bg-amber-50 dark:bg-amber-950/30' },
    { icon: ShoppingBag, label: language === 'en' ? 'Products' : 'পণ্য', value: stats.totalProducts, color: 'text-rose-600', bg: 'bg-rose-50 dark:bg-rose-950/30' },
    { icon: Package, label: language === 'en' ? 'Orders' : 'অর্ডার', value: stats.totalOrders, color: 'text-violet-600', bg: 'bg-violet-50 dark:bg-violet-950/30' },
  ];

  // ===== USER PROFILE DONUT =====
  const activeCount = Math.floor(stats.totalUsers * 0.68);
  const inactiveCount = stats.totalUsers - activeCount;
  const activePercent = stats.totalUsers > 0 ? Math.round((activeCount / stats.totalUsers) * 100) : 0;
  const inactivePercent = 100 - activePercent;
  const circumference = 2 * Math.PI * 40;
  const activeStroke = (activePercent / 100) * circumference;
  const inactiveStroke = (inactivePercent / 100) * circumference;

  // ===== LIVE ACTIVITY FEED =====
  const iconMap: Record<string, typeof Users> = {
    user: Users, house: Building2, shop: Store, product: ShoppingBag, order: Package, payment: CreditCard, default: Activity,
  };
  const colorMap: Record<string, string> = {
    user: 'bg-orange-100 text-orange-600 dark:bg-orange-950/30 dark:text-orange-400',
    house: 'bg-emerald-100 text-emerald-600 dark:bg-emerald-950/30 dark:text-emerald-400',
    shop: 'bg-amber-100 text-amber-600 dark:bg-amber-950/30 dark:text-amber-400',
    product: 'bg-rose-100 text-rose-600 dark:bg-rose-950/30 dark:text-rose-400',
    order: 'bg-violet-100 text-violet-600 dark:bg-violet-950/30 dark:text-violet-400',
    payment: 'bg-teal-100 text-teal-600 dark:bg-teal-950/30 dark:text-teal-400',
    default: 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400',
  };

  const activityFeed = (stats.recentActivity && stats.recentActivity.length > 0)
    ? stats.recentActivity.slice(0, 6).map((a) => ({
        icon: iconMap[a.type] || iconMap.default,
        title: a.title,
        description: a.description,
        time: a.time,
        color: colorMap[a.type] || colorMap.default,
      }))
    : [
        { icon: UserPlus, title: language === 'en' ? 'New user registered' : 'নতুন ব্যবহারকারী নিবন্ধিত', description: language === 'en' ? 'John Doe joined the platform' : 'জন ডো প্ল্যাটফর্মে যোগ দিয়েছেন', time: '2m', color: colorMap.user },
        { icon: Building2, title: language === 'en' ? 'New house listed' : 'নতুন বাড়ি তালিকাভুক্ত', description: language === 'en' ? 'Modern Apartment in Dhaka' : 'ঢাকায় মডার্ন অ্যাপার্টমেন্ট', time: '15m', color: colorMap.house },
        { icon: Package, title: language === 'en' ? 'Order completed' : 'অর্ডার সম্পন্ন', description: language === 'en' ? 'Order #1234 delivered' : 'অর্ডার #১২৩৪ ডেলিভারি', time: '1h', color: colorMap.order },
        { icon: ShoppingBag, title: language === 'en' ? 'New product added' : 'নতুন পণ্য যোগ', description: language === 'en' ? 'Wireless Headphones listed' : 'ওয়্যারলেস হেডফোন তালিকাভুক্ত', time: '2h', color: colorMap.product },
        { icon: CreditCard, title: language === 'en' ? 'Payment received' : 'পেমেন্ট প্রাপ্ত', description: language === 'en' ? '৳5,000 via bKash' : 'বিকাশে ৳৫,০০০', time: '3h', color: colorMap.payment },
      ];

  // ===== SYSTEM HEALTH =====
  const systemHealth = [
    { label: language === 'en' ? 'Database' : 'ডাটাবেস', value: language === 'en' ? 'ONLINE' : 'অনলাইন', icon: Shield },
    { label: language === 'en' ? 'DB Size' : 'ডাটাবেস সাইজ', value: '2.4 GB', icon: Monitor },
    { label: language === 'en' ? 'Concurrent' : 'সমবর্তী', value: `${Math.max(1, Math.floor(stats.totalUsers * 0.08))}`, icon: Users },
    { label: language === 'en' ? 'Disk Usage' : 'ডিস্ক ব্যবহার', value: '34%', icon: PieChart },
  ];

  // ===== ERROR LOGS =====
  const errorLogs = [
    { code: '404', message: language === 'en' ? 'Product not found — ID:892' : 'পণ্য পাওয়া যায়নি — ID:892', time: '2m ago', severity: 'warn' as const },
    { code: '500', message: language === 'en' ? 'Payment gateway timeout' : 'পেমেন্ট গেটওয়ে টাইমআউট', time: '15m ago', severity: 'error' as const },
    { code: '403', message: language === 'en' ? 'Unauthorized admin access attempt' : 'অননুমোদিত অ্যাডমিন অ্যাক্সেস প্রচেষ্টা', time: '1h ago', severity: 'warn' as const },
    { code: '429', message: language === 'en' ? 'Rate limit exceeded — API' : 'রেট লিমিট ছাড়িয়েছে — API', time: '2h ago', severity: 'info' as const },
    { code: '500', message: language === 'en' ? 'Database connection pool full' : 'ডাটাবেস কানেকশন পুল পূর্ণ', time: '3h ago', severity: 'error' as const },
  ];

  return (
    <div className="space-y-6">
      {/* ===== HEADER SECTION ===== */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">
            {greeting},{' '}
            <span className="bg-gradient-to-r from-orange-600 to-orange-400 bg-clip-text text-transparent">
              {adminUser?.name || (language === 'en' ? 'Admin' : 'অ্যাডমিন')}
            </span>{' '}
            👋
          </h2>
          <p className="text-sm text-muted-foreground mt-1 flex items-center gap-2">
            <Clock className="h-3.5 w-3.5" />
            {formattedDate} · {formattedTime}
          </p>
        </div>
        <div className="flex items-center gap-3 flex-wrap">
          <Badge className="bg-green-500/10 text-green-600 dark:text-green-400 border-green-200 dark:border-green-800 px-3 py-1">
            <span className="relative flex h-2 w-2 mr-2">
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75" />
              <span className="relative inline-flex rounded-full h-2 w-2 bg-green-500" />
            </span>
            {language === 'en' ? 'Live System Feed' : 'লাইভ সিস্টেম ফিড'}
          </Badge>
          <Badge variant="outline" className="px-3 py-1">
            <Shield className="h-3.5 w-3.5 mr-1.5 text-orange-500" />
            {adminUser?.role || 'Admin'}
          </Badge>
        </div>
      </div>

      {/* ===== TOP METRICS ROW ===== */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {metricCards.map((card, i) => (
          <Card key={i} className={`relative overflow-hidden border-0 bg-gradient-to-br ${card.gradient} shadow-lg transition-all duration-300 hover:shadow-xl hover:-translate-y-1`}>
            <div className="absolute top-0 right-0 h-32 w-32 rounded-full bg-white/10 -translate-y-8 translate-x-8" />
            <div className="absolute bottom-0 left-0 h-20 w-20 rounded-full bg-white/5 translate-y-6 -translate-x-6" />
            <CardContent className="relative p-4 sm:p-5">
              <div className="flex items-center justify-between mb-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-white/20 backdrop-blur-sm">
                  <card.icon className="h-5 w-5 text-white" strokeWidth={2} />
                </div>
                <div className="flex items-center gap-1 rounded-full bg-white/20 px-2.5 py-1 backdrop-blur-sm">
                  {card.trend === 'up' ? <ArrowUpRight className="h-3 w-3 text-white" /> : <ArrowDownRight className="h-3 w-3 text-white" />}
                  <span className="text-xs font-bold text-white">{card.change}</span>
                </div>
              </div>
              <p className="text-2xl lg:text-3xl font-extrabold text-white tracking-tight">{card.value}</p>
              <p className="mt-1 text-sm text-white/80 font-medium">{card.title}</p>
              <p className="mt-0.5 text-[10px] text-white/50">{card.subtitle}</p>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* ===== QUICK ACTIONS BAR ===== */}
      <Card className="border-0 shadow-sm bg-gradient-to-r from-card to-accent/20">
        <CardContent className="p-4">
          <div className="flex items-center gap-2 overflow-x-auto pb-1" style={{ scrollbarWidth: 'thin' }}>
            {quickActions.map((action, i) => (
              <button
                key={i}
                onClick={() => onNavigate?.(action.tab)}
                className="group flex items-center gap-2 shrink-0 rounded-xl border bg-background/60 px-4 py-2.5 transition-all duration-200 hover:shadow-md hover:-translate-y-0.5 hover:border-orange-300 dark:hover:border-orange-700"
              >
                <div className={`flex h-7 w-7 items-center justify-center rounded-lg ${action.color} transition-transform group-hover:scale-110`}>
                  <action.icon className="h-3.5 w-3.5" />
                </div>
                <span className="text-xs font-medium whitespace-nowrap">{action.label}</span>
              </button>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* ===== MIDDLE ROW: Revenue + Demographics ===== */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* Revenue Overview Chart */}
        <Card className="lg:col-span-2 border-0 shadow-sm">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-base font-bold flex items-center gap-2">
                  <BarChart3 className="h-5 w-5 text-orange-500" />
                  {language === 'en' ? 'Revenue Overview' : 'আয়ের সারসংক্ষেপ'}
                </CardTitle>
                <p className="text-xs text-muted-foreground mt-0.5">{language === 'en' ? 'Last 7 days performance' : 'গত ৭ দিনের পারফরম্যান্স'}</p>
              </div>
              <div className="text-right">
                <p className="text-xs text-muted-foreground">{language === 'en' ? 'Total Revenue' : 'মোট আয়'}</p>
                <p className="text-lg font-bold bg-gradient-to-r from-orange-600 to-orange-400 bg-clip-text text-transparent">৳{totalRevenue.toLocaleString()}</p>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="flex items-end gap-3 h-52 pt-4">
              {revenueData.map((v, i) => (
                <div key={i} className="flex-1 flex flex-col items-center gap-2 group">
                  <div className="relative w-full">
                    <div className="absolute -top-7 left-1/2 -translate-x-1/2 opacity-0 group-hover:opacity-100 transition-opacity duration-200 text-[10px] font-semibold text-foreground bg-popover px-2 py-1 rounded-md shadow-sm border whitespace-nowrap z-10">
                      ৳{v.toLocaleString()}
                    </div>
                    <div
                      className="w-full rounded-t-lg bg-gradient-to-t from-orange-600 to-orange-400 transition-all duration-700 ease-out hover:from-orange-700 hover:to-orange-500 cursor-pointer"
                      style={{ height: animatedBars ? `${(v / maxRevenue) * 180}px` : '0px', minHeight: animatedBars ? '8px' : '0px' }}
                    />
                  </div>
                  <span className="text-[10px] font-medium text-muted-foreground">{days[i]}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Demographics Breakdown */}
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2">
            <CardTitle className="text-base font-bold flex items-center gap-2">
              <PieChart className="h-5 w-5 text-orange-500" />
              {language === 'en' ? 'Demographics' : 'জনসংখ্যাতত্ত্ব'}
            </CardTitle>
            <p className="text-xs text-muted-foreground">{language === 'en' ? 'Platform breakdown' : 'প্ল্যাটফর্ম বিশ্লেষণ'}</p>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {demographics.map((d, i) => {
                const maxVal = Math.max(...demographics.map(x => x.value), 1);
                return (
                  <div key={i} className="flex items-center gap-3 rounded-xl bg-accent/30 p-3 transition-colors hover:bg-accent/50">
                    <div className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-xl ${d.bg}`}>
                      <d.icon className={`h-5 w-5 ${d.color}`} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium">{d.label}</p>
                      <div className="mt-1 h-1.5 rounded-full bg-accent overflow-hidden">
                        <div
                          className="h-full rounded-full bg-gradient-to-r from-orange-600 to-orange-400 transition-all duration-1000"
                          style={{ width: `${Math.min(100, (d.value / maxVal) * 100)}%` }}
                        />
                      </div>
                    </div>
                    <span className="text-sm font-bold shrink-0">{d.value.toLocaleString()}</span>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* ===== BOTTOM ROW: Activity + System Health + Donut + Errors ===== */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Live Activity Feed */}
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm font-bold flex items-center gap-2">
                <Activity className="h-4 w-4 text-orange-500" />
                {language === 'en' ? 'Live Activity' : 'লাইভ কার্যকলাপ'}
              </CardTitle>
              <Badge className="bg-red-500/10 text-red-600 dark:text-red-400 border-red-200 dark:border-red-800 text-[10px] px-2 py-0.5">
                <span className="relative flex h-1.5 w-1.5 mr-1.5">
                  <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75" />
                  <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-red-500" />
                </span>
                LIVE
              </Badge>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-2 max-h-72 overflow-y-auto" style={{ scrollbarWidth: 'thin' }}>
              {activityFeed.map((activity, i) => (
                <div key={i} className="flex items-start gap-2.5 rounded-lg bg-accent/30 p-2.5 transition-colors hover:bg-accent/50">
                  <div className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${activity.color}`}>
                    <activity.icon className="h-3.5 w-3.5" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs font-medium truncate">{activity.title}</p>
                    {activity.description && (
                      <p className="text-[10px] text-muted-foreground truncate">{activity.description}</p>
                    )}
                  </div>
                  <span className="shrink-0 text-[10px] text-muted-foreground whitespace-nowrap flex items-center gap-0.5">
                    <Clock className="h-2.5 w-2.5" />
                    {activity.time}
                  </span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* System Health */}
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm font-bold flex items-center gap-2">
                <Shield className="h-4 w-4 text-orange-500" />
                {language === 'en' ? 'System Health' : 'সিস্টেম স্বাস্থ্য'}
              </CardTitle>
              <Badge className="bg-green-500/10 text-green-600 dark:text-green-400 border-green-200 dark:border-green-800 text-[10px] px-2 py-0.5">
                ALL CLEAR
              </Badge>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-2.5">
              {systemHealth.map((item, i) => (
                <div key={i} className="flex items-center gap-2.5 rounded-lg bg-accent/30 p-2.5 transition-colors hover:bg-accent/50">
                  <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-green-50 dark:bg-green-950/30">
                    <item.icon className="h-4 w-4 text-green-600 dark:text-green-400" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-[10px] text-muted-foreground">{item.label}</p>
                    <p className="text-xs font-bold">{item.value}</p>
                  </div>
                  <div className="relative flex h-2 w-2 shrink-0">
                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-50" />
                    <span className="relative inline-flex rounded-full h-2 w-2 bg-green-500" />
                  </div>
                </div>
              ))}
              {/* Disk capacity progress */}
              <div className="rounded-lg bg-accent/30 p-2.5">
                <div className="flex items-center justify-between mb-1.5">
                  <span className="text-[10px] font-medium text-muted-foreground">{language === 'en' ? 'Disk Capacity' : 'ডিস্ক ক্ষমতা'}</span>
                  <span className="text-[10px] font-bold">34%</span>
                </div>
                <div className="h-2 rounded-full bg-accent overflow-hidden">
                  <div className="h-full rounded-full bg-gradient-to-r from-green-500 to-emerald-400" style={{ width: '34%' }} />
                </div>
                <p className="text-[9px] text-muted-foreground mt-1">{language === 'en' ? '16.3 GB of 48 GB used' : '৪৮ GB এর মধ্যে ১৬.৩ GB ব্যবহৃত'}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Subscription / User Profile — Donut Chart */}
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-bold flex items-center gap-2">
              <PieChart className="h-4 w-4 text-orange-500" />
              {language === 'en' ? 'User Profile' : 'ব্যবহারকারী প্রোফাইল'}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex flex-col items-center">
              {/* SVG Donut Chart */}
              <div className="relative w-32 h-32">
                <svg viewBox="0 0 100 100" className="w-full h-full -rotate-90">
                  {/* Background ring */}
                  <circle cx="50" cy="50" r="40" fill="none" stroke="currentColor" className="text-accent" strokeWidth="12" />
                  {/* Active segment */}
                  <circle
                    cx="50" cy="50" r="40" fill="none"
                    stroke="#f97316" strokeWidth="12"
                    strokeDasharray={`${activeStroke} ${circumference}`}
                    strokeDashoffset="0"
                    strokeLinecap="round"
                    className="transition-all duration-1000"
                  />
                  {/* Inactive segment */}
                  <circle
                    cx="50" cy="50" r="40" fill="none"
                    stroke="#fdba74" strokeWidth="12"
                    strokeDasharray={`${inactiveStroke} ${circumference}`}
                    strokeDashoffset={`${-activeStroke}`}
                    strokeLinecap="round"
                    className="transition-all duration-1000"
                  />
                </svg>
                <div className="absolute inset-0 flex flex-col items-center justify-center">
                  <span className="text-2xl font-extrabold">{activePercent}%</span>
                  <span className="text-[10px] text-muted-foreground">{language === 'en' ? 'Active' : 'সক্রিয়'}</span>
                </div>
              </div>
              {/* Legend */}
              <div className="flex items-center gap-4 mt-4 w-full justify-center">
                <div className="flex items-center gap-1.5">
                  <div className="h-2.5 w-2.5 rounded-full bg-orange-500" />
                  <span className="text-[10px] text-muted-foreground">{language === 'en' ? 'Active' : 'সক্রিয়'} ({activeCount.toLocaleString()})</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <div className="h-2.5 w-2.5 rounded-full bg-orange-300" />
                  <span className="text-[10px] text-muted-foreground">{language === 'en' ? 'Inactive' : 'নিষ্ক্রিয়'} ({inactiveCount.toLocaleString()})</span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Live Application Errors */}
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm font-bold flex items-center gap-2">
                <AlertTriangle className="h-4 w-4 text-orange-500" />
                {language === 'en' ? 'App Errors' : 'অ্যাপ ত্রুটি'}
              </CardTitle>
              <Badge variant="destructive" className="text-[10px] px-2 py-0.5">
                {errorLogs.filter(e => e.severity === 'error').length} {language === 'en' ? 'CRITICAL' : 'সংকটপূর্ণ'}
              </Badge>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-2 max-h-72 overflow-y-auto" style={{ scrollbarWidth: 'thin' }}>
              {errorLogs.map((err, i) => (
                <div key={i} className="flex items-start gap-2 rounded-lg bg-accent/30 p-2.5 transition-colors hover:bg-accent/50">
                  <div className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[9px] font-bold ${
                    err.severity === 'error' ? 'bg-red-100 text-red-600 dark:bg-red-950/30 dark:text-red-400' :
                    err.severity === 'warn' ? 'bg-amber-100 text-amber-600 dark:bg-amber-950/30 dark:text-amber-400' :
                    'bg-sky-100 text-sky-600 dark:bg-sky-950/30 dark:text-sky-400'
                  }`}>
                    {err.code}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-[11px] font-medium truncate">{err.message}</p>
                    <span className="text-[9px] text-muted-foreground">{err.time}</span>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

// ============ TEAM MANAGEMENT ============
function TeamManagement() {
  const { language, adminUser, adminPermissions, adminToken } = useAppStore();
  const [members, setMembers] = useState<TeamMemberData[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [editingMember, setEditingMember] = useState<TeamMemberData | null>(null);
  const [addDialogOpen, setAddDialogOpen] = useState(false);

  const canManageTeam = isSuperAdmin(adminUser?.role || '') || adminPermissions?.canManageTeam;

  const fetchMembers = useCallback(async () => {
    try {
      const res = await adminFetch('/api/admin/team', {}, adminToken);
      if (res.status === 401) { useAppStore.getState().adminLogout(); return; }
      const data = await safeJsonParse<{ success: boolean; members: TeamMemberData[] }>(res);
      if (data?.success) setMembers(data.members);
    } catch (err) {
      console.error('Failed to fetch team:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchMembers(); }, [fetchMembers]);

  const handleDelete = async (id: string) => {
    try {
      const res = await adminFetch('/api/admin/team', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ teamMemberId: id }),
      }, adminToken);
      if (res.status === 401) { useAppStore.getState().adminLogout(); return; }
      const data = await safeJsonParse<{ success: boolean }>(res);
      if (data?.success) fetchMembers();
    } catch (err) {
      console.error('Failed to delete team member:', err);
    }
  };

  const handleToggleActive = async (id: string, current: boolean) => {
    try {
      const res = await adminFetch('/api/admin/team', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ teamMemberId: id, isActive: !current }),
      }, adminToken);
      if (res.status === 401) { useAppStore.getState().adminLogout(); return; }
      const data = await safeJsonParse<{ success: boolean }>(res);
      if (data?.success) fetchMembers();
    } catch (err) {
      console.error('Failed to update member:', err);
    }
  };

  const handleUpdatePermissions = async (id: string, permissions: Record<string, boolean>) => {
    try {
      const res = await adminFetch('/api/admin/team', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ teamMemberId: id, ...permissions }),
      }, adminToken);
      if (res.status === 401) { useAppStore.getState().adminLogout(); return; }
      const data = await safeJsonParse<{ success: boolean }>(res);
      if (data?.success) {
        fetchMembers();
        setEditingMember(null);
      }
    } catch (err) {
      console.error('Failed to update permissions:', err);
    }
  };

  const filtered = members.filter((m) =>
    m.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    m.email.toLowerCase().includes(searchQuery.toLowerCase())
  );

  if (loading) {
    return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>;
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h2 className="text-xl font-bold flex items-center gap-2">
            <UserCog className="h-5 w-5 text-primary" />
            {language === 'en' ? 'Team Management' : 'টিম ম্যানেজমেন্ট'}
          </h2>
          <p className="text-sm text-muted-foreground mt-1">
            {language === 'en' ? 'Create and manage team members with granular access control' : 'সূক্ষ্ম অ্যাক্সেস কন্ট্রোল সহ টিম সদস্য তৈরি এবং পরিচালনা করুন'}
          </p>
        </div>
        {canManageTeam && (
          <Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
            <DialogTrigger asChild>
              <Button className="gap-2 bg-gradient-to-r from-orange-700 to-orange-500 shadow-md hover:from-orange-800 hover:to-orange-600">
                <UserPlus className="h-4 w-4" />
                {language === 'en' ? 'Add Team Member' : 'টিম সদস্য যোগ করুন'}
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2"><UserPlus className="h-5 w-5 text-primary" />{language === 'en' ? 'Add Team Member' : 'টিম সদস্য যোগ করুন'}</DialogTitle>
              </DialogHeader>
              <AddTeamMemberForm onMemberAdded={() => { fetchMembers(); setAddDialogOpen(false); }} />
            </DialogContent>
          </Dialog>
        )}
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: language === 'en' ? 'Total Members' : 'মোট সদস্য', value: members.length, icon: Users, color: 'text-orange-600 bg-orange-50 dark:bg-orange-950/30' },
          { label: language === 'en' ? 'Active' : 'সক্রিয়', value: members.filter(m => m.isActive).length, icon: CheckCircle, color: 'text-emerald-600 bg-emerald-50 dark:bg-emerald-950/30' },
          { label: language === 'en' ? 'Inactive' : 'নিষ্ক্রিয়', value: members.filter(m => !m.isActive).length, icon: Ban, color: 'text-amber-600 bg-amber-50 dark:bg-amber-950/30' },
          { label: language === 'en' ? 'Full Access' : 'সম্পূর্ণ অ্যাক্সেস', value: members.filter(m => m.canManageUsers && m.canManageHouses && m.canManageShops && m.canManageProducts && m.canManageOrders && m.canManageMCQ && m.canManageCommunity && m.canManageTeam).length, icon: Shield, color: 'text-orange-600 bg-orange-50 dark:bg-orange-950/30' },
        ].map((s, i) => (
          <Card key={i} className="transition-shadow hover:shadow-md">
            <CardContent className="p-4 flex items-center gap-3">
              <div className={`flex h-10 w-10 items-center justify-center rounded-xl ${s.color}`}>
                <s.icon className="h-5 w-5" />
              </div>
              <div>
                <p className="text-2xl font-bold">{s.value}</p>
                <p className="text-[10px] text-muted-foreground">{s.label}</p>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        <Input placeholder={language === 'en' ? 'Search team members...' : 'টিম সদস্য খুঁজুন...'} value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="pl-10" />
      </div>

      {/* Members List */}
      <div className="grid gap-4">
        {filtered.map((member) => (
          <Card key={member.id} className={`transition-all hover:shadow-md ${!member.isActive ? 'opacity-60' : ''}`}>
            <CardContent className="p-5">
              <div className="flex flex-col sm:flex-row sm:items-center gap-4">
                {/* Avatar + Info */}
                <div className="flex items-center gap-3 flex-1 min-w-0">
                  <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-orange-600 to-orange-500 shadow-md">
                    <span className="text-lg font-bold text-white">{member.name.charAt(0).toUpperCase()}</span>
                  </div>
                  <div className="min-w-0">
                    <div className="flex items-center flex-wrap gap-1.5">
                      <p className="text-sm font-semibold truncate">{member.name}</p>
                      {getRoleBadge(member.role, language)}
                      <Badge className={`text-[9px] ${member.isActive ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400'}`}>
                        {member.isActive ? (language === 'en' ? 'Active' : 'সক্রিয়') : (language === 'en' ? 'Inactive' : 'নিষ্ক্রিয়')}
                      </Badge>
                    </div>
                    <p className="text-xs text-muted-foreground truncate">{member.email}</p>
                    {member.phone && <p className="text-[10px] text-muted-foreground">{member.phone}</p>}
                    {/* Permission Pills */}
                    <div className="flex flex-wrap gap-1 mt-2">
                      {[
                        { key: 'canManageUsers', label: language === 'en' ? 'Users' : 'ব্যবহারকারী' },
                        { key: 'canManageHouses', label: language === 'en' ? 'Houses' : 'বাড়ি' },
                        { key: 'canManageShops', label: language === 'en' ? 'Shops' : 'দোকান' },
                        { key: 'canManageProducts', label: language === 'en' ? 'Products' : 'পণ্য' },
                        { key: 'canManageOrders', label: language === 'en' ? 'Orders' : 'অর্ডার' },
                        { key: 'canManageMCQ', label: 'MCQ' },
                        { key: 'canManageCommunity', label: language === 'en' ? 'Community' : 'কমিউনিটি' },
                        { key: 'canSendNotification', label: language === 'en' ? 'Notifications' : 'নোটিফিকেশন' },
                        { key: 'canViewAnalytics', label: language === 'en' ? 'Analytics' : 'অ্যানালিটিক্স' },
                        { key: 'canManageTeam', label: language === 'en' ? 'Team' : 'টিম' },
                      ].map((p) => (
                        <span key={p.key} className={`text-[9px] px-1.5 py-0.5 rounded-md ${(member as Record<string, unknown>)[p.key] ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-red-50 text-red-400 dark:bg-red-950/20 dark:text-red-500'}`}>
                          {p.label}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>

                {/* Actions */}
                {canManageTeam && !isSuperAdmin(member.role) && (
                  <div className="flex items-center gap-2 shrink-0">
                    <Button variant="outline" size="sm" className="gap-1.5 text-xs" onClick={() => setEditingMember(member)}>
                      <Edit className="h-3.5 w-3.5" />
                      {language === 'en' ? 'Edit' : 'সম্পাদনা'}
                    </Button>
                    <Button variant="outline" size="sm" className="text-xs" onClick={() => handleToggleActive(member.id, member.isActive)}>
                      {member.isActive ? <Ban className="h-3.5 w-3.5 text-amber-500" /> : <CheckCircle className="h-3.5 w-3.5 text-emerald-500" />}
                    </Button>
                    <AlertDialog>
                      <AlertDialogTrigger asChild>
                        <Button variant="outline" size="sm" className="text-xs text-destructive hover:bg-destructive/5">
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle>{language === 'en' ? 'Delete Team Member?' : 'টিম সদস্য মুছবেন?'}</AlertDialogTitle>
                          <AlertDialogDescription>{language === 'en' ? `Remove ${member.name} from the team? This cannot be undone.` : `${member.name}-কে টিম থেকে সরাবেন? এটি পূর্বাবস্থায় ফেরানো যাবে না।`}</AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>{language === 'en' ? 'Cancel' : 'বাতিল'}</AlertDialogCancel>
                          <AlertDialogAction onClick={() => handleDelete(member.id)} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">{language === 'en' ? 'Delete' : 'মুছুন'}</AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        ))}
        {filtered.length === 0 && (
          <div className="py-16 text-center">
            <UserCog className="h-12 w-12 text-muted-foreground/30 mx-auto mb-3" />
            <p className="text-sm text-muted-foreground">{language === 'en' ? 'No team members yet' : 'এখনও কোনো টিম সদস্য নেই'}</p>
          </div>
        )}
      </div>

      {/* Edit Member Dialog */}
      {editingMember && (
        <Dialog open={!!editingMember} onOpenChange={() => setEditingMember(null)}>
          <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <Edit className="h-5 w-5 text-primary" />
                {language === 'en' ? `Edit ${editingMember.name}` : `${editingMember.name} সম্পাদনা`}
              </DialogTitle>
            </DialogHeader>
            <PermissionEditor
              member={editingMember}
              onSave={(perms) => handleUpdatePermissions(editingMember.id, perms)}
              onCancel={() => setEditingMember(null)}
            />
          </DialogContent>
        </Dialog>
      )}
    </div>
  );
}

// ============ PERMISSION EDITOR ============
function PermissionEditor({ member, onSave, onCancel }: { member: TeamMemberData; onSave: (perms: Record<string, boolean>) => void; onCancel: () => void }) {
  const { language } = useAppStore();
  const [selectedRole, setSelectedRole] = useState(member.role || 'viewer');
  const [perms, setPerms] = useState<Record<string, boolean>>({
    canManageUsers: member.canManageUsers,
    canManageHouses: member.canManageHouses,
    canManageShops: member.canManageShops,
    canManageProducts: member.canManageProducts,
    canManageOrders: member.canManageOrders,
    canManageMCQ: member.canManageMCQ,
    canManageCommunity: member.canManageCommunity,
    canSendNotification: member.canSendNotification,
    canViewAnalytics: member.canViewAnalytics,
    canManageTeam: member.canManageTeam,
  });
  const [saving, setSaving] = useState(false);

  const handleRoleChange = (role: string) => {
    setSelectedRole(role);
    const preset = ROLE_PRESETS[role];
    if (preset) {
      setPerms({ ...preset.permissions });
    }
  };

  const permissionLabels: { key: string; label: string; labelBn: string; icon: React.ElementType; desc: string; descBn: string }[] = [
    { key: 'canManageUsers', label: 'Manage Users', labelBn: 'ব্যবহারকারী পরিচালনা', icon: Users, desc: 'View, create, suspend users', descBn: 'ব্যবহারকারী দেখুন, তৈরি করুন, স্থগিত করুন' },
    { key: 'canManageHouses', label: 'Manage Houses', labelBn: 'বাড়ি পরিচালনা', icon: Building2, desc: 'Approve, suspend house listings', descBn: 'বাড়ির তালিকা অনুমোদন, স্থগিত করুন' },
    { key: 'canManageShops', label: 'Manage Shops', labelBn: 'দোকান পরিচালনা', icon: Store, desc: 'Manage shop rental listings', descBn: 'দোকান ভাড়ার তালিকা পরিচালনা করুন' },
    { key: 'canManageProducts', label: 'Manage Products', labelBn: 'পণ্য পরিচালনা', icon: ShoppingBag, desc: 'Manage marketplace products', descBn: 'মার্কেটপ্লেস পণ্য পরিচালনা করুন' },
    { key: 'canManageOrders', label: 'Manage Orders', labelBn: 'অর্ডার পরিচালনা', icon: Package, desc: 'View and update order statuses', descBn: 'অর্ডার স্ট্যাটাস দেখুন এবং আপডেট করুন' },
    { key: 'canManageMCQ', label: 'Manage MCQ', labelBn: 'MCQ পরিচালনা', icon: GraduationCap, desc: 'Add, edit quiz questions', descBn: 'কুইজ প্রশ্ন যোগ করুন, সম্পাদনা করুন' },
    { key: 'canManageCommunity', label: 'Manage Community', labelBn: 'কমিউনিটি পরিচালনা', icon: MessageSquare, desc: 'Moderate community posts', descBn: 'কমিউনিটি পোস্ট পরিমিত করুন' },
    { key: 'canSendNotification', label: 'Send Notifications', labelBn: 'নোটিফিকেশন পাঠান', icon: Bell, desc: 'Send push notifications to users', descBn: 'ব্যবহারকারীদের পুশ নোটিফিকেশন পাঠান' },
    { key: 'canViewAnalytics', label: 'View Analytics', labelBn: 'অ্যানালিটিক্স দেখুন', icon: BarChart3, desc: 'Access dashboard analytics', descBn: 'ড্যাশবোর্ড অ্যানালিটিক্স অ্যাক্সেস করুন' },
    { key: 'canManageTeam', label: 'Manage Team', labelBn: 'টিম পরিচালনা', icon: UserCog, desc: 'Create and manage team members', descBn: 'টিম সদস্য তৈরি এবং পরিচালনা করুন' },
  ];

  const handleSave = () => {
    setSaving(true);
    onSave({ ...perms, role: selectedRole });
  };

  const toggleAll = (val: boolean) => {
    const newPerms: Record<string, boolean> = {};
    permissionLabels.forEach(p => { newPerms[p.key] = val; });
    setPerms(newPerms);
  };

  return (
    <div className="space-y-4">
      {/* Role Selection */}
      <div className="space-y-2">
        <Label className="text-sm font-medium">{language === 'en' ? 'Role' : 'ভূমিকা'}</Label>
        <Select value={selectedRole} onValueChange={handleRoleChange}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder={language === 'en' ? 'Select role' : 'ভূমিকা নির্বাচন'} />
          </SelectTrigger>
          <SelectContent>
            {Object.entries(ROLE_PRESETS).map(([key, preset]) => (
              <SelectItem key={key} value={key}>
                {language === 'en' ? preset.label : preset.labelBn}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <p className="text-[10px] text-muted-foreground">
          {language === 'en' ? 'Selecting a role auto-fills permissions. You can override individually below.' : 'ভূমিকা নির্বাচন করলে অনুমতি স্বয়ংক্রিয়ভাবে পূরণ হবে। নিচে আলাদাভাবে পরিবর্তন করতে পারেন।'}
        </p>
      </div>

      <Separator />

      <div className="flex items-center justify-between">
        <p className="text-sm text-muted-foreground">{language === 'en' ? 'Fine-tune permissions (overrides role preset)' : 'অনুমতি সূক্ষ্ম সমন্বয় (ভূমিকা প্রিসেট অগ্রাহ্য করে)'}</p>
        <div className="flex gap-1">
          <Button variant="outline" size="sm" className="text-[10px] h-7" onClick={() => toggleAll(true)}>{language === 'en' ? 'Select All' : 'সব নির্বাচন'}</Button>
          <Button variant="outline" size="sm" className="text-[10px] h-7" onClick={() => toggleAll(false)}>{language === 'en' ? 'Deselect All' : 'সব বাতিল'}</Button>
        </div>
      </div>

      <div className="space-y-2 max-h-80 overflow-y-auto pr-1">
        {permissionLabels.map((p) => {
          const Icon = p.icon;
          const checked = perms[p.key] || false;
          return (
            <div key={p.key} className={`flex items-center gap-3 rounded-xl border p-3 transition-all ${checked ? 'border-primary/30 bg-primary/5' : 'border-border'}`}>
              <div className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${checked ? 'bg-primary/10 text-primary' : 'bg-accent text-muted-foreground'}`}>
                <Icon className="h-4 w-4" />
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium">{language === 'en' ? p.label : p.labelBn}</p>
                <p className="text-[10px] text-muted-foreground">{language === 'en' ? p.desc : p.descBn}</p>
              </div>
              <Switch checked={checked} onCheckedChange={(v) => setPerms({ ...perms, [p.key]: v })} />
            </div>
          );
        })}
      </div>

      <div className="flex items-center gap-2 pt-2">
        <Button variant="outline" className="flex-1" onClick={onCancel}>{language === 'en' ? 'Cancel' : 'বাতিল'}</Button>
        <Button className="flex-1 bg-gradient-to-r from-orange-700 to-orange-500" onClick={handleSave} disabled={saving}>
          {saving ? (language === 'en' ? 'Saving...' : 'সংরক্ষণ হচ্ছে...') : (language === 'en' ? 'Save Permissions' : 'অনুমতি সংরক্ষণ করুন')}
        </Button>
      </div>
    </div>
  );
}

// ============ ADD TEAM MEMBER FORM ============
function AddTeamMemberForm({ onMemberAdded }: { onMemberAdded: () => void }) {
  const { language, adminUser, adminToken } = useAppStore();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [selectedRole, setSelectedRole] = useState('admin');
  const [perms, setPerms] = useState<Record<string, boolean>>({ ...ROLE_PRESETS.admin.permissions });
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const handleRoleChange = (role: string) => {
    setSelectedRole(role);
    const preset = ROLE_PRESETS[role];
    if (preset) {
      setPerms({ ...preset.permissions });
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name || !email || !password) return;
    setIsLoading(true);
    setError('');
    try {
      const res = await adminFetch('/api/admin/team', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, email, phone, password, role: selectedRole, createdById: adminUser?.id, ...perms }),
      }, adminToken);
      const data = await safeJsonParse<{ success: boolean }>(res);
      if (data?.success) {
        onMemberAdded();
        setName(''); setEmail(''); setPhone(''); setPassword('');
      } else {
        setError(data.error || 'Failed to create member');
      }
    } catch (err) {
      console.error('Failed to create team member:', err);
      setError('Network error');
    } finally {
      setIsLoading(false);
    }
  };

  const permissionItems = [
    { key: 'canManageUsers', label: language === 'en' ? 'Users' : 'ব্যবহারকারী', icon: Users },
    { key: 'canManageHouses', label: language === 'en' ? 'Houses' : 'বাড়ি', icon: Building2 },
    { key: 'canManageShops', label: language === 'en' ? 'Shops' : 'দোকান', icon: Store },
    { key: 'canManageProducts', label: language === 'en' ? 'Products' : 'পণ্য', icon: ShoppingBag },
    { key: 'canManageOrders', label: language === 'en' ? 'Orders' : 'অর্ডার', icon: Package },
    { key: 'canManageMCQ', label: 'MCQ', icon: GraduationCap },
    { key: 'canManageCommunity', label: language === 'en' ? 'Community' : 'কমিউনিটি', icon: MessageSquare },
    { key: 'canSendNotification', label: language === 'en' ? 'Notifications' : 'নোটিফিকেশন', icon: Bell },
    { key: 'canViewAnalytics', label: language === 'en' ? 'Analytics' : 'অ্যানালিটিক্স', icon: BarChart3 },
    { key: 'canManageTeam', label: language === 'en' ? 'Team' : 'টিম', icon: UserCog },
  ];

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {error && <div className="rounded-lg border border-destructive/20 bg-destructive/5 p-3 text-center text-sm text-destructive">{error}</div>}
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{language === 'en' ? 'Full Name' : 'পুরো নাম'}</Label>
          <Input value={name} onChange={(e) => setName(e.target.value)} required />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{language === 'en' ? 'Phone' : 'ফোন'}</Label>
          <Input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} />
        </div>
      </div>
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">{language === 'en' ? 'Email' : 'ইমেইল'}</Label>
        <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
      </div>
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">{language === 'en' ? 'Password' : 'পাসওয়ার্ড'}</Label>
        <Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
      </div>

      <Separator />

      {/* Role Selection */}
      <div className="space-y-2">
        <Label className="text-xs font-medium">{language === 'en' ? 'Role' : 'ভূমিকা'}</Label>
        <Select value={selectedRole} onValueChange={handleRoleChange}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder={language === 'en' ? 'Select role' : 'ভূমিকা নির্বাচন'} />
          </SelectTrigger>
          <SelectContent>
            {Object.entries(ROLE_PRESETS).filter(([key]) => key !== 'super_admin').map(([key, preset]) => (
              <SelectItem key={key} value={key}>
                {language === 'en' ? preset.label : preset.labelBn}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <p className="text-[10px] text-muted-foreground">
          {language === 'en' ? 'Selecting a role auto-fills permissions below. You can override individually.' : 'ভূমিকা নির্বাচন করলে নিচের অনুমতি স্বয়ংক্রিয়ভাবে পূরণ হবে। আলাদাভাবে পরিবর্তন করতে পারেন।'}
        </p>
      </div>

      <div>
        <Label className="text-xs font-medium mb-2 block">{language === 'en' ? 'Access Permissions' : 'অ্যাক্সেস অনুমতি'}</Label>
        <div className="grid grid-cols-2 gap-2">
          {permissionItems.map((p) => {
            const Icon = p.icon;
            const checked = perms[p.key] || false;
            return (
              <label key={p.key} className={`flex items-center gap-2 rounded-lg border p-2 cursor-pointer transition-all text-xs ${checked ? 'border-primary/30 bg-primary/5' : 'hover:bg-accent'}`}>
                <Switch checked={checked} onCheckedChange={(v) => setPerms({ ...perms, [p.key]: v })} className="scale-75" />
                <Icon className="h-3.5 w-3.5 shrink-0" />
                <span className="font-medium">{p.label}</span>
              </label>
            );
          })}
        </div>
      </div>

      <Button type="submit" className="w-full bg-gradient-to-r from-orange-700 to-orange-500" disabled={isLoading}>
        {isLoading ? (language === 'en' ? 'Creating...' : 'তৈরি হচ্ছে...') : (language === 'en' ? 'Create Team Member' : 'টিম সদস্য তৈরি করুন')}
      </Button>
    </form>
  );
}

// ============ ADMIN USERS (simplified - reused from before) ============
function AdminUsers() {
  const { language, adminToken } = useAppStore();
  const [users, setUsers] = useState<Record<string, unknown>[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');

  const fetchUsers = useCallback(async () => {
    try {
      const res = await adminFetch('/api/admin/users', {}, adminToken);
      const data = await safeJsonParse<Record<string, unknown>>(res);
      if (res.status === 401) { useAppStore.getState().adminLogout(); return; }
      if (data?.success) setUsers(data?.users as unknown as typeof users);
    } catch (err) { console.error('Failed to fetch users:', err); }
    finally { setLoading(false); }
  }, []);
  useEffect(() => { fetchUsers(); }, [fetchUsers]);

  const handleToggleActive = async (userId: string, currentActive: boolean) => {
    try {
      const res = await adminFetch('/api/admin/users', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId, isActive: !currentActive }) }, adminToken);
      const data = await safeJsonParse<Record<string, unknown>>(res);
      if (res.status === 401) { useAppStore.getState().adminLogout(); return; }
      if (data?.success) fetchUsers();
    } catch (err) { console.error('Failed to update user:', err); }
  };

  const handleDelete = async (userId: string) => {
    try {
      const res = await adminFetch('/api/admin/users', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId }) }, adminToken);
      const data = await safeJsonParse<Record<string, unknown>>(res);
      if (res.status === 401) { useAppStore.getState().adminLogout(); return; }
      if (data?.success) fetchUsers();
    } catch (err) { console.error('Failed to delete user:', err); }
  };

  const filtered = users.filter((u) => String(u.name).toLowerCase().includes(searchQuery.toLowerCase()) || String(u.email).toLowerCase().includes(searchQuery.toLowerCase()));

  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>;

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <div className="relative flex-1"><Search className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" /><Input placeholder={language === 'en' ? 'Search users...' : 'ব্যবহারকারী খুঁজুন...'} value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="pl-10" /></div>
        <Dialog><DialogTrigger asChild><Button size="sm" className="gap-1"><Plus className="h-4 w-4" /><span className="hidden sm:inline">{language === 'en' ? 'Add User' : 'ব্যবহারকারী যোগ'}</span></Button></DialogTrigger><DialogContent><DialogHeader><DialogTitle>{language === 'en' ? 'Add New User' : 'নতুন ব্যবহারকারী'}</DialogTitle></DialogHeader><AddUserForm onUserAdded={fetchUsers} /></DialogContent></Dialog>
      </div>
      <Card><CardContent className="p-0"><div className="overflow-x-auto"><Table><TableHeader><TableRow><TableHead>{language === 'en' ? 'Name' : 'নাম'}</TableHead><TableHead className="hidden sm:table-cell">{language === 'en' ? 'Email' : 'ইমেইল'}</TableHead><TableHead>{language === 'en' ? 'Role' : 'ভূমিকা'}</TableHead><TableHead className="hidden md:table-cell">{language === 'en' ? 'Status' : 'স্ট্যাটাস'}</TableHead><TableHead>{language === 'en' ? 'Actions' : 'কাজ'}</TableHead></TableRow></TableHeader>
        <TableBody>{filtered.map((user) => (
          <TableRow key={String(user.id)}><TableCell><div className="flex items-center gap-2"><div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10 text-xs font-bold text-primary">{String(user.name).charAt(0).toUpperCase()}</div><div><p className="text-sm font-medium">{String(user.name)}</p><p className="text-xs text-muted-foreground sm:hidden">{String(user.email)}</p></div></div></TableCell><TableCell className="hidden text-sm sm:table-cell">{String(user.email)}</TableCell><TableCell><Badge variant="outline" className="text-[10px]">{String(user.roles || 'general')}</Badge></TableCell><TableCell className="hidden md:table-cell"><Badge className={`text-[10px] ${user.isActive ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400'}`}>{user.isActive ? (language === 'en' ? 'Active' : 'সক্রিয়') : (language === 'en' ? 'Inactive' : 'নিষ্ক্রিয়')}</Badge></TableCell><TableCell><div className="flex items-center gap-1"><Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleToggleActive(String(user.id), !!user.isActive)}>{user.isActive ? <Ban className="h-3.5 w-3.5 text-amber-500" /> : <CheckCircle className="h-3.5 w-3.5 text-emerald-500" />}</Button><AlertDialog><AlertDialogTrigger asChild><Button variant="ghost" size="icon" className="h-7 w-7"><Trash2 className="h-3.5 w-3.5 text-destructive" /></Button></AlertDialogTrigger><AlertDialogContent><AlertDialogHeader><AlertDialogTitle>{language === 'en' ? 'Delete User?' : 'ব্যবহারকারী মুছবেন?'}</AlertDialogTitle><AlertDialogDescription>{language === 'en' ? `Delete ${String(user.name)}'s account permanently?` : `${String(user.name)}-এর অ্যাকাউন্ট স্থায়ীভাবে মুছবেন?`}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>{language === 'en' ? 'Cancel' : 'বাতিল'}</AlertDialogCancel><AlertDialogAction onClick={() => handleDelete(String(user.id))} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">{language === 'en' ? 'Delete' : 'মুছুন'}</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog></div></TableCell></TableRow>
        ))}{filtered.length === 0 && <TableRow><TableCell colSpan={5} className="py-8 text-center text-sm text-muted-foreground">{language === 'en' ? 'No users found' : 'কোনো ব্যবহারকারী নেই'}</TableCell></TableRow>}</TableBody></Table></div></CardContent></Card>
    </div>
  );
}

function AddUserForm({ onUserAdded }: { onUserAdded: () => void }) {
  const { language, adminToken } = useAppStore();
  const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [phone, setPhone] = useState(''); const [password, setPassword] = useState(''); const [roles, setRoles] = useState('general'); const [isLoading, setIsLoading] = useState(false);
  const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setIsLoading(true); try { const res = await adminFetch('/api/admin/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, email, phone, password, roles }) }, adminToken); const data = await safeJsonParse<Record<string, unknown>>(res); if (data?.success) { onUserAdded(); setName(''); setEmail(''); setPhone(''); setPassword(''); setRoles('general'); } } catch (err) { console.error('Failed:', err); } finally { setIsLoading(false); } };
  return (<form onSubmit={handleSubmit} className="space-y-3"><div className="space-y-1"><Label className="text-xs">{language === 'en' ? 'Name' : 'নাম'}</Label><Input value={name} onChange={(e) => setName(e.target.value)} required /></div><div className="space-y-1"><Label className="text-xs">{language === 'en' ? 'Email' : 'ইমেইল'}</Label><Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required /></div><div className="space-y-1"><Label className="text-xs">{language === 'en' ? 'Phone' : 'ফোন'}</Label><Input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} /></div><div className="space-y-1"><Label className="text-xs">{language === 'en' ? 'Password' : 'পাসওয়ার্ড'}</Label><Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required /></div><div className="space-y-1"><Label className="text-xs">{language === 'en' ? 'Role' : 'ভূমিকা'}</Label><select value={roles} onChange={(e) => setRoles(e.target.value)} className="w-full rounded-md border bg-background px-3 py-2 text-sm"><option value="general">General</option><option value="student">Student</option><option value="houseOwner">House Owner</option><option value="shopOwner">Shop Owner</option><option value="admin">Admin</option></select></div><Button type="submit" className="w-full" disabled={isLoading}>{isLoading ? (language === 'en' ? 'Creating...' : 'তৈরি হচ্ছে...') : (language === 'en' ? 'Create User' : 'ব্যবহারকারী তৈরি')}</Button></form>);
}

// ============ ADMIN LISTINGS ============
function AdminListings({ type }: { type: 'houses' | 'shops' | 'products' }) {
  const { language, adminToken } = useAppStore();
  const [items, setItems] = useState<Record<string, unknown>[]>([]); const [loading, setLoading] = useState(true); const [searchQuery, setSearchQuery] = useState('');
  const fetchItems = useCallback(async () => { try { const res = await adminFetch(`/api/admin/listings?type=${type}`, {}, adminToken); const data = await safeJsonParse<Record<string, unknown>>(res); if (res.status === 401) { useAppStore.getState().adminLogout(); return; } if (data?.success) setItems(data.items); } catch (err) { console.error('Failed:', err); } finally { setLoading(false); } }, [type, adminToken]);
  useEffect(() => { fetchItems(); }, [fetchItems]);
  const handleToggleAvailable = async (id: string, current: boolean) => { try { const res = await adminFetch('/api/admin/listings', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, type, isAvailable: !current }) }, adminToken); const data = await safeJsonParse<Record<string, unknown>>(res); if (data?.success) fetchItems(); } catch (err) { console.error('Failed:', err); } };
  const handleDelete = async (id: string) => { try { const res = await adminFetch('/api/admin/listings', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, type }) }, adminToken); const data = await safeJsonParse<Record<string, unknown>>(res); if (data?.success) fetchItems(); } catch (err) { console.error('Failed:', err); } };
  const filtered = items.filter((item) => String(item.title).toLowerCase().includes(searchQuery.toLowerCase()));
  const Icon = type === 'houses' ? Building2 : type === 'shops' ? Store : ShoppingBag;
  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>;
  return (<div className="space-y-4"><div className="relative"><Search className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" /><Input placeholder={language === 'en' ? 'Search...' : 'খুঁজুন...'} value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="pl-10" /></div><div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">{filtered.map((item) => (<Card key={String(item.id)} className="overflow-hidden transition-all hover:shadow-lg hover:-translate-y-0.5"><div className="h-28 bg-gradient-to-br from-primary/10 to-primary/5 flex items-center justify-center"><Icon className="h-10 w-10 text-primary/30" strokeWidth={1.5} /></div><CardContent className="p-3"><h3 className="truncate text-sm font-semibold">{String(item.title)}</h3><p className="mt-1 text-xs text-muted-foreground line-clamp-2">{String(item.description || '').slice(0, 80)}</p><div className="mt-2 flex items-center justify-between"><span className="text-sm font-bold text-primary">৳{Number(item.price).toLocaleString()}{type !== 'products' ? '/mo' : ''}</span><Badge className={`text-[10px] ${item.isAvailable ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400'}`}>{item.isAvailable ? (language === 'en' ? 'Active' : 'সক্রিয়') : (language === 'en' ? 'Inactive' : 'নিষ্ক্রিয়')}</Badge></div><div className="mt-3 flex items-center gap-2"><Button variant="outline" size="sm" className="flex-1 text-xs" onClick={() => handleToggleAvailable(String(item.id), !!item.isAvailable)}>{item.isAvailable ? (language === 'en' ? 'Suspend' : 'স্থগিত') : (language === 'en' ? 'Approve' : 'অনুমোদন')}</Button><AlertDialog><AlertDialogTrigger asChild><Button variant="outline" size="sm" className="text-xs text-destructive"><Trash2 className="h-3.5 w-3.5" /></Button></AlertDialogTrigger><AlertDialogContent><AlertDialogHeader><AlertDialogTitle>{language === 'en' ? 'Delete?' : 'মুছবেন?'}</AlertDialogTitle><AlertDialogDescription>{language === 'en' ? `Delete "${String(item.title)}"?` : `"${String(item.title)}" মুছবেন?`}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>{language === 'en' ? 'Cancel' : 'বাতিল'}</AlertDialogCancel><AlertDialogAction onClick={() => handleDelete(String(item.id))} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">{language === 'en' ? 'Delete' : 'মুছুন'}</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog></div></CardContent></Card>))}{filtered.length === 0 && <div className="col-span-full py-12 text-center text-sm text-muted-foreground">{language === 'en' ? 'No listings found' : 'কোনো তালিকা নেই'}</div>}</div></div>);
}

// ============ ADMIN ORDERS ============
function AdminOrders() {
  const { language, adminToken } = useAppStore();
  const [orders, setOrders] = useState<Record<string, unknown>[]>([]); const [loading, setLoading] = useState(true); const [filterStatus, setFilterStatus] = useState('all');
  const fetchOrders = useCallback(async () => { try { const res = await adminFetch('/api/admin/orders', {}, adminToken); const data = await safeJsonParse<Record<string, unknown>>(res); if (res.status === 401) { useAppStore.getState().adminLogout(); return; } if (data?.success) setOrders(data.orders); } catch (err) { console.error('Failed:', err); } finally { setLoading(false); } }, [adminToken]);
  useEffect(() => { fetchOrders(); }, [fetchOrders]);
  const handleUpdateStatus = async (orderId: string, status: string) => { try { const res = await adminFetch('/api/admin/orders', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ orderId, status }) }, adminToken); const data = await safeJsonParse<Record<string, unknown>>(res); if (data?.success) fetchOrders(); } catch (err) { console.error('Failed:', err); } };
  const filtered = filterStatus === 'all' ? orders : orders.filter((o) => o.status === filterStatus);
  const statusColors: Record<string, string> = { pending: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400', confirmed: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400', shipped: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400', delivered: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400', cancelled: 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400' };
  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>;
  return (<div className="space-y-4"><div className="flex gap-2 overflow-x-auto pb-1">{['all', 'pending', 'confirmed', 'shipped', 'delivered', 'cancelled'].map((s) => (<Button key={s} variant={filterStatus === s ? 'default' : 'outline'} size="sm" className="shrink-0 text-xs" onClick={() => setFilterStatus(s)}>{s === 'all' ? (language === 'en' ? 'All' : 'সব') : s.charAt(0).toUpperCase() + s.slice(1)}</Button>))}</div><div className="grid gap-3 sm:grid-cols-2">{filtered.map((order) => (<Card key={String(order.id)} className="transition-all hover:shadow-md"><CardContent className="p-4"><div className="flex items-start justify-between"><div><p className="text-xs font-mono text-muted-foreground">{String(order.id).slice(0, 12)}...</p><p className="mt-1 text-sm font-semibold">৳{Number(order.totalAmount).toLocaleString()}</p><p className="text-xs text-muted-foreground">{String(order.address || '').slice(0, 40)}</p></div><Badge className={`text-[10px] ${statusColors[String(order.status)] || ''}`}>{String(order.status)}</Badge></div><Separator className="my-3" /><div className="flex items-center gap-2">{order.status === 'pending' && <><Button size="sm" variant="outline" className="flex-1 text-xs text-emerald-600" onClick={() => handleUpdateStatus(String(order.id), 'confirmed')}><CheckCircle className="mr-1 h-3 w-3" />{language === 'en' ? 'Approve' : 'অনুমোদন'}</Button><Button size="sm" variant="outline" className="flex-1 text-xs text-red-600" onClick={() => handleUpdateStatus(String(order.id), 'cancelled')}><XCircle className="mr-1 h-3 w-3" />{language === 'en' ? 'Reject' : 'প্রত্যাখ্যান'}</Button></>}{order.status === 'confirmed' && <Button size="sm" variant="outline" className="w-full text-xs" onClick={() => handleUpdateStatus(String(order.id), 'shipped')}><Package className="mr-1 h-3 w-3" />{language === 'en' ? 'Ship' : 'শিপ'}</Button>}{order.status === 'shipped' && <Button size="sm" variant="outline" className="w-full text-xs text-emerald-600" onClick={() => handleUpdateStatus(String(order.id), 'delivered')}><CheckCircle className="mr-1 h-3 w-3" />{language === 'en' ? 'Delivered' : 'ডেলিভারড'}</Button>}{(order.status === 'delivered' || order.status === 'cancelled') && <span className="text-xs text-muted-foreground">{language === 'en' ? 'Completed' : 'সম্পন্ন'}</span>}</div></CardContent></Card>))}{filtered.length === 0 && <div className="col-span-full py-12 text-center text-sm text-muted-foreground">{language === 'en' ? 'No orders' : 'কোনো অর্ডার নেই'}</div>}</div></div>);
}

// ============ ADMIN MCQ ============
const MCQ_CLASSES = [
  { id: 'class6-8', label: 'Class 6-8', labelBn: 'শ্রেণি ৬-৮' },
  { id: 'class9-10', label: 'Class 9-10', labelBn: 'শ্রেণি ৯-১০' },
  { id: 'ssc', label: 'SSC', labelBn: 'এসএসসি' },
  { id: 'hsc', label: 'HSC', labelBn: 'এইচএসসি' },
  { id: 'admission', label: 'Admission', labelBn: 'ভর্তি' },
  { id: 'gk', label: 'General Knowledge', labelBn: 'সাধারণ জ্ঞান' },
  { id: 'bcs', label: 'BCS', labelBn: 'বিসিএস' },
];

const MCQ_TOPICS: Record<string, { id: string; label: string; labelBn: string }[]> = {
  'class6-8': [
    { id: 'math', label: 'Mathematics', labelBn: 'গণিত' },
    { id: 'science', label: 'Science', labelBn: 'বিজ্ঞান' },
    { id: 'bangla', label: 'Bangla', labelBn: 'বাংলা' },
    { id: 'english', label: 'English', labelBn: 'ইংরেজি' },
  ],
  'class9-10': [
    { id: 'math', label: 'Mathematics', labelBn: 'গণিত' },
    { id: 'physics', label: 'Physics', labelBn: 'পদার্থবিজ্ঞান' },
    { id: 'chemistry', label: 'Chemistry', labelBn: 'রসায়ন' },
    { id: 'biology', label: 'Biology', labelBn: 'জীববিজ্ঞান' },
    { id: 'bangla', label: 'Bangla', labelBn: 'বাংলা' },
    { id: 'english', label: 'English', labelBn: 'ইংরেজি' },
  ],
  'ssc': [
    { id: 'math', label: 'Mathematics', labelBn: 'গণিত' },
    { id: 'physics', label: 'Physics', labelBn: 'পদার্থবিজ্ঞান' },
    { id: 'chemistry', label: 'Chemistry', labelBn: 'রসায়ন' },
    { id: 'biology', label: 'Biology', labelBn: 'জীববিজ্ঞান' },
    { id: 'ict', label: 'ICT', labelBn: 'আইসিটি' },
    { id: 'bangla', label: 'Bangla', labelBn: 'বাংলা' },
  ],
  'hsc': [
    { id: 'math', label: 'Higher Math', labelBn: 'উচ্চতর গণিত' },
    { id: 'physics', label: 'Physics', labelBn: 'পদার্থবিজ্ঞান' },
    { id: 'chemistry', label: 'Chemistry', labelBn: 'রসায়ন' },
    { id: 'biology', label: 'Biology', labelBn: 'জীববিজ্ঞান' },
    { id: 'ict', label: 'ICT', labelBn: 'আইসিটি' },
    { id: 'english', label: 'English', labelBn: 'ইংরেজি' },
  ],
  'admission': [
    { id: 'math', label: 'Mathematics', labelBn: 'গণিত' },
    { id: 'physics', label: 'Physics', labelBn: 'পদার্থবিজ্ঞান' },
    { id: 'chemistry', label: 'Chemistry', labelBn: 'রসায়ন' },
    { id: 'biology', label: 'Biology', labelBn: 'জীববিজ্ঞান' },
    { id: 'gk', label: 'General Knowledge', labelBn: 'সাধারণ জ্ঞান' },
    { id: 'english', label: 'English', labelBn: 'ইংরেজি' },
  ],
  'gk': [
    { id: 'bangladesh', label: 'Bangladesh', labelBn: 'বাংলাদেশ' },
    { id: 'international', label: 'International', labelBn: 'আন্তর্জাতিক' },
    { id: 'science', label: 'Science', labelBn: 'বিজ্ঞান' },
    { id: 'sports', label: 'Sports', labelBn: 'খেলাধুলা' },
    { id: 'history', label: 'History', labelBn: 'ইতিহাস' },
  ],
  'bcs': [
    { id: 'bangla', label: 'Bangla', labelBn: 'বাংলা' },
    { id: 'english', label: 'English', labelBn: 'ইংরেজি' },
    { id: 'math', label: 'Mathematics', labelBn: 'গণিত' },
    { id: 'gk', label: 'General Knowledge', labelBn: 'সাধারণ জ্ঞান' },
    { id: 'science', label: 'Science', labelBn: 'বিজ্ঞান' },
  ],
};

function AdminMCQ() {
  const { language, adminToken } = useAppStore();
  const [questions, setQuestions] = useState<Record<string, unknown>[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterClass, setFilterClass] = useState<string>('all');
  const [filterTopic, setFilterTopic] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');

  const fetchQuestions = useCallback(async () => {
    try {
      const res = await adminFetch('/api/admin/mcq', {}, adminToken);
      if (res.status === 401) { useAppStore.getState().adminLogout(); return; }
      const data = await safeJsonParse<Record<string, unknown>>(res);
      if (data?.success) setQuestions((data?.questions as Record<string, unknown>[]) || []);
    } catch (err) { console.error('Failed:', err); } finally { setLoading(false); }
  }, [adminToken]);

  useEffect(() => { fetchQuestions(); }, [fetchQuestions]);

  const handleDelete = async (id: string) => {
    try {
      const res = await adminFetch('/api/admin/mcq', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id }) }, adminToken);
      const data = await safeJsonParse<Record<string, unknown>>(res);
      if (data?.success) fetchQuestions();
    } catch (err) { console.error('Failed:', err); }
  };

  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>;

  // Filter questions by class and topic
  const filteredQuestions = questions.filter((q) => {
    const qClass = String(q.class || q.category || 'GK').toLowerCase();
    const qTopic = String(q.topic || 'General').toLowerCase();
    const qCategory = String(q.category || 'gk').toLowerCase();

    if (filterClass !== 'all') {
      const classMatch = qClass === filterClass.toLowerCase() || qCategory === filterClass.toLowerCase();
      if (!classMatch) return false;
    }
    if (filterTopic !== 'all') {
      const topicMatch = qTopic === filterTopic.toLowerCase();
      if (!topicMatch) return false;
    }
    if (searchQuery) {
      const sq = searchQuery.toLowerCase();
      if (!String(q.question).toLowerCase().includes(sq) && !String(q.topic).toLowerCase().includes(sq)) return false;
    }
    return true;
  });

  // Get topics for selected class
  const availableTopics = filterClass !== 'all' ? (MCQ_TOPICS[filterClass] || []) : [];

  // Stats by class
  const classStats = MCQ_CLASSES.map((cls) => ({
    ...cls,
    count: questions.filter((q) => {
      const qClass = String(q.class || q.category || 'GK').toLowerCase();
      const qCategory = String(q.category || 'gk').toLowerCase();
      return qClass === cls.id.toLowerCase() || qCategory === cls.id.toLowerCase();
    }).length,
  }));

  return (
    <div className="space-y-4">
      {/* Class Stats */}
      <div className="grid grid-cols-4 sm:grid-cols-7 gap-2">
        {classStats.map((cls) => (
          <button
            key={cls.id}
            onClick={() => { setFilterClass(filterClass === cls.id ? 'all' : cls.id); setFilterTopic('all'); }}
            className={`flex flex-col items-center gap-1 rounded-xl border p-2.5 text-center transition-all ${filterClass === cls.id ? 'border-primary bg-primary/10 shadow-sm' : 'border-border hover:border-primary/30 hover:bg-accent/50'}`}
          >
            <span className="text-xs font-semibold">{language === 'en' ? cls.label : cls.labelBn}</span>
            <span className="text-lg font-bold text-primary">{cls.count}</span>
          </button>
        ))}
      </div>

      {/* Topic Filter */}
      {availableTopics.length > 0 && (
        <div className="flex flex-wrap gap-1.5">
          <button
            onClick={() => setFilterTopic('all')}
            className={`rounded-full border px-3 py-1 text-[11px] font-medium transition-colors ${filterTopic === 'all' ? 'border-primary bg-primary text-primary-foreground' : 'border-border text-muted-foreground hover:border-primary/30'}`}
          >
            {language === 'en' ? 'All Topics' : 'সব বিষয়'}
          </button>
          {availableTopics.map((topic) => (
            <button
              key={topic.id}
              onClick={() => setFilterTopic(filterTopic === topic.id ? 'all' : topic.id)}
              className={`rounded-full border px-3 py-1 text-[11px] font-medium transition-colors ${filterTopic === topic.id ? 'border-primary bg-primary text-primary-foreground' : 'border-border text-muted-foreground hover:border-primary/30'}`}
            >
              {language === 'en' ? topic.label : topic.labelBn}
            </button>
          ))}
        </div>
      )}

      {/* Header with search and add */}
      <div className="flex items-center gap-3">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input placeholder={language === 'en' ? 'Search questions...' : 'প্রশ্ন খুঁজুন...'} value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="pl-9 h-9 text-sm" />
        </div>
        <Dialog>
          <DialogTrigger asChild>
            <Button size="sm" className="gap-1 shrink-0"><Plus className="h-4 w-4" />{language === 'en' ? 'Add' : 'যোগ'}</Button>
          </DialogTrigger>
          <DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
            <DialogHeader><DialogTitle>{language === 'en' ? 'New MCQ Question' : 'নতুন MCQ প্রশ্ন'}</DialogTitle></DialogHeader>
            <AddMCQForm onQuestionAdded={fetchQuestions} />
          </DialogContent>
        </Dialog>
      </div>

      {/* Results count */}
      <p className="text-xs text-muted-foreground">
        {filteredQuestions.length} {language === 'en' ? 'questions' : 'প্রশ্ন'}
        {filterClass !== 'all' && ` · ${MCQ_CLASSES.find(c => c.id === filterClass)?.label || filterClass}`}
        {filterTopic !== 'all' && ` · ${availableTopics.find(t => t.id === filterTopic)?.label || filterTopic}`}
      </p>

      {/* Questions List */}
      <div className="max-h-[calc(100vh-420px)] overflow-y-auto space-y-2">
        {filteredQuestions.length === 0 ? (
          <Card><CardContent className="flex flex-col items-center py-12 text-center">
            <GraduationCap className="h-10 w-10 text-muted-foreground/40" />
            <p className="mt-3 text-sm text-muted-foreground">{language === 'en' ? 'No questions found' : 'কোনো প্রশ্ন পাওয়া যায়নি'}</p>
          </CardContent></Card>
        ) : filteredQuestions.map((q, i) => {
          const qClass = String(q.class || q.category || 'GK');
          const qTopic = String(q.topic || 'General');
          const qDifficulty = String(q.difficulty || 'medium');
          return (
            <Card key={String(q.id)} className="transition-shadow hover:shadow-md">
              <CardContent className="p-3">
                <div className="flex items-start justify-between gap-2">
                  <div className="flex-1 min-w-0">
                    <div className="flex flex-wrap items-center gap-1.5">
                      <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary/10 text-[10px] font-bold text-primary">{i + 1}</span>
                      <Badge variant="outline" className="text-[9px]">{qClass}</Badge>
                      <Badge variant="secondary" className="text-[9px]">{qTopic}</Badge>
                      <Badge variant="outline" className={`text-[9px] ${qDifficulty === 'easy' ? 'border-green-300 text-green-600' : qDifficulty === 'hard' ? 'border-red-300 text-red-600' : 'border-amber-300 text-amber-600'}`}>{qDifficulty}</Badge>
                    </div>
                    <p className="mt-1.5 text-sm font-medium leading-snug">{String(q.question)}</p>
                    <div className="mt-1.5 grid grid-cols-2 gap-1 text-[11px]">
                      {['A', 'B', 'C', 'D'].map((opt) => (
                        <span key={opt} className={`rounded px-2 py-0.5 ${String(q.correctAnswer) === opt ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400 font-medium' : 'bg-accent'}`}>
                          {opt}. {String(q[`option${opt}`] || '')}
                        </span>
                      ))}
                    </div>
                  </div>
                  <AlertDialog>
                    <AlertDialogTrigger asChild><Button variant="ghost" size="icon" className="h-7 w-7 shrink-0"><Trash2 className="h-3.5 w-3.5 text-destructive" /></Button></AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader><AlertDialogTitle>{language === 'en' ? 'Delete?' : 'মুছবেন?'}</AlertDialogTitle></AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel>{language === 'en' ? 'Cancel' : 'বাতিল'}</AlertDialogCancel>
                        <AlertDialogAction onClick={() => handleDelete(String(q.id))} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">{language === 'en' ? 'Delete' : 'মুছুন'}</AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

function AddMCQForm({ onQuestionAdded }: { onQuestionAdded: () => void }) {
  const { language, adminToken } = useAppStore();
  const [form, setForm] = useState({ question: '', optionA: '', optionB: '', optionC: '', optionD: '', correctAnswer: 'A', category: 'gk', difficulty: 'medium', explanation: '', class: 'gk', topic: 'General' });
  const [isLoading, setIsLoading] = useState(false);

  const selectedClass = form.class;
  const topicsForClass = MCQ_TOPICS[selectedClass] || [];
  const categoryId = selectedClass || 'gk';

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault(); setIsLoading(true);
    try {
      const res = await adminFetch('/api/admin/mcq', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...form, category: categoryId }) }, adminToken);
      const data = await safeJsonParse<Record<string, unknown>>(res);
      if (data?.success) { onQuestionAdded(); setForm({ question: '', optionA: '', optionB: '', optionC: '', optionD: '', correctAnswer: 'A', category: 'gk', difficulty: 'medium', explanation: '', class: 'gk', topic: 'General' }); }
    } catch (err) { console.error('Failed:', err); } finally { setIsLoading(false); }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-3">
      {/* Class Selection */}
      <div className="space-y-1">
        <Label className="text-xs font-medium">{language === 'en' ? 'Class / Category' : 'শ্রেণি / বিভাগ'}</Label>
        <select value={form.class} onChange={(e) => setForm({ ...form, class: e.target.value, topic: 'General' })} className="w-full rounded-md border bg-background px-3 py-2 text-sm">
          {MCQ_CLASSES.map((cls) => <option key={cls.id} value={cls.id}>{language === 'en' ? cls.label : cls.labelBn}</option>)}
        </select>
      </div>

      {/* Topic Selection */}
      <div className="space-y-1">
        <Label className="text-xs font-medium">{language === 'en' ? 'Topic / Subject' : 'বিষয় / বিষয়'}</Label>
        <select value={form.topic} onChange={(e) => setForm({ ...form, topic: e.target.value })} className="w-full rounded-md border bg-background px-3 py-2 text-sm">
          <option value="General">{language === 'en' ? 'General' : 'সাধারণ'}</option>
          {topicsForClass.map((topic) => <option key={topic.id} value={topic.label}>{language === 'en' ? topic.label : topic.labelBn}</option>)}
        </select>
      </div>

      {/* Question */}
      <div className="space-y-1">
        <Label className="text-xs font-medium">{language === 'en' ? 'Question' : 'প্রশ্ন'}</Label>
        <Textarea value={form.question} onChange={(e) => setForm({ ...form, question: e.target.value })} required className="min-h-[60px]" />
      </div>

      {/* Options */}
      <div className="grid grid-cols-2 gap-2">
        {['A', 'B', 'C', 'D'].map((opt) => (
          <div key={opt} className="space-y-1">
            <Label className="text-xs">Option {opt}</Label>
            <Input value={form[`option${opt}` as keyof typeof form] as string} onChange={(e) => setForm({ ...form, [`option${opt}`]: e.target.value })} required />
          </div>
        ))}
      </div>

      {/* Correct Answer, Difficulty */}
      <div className="grid grid-cols-2 gap-2">
        <div className="space-y-1">
          <Label className="text-xs">{language === 'en' ? 'Correct Answer' : 'সঠিক উত্তর'}</Label>
          <select value={form.correctAnswer} onChange={(e) => setForm({ ...form, correctAnswer: e.target.value })} className="w-full rounded-md border bg-background px-3 py-2 text-sm">
            <option value="A">A</option><option value="B">B</option><option value="C">C</option><option value="D">D</option>
          </select>
        </div>
        <div className="space-y-1">
          <Label className="text-xs">{language === 'en' ? 'Difficulty' : 'কঠিনতা'}</Label>
          <select value={form.difficulty} onChange={(e) => setForm({ ...form, difficulty: e.target.value })} className="w-full rounded-md border bg-background px-3 py-2 text-sm">
            <option value="easy">{language === 'en' ? 'Easy' : 'সহজ'}</option>
            <option value="medium">{language === 'en' ? 'Medium' : 'মাঝারি'}</option>
            <option value="hard">{language === 'en' ? 'Hard' : 'কঠিন'}</option>
          </select>
        </div>
      </div>

      {/* Explanation */}
      <div className="space-y-1">
        <Label className="text-xs">{language === 'en' ? 'Explanation (optional)' : 'ব্যাখ্যা (ঐচ্ছিক)'}</Label>
        <Textarea value={form.explanation} onChange={(e) => setForm({ ...form, explanation: e.target.value })} className="min-h-[40px]" />
      </div>

      <Button type="submit" className="w-full" disabled={isLoading}>{isLoading ? '...' : (language === 'en' ? 'Save Question' : 'প্রশ্ন সংরক্ষণ')}</Button>
    </form>
  );
}

// ============ ADMIN COMMUNITY ============
function AdminCommunity() {
  const { language, adminToken } = useAppStore();
  const [posts, setPosts] = useState<Record<string, unknown>[]>([]); const [loading, setLoading] = useState(true);
  const fetchPosts = useCallback(async () => { try { const res = await adminFetch('/api/admin/community', {}, adminToken); const data = await safeJsonParse<Record<string, unknown>>(res); if (res.status === 401) { useAppStore.getState().adminLogout(); return; } if (data?.success) setPosts(data.posts); } catch (err) { console.error('Failed:', err); } finally { setLoading(false); } }, [adminToken]);
  useEffect(() => { fetchPosts(); }, [fetchPosts]);
  const handleDelete = async (id: string) => { try { const res = await adminFetch('/api/admin/community', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id }) }, adminToken); const data = await safeJsonParse<Record<string, unknown>>(res); if (data?.success) fetchPosts(); } catch (err) { console.error('Failed:', err); } };
  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>;
  return (<div className="space-y-3">{posts.map((post) => (<Card key={String(post.id)} className="transition-shadow hover:shadow-md"><CardContent className="p-4"><div className="flex items-start justify-between gap-3"><div className="flex-1"><div className="flex items-center gap-2"><Badge variant="outline" className="text-[10px]">{String(post.postType)}</Badge><span className="text-xs text-muted-foreground">{String(post.likes)} {language === 'en' ? 'likes' : 'লাইক'}</span></div><h3 className="mt-1 text-sm font-semibold">{String(post.title)}</h3><p className="mt-1 text-xs text-muted-foreground line-clamp-2">{String(post.content)}</p></div><AlertDialog><AlertDialogTrigger asChild><Button variant="ghost" size="icon" className="h-7 w-7 shrink-0"><Trash2 className="h-3.5 w-3.5 text-destructive" /></Button></AlertDialogTrigger><AlertDialogContent><AlertDialogHeader><AlertDialogTitle>{language === 'en' ? 'Delete?' : 'মুছবেন?'}</AlertDialogTitle></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>{language === 'en' ? 'Cancel' : 'বাতিল'}</AlertDialogCancel><AlertDialogAction onClick={() => handleDelete(String(post.id))} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">{language === 'en' ? 'Delete' : 'মুছুন'}</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog></div></CardContent></Card>))}{posts.length === 0 && <div className="py-12 text-center text-sm text-muted-foreground">{language === 'en' ? 'No posts' : 'কোনো পোস্ট নেই'}</div>}</div>);
}

// ============ APP CUSTOMIZER (Super Admin Only) ============
function ColorPicker({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
  return (
    <div className="flex items-center gap-3">
      <div className="relative">
        <input
          type="color"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className="h-10 w-10 cursor-pointer rounded-lg border-2 border-border p-0.5"
        />
      </div>
      <div className="flex-1">
        <Label className="text-xs font-medium">{label}</Label>
        <div className="flex items-center gap-2 mt-1">
          <Input
            value={value}
            onChange={(e) => onChange(e.target.value)}
            className="h-8 text-xs font-mono"
            placeholder="#000000"
          />
          <div className="h-8 w-8 rounded-md border" style={{ backgroundColor: value }} />
        </div>
      </div>
    </div>
  );
}

function AppCustomizer() {
  const { language, adminUser } = useAppStore();
  const [config, setConfig] = useState<AppCustomizations>(() => {
    try {
      const stored = localStorage.getItem('needyfy_customizations');
      if (stored) {
        const parsed = JSON.parse(stored);
        return { ...defaultCustomizations, ...parsed };
      }
    } catch { /* ignore */ }
    return defaultCustomizations;
  });
  const [livePreview, setLivePreview] = useState(false);
  const [saved, setSaved] = useState(false);
  const [activeSection, setActiveSection] = useState('theme');

  const applyCustomizations = (c: AppCustomizations) => {
    const root = document.documentElement;
    // Theme & Colors
    if (c.primaryColor) {
      root.style.setProperty('--primary', c.primaryColor);
      root.style.setProperty('--ring', c.primaryColor);
      root.style.setProperty('--sidebar-primary', c.primaryColor);
      root.style.setProperty('--sidebar-ring', c.primaryColor);
    }
    if (c.accentColor) root.style.setProperty('--accent', c.accentColor);
    if (c.buttonColor) root.style.setProperty('--button-color', c.buttonColor);
    if (c.cardBgColor) root.style.setProperty('--card-bg', c.cardBgColor);
    if (c.sidebarColor) root.style.setProperty('--sidebar-bg', c.sidebarColor);
    if (c.headerColor) root.style.setProperty('--header-bg', c.headerColor);
    if (c.gradientStart) root.style.setProperty('--gradient-start', c.gradientStart);
    if (c.gradientEnd) root.style.setProperty('--gradient-end', c.gradientEnd);
    // Font Settings
    if (c.fontFamily) root.style.setProperty('--font-family', c.fontFamily);
    if (c.headingFontFamily) root.style.setProperty('--heading-font-family', c.headingFontFamily);
    if (c.baseFontSize) root.style.setProperty('--base-font-size', c.baseFontSize);
    if (c.headingFontWeight) root.style.setProperty('--heading-font-weight', c.headingFontWeight);
    root.style.fontFamily = c.fontFamily || 'Inter';
    // Text Colors
    if (c.textColor) root.style.setProperty('--text-color', c.textColor);
    if (c.mutedTextColor) root.style.setProperty('--muted-text-color', c.mutedTextColor);
    if (c.headingColor) root.style.setProperty('--heading-color', c.headingColor);
    if (c.linkColor) root.style.setProperty('--link-color', c.linkColor);
    // Dark Mode Colors
    if (c.darkBgColor) root.style.setProperty('--dark-bg-color', c.darkBgColor);
    if (c.darkCardColor) root.style.setProperty('--dark-card-color', c.darkCardColor);
    if (c.darkTextColor) root.style.setProperty('--dark-text-color', c.darkTextColor);
    if (c.darkAccentColor) root.style.setProperty('--dark-accent-color', c.darkAccentColor);
    // UI Effects - Shadow intensity
    const shadowMap: Record<string, string> = {
      none: '0 0 0 0 transparent',
      light: '0 1px 2px 0 rgba(0,0,0,0.05)',
      medium: '0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -2px rgba(0,0,0,0.1)',
      heavy: '0 10px 15px -3px rgba(0,0,0,0.15), 0 4px 6px -4px rgba(0,0,0,0.1)',
    };
    root.style.setProperty('--shadow-intensity', shadowMap[c.shadowIntensity] || shadowMap.medium);
    // Border radius
    const radiusMap: Record<string, string> = {
      'rounded-none': '0px', 'rounded-sm': '2px', 'rounded-md': '6px',
      'rounded-lg': '8px', 'rounded-xl': '12px', 'rounded-2xl': '16px',
    };
    if (c.buttonBorderRadius) root.style.setProperty('--button-radius', radiusMap[c.buttonBorderRadius] || '12px');
    if (c.cardBorderRadius) root.style.setProperty('--card-radius', radiusMap[c.cardBorderRadius] || '12px');
    if (c.inputBorderRadius) root.style.setProperty('--input-radius', radiusMap[c.inputBorderRadius] || '8px');
    // Animations
    root.style.setProperty('--animation-duration', c.enableAnimations ? '150ms' : '0ms');
    // Bottom Nav Colors
    if (c.bottomNavBgColor) root.style.setProperty('--bottom-nav-bg', c.bottomNavBgColor);
    if (c.bottomNavActiveColor) root.style.setProperty('--bottom-nav-active', c.bottomNavActiveColor);
    if (c.bottomNavInactiveColor) root.style.setProperty('--bottom-nav-inactive', c.bottomNavInactiveColor);
    // Sidebar
    if (c.sidebarWidth) root.style.setProperty('--sidebar-width', c.sidebarWidth);
    if (c.sidebarBgOpacity) root.style.setProperty('--sidebar-bg-opacity', c.sidebarBgOpacity + '%');
    // Notification
    if (c.notificationPosition) root.style.setProperty('--notification-position', c.notificationPosition);
    // Custom CSS
    let customStyleEl = document.getElementById('needyfy-custom-css');
    if (c.customCSS && c.customCSS.trim()) {
      if (!customStyleEl) {
        customStyleEl = document.createElement('style');
        customStyleEl.id = 'needyfy-custom-css';
        document.head.appendChild(customStyleEl);
      }
      customStyleEl.textContent = c.customCSS;
    } else if (customStyleEl) {
      customStyleEl.remove();
    }
  };

  // Apply CSS variables when livePreview is on
  useEffect(() => {
    if (livePreview) {
      applyCustomizations(config);
    }
  }, [config, livePreview]);

  const updateConfig = <K extends keyof AppCustomizations>(key: K, value: AppCustomizations[K]) => {
    setConfig(prev => ({ ...prev, [key]: value }));
  };

  const handleSave = () => {
    localStorage.setItem('needyfy_customizations', JSON.stringify(config));
    applyCustomizations(config);
    setSaved(true);
    setTimeout(() => setSaved(false), 3000);
  };

  const handleReset = () => {
    setConfig(defaultCustomizations);
    localStorage.removeItem('needyfy_customizations');
    // Reset CSS variables
    const root = document.documentElement;
    const propsToRemove = [
      '--primary', '--ring', '--sidebar-primary', '--sidebar-ring',
      '--accent', '--button-color', '--card-bg', '--sidebar-bg',
      '--header-bg', '--gradient-start', '--gradient-end',
      '--font-family', '--heading-font-family', '--base-font-size', '--heading-font-weight',
      '--text-color', '--muted-text-color', '--heading-color', '--link-color',
      '--dark-bg-color', '--dark-card-color', '--dark-text-color', '--dark-accent-color',
      '--shadow-intensity', '--button-radius', '--card-radius', '--input-radius',
      '--animation-duration', '--bottom-nav-bg', '--bottom-nav-active', '--bottom-nav-inactive',
      '--sidebar-width', '--sidebar-bg-opacity', '--notification-position',
    ];
    propsToRemove.forEach((prop) => root.style.removeProperty(prop));
    root.style.fontFamily = '';
    // Remove custom CSS
    const customStyleEl = document.getElementById('needyfy-custom-css');
    if (customStyleEl) customStyleEl.remove();
  };

  const handlePreview = () => {
    applyCustomizations(config);
  };

  if (!isSuperAdmin(adminUser?.role || '')) {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-4">
        <Shield className="h-16 w-16 text-muted-foreground/20" />
        <p className="text-sm text-muted-foreground">
          {language === 'en' ? 'Only Super Admin can access this section' : 'শুধুমাত্র সুপার অ্যাডমিন এই বিভাগে অ্যাক্সেস করতে পারেন'}
        </p>
      </div>
    );
  }

  const sections = [
    { id: 'theme', label: language === 'en' ? 'Theme & Colors' : 'থিম ও রং', icon: Palette },
    { id: 'branding', label: language === 'en' ? 'App Branding' : 'অ্যাপ ব্র্যান্ডিং', icon: Type },
    { id: 'hero', label: language === 'en' ? 'Hero Section' : 'হিরো সেকশন', icon: ImageIcon },
    { id: 'features', label: language === 'en' ? 'Feature Toggles' : 'ফিচার টগল', icon: ToggleLeft },
    { id: 'content', label: language === 'en' ? 'Text & Content' : 'টেক্সট ও কন্টেন্ট', icon: Paintbrush },
    { id: 'layout', label: language === 'en' ? 'Layout Settings' : 'লেআউট সেটিংস', icon: Layout },
    { id: 'typography', label: language === 'en' ? 'Typography' : 'টাইপোগ্রাফি', icon: Type },
    { id: 'dark-mode', label: language === 'en' ? 'Dark Mode' : 'ডার্ক মোড', icon: Moon },
    { id: 'effects', label: language === 'en' ? 'UI Effects' : 'UI ইফেক্ট', icon: Sparkles },
    { id: 'navigation', label: language === 'en' ? 'Navigation' : 'নেভিগেশন', icon: Navigation },
    { id: 'advanced', label: language === 'en' ? 'Advanced' : 'অ্যাডভান্সড', icon: Code },
  ];

  const borderRadiusOptions = [
    { value: 'rounded-none', label: 'None' },
    { value: 'rounded-sm', label: 'Small' },
    { value: 'rounded-md', label: 'Medium' },
    { value: 'rounded-lg', label: 'Large' },
    { value: 'rounded-xl', label: 'Extra Large' },
    { value: 'rounded-2xl', label: '2X Large' },
  ];

  const featureToggles: { key: keyof AppCustomizations; label: string; labelBn: string; icon: React.ElementType }[] = [
    { key: 'enableHouseRental', label: 'House Rental', labelBn: 'বাড়ি ভাড়া', icon: Building2 },
    { key: 'enableShopRental', label: 'Shop Rental', labelBn: 'দোকান ভাড়া', icon: Store },
    { key: 'enableMarketplace', label: 'Marketplace', labelBn: 'মার্কেটপ্লেস', icon: ShoppingBag },
    { key: 'enableMedicine', label: 'Medicine', labelBn: 'ওষুধ', icon: GraduationCap },
    { key: 'enableEducation', label: 'Education', labelBn: 'শিক্ষা', icon: GraduationCap },
    { key: 'enableCommunity', label: 'Community', labelBn: 'কমিউনিটি', icon: MessageSquare },
    { key: 'enableMCQ', label: 'MCQ Quiz', labelBn: 'MCQ কুইজ', icon: GraduationCap },
    { key: 'enableOrders', label: 'Orders', labelBn: 'অর্ডার', icon: Package },
    { key: 'enableMessages', label: 'Messages', labelBn: 'মেসেজ', icon: MessageSquare },
    { key: 'enableFavourites', label: 'Favourites', labelBn: 'পছন্দের', icon: Star },
  ];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h2 className="text-xl font-bold flex items-center gap-2">
            <Palette className="h-5 w-5 text-primary" />
            {language === 'en' ? 'Customize App' : 'অ্যাপ কাস্টমাইজ'}
          </h2>
          <p className="text-sm text-muted-foreground mt-1">
            {language === 'en'
              ? 'Customize every aspect of your application — colors, branding, features, and more'
              : 'আপনার অ্যাপ্লিকেশনের প্রতিটি দিক কাস্টমাইজ করুন — রং, ব্র্যান্ডিং, ফিচার এবং আরও অনেক কিছু'}
          </p>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          {/* Live Preview Toggle */}
          <div className="flex items-center gap-2 rounded-lg border px-3 py-1.5">
            <Monitor className="h-4 w-4 text-muted-foreground" />
            <Label className="text-xs font-medium cursor-pointer">
              {language === 'en' ? 'Live Preview' : 'লাইভ প্রিভিউ'}
            </Label>
            <Switch checked={livePreview} onCheckedChange={setLivePreview} />
          </div>
          <Button variant="outline" size="sm" className="gap-1.5 text-xs" onClick={handlePreview}>
            <Eye className="h-3.5 w-3.5" />
            {language === 'en' ? 'Preview' : 'প্রিভিউ'}
          </Button>
          <Button variant="outline" size="sm" className="gap-1.5 text-xs" onClick={handleReset}>
            <RotateCcw className="h-3.5 w-3.5" />
            {language === 'en' ? 'Reset' : 'রিসেট'}
          </Button>
          <Button size="sm" className="gap-1.5 text-xs bg-gradient-to-r from-orange-700 to-orange-500 shadow-md" onClick={handleSave}>
            {saved ? <CheckCircle className="h-3.5 w-3.5" /> : <Save className="h-3.5 w-3.5" />}
            {saved ? (language === 'en' ? 'Saved!' : 'সংরক্ষিত!') : (language === 'en' ? 'Save Changes' : 'পরিবর্তন সংরক্ষণ')}
          </Button>
        </div>
      </div>

      {/* Section Tabs */}
      <div className="flex gap-2 overflow-x-auto pb-1">
        {sections.map((s) => {
          const Icon = s.icon;
          const isActive = activeSection === s.id;
          return (
            <button
              key={s.id}
              onClick={() => setActiveSection(s.id)}
              className={`flex items-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium transition-all shrink-0 ${
                isActive
                  ? 'bg-gradient-to-r from-orange-600/10 to-orange-500/5 text-primary shadow-sm border border-primary/20'
                  : 'text-foreground/60 hover:bg-accent hover:text-foreground border border-transparent'
              }`}
            >
              <Icon className="h-4 w-4" />
              {s.label}
            </button>
          );
        })}
      </div>

      {/* ============ THEME & COLORS ============ */}
      {activeSection === 'theme' && (
        <div className="grid gap-4 sm:grid-cols-2">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Paintbrush className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Primary Colors' : 'প্রাথমিক রং'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <ColorPicker label={language === 'en' ? 'Primary Color' : 'প্রাথমিক রং'} value={config.primaryColor} onChange={(v) => updateConfig('primaryColor', v)} />
              <ColorPicker label={language === 'en' ? 'Accent Color' : 'অ্যাকসেন্ট রং'} value={config.accentColor} onChange={(v) => updateConfig('accentColor', v)} />
              <ColorPicker label={language === 'en' ? 'Button Color' : 'বাটন রং'} value={config.buttonColor} onChange={(v) => updateConfig('buttonColor', v)} />
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Layout className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Surface Colors' : 'সারফেস রং'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <ColorPicker label={language === 'en' ? 'Card Background' : 'কার্ড ব্যাকগ্রাউন্ড'} value={config.cardBgColor} onChange={(v) => updateConfig('cardBgColor', v)} />
              <ColorPicker label={language === 'en' ? 'Sidebar Background' : 'সাইডবার ব্যাকগ্রাউন্ড'} value={config.sidebarColor} onChange={(v) => updateConfig('sidebarColor', v)} />
              <ColorPicker label={language === 'en' ? 'Header Background' : 'হেডার ব্যাকগ্রাউন্ড'} value={config.headerColor} onChange={(v) => updateConfig('headerColor', v)} />
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Wand2 className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Gradient Colors' : 'গ্র্যাডিয়েন্ট রং'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <ColorPicker label={language === 'en' ? 'Gradient Start' : 'গ্র্যাডিয়েন্ট শুরু'} value={config.gradientStart} onChange={(v) => updateConfig('gradientStart', v)} />
              <ColorPicker label={language === 'en' ? 'Gradient End' : 'গ্র্যাডিয়েন্ট শেষ'} value={config.gradientEnd} onChange={(v) => updateConfig('gradientEnd', v)} />
              {/* Gradient Preview */}
              <div className="mt-2">
                <Label className="text-xs text-muted-foreground">{language === 'en' ? 'Preview' : 'প্রিভিউ'}</Label>
                <div
                  className="mt-1 h-12 rounded-xl"
                  style={{ background: `linear-gradient(to right, ${config.gradientStart}, ${config.gradientEnd})` }}
                />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Smartphone className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Border Radius' : 'বর্ডার রেডিয়াস'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <Select value={config.borderRadius} onValueChange={(v) => updateConfig('borderRadius', v)}>
                <SelectTrigger className="h-9">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {borderRadiusOptions.map((opt) => (
                    <SelectItem key={opt.value} value={opt.value}>{opt.label} ({opt.value})</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {/* Preview */}
              <div className="flex items-center gap-3 mt-2">
                <div className={`${config.borderRadius} bg-primary h-12 w-12`} />
                <div className={`${config.borderRadius} bg-accent h-12 w-12 border`} />
                <div className={`${config.borderRadius} h-12 w-12 bg-gradient-to-r from-orange-600 to-orange-500`} />
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ============ APP BRANDING ============ */}
      {activeSection === 'branding' && (
        <div className="grid gap-4 sm:grid-cols-2">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Type className="h-4 w-4 text-primary" />
                {language === 'en' ? 'App Identity' : 'অ্যাপ পরিচয়'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'App Name' : 'অ্যাপের নাম'}</Label>
                <Input value={config.appName} onChange={(e) => updateConfig('appName', e.target.value)} />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'App Tagline / Slogan' : 'অ্যাপ ট্যাগলাইন / স্লোগান'}</Label>
                <Input value={config.appTagline} onChange={(e) => updateConfig('appTagline', e.target.value)} />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <ImageIcon className="h-4 w-4 text-primary" />
                {language === 'en' ? 'App Icons & URLs' : 'অ্যাপ আইকন ও URL'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'App Logo URL' : 'অ্যাপ লোগো URL'}</Label>
                <Input value={config.appLogoUrl} onChange={(e) => updateConfig('appLogoUrl', e.target.value)} placeholder="https://..." />
                {config.appLogoUrl && (
                  <div className="mt-2 flex items-center gap-2">
                    <img src={config.appLogoUrl} alt="Logo preview" className="h-10 w-10 rounded-lg object-cover border" onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                    <span className="text-[10px] text-muted-foreground">{language === 'en' ? 'Logo preview' : 'লোগো প্রিভিউ'}</span>
                  </div>
                )}
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Favicon URL' : 'ফেভিকন URL'}</Label>
                <Input value={config.faviconUrl} onChange={(e) => updateConfig('faviconUrl', e.target.value)} placeholder="https://..." />
              </div>
            </CardContent>
          </Card>

          <Card className="sm:col-span-2">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Globe className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Footer & Copyright' : 'ফুটার ও কপিরাইট'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium">{language === 'en' ? 'Footer Text' : 'ফুটার টেক্সট'}</Label>
                  <Input value={config.footerText} onChange={(e) => updateConfig('footerText', e.target.value)} />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium">{language === 'en' ? 'Copyright Text' : 'কপিরাইট টেক্সট'}</Label>
                  <Input value={config.copyrightText} onChange={(e) => updateConfig('copyrightText', e.target.value)} />
                </div>
              </div>
              {/* Preview */}
              <div className="rounded-xl border bg-accent/30 p-4 mt-2">
                <div className="flex items-center justify-between">
                  <span className="text-xs text-muted-foreground">{config.footerText}</span>
                  <span className="text-[10px] text-muted-foreground/60">{config.copyrightText}</span>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ============ HERO SECTION ============ */}
      {activeSection === 'hero' && (
        <div className="grid gap-4 sm:grid-cols-2">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Type className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Hero Content' : 'হিরো কন্টেন্ট'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Hero Title' : 'হিরো শিরোনাম'}</Label>
                <Input value={config.heroTitle} onChange={(e) => updateConfig('heroTitle', e.target.value)} />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Hero Subtitle' : 'হিরো সাবটাইটেল'}</Label>
                <textarea
                  value={config.heroSubtitle}
                  onChange={(e) => updateConfig('heroSubtitle', e.target.value)}
                  className="w-full rounded-md border bg-background px-3 py-2 text-sm min-h-[60px]"
                />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Wand2 className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Hero Style & Action' : 'হিরো স্টাইল ও অ্যাকশন'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <ColorPicker label={language === 'en' ? 'Hero Background Color' : 'হিরো ব্যাকগ্রাউন্ড রং'} value={config.heroBgColor} onChange={(v) => updateConfig('heroBgColor', v)} />
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Hero Button Text' : 'হিরো বাটন টেক্সট'}</Label>
                <Input value={config.heroButtonText} onChange={(e) => updateConfig('heroButtonText', e.target.value)} />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Hero Button Link' : 'হিরো বাটন লিংক'}</Label>
                <Input value={config.heroButtonLink} onChange={(e) => updateConfig('heroButtonLink', e.target.value)} placeholder="/explore" />
              </div>
            </CardContent>
          </Card>

          {/* Hero Preview */}
          <Card className="sm:col-span-2">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Monitor className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Hero Preview' : 'হিরো প্রিভিউ'}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div
                className="rounded-2xl p-8 text-white relative overflow-hidden"
                style={{ background: `linear-gradient(135deg, ${config.heroBgColor}, ${config.gradientEnd})` }}
              >
                <div className="absolute top-0 right-0 h-32 w-32 rounded-full bg-white/10 -translate-y-1/3 translate-x-1/3" />
                <h2 className="text-2xl font-extrabold">{config.heroTitle}</h2>
                <p className="mt-2 text-sm text-white/80">{config.heroSubtitle}</p>
                <button
                  className="mt-4 rounded-lg bg-white px-5 py-2 text-sm font-semibold shadow-lg"
                  style={{ color: config.heroBgColor }}
                >
                  {config.heroButtonText}
                </button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ============ FEATURE TOGGLES ============ */}
      {activeSection === 'features' && (
        <div className="grid gap-4 sm:grid-cols-2">
          {featureToggles.map((feat) => {
            const Icon = feat.icon;
            const enabled = config[feat.key] as boolean;
            return (
              <Card key={feat.key} className={`transition-all ${enabled ? 'border-primary/20 shadow-sm' : 'opacity-70'}`}>
                <CardContent className="p-4">
                  <div className="flex items-center gap-3">
                    <div className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-xl ${enabled ? 'bg-primary/10 text-primary' : 'bg-accent text-muted-foreground'}`}>
                      <Icon className="h-5 w-5" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold">{language === 'en' ? feat.label : feat.labelBn}</p>
                      <p className="text-[10px] text-muted-foreground">
                        {enabled
                          ? (language === 'en' ? 'Enabled — visible to users' : 'সক্রিয় — ব্যবহারকারীদের দৃশ্যমান')
                          : (language === 'en' ? 'Disabled — hidden from users' : 'নিষ্ক্রিয় — ব্যবহারকারীদের থেকে লুকানো')}
                      </p>
                    </div>
                    <Switch checked={enabled} onCheckedChange={(v) => updateConfig(feat.key, v)} />
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      {/* ============ TEXT & CONTENT ============ */}
      {activeSection === 'content' && (
        <div className="grid gap-4 sm:grid-cols-2">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Type className="h-4 w-4 text-primary" />
                {language === 'en' ? 'General Messages' : 'সাধারণ বার্তা'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Welcome Message' : 'স্বাগত বার্তা'}</Label>
                <Input value={config.welcomeMessage} onChange={(e) => updateConfig('welcomeMessage', e.target.value)} />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Empty State Message' : 'খালি স্টেট বার্তা'}</Label>
                <Input value={config.emptyStateMessage} onChange={(e) => updateConfig('emptyStateMessage', e.target.value)} />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <MessageSquare className="h-4 w-4 text-primary" />
                {language === 'en' ? 'System Messages' : 'সিস্টেম বার্তা'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Error Message' : 'ত্রুটি বার্তা'}</Label>
                <Input value={config.errorMessage} onChange={(e) => updateConfig('errorMessage', e.target.value)} />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Success Message' : 'সাফল্য বার্তা'}</Label>
                <Input value={config.successMessage} onChange={(e) => updateConfig('successMessage', e.target.value)} />
              </div>
            </CardContent>
          </Card>

          <Card className="sm:col-span-2">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Layout className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Section Titles' : 'সেকশন শিরোনাম'}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid gap-4 sm:grid-cols-3">
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium">{language === 'en' ? 'Home Section Title' : 'হোম সেকশন শিরোনাম'}</Label>
                  <Input value={config.homeTitle} onChange={(e) => updateConfig('homeTitle', e.target.value)} />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium">{language === 'en' ? 'Explore Section Title' : 'এক্সপ্লোর সেকশন শিরোনাম'}</Label>
                  <Input value={config.exploreTitle} onChange={(e) => updateConfig('exploreTitle', e.target.value)} />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ============ LAYOUT SETTINGS ============ */}
      {activeSection === 'layout' && (
        <div className="grid gap-4 sm:grid-cols-2">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Layout className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Sidebar & Navigation' : 'সাইডবার ও নেভিগেশন'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Sidebar Position' : 'সাইডবার অবস্থান'}</Label>
                <Select value={config.sidebarPosition} onValueChange={(v) => updateConfig('sidebarPosition', v)}>
                  <SelectTrigger className="h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="left">{language === 'en' ? 'Left' : 'বাম'}</SelectItem>
                    <SelectItem value="right">{language === 'en' ? 'Right' : 'ডান'}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Navigation Style' : 'নেভিগেশন স্টাইল'}</Label>
                <Select value={config.navigationStyle} onValueChange={(v) => updateConfig('navigationStyle', v)}>
                  <SelectTrigger className="h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="bottom-tabs">{language === 'en' ? 'Bottom Tabs' : 'নিচের ট্যাব'}</SelectItem>
                    <SelectItem value="sidebar">{language === 'en' ? 'Sidebar' : 'সাইডবার'}</SelectItem>
                    <SelectItem value="both">{language === 'en' ? 'Both' : 'উভয়'}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Smartphone className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Card & UI Settings' : 'কার্ড ও UI সেটিংস'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Card Style' : 'কার্ড স্টাইল'}</Label>
                <Select value={config.cardStyle} onValueChange={(v) => updateConfig('cardStyle', v)}>
                  <SelectTrigger className="h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="default">{language === 'en' ? 'Default' : 'ডিফল্ট'}</SelectItem>
                    <SelectItem value="compact">{language === 'en' ? 'Compact' : 'কমপ্যাক্ট'}</SelectItem>
                    <SelectItem value="spacious">{language === 'en' ? 'Spacious' : 'প্রশস্ত'}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Search className="h-4 w-4 text-muted-foreground" />
                  <Label className="text-sm font-medium">{language === 'en' ? 'Show Search Bar' : 'সার্চ বার দেখান'}</Label>
                </div>
                <Switch checked={config.showSearchBar} onCheckedChange={(v) => updateConfig('showSearchBar', v)} />
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Bell className="h-4 w-4 text-muted-foreground" />
                  <Label className="text-sm font-medium">{language === 'en' ? 'Show Notifications Bell' : 'নোটিফিকেশন বেল দেখান'}</Label>
                </div>
                <Switch checked={config.showNotificationsBell} onCheckedChange={(v) => updateConfig('showNotificationsBell', v)} />
              </div>
            </CardContent>
          </Card>

          {/* Layout Preview */}
          <Card className="sm:col-span-2">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Monitor className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Layout Preview' : 'লেআউট প্রিভিউ'}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex gap-2 rounded-xl border bg-accent/20 p-4 min-h-[200px]">
                {/* Sidebar preview */}
                {(config.navigationStyle === 'sidebar' || config.navigationStyle === 'both') && (
                  <div
                    className={`w-16 shrink-0 rounded-lg border p-1 ${config.sidebarPosition === 'right' ? 'order-2' : 'order-1'}`}
                    style={{ backgroundColor: config.sidebarColor + '40' }}
                  >
                    {[1, 2, 3, 4].map((i) => (
                      <div key={i} className="mb-1 h-4 rounded bg-foreground/10" />
                    ))}
                  </div>
                )}
                {/* Main content */}
                <div className="flex-1 space-y-2" style={{ order: config.sidebarPosition === 'right' ? 1 : 2 }}>
                  <div className="h-6 rounded-lg border" style={{ backgroundColor: config.headerColor + '40' }} />
                  {config.showSearchBar && <div className="h-5 rounded bg-foreground/5" />}
                  <div className="grid grid-cols-2 gap-2">
                    <div className="h-12 rounded-lg border" style={{ backgroundColor: config.cardBgColor + '60' }} />
                    <div className="h-12 rounded-lg border" style={{ backgroundColor: config.cardBgColor + '60' }} />
                  </div>
                </div>
                {/* Bottom tabs preview */}
                {(config.navigationStyle === 'bottom-tabs' || config.navigationStyle === 'both') && (
                  <div className="absolute bottom-4 left-4 right-4 flex items-center justify-around rounded-lg border bg-card p-2">
                    {[1, 2, 3, 4].map((i) => (
                      <div key={i} className="h-4 w-4 rounded-full bg-foreground/10" />
                    ))}
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ============ TYPOGRAPHY ============ */}
      {activeSection === 'typography' && (
        <div className="grid gap-4 sm:grid-cols-2">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Type className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Font Settings' : 'ফন্ট সেটিংস'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Body Font Family' : 'বডি ফন্ট ফ্যামিলি'}</Label>
                <Select value={config.fontFamily} onValueChange={(v) => updateConfig('fontFamily', v)}>
                  <SelectTrigger className="h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {['Inter', 'Poppins', 'Roboto', 'Open Sans', 'Nunito', 'Montserrat'].map((f) => (
                      <SelectItem key={f} value={f}>{f}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Heading Font Family' : 'হেডিং ফন্ট ফ্যামিলি'}</Label>
                <Select value={config.headingFontFamily} onValueChange={(v) => updateConfig('headingFontFamily', v)}>
                  <SelectTrigger className="h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {['Inter', 'Poppins', 'Roboto', 'Open Sans', 'Nunito', 'Montserrat'].map((f) => (
                      <SelectItem key={f} value={f}>{f}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Base Font Size' : 'বেস ফন্ট সাইজ'}</Label>
                <Select value={config.baseFontSize} onValueChange={(v) => updateConfig('baseFontSize', v)}>
                  <SelectTrigger className="h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {['14px', '15px', '16px', '17px', '18px'].map((s) => (
                      <SelectItem key={s} value={s}>{s}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Heading Font Weight' : 'হেডিং ফন্ট ওয়েট'}</Label>
                <Select value={config.headingFontWeight} onValueChange={(v) => updateConfig('headingFontWeight', v)}>
                  <SelectTrigger className="h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {[
                      { value: '600', label: '600 (Semi Bold)' },
                      { value: '700', label: '700 (Bold)' },
                      { value: '800', label: '800 (Extra Bold)' },
                      { value: '900', label: '900 (Black)' },
                    ].map((w) => (
                      <SelectItem key={w.value} value={w.value}>{w.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Paintbrush className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Text Colors' : 'টেক্সট রং'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <ColorPicker label={language === 'en' ? 'Text Color' : 'টেক্সট রং'} value={config.textColor} onChange={(v) => updateConfig('textColor', v)} />
              <ColorPicker label={language === 'en' ? 'Muted Text Color' : 'মিউটেড টেক্সট রং'} value={config.mutedTextColor} onChange={(v) => updateConfig('mutedTextColor', v)} />
              <ColorPicker label={language === 'en' ? 'Heading Color' : 'হেডিং রং'} value={config.headingColor} onChange={(v) => updateConfig('headingColor', v)} />
              <ColorPicker label={language === 'en' ? 'Link Color' : 'লিংক রং'} value={config.linkColor} onChange={(v) => updateConfig('linkColor', v)} />
            </CardContent>
          </Card>

          {/* Typography Preview */}
          <Card className="sm:col-span-2">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Monitor className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Typography Preview' : 'টাইপোগ্রাফি প্রিভিউ'}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="rounded-xl border bg-card p-6 space-y-4" style={{ fontFamily: config.fontFamily, fontSize: config.baseFontSize }}>
                <h1 style={{ fontFamily: config.headingFontFamily, fontWeight: config.headingFontWeight, color: config.headingColor, fontSize: '2em' }}>
                  {language === 'en' ? 'Heading Preview' : 'হেডিং প্রিভিউ'}
                </h1>
                <h2 style={{ fontFamily: config.headingFontFamily, fontWeight: config.headingFontWeight, color: config.headingColor, fontSize: '1.5em' }}>
                  {language === 'en' ? 'Subheading Preview' : 'সাবহেডিং প্রিভিউ'}
                </h2>
                <p style={{ color: config.textColor }}>
                  {language === 'en'
                    ? 'This is a paragraph of body text. It demonstrates how the body font family and text color appear in the application.'
                    : 'এটি বডি টেক্সটের একটি অনুচ্ছেদ। এটি দেখায় যে অ্যাপ্লিকেশনে বডি ফন্ট ফ্যামিলি এবং টেক্সট রং কেমন দেখায়।'}
                </p>
                <p style={{ color: config.mutedTextColor }}>
                  {language === 'en' ? 'This is muted/secondary text used for descriptions and labels.' : 'এটি বিবরণ এবং লেবেলের জন্য ব্যবহৃত মিউটেড/সেকেন্ডারি টেক্সট।'}
                </p>
                <a href="#" onClick={(e) => e.preventDefault()} style={{ color: config.linkColor, textDecoration: 'underline' }}>
                  {language === 'en' ? 'This is a link' : 'এটি একটি লিংক'}
                </a>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ============ DARK MODE ============ */}
      {activeSection === 'dark-mode' && (
        <div className="grid gap-4 sm:grid-cols-2">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Moon className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Dark Mode Colors' : 'ডার্ক মোড রং'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <ColorPicker label={language === 'en' ? 'Dark Background' : 'ডার্ক ব্যাকগ্রাউন্ড'} value={config.darkBgColor} onChange={(v) => updateConfig('darkBgColor', v)} />
              <ColorPicker label={language === 'en' ? 'Dark Card Color' : 'ডার্ক কার্ড রং'} value={config.darkCardColor} onChange={(v) => updateConfig('darkCardColor', v)} />
              <ColorPicker label={language === 'en' ? 'Dark Text Color' : 'ডার্ক টেক্সট রং'} value={config.darkTextColor} onChange={(v) => updateConfig('darkTextColor', v)} />
              <ColorPicker label={language === 'en' ? 'Dark Accent Color' : 'ডার্ক অ্যাকসেন্ট রং'} value={config.darkAccentColor} onChange={(v) => updateConfig('darkAccentColor', v)} />
            </CardContent>
          </Card>

          {/* Dark Mode Preview */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Monitor className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Dark Mode Preview' : 'ডার্ক মোড প্রিভিউ'}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div
                className="rounded-xl p-6 space-y-4 border border-white/10"
                style={{ backgroundColor: config.darkBgColor }}
              >
                <h3 style={{ color: config.darkTextColor, fontWeight: 700, fontSize: '1.25rem' }}>
                  {language === 'en' ? 'Dark Mode Appearance' : 'ডার্ক মোড চেহারা'}
                </h3>
                <p style={{ color: config.darkTextColor, opacity: 0.7 }} className="text-sm">
                  {language === 'en' ? 'This is how your app will look in dark mode.' : 'ডার্ক মোডে আপনার অ্যাপ এমন দেখাবে।'}
                </p>
                <div
                  className="rounded-lg p-4 space-y-2"
                  style={{ backgroundColor: config.darkCardColor }}
                >
                  <p className="text-sm font-medium" style={{ color: config.darkTextColor }}>
                    {language === 'en' ? 'Card in dark mode' : 'ডার্ক মোডে কার্ড'}
                  </p>
                  <p className="text-xs" style={{ color: config.darkTextColor, opacity: 0.5 }}>
                    {language === 'en' ? 'Secondary text inside a dark card' : 'ডার্ক কার্ডের ভিতরে সেকেন্ডারি টেক্সট'}
                  </p>
                  <button
                    className="rounded-lg px-4 py-1.5 text-sm font-semibold text-white"
                    style={{ backgroundColor: config.darkAccentColor }}
                  >
                    {language === 'en' ? 'Action Button' : 'অ্যাকশন বাটন'}
                  </button>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ============ UI EFFECTS ============ */}
      {activeSection === 'effects' && (
        <div className="grid gap-4 sm:grid-cols-2">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Sparkles className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Animations & Shadows' : 'অ্যানিমেশন ও শ্যাডো'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Zap className="h-4 w-4 text-muted-foreground" />
                  <Label className="text-sm font-medium">{language === 'en' ? 'Enable Animations' : 'অ্যানিমেশন সক্রিয়'}</Label>
                </div>
                <Switch checked={config.enableAnimations} onCheckedChange={(v) => updateConfig('enableAnimations', v)} />
              </div>
              <Separator />
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Shadow Intensity' : 'শ্যাডো তীব্রতা'}</Label>
                <Select value={config.shadowIntensity} onValueChange={(v) => updateConfig('shadowIntensity', v)}>
                  <SelectTrigger className="h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">{language === 'en' ? 'None' : 'কোনোটি নয়'}</SelectItem>
                    <SelectItem value="light">{language === 'en' ? 'Light' : 'হালকা'}</SelectItem>
                    <SelectItem value="medium">{language === 'en' ? 'Medium' : 'মাঝারি'}</SelectItem>
                    <SelectItem value="heavy">{language === 'en' ? 'Heavy' : 'ভারী'}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Smartphone className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Border Radius' : 'বর্ডার রেডিয়াস'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Button Border Radius' : 'বাটন বর্ডার রেডিয়াস'}</Label>
                <Select value={config.buttonBorderRadius} onValueChange={(v) => updateConfig('buttonBorderRadius', v)}>
                  <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {borderRadiusOptions.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Card Border Radius' : 'কার্ড বর্ডার রেডিয়াস'}</Label>
                <Select value={config.cardBorderRadius} onValueChange={(v) => updateConfig('cardBorderRadius', v)}>
                  <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {borderRadiusOptions.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Input Border Radius' : 'ইনপুট বর্ডার রেডিয়াস'}</Label>
                <Select value={config.inputBorderRadius} onValueChange={(v) => updateConfig('inputBorderRadius', v)}>
                  <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {borderRadiusOptions.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          {/* Effects Preview */}
          <Card className="sm:col-span-2">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Monitor className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Effects Preview' : 'ইফেক্ট প্রিভিউ'}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex flex-wrap items-start gap-6">
                {/* Shadow preview */}
                <div className="space-y-2">
                  <Label className="text-xs text-muted-foreground">{language === 'en' ? 'Shadow' : 'শ্যাডো'}</Label>
                  <div
                    className="h-20 w-32 bg-card border"
                    style={{
                      boxShadow: {
                        none: '0 0 0 0 transparent',
                        light: '0 1px 2px 0 rgba(0,0,0,0.05)',
                        medium: '0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -2px rgba(0,0,0,0.1)',
                        heavy: '0 10px 15px -3px rgba(0,0,0,0.15), 0 4px 6px -4px rgba(0,0,0,0.1)',
                      }[config.shadowIntensity],
                    }}
                  />
                </div>
                {/* Button radius preview */}
                <div className="space-y-2">
                  <Label className="text-xs text-muted-foreground">{language === 'en' ? 'Button' : 'বাটন'}</Label>
                  <div className="flex gap-2">
                    <button className={`${config.buttonBorderRadius} bg-primary px-4 py-2 text-sm text-white font-medium transition-transform ${config.enableAnimations ? 'hover:scale-105' : ''}`}>
                      {language === 'en' ? 'Primary' : 'প্রাথমিক'}
                    </button>
                    <button className={`${config.buttonBorderRadius} border px-4 py-2 text-sm font-medium transition-transform ${config.enableAnimations ? 'hover:scale-105' : ''}`}>
                      {language === 'en' ? 'Outline' : 'আউটলাইন'}
                    </button>
                  </div>
                </div>
                {/* Card radius preview */}
                <div className="space-y-2">
                  <Label className="text-xs text-muted-foreground">{language === 'en' ? 'Card' : 'কার্ড'}</Label>
                  <div className={`${config.cardBorderRadius} border bg-card p-4 text-xs`}>
                    <p className="font-medium">{language === 'en' ? 'Card Content' : 'কার্ড কন্টেন্ট'}</p>
                    <p className="text-muted-foreground mt-1">{language === 'en' ? 'Sample text' : 'নমুনা টেক্সট'}</p>
                  </div>
                </div>
                {/* Input radius preview */}
                <div className="space-y-2">
                  <Label className="text-xs text-muted-foreground">{language === 'en' ? 'Input' : 'ইনপুট'}</Label>
                  <Input className={`${config.inputBorderRadius} h-9`} placeholder={language === 'en' ? 'Type here...' : 'এখানে টাইপ করুন...'} />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ============ NAVIGATION ============ */}
      {activeSection === 'navigation' && (
        <div className="grid gap-4 sm:grid-cols-2">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Navigation className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Bottom Navigation' : 'নিচের নেভিগেশন'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <ColorPicker label={language === 'en' ? 'Background Color' : 'ব্যাকগ্রাউন্ড রং'} value={config.bottomNavBgColor} onChange={(v) => updateConfig('bottomNavBgColor', v)} />
              <ColorPicker label={language === 'en' ? 'Active Color' : 'সক্রিয় রং'} value={config.bottomNavActiveColor} onChange={(v) => updateConfig('bottomNavActiveColor', v)} />
              <ColorPicker label={language === 'en' ? 'Inactive Color' : 'নিষ্ক্রিয় রং'} value={config.bottomNavInactiveColor} onChange={(v) => updateConfig('bottomNavInactiveColor', v)} />
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Nav Style' : 'নেভ স্টাইল'}</Label>
                <Select value={config.bottomNavStyle} onValueChange={(v) => updateConfig('bottomNavStyle', v)}>
                  <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="default">{language === 'en' ? 'Default' : 'ডিফল্ট'}</SelectItem>
                    <SelectItem value="floating">{language === 'en' ? 'Floating' : 'ফ্লোটিং'}</SelectItem>
                    <SelectItem value="minimal">{language === 'en' ? 'Minimal' : 'মিনিমাল'}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Layout className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Sidebar & Notifications' : 'সাইডবার ও নোটিফিকেশন'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Sidebar Width' : 'সাইডবার প্রস্থ'}</Label>
                <Select value={config.sidebarWidth} onValueChange={(v) => updateConfig('sidebarWidth', v)}>
                  <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {['240px', '260px', '280px', '300px', '320px'].map((w) => (
                      <SelectItem key={w} value={w}>{w}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Sidebar BG Opacity (%)' : 'সাইডবার BG অস্বচ্ছতা (%)'}</Label>
                <Select value={config.sidebarBgOpacity} onValueChange={(v) => updateConfig('sidebarBgOpacity', v)}>
                  <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {['60', '70', '80', '90', '95', '100'].map((o) => (
                      <SelectItem key={o} value={o}>{o}%</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <Separator />
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Notification Position' : 'নোটিফিকেশন অবস্থান'}</Label>
                <Select value={config.notificationPosition} onValueChange={(v) => updateConfig('notificationPosition', v)}>
                  <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="top-right">{language === 'en' ? 'Top Right' : 'উপরে ডান'}</SelectItem>
                    <SelectItem value="top-left">{language === 'en' ? 'Top Left' : 'উপরে বাম'}</SelectItem>
                    <SelectItem value="bottom-right">{language === 'en' ? 'Bottom Right' : 'নিচে ডান'}</SelectItem>
                    <SelectItem value="bottom-left">{language === 'en' ? 'Bottom Left' : 'নিচে বাম'}</SelectItem>
                    <SelectItem value="top-center">{language === 'en' ? 'Top Center' : 'উপরে মাঝ'}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'Notification Style' : 'নোটিফিকেশন স্টাইল'}</Label>
                <Select value={config.notificationStyle} onValueChange={(v) => updateConfig('notificationStyle', v)}>
                  <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="default">{language === 'en' ? 'Default' : 'ডিফল্ট'}</SelectItem>
                    <SelectItem value="toast">{language === 'en' ? 'Toast' : 'টোস্ট'}</SelectItem>
                    <SelectItem value="banner">{language === 'en' ? 'Banner' : 'ব্যানার'}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          {/* Navigation Preview */}
          <Card className="sm:col-span-2">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Monitor className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Navigation Preview' : 'নেভিগেশন প্রিভিউ'}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="relative rounded-xl border bg-accent/20 p-4 min-h-[240px]">
                {/* Sidebar preview */}
                <div
                  className="absolute top-4 left-4 bottom-16 rounded-lg border p-2"
                  style={{ width: '60px', backgroundColor: config.sidebarColor, opacity: Number(config.sidebarBgOpacity) / 100 }}
                >
                  {[1, 2, 3, 4, 5].map((i) => (
                    <div key={i} className="mb-1.5 h-3 rounded" style={{ backgroundColor: i === 1 ? config.bottomNavActiveColor : config.bottomNavInactiveColor, opacity: i === 1 ? 1 : 0.3 }} />
                  ))}
                </div>
                {/* Bottom Nav preview */}
                <div
                  className={`absolute bottom-4 left-4 right-4 flex items-center justify-around p-2 ${
                    config.bottomNavStyle === 'floating' ? 'rounded-2xl mx-4 shadow-lg' : config.bottomNavStyle === 'minimal' ? 'border-t rounded-none' : 'rounded-lg border'
                  }`}
                  style={{ backgroundColor: config.bottomNavBgColor }}
                >
                  {['🏠', '🔍', '💬', '❤️', '👤'].map((icon, i) => (
                    <div key={i} className="flex flex-col items-center gap-0.5">
                      <span className="text-sm">{icon}</span>
                      <div className="h-0.5 w-4 rounded-full" style={{ backgroundColor: i === 0 ? config.bottomNavActiveColor : 'transparent' }} />
                    </div>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ============ ADVANCED ============ */}
      {activeSection === 'advanced' && (
        <div className="grid gap-4 sm:grid-cols-2">
          {/* Preset Themes */}
          <Card className="sm:col-span-2">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Wand2 className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Preset Themes' : 'প্রিসেট থিম'}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid gap-3 sm:grid-cols-3">
                {presetThemes.map((theme) => (
                  <button
                    key={theme.name}
                    onClick={() => setConfig(prev => ({ ...prev, ...theme.values }))}
                    className="group rounded-xl border p-4 text-left transition-all hover:shadow-md hover:-translate-y-0.5"
                  >
                    <div className={`h-8 rounded-lg bg-gradient-to-r ${theme.preview} mb-3 transition-transform group-hover:scale-105`} />
                    <p className="text-sm font-semibold">{language === 'en' ? theme.name : theme.nameBn}</p>
                    <p className="text-[10px] text-muted-foreground mt-0.5">{language === 'en' ? theme.description : theme.descriptionBn}</p>
                  </button>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* Custom CSS */}
          <Card className="sm:col-span-2">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Code className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Custom CSS' : 'কাস্টম CSS'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="rounded-lg border border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900/30 p-3 flex items-start gap-2">
                <AlertTriangle className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />
                <p className="text-xs text-amber-800 dark:text-amber-200">
                  {language === 'en'
                    ? 'Custom CSS is injected directly into the page. Use with caution — invalid CSS may break the layout. Use CSS variables for consistency.'
                    : 'কাস্টম CSS সরাসরি পৃষ্ঠায় ইনজেক্ট করা হয়। সতর্কতার সাথে ব্যবহার করুন — অবৈধ CSS লেআউট নষ্ট করতে পারে। সামঞ্জস্যের জন্য CSS ভেরিয়েবল ব্যবহার করুন।'}
                </p>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">{language === 'en' ? 'CSS Code' : 'CSS কোড'}</Label>
                <textarea
                  value={config.customCSS}
                  onChange={(e) => updateConfig('customCSS', e.target.value)}
                  className="w-full rounded-lg border bg-gray-950 text-green-400 px-4 py-3 text-sm font-mono min-h-[200px] focus:outline-none focus:ring-2 focus:ring-primary/50"
                  placeholder={`/* Example: */\n.my-class {\n  color: var(--primary);\n  border-radius: var(--card-radius);\n}\n\n/* Override card styles */\n.card {\n  box-shadow: var(--shadow-intensity);\n}`}
                  spellCheck={false}
                />
              </div>
            </CardContent>
          </Card>

          {/* Import / Export */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Download className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Export Configuration' : 'কনফিগারেশন রপ্তানি'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <p className="text-xs text-muted-foreground">
                {language === 'en'
                  ? 'Download your current configuration as a JSON file. You can use this to backup or share your settings.'
                  : 'আপনার বর্তমান কনফিগারেশন একটি JSON ফাইল হিসাবে ডাউনলোড করুন। আপনি এটি ব্যাকআপ বা শেয়ার করতে ব্যবহার করতে পারেন।'}
              </p>
              <Button
                variant="outline"
                size="sm"
                className="gap-1.5 text-xs w-full"
                onClick={() => {
                  const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' });
                  const url = URL.createObjectURL(blob);
                  const a = document.createElement('a');
                  a.href = url;
                  a.download = `needyfy-config-${Date.now()}.json`;
                  a.click();
                  URL.revokeObjectURL(url);
                }}
              >
                <Download className="h-3.5 w-3.5" />
                {language === 'en' ? 'Export JSON' : 'JSON রপ্তানি'}
              </Button>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2">
                <Upload className="h-4 w-4 text-primary" />
                {language === 'en' ? 'Import Configuration' : 'কনফিগারেশন আমদানি'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <p className="text-xs text-muted-foreground">
                {language === 'en'
                  ? 'Upload a previously exported JSON file to restore your settings.'
                  : 'আপনার সেটিংস পুনরুদ্ধার করতে একটি পূর্বে রপ্তানিকৃত JSON ফাইল আপলোড করুন।'}
              </p>
              <Button
                variant="outline"
                size="sm"
                className="gap-1.5 text-xs w-full"
                onClick={() => {
                  const input = document.createElement('input');
                  input.type = 'file';
                  input.accept = '.json';
                  input.onchange = (e) => {
                    const file = (e.target as HTMLInputElement).files?.[0];
                    if (!file) return;
                    const reader = new FileReader();
                    reader.onload = (ev) => {
                      try {
                        const imported = JSON.parse(ev.target?.result as string);
                        setConfig(prev => ({ ...prev, ...imported }));
                      } catch {
                        alert(language === 'en' ? 'Invalid JSON file' : 'অবৈধ JSON ফাইল');
                      }
                    };
                    reader.readAsText(file);
                  };
                  input.click();
                }}
              >
                <Upload className="h-3.5 w-3.5" />
                {language === 'en' ? 'Import JSON' : 'JSON আমদানি'}
              </Button>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
}

// ============ ADMIN SETTINGS ============
function AdminSettings() {
  const { language, adminToken } = useAppStore();
  const [notifTitle, setNotifTitle] = useState(''); const [notifMessage, setNotifMessage] = useState(''); const [sending, setSending] = useState(false); const [sent, setSent] = useState(false);
  const handleSend = async (e: React.FormEvent) => { e.preventDefault(); if (!notifTitle || !notifMessage) return; setSending(true); try { const res = await adminFetch('/api/admin/notify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: notifTitle, message: notifMessage }) }, adminToken); const data = await safeJsonParse<Record<string, unknown>>(res); if (res.status === 401) { useAppStore.getState().adminLogout(); return; } if (data?.success) { setNotifTitle(''); setNotifMessage(''); setSent(true); setTimeout(() => setSent(false), 3000); } } catch (err) { console.error('Failed:', err); } finally { setSending(false); } };
  return (<div className="space-y-6"><Card><CardHeader><CardTitle className="text-sm flex items-center gap-2"><Bell className="h-4 w-4 text-primary" />{language === 'en' ? 'Send Notification' : 'নোটিফিকেশন পাঠান'}</CardTitle></CardHeader><CardContent><form onSubmit={handleSend} className="space-y-3"><div className="space-y-1.5"><Label className="text-xs">{language === 'en' ? 'Title' : 'শিরোনাম'}</Label><Input value={notifTitle} onChange={(e) => setNotifTitle(e.target.value)} required /></div><div className="space-y-1.5"><Label className="text-xs">{language === 'en' ? 'Message' : 'বার্তা'}</Label><textarea value={notifMessage} onChange={(e) => setNotifMessage(e.target.value)} className="w-full rounded-md border bg-background px-3 py-2 text-sm min-h-[80px]" required /></div><Button type="submit" disabled={sending} className="bg-gradient-to-r from-orange-700 to-orange-500">{sent ? '✓ Sent!' : sending ? '...' : (language === 'en' ? 'Send' : 'পাঠান')}</Button></form></CardContent></Card></div>);
}

// ============ MAIN ADMIN PAGE ============
export default function AdminPage() {
  const { language, setAdminUser, isAdminLoggedIn, adminUser, adminLogout, adminTab, setAdminTab, adminPermissions, adminToken } = useAppStore();
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  // Wait for hydration to complete so localStorage-persisted admin state is available
  const [hydrated, setHydrated] = useState(() => {
    if (typeof window !== 'undefined') {
      hydrateStoreFromStorage();
      return true;
    }
    return false;
  });

  useEffect(() => {
    if (isAdminLoggedIn && adminTab === 'dashboard') {
      adminFetch('/api/admin/stats', {}, adminToken).then((res) => safeJsonParse<Record<string, unknown>>(res)).then((data) => { if (data?.success) setStats(data?.stats as DashboardStats); }).catch(console.error);
    }
  }, [isAdminLoggedIn, adminTab, adminToken]);

  const handleLogin = (admin: Record<string, unknown>, token: string | null) => {
    setAdminUser({
      id: String(admin.id),
      name: String(admin.name),
      email: String(admin.email),
      role: String(admin.role),
      avatar: admin.avatar ? String(admin.avatar) : undefined,
      phone: admin.phone ? String(admin.phone) : undefined,
      permissions: admin.permissions as { canManageUsers: boolean; canManageHouses: boolean; canManageShops: boolean; canManageProducts: boolean; canManageOrders: boolean; canManageMCQ: boolean; canManageCommunity: boolean; canSendNotification: boolean; canViewAnalytics: boolean; canManageTeam: boolean } | undefined,
    }, token);
    setAdminTab('dashboard');
    // Also set currentSection to 'admin' so if user navigates to main URL, they see admin portal
    useAppStore.getState().setCurrentSection('admin');
  };

  if (!hydrated) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-950 dark:to-gray-900">
        <div className="flex flex-col items-center gap-4">
          <span className="h-10 w-10 animate-spin rounded-full border-4 border-orange-600 border-t-transparent" />
          <p className="text-sm text-muted-foreground">Loading admin portal...</p>
        </div>
      </div>
    );
  }

  if (!isAdminLoggedIn) {
    return <AdminLoginPage onLogin={handleLogin} />;
  }

  const isSuper = isSuperAdmin(adminUser?.role || '');
  const perms = adminPermissions;

  const allTabs = [
    { id: 'dashboard', label: language === 'en' ? 'Dashboard' : 'ড্যাশবোর্ড', icon: LayoutDashboard, permKey: 'canViewAnalytics' },
    { id: 'users', label: language === 'en' ? 'Users' : 'ব্যবহারকারী', icon: Users, permKey: 'canManageUsers' },
    { id: 'houses', label: language === 'en' ? 'Houses' : 'বাড়ি', icon: Building2, permKey: 'canManageHouses' },
    { id: 'shops', label: language === 'en' ? 'Shops' : 'দোকান', icon: Store, permKey: 'canManageShops' },
    { id: 'products', label: language === 'en' ? 'Products' : 'পণ্য', icon: ShoppingBag, permKey: 'canManageProducts' },
    { id: 'orders', label: language === 'en' ? 'Orders' : 'অর্ডার', icon: Package, permKey: 'canManageOrders' },
    { id: 'mcq', label: 'MCQ', icon: BookOpen, permKey: 'canManageMCQ' },
    { id: 'community', label: language === 'en' ? 'Community' : 'কমিউনিটি', icon: MessageSquare, permKey: 'canManageCommunity' },
    { id: 'team', label: language === 'en' ? 'Team' : 'টিম', icon: UserCog, permKey: 'canManageTeam' },
    { id: 'customize', label: language === 'en' ? 'Customize' : 'কাস্টমাইজ', icon: Palette, permKey: 'canManageTeam' },
    { id: 'payments', label: language === 'en' ? 'Payments' : 'পেমেন্ট', icon: CreditCard, permKey: 'canManageOrders' },
    { id: 'notifications', label: language === 'en' ? 'Notifications' : 'নোটিফিকেশন', icon: Bell, permKey: 'canSendNotification' },
    { id: 'settings', label: language === 'en' ? 'Settings' : 'সেটিংস', icon: Settings, permKey: 'canManageTeam' },
  ];

  // Filter tabs based on permissions
  // Dashboard and Settings are always visible; other tabs require their permission
  const tabs = isSuper ? allTabs : allTabs.filter((tab) => {
    if (tab.id === 'customize') return false; // Only super admin can see Customize tab
    if (tab.id === 'dashboard') return true; // Dashboard always visible
    if (tab.id === 'notifications') return true; // Notifications always visible (accessible via quick actions)
    if (tab.id === 'settings') return true; // Settings always visible
    if (tab.id === 'team') return perms?.canManageTeam;
    const permVal = perms?.[tab.permKey as keyof typeof perms];
    return permVal !== undefined ? permVal : true;
  });

  const renderContent = () => {
    switch (adminTab) {
      case 'dashboard': return <AnalyticsDashboard stats={stats} onNavigate={setAdminTab} />;
      case 'users': return <AdminUsers />;
      case 'houses': return <AdminListings type="houses" />;
      case 'shops': return <AdminListings type="shops" />;
      case 'products': return <AdminListings type="products" />;
      case 'orders': return <AdminOrders />;
      case 'mcq': return <AdminMCQManager />;
      case 'community': return <AdminCommunity />;
      case 'team': return <TeamManagement />;
      case 'customize': return <AppCustomizer />;
      case 'payments': return <AdminPayments />;
      case 'notifications': return <AdminSettings />;
      case 'settings': return <AdminSettings />;
      default: return <AnalyticsDashboard stats={stats} onNavigate={setAdminTab} />;
    }
  };

  return (
    <div className="flex min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-950 dark:to-gray-900">
      {/* Mobile Overlay */}
      {sidebarOpen && <div className="fixed inset-0 z-40 lg:hidden" onClick={() => setSidebarOpen(false)}><div className="absolute inset-0 bg-black/50 backdrop-blur-sm" /></div>}

      {/* Sidebar */}
      <aside className={`fixed inset-y-0 left-0 z-50 w-72 transform border-r bg-card shadow-xl transition-transform duration-300 lg:relative lg:z-0 lg:translate-x-0 lg:shadow-none ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'}`}>
        <div className="flex h-full flex-col">
          {/* Brand */}
          <div className="p-5 border-b">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-gradient-to-br from-orange-600 to-orange-500 shadow-lg">
                  <Shield className="h-5 w-5 text-white" />
                </div>
                <div>
                  <h2 className="text-sm font-bold">Needyfy Admin</h2>
                  <p className="text-[10px] text-muted-foreground">{isSuper ? (language === 'en' ? 'Super Admin' : 'সুপার অ্যাডমিন') : (language === 'en' ? 'Team Admin' : 'টিম অ্যাডমিন')}</p>
                </div>
              </div>
              <Button variant="ghost" size="icon" className="h-7 w-7 lg:hidden" onClick={() => setSidebarOpen(false)}><X className="h-4 w-4" /></Button>
            </div>
          </div>

          {/* User Profile */}
          <div className="p-4 border-b">
            <div className="flex items-center gap-3 rounded-xl bg-accent/50 p-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-orange-600 to-orange-500 shadow">
                <span className="text-sm font-bold text-white">{adminUser?.name?.charAt(0).toUpperCase()}</span>
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold truncate">{adminUser?.name}</p>
                <p className="text-[10px] text-muted-foreground truncate">{adminUser?.email}</p>
              </div>
              {isSuper && <Crown className="h-4 w-4 text-orange-500 shrink-0" />}
            </div>
          </div>

          {/* Navigation */}
          <nav className="flex-1 overflow-y-auto p-3">
            <div className="space-y-0.5">
              {tabs.map((tab) => {
                const Icon = tab.icon;
                const isActive = adminTab === tab.id;
                return (
                  <button key={tab.id} onClick={() => { setAdminTab(tab.id); setSidebarOpen(false); }}
                    className={`flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-sm transition-all duration-150 ${isActive ? 'bg-gradient-to-r from-orange-600/10 to-orange-500/5 font-semibold text-primary shadow-sm' : 'text-foreground/70 hover:bg-accent hover:text-foreground'}`}>
                    <Icon className={`h-4 w-4 ${isActive ? 'text-primary' : ''}`} strokeWidth={isActive ? 2.5 : 2} />
                    <span className="flex-1 text-left">{tab.label}</span>
                    {isActive && <ChevronRight className="h-3.5 w-3.5 text-primary" />}
                  </button>
                );
              })}
            </div>
          </nav>

          {/* Footer */}
          <div className="border-t p-3 space-y-1">
            <a href="/" className="flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground">
              <ArrowLeft className="h-4 w-4" /><span>{language === 'en' ? 'Back to Site' : 'সাইটে ফিরুন'}</span>
            </a>
            <button onClick={adminLogout} className="flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-sm text-destructive transition-colors hover:bg-destructive/5">
              <LogOut className="h-4 w-4" /><span>{language === 'en' ? 'Logout' : 'লগআউট'}</span>
            </button>
          </div>
        </div>
      </aside>

      {/* Main Content */}
      <div className="flex flex-1 flex-col min-w-0">
        {/* Top Bar */}
        <header className="sticky top-0 z-30 flex items-center justify-between border-b bg-card/80 px-5 py-3 backdrop-blur-xl">
          <div className="flex items-center gap-3">
            {adminTab !== 'dashboard' && (
              <Button variant="ghost" size="icon" onClick={() => setAdminTab('dashboard')} className="text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:text-orange-300 dark:hover:bg-orange-950/30">
                <ArrowLeft className="h-5 w-5" />
              </Button>
            )}
            <Button variant="ghost" size="icon" className="lg:hidden" onClick={() => setSidebarOpen(true)}><Menu className="h-5 w-5" /></Button>
            <div className="flex items-center gap-2.5">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10">
                {(() => { const TabIcon = tabs.find((t) => t.id === adminTab)?.icon || LayoutDashboard; return <TabIcon className="h-4 w-4 text-primary" />; })()}
              </div>
              <h1 className="text-sm font-semibold">{tabs.find((t) => t.id === adminTab)?.label || 'Dashboard'}</h1>
            </div>
          </div>
          <div className="flex items-center gap-2">
            {isSuper ? (
              <Badge className="text-[9px] gap-1 bg-gradient-to-r from-orange-600 to-orange-500 text-white border-0 shadow-sm"><Crown className="h-3 w-3" />Super Admin</Badge>
            ) : (
              <Badge variant="outline" className="text-[9px] gap-1"><Shield className="h-3 w-3 text-primary" />Team Admin</Badge>
            )}
          </div>
        </header>

        <main className="flex-1 overflow-y-auto p-4 lg:p-6">
          {adminTab !== 'dashboard' && (
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setAdminTab('dashboard')}
              className="mb-4 gap-1.5 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:text-orange-300 dark:hover:bg-orange-950/30"
            >
              <ArrowLeft className="h-4 w-4" />
              <span>{language === 'en' ? 'Back to Dashboard' : 'ড্যাশবোর্ডে ফিরুন'}</span>
            </Button>
          )}
          {renderContent()}
        </main>
      </div>
    </div>
  );
}
