import React, { useState, useEffect } from 'react';
import { 
  User, Shield, Users, Wallet, Key, CreditCard, Ticket, Settings, Home,
  Plus, Server, Activity, ArrowLeftRight, CheckCircle2, AlertTriangle, 
  ExternalLink, Copy, Check, Send, Sparkles, LogOut, Phone, Layers, RefreshCw,
  Award, Share2, Compass, Info, ArrowRight
} from 'lucide-react';

export default function App() {
  const [initData, setInitData] = useState('');
  const [testUserId, setTestUserId] = useState('');
  const [loading, setLoading] = useState(true);
  const [errorMsg, setErrorMsg] = useState('');

  // OTP Login Flow States
  const [loginTab, setLoginTab] = useState('token'); // token, manual
  const [otpCode, setOtpCode] = useState(null);
  const [botUsername, setBotUsername] = useState('');
  const [isVerifyingOtp, setIsVerifyingOtp] = useState(false);
  const [otpTimer, setOtpTimer] = useState(0);

  // Core Data States
  const [user, setUser] = useState(null);
  const [metrics, setMetrics] = useState({ active_configs: 0, active_tickets: 0 });
  const [subscriptions, setSubscriptions] = useState([]);
  const [plans, setPlans] = useState([]);
  const [servers, setServers] = useState([]);
  const [categories, setCategories] = useState([]);
  const [tickets, setTickets] = useState([]);
  const [agentClients, setAgentClients] = useState([]);
  const [allAgentsList, setAllAgentsList] = useState([]);
  const [resellerTab, setResellerTab] = useState('financial-dashboard');
  const [paymentKeys, setPaymentKeys] = useState({ bank_account: '', holder_name: '' });

  // Reseller Custom Config States
  const [customConfigServerId, setCustomConfigServerId] = useState('');
  const [customConfigLoading, setCustomConfigLoading] = useState(false);
  const [customConfigError, setCustomConfigError] = useState('');
  const [customConfigSuccess, setCustomConfigSuccess] = useState(null);
  const [resellerSelectedPlanId, setResellerSelectedPlanId] = useState('');
  const [showBulkPurchaseModal, setShowBulkPurchaseModal] = useState(false);

  // Test Account Issue State
  const [testAccountResult, setTestAccountResult] = useState(null);
  const [isRequestingTest, setIsRequestingTest] = useState(false);

  // Admin Switch Account (Impersonation)
  const [viewAsUserId, setViewAsUserId] = useState('');
  const [activeViewUserId, setActiveViewUserId] = useState(null); // The one currently active

  // Active UI navigation
  const [activeTab, setActiveTab] = useState('user-dashboard'); // user-dashboard, subscriptions, buy-plans, tickets, wallet-charge, reseller-panel, admin-panel
  const [activeTicket, setActiveTicket] = useState(null);
  const [urlTicketId, setUrlTicketId] = useState(null);
  const [ticketMessages, setTicketMessages] = useState([]);
  const [chatUserInfo, setChatUserInfo] = useState(null);
  const [chatAdminInfo, setChatAdminInfo] = useState(null);
  const [chatInput, setChatInput] = useState('');
  const [replyToMessage, setReplyToMessage] = useState(null);
  const [copiedId, setCopiedId] = useState(null);

  // Form States
  const [profileName, setProfileName] = useState('');
  const [profilePhone, setProfilePhone] = useState('');
  const [isSyncingProfile, setIsSyncingProfile] = useState(false);
  const [manualPayAmount, setManualPayAmount] = useState('');
  const [manualPayCard, setManualPayCard] = useState('');
  const [receiptFile, setReceiptFile] = useState(null);
  const [submitPayMsg, setSubmitPayMsg] = useState(null);

  // Purchase States
  const [selectedServerId, setSelectedServerId] = useState('');
  const [selectedCategoryId, setSelectedCategoryId] = useState('');
  const [selectedPlanId, setSelectedPlanId] = useState('');
  const [isPurchasing, setIsPurchasing] = useState(false);
  const [planPurchaseMethod, setPlanPurchaseMethod] = useState('wallet'); // wallet, card
  const [planReceiptFile, setPlanReceiptFile] = useState(null);
  const [planReceiptPreview, setPlanReceiptPreview] = useState('');
  const [planRemark, setPlanRemark] = useState('');
  const [isSubmittingPlanReceipt, setIsSubmittingPlanReceipt] = useState(false);

  // Ticket creation Form
  const [newTicketTitle, setNewTicketTitle] = useState('');
  const [newTicketCategory, setNewTicketCategory] = useState('بررسی کانفیگ');
  const [newTicketText, setNewTicketText] = useState('');
  const [newTicketFile, setNewTicketFile] = useState(null);
  const [newTicketFilePreview, setNewTicketFilePreview] = useState('');
  const [ticketFilter, setTicketFilter] = useState('open'); // open, closed

  // Agent Form
  const [agentVolBuy, setAgentVolBuy] = useState('');
  const [agentMsg, setAgentMsg] = useState(null);

  // Admin View States
  const [adminStats, setAdminStats] = useState(null);
  const [adminPendingReceipts, setAdminPendingReceipts] = useState([]);
  const [adminActiveTickets, setAdminActiveTickets] = useState([]);
  const [adminSearchQuery, setAdminSearchQuery] = useState('');
  const [adminUsersList, setAdminUsersList] = useState([]);
  const [editingUser, setEditingUser] = useState(null);

  const [directTokenInput, setDirectTokenInput] = useState('');

  // Renew, Details & Purchase success Modals
  const [successModalMsg, setSuccessModalMsg] = useState('');
  const [activeRenewConfig, setActiveRenewConfig] = useState(null);
  const [renewPlanId, setRenewPlanId] = useState('');
  const [renewMethod, setRenewMethod] = useState('wallet');
  const [renewReceiptFile, setRenewReceiptFile] = useState(null);
  const [renewReceiptPreview, setRenewReceiptPreview] = useState('');
  const [isRenewing, setIsRenewing] = useState(false);
  const [activeDetailsConfig, setActiveDetailsConfig] = useState(null);
  const [activeQrCodeLink, setActiveQrCodeLink] = useState(null);

  // Rating Modal
  const [showRatingModal, setShowRatingModal] = useState(false);
  const [ratingValue, setRatingValue] = useState(5);

  // Reseller custom config form
  const [showCustomConfigModal, setShowCustomConfigModal] = useState(false);
  const [customConfigServer, setCustomConfigServer] = useState('');
  const [customConfigRemark, setCustomConfigRemark] = useState('');
  const [customConfigVolume, setCustomConfigVolume] = useState('');
  const [customConfigDays, setCustomConfigDays] = useState('');
  const [customConfigLimitIp, setCustomConfigLimitIp] = useState('0');
  const [isCreatingCustomConfig, setIsCreatingCustomConfig] = useState(false);
  const [createdCustomConfigDetails, setCreatedCustomConfigDetails] = useState(null);

  const messagesEndRef = React.useRef(null);

  const scrollToBottom = () => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  };

  useEffect(() => {
    scrollToBottom();
  }, [ticketMessages]);

  // مقداردهی خودکار شناسه پلن متناظر با سرویس در زمان باز شدن مودال تمدید
  useEffect(() => {
    if (activeRenewConfig) {
      setRenewPlanId(activeRenewConfig.fileid || '');
    } else {
      setRenewPlanId('');
    }
  }, [activeRenewConfig]);

  // Load configuration from Telegram WebApp or LocalStorage session token
  useEffect(() => {
    // Check location hash for navigation shortcut (split by ? first to avoid Telegram parameter issues)
    const hashRaw = window.location.hash.replace('#', '').split('?')[0];
    const hashParts = hashRaw.split('-');
    const hash = hashParts[0];
    const targetTicketId = hashParts[1] ? parseInt(hashParts[1]) : null;

    const validTabs = ['user-dashboard', 'subscriptions', 'buy-plans', 'tickets', 'wallet-charge', 'reseller-panel', 'admin-panel'];
    if (hash && validTabs.includes(hash)) {
      setActiveTab(hash);
      if (targetTicketId) {
        setUrlTicketId(targetTicketId);
      }
    }

    // Check URL parameters first (e.g. ?token=XXX&userid=YYY)
    const params = new URLSearchParams(window.location.search);
    const urlToken = params.get('token');
    const urlUserId = params.get('userid');
    if (urlToken && urlUserId) {
      localStorage.setItem('session_token', urlToken);
      localStorage.setItem('session_userid', urlUserId);
      
      // Clean params from URL bar (keep hash if present)
      window.history.replaceState({}, document.title, window.location.pathname + window.location.hash);
      
      setInitData(`token:${urlToken}`);
      setTestUserId(urlUserId);
      fetchDashboardData(`token:${urlToken}`, urlUserId);
      return;
    }

    if (window.Telegram && window.Telegram.WebApp) {
      const tg = window.Telegram.WebApp;
      tg.ready();
      tg.expand();
      
      const rawInitData = tg.initData || '';
      setInitData(rawInitData);
      
      if (rawInitData) {
        fetchDashboardData(rawInitData);
      } else {
        checkStoredSession();
      }
    } else {
      checkStoredSession();
    }
  }, []);

  // Handle hashchange events for in-app navigation
  useEffect(() => {
    const handleHashChange = () => {
      const hashRaw = window.location.hash.replace('#', '').split('?')[0];
      const hashParts = hashRaw.split('-');
      const hash = hashParts[0];
      const targetTicketId = hashParts[1] ? parseInt(hashParts[1]) : null;

      const validTabs = ['user-dashboard', 'subscriptions', 'buy-plans', 'tickets', 'wallet-charge', 'reseller-panel', 'admin-panel'];
      if (hash && validTabs.includes(hash)) {
        setActiveTab(hash);
        if (targetTicketId) {
          setUrlTicketId(targetTicketId);
        }
      }
    };
    window.addEventListener('hashchange', handleHashChange);
    return () => window.removeEventListener('hashchange', handleHashChange);
  }, []);

  // Auto-open ticket from deep-link (e.g. #tickets-123)
  useEffect(() => {
    if (activeTab === 'tickets' && urlTicketId && tickets.length > 0) {
      const ticket = tickets.find(t => parseInt(t.id) === parseInt(urlTicketId));
      if (ticket) {
        setActiveTicket(ticket);
        fetchTicketMessages(ticket.id);
        setUrlTicketId(null); // Clear after opening
      }
    }
  }, [activeTab, urlTicketId, tickets]);

  // Handle Telegram native back button
  useEffect(() => {
    if (window.Telegram && window.Telegram.WebApp) {
      const tg = window.Telegram.WebApp;
      if (activeTab !== 'user-dashboard' || activeTicket) {
        tg.BackButton.show();
        const handleBack = () => {
          if (activeTicket) {
            setActiveTicket(null);
            fetchTickets();
            window.location.hash = 'tickets';
          } else {
            setActiveTab('user-dashboard');
          }
        };
        tg.BackButton.onClick(handleBack);
        return () => {
          tg.BackButton.offClick(handleBack);
          tg.BackButton.hide();
        };
      }
    }
  }, [activeTab, activeTicket]);

  // Sync activeTab and activeTicket to browser window location hash for deep linking
  useEffect(() => {
    if (activeTab) {
      if (activeTab === 'tickets' && activeTicket) {
        window.location.hash = `tickets-${activeTicket.id}`;
      } else {
        window.location.hash = activeTab;
      }
    }
  }, [activeTab, activeTicket]);

  // Fetch agent/reseller dashboard on tab change (for agents AND admins)
  useEffect(() => {
    if (activeTab === 'reseller-panel' && user && (user.is_agent || user.isAdmin)) {
      fetchAgentDashboard();
    }
  }, [activeTab]);

  const checkStoredSession = () => {
    const storedToken = localStorage.getItem('session_token');
    const storedUserId = localStorage.getItem('session_userid');
    if (storedToken && storedUserId) {
      setInitData(`token:${storedToken}`);
      setTestUserId(storedUserId);
      fetchDashboardData(`token:${storedToken}`, storedUserId);
    } else {
      setLoading(false);
    }
  };

  const getApiHeaders = (customInitData) => {
    const data = customInitData || initData;
    return {
      'Content-Type': 'application/json',
      'X-Session-Token': data || '',
      'Authorization': data ? `Bearer ${encodeURIComponent(data)}` : ''
    };
  };

  // Helper for requests (automatically appends viewAsUserId if admin is impersonating)
  const getRequestBody = (body = {}, customInit = null) => {
    const payload = { ...body };
    const data = customInit || initData;
    if (data) {
      payload.auth_data = data;
    }
    if (testUserId && !data.startsWith('token:')) {
      payload.test_user_id = testUserId;
    }
    if (activeViewUserId) {
      payload.view_as_user_id = activeViewUserId;
    }
    return JSON.stringify(payload);
  };

  const fetchDashboardData = async (customInit = null, customUserId = null) => {
    try {
      setLoading(true);
      setErrorMsg('');
      const headers = getApiHeaders(customInit);
      
      const res = await fetch('../api.php', {
        method: 'POST',
        headers,
        body: getRequestBody({}, customInit)
      });
      const data = await res.json();
      
      if (data.error) {
        setErrorMsg(data.error);
        if (data.error.includes('سشن')) {
          localStorage.removeItem('session_token');
          localStorage.removeItem('session_userid');
          setUser(null);
        }
      } else {
        setUser(data.user);
        if (data.session_token) {
          localStorage.setItem('session_token', data.session_token);
          localStorage.setItem('session_userid', data.user.id);
        }
        setMetrics(data.metrics);
        setProfileName(data.user.name || '');
        setProfilePhone(data.user.phone || '');
        if (data.payment_keys) {
          setPaymentKeys(data.payment_keys);
        }
        
        await fetchSubscriptions(customInit);
        await fetchPlans(customInit);
        await fetchTickets(customInit);
        
        if (data.user.is_agent || data.user.isAdmin) {
          await fetchAgentDashboard(customInit);
        }
        if (data.user.isAdmin) {
          await fetchAdminDashboard(customInit);
        }
      }
    } catch (err) {
      setErrorMsg('خطا در ارتباط با سرور. لطفا اتصال اینترنت خود را بررسی کنید.');
    } finally {
      setLoading(false);
    }
  };

  const fetchSubscriptions = async (customInit = null) => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(customInit),
        body: getRequestBody({ action: 'subscriptions' })
      });
      const data = await res.json();
      if (data.subscriptions) setSubscriptions(data.subscriptions);
    } catch (e) { }
  };

  const fetchPlans = async (customInit = null) => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(customInit),
        body: getRequestBody({ action: 'plans' })
      });
      const data = await res.json();
      if (data.plans) setPlans(data.plans);
      if (data.servers) setServers(data.servers);
      if (data.categories) setCategories(data.categories);
    } catch (e) { }
  };

  const fetchTickets = async (customInit = null) => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(customInit),
        body: getRequestBody({ action: 'tickets' })
      });
      const data = await res.json();
      if (data.tickets) setTickets(data.tickets);
    } catch (e) { }
  };

  const fetchTicketMessages = async (chatId) => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({ action: 'ticket_messages', chat_id: chatId })
      });
      const data = await res.json();
      if (data.messages) setTicketMessages(data.messages);
      if (data.chat_user) setChatUserInfo(data.chat_user);
      if (data.chat_admin) setChatAdminInfo(data.chat_admin);
    } catch (e) { }
  };

  const handleRefreshChat = async (chatId) => {
    if (!chatId) return;
    await fetchTicketMessages(chatId);
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({ action: 'tickets' })
      });
      const data = await res.json();
      if (data.tickets) {
        setTickets(data.tickets);
        const updated = data.tickets.find(t => t.id === chatId);
        if (updated) {
          setActiveTicket(updated);
        }
      }
    } catch (e) { }
  };

  const fetchAgentDashboard = async (customInit = null) => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(customInit),
        body: getRequestBody({ action: 'agent_dashboard' })
      });
      const data = await res.json();
      if (data.status === 'success') {
        setUser(prev => ({
          ...prev,
          agent_volume: data.agent.volume,
          agent_limit: data.agent.limit,
          agent_test_limit: data.agent.test_limit
        }));
        setAgentClients(data.clients || []);
        if (data.agents_list) setAllAgentsList(data.agents_list);
      }
    } catch (e) { }
  };

  const handleCreateCustomConfig = async (e) => {
    if (e) e.preventDefault();
    setCustomConfigLoading(true);
    setCustomConfigError('');
    setCustomConfigSuccess(null);

    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'agent_create_custom_config',
          server_id: customConfigServerId,
          remark: customConfigRemark,
          volume: customConfigVolume,
          days: customConfigDays,
          limitip: customConfigLimitIp
        })
      });
      const data = await res.json();
      if (data.error) {
        setCustomConfigError(data.error);
      } else if (data.status === 'success') {
        setCustomConfigSuccess(data.config);
        setCustomConfigRemark('');
        setCustomConfigVolume('');
        setCustomConfigDays('');
        fetchAgentDashboard();
      } else {
        setCustomConfigError('خطای ناشناخته رخ داده است');
      }
    } catch (err) {
      setCustomConfigError('خطا در برقراری ارتباط با سرور');
    } finally {
      setCustomConfigLoading(false);
    }
  };

  const handleCreateTestConfig = async (serverId) => {
    setCustomConfigLoading(true);
    setCustomConfigError('');
    setCustomConfigSuccess(null);

    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'agent_create_test_config',
          server_id: serverId
        })
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else if (data.status === 'success') {
        setCustomConfigSuccess(data.config);
        fetchAgentDashboard();
      }
    } catch (err) {
      alert('خطا در برقراری ارتباط با سرور');
    } finally {
      setCustomConfigLoading(false);
    }
  };

  const handleBuyQuota = async (planId) => {
    if (!confirm('آیا از خرید این سهمیه اطمینان دارید؟')) return;
    setCustomConfigLoading(true);

    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'agent_buy_quota',
          plan_id: planId
        })
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else if (data.status === 'success') {
        alert(data.message || 'خرید سهمیه با موفقیت انجام شد');
        fetchAgentDashboard();
      }
    } catch (err) {
      alert('خطا در برقراری ارتباط با سرور');
    } finally {
      setCustomConfigLoading(false);
    }
  };

  const handleModifyConfig = async (orderId, actionType, val) => {
    const promptMsg = actionType === 'add_volume' 
      ? 'لطفاً مقدار حجم اضافه (به گیگابایت) را وارد کنید:' 
      : 'لطفاً تعداد روزهای اضافه را وارد کنید:';
    
    const inputVal = prompt(promptMsg, val || '');
    if (inputVal === null) return;
    
    const parsedVal = parseFloat(inputVal);
    if (isNaN(parsedVal) || parsedVal <= 0) {
      alert('مقدار وارد شده نامعتبر است');
      return;
    }

    setCustomConfigLoading(true);
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'agent_modify_config',
          order_id: orderId,
          action_type: actionType,
          value: parsedVal
        })
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else if (data.status === 'success') {
        alert(data.message || 'عملیات با موفقیت انجام شد');
        fetchAgentDashboard();
      }
    } catch (err) {
      alert('خطا در برقراری ارتباط');
    } finally {
      setCustomConfigLoading(false);
    }
  };

  const fetchAdminDashboard = async (customInit = null) => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(customInit),
        body: getRequestBody({ action: 'admin_dashboard' })
      });
      const data = await res.json();
      if (data.status === 'success') {
        setAdminStats(data.stats);
        setAdminPendingReceipts(data.pending_receipts);
        setAdminActiveTickets(data.active_tickets);
      }
    } catch (e) { }
  };

  const handleDirectTokenLogin = (e) => {
    e.preventDefault();
    if (!directTokenInput.trim()) return;

    let token = directTokenInput.trim();
    let userid = '';

    // If they pasted the full URL (e.g. https://.../?token=XXX&userid=YYY)
    try {
      if (token.includes('?')) {
        const urlObj = new URL(token);
        const urlToken = urlObj.searchParams.get('token');
        const urlUserId = urlObj.searchParams.get('userid');
        if (urlToken && urlUserId) {
          token = urlToken;
          userid = urlUserId;
        }
      }
    } catch(err) {}

    // Save
    localStorage.setItem('session_token', token);
    if (userid) {
      localStorage.setItem('session_userid', userid);
    }
    
    const authString = `token:${token}`;
    setInitData(authString);
    if (userid) {
      setTestUserId(userid);
    }
    fetchDashboardData(authString, userid || null);
  };

  // Secure OTP login flow
  const handleRequestOtp = async (e) => {
    e.preventDefault();
    setErrorMsg('');
    setOtpCode(null);
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'request_otp', target_user_id: parseInt(testUserId) })
      });
      const data = await res.json();
      if (data.error) {
        setErrorMsg(data.error);
      } else {
        setOtpCode(data.otp);
        setBotUsername(data.bot_username);
        setOtpTimer(300); // 5 minutes timer
        setIsVerifyingOtp(true);
      }
    } catch (err) {
      setErrorMsg('خطا در دریافت کد تایید از سرور.');
    }
  };

  // Check if OTP has been verified
  const handleCheckOtpStatus = async () => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'check_otp_status', target_user_id: parseInt(testUserId) })
      });
      const data = await res.json();
      if (data.verified) {
        localStorage.setItem('session_token', data.token);
        localStorage.setItem('session_userid', testUserId);
        setIsVerifyingOtp(false);
        setOtpCode(null);
        // Login
        const authString = `token:${data.token}`;
        setInitData(authString);
        fetchDashboardData(authString, testUserId);
      } else {
        alert('کد تایید هنوز در ربات تایید نشده است. ابتدا کد را در ربات تلگرام تایید کنید.');
      }
    } catch (err) {
      alert('خطا در ارتباط با سرور.');
    }
  };

  // Request test account
  const handleRequestTestAccount = async () => {
    setIsRequestingTest(true);
    setTestAccountResult(null);
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({ action: 'get_test_account' })
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else {
        setTestAccountResult(data.config);
        // Refresh
        fetchDashboardData();
      }
    } catch (e) {
      alert('خطا در ارتباط با شبکه.');
    } finally {
      setIsRequestingTest(false);
    }
  };

  const handleBuyPlan = async (planId) => {
    if (!planId) return;
    if (window.Telegram?.WebApp?.showConfirm) {
      window.Telegram.WebApp.showConfirm("آیا از خرید این کانفیگ اطمینان دارید؟ هزینه آن از کیف پول شما کسر خواهد شد.", async (approved) => {
        if (approved) {
          await executeBuyPlan(planId);
        }
      });
    } else {
      if (window.confirm("آیا از خرید این کانفیگ اطمینان دارید؟")) {
        await executeBuyPlan(planId);
      }
    }
  };

  const executeBuyPlan = async (planId) => {
    setIsPurchasing(true);
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({ action: 'buy_plan', plan_id: planId })
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else if (data.status === 'success') {
        alert(data.message);
        setSelectedPlanId('');
        setSelectedCategoryId('');
        setSelectedServerId('');
        setActiveTab('subscriptions');
        await fetchDashboardData();
        await fetchSubscriptions();
      }
    } catch (e) {
      alert("خطا در برقراری ارتباط با سرور.");
    } finally {
      setIsPurchasing(false);
    }
  };

  // Price formatter helper
  const formatPrice = (val) => {
    return (val || 0).toLocaleString();
  };

  // Safe Persian date formatter helper
  const formatPersianDate = (timestamp) => {
    if (!timestamp || isNaN(Number(timestamp)) || Number(timestamp) <= 0) return 'نامحدود';
    try {
      const date = new Date(Number(timestamp) * 1000);
      if (isNaN(date.getTime())) return 'نامحدود';
      return date.toLocaleDateString('fa-IR');
    } catch (e) {
      return 'نامحدود';
    }
  };

  const handleCopy = (text, id) => {
    navigator.clipboard.writeText(text);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
    if (window.Telegram && window.Telegram.WebApp) {
      window.Telegram.WebApp.HapticFeedback.notificationOccurred('success');
    }
  };

  const handleProfileSync = async (e) => {
    e.preventDefault();
    setIsSyncingProfile(true);
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'sync_profile',
          name: profileName,
          phone: profilePhone
        })
      });
      const data = await res.json();
      if (data.status === 'success') {
        setUser(prev => ({ ...prev, name: profileName, phone: profilePhone }));
        alert('پروفایل با موفقیت بروزرسانی شد.');
      }
    } catch (err) {
      alert('خطا در ذخیره‌سازی اطلاعات.');
    } finally {
      setIsSyncingProfile(false);
    }
  };

  const handleSubmitReceipt = async (e) => {
    e.preventDefault();
    setSubmitPayMsg(null);
    if (!receiptFile) {
      setSubmitPayMsg({ type: 'danger', text: 'لطفا تصویر رسید را انتخاب یا رها کنید.' });
      return;
    }
    try {
      const formData = new FormData();
      formData.append('action', 'submit_receipt');
      formData.append('amount', manualPayAmount); // Toman
      formData.append('receipt', receiptFile);

      // Auth context fields for Apache-stripped-header fallback compatibility
      if (initData) {
        formData.append('auth_data', initData);
      }
      if (testUserId) {
        formData.append('auth_userid', testUserId);
      }

      const headers = { ...getApiHeaders() };
      delete headers['Content-Type'];
      delete headers['content-type'];

      const res = await fetch('../api.php', {
        method: 'POST',
        headers: headers,
        body: formData
      });
      const data = await res.json();
      if (data.error) {
        setSubmitPayMsg({ type: 'danger', text: data.error });
      } else {
        setSubmitPayMsg({ type: 'success', text: data.message });
        setManualPayAmount('');
        setReceiptFile(null);
        await fetchDashboardData();
      }
    } catch (err) {
      setSubmitPayMsg({ type: 'danger', text: 'خطا در ارتباط با سرور.' });
    }
  };

  const handleSubmitPlanReceipt = async (e) => {
    e.preventDefault();
    if (!selectedPlanId) return;
    if (!planReceiptFile) {
      alert('لطفا تصویر رسید را بارگذاری کنید.');
      return;
    }
    setIsSubmittingPlanReceipt(true);
    try {
      const formData = new FormData();
      formData.append('action', 'submit_plan_receipt');
      formData.append('plan_id', selectedPlanId);
      formData.append('remark', planRemark);
      formData.append('receipt', planReceiptFile);

      if (initData) {
        formData.append('auth_data', initData);
      }
      if (testUserId) {
        formData.append('auth_userid', testUserId);
      }

      const headers = { ...getApiHeaders() };
      delete headers['Content-Type'];
      delete headers['content-type'];

      const res = await fetch('../api.php', {
        method: 'POST',
        headers: headers,
        body: formData
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else {
        setSuccessModalMsg(data.message || 'خرید شما ثبت شد منتظر تایید ادمین بمانید.');
        setPlanReceiptFile(null);
        setPlanReceiptPreview('');
        setPlanRemark('');
        setSelectedPlanId('');
        setSelectedCategoryId('');
        setSelectedServerId('');
      }
    } catch (err) {
      alert('خطا در ارسال اطلاعات به سرور.');
    } finally {
      setIsSubmittingPlanReceipt(false);
    }
  };

  const handleRenewConfigWallet = async (configId, planId) => {
    if (!configId || !planId) return;
    setIsRenewing(true);
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({ action: 'renew_config_wallet', config_id: configId, plan_id: planId })
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else {
        alert(data.message);
        setActiveRenewConfig(null);
        setRenewPlanId('');
        await fetchDashboardData();
        await fetchSubscriptions();
      }
    } catch (e) {
      alert('خطا در ارتباط با سرور.');
    } finally {
      setIsRenewing(false);
    }
  };

  const handleRenewConfigAgent = async (configId, planId) => {
    if (!configId || !planId) return;
    setIsRenewing(true);
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({ action: 'renew_config_agent', config_id: configId, plan_id: planId })
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else {
        alert(data.message);
        setActiveRenewConfig(null);
        setRenewPlanId('');
        await fetchDashboardData();
        await fetchSubscriptions();
      }
    } catch (e) {
      alert('خطا در ارتباط با سرور.');
    } finally {
      setIsRenewing(false);
    }
  };

  const handleSendNpvtFile = async (configId) => {
    if (!configId) return;
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({ action: 'send_npvt', config_id: configId })
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else {
        alert(data.message);
      }
    } catch (e) {
      alert('خطا در ارتباط با سرور.');
    }
  };

  const handleRenewConfigReceipt = async (e) => {
    e.preventDefault();
    if (!activeRenewConfig || !renewPlanId) return;
    if (!renewReceiptFile) {
      alert('لطفا تصویر رسید را بارگذاری کنید.');
      return;
    }
    setIsRenewing(true);
    try {
      const formData = new FormData();
      formData.append('action', 'renew_config_receipt');
      formData.append('config_id', activeRenewConfig.id);
      formData.append('plan_id', renewPlanId);
      formData.append('receipt', renewReceiptFile);

      if (initData) {
        formData.append('auth_data', initData);
      }
      if (testUserId) {
        formData.append('auth_userid', testUserId);
      }

      const headers = { ...getApiHeaders() };
      delete headers['Content-Type'];
      delete headers['content-type'];

      const res = await fetch('../api.php', {
        method: 'POST',
        headers: headers,
        body: formData
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else {
        setSuccessModalMsg(data.message || 'درخواست تمدید ثبت شد و منتظر تایید ادمین است.');
        setActiveRenewConfig(null);
        setRenewPlanId('');
        setRenewReceiptFile(null);
        setRenewReceiptPreview('');
      }
    } catch (err) {
      alert('خطا در ارسال اطلاعات به سرور.');
    } finally {
      setIsRenewing(false);
    }
  };

  const handleDownloadFileInTelegram = async (fileId, fileType, caption) => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'send_file_to_telegram',
          file_id: fileId,
          file_type: fileType,
          caption: caption
        })
      });
      const data = await res.json();
      if (data.status === 'success') {
        alert('فایل با موفقیت در تلگرام شما ارسال شد. لطفاً چت ربات را چک کنید. 😍');
      } else {
        alert(data.error || 'خطا در ارسال فایل');
      }
    } catch (e) {
      alert('خطای شبکه در ارسال فایل');
    }
  };

  const handleCloseTicket = async () => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'close_ticket',
          chat_id: activeTicket.id,
          rate: ratingValue
        })
      });
      const data = await res.json();
      if (data.status === 'success') {
        setShowRatingModal(false);
        setActiveTicket(null);
        fetchTickets();
        alert('تیکت با موفقیت بسته شد و امتیاز شما ثبت گردید.');
      } else {
        alert(data.error || 'خطا در ثبت درخواست');
      }
    } catch (e) {
      alert('خطا در ارتباط با سرور');
    }
  };


  const handleDeleteAgent = async (targetUserId) => {
    if (!targetUserId) return;
    if (!window.confirm('آیا از حذف این نماینده اطمینان دارید؟ نقش نمایندگی وی سلب خواهد شد.')) return;
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({ action: 'admin_delete_agent', target_user_id: targetUserId })
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else {
        alert(data.message);
        // Refresh agent dashboard
        fetchAgentDashboard();
      }
    } catch (err) {
      alert('خطا در ارتباط با سرور.');
    }
  };

  const handleMessageAgent = async (targetUserId) => {
    if (!targetUserId) return;
    const msgText = window.prompt('متن پیام خصوصی خود را برای ارسال به این نماینده تایپ کنید:');
    if (!msgText || !msgText.trim()) return;
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({ action: 'admin_msg_agent', target_user_id: targetUserId, message: msgText.trim() })
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else {
        alert(data.message);
      }
    } catch (err) {
      alert('خطا در ارتباط با سرور.');
    }
  };

  const handleDeleteConfig = async (configId) => {
    if (!configId) return;
    if (!window.confirm('آیا از حذف این سرویس اطمینان دارید؟ این عمل غیرقابل بازگشت است.')) return;
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({ action: 'delete_config', id: configId })
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else {
        alert(data.message);
        await fetchDashboardData();
        await fetchSubscriptions();
      }
    } catch (e) {
      alert('خطا در ارتباط با سرور.');
    }
  };

  const renderRenewPaymentDetails = () => {
    if (!renewPlanId) return null;
    const plan = plans.find(p => p.id == renewPlanId);
    if (!plan) return null;
    const hasEnough = user && user.wallet >= plan.price;

    return (
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '12px' }}>
          <span style={{ color: 'var(--text-secondary)' }}>قیمت تمدید:</span>
          <span style={{ fontWeight: 'bold' }}>{plan.price.toLocaleString()} تومان</span>
        </div>

        {/* Payment Method Selector */}
        <div style={{ display: 'flex', gap: '6px', marginBottom: '16px' }}>
          <button 
            type="button"
            onClick={() => setRenewMethod('wallet')} 
            className={`btn ${renewMethod === 'wallet' ? 'btn-primary' : ''}`}
            style={{ 
              flex: 1, 
              padding: '8px 2px', 
              fontSize: '11px', 
              borderRadius: '6px', 
              color: 'white', 
              background: renewMethod === 'wallet' ? 'var(--color-primary)' : 'rgba(255,255,255,0.08)',
              border: 'none',
              cursor: 'pointer'
            }}
          >
            کیف پول
          </button>

          {user && (user.is_agent || user.isAdmin) && (
            <button 
              type="button"
              onClick={() => setRenewMethod('agent')} 
              className={`btn ${renewMethod === 'agent' ? 'btn-primary' : ''}`}
              style={{ 
                flex: 1, 
                padding: '8px 2px', 
                fontSize: '11px', 
                borderRadius: '6px', 
                color: 'white', 
                background: renewMethod === 'agent' ? 'var(--color-primary)' : 'rgba(255,255,255,0.08)',
                border: 'none',
                cursor: 'pointer'
              }}
            >
              حجم نمایندگی
            </button>
          )}

          <button 
            type="button"
            onClick={() => setRenewMethod('card')} 
            className={`btn ${renewMethod === 'card' ? 'btn-primary' : ''}`}
            style={{ 
              flex: 1, 
              padding: '8px 2px', 
              fontSize: '11px', 
              borderRadius: '6px', 
              color: 'white', 
              background: renewMethod === 'card' ? 'var(--color-primary)' : 'rgba(255,255,255,0.08)',
              border: 'none',
              cursor: 'pointer'
            }}
          >
            کارت‌به‌کارت
          </button>
        </div>

        {renewMethod === 'agent' ? (
          <>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '8px' }}>
              <span style={{ color: 'var(--text-secondary)' }}>حجم مورد نیاز پلن:</span>
              <span style={{ fontWeight: 'bold', color: 'white' }}>{plan.volume} گیگابایت</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '16px' }}>
              <span style={{ color: 'var(--text-secondary)' }}>حجم کل نمایندگی شما:</span>
              <span style={{ fontWeight: 'bold', color: (user.agent_volume == 0 || user.agent_volume >= plan.volume) ? 'var(--color-success)' : 'var(--color-danger)' }}>
                {user.agent_volume == 0 ? 'نامحدود' : `${user.agent_volume} گیگابایت`}
              </span>
            </div>
            
            <button 
              onClick={() => handleRenewConfigAgent(activeRenewConfig.id, plan.id)}
              disabled={isRenewing || (user.agent_volume > 0 && user.agent_volume < plan.volume)}
              className="btn btn-success" 
              style={{ width: '100%', borderRadius: '10px' }}
            >
              {isRenewing ? 'در حال پردازش...' : ((user.agent_volume == 0 || user.agent_volume >= plan.volume) ? 'تمدید از حجم نمایندگی ⚡️' : 'حجم نمایندگی ناکافی')}
            </button>
          </>
        ) : renewMethod === 'wallet' ? (
          <>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '16px' }}>
              <span style={{ color: 'var(--text-secondary)' }}>موجودی کیف پول شما:</span>
              <span style={{ fontWeight: 'bold', color: hasEnough ? 'var(--color-success)' : 'var(--color-danger)' }}>
                {user ? user.wallet.toLocaleString() : 0} تومان
              </span>
            </div>
            
            <button 
              onClick={() => handleRenewConfigWallet(activeRenewConfig.id, plan.id)}
              disabled={isRenewing || !hasEnough}
              className="btn btn-success" 
              style={{ width: '100%', borderRadius: '10px' }}
            >
              {isRenewing ? 'در حال پردازش...' : (hasEnough ? 'پرداخت و تمدید آنی' : 'موجودی ناکافی')}
            </button>
          </>
        ) : (
          <form onSubmit={handleRenewConfigReceipt}>
            <div style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.05)', borderRadius: '12px', padding: '12px', marginBottom: '12px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '4px', alignItems: 'center' }}>
                <span style={{ color: 'var(--text-secondary)' }}>شماره کارت:</span>
                <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                  <span style={{ fontWeight: 'bold', letterSpacing: '1px' }}>{paymentKeys.bank_account || 'بارگذاری نشده'}</span>
                  {paymentKeys.bank_account && (
                    <button
                      type="button"
                      onClick={() => handleCopy(paymentKeys.bank_account, 'card_num')}
                      style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, display: 'flex', alignItems: 'center' }}
                    >
                      {copiedId === 'card_num' ? (
                        <span style={{ fontSize: '10px', color: 'var(--color-success)' }}>کپی شد</span>
                      ) : (
                        <Copy size={12} className="text-secondary" style={{ color: 'var(--text-secondary)' }} />
                      )}
                    </button>
                  )}
                </div>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px' }}>
                <span style={{ color: 'var(--text-secondary)' }}>به نام:</span>
                <span style={{ fontWeight: 'bold' }}>{paymentKeys.holder_name || 'بارگذاری نشده'}</span>
              </div>
            </div>

            <div className="form-group">
              <label className="form-label" style={{ fontSize: '11px' }}>تصویر رسید پرداخت (اسکرین‌شات)</label>
              <div 
                onClick={() => document.getElementById('renew-receipt-file-input').click()}
                onDragOver={(e) => e.preventDefault()}
                onDrop={(e) => {
                  e.preventDefault();
                  if (e.dataTransfer.files && e.dataTransfer.files[0]) {
                    setRenewReceiptFile(e.dataTransfer.files[0]);
                    setRenewReceiptPreview(URL.createObjectURL(e.dataTransfer.files[0]));
                  }
                }}
                style={{
                  border: '2px dashed rgba(255,255,255,0.15)',
                  borderRadius: '12px',
                  padding: '16px',
                  textAlign: 'center',
                  cursor: 'pointer',
                  background: 'rgba(255,255,255,0.01)',
                  transition: 'all 0.2s',
                }}
              >
                <input 
                  type="file" 
                  id="renew-receipt-file-input" 
                  accept="image/*" 
                  onChange={(e) => {
                    if (e.target.files && e.target.files[0]) {
                      setRenewReceiptFile(e.target.files[0]);
                      setRenewReceiptPreview(URL.createObjectURL(e.target.files[0]));
                    }
                  }} 
                  style={{ display: 'none' }} 
                />
                {renewReceiptPreview ? (
                  <img src={renewReceiptPreview} alt="رسید" style={{ maxHeight: '80px', display: 'block', margin: '0 auto', borderRadius: '6px' }} />
                ) : (
                  <p style={{ fontSize: '11px', color: 'var(--text-secondary)', margin: 0 }}>
                    برای انتخاب تصویر رسید تمدید، اینجا را لمس کنید یا فایل را بکشید
                  </p>
                )}
              </div>
            </div>

            <button 
              type="submit"
              disabled={isRenewing}
              className="btn btn-success" 
              style={{ width: '100%', borderRadius: '10px' }}
            >
              {isRenewing ? 'در حال ارسال رسید...' : 'ارسال رسید و درخواست تمدید'}
            </button>
          </form>
        )}
      </div>
    );
  };

  const handleCreateTicket = async (e) => {
    e.preventDefault();
    try {
      let res;
      if (newTicketFile) {
        const formData = new FormData();
        formData.append('action', 'create_ticket');
        formData.append('title', newTicketTitle);
        formData.append('category', newTicketCategory);
        formData.append('text', newTicketText);
        formData.append('file', newTicketFile);
        
        const data = initData;
        if (data) {
          formData.append('auth_data', data);
        }
        if (testUserId && !data.startsWith('token:')) {
          formData.append('test_user_id', testUserId);
        }
        if (activeViewUserId) {
          formData.append('view_as_user_id', activeViewUserId);
        }
        
        const headers = getApiHeaders();
        delete headers['Content-Type'];
        
        res = await fetch('../api.php', {
          method: 'POST',
          headers: headers,
          body: formData
        });
      } else {
        res = await fetch('../api.php', {
          method: 'POST',
          headers: getApiHeaders(),
          body: getRequestBody({
            action: 'create_ticket',
            title: newTicketTitle,
            category: newTicketCategory,
            text: newTicketText
          })
        });
      }
      
      const data = await res.json();
      if (data.status === 'success') {
        setNewTicketTitle('');
        setNewTicketText('');
        setNewTicketFile(null);
        setNewTicketFilePreview('');
        fetchTickets();
        alert('تیکت شما با موفقیت ایجاد شد.');
      } else {
        alert(data.error || 'خطا در ایجاد تیکت');
      }
    } catch (err) {
      alert('خطا در ارتباط با سرور');
    }
  };

  const handleSendReply = async () => {
    if (!chatInput.trim() || !activeTicket) return;
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'send_ticket_reply',
          chat_id: activeTicket.id,
          text: chatInput,
          reply_to_id: replyToMessage ? replyToMessage.id : null
        })
      });
      const data = await res.json();
      if (data.status === 'success') {
        setChatInput('');
        setReplyToMessage(null);
        fetchTicketMessages(activeTicket.id);
      }
    } catch (err) { }
  };

  const handleUploadChatFile = async (e) => {
    const file = e.target.files[0];
    if (!file || !activeTicket) return;
    
    const formData = new FormData();
    formData.append('chat_id', activeTicket.id);
    formData.append('file', file);
    formData.append('caption', chatInput || '');
    formData.append('action', 'send_ticket_reply_file');
    if (replyToMessage) {
      formData.append('reply_to_id', replyToMessage.id);
    }
    
    const data = initData;
    if (data) {
      formData.append('auth_data', data);
    }
    if (testUserId && !data.startsWith('token:')) {
      formData.append('test_user_id', testUserId);
    }
    if (activeViewUserId) {
      formData.append('view_as_user_id', activeViewUserId);
    }
    
    const headers = getApiHeaders();
    delete headers['Content-Type'];
    
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: headers,
        body: formData
      });
      const dataJson = await res.json();
      if (dataJson.status === 'success') {
        setChatInput('');
        setReplyToMessage(null);
        fetchTicketMessages(activeTicket.id);
      } else {
        alert(dataJson.error || 'خطا در ارسال فایل');
      }
    } catch (e) {
      alert('خطای شبکه در ارسال فایل');
    }
  };

  const handleAgentBuyVolume = async (e) => {
    e.preventDefault();
    setAgentMsg(null);
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'agent_purchase_volume',
          volume: parseInt(agentVolBuy)
        })
      });
      const data = await res.json();
      if (data.error) {
        setAgentMsg({ type: 'danger', text: data.error });
      } else {
        setAgentMsg({ type: 'success', text: data.message });
        setAgentVolBuy('');
        fetchDashboardData();
      }
    } catch (e) {
      setAgentMsg({ type: 'danger', text: 'خطا در شبکه.' });
    }
  };

  const handleAdminSearch = async () => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'admin_users',
          query: adminSearchQuery
        })
      });
      const data = await res.json();
      if (data.users) setAdminUsersList(data.users);
    } catch (e) { }
  };

  const handleAdminVerifyPayment = async (payId, decision) => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'admin_verify_payment',
          pay_id: payId,
          decision
        })
      });
      const data = await res.json();
      if (data.status === 'success') {
        alert(data.message);
        fetchAdminDashboard();
      }
    } catch (e) { }
  };

  const handleAdminEditUser = async (e) => {
    e.preventDefault();
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({
          action: 'admin_edit_user',
          target_user_id: editingUser.userid,
          wallet: parseFloat(editingUser.wallet),
          is_agent: parseInt(editingUser.is_agent),
          is_admin: parseInt(editingUser.isAdmin),
          agent_volume: parseFloat(editingUser.agent_volume || 0),
          agent_limit: parseInt(editingUser.agent_limit || 0)
        })
      });
      const data = await res.json();
      if (data.status === 'success') {
        alert(data.message);
        setEditingUser(null);
        handleAdminSearch();
      }
    } catch (e) { }
  };

  const handleRequestAgency = async () => {
    const msg = "دوست من درخواست نمایندگی فقط در صورتی تایید می شود که شما حداقل یک کانفیگ از ربات خریداری کرده باشید و حداقل ۱۰ کاربر ماهانه داشته باشید. این بخش مزایای زیادی دارد. آیا این شرایط را دارید؟";
    
    const proceed = () => {
      requestAgencyApi();
    };

    if (window.Telegram && window.Telegram.WebApp && window.Telegram.WebApp.showConfirm) {
      window.Telegram.WebApp.showConfirm(msg, (ok) => {
        if (ok) proceed();
      });
    } else {
      if (window.confirm(msg)) {
        proceed();
      }
    }
  };

  const requestAgencyApi = async () => {
    try {
      const res = await fetch('../api.php', {
        method: 'POST',
        headers: getApiHeaders(),
        body: getRequestBody({ action: 'request_agency' })
      });
      const data = await res.json();
      if (data.error) {
        if (window.Telegram && window.Telegram.WebApp && window.Telegram.WebApp.showAlert) {
          window.Telegram.WebApp.showAlert(data.error);
        } else {
          alert(data.error);
        }
      } else {
        if (window.Telegram && window.Telegram.WebApp && window.Telegram.WebApp.showAlert) {
          window.Telegram.WebApp.showAlert(data.message);
        } else {
          alert(data.message);
        }
      }
    } catch (e) { }
  };

  // Switched Account / Impersonation trigger
  const handleSwitchAccount = (e) => {
    e.preventDefault();
    if (viewAsUserId) {
      setActiveViewUserId(viewAsUserId);
      alert(`سوییچ به حساب کاربر ${viewAsUserId} انجام شد.`);
      setTimeout(() => fetchDashboardData(), 100);
    }
  };

  const handleExitSwitchedAccount = () => {
    setActiveViewUserId(null);
    setViewAsUserId('');
    alert('به حساب مدیریت خود بازگشتید.');
    setTimeout(() => fetchDashboardData(), 100);
  };

  // Helper function to format bytes to human readable sizes
  const formatBytes = (bytes, decimals = 2) => {
    if (!bytes || bytes === 0) return '0 گیگابایت';
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['بایت', 'کیلوبایت', 'مگابایت', 'گیگابایت', 'ترابایت'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  };

  // Render Login Page for non-telegram environments
  if (!user && !loading) {
    return (
      <div className="container" style={{ marginTop: '10%' }}>
        <div className="glass-card" style={{ padding: '24px' }}>
          <div style={{ textAlign: 'center', marginBottom: '20px' }}>
            <Sparkles size={44} className="text-primary" style={{ margin: '0 auto 12px', color: 'var(--color-primary)' }} />
            <h2 style={{ fontSize: '18px', fontWeight: 'bold' }}>ورود به مینی‌اپ نت‌فریدوم</h2>
          </div>

          <div style={{ display: 'flex', gap: '4px', marginBottom: '16px', background: 'rgba(255,255,255,0.02)', padding: '4px', borderRadius: '8px' }}>
            <button 
              onClick={() => { setLoginTab('token'); setErrorMsg(''); }} 
              className={`btn ${loginTab === 'token' ? 'btn-primary' : ''}`}
              style={{ flex: 1, padding: '8px 2px', fontSize: '11px', borderRadius: '6px' }}
            >
              توکن اختصاصی
            </button>
            <button 
              onClick={() => { setLoginTab('manual'); setErrorMsg(''); }} 
              className={`btn ${loginTab === 'manual' ? 'btn-primary' : ''}`}
              style={{ flex: 1, padding: '8px 2px', fontSize: '11px', borderRadius: '6px' }}
            >
              کد تایید عددی (OTP)
            </button>
          </div>

          {loginTab === 'manual' && (
            <div>
              {!isVerifyingOtp ? (
                <form onSubmit={handleRequestOtp}>
                  <p style={{ color: 'var(--text-secondary)', fontSize: '12px', marginBottom: '16px', textAlign: 'center' }}>
                    برای دریافت کد تایید موقت، شناسه عددی تلگرام خود را وارد کنید:
                  </p>
                  <div className="form-group">
                    <input 
                      type="number" 
                      value={testUserId} 
                      onChange={(e) => setTestUserId(e.target.value)} 
                      placeholder="مثال: ۲۹۳۸۱۹۲۸۳" 
                      className="form-input" 
                      required 
                    />
                  </div>
                  <button type="submit" className="btn btn-primary" style={{ width: '100%' }}>دریافت کد تایید</button>
                </form>
              ) : (
                <div style={{ textAlign: 'center' }}>
                  <p style={{ fontSize: '13px', color: 'var(--text-secondary)', marginBottom: '12px' }}>
                    کد تأیید ۶ رقمی زیر ایجاد شد. لطفاً آن را کپی کرده و به ربات بفرستید (یا روی دکمه زیر ضربه بزنید تا ربات باز شود):
                  </p>
                  <div style={{ fontSize: '28px', fontWeight: '900', letterSpacing: '4px', background: 'rgba(255,255,255,0.05)', padding: '12px', borderRadius: '12px', color: 'var(--color-primary)', display: 'inline-block', margin: '8px 0 16px' }}>
                    {otpCode}
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                    <a 
                      href={`https://t.me/${botUsername || 'VPNNetFreedom_bot'}?start=otp_${otpCode}`} 
                      target="_blank" 
                      rel="noopener noreferrer" 
                      className="btn btn-primary" 
                      style={{ fontSize: '12px' }}
                    >
                      تایید هویت خودکار در ربات
                    </a>
                    <button onClick={handleCheckOtpStatus} className="btn btn-success" style={{ fontSize: '12px' }}>
                      بررسی وضعیت تایید هویت
                    </button>
                    <button onClick={() => setIsVerifyingOtp(false)} className="btn btn-danger" style={{ fontSize: '12px' }}>
                      تغییر شناسه عددی
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}

          {loginTab === 'token' && (
            <div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginBottom: '16px' }}>
                <a 
                  href="https://t.me/VPNNetFreedom_bot?start=login" 
                  target="_blank" 
                  rel="noopener noreferrer" 
                  className="btn btn-success" 
                  style={{ fontSize: '11px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', width: '100%', background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)', border: 'none', color: 'white', padding: '10px 14px', borderRadius: '10px', textDecoration: 'none', fontWeight: 'bold' }}
                >
                  <Send size={12} /> 💬 دریافت توکن ورود اختصاصی از ربات
                </a>
              </div>

              <form onSubmit={handleDirectTokenLogin}>
                <p style={{ color: 'var(--text-secondary)', fontSize: '12px', marginBottom: '12px', textAlign: 'center' }}>
                  توکن ورود یا لینک ورود مستقیم خود را وارد کنید:
                </p>
                <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                  <input 
                    type="text" 
                    value={directTokenInput} 
                    onChange={(e) => setDirectTokenInput(e.target.value)} 
                    placeholder="توکن ورود خود را وارد کنید..." 
                    className="form-input" 
                    style={{ flex: 1, margin: 0 }}
                    required 
                  />
                  <button type="submit" className="btn btn-primary" style={{ padding: '0 20px', whiteSpace: 'nowrap', height: '42px', borderRadius: '10px' }}>
                    ورود
                  </button>
                </div>
              </form>
            </div>
          )}

          {errorMsg && (
            <p style={{ color: 'var(--color-danger)', fontSize: '12px', marginTop: '16px', textAlign: 'center' }}>{errorMsg}</p>
          )}
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100vh', gap: '16px' }}>
        <RefreshCw size={36} className="animate-spin" style={{ color: 'var(--color-primary)' }} />
        <span>در حال بارگذاری اطلاعات...</span>
      </div>
    );
  }

  const isChatActive = activeTab === 'tickets' && activeTicket;
  return (
    <div style={{ height: isChatActive ? '100vh' : 'auto', overflow: isChatActive ? 'hidden' : 'visible' }}>
      
      {/* Impersonation Switched Mode Banner */}
      {activeViewUserId && (
        <div style={{ background: 'linear-gradient(90deg, #b91c1c 0%, #ef4444 100%)', color: 'white', padding: '10px', textAlign: 'center', fontSize: '13px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', position: 'sticky', top: 0, zIndex: 1000, boxShadow: '0 4px 15px rgba(0,0,0,0.3)' }}>
          <span>⚠️ در حال مشاهده و مدیریت حساب کاربر: <b>{activeViewUserId}</b></span>
          <button 
            onClick={handleExitSwitchedAccount} 
            className="btn btn-danger" 
            style={{ padding: '4px 10px', fontSize: '11px', background: 'white', color: '#b91c1c', border: 'none', borderRadius: '6px' }}
          >
            خروج و بازگشت به ادمین
          </button>
        </div>
      )}

      {/* Dynamic Header */}
      <div className="glass-card" style={{ margin: '12px', borderRadius: '12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 16px', background: 'rgba(30, 41, 59, 0.8)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <Sparkles className="text-primary" style={{ color: 'var(--color-primary)' }} />
          <span style={{ fontWeight: 'bold' }}>داشبورد نت‌فریدوم</span>
        </div>
      </div>

      <div className="container" style={{ paddingBottom: isChatActive ? '70px' : '80px' }}>
        
        {/* VIEW 1: Dashboard */}
        {activeTab === 'user-dashboard' && (
          <div>
            
            {/* User Profile Header Card (mockup matching) */}
            <div className="glass-card" style={{
              display: 'flex',
              alignItems: 'center',
              gap: '16px',
              padding: '16px',
              marginBottom: '16px',
              background: 'rgba(255, 255, 255, 0.03)',
              border: '1px solid rgba(255, 255, 255, 0.05)',
              borderRadius: '20px'
            }}>
              {/* Avatar on the right (RTL layout) */}
              <div style={{ position: 'relative', width: '56px', height: '56px', flexShrink: 0, order: 2 }}>
                <div style={{
                  width: '100%',
                  height: '100%',
                  borderRadius: '50%',
                  background: 'linear-gradient(135deg, var(--color-primary) 0%, #3b82f6 100%)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '20px',
                  fontWeight: 'bold',
                  color: 'white',
                  boxShadow: '0 4px 10px rgba(0, 0, 0, 0.2)',
                  overflow: 'hidden'
                }}>
                  {user.photo_url ? (
                    <img src={user.photo_url} alt={user.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                  ) : (
                    user.name ? user.name.substring(0, 1) : <User />
                  )}
                </div>
                {/* Active online status indicator */}
                <div style={{
                  position: 'absolute',
                  bottom: '2px',
                  left: '2px',
                  width: '12px',
                  height: '12px',
                  borderRadius: '50%',
                  backgroundColor: '#2ecc71',
                  border: '2px solid rgba(22, 24, 38, 0.95)'
                }}></div>
              </div>
              
              {/* Profile Details left of Avatar */}
              <div style={{ flex: 1, textAlign: 'right', display: 'flex', flexDirection: 'column', gap: '2px', order: 1 }}>
                <h3 style={{ fontSize: '15px', fontWeight: '800', color: 'white', margin: 0 }}>{user.name || 'کاربر گرامی'}</h3>
                {user.username && (
                  <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>@{user.username}</span>
                )}
                <span style={{ fontSize: '10px', color: 'var(--text-secondary)', opacity: 0.8 }}>UserID: {user.id}</span>
              </div>

              {/* Bell icon showing open tickets count */}
              <div 
                onClick={() => setActiveTab('tickets')}
                style={{ 
                  position: 'relative', 
                  cursor: 'pointer', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  width: '38px',
                  height: '38px',
                  borderRadius: '12px',
                  background: 'rgba(255,255,255,0.05)',
                  border: '1px solid rgba(255,255,255,0.1)',
                  order: 0 
                }}
                title="تیکت‌های باز"
              >
                <span style={{ fontSize: '18px' }}>🔔</span>
                {metrics.active_tickets > 0 && (
                  <div style={{
                    position: 'absolute',
                    top: '-6px',
                    right: '-6px',
                    background: '#ef4444',
                    color: 'white',
                    borderRadius: '50%',
                    width: '18px',
                    height: '18px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: '9px',
                    fontWeight: 'bold',
                    border: '2px solid #1a1b26'
                  }}>
                    {metrics.active_tickets}
                  </div>
                )}
              </div>
            </div>

            {/* Green Call to Action Button */}
            <button 
              onClick={() => setActiveTab('buy-plans')} 
              className="btn btn-success" 
              style={{
                width: '100%',
                padding: '14px',
                fontSize: '14px',
                fontWeight: '800',
                borderRadius: '16px',
                background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
                boxShadow: '0 0 15px rgba(16, 185, 129, 0.4)',
                border: 'none',
                color: '#fff',
                marginBottom: '16px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: '8px',
                cursor: 'pointer'
              }}
            >
              <Plus size={18} /> خرید کانفیگ جدید
            </button>

            {/* Test Account Issued Alert Modal/Card */}
            {testAccountResult && (
              <div className="glass-card" style={{ marginBottom: '16px', border: '1px solid var(--color-success)', background: 'rgba(16, 185, 129, 0.05)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                  <span style={{ fontWeight: 'bold', color: 'var(--color-success)', fontSize: '14px', display: 'flex', alignItems: 'center', gap: '6px' }}>
                    <CheckCircle2 size={16} /> اکانت تست شما با موفقیت صادر شد!
                  </span>
                  <button onClick={() => setTestAccountResult(null)} style={{ background: 'none', border: 'none', color: 'var(--text-secondary)', cursor: 'pointer', fontSize: '16px' }}>&times;</button>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', fontSize: '12px' }}>
                  <div style={{ background: 'rgba(0,0,0,0.2)', padding: '10px', borderRadius: '8px' }}>
                    <span style={{ color: 'var(--text-secondary)', display: 'block', marginBottom: '4px' }}>لینک اتصال:</span>
                    <code style={{ wordBreak: 'break-all', display: 'block', fontSize: '10px' }}>{testAccountResult.link}</code>
                    <button onClick={() => handleCopy(testAccountResult.link, 'trial-link')} className="btn btn-primary" style={{ padding: '4px 8px', fontSize: '10px', marginTop: '6px', width: '100%' }}>
                      {copiedId === 'trial-link' ? 'کپی شد' : 'کپی لینک اتصال'}
                    </button>
                  </div>
                  <div style={{ background: 'rgba(0,0,0,0.2)', padding: '10px', borderRadius: '8px' }}>
                    <span style={{ color: 'var(--text-secondary)', display: 'block', marginBottom: '4px' }}>لینک ساب‌سکرایب:</span>
                    <code style={{ wordBreak: 'break-all', display: 'block', fontSize: '10px' }}>{testAccountResult.sub_link}</code>
                    <button onClick={() => handleCopy(testAccountResult.sub_link, 'trial-sub')} className="btn btn-primary" style={{ padding: '4px 8px', fontSize: '10px', marginTop: '6px', width: '100%' }}>
                      {copiedId === 'trial-sub' ? 'کپی شد' : 'کپی لینک ساب‌سکرایب'}
                    </button>
                  </div>
                  <a href={testAccountResult.web_link} target="_blank" rel="noopener noreferrer" className="btn btn-success" style={{ textAlign: 'center', padding: '8px', fontSize: '11px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}>
                    <ExternalLink size={12} /> مشاهده وب پنل ترافیک
                  </a>
                </div>
              </div>
            )}

            {/* My Stats - Aggregate Donut Chart Section */}
            <div className="glass-card" style={{ marginBottom: '16px', padding: '16px 20px' }}>
              <h3 style={{ fontSize: '13px', fontWeight: 'bold', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px', color: 'white' }}>
                <Activity size={16} className="text-primary" /> وضعیت سرویس‌های من
              </h3>
              
              {subscriptions.length === 0 ? (
                <div style={{ textAlign: 'center', padding: '24px 0', color: 'var(--text-secondary)', fontSize: '12px' }}>
                  <AlertTriangle size={24} style={{ margin: '0 auto 8px', color: 'var(--text-secondary)' }} />
                  <span>شما در حال حاضر هیچ کانفیگ فعالی در سیستم ندارید.</span>
                </div>
              ) : (() => {
                const activeConfigsList = subscriptions.filter(cfg => cfg.status !== 'pending');
                if (activeConfigsList.length === 0) {
                  return (
                    <div style={{ textAlign: 'center', padding: '24px 0', color: 'var(--text-secondary)', fontSize: '12px' }}>
                      <AlertTriangle size={24} style={{ margin: '0 auto 8px', color: 'var(--text-secondary)' }} />
                      <span>شما در حال حاضر هیچ کانفیگ فعالی در سیستم ندارید.</span>
                    </div>
                  );
                }

                let totalVol = 0;
                let usedVol = 0;
                const colorPalette = ['#2ecc71', '#3498db', '#9b59b6', '#f1c40f', '#e67e22', '#1abc9c'];
                const configSlices = [];

                activeConfigsList.forEach((cfg, index) => {
                  let tot = cfg.stats?.total || 0;
                  if (tot === 0) {
                    tot = 60 * 1073741824; // 60 GB in bytes
                  }
                  const usd = cfg.stats?.used || 0;
                  const rem = Math.max(0, tot - usd);

                  totalVol += tot;
                  usedVol += usd;

                  configSlices.push({
                    remark: cfg.remark,
                    remaining: rem,
                    color: colorPalette[index % colorPalette.length],
                    expire_date: cfg.expire_date,
                    status: cfg.status
                  });
                });

                const usedPct = totalVol > 0 ? (usedVol / totalVol) * 100 : 0;
                const r = 35;
                const C = 2 * Math.PI * r;
                const usedDash = (usedPct / 100) * C;
                let currentOffset = usedDash;

                return (
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '16px' }}>
                    {/* Left Side: Legend */}
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                          <span style={{ width: '10px', height: '10px', borderRadius: '3px', backgroundColor: '#64748b' }}></span>
                          <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>حجم کل</span>
                        </div>
                        <span style={{ fontSize: '11px', fontWeight: 'bold', color: 'white' }}>
                          {formatBytes(totalVol)}
                        </span>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                          <span style={{ width: '10px', height: '10px', borderRadius: '3px', backgroundColor: '#ef4444' }}></span>
                          <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>مصرف شده</span>
                        </div>
                        <span style={{ fontSize: '11px', fontWeight: 'bold', color: '#ef4444' }}>
                          {formatBytes(usedVol)}
                        </span>
                      </div>
                      
                      {configSlices.map((slice, idx) => {
                        const isExpired = parseInt(slice.status) !== 1;
                        return (
                          <div key={idx} style={{ 
                            display: 'flex', 
                            flexDirection: 'column', 
                            gap: '4px', 
                            borderTop: '1px solid rgba(255,255,255,0.05)',
                            paddingTop: '8px',
                            marginTop: '4px'
                          }}>
                            {/* Row 1: Dot, Name and Status */}
                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                              <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                                <span style={{ width: '8px', height: '8px', borderRadius: '50%', backgroundColor: slice.color }}></span>
                                <span style={{ fontSize: '11px', fontWeight: 'bold', color: 'white', maxWidth: '120px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                  {slice.remark}
                                </span>
                              </div>
                              <span style={{ fontSize: '10px', fontWeight: 'bold', color: isExpired ? '#ef4444' : '#2ecc71' }}>
                                {isExpired ? 'غیرفعال / منقضی' : 'فعال'}
                              </span>
                            </div>
                            {/* Row 2: Expiration and Remaining Volume */}
                            <div style={{ display: 'flex', justifyContent: 'space-between', paddingRight: '14px' }}>
                              <span style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>
                                🗓️ {formatPersianDate(slice.expire_date)}
                              </span>
                              <span style={{ fontSize: '10px', fontWeight: 'bold', color: slice.color }}>
                                {formatBytes(slice.remaining)} باقی‌مانده
                              </span>
                            </div>
                          </div>
                        );
                      })}
                    </div>

                    {/* Right Side: Donut Chart */}
                    <div style={{ position: 'relative', width: '110px', height: '110px', flexShrink: 0 }}>
                      <svg width="110" height="110" viewBox="0 0 110 110" style={{ transform: 'rotate(-90deg)' }}>
                        <circle cx="55" cy="55" r={r} fill="transparent" stroke="#475569" strokeWidth="8" />
                        {/* Red slice for Consumed/Used traffic */}
                        <circle 
                          cx="55" 
                          cy="55" 
                          r={r} 
                          fill="transparent" 
                          stroke="#ef4444" 
                          strokeWidth="8" 
                          strokeDasharray={`${usedDash} ${C}`}
                          strokeDashoffset="0"
                        />
                        {/* Custom color slices for each config remaining traffic */}
                        {configSlices.map((slice, idx) => {
                          const slicePct = totalVol > 0 ? (slice.remaining / totalVol) * 100 : 0;
                          const sliceDash = (slicePct / 100) * C;
                          const offset = currentOffset;
                          currentOffset += sliceDash;
                          return (
                            <circle 
                              key={idx}
                              cx="55" 
                              cy="55" 
                              r={r} 
                              fill="transparent" 
                              stroke={slice.color} 
                              strokeWidth="8" 
                              strokeDasharray={`${sliceDash} ${C}`}
                              strokeDashoffset={`-${offset}`}
                            />
                          );
                        })}
                      </svg>
                      <div style={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        textAlign: 'center'
                      }}>
                        <span style={{ fontSize: '9px', color: 'var(--text-secondary)' }}>حجم کل</span>
                        <span style={{ fontSize: '12px', fontWeight: 'bold', color: 'white', marginTop: '2px' }}>
                          {formatBytes(totalVol)}
                        </span>
                      </div>
                    </div>
                  </div>
                );
              })()}
            </div>

            {/* 2x2 Quick Access Grid Menu */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '16px' }}>
              {/* Request Test Account */}
              <div 
                onClick={(user.freetrial === 'used' && !user.isAdmin) ? () => alert('شما قبلاً اکانت تست را دریافت کرده‌اید.') : handleRequestTestAccount} 
                style={{
                  background: 'rgba(59, 130, 246, 0.05)',
                  border: '1px solid rgba(59, 130, 246, 0.1)',
                  padding: '16px 12px',
                  borderRadius: '16px',
                  textAlign: 'center',
                  cursor: 'pointer',
                  transition: 'transform 0.2s',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justify: 'center',
                  gap: '6px',
                  opacity: (user.freetrial === 'used' && !user.isAdmin) ? 0.6 : 1
                }}
              >
                {isRequestingTest ? (
                  <RefreshCw size={24} className="animate-spin text-primary" style={{ color: 'var(--color-primary)' }} />
                ) : (
                  <span style={{ fontSize: '24px' }}>🎁</span>
                )}
                <span style={{ fontSize: '12px', fontWeight: 'bold', color: 'white' }}>دریافت اکانت تست</span>
              </div>

              {/* Wallet Info Card */}
              <div 
                onClick={() => setActiveTab('wallet-charge')}
                style={{
                  background: 'rgba(46, 204, 113, 0.05)',
                  border: '1px solid rgba(46, 204, 113, 0.1)',
                  padding: '16px 12px',
                  borderRadius: '16px',
                  textAlign: 'center',
                  cursor: 'pointer',
                  transition: 'transform 0.2s',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justify: 'center',
                  gap: '6px'
                }}
              >
                <span style={{ fontSize: '24px' }}>💼</span>
                <span style={{ fontSize: '12px', fontWeight: 'bold', color: 'white' }}>کیف پول</span>
                <span style={{ fontSize: '10px', color: '#2ecc71', fontWeight: 'bold' }}>
                  {user.wallet.toLocaleString()} تومان
                </span>
              </div>

              {/* Support Tickets */}
              <div 
                onClick={() => setActiveTab('tickets')}
                style={{
                  background: 'rgba(239, 68, 68, 0.05)',
                  border: '1px solid rgba(239, 68, 68, 0.1)',
                  padding: '16px 12px',
                  borderRadius: '16px',
                  textAlign: 'center',
                  cursor: 'pointer',
                  transition: 'transform 0.2s',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justify: 'center',
                  gap: '6px'
                }}
              >
                <span style={{ fontSize: '24px' }}>🎫</span>
                <span style={{ fontSize: '12px', fontWeight: 'bold', color: 'white' }}>تیکت‌های من</span>
                <span style={{ fontSize: '10px', color: '#ef4444', fontWeight: 'bold' }}>
                  {metrics.active_tickets} باز
                </span>
              </div>

              {/* Partnership / Agency */}
              <div 
                onClick={() => {
                  if (user.is_agent || user.isAdmin) {
                    setActiveTab('reseller-panel');
                  } else {
                    handleRequestAgency();
                  }
                }}
                style={{
                  background: 'rgba(243, 156, 18, 0.05)',
                  border: '1px solid rgba(243, 156, 18, 0.1)',
                  padding: '16px 12px',
                  borderRadius: '16px',
                  textAlign: 'center',
                  cursor: 'pointer',
                  transition: 'transform 0.2s',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justify: 'center',
                  gap: '6px'
                }}
              >
                <span style={{ fontSize: '24px' }}>🤝</span>
                <span style={{ fontSize: '12px', fontWeight: 'bold', color: 'white' }}>
                  {(user.is_agent || user.isAdmin) ? 'پنل نمایندگی' : 'درخواست نمایندگی'}
                </span>
              </div>
            </div>

            {/* Affiliate & Sub-member Stats Section */}
            <div className="glass-card" style={{ marginBottom: '16px', padding: '16px' }}>
              <h3 style={{ fontSize: '13px', fontWeight: 'bold', marginBottom: '14px', display: 'flex', alignItems: 'center', gap: '8px', color: 'white' }}>
                <span style={{ fontSize: '16px' }}>👥</span> کسب درآمد / زیرمجموعه‌گیری
              </h3>
              
              <p style={{ fontSize: '11px', color: 'var(--text-secondary)', marginBottom: '8px' }}>با اشتراک لینک زیر سود کنید:</p>
              
              {/* Copy Link Input Field */}
              <div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
                <input 
                  type="text" 
                  readOnly 
                  value={user.ref_link || ''} 
                  style={{
                    flex: 1,
                    background: 'rgba(255,255,255,0.03)',
                    border: '1px solid rgba(255,255,255,0.08)',
                    borderRadius: '10px',
                    padding: '8px 12px',
                    fontSize: '11px',
                    color: 'var(--text-secondary)',
                    textAlign: 'left',
                    direction: 'ltr'
                  }}
                />
                <button 
                  onClick={() => handleCopy(user.ref_link, 'reflink')} 
                  className="btn btn-primary" 
                  style={{ padding: '8px 16px', fontSize: '11px', borderRadius: '10px', flexShrink: 0 }}
                >
                  {copiedId === 'reflink' ? 'کپی شد' : 'کپی'}
                </button>
              </div>

              {/* Referral Stats Grid */}
              <div style={{ display: 'flex', borderTop: '1px solid rgba(255,255,255,0.05)', paddingTop: '12px' }}>
                <div style={{ flex: 1, textAlign: 'center', borderLeft: '1px solid rgba(255,255,255,0.05)' }}>
                  <span style={{ fontSize: '10px', color: 'var(--text-secondary)', display: 'block', marginBottom: '4px' }}>تعداد کل ورودی‌ها</span>
                  <span style={{ fontSize: '13px', fontWeight: 'bold', color: 'white' }}>{user.referred_count || 0}</span>
                </div>
                <div style={{ flex: 1, textAlign: 'center', borderLeft: '1px solid rgba(255,255,255,0.05)' }}>
                  <span style={{ fontSize: '10px', color: 'var(--text-secondary)', display: 'block', marginBottom: '4px' }}>تعداد خرید</span>
                  <span style={{ fontSize: '13px', fontWeight: 'bold', color: 'white' }}>{user.referred_purchases || 0}</span>
                </div>
                <div style={{ flex: 1, textAlign: 'center' }}>
                  <span style={{ fontSize: '10px', color: 'var(--text-secondary)', display: 'block', marginBottom: '4px' }}>سود شما</span>
                  <span style={{ fontSize: '12px', fontWeight: 'bold', color: '#2ecc71' }}>
                    {(user.referred_earnings || 0).toLocaleString()} <span style={{ fontSize: '9px' }}>تومان</span>
                  </span>
                </div>
              </div>
            </div>

          </div>
        )}
        {activeTab === 'subscriptions' && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
              <h2 style={{ fontSize: '16px', fontWeight: 'bold' }}>اشتراک‌های خریداری شده</h2>
              <button 
                onClick={() => setActiveTab('buy-plans')} 
                className="btn btn-success" 
                style={{ padding: '6px 12px', fontSize: '12px' }}
              >
                <Plus size={14} style={{ marginLeft: '4px' }} /> خرید جدید
              </button>
            </div>

            {subscriptions.length === 0 ? (
              <div className="glass-card" style={{ textAlign: 'center', padding: '32px' }}>
                <AlertTriangle size={32} style={{ margin: '0 auto 12px', color: 'var(--text-secondary)' }} />
                <p style={{ color: 'var(--text-secondary)' }}>شما هیچ کانفیگ فعالی در دیتابیس ندارید.</p>
                <button onClick={() => setActiveTab('buy-plans')} className="btn btn-primary" style={{ marginTop: '16px', fontSize: '12px' }}>خرید اولین اشتراک</button>
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                {subscriptions.map(cfg => (
                  <div key={cfg.id} className="glass-card" style={{ padding: '14px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
                        <span style={{ fontWeight: 'bold', fontSize: '14px' }}>{cfg.remark}</span>
                        {cfg.status !== 'pending' && (() => {
                          const total = cfg.stats?.total || 0;
                          const used = cfg.stats?.used || 0;
                          const pct = total > 0 ? Math.min(100, Math.round((used / total) * 100)) : 0;
                          const totalGB = (total / (1024 * 1024 * 1024)).toFixed(1);
                          const usedGB = (used / (1024 * 1024 * 1024)).toFixed(1);
                          const onlineCount = cfg.stats?.online_count || 0;
                          const limitIp = cfg.stats?.limit_ip;
                          const ipLimitText = limitIp === 0 ? 'نامحدود' : (limitIp || 'نامحدود');
                          return (
                            <span style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>
                              🗓️ سررسید: {formatPersianDate(cfg.expire_date)} | 📊 مصرف: {usedGB} از {totalGB} گیگ ({pct}%) | 👥 آنلاین: {onlineCount} از {ipLimitText} دستگاه
                            </span>
                          );
                        })()}
                      </div>
                      <span className={`badge ${cfg.status === 'pending' ? 'badge-danger' : (parseInt(cfg.status) === 1 ? 'badge-success' : 'badge-danger')}`} style={{ background: cfg.status === 'pending' ? 'rgba(243, 156, 18, 0.15)' : '', color: cfg.status === 'pending' ? '#f39c12' : '', border: cfg.status === 'pending' ? '1px solid rgba(243, 156, 18, 0.3)' : '' }}>
                        {cfg.status === 'pending' ? 'در حال انتظار' : (parseInt(cfg.status) === 1 ? 'فعال' : 'غیرفعال / منقضی')}
                      </span>
                    </div>

                    {cfg.status === 'pending' ? (
                      <div style={{ padding: '12px', borderRadius: '10px', background: 'rgba(243,156,18,0.05)', border: '1px solid rgba(243,156,18,0.1)', color: '#f39c12', fontSize: '11px', textAlign: 'center' }}>
                        ⏳ رسید پرداخت شما ثبت شده و در انتظار تایید نهایی مدیریت است. پس از تایید ادمین، اکانت شما فوراً صادر خواهد شد.
                      </div>
                    ) : (
                      <>
                        {/* 2 Columns: QR Code (Left) and Buttons Stack (Right) */}
                        <div style={{ display: 'flex', gap: '14px', alignItems: 'center', marginBottom: '12px', background: 'rgba(255,255,255,0.02)', padding: '12px', borderRadius: '12px' }}>
                          
                          {/* Column 1: QR Code (30%) */}
                          <div style={{ width: '30%', display: 'flex', justifyContent: 'center' }}>
                            {cfg.link ? (
                              <img 
                                onClick={() => setActiveQrCodeLink(cfg.link)}
                                src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(cfg.link)}`} 
                                alt="QR" 
                                style={{ width: '100px', height: '100px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.15)', background: 'white', padding: '4px', cursor: 'pointer' }} 
                              />
                            ) : (
                              <div style={{ width: '100px', height: '100px', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(255,255,255,0.05)', borderRadius: '8px', fontSize: '10px' }}>⏳</div>
                            )}
                          </div>

                          {/* Column 2: Buttons Stack (70%) */}
                          <div style={{ width: '70%', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                            <button 
                              onClick={() => handleCopy(cfg.link, `${cfg.id}_config`)}
                              className="btn btn-primary"
                              style={{ padding: '6px 12px', fontSize: '12px', height: '32px', borderRadius: '8px', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px' }}
                            >
                              <span>💝</span>
                              <span>{copiedId === `${cfg.id}_config` ? 'کپی شد' : 'کپی کانفیگ'}</span>
                            </button>
                            
                            {cfg.volume_web_link && (
                              <a 
                                href={cfg.volume_web_link}
                                target="_blank" 
                                rel="noopener noreferrer"
                                className="btn btn-primary"
                                style={{ padding: '6px 12px', fontSize: '12px', height: '32px', borderRadius: '8px', textDecoration: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', width: '100%' }}
                              >
                                <span>🔋</span>
                                <span>مشاهده پنل وب</span>
                              </a>
                            )}

                            {cfg.subscription_link && (
                              <a 
                                href={cfg.subscription_link}
                                target="_blank" 
                                rel="noopener noreferrer"
                                className="btn btn-primary"
                                style={{ padding: '6px 12px', fontSize: '12px', height: '32px', borderRadius: '8px', textDecoration: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', width: '100%' }}
                              >
                                <span>🌐</span>
                                <span>لینک سابسکریپشن</span>
                              </a>
                            )}
                          </div>
                        </div>

                        {/* Action buttons row */}
                        <div style={{ display: 'flex', gap: '6px' }}>
                          <button 
                            onClick={() => {
                              const curP = cfg.fileid && cfg.fileid != 0 ? plans.find(p => p.id == cfg.fileid) : null;
                              const isTrial = curP && (curP.price === 0 || curP.title.includes('تست') || curP.title.toLowerCase().includes('test') || curP.title.toLowerCase().includes('trial'));
                              setActiveRenewConfig(cfg);
                              setRenewPlanId(curP && !isTrial ? curP.id.toString() : '');
                              setRenewMethod('wallet');
                            }}
                            className="btn btn-success" 
                            style={{ flex: 1, padding: '8px 4px', fontSize: '11px', borderRadius: '10px' }}
                          >
                            🔄 تمدید کانفیگ
                          </button>
                          <button 
                            onClick={() => setActiveDetailsConfig(cfg)}
                            className="btn btn-primary" 
                            style={{ flex: 1, padding: '8px 4px', fontSize: '11px', borderRadius: '10px' }}
                          >
                            🔍 جزئیات بیشتر
                          </button>
                          <button 
                            onClick={() => handleDeleteConfig(cfg.id)}
                            className="btn btn-danger" 
                            style={{ padding: '8px 12px', fontSize: '11px', borderRadius: '10px' }}
                          >
                            🗑️ حذف
                          </button>
                        </div>
                      </>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* VIEW 3: Purchase Plan */}
        {activeTab === 'buy-plans' && (
          <div>
            <h2 style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px' }}>
              📍 خرید کانفیگ جدید
            </h2>
            
            {servers.length === 0 ? (
              <p style={{ textAlign: 'center', color: 'var(--text-secondary)' }}>هیچ سروری در دیتابیس تعریف نشده است.</p>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                
                {/* 1. Server Selector */}
                <div className="form-group">
                  <label className="form-label" style={{ fontWeight: 'bold' }}>➊ انتخاب سرور:</label>
                  <select 
                    value={selectedServerId} 
                    onChange={(e) => {
                      setSelectedServerId(e.target.value);
                      setSelectedCategoryId('');
                      setSelectedPlanId('');
                    }}
                    className="form-input"
                  >
                    <option value="">-- لطفا یک سرور انتخاب کنید --</option>
                    {servers.map(server => (
                      <option key={server.id} value={server.id}>{server.name}</option>
                    ))}
                  </select>
                </div>

                {/* 2. Category Selector (Only visible if server is selected) */}
                {selectedServerId && (() => {
                  const activeCatIds = Array.from(new Set(
                    plans.filter(p => p.server_id == selectedServerId).map(p => p.catid)
                  ));
                  const serverCats = categories.filter(c => activeCatIds.includes(c.id));

                  return (
                    <div className="form-group">
                      <label className="form-label" style={{ fontWeight: 'bold' }}>➋ انتخاب دسته‌بندی:</label>
                      {serverCats.length === 0 ? (
                        <p style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>هیچ دسته‌بندی فعالی برای این سرور وجود ندارد.</p>
                      ) : (
                        <select 
                          value={selectedCategoryId} 
                          onChange={(e) => {
                            setSelectedCategoryId(e.target.value);
                            setSelectedPlanId('');
                          }}
                          className="form-input"
                        >
                          <option value="">-- لطفا یک دسته‌بندی انتخاب کنید --</option>
                          {serverCats.map(cat => (
                            <option key={cat.id} value={cat.id}>{cat.title}</option>
                          ))}
                        </select>
                      )}
                    </div>
                  );
                })()}

                {/* 3. Plan Selector (Only visible if category is selected) */}
                {selectedServerId && selectedCategoryId && (() => {
                  const categoryPlans = plans.filter(p => p.server_id == selectedServerId && p.catid == selectedCategoryId);

                  return (
                    <div className="form-group">
                      <label className="form-label" style={{ fontWeight: 'bold' }}>➌ انتخاب پلن:</label>
                      {categoryPlans.length === 0 ? (
                        <p style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>هیچ پلنی در این دسته‌بندی یافت نشد.</p>
                      ) : (
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                          {categoryPlans.map(plan => (
                            <div 
                              key={plan.id}
                              onClick={() => setSelectedPlanId(plan.id)}
                              className="glass-card"
                              style={{
                                display: 'flex',
                                justifyContent: 'space-between',
                                alignItems: 'center',
                                border: selectedPlanId == plan.id ? '2px solid var(--color-primary)' : '1px solid var(--panel-border)',
                                cursor: 'pointer',
                                background: selectedPlanId == plan.id ? 'rgba(59, 130, 246, 0.05)' : 'rgba(255,255,255,0.01)',
                                transition: 'all 0.2s'
                              }}
                            >
                              <div>
                                <span style={{ fontSize: '13px', display: 'block', fontWeight: 'bold' }}>{plan.title}</span>
                                <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>
                                  حجم: {plan.volume} گیگ | مدت: {parseInt(plan.days) === 0 ? 'نامحدود' : `${plan.days} روز`}
                                </span>
                              </div>
                              <span style={{ fontSize: '14px', fontWeight: 'bold', color: 'var(--color-primary)' }}>
                                {plan.price.toLocaleString()} تومان
                              </span>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                })()}

                {/* 4. Payment Info (Only visible if plan is selected) */}
                {selectedServerId && selectedCategoryId && selectedPlanId && (() => {
                  const plan = plans.find(p => p.id == selectedPlanId);
                  if (!plan) return null;

                  const hasEnoughWallet = user && (user.wallet >= plan.price);

                  return (
                    <div className="glass-card" style={{ border: '1px solid var(--panel-border)', marginTop: '10px' }}>
                      <h3 style={{ fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>➍ روش پرداخت</h3>
                      
                      {/* Payment Method Toggle Tabs */}
                      <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', background: 'rgba(255,255,255,0.02)', padding: '4px', borderRadius: '8px' }}>
                        <button 
                          type="button"
                          onClick={() => setPlanPurchaseMethod('wallet')} 
                          className={`btn ${planPurchaseMethod === 'wallet' ? 'btn-primary' : ''}`}
                          style={{ flex: 1, padding: '8px 2px', fontSize: '11px', borderRadius: '6px' }}
                        >
                          کیف پول دیجیتال
                        </button>
                        <button 
                          type="button"
                          onClick={() => setPlanPurchaseMethod('card')} 
                          className={`btn ${planPurchaseMethod === 'card' ? 'btn-primary' : ''}`}
                          style={{ flex: 1, padding: '8px 2px', fontSize: '11px', borderRadius: '6px' }}
                        >
                          کارت‌به‌کارت مستقیم
                        </button>
                      </div>

                      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '12px' }}>
                        <span style={{ color: 'var(--text-secondary)' }}>قیمت پلن:</span>
                        <span style={{ fontWeight: 'bold' }}>{plan.price.toLocaleString()} تومان</span>
                      </div>

                      {planPurchaseMethod === 'wallet' ? (
                        <>
                          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '16px' }}>
                            <span style={{ color: 'var(--text-secondary)' }}>موجودی کیف پول شما:</span>
                            <span style={{ fontWeight: 'bold', color: hasEnoughWallet ? 'var(--color-success)' : 'var(--color-danger)' }}>
                              {user ? user.wallet.toLocaleString() : 0} تومان
                            </span>
                          </div>

                          {hasEnoughWallet ? (
                            <button 
                              onClick={() => handleBuyPlan(plan.id)}
                              disabled={isPurchasing}
                              className="btn btn-success" 
                              style={{ width: '100%', padding: '12px', fontWeight: 'bold' }}
                            >
                              {isPurchasing ? 'در حال صدور اکانت...' : 'خرید با کیف پول (پرداخت مستقیم)'}
                            </button>
                          ) : (
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                              <div style={{ background: 'rgba(239, 68, 68, 0.05)', border: '1px solid rgba(239, 68, 68, 0.1)', padding: '10px', borderRadius: '8px', fontSize: '11px', textAlign: 'center', color: 'var(--color-danger)' }}>
                                موجودی کیف پول شما کافی نیست. لطفا ابتدا آن را شارژ کنید یا از پرداخت مستقیم کارت‌به‌کارت استفاده کنید.
                              </div>
                              <button 
                                onClick={() => setActiveTab('wallet-charge')}
                                className="btn btn-primary" 
                                style={{ width: '100%', padding: '12px', fontWeight: 'bold' }}
                              >
                                💳 شارژ کیف پول و کارت‌به‌کارت
                              </button>
                            </div>
                          )}
                        </>
                      ) : (
                        <form onSubmit={handleSubmitPlanReceipt} style={{ display: 'flex', flexDirection: 'column', gap: '12px', marginTop: '8px' }}>
                          {/* Card details */}
                          <div style={{ background: 'rgba(255,255,255,0.02)', padding: '12px', borderRadius: '12px', fontSize: '12px', border: '1px dashed var(--panel-border)' }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                              <span style={{ color: 'var(--text-secondary)' }}>شماره کارت جهت واریز:</span>
                              <span style={{ fontWeight: 'bold', display: 'flex', alignItems: 'center', gap: '6px' }}>
                                <code>{paymentKeys.bank_account || 'بارگذاری نشده'}</code>
                                {paymentKeys.bank_account && (
                                  <button 
                                    type="button" 
                                    onClick={() => handleCopy(paymentKeys.bank_account, 'bank_card_plan')}
                                    className="btn btn-primary"
                                    style={{ padding: '2px 6px', fontSize: '10px', height: 'auto', display: 'inline-flex', alignItems: 'center', borderRadius: '6px' }}
                                  >
                                    {copiedId === 'bank_card_plan' ? 'کپی شد' : 'کپی'}
                                  </button>
                                )}
                              </span>
                            </div>
                            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                              <span style={{ color: 'var(--text-secondary)' }}>به نام:</span>
                              <span style={{ fontWeight: 'bold' }}>{paymentKeys.holder_name || 'بارگذاری نشده'}</span>
                            </div>
                            <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginTop: '8px', textAlign: 'center' }}>
                              💡 مبلغ <b>{plan.price.toLocaleString()} تومان</b> را به کارت فوق واریز کرده و رسید آن را در کادر زیر آپلود کنید.
                            </div>
                          </div>

                          <div className="form-group" style={{ margin: 0 }}>
                            <label className="form-label" style={{ fontSize: '11px' }}>نام دلخواه برای سرویس (اختیاری)</label>
                            <input 
                              type="text" 
                              value={planRemark} 
                              onChange={(e) => setPlanRemark(e.target.value)} 
                              placeholder="مثال: سرویس تست جدید" 
                              className="form-input" 
                            />
                          </div>

                          <div className="form-group" style={{ margin: 0 }}>
                            <label className="form-label" style={{ fontSize: '11px' }}>تصویر رسید پرداخت (اسکرین‌شات)</label>
                            <div 
                              onClick={() => document.getElementById('plan-receipt-file-input').click()}
                              onDragOver={(e) => e.preventDefault()}
                              onDrop={(e) => {
                                e.preventDefault();
                                if (e.dataTransfer.files && e.dataTransfer.files[0]) {
                                  setPlanReceiptFile(e.dataTransfer.files[0]);
                                  setPlanReceiptPreview(URL.createObjectURL(e.dataTransfer.files[0]));
                                }
                              }}
                              style={{
                                border: '2px dashed rgba(255,255,255,0.15)',
                                borderRadius: '12px',
                                padding: '20px',
                                textAlign: 'center',
                                cursor: 'pointer',
                                background: 'rgba(255,255,255,0.01)',
                                transition: 'all 0.2s',
                              }}
                            >
                              <input 
                                type="file" 
                                id="plan-receipt-file-input" 
                                accept="image/*" 
                                onChange={(e) => {
                                  if (e.target.files && e.target.files[0]) {
                                    setPlanReceiptFile(e.target.files[0]);
                                    setPlanReceiptPreview(URL.createObjectURL(e.target.files[0]));
                                  }
                                }} 
                                style={{ display: 'none' }} 
                              />
                              {planReceiptPreview ? (
                                <img src={planReceiptPreview} alt="رسید" style={{ maxHeight: '100px', display: 'block', margin: '0 auto', borderRadius: '6px' }} />
                              ) : (
                                <p style={{ fontSize: '11px', color: 'var(--text-secondary)', margin: 0 }}>
                                  برای انتخاب تصویر رسید، اینجا را لمس کنید
                                </p>
                              )}
                            </div>
                          </div>

                          <button 
                            type="submit" 
                            disabled={isSubmittingPlanReceipt}
                            className="btn btn-success" 
                            style={{ width: '100%', padding: '12px', fontWeight: 'bold' }}
                          >
                            {isSubmittingPlanReceipt ? 'در حال ارسال رسید...' : 'ارسال رسید جهت تایید و خرید'}
                          </button>
                        </form>
                      )}
                    </div>
                  );
                })()}

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

        {/* VIEW 4: Wallet & Charge */}
        {activeTab === 'wallet-charge' && (
          <div>
            <h2 style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '12px' }}>شارژ کیف پول کاربری</h2>
            
            {/* Card to card info */}
            <div className="glass-card" style={{ marginBottom: '16px' }}>
              <h3 style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>واریز نقدی و ثبت کارت‌به‌کارت</h3>
              <div style={{ background: 'rgba(255,255,255,0.02)', padding: '12px', borderRadius: '12px', fontSize: '13px', border: '1px dashed var(--panel-border)', marginBottom: '16px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                  <span style={{ color: 'var(--text-secondary)' }}>شماره کارت واریز:</span>
                  <span style={{ fontWeight: 'bold', display: 'flex', alignItems: 'center', gap: '6px' }}>
                    <code>{paymentKeys.bank_account || 'بارگذاری نشده'}</code>
                    {paymentKeys.bank_account && (
                      <button 
                        type="button" 
                        onClick={() => handleCopy(paymentKeys.bank_account, 'bank_card')}
                        className="btn btn-primary"
                        style={{ padding: '2px 6px', fontSize: '10px', height: 'auto', display: 'inline-flex', alignItems: 'center', borderRadius: '6px' }}
                      >
                        {copiedId === 'bank_card' ? 'کپی شد' : 'کپی'}
                      </button>
                    )}
                  </span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ color: 'var(--text-secondary)' }}>به نام:</span>
                  <span style={{ fontWeight: 'bold' }}>{paymentKeys.holder_name || 'بارگذاری نشده'}</span>
                </div>
              </div>

              <form onSubmit={handleSubmitReceipt}>
                <div className="form-group">
                  <label className="form-label">مبلغ پرداختی (تومان)</label>
                  <input 
                    type="number" 
                    value={manualPayAmount} 
                    onChange={(e) => setManualPayAmount(e.target.value)} 
                    placeholder="مثال: ۵۰۰۰۰" 
                    className="form-input" 
                    required 
                  />
                </div>
                <div className="form-group">
                  <label className="form-label">تصویر رسید پرداخت (اسکرین‌شات)</label>
                  <div 
                    onClick={() => document.getElementById('receipt-file-input').click()}
                    style={{
                      border: '2px dashed rgba(255,255,255,0.15)',
                      borderRadius: '12px',
                      padding: '24px',
                      textAlign: 'center',
                      cursor: 'pointer',
                      background: 'rgba(255,255,255,0.01)',
                      transition: 'all 0.2s',
                    }}
                    onDragOver={(e) => e.preventDefault()}
                    onDrop={(e) => {
                      e.preventDefault();
                      if (e.dataTransfer.files && e.dataTransfer.files[0]) {
                        setReceiptFile(e.dataTransfer.files[0]);
                      }
                    }}
                  >
                    <input 
                      type="file" 
                      id="receipt-file-input" 
                      style={{ display: 'none' }} 
                      accept="image/*"
                      onChange={(e) => {
                        if (e.target.files && e.target.files[0]) {
                          setReceiptFile(e.target.files[0]);
                        }
                      }}
                    />
                    <div style={{ fontSize: '28px', marginBottom: '8px' }}>📸</div>
                    {receiptFile ? (
                      <span style={{ fontSize: '12px', color: 'var(--color-success)', fontWeight: 'bold' }}>
                        ✅ {receiptFile.name} ({Math.round(receiptFile.size / 1024)} KB)
                      </span>
                    ) : (
                      <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>
                        برای انتخاب فایل ضربه بزنید یا تصویر را به اینجا بکشید
                      </span>
                    )}
                  </div>
                </div>
                <button type="submit" className="btn btn-success" style={{ width: '100%', padding: '12px', borderRadius: '12px' }}>ثبت رسید پرداخت</button>
              </form>

              {submitPayMsg && (
                <div style={{ marginTop: '12px', padding: '10px', borderRadius: '8px', fontSize: '12px', background: submitPayMsg.type === 'success' ? 'rgba(16,185,129,0.1)' : 'rgba(239,68,68,0.1)', color: submitPayMsg.type === 'success' ? 'var(--color-success)' : 'var(--color-danger)' }}>
                  {submitPayMsg.text}
                </div>
              )}
            </div>
          </div>
        )}

        {/* VIEW 5: Ticket support system */}
        {activeTab === 'tickets' && (
          <div>
            {!activeTicket ? (
              <div>
                <h2 style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '12px' }}>
                  {user?.isAdmin ? 'مدیریت و پاسخ‌دهی به تیکت‌ها' : 'پشتیبانی و ثبت تیکت جدید'}
                </h2>
                
                {/* Add ticket form (only for non-admins) */}
                {!user?.isAdmin && (
                  <div className="glass-card" style={{ marginBottom: '16px' }}>
                    <form onSubmit={handleCreateTicket}>
                      <div className="form-group">
                        <label className="form-label">موضوع تیکت</label>
                        <input 
                          type="text" 
                          value={newTicketTitle} 
                          onChange={(e) => setNewTicketTitle(e.target.value)} 
                          className="form-input" 
                          placeholder="مثال: عدم دریافت اطلاعات کانفیگ"
                          maxLength={100}
                          required 
                        />
                      </div>
                      <div className="form-group">
                        <label className="form-label">بخش مربوطه</label>
                        <select 
                          value={newTicketCategory} 
                          onChange={(e) => setNewTicketCategory(e.target.value)} 
                          className="form-input"
                          style={{ background: '#13141f' }}
                        >
                          <option value="بررسی کانفیگ">بررسی کانفیگ</option>
                          <option value="فنی">پشتیبانی فنی</option>
                          <option value="مالی">امور مالی</option>
                          <option value="شکایت">شکایت</option>
                        </select>
                      </div>
                      <div className="form-group">
                        <label className="form-label">پیام</label>
                        <textarea 
                          value={newTicketText} 
                          onChange={(e) => setNewTicketText(e.target.value)} 
                          className="form-input" 
                          rows="3" 
                          placeholder="جزئیات پیام خود را اینجا بنویسید..."
                          required={!newTicketFile} 
                        />
                      </div>
                      <div className="form-group" style={{ marginBottom: '16px' }}>
                        <label className="form-label">فایل پیوست (تصویر یا سند - اختیاری)</label>
                        <div 
                          style={{
                            border: '2px dashed rgba(255, 255, 255, 0.1)',
                            borderRadius: '12px',
                            padding: '16px',
                            textAlign: 'center',
                            cursor: 'pointer',
                            background: 'rgba(255,255,255,0.01)',
                            transition: 'border-color 0.2s'
                          }}
                          onClick={() => document.getElementById('new-ticket-file-input').click()}
                        >
                          <input 
                            type="file" 
                            id="new-ticket-file-input" 
                            style={{ display: 'none' }} 
                            onChange={(e) => {
                              const file = e.target.files[0];
                              if (file) {
                                setNewTicketFile(file);
                                if (file.type.startsWith('image/')) {
                                  setNewTicketFilePreview(URL.createObjectURL(file));
                                } else {
                                  setNewTicketFilePreview('');
                                }
                              }
                            }} 
                          />
                          {newTicketFile ? (
                            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '8px' }}>
                              {newTicketFilePreview && (
                                <img src={newTicketFilePreview} alt="Preview" style={{ maxWidth: '80px', maxHeight: '80px', borderRadius: '8px', objectFit: 'cover' }} />
                              )}
                              <span style={{ fontSize: '12px', color: 'var(--color-success)', fontWeight: 'bold' }}>
                                ✅ {newTicketFile.name} ({Math.round(newTicketFile.size / 1024)} KB)
                              </span>
                            </div>
                          ) : (
                            <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>
                              برای انتخاب فایل ضربه بزنید یا تصویر را به اینجا بکشید
                            </span>
                          )}
                        </div>
                      </div>
                      <button type="submit" className="btn btn-primary" style={{ width: '100%' }}>ارسال تیکت</button>
                    </form>
                  </div>
                )}

                {/* Two Square Filter Cards */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '16px' }}>
                  <div 
                    onClick={() => setTicketFilter('open')}
                    style={{
                      background: ticketFilter === 'open' ? 'rgba(52, 152, 219, 0.15)' : 'rgba(255, 255, 255, 0.02)',
                      border: ticketFilter === 'open' ? '1px solid var(--color-primary)' : '1px solid rgba(255, 255, 255, 0.05)',
                      borderRadius: '16px',
                      padding: '16px',
                      textAlign: 'center',
                      cursor: 'pointer',
                      transition: 'all 0.2s',
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      justifyContent: 'center',
                      gap: '8px'
                    }}
                  >
                    <span style={{ fontSize: '28px' }}>✉️</span>
                    <span style={{ fontSize: '13px', fontWeight: 'bold', color: 'white' }}>تیکت‌های باز</span>
                    <span style={{ fontSize: '10px', color: 'var(--color-primary)', fontWeight: 'bold' }}>
                      {tickets.filter(t => parseInt(t.state) !== 2).length} تیکت
                    </span>
                  </div>

                  <div 
                    onClick={() => setTicketFilter('closed')}
                    style={{
                      background: ticketFilter === 'closed' ? 'rgba(46, 204, 113, 0.15)' : 'rgba(255, 255, 255, 0.02)',
                      border: ticketFilter === 'closed' ? '1px solid var(--color-success)' : '1px solid rgba(255, 255, 255, 0.05)',
                      borderRadius: '16px',
                      padding: '16px',
                      textAlign: 'center',
                      cursor: 'pointer',
                      transition: 'all 0.2s',
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      justifyContent: 'center',
                      gap: '8px'
                    }}
                  >
                    <span style={{ fontSize: '28px' }}>✅</span>
                    <span style={{ fontSize: '13px', fontWeight: 'bold', color: 'white' }}>تیکت‌های بسته</span>
                    <span style={{ fontSize: '10px', color: 'var(--color-success)', fontWeight: 'bold' }}>
                      {tickets.filter(t => parseInt(t.state) === 2).length} تیکت
                    </span>
                  </div>
                </div>

                {/* Filtered Tickets List */}
                <h3 style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '10px' }}>
                  {ticketFilter === 'open' ? 'تیکت‌های باز و در انتظار پاسخ' : 'تاریخچه تیکت‌های بسته شده'}
                </h3>
                {tickets.filter(t => ticketFilter === 'open' ? parseInt(t.state) !== 2 : parseInt(t.state) === 2).length === 0 ? (
                  <p style={{ textAlign: 'center', color: 'var(--text-secondary)', padding: '20px' }}>تیکتی در این بخش وجود ندارد.</p>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                    {tickets.filter(t => ticketFilter === 'open' ? parseInt(t.state) !== 2 : parseInt(t.state) === 2).map(ticket => (
                      <div 
                        key={ticket.id} 
                        onClick={() => {
                          setActiveTicket(ticket);
                          fetchTicketMessages(ticket.id);
                        }} 
                        className="glass-card" 
                        style={{ cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '10px' }}
                      >
                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                          <div style={{ position: 'relative', display: 'inline-block' }}>
                            {user?.isAdmin && ticket.user_photo ? (
                              <img 
                                src={ticket.user_photo} 
                                alt="Avatar" 
                                style={{ width: '36px', height: '36px', borderRadius: '50%', objectFit: 'cover' }} 
                              />
                            ) : (
                              <div style={{ width: '36px', height: '36px', borderRadius: '50%', background: 'var(--color-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '14px' }}>
                                ✉️
                              </div>
                            )}
                            <div style={{
                              position: 'absolute',
                              bottom: '0',
                              right: '0',
                              width: '10px',
                              height: '10px',
                              borderRadius: '50%',
                              background: parseInt(ticket.state) !== 2 ? '#2ecc71' : '#95a5a6',
                              border: '2px solid #13141f'
                            }} />
                          </div>
                          <div>
                            <span style={{ fontWeight: 'bold', display: 'block', fontSize: '13px' }}>{ticket.title}</span>
                            <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>
                              {user?.isAdmin ? `کاربر: ${ticket.user_name || 'نامشخص'} | دسته‌بندی: ${ticket.category}` : `دسته‌بندی: ${ticket.category}`}
                              {ticket.create_date && ` | 🗓️ ${formatPersianDate(ticket.create_date)}`}
                            </span>
                          </div>
                        </div>
                        <span className={`badge ${parseInt(ticket.state) === 2 ? 'badge-danger' : (parseInt(ticket.state) === 1 ? 'badge-success' : 'badge-primary')}`}>
                          {parseInt(ticket.state) === 2 ? 'بسته شده' : (parseInt(ticket.state) === 1 ? 'پاسخ داده شده' : 'پاسخ داده نشده')}
                        </span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            ) : (
              /* Telegram Style Chat View (Sender is on Right, Receiver is on Left) */
              <div style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 160px)', minHeight: '450px' }}>
                {/* Telegram Chat Header with Action Buttons at Top, and Info at Bottom */}
                <div style={{ 
                  display: 'flex', 
                  flexDirection: 'column', 
                  gap: '12px', 
                  marginBottom: '16px', 
                  background: 'rgba(255,255,255,0.02)', 
                  padding: '12px 14px', 
                  borderRadius: '16px', 
                  border: '1px solid rgba(255,255,255,0.05)' 
                }}>
                  {/* Row 1: Action Buttons */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px', width: '100%' }}>
                    <button onClick={() => { setActiveTicket(null); fetchTickets(); window.location.hash = 'tickets'; }} className="btn btn-danger" style={{ padding: '6px 12px', borderRadius: '8px', fontSize: '12px', flex: 1 }}>بازگشت</button>
                    <button 
                      onClick={() => handleRefreshChat(activeTicket.id)} 
                      className="btn btn-primary" 
                      style={{ padding: '6px 12px', borderRadius: '8px', fontSize: '12px', flex: 1, background: 'rgba(59, 130, 246, 0.2)', border: '1px solid var(--color-primary)' }}
                    >
                      🔄 بروزرسانی
                    </button>
                    {parseInt(activeTicket.state) !== 2 && (
                      <button 
                        onClick={() => {
                          setRatingValue(5);
                          setShowRatingModal(true);
                        }} 
                        className="btn btn-danger" 
                        style={{ padding: '6px 12px', borderRadius: '8px', fontSize: '12px', flex: 1, background: 'rgba(231, 76, 60, 0.2)', border: '1px solid #e74c3c' }}
                      >
                        🔒 بستن تیکت
                      </button>
                    )}
                  </div>
                  
                  <hr style={{ border: 'none', borderTop: '1px solid rgba(255,255,255,0.05)', margin: '0' }} />

                  {/* Row 2: Ticket User Details */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                    {/* Header Avatar */}
                    <div style={{ position: 'relative', display: 'inline-block' }}>
                      {(() => {
                        const headerAvatar = user.isAdmin ? (chatUserInfo?.photo || '') : (user.photo_url || '');
                        if (headerAvatar) {
                          return (
                            <img 
                              src={headerAvatar} 
                              alt="Avatar" 
                              style={{ width: '40px', height: '40px', borderRadius: '50%', objectFit: 'cover', border: '1px solid rgba(255,255,255,0.1)' }} 
                            />
                          );
                        } else {
                          return (
                            <div style={{ width: '40px', height: '40px', borderRadius: '50%', background: 'var(--color-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 'bold', color: 'white', fontSize: '13px' }}>
                              {user.isAdmin ? (chatUserInfo?.name ? chatUserInfo.name.substring(0, 2) : 'US') : (user.name ? user.name.substring(0, 2) : 'US')}
                            </div>
                          );
                        }
                      })()}
                      
                      {/* Active Status Light */}
                      <div style={{
                        position: 'absolute',
                        bottom: '0',
                        right: '0',
                        width: '11px',
                        height: '11px',
                        borderRadius: '50%',
                        background: parseInt(activeTicket.state) !== 2 ? '#2ecc71' : '#e74c3c',
                        border: '2px solid #1a1b26'
                      }} />
                    </div>

                    <div style={{ display: 'flex', flexDirection: 'column', gap: '2px', textAlign: 'right' }}>
                      <span style={{ fontSize: '13px', fontWeight: 'bold', color: 'white' }}>
                        موضوع: {activeTicket.title}
                      </span>
                      <span style={{ fontSize: '10px', color: parseInt(activeTicket.state) !== 2 ? '#2ecc71' : 'var(--text-secondary)' }}>
                        {user?.isAdmin ? (chatUserInfo?.name ? `${chatUserInfo.name} | ` : '') : ''}
                        {parseInt(activeTicket.state) !== 2 ? '● آنلاین / در انتظار پاسخ' : '● بسته شده / غیرفعال'}
                      </span>
                    </div>
                  </div>
                </div> {/* پایان هدر چت */}
                <div className="glass-card" style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '16px', padding: '16px', marginBottom: '12px', overflowY: 'auto', background: 'rgba(15, 17, 26, 0.7)' }}>
                  {(() => {
                    let lastDateStr = '';
                    return ticketMessages.map((msg, index) => {
                      // Case-insensitive msg_type evaluation
                      const isAdminMsg = msg.msg_type && msg.msg_type.toLowerCase() === 'admin';
                      
                      // Determine if I am the sender of this message
                      const isMe = user.isAdmin ? isAdminMsg : !isAdminMsg;
                      
                      // Avatar and sender name resolution
                      const myPhoto = user.photo_url || '';
                      const otherPhoto = user.isAdmin ? (chatUserInfo?.photo || '') : (chatAdminInfo?.photo || '');
                      const avatar = isMe ? myPhoto : otherPhoto;
                      
                      const senderName = isMe ? 'شما' : (user.isAdmin ? (chatUserInfo?.name || 'کاربر') : 'پشتیبانی');
                      
                      // Format message date for date separators
                      const msgDate = new Date(msg.sent_date * 1000);
                      const msgDateStr = msgDate.toLocaleDateString('fa-IR', { weekday: 'long', day: 'numeric', month: 'long' });
                      let showDateSeparator = false;
                      if (msgDateStr !== lastDateStr) {
                        showDateSeparator = true;
                        lastDateStr = msgDateStr;
                      }

                      return (
                        <div key={index} style={{ display: 'flex', flexDirection: 'column', width: '100%' }}>
                          {/* Date Separator Banner */}
                          {showDateSeparator && (
                            <div style={{ alignSelf: 'center', margin: '8px 0', padding: '4px 12px', borderRadius: '12px', background: 'rgba(255,255,255,0.05)', fontSize: '10px', color: 'var(--text-secondary)', fontWeight: 'bold' }}>
                              {msgDateStr}
                            </div>
                          )}

                          <div 
                            style={{
                              display: 'flex',
                              alignItems: 'flex-start',
                              gap: '8px',
                              alignSelf: isMe ? 'flex-start' : 'flex-end',
                              flexDirection: isMe ? 'row' : 'row-reverse',
                              maxWidth: '85%',
                              marginTop: '4px'
                            }}
                          >
                            {/* Avatar with Status Light */}
                            <div style={{ position: 'relative', display: 'inline-block' }}>
                              {avatar ? (
                                <img 
                                  src={avatar} 
                                  alt={senderName} 
                                  style={{ width: '32px', height: '32px', borderRadius: '50%', objectFit: 'cover', border: '1px solid rgba(255,255,255,0.1)' }} 
                                />
                              ) : (
                                <div style={{ width: '32px', height: '32px', borderRadius: '50%', background: isMe ? 'var(--color-success)' : 'var(--color-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '11px', fontWeight: 'bold', color: 'white' }}>
                                  {isMe ? 'من' : 'او'}
                                </div>
                              )}
                              <div style={{
                                position: 'absolute',
                                bottom: '0',
                                right: '0',
                                width: '8px',
                                height: '8px',
                                borderRadius: '50%',
                                background: isMe ? '#2ecc71' : (activeTicket.state === 1 ? '#2ecc71' : '#e74c3c'),
                                border: '1px solid #15161f'
                              }} />
                            </div>

                            {/* Bubble */}
                            <div 
                              style={{
                                background: isMe ? 'rgba(46, 204, 113, 0.15)' : 'rgba(52, 152, 219, 0.15)',
                                border: isMe ? '1px solid rgba(46, 204, 113, 0.3)' : '1px solid rgba(52, 152, 219, 0.3)',
                                borderRadius: '16px',
                                padding: '10px 14px',
                                position: 'relative'
                              }}
                            >
                              <span style={{ display: 'block', fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '3px', fontWeight: 'bold' }}>
                                {senderName}
                              </span>
                              
                              {/* Replied Message Preview inside Bubble */}
                              {(() => {
                                if (msg.reply_to_id) {
                                  const repliedMsg = ticketMessages.find(m => parseInt(m.id) === parseInt(msg.reply_to_id));
                                  if (repliedMsg) {
                                    return (
                                      <div 
                                        style={{
                                          background: 'rgba(255, 255, 255, 0.08)',
                                          borderRight: '3px solid var(--color-primary)',
                                          padding: '6px 10px',
                                          borderRadius: '8px',
                                          marginBottom: '8px',
                                          fontSize: '11px',
                                          textAlign: 'right'
                                        }}
                                      >
                                        <span style={{ fontWeight: 'bold', display: 'block', color: 'var(--text-secondary)', fontSize: '10px' }}>
                                          {repliedMsg.msg_type && repliedMsg.msg_type.toLowerCase() === 'admin' ? 'پشتیبانی' : (user.isAdmin ? (chatUserInfo?.name || 'کاربر') : 'شما')}
                                        </span>
                                        <span style={{ color: 'rgba(255,255,255,0.7)', display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '200px' }}>
                                          {(() => {
                                            let fileData = null;
                                            try {
                                              if (repliedMsg.text && (repliedMsg.text.trim().startsWith('{') || repliedMsg.text.trim().startsWith('['))) {
                                                fileData = JSON.parse(repliedMsg.text);
                                              }
                                            } catch (e) {}
                                            if (fileData && fileData.file_id) {
                                              return `📎 فایل ارسالی (${fileData.file_type || 'فایل'})`;
                                            }
                                            return repliedMsg.text;
                                          })()}
                                        </span>
                                      </div>
                                    );
                                  }
                                }
                                return null;
                              })()}

                              <span style={{ display: 'block', fontSize: '13px', color: 'white', whiteSpace: 'pre-wrap', lineHeight: '1.5', wordBreak: 'break-all' }}>
                                {(() => {
                                  let fileData = null;
                                  try {
                                    if (msg.text && (msg.text.trim().startsWith('{') || msg.text.trim().startsWith('['))) {
                                      fileData = JSON.parse(msg.text);
                                    }
                                  } catch (e) {
                                    fileData = null;
                                  }

                                  if (fileData && fileData.file_id) {
                                    const fileType = fileData.file_type || 'file';
                                    const caption = fileData.caption || '';
                                    let emoji = '📎';
                                    if (fileType === 'photo') emoji = '🖼️';
                                    else if (fileType === 'video') emoji = '🎥';
                                    else if (fileType === 'voice') emoji = '🎙️';
                                    else if (fileType === 'audio') emoji = '🎵';

                                    return (
                                      <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', minWidth: '180px' }}>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', background: 'rgba(255,255,255,0.05)', padding: '8px 12px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.1)' }}>
                                          <span style={{ fontSize: '18px' }}>{emoji}</span>
                                          <div style={{ display: 'flex', flexDirection: 'column' }}>
                                            <span style={{ fontSize: '12px', fontWeight: 'bold', color: 'white' }}>فایل ارسالی ({fileType === 'voice' ? 'وویس' : fileType})</span>
                                            {caption && <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>{caption}</span>}
                                          </div>
                                        </div>
                                        <button 
                                          type="button"
                                          onClick={() => handleDownloadFileInTelegram(fileData.file_id, fileType, caption)}
                                          className="btn btn-primary"
                                          style={{ padding: '6px 12px', fontSize: '11px', height: 'auto', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', width: '100%', borderRadius: '8px', marginTop: '4px' }}
                                        >
                                          📥 دریافت در تلگرام
                                        </button>
                                      </div>
                                    );
                                  }

                                  return msg.text;
                                })()}
                              </span>
                              <span style={{ display: 'block', fontSize: '8px', color: 'var(--text-secondary)', marginTop: '4px', textAlign: isMe ? 'left' : 'right' }}>
                                {new Date(msg.sent_date * 1000).toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' })}
                              </span>
                            </div>

                            {/* Reply Action Button */}
                            <button
                              type="button"
                              onClick={() => setReplyToMessage(msg)}
                              style={{
                                background: 'none',
                                border: 'none',
                                color: 'var(--text-secondary)',
                                cursor: 'pointer',
                                padding: '4px',
                                fontSize: '12px',
                                alignSelf: 'center',
                                display: 'flex',
                                alignItems: 'center',
                                opacity: 0.6
                              }}
                              title="پاسخ"
                            >
                              ↩️
                            </button>
                          </div>
                        </div>
                      );
                    });
                  })()}
                  {ticketMessages.length === 0 && (
                    <p style={{ textAlign: 'center', color: 'var(--text-secondary)', fontSize: '12px' }}>پیامی در این تیکت وجود ندارد.</p>
                  )}
                  <div ref={messagesEndRef} />
                </div>

                {replyToMessage && (
                  <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    background: 'rgba(59, 130, 246, 0.1)',
                    border: '1px solid rgba(59, 130, 246, 0.2)',
                    padding: '8px 12px',
                    borderRadius: '12px',
                    marginBottom: '8px',
                    fontSize: '12px'
                  }}>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '2px', textAlign: 'right' }}>
                      <span style={{ fontWeight: 'bold', color: 'var(--color-primary)' }}>
                        پاسخ به: {replyToMessage.msg_type && replyToMessage.msg_type.toLowerCase() === 'admin' ? 'پشتیبانی' : (user.isAdmin ? (chatUserInfo?.name || 'کاربر') : 'شما')}
                      </span>
                      <span style={{ color: 'var(--text-secondary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '250px' }}>
                        {(() => {
                          let fileData = null;
                          try {
                            if (replyToMessage.text && (replyToMessage.text.trim().startsWith('{') || replyToMessage.text.trim().startsWith('['))) {
                              fileData = JSON.parse(replyToMessage.text);
                            }
                          } catch (e) {}
                          if (fileData && fileData.file_id) {
                            return `📎 فایل ارسالی (${fileData.file_type || 'فایل'})`;
                          }
                          return replyToMessage.text;
                        })()}
                      </span>
                    </div>
                    <button 
                      onClick={() => setReplyToMessage(null)} 
                      style={{ background: 'none', border: 'none', color: '#ef4444', fontSize: '14px', cursor: 'pointer', fontWeight: 'bold' }}
                    >
                      ✕
                    </button>
                  </div>
                )}

                <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                  <input 
                    type="file" 
                    id="chat-file-upload" 
                    style={{ display: 'none' }} 
                    onChange={handleUploadChatFile}
                  />
                  <button 
                    type="button" 
                    onClick={() => document.getElementById('chat-file-upload').click()} 
                    className="btn btn-primary" 
                    style={{ padding: '12px', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(59, 130, 246, 0.2)', border: '1px solid var(--color-primary)' }}
                  >
                    📎
                  </button>
                  <input 
                    type="text" 
                    value={chatInput} 
                    onChange={(e) => setChatInput(e.target.value)} 
                    placeholder="پیام خود را بنویسید..." 
                    className="form-input" 
                    style={{ flex: 1 }} 
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') handleSendReply();
                    }}
                  />
                  <button onClick={handleSendReply} className="btn btn-success" style={{ padding: '12px' }}><Send size={16} /></button>
                </div>
              </div>
            )}
          </div>
        )}

        {/* VIEW 6: Reseller Panel */}
        {activeTab === 'reseller-panel' && (user.is_agent || user.isAdmin) && (
          <div style={{ background: 'var(--bg-glass)', borderRadius: '16px', padding: '16px', border: '1px solid var(--border-glass)' }}>
            
            {/* Tabs Header */}
            <div style={{ display: 'flex', borderBottom: '1px solid rgba(255,255,255,0.1)', marginBottom: '16px', paddingBottom: '8px', gap: '8px', overflowX: 'auto', whiteSpace: 'nowrap' }}>
              {[
                { id: 'financial-dashboard', label: 'داشبورد مالی' },
                { id: 'clients-management', label: user.isAdmin ? 'مدیریت کل کلاینت‌ها' : 'مدیریت کلاینت‌ها' },
                user.isAdmin ? { id: 'agents-management', label: 'مدیریت نمایندگان' } : null,
                { id: 'custom-configs', label: 'کانفیگ سفارشی' }
              ].filter(Boolean).map(t => (
                <button
                  key={t.id}
                  onClick={() => setResellerTab(t.id)}
                  style={{
                    padding: '6px 12px',
                    fontSize: '12px',
                    borderRadius: '8px',
                    border: 'none',
                    background: resellerTab === t.id ? 'var(--color-primary)' : 'transparent',
                    color: resellerTab === t.id ? 'white' : 'var(--text-secondary)',
                    fontWeight: resellerTab === t.id ? 'bold' : 'normal',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                >
                  {t.label}
                </button>
              ))}
            </div>

            {/* TAB 1: Financial Dashboard */}
            {resellerTab === 'financial-dashboard' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                <div className="glass-card" style={{ display: 'flex', alignItems: 'center', gap: '14px', padding: '20px' }}>
                  <div style={{ width: '48px', height: '48px', borderRadius: '12px', background: 'rgba(59,130,246,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '24px' }}>💼</div>
                  <div>
                    <span style={{ fontSize: '12px', color: 'var(--text-secondary)', display: 'block' }}>{user.isAdmin ? 'کل موجودی کیف پول ادمین' : 'اعتبار فعلی نمایندگی'}</span>
                    <span style={{ fontSize: '20px', fontWeight: 'bold', color: 'white' }}>{formatPrice(user.wallet)} تومان</span>
                  </div>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                  <div className="glass-card" style={{ padding: '14px', textAlign: 'center' }}>
                    <span style={{ fontSize: '11px', color: 'var(--text-secondary)', display: 'block', marginBottom: '4px' }}>تعداد کلاینت‌ها</span>
                    <span style={{ fontSize: '18px', fontWeight: 'bold', color: 'white' }}>{agentClients.length}</span>
                  </div>
                  <div className="glass-card" style={{ padding: '14px', textAlign: 'center' }}>
                    <span style={{ fontSize: '11px', color: 'var(--text-secondary)', display: 'block', marginBottom: '4px' }}>فروش ماه جاری</span>
                    <span style={{ fontSize: '18px', fontWeight: 'bold', color: 'white' }}>
                      {formatPrice(agentClients.reduce((acc, c) => {
                        const orderDate = new Date((c.date || 0) * 1000);
                        const now = new Date();
                        if (orderDate.getMonth() === now.getMonth() && orderDate.getFullYear() === now.getFullYear()) {
                          return acc + (c.amount || 0);
                        }
                        return acc;
                      }, 0))} تومان
                    </span>
                  </div>
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                  <div style={{ display: 'flex', gap: '10px' }}>
                    <button onClick={() => setShowBulkPurchaseModal(true)} className="btn btn-primary" style={{ flex: 1, padding: '10px' }}>+ خرید انبوه جدید</button>
                    <button onClick={() => setActiveTab('buy-plans')} className="btn btn-success" style={{ flex: 1, padding: '10px' }}>خرید تکی</button>
                  </div>
                  <button 
                    onClick={() => {
                      if (servers && servers.length > 0) {
                        setCustomConfigServer(servers[0].id);
                      }
                      setShowCustomConfigModal(true);
                    }} 
                    className="btn btn-primary" 
                    style={{ width: '100%', padding: '10px', background: 'rgba(59, 130, 246, 0.15)', border: '1px solid var(--color-primary)' }}
                  >
                    🛠️ کانفیگ سفارشی نمایندگی
                  </button>
                </div>
              </div>
            )}

            {/* TAB 2: Clients Management */}
            {resellerTab === 'clients-management' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                <h3 style={{ fontSize: '13px', fontWeight: 'bold', marginBottom: '6px' }}>
                  {user.isAdmin ? 'کل کلاینت‌های نمایندگی‌ها' : 'کلاینت‌های شما'}
                </h3>
                {agentClients.length === 0 ? (
                  <p style={{ fontSize: '12px', color: 'var(--text-secondary)', textAlign: 'center', padding: '20px' }}>هیچ کلاینتی ثبت نشده است.</p>
                ) : (
                  agentClients.map(c => {
                    const remark = c.remark || '';
                    const getFlag = (rem) => {
                      const r = rem.toLowerCase();
                      if (r.includes('آلمان') || r.includes('germany') || r.includes('de')) return '🇩🇪';
                      if (r.includes('فرانسه') || r.includes('france') || r.includes('fr')) return '🇫🇷';
                      if (r.includes('هلند') || r.includes('netherlands') || r.includes('nl')) return '🇳🇱';
                      if (r.includes('ترکیه') || r.includes('turkey') || r.includes('tr')) return '🇹🇷';
                      if (r.includes('انگلیس') || r.includes('uk') || r.includes('gb')) return '🇬🇧';
                      if (r.includes('آمریکا') || r.includes('usa') || r.includes('us')) return '🇺🇸';
                      return '🌐';
                    };
                    const getFlagName = (rem) => {
                      const r = rem.toLowerCase();
                      if (r.includes('آلمان') || r.includes('germany') || r.includes('de')) return 'آلمان پرمیوم';
                      if (r.includes('فرانسه') || r.includes('france') || r.includes('fr')) return 'فرانسه توربو';
                      if (r.includes('هلند') || r.includes('netherlands') || r.includes('nl')) return 'هلند پرسرعت';
                      if (r.includes('ترکیه') || r.includes('turkey') || r.includes('tr')) return 'ترکیه';
                      return 'سرویس اشتراکی';
                    };

                    const total = c.stats?.total || 0;
                    const used = c.stats?.used || 0;
                    const pct = total > 0 ? Math.min(100, Math.round((used / total) * 100)) : 0;
                    const totalGB = (total / (1024 * 1024 * 1024)).toFixed(1);
                    const usedGB = (used / (1024 * 1024 * 1024)).toFixed(1);

                    return (
                      <div key={c.id} className="glass-card" style={{ padding: '10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px' }}>
                        
                        {/* Right Section: Flag & Name */}
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', width: '35%' }}>
                          <span style={{ fontSize: '24px' }}>{getFlag(remark)}</span>
                          <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
                            <span style={{ fontSize: '12px', fontWeight: 'bold', color: 'white' }}>{getFlagName(remark)}</span>
                            {c.agent_name && (
                              <span style={{ fontSize: '9px', color: 'var(--color-primary)' }}>نماینده: {c.agent_name}</span>
                            )}
                            <span style={{ fontSize: '9px', color: 'var(--text-secondary)' }}>UID: {c.uuid ? c.uuid.substring(0, 8) : 'نامشخص'}</span>
                          </div>
                        </div>

                        {/* Middle Section: Progress Bar & Expiry */}
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', width: '35%', alignItems: 'center' }}>
                          <div style={{ width: '100%', height: '6px', background: 'rgba(255,255,255,0.05)', borderRadius: '3px', overflow: 'hidden' }}>
                            <div style={{ width: `${pct}%`, height: '100%', background: pct > 80 ? 'var(--color-danger)' : 'var(--color-success)', borderRadius: '3px' }} />
                          </div>
                          <span style={{ fontSize: '9px', color: 'var(--text-secondary)' }}>مصرف {pct}% | {usedGB}/{totalGB} گیگ</span>
                          <span style={{ fontSize: '9px', color: 'var(--text-secondary)' }}>🗓️ {c.expire_date ? new Date(c.expire_date * 1000).toLocaleDateString('fa-IR') : 'نامحدود'}</span>
                        </div>

                        {/* Left Section: Action Buttons */}
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', width: '25%' }}>
                          <button 
                            onClick={() => {
                              setActiveRenewConfig(c);
                              setRenewPlanId('');
                              setRenewMethod('wallet');
                              setActiveTab('subscriptions');
                            }}
                            className="btn btn-primary" 
                            style={{ padding: '4px 0', fontSize: '9px', height: '20px', borderRadius: '4px', width: '100%' }}
                          >
                            + افزایش حجم
                          </button>
                          <button 
                            onClick={() => {
                              const curP = c.fileid && c.fileid != 0 ? plans.find(p => p.id == c.fileid) : null;
                              const isTrial = curP && (curP.price === 0 || curP.title.includes('تست') || curP.title.toLowerCase().includes('test') || curP.title.toLowerCase().includes('trial'));
                              setActiveRenewConfig(c);
                              setRenewPlanId(curP && !isTrial ? curP.id.toString() : '');
                              setRenewMethod('wallet');
                              setActiveTab('subscriptions');
                            }}
                            className="btn btn-success" 
                            style={{ padding: '4px 0', fontSize: '9px', height: '20px', borderRadius: '4px', width: '100%' }}
                          >
                            تمدید
                          </button>
                        </div>

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

            {/* TAB: Agents Management (Admin Only) */}
            {resellerTab === 'agents-management' && user.isAdmin && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                <h3 style={{ fontSize: '13px', fontWeight: 'bold', marginBottom: '6px' }}>کل نمایندگان سیستم</h3>
                {allAgentsList.length === 0 ? (
                  <p style={{ fontSize: '12px', color: 'var(--text-secondary)', textAlign: 'center', padding: '20px' }}>نماینده‌ای یافت نشد.</p>
                ) : (
                  allAgentsList.map(ag => (
                    <div key={ag.userid} className="glass-card" style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <div>
                          <span style={{ fontWeight: 'bold', display: 'block', fontSize: '13px', color: 'white' }}>{ag.name}</span>
                          <span style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>آیدی عددی: {ag.userid} | یوزرنیم: @{ag.username || 'ندارد'}</span>
                        </div>
                        <span className="badge badge-success">فعال</span>
                      </div>
                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', borderTop: '1px solid rgba(255,255,255,0.05)', paddingTop: '8px', fontSize: '10px', color: 'var(--text-secondary)' }}>
                        <div>
                          <span>اعتبار: </span>
                          <span style={{ color: 'white', fontWeight: 'bold' }}>{formatPrice(ag.wallet)} تومان</span>
                        </div>
                        <div>
                          <span>حجم کل: </span>
                          <span style={{ color: 'white', fontWeight: 'bold' }}>{ag.agent_volume} GB</span>
                        </div>
                        <div>
                          <span>فروش: </span>
                          <span style={{ color: 'white', fontWeight: 'bold' }}>{ag.configs_sold} عدد</span>
                        </div>
                      </div>
                      
                      {/* Action buttons for reseller management */}
                      <div style={{ display: 'flex', gap: '8px', marginTop: '6px' }}>
                        <button 
                          onClick={() => handleMessageAgent(ag.userid)} 
                          className="btn btn-primary" 
                          style={{ flex: 1, padding: '6px 0', fontSize: '10px', borderRadius: '8px' }}
                        >
                          💬 پیام خصوصی
                        </button>
                        <button 
                          onClick={() => handleDeleteAgent(ag.userid)} 
                          className="btn btn-danger" 
                          style={{ flex: 1, padding: '6px 0', fontSize: '10px', borderRadius: '8px' }}
                        >
                          🗑️ حذف نماینده
                        </button>
                      </div>
                    </div>
                  ))
                )}
              </div>
            )}



            {/* TAB 4: Custom Configs */}
            {resellerTab === 'custom-configs' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                {/* 1. Circular Statistics */}
                <div className="glass-card" style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'center', padding: '16px', gap: '12px' }}>
                  {/* Volume Circular Stats */}
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '6px' }}>
                    <div style={{ position: 'relative', width: '70px', height: '70px' }}>
                      <svg width="70" height="70" viewBox="0 0 70 70" style={{ transform: 'rotate(-90deg)' }}>
                        <circle cx="35" cy="35" r="28" fill="transparent" stroke="rgba(255,255,255,0.05)" strokeWidth="6" />
                        <circle 
                          cx="35" 
                          cy="35" 
                          r="28" 
                          fill="transparent" 
                          stroke="var(--color-primary)" 
                          strokeWidth="6" 
                          strokeDasharray={`${2 * Math.PI * 28}`}
                          strokeDashoffset={`${user.agent_volume > 0 ? (2 * Math.PI * 28) * (1 - Math.min(1, user.agent_volume / 100)) : 0}`}
                        />
                      </svg>
                      <div style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '10px', fontWeight: 'bold' }}>
                        {user.agent_volume == 0 ? '∞' : `${Math.round(user.agent_volume)}G`}
                      </div>
                    </div>
                    <span style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>سهمیه حجم</span>
                  </div>

                  {/* Limit/Accounts Circular Stats */}
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '6px' }}>
                    <div style={{ position: 'relative', width: '70px', height: '70px' }}>
                      <svg width="70" height="70" viewBox="0 0 70 70" style={{ transform: 'rotate(-90deg)' }}>
                        <circle cx="35" cy="35" r="28" fill="transparent" stroke="rgba(255,255,255,0.05)" strokeWidth="6" />
                        <circle 
                          cx="35" 
                          cy="35" 
                          r="28" 
                          fill="transparent" 
                          stroke="var(--color-success)" 
                          strokeWidth="6" 
                          strokeDasharray={`${2 * Math.PI * 28}`}
                          strokeDashoffset={`${user.agent_limit > 0 ? (2 * Math.PI * 28) * (1 - Math.min(1, user.agent_limit / 50)) : 0}`}
                        />
                      </svg>
                      <div style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '10px', fontWeight: 'bold' }}>
                        {user.agent_limit == 0 ? '∞' : user.agent_limit}
                      </div>
                    </div>
                    <span style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>اکانت قابل ساخت</span>
                  </div>

                  {/* Test Limits Circular Stats */}
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '6px' }}>
                    <div style={{ position: 'relative', width: '70px', height: '70px' }}>
                      <svg width="70" height="70" viewBox="0 0 70 70" style={{ transform: 'rotate(-90deg)' }}>
                        <circle cx="35" cy="35" r="28" fill="transparent" stroke="rgba(255,255,255,0.05)" strokeWidth="6" />
                        <circle 
                          cx="35" 
                          cy="35" 
                          r="28" 
                          fill="transparent" 
                          stroke="var(--color-danger)" 
                          strokeWidth="6" 
                          strokeDasharray={`${2 * Math.PI * 28}`}
                          strokeDashoffset={`${user.agent_test_limit > 0 ? (2 * Math.PI * 28) * (1 - Math.min(1, user.agent_test_limit / 10)) : (2 * Math.PI * 28)}`}
                        />
                      </svg>
                      <div style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '10px', fontWeight: 'bold' }}>
                        {user.agent_test_limit}
                      </div>
                    </div>
                    <span style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>اکانت تست</span>
                  </div>
                </div>

                {/* 2. Success Result Alert */}
                {customConfigSuccess && (
                  <div className="glass-card" style={{ border: '1px solid var(--color-success)', padding: '14px', background: 'rgba(16,185,129,0.08)' }}>
                    <span style={{ display: 'block', fontSize: '12px', fontWeight: 'bold', color: 'var(--color-success)', marginBottom: '8px' }}>✅ کانفیگ جدید با موفقیت ساخته شد:</span>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', fontSize: '12px' }}>
                      <div><b>نام کاربری:</b> <code>{customConfigSuccess.remark}</code></div>
                      <div><b>لینک اتصال:</b> <code style={{ wordBreak: 'break-all', display: 'block', background: 'rgba(0,0,0,0.2)', padding: '6px', borderRadius: '6px', marginTop: '4px' }}>{customConfigSuccess.link}</code></div>
                      <div><b>لینک اشتراک:</b> <code style={{ wordBreak: 'break-all', display: 'block', background: 'rgba(0,0,0,0.2)', padding: '6px', borderRadius: '6px', marginTop: '4px' }}>{customConfigSuccess.subscription}</code></div>
                      <button onClick={() => { navigator.clipboard.writeText(customConfigSuccess.link); alert('کپی شد!'); }} className="btn btn-primary" style={{ padding: '6px 12px', fontSize: '11px', alignSelf: 'flex-start', marginTop: '4px' }}>📋 کپی لینک کانفیگ</button>
                    </div>
                  </div>
                )}

                {/* 3. Create Custom Config Form */}
                <div className="glass-card" style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                  <h3 style={{ fontSize: '13px', fontWeight: 'bold' }}>➕ ساخت کانفیگ جدید (کسر از سهمیه)</h3>
                  {customConfigError && <div style={{ fontSize: '12px', color: 'var(--color-danger)' }}>⚠️ {customConfigError}</div>}
                  
                  <form onSubmit={handleCreateCustomConfig} style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                    <div className="form-group" style={{ marginBottom: 0 }}>
                      <span className="form-label">سرور میزبان</span>
                      <select 
                        className="form-input" 
                        value={customConfigServerId} 
                        onChange={(e) => setCustomConfigServerId(e.target.value)} 
                        required
                        style={{ background: 'rgba(15, 17, 26, 0.7)' }}
                      >
                        <option value="">انتخاب سرور...</option>
                        {servers.map(s => (
                          <option key={s.id} value={s.id}>{s.flag} {s.name}</option>
                        ))}
                      </select>
                    </div>

                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
                      <div className="form-group" style={{ marginBottom: 0 }}>
                        <span className="form-label">حجم (گیگابایت)</span>
                        <input 
                          type="number" 
                          className="form-input" 
                          value={customConfigVolume} 
                          onChange={(e) => setCustomConfigVolume(e.target.value)} 
                          placeholder="مثال: ۱۰"
                          required
                          min="1"
                        />
                      </div>
                      <div className="form-group" style={{ marginBottom: 0 }}>
                        <span className="form-label">زمان (روز)</span>
                        <input 
                          type="number" 
                          className="form-input" 
                          value={customConfigDays} 
                          onChange={(e) => setCustomConfigDays(e.target.value)} 
                          placeholder="مثال: ۳۰"
                          required
                          min="1"
                        />
                      </div>
                    </div>

                    <div className="form-group" style={{ marginBottom: 8 }}>
                      <span className="form-label">محدودیت IP</span>
                      <select 
                        className="form-input" 
                        value={customConfigLimitIp} 
                        onChange={(e) => setCustomConfigLimitIp(e.target.value)}
                        style={{ background: 'rgba(15, 17, 26, 0.7)' }}
                      >
                        <option value="1">۱ کاربر</option>
                        <option value="2">۲ کاربر</option>
                        <option value="3">۳ کاربر</option>
                        <option value="0">نامحدود</option>
                      </select>
                    </div>

                    <button type="submit" disabled={customConfigLoading} className="btn btn-success" style={{ width: '100%' }}>
                      {customConfigLoading ? 'در حال ایجاد...' : 'ساخت و کسر از سهمیه'}
                    </button>
                  </form>
                </div>

                {/* 4. Test Config & Quota Buying */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '12px' }}>
                  {/* Test Account Section */}
                  <div className="glass-card" style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                    <h3 style={{ fontSize: '13px', fontWeight: 'bold' }}>🎁 دریافت اکانت تست نمایندگی</h3>
                    <p style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>سهمیه اکانت تست رایگان فعلی: <b>{user.agent_test_limit} عدد</b></p>
                    
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <button 
                        onClick={() => {
                          handleCreateTestConfig('');
                        }} 
                        disabled={user.agent_test_limit <= 0 || customConfigLoading} 
                        className="btn btn-primary" 
                        style={{ width: '100%', padding: '12px', fontSize: '13px', fontWeight: 'bold' }}
                      >
                        دریافت اکانت تست نمایندگی
                      </button>
                    </div>
                  </div>

                  {/* Quota Purchase Section */}
                  <div className="glass-card" style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                    <h3 style={{ fontSize: '13px', fontWeight: 'bold' }}>🛍 خرید سهمیه جدید نمایندگی</h3>
                    <p style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>از اعتبار کیف پول شما کسر خواهد شد (موجودی: {formatPrice(user.wallet)} تومان)</p>
                    
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                      {plans.filter(p => p.type === 'agent_quota').map(plan => (
                        <div key={plan.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'rgba(255,255,255,0.02)', padding: '10px', borderRadius: '10px', border: '1px solid rgba(255,255,255,0.04)' }}>
                          <div style={{ display: 'flex', flexDirection: 'column', textAlign: 'right', gap: '2px' }}>
                            <span style={{ fontSize: '12px', fontWeight: 'bold', color: 'white' }}>{plan.title}</span>
                            <span style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>حجم: {plan.volume}GB | تعداد: {plan.acount} عدد</span>
                            <span style={{ fontSize: '11px', color: 'var(--color-primary)' }}>قیمت: {formatPrice(plan.price)} تومان</span>
                          </div>
                          <button 
                            onClick={() => handleBuyQuota(plan.id)} 
                            disabled={customConfigLoading} 
                            className="btn btn-success" 
                            style={{ padding: '8px 14px', fontSize: '12px' }}
                          >
                            خرید طرح
                          </button>
                        </div>
                      ))}
                      {plans.filter(p => p.type === 'agent_quota').length === 0 && (
                        <span style={{ fontSize: '11px', color: 'var(--text-secondary)', textAlign: 'center' }}>هیچ طرح خریدی فعلاً وجود ندارد.</span>
                      )}
                    </div>
                  </div>
                </div>

                {/* 5. Manage Created Configs */}
                <div className="glass-card" style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                  <h3 style={{ fontSize: '13px', fontWeight: 'bold' }}>📋 مدیریت کانفیگ‌های تولید شده</h3>
                  
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', maxHeight: '400px', overflowY: 'auto' }}>
                    {agentClients.map(client => (
                      <div key={client.id} style={{ display: 'flex', flexDirection: 'column', gap: '8px', background: 'rgba(255,255,255,0.02)', padding: '12px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.05)', textAlign: 'right' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span style={{ fontSize: '13px', fontWeight: 'bold', color: 'white' }}>{client.remark}</span>
                          <span className={`badge ${client.stats?.state === 'active' ? 'badge-success' : 'badge-danger'}`}>
                            {client.stats?.state === 'active' ? 'فعال' : 'غیرفعال'}
                          </span>
                        </div>

                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', fontSize: '11px', color: 'var(--text-secondary)' }}>
                          <div><b>حجم اختصاصی:</b> {client.fileid} GB</div>
                          <div><b>حجم مصرف شده:</b> {client.stats ? (client.stats.used / 1073741824).toFixed(2) : 0} GB</div>
                          <div><b>تاریخ انقضا:</b> {client.expire_date > 0 ? formatPersianDate(client.expire_date) : 'نامحدود'}</div>
                          <div><b>سرور:</b> {servers.find(s => s.id === client.server_id)?.name || 'نامشخص'}</div>
                        </div>

                        <div style={{ display: 'flex', gap: '8px', marginTop: '6px' }}>
                          <button 
                            onClick={() => handleModifyConfig(client.id, 'add_volume')} 
                            className="btn btn-primary" 
                            style={{ flex: 1, padding: '6px 10px', fontSize: '11px', background: 'rgba(59, 130, 246, 0.15)', border: '1px solid var(--color-primary)' }}
                          >
                            ➕ افزایش حجم
                          </button>
                          <button 
                            onClick={() => handleModifyConfig(client.id, 'add_days')} 
                            className="btn btn-success" 
                            style={{ flex: 1, padding: '6px 10px', fontSize: '11px', background: 'rgba(16, 185, 129, 0.15)', border: '1px solid var(--color-success)' }}
                          >
                            ⏳ افزایش زمان
                          </button>
                        </div>
                      </div>
                    ))}
                    {agentClients.length === 0 && (
                      <span style={{ fontSize: '11px', color: 'var(--text-secondary)', textAlign: 'center', padding: '16px' }}>شما هنوز هیچ کانفیگی ایجاد نکرده‌اید.</span>
                    )}
                  </div>
                </div>
              </div>
            )}

          </div>
        )}

        {/* VIEW 7: Administrative Panel */}
        {activeTab === 'admin-panel' && user.isAdmin && (
          <div>
            <h2 style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '16px' }}>کنسول مدیریت سیستم ربات</h2>
            
            {/* Admin Switch Account Form */}
            <div className="glass-card" style={{ marginBottom: '16px', border: '1px solid rgba(239,68,68,0.2)' }}>
              <h3 style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '8px', color: 'var(--color-danger)' }}>🕵️ سوییچ اکانت (مشاهده حساب کاربران)</h3>
              <form onSubmit={handleSwitchAccount} style={{ display: 'flex', gap: '8px' }}>
                <input 
                  type="number" 
                  value={viewAsUserId} 
                  onChange={(e) => setViewAsUserId(e.target.value)} 
                  placeholder="شناسه کاربری مورد نظر (مثال: 8938192)" 
                  className="form-input" 
                  style={{ flex: 1 }} 
                  required 
                />
                <button type="submit" className="btn btn-danger" style={{ padding: '10px 16px', fontSize: '12px' }}>سوییچ</button>
              </form>
            </div>

            {/* Admin metrics */}
            {adminStats && (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '10px', marginBottom: '16px' }}>
                <div className="glass-card" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <Users size={20} style={{ color: 'var(--color-primary)' }} />
                  <div>
                    <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>کل کاربران</span>
                    <span style={{ fontWeight: 'bold', display: 'block' }}>{adminStats.users} نفر</span>
                  </div>
                </div>
                <div className="glass-card" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <Activity size={20} style={{ color: 'var(--color-success)' }} />
                  <div>
                    <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>تراکنش‌های معلق</span>
                    <span style={{ fontWeight: 'bold', display: 'block' }}>{adminStats.pending_payments} رسید</span>
                  </div>
                </div>
                <div className="glass-card" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <Ticket size={20} style={{ color: 'var(--color-primary)' }} />
                  <div>
                    <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>تیکت‌های باز</span>
                    <span style={{ fontWeight: 'bold', display: 'block' }}>{adminStats.active_tickets || 0} تیکت</span>
                  </div>
                </div>
              </div>
            )}

            {/* Verification Queue */}
            <div className="glass-card" style={{ marginBottom: '16px' }}>
              <h3 style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>تایید کارت‌به‌کارت‌های معلق</h3>
              {adminPendingReceipts.length === 0 ? (
                <p style={{ textAlign: 'center', color: 'var(--text-secondary)', fontSize: '12px' }}>رسید معلقی در سیستم ثبت نشده است.</p>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                  {adminPendingReceipts.map(rec => (
                    <div key={rec.id} style={{ border: '1px solid var(--panel-border)', padding: '10px', borderRadius: '12px', background: 'rgba(255,255,255,0.01)' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                        <span style={{ fontWeight: 'bold' }}>{rec.user_name || 'کاربر بدون نام'}</span>
                        <span style={{ color: 'var(--color-primary)', fontWeight: 'bold' }}>{rec.price.toLocaleString()} تومان</span>
                      </div>
                      <p style={{ fontSize: '11px', color: 'var(--text-secondary)', marginBottom: '8px' }}>{rec.description} | تاریخ: {new Date(rec.request_date * 1000).toLocaleDateString('fa-IR')}</p>
                      <div style={{ display: 'flex', gap: '6px' }}>
                        <button onClick={() => handleAdminVerifyPayment(rec.id, 'approve')} className="btn btn-success" style={{ padding: '4px 10px', fontSize: '11px', flex: 1 }}>تایید فیش</button>
                        <button onClick={() => handleAdminVerifyPayment(rec.id, 'decline')} className="btn btn-danger" style={{ padding: '4px 10px', fontSize: '11px' }}>رد فیش</button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Ticket Management */}
            <div className="glass-card" style={{ marginBottom: '16px' }}>
              <h3 style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>تیکت‌های باز پشتیبانی</h3>
              {adminActiveTickets.length === 0 ? (
                <p style={{ textAlign: 'center', color: 'var(--text-secondary)', fontSize: '12px' }}>تیکت باز و پاسخ داده نشده‌ای وجود ندارد.</p>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                  {adminActiveTickets.map(tick => (
                    <div 
                      key={tick.id} 
                      onClick={() => {
                        setActiveTicket(tick);
                        setActiveTab('tickets');
                        fetchTicketMessages(tick.id);
                      }} 
                      className="glass-card" 
                      style={{ cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'rgba(255,255,255,0.01)' }}
                    >
                      <div>
                        <span style={{ fontWeight: 'bold', display: 'block', fontSize: '13px' }}>{tick.title}</span>
                        <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>ارسال کننده: {tick.user_name} | بخش: {tick.category}</span>
                      </div>
                      <span className="badge badge-primary">پاسخ بدهید</span>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Edit User settings */}
            <div className="glass-card">
              <h3 style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>جستجو و ویرایش کاربران</h3>
              <div style={{ display: 'flex', gap: '8px', marginBottom: '12px' }}>
                <input 
                  type="text" 
                  value={adminSearchQuery} 
                  onChange={(e) => setAdminSearchQuery(e.target.value)} 
                  placeholder="شناسه عددی یا نام کاربری..." 
                  className="form-input" 
                  style={{ flex: 1 }} 
                />
                <button onClick={handleAdminSearch} className="btn btn-primary">جستجو</button>
              </div>

              {editingUser ? (
                <form onSubmit={handleAdminEditUser} style={{ background: 'rgba(0,0,0,0.1)', padding: '12px', borderRadius: '12px', border: '1px solid var(--panel-border)' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
                    <span style={{ fontWeight: 'bold' }}>ویرایش: {editingUser.name}</span>
                    <button type="button" onClick={() => setEditingUser(null)} style={{ background: 'none', border: 'none', color: 'var(--color-danger)', cursor: 'pointer' }}>لغو</button>
                  </div>
                  
                  <div className="form-group">
                    <label className="form-label">موجودی کیف پول (ریال)</label>
                    <input 
                      type="number" 
                      value={editingUser.wallet} 
                      onChange={(e) => setEditingUser({ ...editingUser, wallet: e.target.value })} 
                      className="form-input" 
                    />
                  </div>

                  <div className="form-group" style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
                    <label className="form-label" style={{ marginBottom: 0 }}>نماینده فروش:</label>
                    <input 
                      type="checkbox" 
                      checked={parseInt(editingUser.is_agent) === 1} 
                      onChange={(e) => setEditingUser({ ...editingUser, is_agent: e.target.checked ? 1 : 0 })} 
                      style={{ width: '18px', height: '18px' }}
                    />
                  </div>

                  <div className="form-group" style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
                    <label className="form-label" style={{ marginBottom: 0 }}>ادمین سیستم:</label>
                    <input 
                      type="checkbox" 
                      checked={parseInt(editingUser.isAdmin) === 1} 
                      onChange={(e) => setEditingUser({ ...editingUser, isAdmin: e.target.checked ? 1 : 0 })} 
                      style={{ width: '18px', height: '18px' }}
                    />
                  </div>

                  {parseInt(editingUser.is_agent) === 1 && (
                    <>
                      <div className="form-group">
                        <label className="form-label">حجم اختصاصی همکار (GB)</label>
                        <input 
                          type="number" 
                          value={editingUser.agent_volume} 
                          onChange={(e) => setEditingUser({ ...editingUser, agent_volume: e.target.value })} 
                          className="form-input" 
                        />
                      </div>
                      <div className="form-group">
                        <label className="form-label">محدودیت تعداد کاربر همکار</label>
                        <input 
                          type="number" 
                          value={editingUser.agent_limit} 
                          onChange={(e) => setEditingUser({ ...editingUser, agent_limit: e.target.value })} 
                          className="form-input" 
                        />
                      </div>
                    </>
                  )}

                  <button type="submit" className="btn btn-success" style={{ width: '100%' }}>ذخیره تغییرات کاربر</button>
                </form>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
                  {adminUsersList.map(u => (
                    <div key={u.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'rgba(255,255,255,0.02)', padding: '8px 12px', borderRadius: '8px' }}>
                      <div>
                        <span style={{ fontWeight: 'bold', fontSize: '13px' }}>{u.name}</span>
                        <span style={{ display: 'block', fontSize: '11px', color: 'var(--text-secondary)' }}>ID: {u.userid} | موجودی: {u.wallet.toLocaleString()} تومان</span>
                      </div>
                      <button onClick={() => setEditingUser(u)} className="btn btn-primary" style={{ padding: '4px 10px', fontSize: '11px' }}>ویرایش</button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}

      </div>

      {/* 1. Success Message Modal */}
      {successModalMsg && (
        <div style={{
          position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
          background: 'rgba(0,0,0,0.8)', display: 'flex', justifyContent: 'center',
          alignItems: 'center', zIndex: 1000, padding: '20px', direction: 'rtl'
        }}>
          <div className="glass-card" style={{ width: '100%', maxWidth: '400px', textAlign: 'center', border: '1px solid var(--color-success)', boxShadow: '0 0 30px rgba(16,185,129,0.2)' }}>
            <div style={{ fontSize: '40px', marginBottom: '12px' }}>✅</div>
            <h3 style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '12px', color: 'white' }}>عملیات موفقیت‌آمیز</h3>
            <p style={{ fontSize: '13px', color: 'var(--text-secondary)', marginBottom: '20px', lineHeight: '1.6' }}>
              {successModalMsg}
            </p>
            <button 
              onClick={async () => {
                setSuccessModalMsg('');
                setActiveTab('subscriptions');
                await fetchDashboardData();
                await fetchSubscriptions();
              }}
              className="btn btn-success" 
              style={{ width: '100%' }}
            >
              تایید و مشاهده سرویس‌ها
            </button>
          </div>
        </div>
      )}

      {/* 2. Renew Config Modal */}
      {activeRenewConfig && (
        <div style={{
          position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
          background: 'rgba(0,0,0,0.8)', display: 'flex', justifyContent: 'center',
          alignItems: 'center', zIndex: 1000, padding: '20px', direction: 'rtl',
          overflowY: 'auto'
        }}>
          <div className="glass-card" style={{ width: '100%', maxWidth: '420px', maxHeight: '90vh', overflowY: 'auto' }}>
            <h3 style={{ fontSize: '15px', fontWeight: 'bold', marginBottom: '14px', borderBottom: '1px solid rgba(255,255,255,0.05)', paddingBottom: '10px' }}>
              ♻️ تمدید سرویس: {activeRenewConfig.remark}
            </h3>

            {(() => {
              const currentPlan = (activeRenewConfig.fileid && activeRenewConfig.fileid != 0) ? plans.find(p => p.id == activeRenewConfig.fileid) : null;
              const isTrial = currentPlan && (currentPlan.price === 0 || currentPlan.title.includes('تست') || currentPlan.title.toLowerCase().includes('test') || currentPlan.title.toLowerCase().includes('trial'));
              if (currentPlan && !isTrial) {
                return (
                  <div style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.05)', borderRadius: '12px', padding: '12px', marginBottom: '14px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '6px' }}>
                      <span style={{ color: 'var(--text-secondary)' }}>پلن فعلی سرویس:</span>
                      <span style={{ fontWeight: 'bold', color: 'white' }}>{currentPlan.title}</span>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '6px' }}>
                      <span style={{ color: 'var(--text-secondary)' }}>حجم تمدید:</span>
                      <span style={{ fontWeight: 'bold', color: 'white' }}>{currentPlan.volume} گیگابایت</span>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px' }}>
                      <span style={{ color: 'var(--text-secondary)' }}>مدت تمدید:</span>
                      <span style={{ fontWeight: 'bold', color: 'white' }}>{currentPlan.days} روز</span>
                    </div>
                  </div>
                );
              }
              return (
                <div className="form-group">
                  <label className="form-label" style={{ fontWeight: 'bold' }}>➊ انتخاب پلن تمدید:</label>
                  <select 
                    value={renewPlanId} 
                    onChange={(e) => setRenewPlanId(e.target.value)}
                    className="form-input"
                    style={{ background: 'rgba(15, 17, 26, 0.7)' }}
                  >
                    <option value="">-- لطفا یک پلن انتخاب کنید --</option>
                    {plans.filter(p => p.server_id == activeRenewConfig.server_id).map(plan => (
                      <option key={plan.id} value={plan.id}>
                        {plan.title} ({plan.volume} گیگ / {plan.days} روز) - {plan.price.toLocaleString()} تومان
                      </option>
                    ))}
                  </select>
                </div>
              );
            })()}

            {renderRenewPaymentDetails()}

            <button 
              onClick={() => setActiveRenewConfig(null)}
              className="btn btn-danger" 
              style={{ width: '100%', marginTop: '8px', borderRadius: '10px', background: 'rgba(239, 68, 68, 0.1)', color: 'var(--color-danger)' }}
            >
              انصراف
            </button>
          </div>
        </div>
      )}

      {/* 3. Details / Successful Issue Modal */}
      {activeDetailsConfig && (
        <div style={{
          position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
          background: 'rgba(0,0,0,0.8)', display: 'flex', justifyContent: 'center',
          alignItems: 'center', zIndex: 1000, padding: '20px', direction: 'rtl'
        }}>
          <div className="glass-card" style={{ width: '100%', maxWidth: '400px', border: '1px solid var(--color-primary)' }}>
            <div style={{ textAlign: 'center', marginBottom: '14px' }}>
              <div style={{ fontSize: '32px' }}>✨</div>
              <h3 style={{ fontSize: '15px', fontWeight: 'bold', color: 'white', marginTop: '6px' }}>جزئیات اشتراک خریداری شده</h3>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', background: 'rgba(255,255,255,0.01)', padding: '12px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.05)', fontSize: '12px', marginBottom: '16px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'var(--text-secondary)' }}>✏️ نام سرویس:</span>
                <span style={{ fontWeight: 'bold' }}>{activeDetailsConfig.remark}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'var(--text-secondary)' }}>🛡️ پروتکل:</span>
                <span style={{ fontWeight: 'bold', textTransform: 'uppercase' }}>{activeDetailsConfig.protocol}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'var(--text-secondary)' }}>🔋 حجم کل:</span>
                <span style={{ fontWeight: 'bold' }}>{activeDetailsConfig.stats?.total === 0 ? 'نامحدود' : formatBytes(activeDetailsConfig.stats?.total)}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'var(--text-secondary)' }}>⏳ روزهای معتبر:</span>
                <span style={{ fontWeight: 'bold' }}>{activeDetailsConfig.stats?.expiry_days === -1 ? 'نامحدود' : `${activeDetailsConfig.stats?.expiry_days} روز`}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: 'var(--text-secondary)' }}>🗓️ تاریخ سررسید:</span>
                <span style={{ fontWeight: 'bold' }}>{activeDetailsConfig.expire_date ? new Date(activeDetailsConfig.expire_date * 1000).toLocaleDateString('fa-IR') : 'نامحدود'}</span>
              </div>
            </div>

            {/* Inputs with Copy button next to them */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '20px' }}>
              <div>
                <label className="form-label" style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>💝 لینک اتصال (Config)</label>
                <div style={{ display: 'flex', gap: '6px' }}>
                  <input type="text" readOnly value={activeDetailsConfig.link || ''} className="form-input" style={{ fontSize: '10px', padding: '6px 10px', background: 'rgba(255,255,255,0.03)', direction: 'ltr', textAlign: 'left' }} />
                  <button onClick={() => handleCopy(activeDetailsConfig.link, 'det_config')} className="btn btn-primary" style={{ padding: '6px 12px', fontSize: '11px', borderRadius: '10px' }}>
                    {copiedId === 'det_config' ? 'کپی شد' : 'کپی'}
                  </button>
                </div>
              </div>

              {activeDetailsConfig.volume_web_link && (
                <div>
                  <label className="form-label" style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>🔋 وب‌سایت گزارش ترافیک (Volume Web)</label>
                  <div style={{ display: 'flex', gap: '6px' }}>
                    <input type="text" readOnly value={activeDetailsConfig.volume_web_link || ''} className="form-input" style={{ fontSize: '10px', padding: '6px 10px', background: 'rgba(255,255,255,0.03)', direction: 'ltr', textAlign: 'left' }} />
                    <button onClick={() => handleCopy(activeDetailsConfig.volume_web_link, 'det_volume')} className="btn btn-primary" style={{ padding: '6px 12px', fontSize: '11px', borderRadius: '10px' }}>
                      {copiedId === 'det_volume' ? 'کپی شد' : 'کپی'}
                    </button>
                  </div>
                </div>
              )}

              {activeDetailsConfig.subscription_link && (
                <div>
                  <label className="form-label" style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>🌐 لینک سابسکریپشن (Subscription)</label>
                  <div style={{ display: 'flex', gap: '6px' }}>
                    <input type="text" readOnly value={activeDetailsConfig.subscription_link || ''} className="form-input" style={{ fontSize: '10px', padding: '6px 10px', background: 'rgba(255,255,255,0.03)', direction: 'ltr', textAlign: 'left' }} />
                    <button onClick={() => handleCopy(activeDetailsConfig.subscription_link, 'det_sub')} className="btn btn-primary" style={{ padding: '6px 12px', fontSize: '11px', borderRadius: '10px' }}>
                      {copiedId === 'det_sub' ? 'کپی شد' : 'کپی'}
                    </button>
                  </div>
                </div>
              )}
            </div>

            <button 
              onClick={() => handleSendNpvtFile(activeDetailsConfig.id)}
              className="btn btn-success" 
              style={{ width: '100%', borderRadius: '10px', marginBottom: '8px' }}
            >
              📄 دریافت فایل متنی کانفیگ‌ها در تلگرام
            </button>

            <button 
              onClick={() => setActiveDetailsConfig(null)}
              className="btn btn-danger" 
              style={{ width: '100%', borderRadius: '10px' }}
            >
              بستن جزئیات
            </button>
          </div>
        </div>
      )}

      {/* 4. Rating Modal (Close Ticket) */}
      {showRatingModal && (
        <div style={{
          position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
          background: 'rgba(0,0,0,0.8)', display: 'flex', justifyContent: 'center',
          alignItems: 'center', zIndex: 1100, padding: '20px', direction: 'rtl'
        }}>
          <div className="glass-card" style={{ width: '100%', maxWidth: '380px', textAlign: 'center', padding: '24px' }}>
            <h3 style={{ fontSize: '16px', fontWeight: 'bold', color: 'white', marginBottom: '12px' }}>🔒 بستن تیکت و ثبت امتیاز</h3>
            <p style={{ fontSize: '12px', color: 'var(--text-secondary)', marginBottom: '20px' }}>لطفاً به کیفیت پاسخگویی و حل مشکل خود امتیاز دهید:</p>
            
            {/* Emojis selection from sad to happy */}
            <div style={{ display: 'flex', justifyContent: 'center', gap: '14px', marginBottom: '24px' }}>
              {[
                { val: 1, label: '😡', text: 'خیلی بد' },
                { val: 2, label: '🙁', text: 'بد' },
                { val: 3, label: '😐', text: 'معمولی' },
                { val: 4, label: '🙂', text: 'خوب' },
                { val: 5, label: '😍', text: 'عالی' }
              ].map(emoji => (
                <div 
                  key={emoji.val}
                  onClick={() => setRatingValue(emoji.val)}
                  style={{
                    cursor: 'pointer',
                    transform: ratingValue === emoji.val ? 'scale(1.25)' : 'scale(1.0)',
                    opacity: ratingValue === emoji.val ? 1 : 0.4,
                    transition: 'all 0.2s',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    gap: '4px'
                  }}
                >
                  <span style={{ fontSize: '32px' }}>{emoji.label}</span>
                  <span style={{ fontSize: '10px', color: ratingValue === emoji.val ? 'white' : 'var(--text-secondary)' }}>{emoji.text}</span>
                </div>
              ))}
            </div>

            <div style={{ display: 'flex', gap: '8px' }}>
              <button 
                onClick={handleCloseTicket}
                className="btn btn-success" 
                style={{ flex: 1, padding: '10px', borderRadius: '10px' }}
              >
                ثبت و بستن تیکت
              </button>
              <button 
                onClick={() => setShowRatingModal(false)}
                className="btn btn-danger" 
                style={{ flex: 1, padding: '10px', borderRadius: '10px', background: 'rgba(239, 68, 68, 0.1)', color: 'var(--color-danger)' }}
              >
                انصراف
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 5. Custom Config Reseller Modal */}
      {showCustomConfigModal && (
        <div style={{
          position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
          background: 'rgba(0,0,0,0.8)', display: 'flex', justifyContent: 'center',
          alignItems: 'center', zIndex: 1050, padding: '20px', direction: 'rtl',
          overflowY: 'auto'
        }}>
          <div className="glass-card" style={{ width: '100%', maxWidth: '420px', maxHeight: '90vh', overflowY: 'auto', padding: '20px' }}>
            <h3 style={{ fontSize: '15px', fontWeight: 'bold', marginBottom: '14px', borderBottom: '1px solid rgba(255,255,255,0.05)', paddingBottom: '10px' }}>
              🛠️ پنل مدیریت کانفیگ سفارشی نمایندگی
            </h3>

            {createdCustomConfigDetails ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                <div style={{ textAlign: 'center', padding: '10px', background: 'rgba(46, 204, 113, 0.15)', borderRadius: '12px', border: '1px solid var(--color-success)', marginBottom: '10px' }}>
                  <span style={{ fontSize: '24px' }}>🎉</span>
                  <p style={{ fontSize: '13px', fontWeight: 'bold', color: 'white', marginTop: '6px' }}>کانفیگ سفارشی با موفقیت ساخته شد!</p>
                </div>
                
                <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', background: 'rgba(255,255,255,0.01)', padding: '12px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.05)', fontSize: '12px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: 'var(--text-secondary)' }}>✏️ نام سرویس:</span>
                    <span style={{ fontWeight: 'bold' }}>{createdCustomConfigDetails.remark}</span>
                  </div>
                </div>

                <div>
                  <label className="form-label" style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>💝 لینک اتصال (Config)</label>
                  <div style={{ display: 'flex', gap: '6px' }}>
                    <input type="text" readOnly value={createdCustomConfigDetails.link || ''} className="form-input" style={{ fontSize: '10px', padding: '6px 10px', background: 'rgba(255,255,255,0.03)', direction: 'ltr', textAlign: 'left' }} />
                    <button onClick={() => handleCopy(createdCustomConfigDetails.link, 'cust_link')} className="btn btn-primary" style={{ padding: '6px 12px', fontSize: '11px', borderRadius: '10px' }}>
                      {copiedId === 'cust_link' ? 'کپی شد' : 'کپی'}
                    </button>
                  </div>
                </div>

                {createdCustomConfigDetails.web_link && (
                  <div>
                    <label className="form-label" style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>🔋 وب‌سایت گزارش ترافیک (Volume Web)</label>
                    <div style={{ display: 'flex', gap: '6px' }}>
                      <input type="text" readOnly value={createdCustomConfigDetails.web_link || ''} className="form-input" style={{ fontSize: '10px', padding: '6px 10px', background: 'rgba(255,255,255,0.03)', direction: 'ltr', textAlign: 'left' }} />
                      <button onClick={() => handleCopy(createdCustomConfigDetails.web_link, 'cust_volume')} className="btn btn-primary" style={{ padding: '6px 12px', fontSize: '11px', borderRadius: '10px' }}>
                        {copiedId === 'cust_volume' ? 'کپی شد' : 'کپی'}
                      </button>
                    </div>
                  </div>
                )}

                {createdCustomConfigDetails.subscription && (
                  <div>
                    <label className="form-label" style={{ fontSize: '10px', color: 'var(--text-secondary)' }}>🌐 لینک سابسکریپشن (Subscription)</label>
                    <div style={{ display: 'flex', gap: '6px' }}>
                      <input type="text" readOnly value={createdCustomConfigDetails.subscription || ''} className="form-input" style={{ fontSize: '10px', padding: '6px 10px', background: 'rgba(255,255,255,0.03)', direction: 'ltr', textAlign: 'left' }} />
                      <button onClick={() => handleCopy(createdCustomConfigDetails.subscription, 'cust_sub')} className="btn btn-primary" style={{ padding: '6px 12px', fontSize: '11px', borderRadius: '10px' }}>
                        {copiedId === 'cust_sub' ? 'کپی شد' : 'کپی'}
                      </button>
                    </div>
                  </div>
                )}

                <button 
                  onClick={() => setCreatedCustomConfigDetails(null)}
                  className="btn btn-success" 
                  style={{ width: '100%', borderRadius: '10px', marginTop: '10px' }}
                >
                  ساخت کانفیگ دیگر
                </button>
              </div>
            ) : (
              <form onSubmit={handleCreateCustomConfig} style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                
                {/* Server select */}
                <div className="form-group">
                  <label className="form-label">➊ سرور میزبان:</label>
                  <select 
                    value={customConfigServer} 
                    onChange={(e) => setCustomConfigServer(e.target.value)}
                    className="form-input"
                    required
                  >
                    <option value="">-- لطفا یک سرور انتخاب کنید --</option>
                    {servers.map(srv => (
                      <option key={srv.id} value={srv.id}>
                        {srv.title} (ظرفیت: {srv.ucount})
                      </option>
                    ))}
                  </select>
                </div>

                {/* Name/Remark */}
                <div className="form-group">
                  <label className="form-label">➋ نام کانفیگ (Remark):</label>
                  <input 
                    type="text" 
                    value={customConfigRemark} 
                    onChange={(e) => setCustomConfigRemark(e.target.value)} 
                    className="form-input" 
                    placeholder="فقط حروف انگلیسی، اعداد و خط‌تیره" 
                    required 
                  />
                </div>

                {/* Volume GB */}
                <div className="form-group">
                  <label className="form-label">➌ ترافیک کانفیگ (GB):</label>
                  <input 
                    type="number" 
                    value={customConfigVolume} 
                    onChange={(e) => setCustomConfigVolume(e.target.value)} 
                    className="form-input" 
                    placeholder="مثال: 20" 
                    required 
                    min="1"
                  />
                </div>

                {/* Days */}
                <div className="form-group">
                  <label className="form-label">➍ مدت اعتبار (روز):</label>
                  <input 
                    type="number" 
                    value={customConfigDays} 
                    onChange={(e) => setCustomConfigDays(e.target.value)} 
                    className="form-input" 
                    placeholder="مثال: 30" 
                    required 
                    min="1"
                  />
                </div>

                {/* IP Limit */}
                <div className="form-group">
                  <label className="form-label">➎ محدودیت کاربر همزمان (IP Limit):</label>
                  <input 
                    type="number" 
                    value={customConfigLimitIp} 
                    onChange={(e) => setCustomConfigLimitIp(e.target.value)} 
                    className="form-input" 
                    placeholder="0 برای نامحدود" 
                    min="0"
                  />
                </div>

                <button 
                  type="submit" 
                  disabled={isCreatingCustomConfig} 
                  className="btn btn-success" 
                  style={{ width: '100%', borderRadius: '10px', marginTop: '10px' }}
                >
                  {isCreatingCustomConfig ? 'در حال ساخت کانفیگ...' : '➕ ساخت کانفیگ سفارشی (کسر از سهمیه)'}
                </button>

              </form>
            )}

            <button 
              onClick={() => {
                setShowCustomConfigModal(false);
                setCreatedCustomConfigDetails(null);
              }}
              className="btn btn-danger" 
              style={{ width: '100%', marginTop: '8px', borderRadius: '10px', background: 'rgba(239, 68, 68, 0.1)', color: 'var(--color-danger)' }}
            >
              انصراف و بازگشت
            </button>
          </div>
        </div>
      )}

      {/* 6. QR Code Zoom Modal */}
      {activeQrCodeLink && (
        <div style={{
          position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
          background: 'rgba(0,0,0,0.9)', display: 'flex', justifyContent: 'center',
          alignItems: 'center', zIndex: 1200, padding: '20px', direction: 'rtl'
        }}>
          <div className="glass-card" style={{ width: '100%', maxWidth: '340px', textAlign: 'center', padding: '24px' }}>
            <h3 style={{ fontSize: '15px', fontWeight: 'bold', color: 'white', marginBottom: '16px' }}>📱 اسکن کد QR</h3>
            
            <div style={{ background: 'white', padding: '12px', borderRadius: '12px', display: 'inline-block', marginBottom: '20px' }}>
              <img 
                src={`https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(activeQrCodeLink)}`} 
                alt="Large QR" 
                style={{ width: '240px', height: '240px', display: 'block' }} 
              />
            </div>

            <button 
              onClick={() => setActiveQrCodeLink(null)}
              className="btn btn-danger" 
              style={{ width: '100%', borderRadius: '10px' }}
            >
              بازگشت به کانفیگ‌ها
            </button>
          </div>
        </div>
      )}

      {/* 7. Bulk Purchase Modal */}
      {showBulkPurchaseModal && (
        <div style={{
          position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
          background: 'rgba(0,0,0,0.85)', display: 'flex', justifyContent: 'center',
          alignItems: 'center', zIndex: 1100, padding: '20px', direction: 'rtl'
        }}>
          <div className="glass-card" style={{ width: '100%', maxWidth: '380px', padding: '20px' }}>
            <h3 style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '14px' }}>🛍 خرید عمده ترافیک نماینده (هر گیگ ۱۰۰ تومان)</h3>
            <form onSubmit={(e) => {
              handleAgentBuyVolume(e);
              setShowBulkPurchaseModal(false);
            }}>
              <div className="form-group" style={{ marginBottom: '12px' }}>
                <label className="form-label" style={{ fontSize: '11px' }}>مقدار حجم (به گیگابایت)</label>
                <input 
                  type="number" 
                  value={agentVolBuy} 
                  onChange={(e) => setAgentVolBuy(e.target.value)} 
                  placeholder="مثال: ۱۰۰" 
                  className="form-input" 
                  style={{ fontSize: '12px', padding: '8px' }}
                  required 
                />
              </div>
              <button type="submit" className="btn btn-success" style={{ width: '100%', padding: '10px' }}>خرید و کسر از اعتبار نمایندگی</button>
            </form>
            <button 
              onClick={() => setShowBulkPurchaseModal(false)}
              className="btn btn-danger" 
              style={{ width: '100%', marginTop: '8px', borderRadius: '10px', background: 'rgba(239, 68, 68, 0.1)', color: 'var(--color-danger)' }}
            >
              انصراف
            </button>
          </div>
        </div>
      )}

      {/* Persistence Glassmorphic Bottom Navigation Menu */}
      <div className="bottom-nav">
        <div 
          onClick={() => setActiveTab('user-dashboard')} 
          className={`nav-item ${activeTab === 'user-dashboard' ? 'active' : ''}`}
        >
          <Home size={20} />
          <span>داشبورد</span>
        </div>

        <div 
          onClick={() => setActiveTab('subscriptions')} 
          className={`nav-item ${activeTab === 'subscriptions' ? 'active' : ''}`}
        >
          <Settings size={20} />
          <span>کانفیگ‌های من</span>
        </div>

        <div 
          onClick={() => setActiveTab('tickets')} 
          className={`nav-item ${activeTab === 'tickets' ? 'active' : ''}`}
        >
          <Ticket size={20} />
          <span>تیکت‌ها</span>
        </div>

        {user && (user.is_agent || user.isAdmin) && (
          <div 
            onClick={() => setActiveTab('reseller-panel')} 
            className={`nav-item ${activeTab === 'reseller-panel' ? 'active' : ''}`}
          >
            <Users size={20} />
            <span>نمایندگی</span>
          </div>
        )}

        {user && user.isAdmin && (
          <div 
            onClick={() => setActiveTab('admin-panel')} 
            className={`nav-item ${activeTab === 'admin-panel' ? 'active' : ''}`}
          >
            <Shield size={20} />
            <span>ادمین</span>
          </div>
        )}
      </div>
    </div>
  );
}
