// Licenses / User Keys Management Page Component (Enhanced)
window.LicensesPage = function LicensesPage({ user, apps, showToast, onRefreshData }) {
  const isOwner = user?.role === 'owner';
  const perms = user?.permissions || {};

  const canCreate = isOwner || perms.can_create_keys;
  const canAddTime = isOwner || perms.can_add_time;
  const canResetHwid = isOwner || perms.can_reset_hwid;
  const canBan = isOwner || perms.can_ban_users;
  const canFreeze = isOwner || perms.can_freeze_users;
  const canDelete = isOwner || perms.can_delete_users;
  const canExport = isOwner || perms.can_export_keys;

  const [users, setUsers] = React.useState([]);
  const [selectedApp, setSelectedApp] = React.useState('all');
  const [selectedStatus, setSelectedStatus] = React.useState('all');
  const [selectedCreator, setSelectedCreator] = React.useState('all');
  const [searchQuery, setSearchQuery] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  // Bulk Selection
  const [selectedIds, setSelectedIds] = React.useState([]);

  // Modals
  const [showCreateModal, setShowCreateModal] = React.useState(false);
  const [createMode, setCreateMode] = React.useState('random');
  const [createAppId, setCreateAppId] = React.useState(apps?.[0]?.id || 'app_default');
  const [manualUser, setManualUser] = React.useState('');
  const [manualPass, setManualPass] = React.useState('');
  const [manualNote, setManualNote] = React.useState('');
  const [durationDays, setDurationDays] = React.useState(30);
  const [batchCount, setBatchCount] = React.useState(5);

  const [showAddTimeModal, setShowAddTimeModal] = React.useState(false);
  const [targetUser, setTargetUser] = React.useState(null);
  const [addDays, setAddDays] = React.useState(7);
  const [addHours, setAddHours] = React.useState(0);

  const [showAddTimeAllModal, setShowAddTimeAllModal] = React.useState(false);
  const [addTimeAllAppId, setAddTimeAllAppId] = React.useState(apps?.[0]?.id || 'app_default');
  const [addTimeAllDays, setAddTimeAllDays] = React.useState(3);

  const [showExportModal, setShowExportModal] = React.useState(false);
  const [exportText, setExportText] = React.useState('');

  const [showNoteModal, setShowNoteModal] = React.useState(false);
  const [editingNoteUser, setEditingNoteUser] = React.useState(null);
  const [noteContent, setNoteContent] = React.useState('');

  const [createdLicensesResult, setCreatedLicensesResult] = React.useState(null);
  const [showLicensesResultModal, setShowLicensesResultModal] = React.useState(false);
  const [copiedLicenseIdx, setCopiedLicenseIdx] = React.useState(null);

  const fetchUsers = async () => {
    setLoading(true);
    try {
      let url = `/api/licenses?app_id=${selectedApp}&status=${selectedStatus}`;
      if (selectedCreator !== 'all') url += `&creator=${encodeURIComponent(selectedCreator)}`;
      if (searchQuery.trim()) url += `&search=${encodeURIComponent(searchQuery.trim())}`;

      const res = await fetch(url, {
        headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` }
      });
      const data = await res.json();
      if (data.success) {
        setUsers(data.users);
      }
    } catch (err) {
      console.error('Fetch users error:', err);
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    fetchUsers();
    const interval = setInterval(fetchUsers, 4000);
    return () => clearInterval(interval);
  }, [selectedApp, selectedStatus, selectedCreator, searchQuery]);

  const copyToClipboard = (text, label = 'Copied') => {
    navigator.clipboard.writeText(text);
    showToast(`${label} copied to clipboard!`, 'success');
  };

  // Bulk Selection Handlers
  const handleSelectAll = (e) => {
    if (e.target.checked) {
      setSelectedIds(users.map(u => u.id));
    } else {
      setSelectedIds([]);
    }
  };

  const handleToggleRowSelect = (id) => {
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(item => item !== id) : [...prev, id]
    );
  };

  const handleBulkAction = async (action, days = 0) => {
    if (selectedIds.length === 0) return;
    if (action === 'delete' && !confirm(`Are you sure you want to delete ${selectedIds.length} selected keys?`)) return;

    try {
      const res = await fetch('/api/licenses/bulk-action', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ action, ids: selectedIds, days })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        setSelectedIds([]);
        fetchUsers();
        onRefreshData();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Bulk action failed', 'error');
    }
  };

  const handleQuickExtend = async (u, days) => {
    try {
      const res = await fetch('/api/licenses/quick-extend', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ id: u.id, days })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        fetchUsers();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error extending key', 'error');
    }
  };

  const handleCreate = async (e) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/licenses/create', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({
          mode: createMode,
          app_id: createAppId,
          username: manualUser,
          password: manualPass,
          duration_days: durationDays,
          count: batchCount,
          note: manualNote
        })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        setShowCreateModal(false);
        const createdItems = data.users || (data.user ? [data.user] : []);
        setCreatedLicensesResult({
          items: createdItems,
          app_name: apps.find(a => a.id === createAppId)?.name || createAppId,
          duration_days: durationDays,
          created_at: new Date().toLocaleString()
        });
        setShowLicensesResultModal(true);
        setManualUser('');
        setManualPass('');
        setManualNote('');
        fetchUsers();
        onRefreshData();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Creation failed: ' + err.message, 'error');
    }
  };

  const handleAddTime = async (e) => {
    e.preventDefault();
    if (!targetUser) return;
    try {
      const res = await fetch('/api/licenses/add-time', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({
          username: targetUser.username,
          app_id: targetUser.app_id,
          days: addDays,
          hours: addHours
        })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        setShowAddTimeModal(false);
        fetchUsers();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error adding time', 'error');
    }
  };

  const handleAddTimeAll = async (e) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/licenses/add-time-all', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({
          app_id: addTimeAllAppId,
          days: addTimeAllDays,
          hours: 0
        })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        setShowAddTimeAllModal(false);
        fetchUsers();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error adding time to all', 'error');
    }
  };

  const handleResetHwid = async (u) => {
    if (!confirm(`Reset HWID lock for user '${u.username}'?`)) return;
    try {
      const res = await fetch('/api/licenses/reset-hwid', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ username: u.username, app_id: u.app_id })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        fetchUsers();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error resetting HWID', 'error');
    }
  };

  const handleToggleFreeze = async (u) => {
    try {
      const res = await fetch('/api/licenses/toggle-freeze', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ username: u.username, app_id: u.app_id })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        fetchUsers();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error freezing key', 'error');
    }
  };

  const handleToggleBan = async (u) => {
    const reason = !u.banned ? prompt('ระบุเหตุผลการแบน:', 'ผิดกฎการใช้งาน') : '';
    if (!u.banned && reason === null) return;

    try {
      const res = await fetch('/api/licenses/toggle-ban', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ username: u.username, app_id: u.app_id, reason })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        fetchUsers();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error toggling ban', 'error');
    }
  };

  const handleDelete = async (u) => {
    if (!confirm(`ต้องการลบคีย์ '${u.username}' ถาวรหรือไม่?`)) return;
    try {
      const res = await fetch('/api/licenses/delete', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ username: u.username, app_id: u.app_id })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        fetchUsers();
        onRefreshData();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error deleting user', 'error');
    }
  };

  const handleQuickBanIp = async (ip, username) => {
    if (!ip) return;
    if (!confirm(`แบน IP '${ip}' เครื่องของ ${username} ถาวรหรือไม่?`)) return;
    try {
      const res = await fetch('/api/security/ban-ip', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ ip, reason: `Quick-banned from user ${username}` })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error banning IP', 'error');
    }
  };

  const handleQuickBanHwid = async (hwid, username) => {
    if (!hwid) return;
    if (!confirm(`แบน Machine HWID ของ ${username} ถาวรหรือไม่?`)) return;
    try {
      const res = await fetch('/api/security/ban-hwid', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ hwid, reason: `Quick-banned HWID from ${username}` })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error banning HWID', 'error');
    }
  };

  const handleSaveNote = async (e) => {
    e.preventDefault();
    if (!editingNoteUser) return;
    try {
      const res = await fetch('/api/licenses/update-note', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ id: editingNoteUser.id, note: noteContent })
      });
      const data = await res.json();
      if (data.success) {
        showToast('อัปเดตบันทึกเรียบร้อย', 'success');
        setShowNoteModal(false);
        fetchUsers();
      }
    } catch (err) {
      showToast('Error saving note', 'error');
    }
  };

  const handleExportKeys = () => {
    const lines = users.map(u => `${u.username}:${u.password} | ${u.app_name} | ${u.remaining_days}d | Note: ${u.note || '-'}`);
    setExportText(lines.join('\n'));
    setShowExportModal(true);
  };

  // Get distinct creators
  const creators = Array.from(new Set(users.map(u => u.created_by || 'admin')));

  return (
    <div className="space-y-5 animate-fade-in w-full">
      {/* Top Filter and Action Bar - Sharp Square Cyber Theme */}
      <div className="p-4 sm:p-5 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-4 shadow-xl">
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-3">
          {/* Filters Row */}
          <div className="flex flex-wrap items-center gap-2 flex-1">
            {/* App Filter */}
            <select
              value={selectedApp}
              onChange={(e) => setSelectedApp(e.target.value)}
              className="flex-1 sm:flex-none px-3 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-xs text-white focus:border-[#1D63FF] outline-none"
            >
              <option value="all">ทุกแอป (All Apps)</option>
              {apps && apps.map(a => (
                <option key={a.id} value={a.id}>{a.name}</option>
              ))}
            </select>

            {/* Status Filter */}
            <select
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
              className="flex-1 sm:flex-none px-3 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-xs text-white focus:border-[#1D63FF] outline-none"
            >
              <option value="all">ทุกสถานะ (All Status)</option>
              <option value="online">ออนไลน์ตอนนี้ (Online)</option>
              <option value="active">ใช้งานอยู่ (Active)</option>
              <option value="unused">ยังไม่เปิดใช้ (Unused)</option>
              <option value="expired">หมดอายุ (Expired)</option>
              <option value="frozen">แช่เวลา (Frozen)</option>
              <option value="banned">ถูกแบน (Banned)</option>
            </select>

            {/* Creator Filter */}
            {isOwner && creators.length > 1 && (
              <select
                value={selectedCreator}
                onChange={(e) => setSelectedCreator(e.target.value)}
                className="flex-1 sm:flex-none px-3 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-xs text-white focus:border-[#1D63FF] outline-none font-mono"
              >
                <option value="all">ผู้สร้างทั้งหมด (All Creators)</option>
                {creators.map(c => (
                  <option key={c} value={c}>โดย: {c}</option>
                ))}
              </select>
            )}

            {/* Search Input */}
            <div className="relative w-full sm:w-auto flex-1 min-w-[200px]">
              <i className="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-xs"></i>
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="ค้นหายูสเซอร์, HWID, IP, โน้ต..."
                className="w-full pl-9 pr-3 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-xs text-white focus:border-[#1D63FF] outline-none"
              />
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex items-center gap-2 shrink-0 flex-wrap">
            {canCreate && (
              <button
                onClick={() => setShowCreateModal(true)}
                className="px-4 py-2 rounded-none bg-[#1D63FF] hover:bg-[#3878FF] text-white font-semibold text-xs transition flex items-center gap-2 border border-[#1D63FF]"
              >
                <i className="fa-solid fa-plus text-xs"></i>
                <span>สร้างคีย์ใหม่</span>
              </button>
            )}

            {canAddTime && (
              <button
                onClick={() => setShowAddTimeAllModal(true)}
                className="px-3.5 py-2 rounded-none bg-[#080C14] hover:bg-[#131D31] border border-[#1E2D4A] text-slate-200 text-xs font-medium transition flex items-center gap-1.5"
              >
                <i className="fa-solid fa-clock-rotate-left text-cyan-400 text-xs"></i>
                <span>ต่อเวลาทุกคน</span>
              </button>
            )}

            {canExport && (
              <button
                onClick={handleExportKeys}
                className="px-3.5 py-2 rounded-none bg-[#080C14] hover:bg-[#131D31] border border-[#1E2D4A] text-slate-200 text-xs font-medium transition flex items-center gap-1.5"
                title="ส่งออกคีย์"
              >
                <i className="fa-solid fa-file-export text-slate-400 text-xs"></i>
                <span>Export</span>
              </button>
            )}
          </div>
        </div>

        {/* Bulk Action Bar (When rows are selected) */}
        {selectedIds.length > 0 && (
          <div className="p-3 rounded-none bg-blue-600/10 border border-blue-500/30 flex flex-wrap items-center justify-between gap-3 animate-fade-in">
            <div className="flex items-center gap-2 text-xs font-semibold text-blue-300 font-mono">
              <i className="fa-solid fa-circle-check"></i>
              <span>เลือกไว้ {selectedIds.length} รายการ</span>
            </div>

            <div className="flex flex-wrap items-center gap-1.5">
              {canAddTime && (
                <>
                  <button
                    onClick={() => handleBulkAction('add_time', 1)}
                    className="px-2.5 py-1.5 rounded-none bg-blue-600 hover:bg-blue-500 text-white text-xs font-mono transition"
                  >
                    +1 วัน
                  </button>
                  <button
                    onClick={() => handleBulkAction('add_time', 7)}
                    className="px-2.5 py-1.5 rounded-none bg-blue-600 hover:bg-blue-500 text-white text-xs font-mono transition"
                  >
                    +7 วัน
                  </button>
                  <button
                    onClick={() => handleBulkAction('add_time', 30)}
                    className="px-2.5 py-1.5 rounded-none bg-blue-600 hover:bg-blue-500 text-white text-xs font-mono transition"
                  >
                    +30 วัน
                  </button>
                </>
              )}

              {canFreeze && (
                <button
                  onClick={() => handleBulkAction('freeze')}
                  className="px-2.5 py-1.5 rounded-none bg-amber-500/20 hover:bg-amber-500/30 text-amber-300 border border-amber-500/30 text-xs font-mono transition"
                >
                  แช่เวลา
                </button>
              )}

              {canBan && (
                <button
                  onClick={() => handleBulkAction('ban')}
                  className="px-2.5 py-1.5 rounded-none bg-rose-500/20 hover:bg-rose-500/30 text-rose-300 border border-rose-500/30 text-xs font-mono transition"
                >
                  แบน
                </button>
              )}

              {canDelete && (
                <button
                  onClick={() => handleBulkAction('delete')}
                  className="px-2.5 py-1.5 rounded-none bg-rose-600 hover:bg-rose-500 text-white text-xs font-mono transition"
                >
                  ลบที่เลือก
                </button>
              )}

              <button
                onClick={() => setSelectedIds([])}
                className="px-2.5 py-1.5 rounded-none bg-slate-800 text-slate-300 text-xs hover:text-white border border-slate-700"
              >
                ยกเลิก
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Licenses Table Container with Zero Border Eating / Overflow */}
      <div className="rounded-none bg-[#0E1626] border border-[#1E2D4A] overflow-hidden shadow-2xl w-full">
        <div className="table-responsive-container">
          <table className="w-full text-left text-xs border-collapse min-w-[950px]">
            <thead>
              <tr className="border-b border-[#1E2D4A] bg-[#0A0F1D] text-slate-400 font-mono">
                <th className="py-3.5 px-4 w-10 text-center">
                  <input
                    type="checkbox"
                    checked={users.length > 0 && selectedIds.length === users.length}
                    onChange={handleSelectAll}
                    className="w-4 h-4 rounded-none text-blue-600 bg-slate-800 border-slate-700 cursor-pointer"
                  />
                </th>
                <th className="py-3.5 px-4">สถานะ</th>
                <th className="py-3.5 px-4">ชื่อ / รหัสผ่าน</th>
                <th className="py-3.5 px-4">แอปพลิเคชัน</th>
                <th className="py-3.5 px-4">เวลาคงเหลือ</th>
                <th className="py-3.5 px-4">HWID เครื่อง</th>
                <th className="py-3.5 px-4">IP ล่าสุด</th>
                <th className="py-3.5 px-4">บันทึก / ลูกค้า</th>
                <th className="py-3.5 px-4">ผู้สร้าง</th>
                <th className="py-3.5 px-4 text-right">จัดการ</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#1E2D4A]/50 font-sans">
              {users && users.length > 0 ? (
                users.map((u) => {
                  const isSelected = selectedIds.includes(u.id);
                  const isOnline = u.is_online;
                  const status = u.computed_status;

                  return (
                    <tr
                      key={u.id}
                      className={`transition ${isSelected ? 'bg-blue-600/10' : 'hover:bg-[#131D31]/40'}`}
                    >
                      {/* Checkbox */}
                      <td className="py-3.5 px-4 text-center">
                        <input
                          type="checkbox"
                          checked={isSelected}
                          onChange={() => handleToggleRowSelect(u.id)}
                          className="w-4 h-4 rounded-none text-blue-600 bg-slate-800 border-slate-700 cursor-pointer"
                        />
                      </td>

                      {/* Status Badge */}
                      <td className="py-3.5 px-4">
                        <div className="flex items-center gap-2">
                          {isOnline && (
                            <span className="w-2 h-2 rounded-full bg-[#00FF9D] badge-pulse shrink-0" title="กำลังออนไลน์"></span>
                          )}
                          <span className={`px-2 py-0.5 rounded-none text-[10px] font-mono font-semibold uppercase ${
                            status === 'active'
                              ? 'bg-emerald-500/10 text-[#00FF9D] border border-emerald-500/20'
                              : status === 'unused'
                              ? 'bg-blue-500/10 text-cyan-400 border border-blue-500/20'
                              : status === 'frozen'
                              ? 'bg-amber-500/10 text-amber-400 border border-amber-500/20'
                              : status === 'banned'
                              ? 'bg-rose-500/10 text-rose-400 border border-rose-500/20'
                              : 'bg-slate-800 text-slate-400 border border-slate-700'
                          }`}>
                            {status}
                          </span>
                        </div>
                      </td>

                      {/* Username / Password */}
                      <td className="py-3.5 px-4 font-mono">
                        <div className="flex items-center gap-1.5">
                          <span className="font-bold text-white tracking-wider">{u.username}</span>
                          <span className="text-slate-500">:</span>
                          <span className="text-slate-300">{u.password}</span>
                          <button
                            onClick={() => copyToClipboard(`${u.username}:${u.password}`, 'Credentials')}
                            className="text-slate-500 hover:text-white transition ml-1"
                            title="คัดลอก user:pass"
                          >
                            <i className="fa-regular fa-copy text-xs"></i>
                          </button>
                        </div>
                      </td>

                      {/* App */}
                      <td className="py-3.5 px-4">
                        <span className="font-medium text-slate-300">{u.app_name}</span>
                      </td>

                      {/* Time Remaining & Quick Extends */}
                      <td className="py-3.5 px-4 font-mono">
                        <div className="space-y-1">
                          {status === 'unused' ? (
                            <span className="text-cyan-400">{u.duration_days} วัน (ยังไม่เริ่มนับ)</span>
                          ) : status === 'expired' ? (
                            <span className="text-rose-400">หมดอายุแล้ว</span>
                          ) : (
                            <div className="flex items-center gap-1.5">
                              <span className="text-white font-bold">{u.remaining_days} วัน</span>
                              {canAddTime && (
                                <div className="flex items-center gap-1 ml-1">
                                  <button
                                    onClick={() => handleQuickExtend(u, 1)}
                                    className="px-1.5 py-0.5 rounded-none bg-blue-500/10 hover:bg-blue-500/30 text-blue-300 text-[10px] border border-blue-500/20 transition"
                                    title="เพิ่ม 1 วันทันที"
                                  >
                                    +1d
                                  </button>
                                  <button
                                    onClick={() => handleQuickExtend(u, 7)}
                                    className="px-1.5 py-0.5 rounded-none bg-blue-500/10 hover:bg-blue-500/30 text-blue-300 text-[10px] border border-blue-500/20 transition"
                                    title="เพิ่ม 7 วันทันที"
                                  >
                                    +7d
                                  </button>
                                </div>
                              )}
                            </div>
                          )}
                        </div>
                      </td>

                      {/* HWID */}
                      <td className="py-3.5 px-4 font-mono">
                        {u.hwid ? (
                          <div className="flex items-center gap-1.5">
                            <span className="truncate max-w-[120px] text-slate-300" title={u.hwid}>
                              {u.hwid.substring(0, 10)}...
                            </span>
                            <button
                              onClick={() => copyToClipboard(u.hwid, 'HWID')}
                              className="text-slate-500 hover:text-white"
                              title="Copy HWID"
                            >
                              <i className="fa-regular fa-copy text-[11px]"></i>
                            </button>
                            {isOwner && (
                              <button
                                onClick={() => handleQuickBanHwid(u.hwid, u.username)}
                                className="text-slate-500 hover:text-rose-400"
                                title="แบน HWID เครื่องนี้"
                              >
                                <i className="fa-solid fa-ban text-[11px]"></i>
                              </button>
                            )}
                          </div>
                        ) : (
                          <span className="text-slate-600 text-[11px]">- ยังไม่ผูก -</span>
                        )}
                      </td>

                      {/* Last IP */}
                      <td className="py-3.5 px-4 font-mono">
                        {u.last_ip ? (
                          <div className="flex items-center gap-1.5">
                            <span className="text-slate-400">{u.last_ip}</span>
                            {isOwner && (
                              <button
                                onClick={() => handleQuickBanIp(u.last_ip, u.username)}
                                className="text-slate-500 hover:text-rose-400"
                                title="แบน IP นี้"
                              >
                                <i className="fa-solid fa-shield-virus text-[11px]"></i>
                              </button>
                            )}
                          </div>
                        ) : (
                          <span className="text-slate-600">-</span>
                        )}
                      </td>

                      {/* Customer Note */}
                      <td className="py-3.5 px-4">
                        <button
                          onClick={() => { setEditingNoteUser(u); setNoteContent(u.note || ''); setShowNoteModal(true); }}
                          className="flex items-center gap-1 text-slate-400 hover:text-cyan-400 transition truncate max-w-[120px]"
                          title="คลิกเพื่อแก้ไขโน้ต"
                        >
                          <i className="fa-regular fa-note-sticky text-[10px]"></i>
                          <span className="truncate">{u.note || 'เพิ่มโน้ต...'}</span>
                        </button>
                      </td>

                      {/* Creator */}
                      <td className="py-3.5 px-4 font-mono text-[11px] text-slate-400">
                        {u.created_by || 'admin'}
                      </td>

                      {/* Action Buttons */}
                      <td className="py-3.5 px-4 text-right">
                        <div className="flex items-center justify-end gap-1.5">
                          {canAddTime && (
                            <button
                              onClick={() => { setTargetUser(u); setShowAddTimeModal(true); }}
                              className="p-1.5 rounded-none bg-[#080C14] hover:bg-blue-600/20 text-slate-400 hover:text-blue-400 border border-[#1E2D4A] transition"
                              title="ต่อเวลา"
                            >
                              <i className="fa-solid fa-plus text-xs"></i>
                            </button>
                          )}

                          {canResetHwid && u.hwid && (
                            <button
                              onClick={() => handleResetHwid(u)}
                              className="p-1.5 rounded-none bg-[#080C14] hover:bg-cyan-600/20 text-slate-400 hover:text-cyan-400 border border-[#1E2D4A] transition"
                              title="รีเซ็ต HWID"
                            >
                              <i className="fa-solid fa-arrows-rotate text-xs"></i>
                            </button>
                          )}

                          {canFreeze && (
                            <button
                              onClick={() => handleToggleFreeze(u)}
                              className={`p-1.5 rounded-none border transition ${
                                u.frozen
                                  ? 'bg-amber-500/20 text-amber-300 border-amber-500/30'
                                  : 'bg-[#080C14] hover:bg-amber-600/20 text-slate-400 hover:text-amber-400 border-[#1E2D4A]'
                              }`}
                              title={u.frozen ? 'ยกเลิกแช่เวลา' : 'แช่เวลา (Freeze)'}
                            >
                              <i className="fa-regular fa-snowflake text-xs"></i>
                            </button>
                          )}

                          {canBan && (
                            <button
                              onClick={() => handleToggleBan(u)}
                              className={`p-1.5 rounded-none border transition ${
                                u.banned
                                  ? 'bg-rose-500/20 text-rose-300 border-rose-500/30'
                                  : 'bg-[#080C14] hover:bg-rose-600/20 text-slate-400 hover:text-rose-400 border-[#1E2D4A]'
                              }`}
                              title={u.banned ? 'ปลดแบน' : 'แบนคีย์'}
                            >
                              <i className="fa-solid fa-ban text-xs"></i>
                            </button>
                          )}

                          {canDelete && (
                            <button
                              onClick={() => handleDelete(u)}
                              className="p-1.5 rounded-none bg-[#080C14] hover:bg-rose-600/20 text-slate-400 hover:text-rose-400 border border-[#1E2D4A] transition"
                              title="ลบคีย์"
                            >
                              <i className="fa-solid fa-trash text-xs"></i>
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })
              ) : (
                <tr>
                  <td colSpan="10" className="py-12 text-center text-slate-500 font-mono text-xs">
                    {loading ? 'กำลังโหลดข้อมูล...' : 'ไม่พบคีย์ที่ตรงตามเงื่อนไข'}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* CREATE KEY MODAL */}
      <window.Modal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        title="สร้างคีย์ผู้ใช้ (Generate Keys)"
        icon="fa-key"
      >
        <form onSubmit={handleCreate} className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">แอปพลิเคชัน *</label>
            <select
              value={createAppId}
              onChange={(e) => setCreateAppId(e.target.value)}
              className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none"
            >
              {apps && apps.map(a => (
                <option key={a.id} value={a.id}>{a.name} (v{a.version})</option>
              ))}
            </select>
          </div>

          {/* Mode Switch */}
          <div className="grid grid-cols-2 gap-2 p-1 rounded-none bg-[#080C14] border border-[#1E2D4A]">
            <button
              type="button"
              onClick={() => setCreateMode('random')}
              className={`py-2 rounded-none text-xs font-semibold font-mono transition border ${
                createMode === 'random' ? 'bg-[#1D63FF] text-white border-[#1D63FF]' : 'text-slate-400 hover:text-white border-transparent'
              }`}
            >
              <i className="fa-solid fa-dice mr-1.5"></i>
              สุ่มคีย์ (BATCH)
            </button>
            <button
              type="button"
              onClick={() => setCreateMode('manual')}
              className={`py-2 rounded-none text-xs font-semibold font-mono transition border ${
                createMode === 'manual' ? 'bg-[#1D63FF] text-white border-[#1D63FF]' : 'text-slate-400 hover:text-white border-transparent'
              }`}
            >
              <i className="fa-solid fa-pen mr-1.5"></i>
              กำหนดเอง (MANUAL)
            </button>
          </div>

          {createMode === 'manual' ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">USERNAME *</label>
                <input
                  type="text"
                  required
                  value={manualUser}
                  onChange={(e) => setManualUser(e.target.value)}
                  placeholder="Username"
                  className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none font-mono"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">PASSWORD *</label>
                <input
                  type="text"
                  required
                  value={manualPass}
                  onChange={(e) => setManualPass(e.target.value)}
                  placeholder="Password"
                  className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none font-mono"
                />
              </div>
            </div>
          ) : (
            <div>
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
                จำนวนที่ต้องการสุ่ม (1 - 100 คีย์)
              </label>
              <input
                type="number"
                min="1"
                max="100"
                value={batchCount}
                onChange={(e) => setBatchCount(e.target.value)}
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none font-mono"
              />
            </div>
          )}

          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">อายุการใช้งาน (จำนวนวัน) *</label>
            <input
              type="number"
              min="0.1"
              step="any"
              value={durationDays}
              onChange={(e) => setDurationDays(e.target.value)}
              placeholder="30"
              className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none font-mono"
            />
          </div>

          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">บันทึกข้อมูลลูกค้า / โน้ต (ถ้ามี)</label>
            <input
              type="text"
              value={manualNote}
              onChange={(e) => setManualNote(e.target.value)}
              placeholder="เช่น Discord: IceX#9999 / ลูกค้า VIP"
              className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none"
            />
          </div>

          <div className="flex justify-end gap-2.5 pt-3 border-t border-[#1E2D4A]">
            <button
              type="button"
              onClick={() => setShowCreateModal(false)}
              className="px-4 py-2 rounded-none bg-[#080C14] hover:bg-slate-800 border border-[#1E2D4A] text-slate-300 text-xs font-medium"
            >
              ยกเลิก
            </button>
            <button
              type="submit"
              className="px-5 py-2 rounded-none bg-[#1D63FF] hover:bg-[#3878FF] text-white text-xs font-semibold border border-[#1D63FF]"
            >
              สร้างคีย์ทันที
            </button>
          </div>
        </form>
      </window.Modal>

      {/* EDIT NOTE MODAL */}
      <window.Modal
        isOpen={showNoteModal}
        onClose={() => setShowNoteModal(false)}
        title={`แก้ไขโน้ตลูกค้า: ${editingNoteUser?.username}`}
        icon="fa-note-sticky"
      >
        <form onSubmit={handleSaveNote} className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">บันทึกช่วยจำ / ข้อมูลลูกค้า</label>
            <textarea
              rows="3"
              value={noteContent}
              onChange={(e) => setNoteContent(e.target.value)}
              placeholder="เช่น Facebook, Discord ID, เบอร์โทร หรือบันทึกข้อความ..."
              className="w-full p-3 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none"
            ></textarea>
          </div>
          <div className="flex justify-end gap-2.5 pt-3 border-t border-[#1E2D4A]">
            <button
              type="button"
              onClick={() => setShowNoteModal(false)}
              className="px-4 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-slate-300 text-xs"
            >
              ยกเลิก
            </button>
            <button
              type="submit"
              className="px-5 py-2 rounded-none bg-[#1D63FF] border border-[#1D63FF] text-white text-xs font-semibold"
            >
              บันทึกโน้ต
            </button>
          </div>
        </form>
      </window.Modal>

      {/* ADD TIME MODAL */}
      <window.Modal
        isOpen={showAddTimeModal}
        onClose={() => setShowAddTimeModal(false)}
        title={`ต่ออายุคีย์: ${targetUser?.username}`}
        icon="fa-clock-rotate-left"
      >
        <form onSubmit={handleAddTime} className="space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">เพิ่มวัน</label>
              <input
                type="number"
                min="0"
                value={addDays}
                onChange={(e) => setAddDays(e.target.value)}
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-blue-500 outline-none font-mono"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">เพิ่มชั่วโมง</label>
              <input
                type="number"
                min="0"
                value={addHours}
                onChange={(e) => setAddHours(e.target.value)}
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-blue-500 outline-none font-mono"
              />
            </div>
          </div>
          <div className="flex justify-end gap-2.5 pt-3 border-t border-[#1E2D4A]">
            <button
              type="button"
              onClick={() => setShowAddTimeModal(false)}
              className="px-4 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-slate-300 text-xs"
            >
              ยกเลิก
            </button>
            <button
              type="submit"
              className="px-5 py-2 rounded-none bg-[#1D63FF] border border-[#1D63FF] text-white text-xs font-semibold"
            >
              ยืนยันการต่อเวลา
            </button>
          </div>
        </form>
      </window.Modal>

      {/* ADD TIME ALL MODAL */}
      <window.Modal
        isOpen={showAddTimeAllModal}
        onClose={() => setShowAddTimeAllModal(false)}
        title="ต่อเวลาให้ทุกคนในแอป"
        icon="fa-clock-rotate-left"
      >
        <form onSubmit={handleAddTimeAll} className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">แอปพลิเคชันเป้าหมาย</label>
            <select
              value={addTimeAllAppId}
              onChange={(e) => setAddTimeAllAppId(e.target.value)}
              className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-blue-500 outline-none"
            >
              {apps && apps.map(a => (
                <option key={a.id} value={a.id}>{a.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">จำนวนวันที่ต้องการเพิ่ม</label>
            <input
              type="number"
              min="1"
              value={addTimeAllDays}
              onChange={(e) => setAddTimeAllDays(e.target.value)}
              className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-blue-500 outline-none font-mono"
            />
          </div>
          <div className="flex justify-end gap-2.5 pt-3 border-t border-[#1E2D4A]">
            <button
              type="button"
              onClick={() => setShowAddTimeAllModal(false)}
              className="px-4 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-slate-300 text-xs"
            >
              ยกเลิก
            </button>
            <button
              type="submit"
              className="px-5 py-2 rounded-none bg-[#1D63FF] border border-[#1D63FF] text-white text-xs font-semibold"
            >
              เพิ่มเวลาให้ทุกคน
            </button>
          </div>
        </form>
      </window.Modal>

      {/* EXPORT MODAL */}
      <window.Modal
        isOpen={showExportModal}
        onClose={() => setShowExportModal(false)}
        title="ส่งออกรายการคีย์ (Export Keys)"
        icon="fa-file-export"
        maxWidth="max-w-3xl"
      >
        <div className="space-y-4">
          <textarea
            readOnly
            rows="12"
            value={exportText}
            className="w-full p-4 rounded-none bg-[#080C14] border border-[#1E2D4A] text-xs font-mono text-cyan-300 focus:outline-none custom-scroll break-anywhere"
          ></textarea>
          <div className="flex justify-end gap-2.5">
            <button
              onClick={() => copyToClipboard(exportText, 'All keys')}
              className="px-4 py-2 rounded-none bg-[#1D63FF] hover:bg-[#3878FF] text-white text-xs font-semibold flex items-center gap-2 border border-[#1D63FF]"
            >
              <i className="fa-regular fa-copy"></i>
              <span>คัดลอกทั้งหมดลงคลิปบอร์ด</span>
            </button>
          </div>
        </div>
      </window.Modal>

      {/* CREATED LICENSES RESULT MODAL */}
      <window.Modal
        isOpen={showLicensesResultModal}
        onClose={() => setShowLicensesResultModal(false)}
        title={`สรุปคีย์ที่สร้างสำเร็จ (${createdLicensesResult?.items?.length || 0} คีย์)`}
        icon="fa-circle-check"
        maxWidth="max-w-2xl"
      >
        {createdLicensesResult && (
          <div className="space-y-4">
            <div className="p-3 rounded-none bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs flex items-center justify-between gap-2">
              <div className="flex items-center gap-2 min-w-0">
                <i className="fa-solid fa-circle-check text-sm shrink-0"></i>
                <span className="truncate">สร้างคีย์เรียบร้อยแล้ว {createdLicensesResult.items.length} บัญชี!</span>
              </div>
              <span className="text-[11px] font-mono text-slate-400 shrink-0">
                {createdLicensesResult.app_name} &bull; {createdLicensesResult.duration_days} วัน
              </span>
            </div>

            {/* Actions Bar */}
            <div className="flex items-center justify-between gap-2">
              <span className="text-xs text-slate-400 font-mono">
                รายการคีย์พร้อมใช้งาน:
              </span>
              <button
                type="button"
                onClick={() => {
                  const allText = createdLicensesResult.items.map(u => {
                    if (u.password) return `${u.username}:${u.password}`;
                    return u.username;
                  }).join('\n');
                  navigator.clipboard.writeText(allText);
                  setCopiedLicenseIdx('all');
                  setTimeout(() => setCopiedLicenseIdx(null), 2000);
                  showToast('คัดลอกคีย์ทั้งหมดสำเร็จ!', 'success');
                }}
                className="px-3.5 py-1.5 rounded-none bg-[#1D63FF] hover:bg-[#3878FF] text-white text-xs font-semibold font-mono transition flex items-center gap-2 cyber-btn-interactive"
              >
                <i className={`fa-solid ${copiedLicenseIdx === 'all' ? 'fa-check text-emerald-300' : 'fa-copy'} text-xs`}></i>
                <span>{copiedLicenseIdx === 'all' ? 'คัดลอกแล้ว!' : 'คัดลอกคีย์ทั้งหมด (Copy All)'}</span>
              </button>
            </div>

            {/* Scrollable Keys List */}
            <div className="max-h-72 overflow-y-auto border border-[#1E2D4A] divide-y divide-[#1E2D4A]/60 bg-[#080C14] custom-scroll">
              {createdLicensesResult.items.map((item, idx) => {
                const itemString = item.password ? `${item.username}:${item.password}` : item.username;
                const isCopied = copiedLicenseIdx === idx;

                return (
                  <div key={idx} className="p-2.5 px-3 flex items-center justify-between gap-3 hover:bg-[#131D31]/40 transition text-xs font-mono">
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="text-slate-500 text-[11px]">#{idx + 1}</span>
                        <span className="text-white font-bold tracking-wider">{item.username}</span>
                        {item.password && (
                          <span className="text-cyan-400 bg-cyan-500/10 px-1.5 py-0.5 border border-cyan-500/20 text-[10px]">
                            PW: {item.password}
                          </span>
                        )}
                      </div>
                      {item.note && (
                        <div className="text-[10px] text-slate-500 truncate mt-0.5">โน้ต: {item.note}</div>
                      )}
                    </div>
                    <button
                      type="button"
                      onClick={() => {
                        navigator.clipboard.writeText(itemString);
                        setCopiedLicenseIdx(idx);
                        setTimeout(() => setCopiedLicenseIdx(null), 2000);
                        showToast(`คัดลอก ${item.username} แล้ว`, 'success');
                      }}
                      className="px-2.5 py-1 rounded-none bg-[#131D31] hover:bg-[#18243D] text-slate-300 hover:text-white border border-[#1E2D4A] text-[10px] shrink-0 font-mono transition"
                    >
                      {isCopied ? '✓ Copied' : 'Copy'}
                    </button>
                  </div>
                );
              })}
            </div>

            <div className="flex justify-end pt-2">
              <button
                type="button"
                onClick={() => setShowLicensesResultModal(false)}
                className="px-4 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-slate-300 hover:text-white text-xs font-mono"
              >
                เสร็จสิ้น / ปิดหน้าต่าง
              </button>
            </div>
          </div>
        )}
      </window.Modal>
    </div>
  );
};
