// Applications Management Page Component
window.AppsPage = function AppsPage({ user, apps, onRefreshApps, showToast }) {
  const isOwner = user?.role === 'owner';

  // Modals
  const [showCreateModal, setShowCreateModal] = React.useState(false);
  const [showEditModal, setShowEditModal] = React.useState(false);
  const [showGuideModal, setShowGuideModal] = React.useState(false);
  const [showConfigModal, setShowConfigModal] = React.useState(false);
  const [selectedApp, setSelectedApp] = React.useState(null);
  const [guideData, setGuideData] = React.useState(null);
  const [activeCodeTab, setActiveCodeTab] = React.useState('csharp');

  // Form states
  const [appName, setAppName] = React.useState('');
  const [appVersion, setAppVersion] = React.useState('1.0.0');
  const [appDownloadUrl, setAppDownloadUrl] = React.useState('');
  const [appAnnouncement, setAppAnnouncement] = React.useState('');
  const [appStatus, setAppStatus] = React.useState('active');
  const [configJsonText, setConfigJsonText] = React.useState('{}');
  const [visibleTokens, setVisibleTokens] = React.useState({});

  const toggleTokenVisibility = (appId) => {
    setVisibleTokens((prev) => ({ ...prev, [appId]: !prev[appId] }));
  };

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

  const handleCreateApp = async (e) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/apps', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({
          name: appName,
          version: appVersion,
          download_url: appDownloadUrl,
          announcement: appAnnouncement
        })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        setShowCreateModal(false);
        setAppName('');
        setAppVersion('1.0.0');
        setAppDownloadUrl('');
        setAppAnnouncement('');
        onRefreshApps();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Failed to create app: ' + err.message, 'error');
    }
  };

  const openEditModal = (app) => {
    setSelectedApp(app);
    setAppName(app.name);
    setAppVersion(app.version || '1.0.0');
    setAppDownloadUrl(app.download_url || '');
    setAppAnnouncement(app.announcement || '');
    setAppStatus(app.status || 'active');
    setShowEditModal(true);
  };

  const handleUpdateApp = async (e) => {
    e.preventDefault();
    if (!selectedApp) return;
    try {
      const res = await fetch(`/api/apps/${selectedApp.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({
          name: appName,
          version: appVersion,
          download_url: appDownloadUrl,
          announcement: appAnnouncement,
          status: appStatus
        })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        setShowEditModal(false);
        onRefreshApps();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Failed to update app: ' + err.message, 'error');
    }
  };

  const openRemoteConfigModal = (app) => {
    setSelectedApp(app);
    setConfigJsonText(JSON.stringify(app.remote_config || { safe_mode: true, aimbot: true, esp: true }, null, 2));
    setShowConfigModal(true);
  };

  const handleSaveRemoteConfig = async (e) => {
    e.preventDefault();
    if (!selectedApp) return;
    try {
      const parsedConfig = JSON.parse(configJsonText);
      const res = await fetch(`/api/apps/${selectedApp.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ remote_config: parsedConfig })
      });
      const data = await res.json();
      if (data.success) {
        showToast('อัปเดต Remote Config เรียบร้อย', 'success');
        setShowConfigModal(false);
        onRefreshApps();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('JSON Syntax Error: รูปแบบ JSON ไม่ถูกต้อง', 'error');
    }
  };

  const handleRegenerateToken = async (app) => {
    if (!confirm(`คำเตือน: การสุ่ม Token ใหม่ของ '${app.name}' จะทำให้โปรแกรมภายนอกที่ใช้ Token เก่าหลุดทันที ดำเนินการต่อหรือไม่?`)) return;
    try {
      const res = await fetch(`/api/apps/${app.id}/regenerate-token`, {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` }
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        onRefreshApps();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error regenerating token', 'error');
    }
  };

  const handleToggleFreeze = async (app) => {
    try {
      const res = await fetch(`/api/apps/${app.id}/toggle-freeze`, {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` }
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        onRefreshApps();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error toggling freeze', 'error');
    }
  };

  const handleDeleteApp = async (app) => {
    if (!confirm(`คุณแน่ใจหรือไม่ว่าต้องการลบแอป '${app.name}'?`)) return;
    try {
      const res = await fetch(`/api/apps/${app.id}`, {
        method: 'DELETE',
        headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` }
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        onRefreshApps();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error deleting app', 'error');
    }
  };

  const openIntegrationGuide = async (app) => {
    try {
      const res = await fetch(`/api/apps/${app.id}/integration`, {
        headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` }
      });
      const data = await res.json();
      if (data.success) {
        setSelectedApp(app);
        setGuideData(data);
        setShowGuideModal(true);
      }
    } catch (err) {
      showToast('Error fetching integration guide', 'error');
    }
  };

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Header */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pb-4 border-b border-[#1E2D4A]">
        <div>
          <h2 className="text-xl font-bold text-white font-brand flex items-center gap-2.5">
            <i className="fa-solid fa-cube text-cyan-400"></i>
            <span>Applications & Client API Integration</span>
          </h2>
          <p className="text-xs text-slate-400 mt-0.5">
            จัดการแอปพลิเคชัน, App Token, หมายเลข Version, Remote Features Config และคู่มือเชื่อมต่อ API
          </p>
        </div>

        {isOwner && (
          <button
            onClick={() => setShowCreateModal(true)}
            className="px-4 py-2.5 rounded-none bg-[#1D63FF] hover:bg-[#3878FF] text-white font-semibold text-xs transition flex items-center gap-2 border border-[#1D63FF] shrink-0"
          >
            <i className="fa-solid fa-plus text-xs"></i>
            <span>สร้างแอปพลิเคชันใหม่</span>
          </button>
        )}
      </div>

      {/* Apps Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 w-full">
        {apps && apps.length > 0 ? (
          apps.map((app) => {
            const isTokenVisible = visibleTokens[app.id];
            const maskedToken = app.token ? `${app.token.substring(0, 6)}••••••••••••••••${app.token.substring(app.token.length - 4)}` : '••••••••';

            return (
              <div
                key={app.id}
                className="p-4 sm:p-6 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex flex-col justify-between space-y-4 hover:border-cyan-500/40 transition shadow-xl min-w-0"
              >
                <div className="space-y-4 min-w-0">
                  {/* Top row */}
                  <div className="flex items-start justify-between gap-2.5 min-w-0">
                    <div className="flex items-center gap-2.5 sm:gap-3 min-w-0 flex-1">
                      <div className="w-10 h-10 sm:w-12 sm:h-12 rounded-none bg-cyan-500/10 border border-cyan-500/30 flex items-center justify-center text-cyan-400 text-base sm:text-lg shadow-lg shrink-0">
                        <i className="fa-solid fa-layer-group"></i>
                      </div>
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-2 flex-wrap">
                          <h3 className="text-sm sm:text-base font-bold text-white font-brand truncate max-w-[150px] sm:max-w-xs">{app.name}</h3>
                          <span className={`text-[9px] sm:text-[10px] font-mono px-1.5 py-0.5 rounded-none ${
                            app.status === 'active'
                              ? 'bg-emerald-500/10 text-[#00FF9D] border border-emerald-500/20'
                              : app.status === 'maintenance'
                              ? 'bg-amber-500/10 text-amber-400 border border-amber-500/20'
                              : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'
                          }`}>
                            {app.status ? app.status.toUpperCase() : 'ACTIVE'}
                          </span>
                        </div>
                        <div className="text-[10px] sm:text-[11px] text-slate-400 font-mono flex items-center gap-1.5 sm:gap-2 mt-0.5 truncate">
                          <span>ID: <strong className="text-slate-200">{app.id}</strong></span>
                          <span>&bull;</span>
                          <span className="truncate">Owner: <strong className="text-amber-400">{app.owner_id || 'OWNER-001'}</strong></span>
                        </div>
                      </div>
                    </div>

                    <div className="px-2 py-0.5 rounded-none bg-blue-500/10 border border-blue-500/20 text-blue-400 font-mono text-[11px] font-semibold shrink-0">
                      v{app.version || '1.0.0'}
                    </div>
                  </div>

                  {/* App Token Box */}
                  <div className="p-3 rounded-none bg-[#080C14] border border-[#1E2D4A] space-y-1 min-w-0">
                    <div className="flex items-center justify-between text-[11px] font-mono text-slate-400">
                      <span className="flex items-center gap-1.5">
                        <i className="fa-solid fa-key text-cyan-400 text-xs"></i>
                        <span>APP SECRET TOKEN</span>
                      </span>
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => toggleTokenVisibility(app.id)}
                          className="hover:text-white transition text-xs"
                          title={isTokenVisible ? 'Hide Token' : 'Show Token'}
                        >
                          <i className={`fa-solid ${isTokenVisible ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                        </button>
                        <button
                          onClick={() => copyToClipboard(app.token, 'App Token')}
                          className="hover:text-white transition text-xs"
                          title="Copy Token"
                        >
                          <i className="fa-regular fa-copy"></i>
                        </button>
                      </div>
                    </div>
                    <div className="font-mono text-xs text-slate-200 tracking-wider truncate">
                      {isTokenVisible ? app.token : maskedToken}
                    </div>
                  </div>

                  {/* Metric Badges - 2 columns on mobile, 4 on tablet+ */}
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-center">
                    <div className="p-2 rounded-none bg-[#080C14] border border-[#1E2D4A]">
                      <div className="text-[10px] text-slate-400 font-mono">TOTAL</div>
                      <div className="text-sm font-bold text-white font-brand">{app.total_users || 0}</div>
                    </div>
                    <div className="p-2 rounded-none bg-[#080C14] border border-[#1E2D4A]">
                      <div className="text-[10px] text-[#00FF9D] font-mono">ONLINE</div>
                      <div className="text-sm font-bold text-[#00FF9D] font-brand">{app.online_users || 0}</div>
                    </div>
                    <div className="p-2 rounded-none bg-[#080C14] border border-[#1E2D4A]">
                      <div className="text-[10px] text-cyan-400 font-mono">ACTIVE</div>
                      <div className="text-sm font-bold text-cyan-400 font-brand">{app.active_users || 0}</div>
                    </div>
                    <div className="p-2 rounded-none bg-[#080C14] border border-[#1E2D4A]">
                      <div className="text-[10px] text-slate-400 font-mono">EXPIRED</div>
                      <div className="text-sm font-bold text-slate-400 font-brand">{app.expired_users || 0}</div>
                    </div>
                  </div>
                </div>

                {/* Footer Action Buttons */}
                <div className="pt-3 border-t border-[#1E2D4A] flex flex-wrap items-center justify-between gap-2">
                  <div className="flex items-center gap-1.5 sm:gap-2">
                    <button
                      onClick={() => openIntegrationGuide(app)}
                      className="px-3 py-1.5 rounded-none bg-cyan-500/10 hover:bg-cyan-500/20 border border-cyan-500/30 text-cyan-300 text-xs font-semibold transition flex items-center gap-1.5"
                    >
                      <i className="fa-solid fa-code text-xs"></i>
                      <span>API Code</span>
                    </button>

                    {isOwner && (
                      <button
                        onClick={() => openRemoteConfigModal(app)}
                        className="px-3 py-1.5 rounded-none bg-purple-500/10 hover:bg-purple-500/20 border border-purple-500/30 text-purple-300 text-xs font-semibold transition flex items-center gap-1.5"
                        title="Remote Feature Flags"
                      >
                        <i className="fa-solid fa-sliders text-xs"></i>
                        <span>Config</span>
                      </button>
                    )}
                  </div>

                  {isOwner && (
                    <div className="flex items-center gap-1.5">
                      <button
                        onClick={() => handleToggleFreeze(app)}
                        className={`p-1.5 rounded-none border text-xs transition ${
                          app.freeze_all
                            ? 'bg-amber-500/20 border-amber-500/40 text-amber-300'
                            : 'bg-[#080C14] border-[#1E2D4A] text-slate-400 hover:text-white'
                        }`}
                        title={app.freeze_all ? 'Unfreeze All' : 'Freeze All Users'}
                      >
                        <i className="fa-regular fa-snowflake"></i>
                      </button>
                      <button
                        onClick={() => handleRegenerateToken(app)}
                        className="p-1.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-slate-400 hover:text-amber-400 transition text-xs"
                        title="Regenerate Token"
                      >
                        <i className="fa-solid fa-arrows-rotate"></i>
                      </button>
                      <button
                        onClick={() => openEditModal(app)}
                        className="p-1.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-slate-400 hover:text-blue-400 transition text-xs"
                        title="Edit App"
                      >
                        <i className="fa-solid fa-pen-to-square"></i>
                      </button>
                      <button
                        onClick={() => handleDeleteApp(app)}
                        className="p-1.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-slate-400 hover:text-rose-400 transition text-xs"
                        title="Delete App"
                      >
                        <i className="fa-solid fa-trash"></i>
                      </button>
                    </div>
                  )}
                </div>
              </div>
            );
          })
        ) : (
          <div className="col-span-2 text-center py-12 text-slate-500 text-xs font-mono">
            ไม่พบแอปพลิเคชัน
          </div>
        )}
      </div>

      {/* CREATE APP MODAL */}
      <window.Modal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        title="สร้างแอปพลิเคชันใหม่"
        icon="fa-cube"
      >
        <form onSubmit={handleCreateApp} className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">APP NAME *</label>
            <input
              type="text"
              required
              value={appName}
              onChange={(e) => setAppName(e.target.value)}
              placeholder="e.g. IceX VIP Mod, AotForms Pro"
              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="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">VERSION *</label>
              <input
                type="text"
                required
                value={appVersion}
                onChange={(e) => setAppVersion(e.target.value)}
                placeholder="1.0.0"
                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">DOWNLOAD URL</label>
              <input
                type="url"
                value={appDownloadUrl}
                onChange={(e) => setAppDownloadUrl(e.target.value)}
                placeholder="https://..."
                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">ANNOUNCEMENT (ประกาศในตัวโปรแกรม)</label>
            <textarea
              rows="2"
              value={appAnnouncement}
              onChange={(e) => setAppAnnouncement(e.target.value)}
              placeholder="ข้อความประกาศที่จะแสดงในโปรแกรมของลูกค้า..."
              className="w-full px-3.5 py-2 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={() => setShowCreateModal(false)}
              className="px-4 py-2 rounded-none bg-[#080C14] 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>

      {/* REMOTE CONFIG MODAL */}
      <window.Modal
        isOpen={showConfigModal}
        onClose={() => setShowConfigModal(false)}
        title={`Remote Features Config: ${selectedApp?.name}`}
        icon="fa-sliders"
        maxWidth="max-w-2xl"
      >
        <form onSubmit={handleSaveRemoteConfig} className="space-y-4">
          <p className="text-xs text-slate-400">
            ตัวแปรและฟีเจอร์สำหรับส่งกลับไปให้ตัวโปรแกรมผ่าน API <code>/init</code> โดยไม่ต้อง Recompile โปรแกรมใหม่:
          </p>
          <textarea
            rows="8"
            value={configJsonText}
            onChange={(e) => setConfigJsonText(e.target.value)}
            className="w-full p-3.5 rounded-none bg-[#080C14] border border-[#1E2D4A] font-mono text-xs text-cyan-300 focus:border-[#1D63FF] outline-none break-anywhere"
          ></textarea>
          <div className="flex justify-end gap-2.5 pt-3 border-t border-[#1E2D4A]">
            <button
              type="button"
              onClick={() => setShowConfigModal(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-purple-600 hover:bg-purple-500 border border-purple-500 text-white text-xs font-semibold"
            >
              บันทึก Config
            </button>
          </div>
        </form>
      </window.Modal>

      {/* EDIT MODAL */}
      <window.Modal
        isOpen={showEditModal}
        onClose={() => setShowEditModal(false)}
        title={`แก้ไขแอป: ${selectedApp?.name}`}
        icon="fa-pen-to-square"
      >
        <form onSubmit={handleUpdateApp} className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">APP NAME</label>
            <input
              type="text"
              required
              value={appName}
              onChange={(e) => setAppName(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"
            />
          </div>

          <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">VERSION</label>
              <input
                type="text"
                required
                value={appVersion}
                onChange={(e) => setAppVersion(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">STATUS</label>
              <select
                value={appStatus}
                onChange={(e) => setAppStatus(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"
              >
                <option value="active">Active (เปิดใช้งานปกติ)</option>
                <option value="maintenance">Maintenance (ปิดปรับปรุง)</option>
                <option value="disabled">Disabled (ปิดถาวร)</option>
              </select>
            </div>
          </div>

          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">DOWNLOAD URL</label>
            <input
              type="url"
              value={appDownloadUrl}
              onChange={(e) => setAppDownloadUrl(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">ANNOUNCEMENT</label>
            <textarea
              rows="2"
              value={appAnnouncement}
              onChange={(e) => setAppAnnouncement(e.target.value)}
              className="w-full px-3.5 py-2 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={() => setShowEditModal(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>

      {/* CODE GUIDE MODAL */}
      <window.Modal
        isOpen={showGuideModal}
        onClose={() => setShowGuideModal(false)}
        title={`Integration Guide: ${selectedApp?.name}`}
        icon="fa-code"
        maxWidth="max-w-4xl"
      >
        <div className="space-y-4">
          <div className="p-3.5 rounded-none bg-[#080C14] border border-[#1E2D4A] space-y-2">
            <div className="text-xs font-semibold text-white font-mono flex items-center gap-2">
              <i className="fa-solid fa-link text-cyan-400"></i>
              <span>API ENDPOINTS (พร้อมระบบ HMAC-SHA256 ป้องกันดักฟัง)</span>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-xs font-mono">
              <div className="p-2 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex items-center justify-between">
                <div>
                  <span className="text-[#00FF9D] font-bold">POST</span> <span className="text-slate-300">/api/v1/client/login</span>
                </div>
                <button
                  onClick={() => copyToClipboard(guideData?.endpoints?.login, 'Login URL')}
                  className="text-slate-400 hover:text-white p-1"
                >
                  <i className="fa-regular fa-copy"></i>
                </button>
              </div>
              <div className="p-2 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex items-center justify-between">
                <div>
                  <span className="text-[#1D63FF] font-bold">POST</span> <span className="text-slate-300">/api/v1/client/heartbeat</span>
                </div>
                <button
                  onClick={() => copyToClipboard(guideData?.endpoints?.heartbeat, 'Heartbeat URL')}
                  className="text-slate-400 hover:text-white p-1"
                >
                  <i className="fa-regular fa-copy"></i>
                </button>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-1.5 sm:gap-2 border-b border-[#1E2D4A] pb-2 overflow-x-auto no-scrollbar">
            {[
              { id: 'csharp', label: 'C# (.NET / Unity)', icon: 'fa-cubes' },
              { id: 'python', label: 'Python', icon: 'fa-brands fa-python' },
              { id: 'cpp', label: 'C++ (WinINet)', icon: 'fa-c' }
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveCodeTab(tab.id)}
                className={`px-3 py-1.5 rounded-none text-xs font-mono flex items-center gap-2 transition shrink-0 border ${
                  activeCodeTab === tab.id
                    ? 'bg-[#1D63FF]/20 text-blue-400 border-blue-500/40 font-semibold'
                    : 'text-slate-400 hover:text-white border-transparent'
                }`}
              >
                <i className={tab.icon}></i>
                <span>{tab.label}</span>
              </button>
            ))}
            <button
              onClick={() => copyToClipboard(guideData?.code_snippets?.[activeCodeTab], 'Code snippet')}
              className="ml-auto px-3 py-1.5 rounded-none bg-[#080C14] hover:bg-[#131D31] border border-[#1E2D4A] text-slate-300 hover:text-white text-xs font-mono transition flex items-center gap-1.5 shrink-0"
            >
              <i className="fa-regular fa-copy"></i>
              <span>Copy Code</span>
            </button>
          </div>

          <div className="relative rounded-none overflow-hidden border border-[#1E2D4A] bg-[#060911]">
            <pre className="p-4 text-xs font-mono text-cyan-300 overflow-x-auto custom-scroll max-h-96">
              <code>{guideData?.code_snippets?.[activeCodeTab]}</code>
            </pre>
          </div>
        </div>
      </window.Modal>
    </div>
  );
};
