import React, { useState, useEffect, useCallback } from 'react';
import {
  ShieldCheck,
  LayoutDashboard,
  Package,
  FolderTree,
  ShoppingBag,
  Tag,
  Users,
  Plus,
  Edit2,
  Trash2,
  CheckCircle2,
  AlertCircle,
  Clock,
  ArrowRight,
  Zap,
  TrendingUp,
  DollarSign,
  Search,
  X,
  ExternalLink,
  Lock,
  Eye,
  RefreshCw,
  Sparkles,
  BookOpen
} from 'lucide-react';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
import { api } from '../services/api';
import type { Product, Category, Coupon, Order, User, DashboardStats, OrderStatus, PaymentStatus, Tutorial } from '../types';
import { formatPrice, formatDate, getOrderStatusBadge, toPersianDigits } from '../utils/formatters';

interface AdminPanelProps {
  onBackToStore: () => void;
  onRefreshData?: () => void;
}

export const AdminPanel: React.FC<AdminPanelProps> = ({ onBackToStore, onRefreshData }) => {
  const { user, isAdmin, openAuthModal } = useAuth();
  const { success, error, info } = useToast();

  const [activeTab, setActiveTab] = useState<'dashboard' | 'products' | 'categories' | 'orders' | 'coupons' | 'users' | 'tutorials'>('dashboard');
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [orders, setOrders] = useState<Order[]>([]);
  const [coupons, setCoupons] = useState<Coupon[]>([]);
  const [usersList, setUsersList] = useState<User[]>([]);
  const [tutorials, setTutorials] = useState<Tutorial[]>([]);
  const [loading, setLoading] = useState(false);

  // Modal / Form States
  const [editingProduct, setEditingProduct] = useState<Partial<Product> | null>(null);
  const [editingCategory, setEditingCategory] = useState<Partial<Category> | null>(null);
  const [editingCoupon, setEditingCoupon] = useState<Partial<Coupon> | null>(null);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [newLicenseKey, setNewLicenseKey] = useState('');
  const [deliveryNoteInput, setDeliveryNoteInput] = useState('');
  const [editingTutorial, setEditingTutorial] = useState<Partial<Tutorial> | null>(null);

  // Search filters inside tabs
  const [filterSearch, setFilterSearch] = useState('');

  // Load all admin data
  const loadAdminData = useCallback(async () => {
    if (!isAdmin) return;
    setLoading(true);
    try {
      const [statsRes, prodsRes, catsRes, ordsRes, coupsRes, usrsRes, tutorialsRes] = await Promise.all([
        api.getDashboardStats(),
        api.getProducts({ all: true }),
        api.getCategories(true),
        api.getOrders(),
        api.getCoupons(),
        api.getUsers(),
        api.getTutorials(true),
      ]);
      setStats(statsRes);
      setProducts(prodsRes);
      setCategories(catsRes);
      setOrders(ordsRes);
      setCoupons(coupsRes);
      setUsersList(usrsRes);
      setTutorials(tutorialsRes);
    } catch (err: any) {
      error(err.message || 'خطا در بارگذاری اطلاعات پنل مدیریت');
    } finally {
      setLoading(false);
    }
  }, [isAdmin, error]);

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

  // Guard if not admin
  if (!isAdmin) {
    return (
      <div className="py-20 max-w-lg mx-auto px-4 text-center space-y-6 text-right">
        <div className="w-16 h-16 rounded-3xl bg-rose-950/60 border border-rose-500/40 text-rose-400 mx-auto flex items-center justify-center shadow-xl">
          <Lock className="w-8 h-8" />
        </div>
        <div className="space-y-2 text-center">
          <h2 className="text-2xl font-black text-white">دسترسی به پنل مدیریت نیازمند ورود ادمین است</h2>
          <p className="text-xs text-zinc-400 leading-relaxed max-w-md mx-auto">
            این بخش فقط برای کاربران دارای نقش Administrator فعال است.
          </p>
        </div>
        <button
          onClick={() => openAuthModal('login')}
          className="w-full py-3 rounded-xl bg-purple-600 hover:bg-purple-500 text-white font-bold text-xs shadow-lg shadow-purple-600/30 transition-all flex items-center justify-center gap-2"
        >
          <ShieldCheck className="w-4 h-4" />
          <span>ورود مدیر</span>
        </button>
        <button
          onClick={onBackToStore}
          className="text-xs text-zinc-400 hover:text-white"
        >
          بازگشت به فروشگاه
        </button>
      </div>
    );
  }

  // --- Product CRUD Handlers ---
  const handleSaveProduct = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingProduct) return;
    try {
      if (editingProduct.id) {
        await api.updateProduct(editingProduct.id, editingProduct);
        success('محصول با موفقیت ویرایش شد');
      } else {
        await api.createProduct(editingProduct);
        success('محصول جدید با موفقیت ایجاد شد');
      }
      setEditingProduct(null);
      loadAdminData();
      if (onRefreshData) onRefreshData();
    } catch (err: any) {
      error(err.message || 'خطا در ذخیره محصول');
    }
  };

  const handleDeleteProduct = async (id: string, title: string) => {
    if (!window.confirm(`آیا از حذف محصول "${title}" اطمینان دارید؟`)) return;
    try {
      await api.deleteProduct(id);
      success('محصول حذف شد');
      loadAdminData();
      if (onRefreshData) onRefreshData();
    } catch (err: any) {
      error(err.message || 'خطا در حذف محصول');
    }
  };

  // --- Category CRUD Handlers ---
  const handleSaveCategory = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingCategory) return;
    try {
      if (editingCategory.id) {
        await api.updateCategory(editingCategory.id, editingCategory);
        success('دسته‌بندی با موفقیت بروزرسانی شد');
      } else {
        await api.createCategory(editingCategory);
        success('دسته‌بندی جدید ایجاد شد');
      }
      setEditingCategory(null);
      loadAdminData();
      if (onRefreshData) onRefreshData();
    } catch (err: any) {
      error(err.message || 'خطا در ذخیره دسته‌بندی');
    }
  };

  const handleDeleteCategory = async (id: string, name: string) => {
    if (!window.confirm(`آیا از حذف دسته‌بندی "${name}" اطمینان دارید؟`)) return;
    try {
      await api.deleteCategory(id);
      success('دسته‌بندی با موفقیت حذف شد');
      loadAdminData();
      if (onRefreshData) onRefreshData();
    } catch (err: any) {
      error(err.message || 'خطا در حذف دسته‌بندی');
    }
  };

  // --- Coupon CRUD Handlers ---
  const handleSaveCoupon = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingCoupon) return;
    try {
      if (editingCoupon.id) {
        await api.updateCoupon(editingCoupon.id, editingCoupon);
        success('کد تخفیف ویرایش شد');
      } else {
        await api.createCoupon(editingCoupon as any);
        success('کد تخفیف جدید ایجاد شد');
      }
      setEditingCoupon(null);
      loadAdminData();
    } catch (err: any) {
      error(err.message || 'خطا در ذخیره کد تخفیف');
    }
  };

  const handleDeleteCoupon = async (id: string, code: string) => {
    if (!window.confirm(`آیا از حذف کد تخفیف "${code}" اطمینان دارید؟`)) return;
    try {
      await api.deleteCoupon(id);
      success('کد تخفیف حذف شد');
      loadAdminData();
    } catch (err: any) {
      error(err.message || 'خطا در حذف کد تخفیف');
    }
  };

  // --- Order Status & Delivery Updates ---
  const handleUpdateOrderStatus = async (orderId: string, status: OrderStatus) => {
    try {
      const updated = await api.updateOrderStatus(orderId, { orderStatus: status });
      success(`وضعیت سفارش به "${getOrderStatusBadge(status).label}" تغییر یافت`);
      if (selectedOrder && selectedOrder.id === orderId) {
        setSelectedOrder(updated);
      }
      loadAdminData();
    } catch (err: any) {
      error(err.message || 'خطا در تغییر وضعیت سفارش');
    }
  };

  const handleAddLicenseToOrder = async () => {
    if (!selectedOrder || !newLicenseKey.trim()) return;
    const currentKeys = selectedOrder.licenseKeys || [];
    const updatedKeys = [...currentKeys, newLicenseKey.trim()];
    try {
      const updated = await api.updateOrderStatus(selectedOrder.id, {
        licenseKeys: updatedKeys,
        orderStatus: 'completed',
        deliveryInstructions: deliveryNoteInput.trim() || selectedOrder.deliveryInstructions,
      });
      setSelectedOrder(updated);
      setNewLicenseKey('');
      success('لایسنس به سفارش افزوده و وضعیت آن تکمیل شد');
      loadAdminData();
    } catch (err: any) {
      error(err.message || 'خطا در ثبت لایسنس');
    }
  };

  // --- Tutorial CRUD ---
  const handleSaveTutorial = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingTutorial) return;
    try {
      if (editingTutorial.id) {
        await api.updateTutorial(editingTutorial.id, editingTutorial);
        success('آموزش با موفقیت ویرایش شد');
      } else {
        await api.createTutorial(editingTutorial);
        success('آموزش جدید اضافه شد');
      }
      setEditingTutorial(null);
      loadAdminData();
    } catch (err: any) { error(err.message || 'خطا در ذخیره آموزش'); }
  };

  const handleDeleteTutorial = async (id: string) => {
    if (!window.confirm('آیا از حذف این آموزش مطمئن هستید؟')) return;
    try {
      await api.deleteTutorial(id);
      success('آموزش حذف شد');
      loadAdminData();
    } catch (err: any) { error(err.message || 'خطا در حذف آموزش'); }
  };

  // --- User Role / Status Updates ---
  const handleToggleUserRole = async (targetUser: User) => {
    const newRole = targetUser.role === 'admin' ? 'user' : 'admin';
    if (!window.confirm(`نقش کاربر "${targetUser.name}" به ${newRole === 'admin' ? 'مدیر (Admin)' : 'کاربر عادی (User)'} تغییر یابد؟`)) return;
    try {
      await api.updateUser(targetUser.id, { role: newRole });
      success('نقش کاربر تغییر یافت');
      loadAdminData();
    } catch (err: any) {
      error(err.message);
    }
  };

  const handleToggleUserActive = async (targetUser: User) => {
    try {
      await api.updateUser(targetUser.id, { isActive: !targetUser.isActive });
      success(targetUser.isActive ? 'کاربر غیرفعال شد' : 'کاربر فعال شد');
      loadAdminData();
    } catch (err: any) {
      error(err.message);
    }
  };

  return (
    <div className="min-h-screen bg-[#090514] py-8 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-right space-y-8">
      
      {/* Top Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-purple-900/40 pb-6">
        <div>
          <div className="flex items-center gap-2">
            <span className="p-1.5 rounded-lg bg-purple-600 text-white">
              <ShieldCheck className="w-5 h-5" />
            </span>
            <h1 className="text-2xl font-black text-white">پنل مدیریت یکپارچه ZaccShop</h1>
          </div>
          <p className="text-xs text-zinc-400 mt-1">
            مدیریت کامل و بدون کدنویسی محصولات، دسته‌بندی‌ها، قیمت‌ها، سفارش‌ها، کاربران و تخفیف‌ها
          </p>
        </div>

        <div className="flex items-center gap-3">
          <button
            onClick={loadAdminData}
            disabled={loading}
            className="p-2.5 rounded-xl bg-[#140c28] border border-purple-500/20 text-xs text-purple-300 hover:text-white transition-colors flex items-center gap-1.5"
            title="بروزرسانی داده‌ها"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
            <span>بروزرسانی</span>
          </button>
          <button
            onClick={onBackToStore}
            className="px-4 py-2.5 rounded-xl bg-purple-600/20 hover:bg-purple-600/40 text-purple-200 border border-purple-500/30 text-xs font-bold transition-all flex items-center gap-1.5"
          >
            <span>مشاهده فروشگاه</span>
            <ArrowRight className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Tabs Navigation */}
      <div className="flex overflow-x-auto gap-2 p-1.5 bg-[#120b24] border border-purple-500/20 rounded-2xl">
        {[
          { id: 'dashboard', label: 'داشبورد آمار', icon: LayoutDashboard },
          { id: 'products', label: `محصولات (${toPersianDigits(products.length)})`, icon: Package },
          { id: 'categories', label: `دسته‌بندی‌ها (${toPersianDigits(categories.length)})`, icon: FolderTree },
          { id: 'orders', label: `سفارش‌ها (${toPersianDigits(orders.length)})`, icon: ShoppingBag },
          { id: 'coupons', label: `کدهای تخفیف (${toPersianDigits(coupons.length)})`, icon: Tag },
          { id: 'users', label: `کاربران (${toPersianDigits(usersList.length)})`, icon: Users },
          { id: 'tutorials', label: `آموزش‌ها (${toPersianDigits(tutorials.length)})`, icon: BookOpen },
        ].map((tab) => {
          const Icon = tab.icon;
          const isActive = activeTab === tab.id;
          return (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as any)}
              className={`flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-bold whitespace-nowrap transition-all ${
                isActive
                  ? 'bg-purple-600 text-white shadow-md shadow-purple-600/30'
                  : 'text-zinc-400 hover:text-white hover:bg-purple-950/40'
              }`}
            >
              <Icon className="w-4 h-4" />
              <span>{tab.label}</span>
            </button>
          );
        })}
      </div>

      {/* --- TAB 1: DASHBOARD --- */}
      {activeTab === 'dashboard' && stats && (
        <div className="space-y-6">
          {/* Top Metric Cards */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="p-5 rounded-2xl bg-[#130b28] border border-purple-500/20 flex items-center justify-between">
              <div>
                <div className="text-xs text-zinc-400 font-medium">فروش کل پرداخت‌شده</div>
                <div className="text-xl font-black text-purple-300 mt-1">{formatPrice(stats.totalSales)}</div>
              </div>
              <div className="w-12 h-12 rounded-xl bg-purple-950 text-purple-400 flex items-center justify-center">
                <DollarSign className="w-6 h-6" />
              </div>
            </div>

            <div className="p-5 rounded-2xl bg-[#130b28] border border-purple-500/20 flex items-center justify-between">
              <div>
                <div className="text-xs text-zinc-400 font-medium">تعداد کل سفارش‌ها</div>
                <div className="text-xl font-black text-white mt-1">{toPersianDigits(stats.totalOrders)} سفارش</div>
              </div>
              <div className="w-12 h-12 rounded-xl bg-indigo-950 text-indigo-400 flex items-center justify-center">
                <ShoppingBag className="w-6 h-6" />
              </div>
            </div>

            <div className="p-5 rounded-2xl bg-[#130b28] border border-purple-500/20 flex items-center justify-between">
              <div>
                <div className="text-xs text-zinc-400 font-medium">در انتظار پردازش/تحویل</div>
                <div className="text-xl font-black text-amber-400 mt-1">{toPersianDigits(stats.pendingOrders)} سفارش</div>
              </div>
              <div className="w-12 h-12 rounded-xl bg-amber-950 text-amber-400 flex items-center justify-center">
                <Clock className="w-6 h-6" />
              </div>
            </div>

            <div className="p-5 rounded-2xl bg-[#130b28] border border-purple-500/20 flex items-center justify-between">
              <div>
                <div className="text-xs text-zinc-400 font-medium">کاربران ثبت‌نامی</div>
                <div className="text-xl font-black text-emerald-400 mt-1">{toPersianDigits(stats.totalUsers)} کاربر</div>
              </div>
              <div className="w-12 h-12 rounded-xl bg-emerald-950 text-emerald-400 flex items-center justify-center">
                <Users className="w-6 h-6" />
              </div>
            </div>
          </div>

          {/* Recent Orders & Top Selling Products */}
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
            
            {/* Recent Orders */}
            <div className="lg:col-span-8 bg-[#120b24] p-5 rounded-2xl border border-purple-500/20 space-y-4">
              <div className="flex items-center justify-between border-b border-purple-900/40 pb-3">
                <h3 className="font-bold text-sm text-white flex items-center gap-2">
                  <ShoppingBag className="w-4 h-4 text-purple-400" />
                  آخرین سفارش‌های ثبت‌شده
                </h3>
                <button
                  onClick={() => setActiveTab('orders')}
                  className="text-xs text-purple-400 hover:text-purple-300"
                >
                  مشاهده همه
                </button>
              </div>

              <div className="overflow-x-auto">
                <table className="w-full text-xs text-right">
                  <thead>
                    <tr className="text-zinc-500 border-b border-purple-900/30">
                      <th className="py-2.5">شماره سفارش</th>
                      <th className="py-2.5">مشتری</th>
                      <th className="py-2.5">مبلغ نهایی</th>
                      <th className="py-2.5">وضعیت</th>
                      <th className="py-2.5">تاریخ</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-purple-900/20 text-zinc-300">
                    {stats.recentOrders.map((ord) => {
                      const badge = getOrderStatusBadge(ord.orderStatus);
                      return (
                        <tr key={ord.id} className="hover:bg-purple-950/20 cursor-pointer" onClick={() => { setSelectedOrder(ord); setActiveTab('orders'); }}>
                          <td className="py-3 font-mono font-bold text-purple-300">{ord.orderNumber}</td>
                          <td className="py-3 font-medium">{ord.guestInfo.name}</td>
                          <td className="py-3 font-bold text-white">{formatPrice(ord.finalTotal)}</td>
                          <td className="py-3">
                            <span className={`px-2 py-0.5 rounded text-[10px] font-bold border ${badge.bg} ${badge.text} ${badge.border}`}>
                              {badge.label}
                            </span>
                          </td>
                          <td className="py-3 text-zinc-500">{formatDate(ord.createdAt)}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Top Products */}
            <div className="lg:col-span-4 bg-[#120b24] p-5 rounded-2xl border border-purple-500/20 space-y-4">
              <h3 className="font-bold text-sm text-white flex items-center gap-2 border-b border-purple-900/40 pb-3">
                <TrendingUp className="w-4 h-4 text-emerald-400" />
                محصولات پرفروش
              </h3>

              <div className="space-y-3">
                {stats.topProducts.map((p, i) => (
                  <div key={p.productId} className="p-3 rounded-xl bg-[#170e30] border border-purple-500/15 flex items-center justify-between text-xs">
                    <div className="min-w-0 flex-1 ml-2">
                      <div className="font-bold text-zinc-200 truncate">{p.title}</div>
                      <div className="text-[11px] text-purple-400 mt-0.5">{toPersianDigits(p.salesCount)} فروش</div>
                    </div>
                    <div className="font-black text-white text-left shrink-0">
                      {formatPrice(p.revenue)}
                    </div>
                  </div>
                ))}
              </div>
            </div>

          </div>
        </div>
      )}

      {/* --- TAB 2: PRODUCTS CRUD --- */}
      {activeTab === 'products' && (
        <div className="space-y-6">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <h2 className="text-lg font-bold text-white">مدیریت محصولات و قیمت‌ها</h2>
            <button
              onClick={() => setEditingProduct({
                title: '',
                slug: '',
                categoryId: categories[0]?.id || '',
                price: 100000,
                originalPrice: undefined,
                discountPercent: undefined,
                description: '',
                features: ['گارانتی اصالت', 'تحویل آنی'],
                tags: ['دیجیتال'],
                image: 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=800&q=80',
                badge: '',
                inStock: true,
                stockCount: 50,
                isFeatured: false,
                isBestSeller: false,
                platform: 'software',
                regions: [],
                deliveryType: 'instant_code',
                deliveryNote: 'کد بلافاصله صادر می‌شود.',
              })}
              className="px-4 py-2.5 rounded-xl bg-purple-600 hover:bg-purple-500 text-white text-xs font-bold transition-colors flex items-center gap-1.5 self-start sm:self-auto shadow-md"
            >
              <Plus className="w-4 h-4" />
              <span>افزودن محصول جدید</span>
            </button>
          </div>

          {/* Products Table */}
          <div className="bg-[#120b24] rounded-2xl border border-purple-500/20 overflow-hidden shadow-xl">
            <div className="overflow-x-auto">
              <table className="w-full text-xs text-right">
                <thead>
                  <tr className="bg-[#180f33] text-zinc-400 border-b border-purple-900/40">
                    <th className="py-3 px-4">تصویر و نام محصول</th>
                    <th className="py-3 px-4">دسته‌بندی</th>
                    <th className="py-3 px-4">قیمت فعلی</th>
                    <th className="py-3 px-4">تخفیف</th>
                    <th className="py-3 px-4">موجودی</th>
                    <th className="py-3 px-4 text-left">عملیات</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-purple-900/20 text-zinc-300">
                  {products.map((prod) => (
                    <tr key={prod.id} className="hover:bg-purple-950/20">
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-3">
                          <img src={prod.image} alt={prod.title} className="w-10 h-10 rounded-lg object-cover bg-purple-950 shrink-0" referrerPolicy="no-referrer" />
                          <div>
                            <div className="font-bold text-white text-sm">{prod.title}</div>
                            <div className="text-[11px] text-zinc-500 font-mono">{prod.slug}</div>
                          </div>
                        </div>
                      </td>
                      <td className="py-3 px-4 font-medium text-purple-300">{prod.categoryName || 'بدون دسته‌بندی'}</td>
                      <td className="py-3 px-4 font-black text-white">{formatPrice(prod.price)}</td>
                      <td className="py-3 px-4">
                        {prod.discountPercent ? (
                          <span className="px-2 py-0.5 rounded bg-rose-950 text-rose-300 font-bold border border-rose-500/30">
                            {toPersianDigits(prod.discountPercent)}٪
                          </span>
                        ) : '-'}
                      </td>
                      <td className="py-3 px-4">
                        {prod.inStock ? (
                          <span className="text-emerald-400 font-medium">موجود ({toPersianDigits(prod.stockCount)})</span>
                        ) : (
                          <span className="text-rose-400 font-medium">ناموجود</span>
                        )}
                      </td>
                      <td className="py-3 px-4 text-left">
                        <div className="flex items-center justify-end gap-2">
                          <button
                            onClick={() => setEditingProduct(prod)}
                            className="p-1.5 rounded-lg bg-purple-950 text-purple-300 hover:text-white border border-purple-500/30"
                            title="ویرایش"
                          >
                            <Edit2 className="w-3.5 h-3.5" />
                          </button>
                          <button
                            onClick={() => handleDeleteProduct(prod.id, prod.title)}
                            className="p-1.5 rounded-lg bg-rose-950 text-rose-300 hover:text-white border border-rose-500/30"
                            title="حذف"
                          >
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Product Edit / Create Modal Form */}
          {editingProduct && (
            <div className="fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4">
              <div onClick={() => setEditingProduct(null)} className="fixed inset-0 bg-black/80 backdrop-blur-sm" />
              <div className="relative w-full max-w-2xl bg-[#110926] border border-purple-500/30 rounded-3xl p-6 sm:p-8 shadow-2xl z-10 text-right max-h-[90vh] overflow-y-auto space-y-5">
                <div className="flex items-center justify-between border-b border-purple-900/40 pb-3">
                  <h3 className="text-lg font-bold text-white">
                    {editingProduct.id ? 'ویرایش محصول' : 'ایجاد محصول جدید'}
                  </h3>
                  <button onClick={() => setEditingProduct(null)} className="p-1 text-zinc-400 hover:text-white">
                    <X className="w-5 h-5" />
                  </button>
                </div>

                <form onSubmit={handleSaveProduct} className="space-y-4 text-xs">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="sm:col-span-2">
                      <label className="block font-bold text-zinc-300 mb-1">عنوان محصول *</label>
                      <input
                        type="text"
                        required
                        value={editingProduct.title || ''}
                        onChange={(e) => setEditingProduct({ ...editingProduct, title: e.target.value })}
                        className="w-full bg-[#0c071a] text-xs text-white p-2.5 rounded-xl border border-purple-500/20"
                      />
                    </div>

                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">اسلاگ (URL Slug)</label>
                      <input
                        type="text"
                        value={editingProduct.slug || ''}
                        onChange={(e) => setEditingProduct({ ...editingProduct, slug: e.target.value })}
                        className="w-full bg-[#0c071a] text-xs text-white p-2.5 rounded-xl border border-purple-500/20 font-mono text-left"
                        dir="ltr"
                      />
                    </div>

                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">دسته‌بندی *</label>
                      <select
                        value={editingProduct.categoryId || ''}
                        onChange={(e) => setEditingProduct({ ...editingProduct, categoryId: e.target.value })}
                        className="w-full bg-[#0c071a] text-xs text-white p-2.5 rounded-xl border border-purple-500/20"
                      >
                        {categories.map((c) => (
                          <option key={c.id} value={c.id}>{c.name}</option>
                        ))}
                      </select>
                    </div>

                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">پلتفرم</label>
                      <select
                        value={editingProduct.platform || ''}
                        onChange={(e) => setEditingProduct({ ...editingProduct, platform: e.target.value as any })}
                        className="w-full bg-[#0c071a] text-xs text-white p-2.5 rounded-xl border border-purple-500/20"
                      >
                        <option value="">بدون پلتفرم</option>
                        <option value="steam">Steam</option>
                        <option value="playstation">PlayStation</option>
                        <option value="xbox">Xbox</option>
                        <option value="software">نرم‌افزار</option>
                        <option value="music">موسیقی</option>
                        <option value="gaming_service">سرویس گیمینگ</option>
                      </select>
                    </div>

                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">ریجن‌های قابل تحویل</label>
                      <input
                        type="text"
                        placeholder="مثال: Global, Ukraine, China"
                        value={(editingProduct.regions || []).join(', ')}
                        onChange={(e) => setEditingProduct({ ...editingProduct, regions: e.target.value.split(',').map(v => v.trim()).filter(Boolean) })}
                        className="w-full bg-[#0c071a] text-xs text-white p-2.5 rounded-xl border border-purple-500/20"
                        dir="ltr"
                      />
                    </div>

                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">قیمت نهایی به تومان *</label>
                      <input
                        type="number"
                        required
                        value={editingProduct.price || ''}
                        onChange={(e) => setEditingProduct({ ...editingProduct, price: Number(e.target.value) })}
                        className="w-full bg-[#0c071a] text-xs text-white p-2.5 rounded-xl border border-purple-500/20 font-mono text-left"
                        dir="ltr"
                      />
                    </div>

                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">قیمت اصلی بدون تخفیف (اختیاری)</label>
                      <input
                        type="number"
                        value={editingProduct.originalPrice || ''}
                        onChange={(e) => setEditingProduct({ ...editingProduct, originalPrice: e.target.value ? Number(e.target.value) : undefined })}
                        className="w-full bg-[#0c071a] text-xs text-white p-2.5 rounded-xl border border-purple-500/20 font-mono text-left"
                        dir="ltr"
                      />
                    </div>

                    <div className="sm:col-span-2">
                      <label className="block font-bold text-zinc-300 mb-1">آدرس تصویر محصول (Image URL)</label>
                      <input
                        type="text"
                        value={editingProduct.image || ''}
                        onChange={(e) => setEditingProduct({ ...editingProduct, image: e.target.value })}
                        className="w-full bg-[#0c071a] text-xs text-white p-2.5 rounded-xl border border-purple-500/20 font-mono text-left"
                        dir="ltr"
                      />
                    </div>

                    <div className="sm:col-span-2">
                      <label className="block font-bold text-zinc-300 mb-1">توضیحات کامل محصول</label>
                      <textarea
                        rows={3}
                        value={editingProduct.description || ''}
                        onChange={(e) => setEditingProduct({ ...editingProduct, description: e.target.value })}
                        className="w-full bg-[#0c071a] text-xs text-white p-2.5 rounded-xl border border-purple-500/20 leading-relaxed"
                      />
                    </div>

                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">بج اختصاصی (مثال: پرفروش، ویژه)</label>
                      <input
                        type="text"
                        value={editingProduct.badge || ''}
                        onChange={(e) => setEditingProduct({ ...editingProduct, badge: e.target.value })}
                        className="w-full bg-[#0c071a] text-xs text-white p-2.5 rounded-xl border border-purple-500/20"
                      />
                    </div>

                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">موجودی انبار</label>
                      <input
                        type="number"
                        value={editingProduct.stockCount || 10}
                        onChange={(e) => setEditingProduct({ ...editingProduct, stockCount: Number(e.target.value) })}
                        className="w-full bg-[#0c071a] text-xs text-white p-2.5 rounded-xl border border-purple-500/20 font-mono text-left"
                        dir="ltr"
                      />
                    </div>

                    <div className="sm:col-span-2 flex items-center gap-6 pt-2">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={editingProduct.inStock ?? true}
                          onChange={(e) => setEditingProduct({ ...editingProduct, inStock: e.target.checked })}
                          className="w-4 h-4 accent-purple-500"
                        />
                        <span className="font-bold text-zinc-300">موجود برای فروش</span>
                      </label>

                      <label className="flex items-center gap-2 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={editingProduct.isFeatured ?? false}
                          onChange={(e) => setEditingProduct({ ...editingProduct, isFeatured: e.target.checked })}
                          className="w-4 h-4 accent-purple-500"
                        />
                        <span className="font-bold text-zinc-300">نمایش در محصولات ویژه</span>
                      </label>
                    </div>
                  </div>

                  <div className="flex justify-end gap-2 pt-4 border-t border-purple-900/40">
                    <button
                      type="button"
                      onClick={() => setEditingProduct(null)}
                      className="px-4 py-2 rounded-xl bg-[#140c28] text-zinc-300 hover:text-white"
                    >
                      انصراف
                    </button>
                    <button
                      type="submit"
                      className="px-6 py-2 rounded-xl bg-purple-600 hover:bg-purple-500 text-white font-bold"
                    >
                      ذخیره محصول در دیتابیس
                    </button>
                  </div>
                </form>
              </div>
            </div>
          )}
        </div>
      )}

      {/* --- TAB: TUTORIALS CRUD --- */}
      {activeTab === 'tutorials' && (
        <div className="space-y-6">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div>
              <h2 className="text-lg font-bold text-white">مدیریت آموزش‌های WireGuard</h2>
              <p className="text-xs text-zinc-400 mt-1">لینک آپارات را وارد کن؛ ویدیو داخل سایت نمایش داده می‌شود و لینک مستقیم آپارات هم همیشه در دسترس مشتری خواهد بود.</p>
            </div>
            <button onClick={() => setEditingTutorial({ title: '', platform: 'Windows', description: '', aparatUrl: '', embedUrl: '', thumbnail: '', active: true })} className="px-4 py-2.5 rounded-xl bg-purple-600 hover:bg-purple-500 text-white text-xs font-bold flex items-center gap-2">
              <Plus className="w-4 h-4" /> افزودن آموزش
            </button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {tutorials.map(t => (
              <div key={t.id} className="rounded-2xl border border-purple-500/15 bg-[#120b24] p-4 space-y-3">
                <div className="flex items-center justify-between gap-3">
                  <span className="px-2 py-1 rounded-lg bg-purple-500/10 text-purple-300 text-[11px] font-bold">{t.platform}</span>
                  <span className={`text-[11px] font-bold ${t.active ? 'text-emerald-400' : 'text-zinc-500'}`}>{t.active ? 'فعال' : 'غیرفعال'}</span>
                </div>
                <h3 className="font-black text-white text-sm">{t.title}</h3>
                <p className="text-xs text-zinc-500 leading-6 min-h-12">{t.description || 'بدون توضیحات'}</p>
                <div className="text-[11px] text-zinc-500 truncate" dir="ltr">{t.aparatUrl || 'لینک آپارات هنوز وارد نشده'}</div>
                <div className="flex gap-2 pt-1">
                  <button onClick={() => setEditingTutorial(t)} className="flex-1 py-2 rounded-xl bg-purple-500/10 text-purple-200 hover:bg-purple-500/20 text-xs font-bold flex items-center justify-center gap-1"><Edit2 className="w-3.5 h-3.5" /> ویرایش</button>
                  <button onClick={() => handleDeleteTutorial(t.id)} className="px-3 py-2 rounded-xl bg-rose-500/10 text-rose-300 hover:bg-rose-500/20"><Trash2 className="w-3.5 h-3.5" /></button>
                </div>
              </div>
            ))}
          </div>

          {editingTutorial && (
            <div className="rounded-3xl border border-purple-500/20 bg-[#120b24] p-5 sm:p-7">
              <div className="flex items-center justify-between mb-5">
                <h3 className="font-black text-white">{editingTutorial.id ? 'ویرایش آموزش' : 'افزودن آموزش جدید'}</h3>
                <button onClick={() => setEditingTutorial(null)} className="text-zinc-400 hover:text-white"><X className="w-5 h-5" /></button>
              </div>
              <form onSubmit={handleSaveTutorial} className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
                <div><label className="block text-zinc-300 font-bold mb-1">عنوان آموزش *</label><input required value={editingTutorial.title || ''} onChange={e => setEditingTutorial({...editingTutorial,title:e.target.value})} className="w-full bg-[#0c071a] text-white p-3 rounded-xl border border-purple-500/20" /></div>
                <div><label className="block text-zinc-300 font-bold mb-1">پلتفرم *</label><select value={editingTutorial.platform || 'Windows'} onChange={e => setEditingTutorial({...editingTutorial,platform:e.target.value as Tutorial['platform']})} className="w-full bg-[#0c071a] text-white p-3 rounded-xl border border-purple-500/20"><option>Windows</option><option>Android</option><option>iOS</option></select></div>
                <div className="md:col-span-2"><label className="block text-zinc-300 font-bold mb-1">لینک مستقیم آپارات *</label><input required value={editingTutorial.aparatUrl || ''} onChange={e => setEditingTutorial({...editingTutorial,aparatUrl:e.target.value})} placeholder="https://www.aparat.com/v/..." dir="ltr" className="w-full bg-[#0c071a] text-white p-3 rounded-xl border border-purple-500/20 font-mono" /></div>
                <div className="md:col-span-2"><label className="block text-zinc-300 font-bold mb-1">لینک Embed آپارات (اختیاری)</label><input value={editingTutorial.embedUrl || ''} onChange={e => setEditingTutorial({...editingTutorial,embedUrl:e.target.value})} placeholder="لینک Embed ویدیو" dir="ltr" className="w-full bg-[#0c071a] text-white p-3 rounded-xl border border-purple-500/20 font-mono" /></div>
                <div className="md:col-span-2"><label className="block text-zinc-300 font-bold mb-1">توضیحات</label><textarea rows={3} value={editingTutorial.description || ''} onChange={e => setEditingTutorial({...editingTutorial,description:e.target.value})} className="w-full bg-[#0c071a] text-white p-3 rounded-xl border border-purple-500/20" /></div>
                <div className="md:col-span-2"><label className="block text-zinc-300 font-bold mb-1">Thumbnail URL (اختیاری)</label><input value={editingTutorial.thumbnail || ''} onChange={e => setEditingTutorial({...editingTutorial,thumbnail:e.target.value})} dir="ltr" className="w-full bg-[#0c071a] text-white p-3 rounded-xl border border-purple-500/20 font-mono" /></div>
                <label className="flex items-center gap-2 text-zinc-300 font-bold"><input type="checkbox" checked={editingTutorial.active ?? true} onChange={e => setEditingTutorial({...editingTutorial,active:e.target.checked})} className="accent-purple-500" /> نمایش در سایت</label>
                <div className="md:col-span-2 flex justify-end gap-2 pt-3 border-t border-purple-900/40"><button type="button" onClick={() => setEditingTutorial(null)} className="px-4 py-2 rounded-xl bg-[#0c071a] text-zinc-300">انصراف</button><button type="submit" className="px-5 py-2 rounded-xl bg-purple-600 hover:bg-purple-500 text-white font-bold">ذخیره آموزش</button></div>
              </form>
            </div>
          )}
        </div>
      )}

      {/* --- TAB 3: CATEGORIES CRUD --- */}
      {activeTab === 'categories' && (
        <div className="space-y-6">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div>
              <h2 className="text-lg font-bold text-white">مدیریت دسته‌بندی‌ها</h2>
              <p className="text-xs text-zinc-400">می‌توانید بدون تغییر کد هر زمان دسته‌بندی‌های جدید (مثل AI Tools, VPN, Game) اضافه کنید.</p>
            </div>
            <button
              onClick={() => setEditingCategory({
                name: '',
                slug: '',
                icon: 'Sparkles',
                description: '',
                isActive: true,
                sortOrder: categories.length + 1,
              })}
              className="px-4 py-2.5 rounded-xl bg-purple-600 hover:bg-purple-500 text-white text-xs font-bold transition-colors flex items-center gap-1.5 self-start sm:self-auto shadow-md"
            >
              <Plus className="w-4 h-4" />
              <span>افزودن دسته‌بندی جدید</span>
            </button>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {categories.map((cat) => (
              <div key={cat.id} className="p-4 rounded-2xl bg-[#120b24] border border-purple-500/20 space-y-3 flex flex-col justify-between">
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-bold text-white text-sm">{cat.name}</span>
                    <span className="text-[11px] px-2 py-0.5 rounded bg-purple-950 text-purple-300 border border-purple-500/20 font-mono">
                      {cat.icon}
                    </span>
                  </div>
                  <p className="text-xs text-zinc-400">{cat.description || 'بدون توضیحات'}</p>
                  <div className="text-[11px] text-zinc-500 font-mono mt-1">/{cat.slug}</div>
                </div>

                <div className="flex items-center justify-between pt-3 border-t border-purple-900/30">
                  <span className="text-xs text-zinc-400">{toPersianDigits(cat.productCount || 0)} محصول فعال</span>
                  <div className="flex gap-2">
                    <button
                      onClick={() => setEditingCategory(cat)}
                      className="p-1.5 rounded-lg bg-purple-950 text-purple-300 hover:text-white border border-purple-500/30"
                      title="ویرایش"
                    >
                      <Edit2 className="w-3.5 h-3.5" />
                    </button>
                    <button
                      onClick={() => handleDeleteCategory(cat.id, cat.name)}
                      className="p-1.5 rounded-lg bg-rose-950 text-rose-300 hover:text-white border border-rose-500/30"
                      title="حذف"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* Category Modal */}
          {editingCategory && (
            <div className="fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4">
              <div onClick={() => setEditingCategory(null)} className="fixed inset-0 bg-black/80 backdrop-blur-sm" />
              <div className="relative w-full max-w-md bg-[#110926] border border-purple-500/30 rounded-3xl p-6 shadow-2xl z-10 text-right space-y-4">
                <div className="flex items-center justify-between border-b border-purple-900/40 pb-2">
                  <h3 className="text-base font-bold text-white">
                    {editingCategory.id ? 'ویرایش دسته‌بندی' : 'افزودن دسته‌بندی جدید'}
                  </h3>
                  <button onClick={() => setEditingCategory(null)} className="p-1 text-zinc-400 hover:text-white">
                    <X className="w-4 h-4" />
                  </button>
                </div>

                <form onSubmit={handleSaveCategory} className="space-y-3 text-xs">
                  <div>
                    <label className="block font-bold text-zinc-300 mb-1">نام دسته‌بندی *</label>
                    <input
                      type="text"
                      required
                      placeholder="مثال: هوش مصنوعی و VPN"
                      value={editingCategory.name || ''}
                      onChange={(e) => setEditingCategory({ ...editingCategory, name: e.target.value })}
                      className="w-full bg-[#0c071a] p-2.5 rounded-xl border border-purple-500/20 text-white"
                    />
                  </div>

                  <div>
                    <label className="block font-bold text-zinc-300 mb-1">اسلاگ لاتین (URL Slug)</label>
                    <input
                      type="text"
                      placeholder="ai-vpn-tools"
                      value={editingCategory.slug || ''}
                      onChange={(e) => setEditingCategory({ ...editingCategory, slug: e.target.value })}
                      className="w-full bg-[#0c071a] p-2.5 rounded-xl border border-purple-500/20 text-white font-mono text-left"
                      dir="ltr"
                    />
                  </div>

                  <div>
                    <label className="block font-bold text-zinc-300 mb-1">نام آیکون (Lucide Icon)</label>
                    <select
                      value={editingCategory.icon || 'Folder'}
                      onChange={(e) => setEditingCategory({ ...editingCategory, icon: e.target.value })}
                      className="w-full bg-[#0c071a] p-2.5 rounded-xl border border-purple-500/20 text-white"
                    >
                      <option value="Sparkles">Sparkles (هوش مصنوعی / نرم‌افزار)</option>
                      <option value="Gamepad2">Gamepad2 (بازی استیم / PC)</option>
                      <option value="Tv2">Tv2 (پلی‌استیشن / کنسول)</option>
                      <option value="Zap">Zap (کاهش پینگ / سرعت)</option>
                      <option value="Headphones">Headphones (موسیقی و استریم)</option>
                      <option value="Shield">Shield (امنیت و ضد تحریم)</option>
                      <option value="Server">Server (سرور و کلود)</option>
                      <option value="Globe">Globe (سرویس جهانی)</option>
                    </select>
                  </div>

                  <div>
                    <label className="block font-bold text-zinc-300 mb-1">توضیحات کوتاه</label>
                    <input
                      type="text"
                      value={editingCategory.description || ''}
                      onChange={(e) => setEditingCategory({ ...editingCategory, description: e.target.value })}
                      className="w-full bg-[#0c071a] p-2.5 rounded-xl border border-purple-500/20 text-white"
                    />
                  </div>

                  <div className="flex justify-end gap-2 pt-3 border-t border-purple-900/40">
                    <button
                      type="button"
                      onClick={() => setEditingCategory(null)}
                      className="px-4 py-2 rounded-xl bg-[#140c28] text-zinc-300"
                    >
                      انصراف
                    </button>
                    <button
                      type="submit"
                      className="px-5 py-2 rounded-xl bg-purple-600 hover:bg-purple-500 text-white font-bold"
                    >
                      ذخیره دسته‌بندی
                    </button>
                  </div>
                </form>
              </div>
            </div>
          )}
        </div>
      )}

      {/* --- TAB 4: ORDERS MANAGEMENT --- */}
      {activeTab === 'orders' && (
        <div className="space-y-6">
          <h2 className="text-lg font-bold text-white">مدیریت سفارش‌ها و تحویل دیجیتال</h2>

          <div className="bg-[#120b24] rounded-2xl border border-purple-500/20 overflow-hidden shadow-xl">
            <div className="overflow-x-auto">
              <table className="w-full text-xs text-right">
                <thead>
                  <tr className="bg-[#180f33] text-zinc-400 border-b border-purple-900/40">
                    <th className="py-3 px-4">کد سفارش</th>
                    <th className="py-3 px-4">مشتری و تماس</th>
                    <th className="py-3 px-4">اقلام سفارش</th>
                    <th className="py-3 px-4">مبلغ کل</th>
                    <th className="py-3 px-4">وضعیت سفارش</th>
                    <th className="py-3 px-4 text-left">عملیات</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-purple-900/20 text-zinc-300">
                  {orders.map((ord) => {
                    const badge = getOrderStatusBadge(ord.orderStatus);
                    return (
                      <tr key={ord.id} className="hover:bg-purple-950/20">
                        <td className="py-3 px-4 font-mono font-bold text-purple-300">{ord.orderNumber}</td>
                        <td className="py-3 px-4">
                          <div className="font-bold text-white">{ord.guestInfo.name}</div>
                          <div className="text-[11px] text-zinc-400 font-mono" dir="ltr">{ord.guestInfo.mobile}</div>
                        </td>
                        <td className="py-3 px-4">
                          <div className="max-w-xs truncate">
                            {ord.items.map(i => `${i.title} (${toPersianDigits(i.quantity)})`).join('، ')}
                          </div>
                        </td>
                        <td className="py-3 px-4 font-bold text-white">{formatPrice(ord.finalTotal)}</td>
                        <td className="py-3 px-4">
                          <span className={`px-2 py-0.5 rounded text-[10px] font-bold border ${badge.bg} ${badge.text} ${badge.border}`}>
                            {badge.label}
                          </span>
                        </td>
                        <td className="py-3 px-4 text-left">
                          <button
                            onClick={() => setSelectedOrder(ord)}
                            className="px-3 py-1.5 rounded-lg bg-purple-950 text-purple-300 hover:text-white border border-purple-500/30 text-xs font-semibold"
                          >
                            مشاهده و تحویل
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>

          {/* Order Details & License Delivery Modal */}
          {selectedOrder && (
            <div className="fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4">
              <div onClick={() => setSelectedOrder(null)} className="fixed inset-0 bg-black/80 backdrop-blur-sm" />
              <div className="relative w-full max-w-2xl bg-[#110926] border border-purple-500/30 rounded-3xl p-6 sm:p-8 shadow-2xl z-10 text-right max-h-[90vh] overflow-y-auto space-y-6">
                
                <div className="flex items-center justify-between border-b border-purple-900/40 pb-3">
                  <div>
                    <h3 className="text-lg font-bold text-white">جزئیات کامل سفارش {selectedOrder.orderNumber}</h3>
                    <div className="text-xs text-zinc-400">{formatDate(selectedOrder.createdAt)}</div>
                  </div>
                  <button onClick={() => setSelectedOrder(null)} className="p-1 text-zinc-400 hover:text-white">
                    <X className="w-5 h-5" />
                  </button>
                </div>

                {/* Customer Details */}
                <div className="grid grid-cols-2 gap-3 p-4 rounded-2xl bg-[#170e30] border border-purple-500/15 text-xs">
                  <div>
                    <span className="text-zinc-400">نام مشتری: </span>
                    <span className="font-bold text-white">{selectedOrder.guestInfo.name}</span>
                  </div>
                  <div>
                    <span className="text-zinc-400">شماره تماس: </span>
                    <span className="font-mono text-white" dir="ltr">{selectedOrder.guestInfo.mobile}</span>
                  </div>
                  <div>
                    <span className="text-zinc-400">ایمیل: </span>
                    <span className="font-mono text-white" dir="ltr">{selectedOrder.guestInfo.email || '-'}</span>
                  </div>
                  <div>
                    <span className="text-zinc-400">روش پرداخت: </span>
                    <span className="text-purple-300 font-bold">{selectedOrder.paymentMethod}</span>
                  </div>
                  {selectedOrder.guestInfo.notes && (
                    <div className="col-span-2 pt-2 border-t border-purple-900/30">
                      <span className="text-zinc-400">یادداشت مشتری: </span>
                      <span className="text-zinc-200">{selectedOrder.guestInfo.notes}</span>
                    </div>
                  )}
                </div>

                <div className="flex flex-wrap gap-2">
                  {selectedOrder.guestInfo.email && (
                    <a
                      href={`mailto:${selectedOrder.guestInfo.email}?subject=ZaccShop - ${selectedOrder.orderNumber}`}
                      className="px-3 py-2 rounded-xl bg-purple-600/15 border border-purple-500/25 text-purple-200 text-xs font-bold hover:bg-purple-600/25 transition-colors"
                    >
                      ارسال ایمیل به مشتری
                    </a>
                  )}
                  <a
                    href={`https://t.me/${(import.meta.env.VITE_SUPPORT_TELEGRAM_ID || 'ZaccShopSupport').replace(/^@/, '')}`}
                    target="_blank"
                    rel="noreferrer"
                    className="px-3 py-2 rounded-xl bg-[#229ED9]/10 border border-[#229ED9]/20 text-sky-300 text-xs font-bold hover:bg-[#229ED9]/20 transition-colors"
                  >
                    باز کردن پشتیبانی تلگرام
                  </a>
                </div>

                {/* Items */}
                <div className="space-y-2 text-xs">
                  <div className="font-bold text-zinc-300">محصولات سفارش:</div>
                  {selectedOrder.items.map((item, idx) => (
                    <div key={idx} className="flex items-center justify-between p-2.5 rounded-xl bg-[#0c071a] border border-purple-500/10">
                      <div className="flex items-center gap-2.5">
                        <img src={item.image} alt={item.title} className="w-8 h-8 rounded-lg object-cover bg-purple-950" />
                        <div>
                          <span className="font-bold text-zinc-200">{item.title}</span>
                          <span className="text-zinc-500 mr-2">({toPersianDigits(item.quantity)} عدد)</span>
                        </div>
                      </div>
                      <span className="font-bold text-purple-300">{formatPrice(item.price * item.quantity)}</span>
                    </div>
                  ))}
                </div>

                {/* Status Changer */}
                <div className="space-y-2 text-xs pt-2">
                  <label className="font-bold text-zinc-300">تغییر وضعیت سفارش:</label>
                  <div className="flex flex-wrap gap-2">
                    {[
                      { id: 'pending_payment', label: 'در انتظار پرداخت' },
                      { id: 'processing', label: 'در حال پردازش' },
                      { id: 'completed', label: 'تکمیل و تحویل شد' },
                      { id: 'cancelled', label: 'لغو شده' },
                    ].map((st) => (
                      <button
                        key={st.id}
                        onClick={() => handleUpdateOrderStatus(selectedOrder.id, st.id as any)}
                        className={`px-3 py-1.5 rounded-lg font-bold transition-all ${
                          selectedOrder.orderStatus === st.id
                            ? 'bg-purple-600 text-white shadow'
                            : 'bg-[#150e2d] text-zinc-400 hover:text-white'
                        }`}
                      >
                        {st.label}
                      </button>
                    ))}
                  </div>
                </div>

                {/* License Delivery Section */}
                <div className="p-4 rounded-2xl bg-[#0c071a] border border-purple-500/20 space-y-3 text-xs">
                  <div className="font-bold text-emerald-400 flex items-center gap-1.5">
                    <Zap className="w-4 h-4" />
                    صدور و تخصیص لایسنس دیجیتال یا کانفیگ:
                  </div>

                  {selectedOrder.licenseKeys && selectedOrder.licenseKeys.length > 0 && (
                    <div className="space-y-1.5">
                      {selectedOrder.licenseKeys.map((k, i) => (
                        <div key={i} className="p-2 bg-[#170e30] rounded-lg font-mono text-purple-200 select-all break-all">
                          {k}
                        </div>
                      ))}
                    </div>
                  )}

                  <div className="flex gap-2">
                    <input
                      type="text"
                      placeholder="کد لایسنس یا اکانت جدید..."
                      value={newLicenseKey}
                      onChange={(e) => setNewLicenseKey(e.target.value)}
                      className="flex-1 bg-[#150e2d] text-white p-2 rounded-xl border border-purple-500/20 font-mono text-left"
                      dir="ltr"
                    />
                    <button
                      onClick={handleAddLicenseToOrder}
                      disabled={!newLicenseKey.trim()}
                      className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold disabled:opacity-50"
                    >
                      افزودن و تحویل
                    </button>
                  </div>
                </div>

              </div>
            </div>
          )}
        </div>
      )}

      {/* --- TAB 5: COUPONS --- */}
      {activeTab === 'coupons' && (
        <div className="space-y-6">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <h2 className="text-lg font-bold text-white">مدیریت کدهای تخفیف (Coupon Codes)</h2>
            <button
              onClick={() => setEditingCoupon({
                code: '',
                discountType: 'percent',
                discountValue: 10,
                minPurchase: 100000,
                maxDiscount: 50000,
                maxUses: 100,
                isActive: true,
              })}
              className="px-4 py-2.5 rounded-xl bg-purple-600 hover:bg-purple-500 text-white text-xs font-bold transition-colors flex items-center gap-1.5 self-start sm:self-auto shadow-md"
            >
              <Plus className="w-4 h-4" />
              <span>ایجاد کد تخفیف جدید</span>
            </button>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {coupons.map((c) => (
              <div key={c.id} className="p-4 rounded-2xl bg-[#120b24] border border-purple-500/20 space-y-3">
                <div className="flex items-center justify-between">
                  <span className="font-mono text-base font-black text-purple-300 tracking-wider bg-purple-950/80 px-2.5 py-1 rounded-lg border border-purple-500/30">
                    {c.code}
                  </span>
                  <span className="text-xs font-bold text-emerald-400">
                    {c.discountType === 'percent' ? `${toPersianDigits(c.discountValue)}٪ تخفیف` : formatPrice(c.discountValue)}
                  </span>
                </div>

                <div className="space-y-1 text-xs text-zinc-400">
                  <div>حداقل خرید: {formatPrice(c.minPurchase)}</div>
                  {c.maxDiscount && <div>سقف تخفیف: {formatPrice(c.maxDiscount)}</div>}
                  <div>استفاده شده: {toPersianDigits(c.usedCount)} از {toPersianDigits(c.maxUses)} بار</div>
                </div>

                <div className="flex items-center justify-between pt-3 border-t border-purple-900/30">
                  <span className={`text-[11px] font-bold ${c.isActive ? 'text-emerald-400' : 'text-zinc-500'}`}>
                    {c.isActive ? 'فعال' : 'غیرفعال'}
                  </span>
                  <div className="flex gap-2">
                    <button
                      onClick={() => setEditingCoupon(c)}
                      className="p-1.5 rounded-lg bg-purple-950 text-purple-300 hover:text-white border border-purple-500/30"
                    >
                      <Edit2 className="w-3.5 h-3.5" />
                    </button>
                    <button
                      onClick={() => handleDeleteCoupon(c.id, c.code)}
                      className="p-1.5 rounded-lg bg-rose-950 text-rose-300 hover:text-white border border-rose-500/30"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* Coupon Modal Form */}
          {editingCoupon && (
            <div className="fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4">
              <div onClick={() => setEditingCoupon(null)} className="fixed inset-0 bg-black/80 backdrop-blur-sm" />
              <div className="relative w-full max-w-md bg-[#110926] border border-purple-500/30 rounded-3xl p-6 shadow-2xl z-10 text-right space-y-4">
                <div className="flex items-center justify-between border-b border-purple-900/40 pb-2">
                  <h3 className="text-base font-bold text-white">
                    {editingCoupon.id ? 'ویرایش کد تخفیف' : 'ایجاد کد تخفیف جدید'}
                  </h3>
                  <button onClick={() => setEditingCoupon(null)} className="p-1 text-zinc-400 hover:text-white">
                    <X className="w-4 h-4" />
                  </button>
                </div>

                <form onSubmit={handleSaveCoupon} className="space-y-3 text-xs">
                  <div>
                    <label className="block font-bold text-zinc-300 mb-1">کد کوپن (لاتین) *</label>
                    <input
                      type="text"
                      required
                      placeholder="SUMMER2025"
                      value={editingCoupon.code || ''}
                      onChange={(e) => setEditingCoupon({ ...editingCoupon, code: e.target.value })}
                      className="w-full bg-[#0c071a] p-2.5 rounded-xl border border-purple-500/20 text-white font-mono uppercase text-left"
                      dir="ltr"
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">نوع تخفیف</label>
                      <select
                        value={editingCoupon.discountType || 'percent'}
                        onChange={(e) => setEditingCoupon({ ...editingCoupon, discountType: e.target.value as any })}
                        className="w-full bg-[#0c071a] p-2.5 rounded-xl border border-purple-500/20 text-white"
                      >
                        <option value="percent">درصدی (%)</option>
                        <option value="fixed">مبلغ ثابت (تومان)</option>
                      </select>
                    </div>

                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">مقدار تخفیف *</label>
                      <input
                        type="number"
                        required
                        value={editingCoupon.discountValue || ''}
                        onChange={(e) => setEditingCoupon({ ...editingCoupon, discountValue: Number(e.target.value) })}
                        className="w-full bg-[#0c071a] p-2.5 rounded-xl border border-purple-500/20 text-white font-mono text-left"
                        dir="ltr"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">حداقل خرید (تومان)</label>
                      <input
                        type="number"
                        value={editingCoupon.minPurchase || ''}
                        onChange={(e) => setEditingCoupon({ ...editingCoupon, minPurchase: Number(e.target.value) })}
                        className="w-full bg-[#0c071a] p-2.5 rounded-xl border border-purple-500/20 text-white font-mono text-left"
                        dir="ltr"
                      />
                    </div>

                    <div>
                      <label className="block font-bold text-zinc-300 mb-1">سقف تخفیف (تومان)</label>
                      <input
                        type="number"
                        value={editingCoupon.maxDiscount || ''}
                        onChange={(e) => setEditingCoupon({ ...editingCoupon, maxDiscount: e.target.value ? Number(e.target.value) : undefined })}
                        className="w-full bg-[#0c071a] p-2.5 rounded-xl border border-purple-500/20 text-white font-mono text-left"
                        dir="ltr"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block font-bold text-zinc-300 mb-1">حداکثر تعداد استفاده</label>
                    <input
                      type="number"
                      value={editingCoupon.maxUses || 100}
                      onChange={(e) => setEditingCoupon({ ...editingCoupon, maxUses: Number(e.target.value) })}
                      className="w-full bg-[#0c071a] p-2.5 rounded-xl border border-purple-500/20 text-white font-mono text-left"
                      dir="ltr"
                    />
                  </div>

                  <div className="flex justify-end gap-2 pt-3 border-t border-purple-900/40">
                    <button
                      type="button"
                      onClick={() => setEditingCoupon(null)}
                      className="px-4 py-2 rounded-xl bg-[#140c28] text-zinc-300"
                    >
                      انصراف
                    </button>
                    <button
                      type="submit"
                      className="px-5 py-2 rounded-xl bg-purple-600 hover:bg-purple-500 text-white font-bold"
                    >
                      ذخیره کد
                    </button>
                  </div>
                </form>
              </div>
            </div>
          )}
        </div>
      )}

      {/* --- TAB 6: USERS MANAGEMENT --- */}
      {activeTab === 'users' && (
        <div className="space-y-6">
          <h2 className="text-lg font-bold text-white">مدیریت کاربران و نقش‌ها (Role-Based Access Control)</h2>

          <div className="bg-[#120b24] rounded-2xl border border-purple-500/20 overflow-hidden shadow-xl">
            <div className="overflow-x-auto">
              <table className="w-full text-xs text-right">
                <thead>
                  <tr className="bg-[#180f33] text-zinc-400 border-b border-purple-900/40">
                    <th className="py-3 px-4">نام کاربر</th>
                    <th className="py-3 px-4">ایمیل</th>
                    <th className="py-3 px-4">شماره موبایل</th>
                    <th className="py-3 px-4">نقش کاربری</th>
                    <th className="py-3 px-4">وضعیت</th>
                    <th className="py-3 px-4 text-left">عملیات</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-purple-900/20 text-zinc-300">
                  {usersList.map((u) => (
                    <tr key={u.id} className="hover:bg-purple-950/20">
                      <td className="py-3 px-4 font-bold text-white">{u.name}</td>
                      <td className="py-3 px-4 font-mono text-zinc-300" dir="ltr">{u.email}</td>
                      <td className="py-3 px-4 font-mono" dir="ltr">{u.mobile || '-'}</td>
                      <td className="py-3 px-4">
                        <span className={`px-2 py-0.5 rounded text-[10px] font-bold border ${
                          u.role === 'admin'
                            ? 'bg-purple-950 text-purple-300 border-purple-500/40'
                            : 'bg-zinc-900 text-zinc-400 border-zinc-700'
                        }`}>
                          {u.role === 'admin' ? 'مدیر (Admin)' : 'کاربر عادی (User)'}
                        </span>
                      </td>
                      <td className="py-3 px-4">
                        <span className={`text-[11px] font-semibold ${u.isActive ? 'text-emerald-400' : 'text-rose-400'}`}>
                          {u.isActive ? 'فعال' : 'مسدود'}
                        </span>
                      </td>
                      <td className="py-3 px-4 text-left">
                        <div className="flex items-center justify-end gap-2">
                          <button
                            onClick={() => handleToggleUserRole(u)}
                            className="px-2.5 py-1 rounded-lg bg-purple-950 text-purple-300 hover:text-white border border-purple-500/30 text-[11px]"
                          >
                            تغییر به {u.role === 'admin' ? 'User' : 'Admin'}
                          </button>
                          <button
                            onClick={() => handleToggleUserActive(u)}
                            className="px-2.5 py-1 rounded-lg bg-[#140c28] text-zinc-300 hover:text-white border border-purple-500/20 text-[11px]"
                          >
                            {u.isActive ? 'غیرفعال‌سازی' : 'فعال‌سازی'}
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

    </div>
  );
};
