// Comprehensive API Documentation & Integration Hub Component
window.ApiDocsPage = function ApiDocsPage({ user, apps, showToast }) {
  const [selectedLang, setSelectedLang] = React.useState('cpp');
  const [selectedEndpoint, setSelectedEndpoint] = React.useState('login');
  const [copiedKey, setCopiedKey] = React.useState('');

  const currentApp = apps?.[0] || {
    id: 'app_default',
    name: 'IceX VIP Mod',
    token: '53f8c524a28bc58f415a99e1c6ef450aa0dbb3ac7db03c3a',
    owner_id: user?.owner_id || '84920183',
    version: '1.0.0'
  };

  const copyCode = (code, label) => {
    navigator.clipboard.writeText(code);
    setCopiedKey(label);
    setTimeout(() => setCopiedKey(''), 2000);
    showToast(`คัดลอกโค้ด ${label} เรียบร้อยแล้ว!`, 'success');
  };

  const fileDownloadMap = {
    csharp: { filename: 'AuthClient.cs', url: '/downloads/AuthClient.cs', label: 'C# .NET / Native AOT' },
    cpp: { filename: 'AuthClient.hpp', url: '/downloads/AuthClient.hpp', label: 'C++ Single Header' },
    python: { filename: 'auth_client.py', url: '/downloads/auth_client.py', label: 'Python 3 Standalone' },
    node: { filename: 'auth_client.js', url: '/downloads/auth_client.js', label: 'Node.js / Electron SDK' },
    curl: null
  };

  const downloadFile = (filePath, fileName) => {
    const a = document.createElement('a');
    a.href = filePath;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    showToast(`กำลังเริ่มดาวน์โหลด ${fileName}`, 'success');
  };

  const baseUrl = window.location.origin;

  // Code Snippets
  const codeExamples = {
    cpp: `// ============================================================================
// IceX Modz - C++ Client Authentication Module (WinINet + WinCrypt)
// No external dependencies needed! Link with: wininet.lib crypt32.lib
// ============================================================================
#include <windows.h>
#include <wininet.h>
#include <wincrypt.h>
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <chrono>

#pragma comment(lib, "wininet.lib")
#pragma comment(lib, "crypt32.lib")

// Project Configuration
const std::string API_BASE_HOST = "${window.location.hostname}";
const int API_PORT = ${window.location.port || (window.location.protocol === 'https:' ? 443 : 80)};
const bool USE_HTTPS = ${window.location.protocol === 'https:' ? 'true' : 'false'};

const std::string APP_ID    = "${currentApp.id}";
const std::string APP_TOKEN = "${currentApp.token}";
const std::string OWNER_ID  = "${currentApp.owner_id || '84920183'}";
const std::string APP_VER   = "${currentApp.version || '1.0.0'}";

// Helper: Generate HMAC-SHA256 Signature
std::string ComputeHMAC_SHA256(const std::string& key, const std::string& data) {
    HCRYPTPROV hProv = 0;
    HCRYPTHASH hHash = 0;
    HCRYPTKEY hKey = 0;
    std::string hexOutput = "";

    if (!CryptAcquireContext(&hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) return "";

    struct {
        BLOBHEADER hdr;
        DWORD len;
        BYTE key[1024];
    } keyBlob;

    keyBlob.hdr.bType = PLAINTEXTKEYBLOB;
    keyBlob.hdr.bVersion = CUR_BLKEYVER;
    keyBlob.hdr.reserved = 0;
    keyBlob.hdr.aiKeyAlg = CALG_RC2;
    keyBlob.len = (DWORD)key.length();
    memcpy(keyBlob.key, key.data(), keyBlob.len);

    if (CryptImportKey(hProv, (BYTE*)&keyBlob, sizeof(BLOBHEADER) + sizeof(DWORD) + keyBlob.len, 0, CRYPT_IPSEC_HMAC_KEY, &hKey)) {
        HMAC_INFO HmacInfo;
        ZeroMemory(&HmacInfo, sizeof(HmacInfo));
        HmacInfo.HashAlgid = CALG_SHA_256;

        if (CryptCreateHash(hProv, CALG_HMAC, hKey, 0, &hHash)) {
            CryptSetHashParam(hHash, HP_HMAC_INFO, (BYTE*)&HmacInfo, 0);
            CryptHashData(hHash, (BYTE*)data.data(), (DWORD)data.length(), 0);

            DWORD dwDataLen = 32;
            BYTE bHash[32];
            if (CryptGetHashParam(hHash, HP_HASHVAL, bHash, &dwDataLen, 0)) {
                std::stringstream ss;
                for (DWORD i = 0; i < dwDataLen; i++) {
                    ss << std::hex << std::setw(2) << std::setfill('0') << (int)bHash[i];
                }
                hexOutput = ss.str();
            }
            CryptDestroyHash(hHash);
        }
        CryptDestroyKey(hKey);
    }
    CryptReleaseContext(hProv, 0);
    return hexOutput;
}

// Client Login Function
bool IceX_ClientLogin(const std::string& username, const std::string& password, const std::string& hwid, std::string& outResponse) {
    long long timestamp = std::chrono::duration_cast<std::chrono::seconds>(
        std::chrono::system_clock::now().time_since_epoch()
    ).count();

    // 1. Calculate HMAC signature: timestamp + username + hwid
    std::string payloadToSign = std::to_string(timestamp) + username + hwid;
    std::string signature = ComputeHMAC_SHA256(APP_TOKEN, payloadToSign);

    // 2. Prepare JSON Body
    std::string jsonBody = "{\\"app_id\\":\\"" + APP_ID + "\\","
                           "\\"app_token\\":\\"" + APP_TOKEN + "\\","
                           "\\"username\\":\\"" + username + "\\","
                           "\\"password\\":\\"" + password + "\\","
                           "\\"hwid\\":\\"" + hwid + "\\","
                           "\\"timestamp\\":" + std::to_string(timestamp) + "}";

    // 3. Send HTTP POST
    HINTERNET hInternet = InternetOpenA("IceX-Client/1.0", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    if (!hInternet) return false;

    HINTERNET hConnect = InternetConnectA(hInternet, API_BASE_HOST.c_str(), API_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
    if (!hConnect) { InternetCloseHandle(hInternet); return false; }

    DWORD flags = (USE_HTTPS ? INTERNET_FLAG_SECURE : 0) | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
    HINTERNET hRequest = HttpOpenRequestA(hConnect, "POST", "/api/v1/client/login", NULL, NULL, NULL, flags, 0);
    if (!hRequest) { InternetCloseHandle(hConnect); InternetCloseHandle(hInternet); return false; }

    std::string headers = "Content-Type: application/json\\r\\n"
                          "X-IceX-Signature: " + signature + "\\r\\n"
                          "X-IceX-Timestamp: " + std::to_string(timestamp) + "\\r\\n";

    BOOL sent = HttpSendRequestA(hRequest, headers.c_str(), (DWORD)headers.length(), (LPVOID)jsonBody.c_str(), (DWORD)jsonBody.length());
    if (sent) {
        char buffer[2048];
        DWORD bytesRead = 0;
        std::string responseStr = "";
        while (InternetReadFile(hRequest, buffer, sizeof(buffer) - 1, &bytesRead) && bytesRead > 0) {
            buffer[bytesRead] = '\\0';
            responseStr += buffer;
        }
        outResponse = responseStr;
    }

    InternetCloseHandle(hRequest);
    InternetCloseHandle(hConnect);
    InternetCloseHandle(hInternet);
    return sent && outResponse.find("\\"success\\":true") != std::string::npos;
}

int main() {
    std::cout << "[IceX Modz] Initializing client auth..." << std::endl;
    std::string response;
    std::string username = "MY_KEY_OR_USER";
    std::string password = "MY_PASSWORD";
    std::string machineHwid = "PC-WIN-EXAMPLE-HWID-12345";

    if (IceX_ClientLogin(username, password, machineHwid, response)) {
        std::cout << "[+] Authentication SUCCESS!" << std::endl;
        std::cout << response << std::endl;
    } else {
        std::cout << "[-] Authentication FAILED!" << std::endl;
        std::cout << response << std::endl;
    }
    return 0;
}`,

    csharp: `// ============================================================================
// IceX Modz - C# / .NET Client Authentication SDK (Native AOT Safe)
// Copyright By Hack.CL 2026
// Compatible with .NET 6/7/8/9 Native AOT, Windows Forms, WPF & Console
// Zero External Dependencies, Zero Reflection, JIT-Free Regex
// ============================================================================
using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32;

namespace IceX
{
    public static class AuthClient
    {
        // Default Server Configuration
        public static string ServerUrl = "${baseUrl}";
        public static string AppId     = "${currentApp.id}";
        public static string AppToken  = "${currentApp.token}";
        public static string OwnerId   = "${currentApp.owner_id || '84920183'}";

        // Status & Session Properties
        public static bool IsInitialized { get; private set; } = false;
        public static bool IsLoggedIn { get; private set; } = false;
        public static string CurrentToken { get; private set; } = "";
        public static string Hwid { get; private set; } = "";

        public static AuthResponse Response = new AuthResponse();
        public static UserData User = new UserData();

        private static readonly HttpClient httpClient = new HttpClient();
        private static Timer heartbeatTimer;

        public class AuthResponse
        {
            public bool Success { get; set; } = false;
            public string Message { get; set; } = "";
        }

        public class UserData
        {
            public string Username { get; set; } = "";
            public string RemainingDays { get; set; } = "0";
            public long ExpiresAt { get; set; } = 0;
            public bool IsFrozen { get; set; } = false;
        }

        public static void Log(string message)
        {
            try
            {
                string logDir = Path.Combine(Path.GetTempPath(), "IceX");
                if (!Directory.Exists(logDir)) Directory.CreateDirectory(logDir);
                string logFile = Path.Combine(logDir, "icex_login.log");
                string line = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {message}\\r\\n";
                File.AppendAllText(logFile, line);
            }
            catch { }
        }

        public static void Init()
        {
            try
            {
                Log("[AuthClient] Initializing IceX AuthClient...");

                // Check if custom server config exists
                string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server_config.json");
                if (File.Exists(configPath))
                {
                    string json = File.ReadAllText(configPath);
                    string customUrl = JsonExtractString(json, "server_url");
                    if (!string.IsNullOrEmpty(customUrl)) ServerUrl = customUrl.TrimEnd('/');
                }

                httpClient.Timeout = TimeSpan.FromSeconds(10);
                Hwid = GenerateHwid();
                IsInitialized = true;
                Log($"[AuthClient] Init complete. ServerUrl={ServerUrl}, HWID={Hwid}");
            }
            catch (Exception ex)
            {
                Response.Success = false;
                Response.Message = "Init failed: " + ex.Message;
                Log($"[AuthClient] Init error: {ex}");
            }
        }

        // Synchronous Login
        public static bool Login(string username, string password = "")
        {
            try
            {
                return Task.Run(() => LoginAsync(username, password)).ConfigureAwait(false).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                Response.Success = false;
                Response.Message = "Login error: " + ex.Message;
                Log($"[AuthClient] Login sync error: {ex}");
                return false;
            }
        }

        // Asynchronous Login with HMAC-SHA256 & Timestamp Protection
        public static async Task<bool> LoginAsync(string username, string password = "")
        {
            if (!IsInitialized) Init();

            try
            {
                string cleanUser = (username ?? "").Trim();
                string cleanPass = (password ?? "").Trim();
                long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

                string signature = "";
                if (!string.IsNullOrEmpty(AppToken))
                {
                    signature = GenerateHmac(AppToken, $"{timestamp}{cleanUser}{Hwid}");
                }

                string jsonBody = "{" +
                    "\\"app_id\\":\\"" + Escape(AppId) + "\\"," +
                    "\\"app_token\\":\\"" + Escape(AppToken) + "\\"," +
                    "\\"username\\":\\"" + Escape(cleanUser) + "\\"," +
                    "\\"password\\":\\"" + Escape(cleanPass) + "\\"," +
                    "\\"hwid\\":\\"" + Escape(Hwid) + "\\"," +
                    "\\"timestamp\\":" + timestamp +
                "}";

                using var request = new HttpRequestMessage(HttpMethod.Post, ServerUrl.TrimEnd('/') + "/api/v1/client/login");
                request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

                if (!string.IsNullOrEmpty(signature))
                {
                    request.Headers.Add("X-IceX-Signature", signature);
                    request.Headers.Add("X-IceX-Timestamp", timestamp.ToString());
                }

                var httpResponse = await httpClient.SendAsync(request).ConfigureAwait(false);
                string responseStr = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                Log($"[AuthClient] HTTP {(int)httpResponse.StatusCode} response: {responseStr}");

                bool success = JsonExtractBool(responseStr, "success");
                string msg = JsonExtractString(responseStr, "message");

                Response.Success = success;
                Response.Message = msg;

                if (success)
                {
                    IsLoggedIn = true;
                    CurrentToken = JsonExtractString(responseStr, "token");

                    string parsedUser = JsonExtractString(responseStr, "username");
                    User.Username = !string.IsNullOrEmpty(parsedUser) ? parsedUser : cleanUser;
                    User.RemainingDays = JsonExtractString(responseStr, "remaining_days");
                    if (string.IsNullOrEmpty(User.RemainingDays)) User.RemainingDays = "0";
                    User.ExpiresAt = JsonExtractLong(responseStr, "expires_at");
                    User.IsFrozen = JsonExtractBool(responseStr, "is_frozen");

                    Log($"[AuthClient] Login SUCCESS! User={User.Username}, Days={User.RemainingDays}");

                    StartHeartbeat(cleanUser);
                    return true;
                }

                Log($"[AuthClient] Login REJECTED: {msg}");
                return false;
            }
            catch (Exception ex)
            {
                Response.Success = false;
                Response.Message = "Cannot connect to auth server (" + ServerUrl + "): " + ex.Message;
                Log($"[AuthClient] Exception in LoginAsync: {ex}");
                return false;
            }
        }

        public static async Task<bool> VerifyAsync()
        {
            if (!IsLoggedIn) return false;
            try
            {
                string jsonBody = "{\\"key\\":\\"" + Escape(User.Username) + "\\",\\"app_token\\":\\"" + Escape(AppToken) + "\\"}";
                var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
                var res = await httpClient.PostAsync(ServerUrl.TrimEnd('/') + "/api/v1/client/verify", content).ConfigureAwait(false);
                string str = await res.Content.ReadAsStringAsync().ConfigureAwait(false);
                return JsonExtractBool(str, "valid");
            }
            catch
            {
                return false;
            }
        }

        private static void StartHeartbeat(string username)
        {
            try
            {
                if (heartbeatTimer != null) heartbeatTimer.Dispose();

                heartbeatTimer = new Timer(async (state) =>
                {
                    try
                    {
                        string json = "{\\"username\\":\\"" + Escape(username) + "\\",\\"token\\":\\"" + Escape(CurrentToken) + "\\",\\"hwid\\":\\"" + Escape(Hwid) + "\\"}";
                        var content = new StringContent(json, Encoding.UTF8, "application/json");
                        await httpClient.PostAsync(ServerUrl.TrimEnd('/') + "/api/client/heartbeat", content).ConfigureAwait(false);
                    }
                    catch { }
                }, null, 30000, 30000);
            }
            catch { }
        }

        private static string GenerateHmac(string key, string message)
        {
            using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
            byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
            var sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++) sb.Append(hash[i].ToString("x2"));
            return sb.ToString();
        }

        private static string Escape(string s)
        {
            if (string.IsNullOrEmpty(s)) return "";
            return s.Replace("\\\\", "\\\\\\\\").Replace("\\"", "\\\\\\\"");
        }

        public static string JsonExtractString(string json, string key)
        {
            if (string.IsNullOrEmpty(json)) return "";
            var match = Regex.Match(json, $"\\"{key}\\"\\\\s*:\\\\s*\\"([^\\"]*)\\"");
            return match.Success ? match.Groups[1].Value : "";
        }

        public static bool JsonExtractBool(string json, string key)
        {
            if (string.IsNullOrEmpty(json)) return false;
            var match = Regex.Match(json, $"\\"{key}\\"\\\\s*:\\\\s*(true|false)", RegexOptions.IgnoreCase);
            return match.Success && bool.TryParse(match.Groups[1].Value, out bool val) && val;
        }

        public static long JsonExtractLong(string json, string key)
        {
            if (string.IsNullOrEmpty(json)) return 0;
            var match = Regex.Match(json, $"\\"{key}\\"\\\\s*:\\\\s*(-?\\\\d+)");
            return match.Success && long.TryParse(match.Groups[1].Value, out long val) ? val : 0;
        }

        private static string GenerateHwid()
        {
            try
            {
                string rawHwid = "";
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Cryptography"))
                {
                    if (key != null)
                    {
                        object val = key.GetValue("MachineGuid");
                        if (val != null) rawHwid += val.ToString();
                    }
                }
                rawHwid += Environment.MachineName + Environment.ProcessorCount.ToString() + Environment.UserName;
                using (SHA256 sha = SHA256.Create())
                {
                    byte[] bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(rawHwid));
                    var sb = new StringBuilder();
                    for (int i = 0; i < bytes.Length; i++) sb.Append(bytes[i].ToString("X2"));
                    return sb.ToString();
                }
            }
            catch
            {
                return Guid.NewGuid().ToString("N").ToUpper();
            }
        }
    }
}`,

    python: `# ============================================================================
# IceX Modz - Python 3 Client Authentication Script
# Requirements: pip install requests
# ============================================================================
import time
import hmac
import hashlib
import requests

API_BASE_URL = "${baseUrl}"
APP_ID       = "${currentApp.id}"
APP_TOKEN    = "${currentApp.token}"
OWNER_ID     = "${currentApp.owner_id || '84920183'}"

def compute_hmac_signature(secret: str, data: str) -> str:
    return hmac.new(secret.encode('utf-8'), data.encode('utf-8'), hashlib.sha256).hexdigest()

def icex_login(username: str, password: str = "", hwid: str = "MACHINE-HWID-001"):
    timestamp = int(time.time())
    payload_to_sign = f"{timestamp}{username}{hwid}"
    signature = compute_hmac_signature(APP_TOKEN, payload_to_sign)

    headers = {
        "Content-Type": "application/json",
        "X-IceX-Signature": signature,
        "X-IceX-Timestamp": str(timestamp)
    }

    data = {
        "app_id": APP_ID,
        "app_token": APP_TOKEN,
        "username": username,
        "password": password,
        "hwid": hwid,
        "timestamp": timestamp
    }

    try:
        response = requests.post(f"{API_BASE_URL}/api/v1/client/login", json=data, headers=headers, timeout=10)
        return response.json()
    except Exception as e:
        return {"success": False, "message": f"Network error: {str(e)}"}

# Test Login
if __name__ == "__main__":
    print("[IceX Modz] Testing client login...")
    result = icex_login("MY_LICENSE_KEY", "", "PC-HWID-WIN11-TEST")
    print("Response:", result)
`,

    node: `// ============================================================================
// IceX Modz - Node.js / JavaScript Client SDK
// ============================================================================
const crypto = require('crypto');

const API_BASE_URL = '${baseUrl}';
const APP_ID       = '${currentApp.id}';
const APP_TOKEN    = '${currentApp.token}';

async function icexClientLogin(username, password = '', hwid = 'PC-HWID-DEFAULT') {
  const timestamp = Math.floor(Date.now() / 1000);
  const signature = crypto
    .createHmac('sha256', APP_TOKEN)
    .update(\`\${timestamp}\${username}\${hwid}\`)
    .digest('hex');

  const res = await fetch(\`\${API_BASE_URL}/api/v1/client/login\`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-IceX-Signature': signature,
      'X-IceX-Timestamp': timestamp.toString()
    },
    body: JSON.stringify({
      app_id: APP_ID,
      app_token: APP_TOKEN,
      username,
      password,
      hwid,
      timestamp
    })
  });

  return await res.json();
}

// Execution
icexClientLogin('MY_LICENSE_KEY', '', 'HWID_001').then(console.log);`,

    curl: `# ============================================================================
# IceX Modz - cURL Command Line Example
# ============================================================================
# 1. Compute HMAC: echo -n "TIMESTAMP+USER+HWID" | openssl dgst -sha256 -hmac "APP_TOKEN"
# 2. Execute Request:

curl -X POST "${baseUrl}/api/v1/client/login" \\
  -H "Content-Type: application/json" \\
  -H "X-IceX-Signature: YOUR_COMPUTED_HMAC_SHA256" \\
  -H "X-IceX-Timestamp: 1789440000" \\
  -d '{
    "app_id": "${currentApp.id}",
    "app_token": "${currentApp.token}",
    "username": "VIP-KEY-XXXX-YYYY",
    "password": "",
    "hwid": "PC-HWID-EXAMPLE",
    "timestamp": 1789440000
  }'`
  };

  return (
    <div className="space-y-6 animate-card-in">
      {/* Header */}
      <div className="p-5 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex flex-col md:flex-row items-start md:items-center justify-between gap-4 shadow-xl">
        <div>
          <h2 className="text-xl font-bold text-white font-brand flex items-center gap-2.5">
            <i className="fa-solid fa-code text-cyan-400"></i>
            <span>เอกสารและคู่มือการเชื่อมต่อ API (API Documentation)</span>
          </h2>
          <p className="text-xs text-slate-400 mt-1 font-mono">
            โค้ดตัวอย่าง C++, C#, Python, Node.js พร้อมระบบป้องกันการดักแอบแก้ข้อมูล (HMAC-SHA256 Anti-Sniffing)
          </p>
        </div>

        <div className="flex items-center gap-2 text-xs font-mono">
          <span className="px-2.5 py-1 bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
            API v1.0 ONLINE
          </span>
        </div>
      </div>

      {/* Security Architecture Box */}
      <div className="p-5 rounded-none bg-[#0E1626] border border-cyan-500/30 space-y-3 shadow-xl">
        <div className="flex items-center gap-2 text-sm font-bold text-white font-mono">
          <i className="fa-solid fa-shield-halved text-cyan-400"></i>
          <span>สถาปัตยกรรมความปลอดภัย & ระบบ Anti-Sniffing (HMAC-SHA256)</span>
        </div>
        <p className="text-xs text-slate-300 leading-relaxed font-sans">
          IceX Modz ใช้ระบบ <strong>HMAC-SHA256 Signature Verification</strong> ร่วมกับ <strong>Timestamp Replay-Attack Protection (±300 วินาที)</strong> และ <strong>Hardware ID Binding</strong> เพื่อป้องกันไม่ให้ผู้ไม่ประสงค์ดีดักจับแพ็กเก็ต (Fiddler / Charles / Wireshark) แล้วปลอมแปลงคำขอหรือแก้ Response:
        </p>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-3 pt-2 font-mono text-xs">
          <div className="p-3 bg-[#080C14] border border-[#1E2D4A] space-y-1">
            <div className="text-cyan-400 font-bold">1. HMAC-SHA256 SIGNATURE</div>
            <p className="text-[11px] text-slate-400 font-sans">
              สร้าง Signature จาก <code>timestamp + username + hwid</code> โดยใช้ <code>App Token</code> เป็น Secret Key
            </p>
          </div>
          <div className="p-3 bg-[#080C14] border border-[#1E2D4A] space-y-1">
            <div className="text-purple-400 font-bold">2. REPLAY ATTACK DEFENSE</div>
            <p className="text-[11px] text-slate-400 font-sans">
              Timestamp ต้องตรงกับเวลาเซิร์ฟเวอร์ภายใน ±300 วินาที หากมีการนำ Request เก่ามายิงซ้ำจะถูกบล็อกทันที
            </p>
          </div>
          <div className="p-3 bg-[#080C14] border border-[#1E2D4A] space-y-1">
            <div className="text-emerald-400 font-bold">3. HARDWARE LOCK (HWID)</div>
            <p className="text-[11px] text-slate-400 font-sans">
              เมื่อคีย์ถูกเปิดใช้งานครั้งแรก ระบบจะผูก Hardware ID เครื่องนั้นไว้ทันที หากแชร์ให้ผู้อื่นจะติดสถานะ Mismatch
            </p>
          </div>
        </div>
      </div>

      {/* Endpoints Reference Navigator */}
      <div className="p-5 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-4 shadow-xl">
        <div className="flex items-center gap-2 text-xs font-bold text-white font-mono uppercase pb-3 border-b border-[#1E2D4A]">
          <i className="fa-solid fa-list-check text-cyan-400"></i>
          <span>รายการ Endpoint สำหรับ Client & ระบบภายนอก</span>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
          {/* Endpoint Sidebar */}
          <div className="space-y-1.5 font-mono text-xs">
            <button
              onClick={() => setSelectedEndpoint('login')}
              className={`w-full text-left p-2.5 px-3 rounded-none border transition flex items-center justify-between ${
                selectedEndpoint === 'login'
                  ? 'bg-blue-600/20 text-blue-300 border-blue-500/40'
                  : 'bg-[#080C14] border-[#1E2D4A] text-slate-400 hover:text-white'
              }`}
            >
              <span>POST /login</span>
              <span className="text-[10px] px-1.5 py-0.5 bg-blue-500/10 text-blue-400 border border-blue-500/20">Client</span>
            </button>

            <button
              onClick={() => setSelectedEndpoint('verify')}
              className={`w-full text-left p-2.5 px-3 rounded-none border transition flex items-center justify-between ${
                selectedEndpoint === 'verify'
                  ? 'bg-blue-600/20 text-blue-300 border-blue-500/40'
                  : 'bg-[#080C14] border-[#1E2D4A] text-slate-400 hover:text-white'
              }`}
            >
              <span>POST /verify</span>
              <span className="text-[10px] px-1.5 py-0.5 bg-blue-500/10 text-blue-400 border border-blue-500/20">Client</span>
            </button>

            <button
              onClick={() => setSelectedEndpoint('heartbeat')}
              className={`w-full text-left p-2.5 px-3 rounded-none border transition flex items-center justify-between ${
                selectedEndpoint === 'heartbeat'
                  ? 'bg-blue-600/20 text-blue-300 border-blue-500/40'
                  : 'bg-[#080C14] border-[#1E2D4A] text-slate-400 hover:text-white'
              }`}
            >
              <span>POST /heartbeat</span>
              <span className="text-[10px] px-1.5 py-0.5 bg-blue-500/10 text-blue-400 border border-blue-500/20">Client</span>
            </button>

            <button
              onClick={() => setSelectedEndpoint('config')}
              className={`w-full text-left p-2.5 px-3 rounded-none border transition flex items-center justify-between ${
                selectedEndpoint === 'config'
                  ? 'bg-blue-600/20 text-blue-300 border-blue-500/40'
                  : 'bg-[#080C14] border-[#1E2D4A] text-slate-400 hover:text-white'
              }`}
            >
              <span>POST /config</span>
              <span className="text-[10px] px-1.5 py-0.5 bg-blue-500/10 text-blue-400 border border-blue-500/20">Client</span>
            </button>

            <button
              onClick={() => setSelectedEndpoint('hwid-reset')}
              className={`w-full text-left p-2.5 px-3 rounded-none border transition flex items-center justify-between ${
                selectedEndpoint === 'hwid-reset'
                  ? 'bg-blue-600/20 text-blue-300 border-blue-500/40'
                  : 'bg-[#080C14] border-[#1E2D4A] text-slate-400 hover:text-white'
              }`}
            >
              <span>POST /public-reset</span>
              <span className="text-[10px] px-1.5 py-0.5 bg-cyan-500/10 text-cyan-400 border border-cyan-500/20">Public Link</span>
            </button>
          </div>

          {/* Endpoint Specification Details */}
          <div className="lg:col-span-3 p-4 bg-[#080C14] border border-[#1E2D4A] space-y-3 text-xs font-mono">
            {selectedEndpoint === 'login' && (
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <span className="px-2 py-0.5 bg-blue-600 text-white font-bold">POST</span>
                  <span className="text-white font-bold text-sm">/api/v1/client/login</span>
                </div>
                <p className="text-slate-400 font-sans">
                  ใช้สำหรับให้ Client (Mod / Loader) ส่งข้อมูลเข้าสู่ระบบ, ตรวจสอบอายุการใช้งาน, ผูก HWID อัตโนมัติในครั้งแรก และรับ Session Token
                </p>

                <div className="space-y-1">
                  <span className="text-cyan-400 font-bold">REQUIRED HEADERS:</span>
                  <pre className="p-2.5 bg-[#0E1626] border border-[#1E2D4A] text-[11px] text-slate-300 overflow-x-auto">
Content-Type: application/json
X-IceX-Signature: hex(HMAC_SHA256(app_token, timestamp + username + hwid))
X-IceX-Timestamp: 1789440000</pre>
                </div>

                <div className="space-y-1">
                  <span className="text-cyan-400 font-bold">SUCCESS RESPONSE (200 OK):</span>
                  <pre className="p-2.5 bg-[#0E1626] border border-[#1E2D4A] text-[11px] text-emerald-400 overflow-x-auto">
{`{
  "success": true,
  "message": "Login successful",
  "token": "icex_sess_...",
  "username": "user123",
  "expires_at": 1792032000000,
  "remaining_days": 29.8,
  "app_name": "IceX VIP Mod",
  "version": "1.0.0"
}`}</pre>
                </div>
              </div>
            )}

            {selectedEndpoint === 'verify' && (
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <span className="px-2 py-0.5 bg-blue-600 text-white font-bold">POST</span>
                  <span className="text-white font-bold text-sm">/api/v1/client/verify</span>
                </div>
                <p className="text-slate-400 font-sans">
                  ตรวจสอบสถานะของคีย์หรือ Session Token อย่างรวดเร็ว เพื่อเช็คว่าคีย์ยังคง Active ไม่หมดอายุ หรือไม่ได้ถูกแบนระหว่างใช้งาน
                </p>
                <div className="space-y-1">
                  <span className="text-cyan-400 font-bold">PAYLOAD:</span>
                  <pre className="p-2.5 bg-[#0E1626] border border-[#1E2D4A] text-[11px] text-slate-300 overflow-x-auto">
{`{
  "app_id": "${currentApp.id}",
  "app_token": "${currentApp.token}",
  "token": "icex_sess_...",
  "hwid": "PC-HWID"
}`}</pre>
                </div>
              </div>
            )}

            {selectedEndpoint === 'heartbeat' && (
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <span className="px-2 py-0.5 bg-blue-600 text-white font-bold">POST</span>
                  <span className="text-white font-bold text-sm">/api/v1/client/heartbeat</span>
                </div>
                <p className="text-slate-400 font-sans">
                  ส่ง Ping ทุกๆ 30-60 วินาทีขณะที่โปรแกรมทำงาน เพื่อให้หน้าพาเนลแสดงสถานะ Online แบบเรียลไทม์
                </p>
              </div>
            )}

            {selectedEndpoint === 'config' && (
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <span className="px-2 py-0.5 bg-blue-600 text-white font-bold">POST</span>
                  <span className="text-white font-bold text-sm">/api/v1/client/config</span>
                </div>
                <p className="text-slate-400 font-sans">
                  ดึงการตั้งค่าระยะไกล เช่น ข้อความประกาศ Announcement, ลิงก์ดาวน์โหลดอัปเดตเวอร์ชันใหม่ และสถานะเปิด/ปิดระบบชั่วคราว (Maintenance Mode)
                </p>
              </div>
            )}

            {selectedEndpoint === 'hwid-reset' && (
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <span className="px-2 py-0.5 bg-cyan-600 text-white font-bold">POST</span>
                  <span className="text-white font-bold text-sm">/api/hwid-links/public-reset/:token</span>
                </div>
                <p className="text-slate-400 font-sans">
                  รีเซ็ต Hardware ID ผ่านลิงก์พอร์ทัล โดยระบุ <code>token</code> ใน URL และส่งเพียง <code>username</code> ใน Body ระบบจะล้างค่า HWID ให้ทันที
                </p>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Client SDK Downloads Section */}
      <div className="p-5 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-4 shadow-xl">
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 pb-3 border-b border-[#1E2D4A]">
          <div>
            <h3 className="text-sm sm:text-base font-bold text-white font-brand flex items-center gap-2">
              <i className="fa-solid fa-cloud-arrow-down text-cyan-400"></i>
              <span>ศูนย์ดาวน์โหลด Client SDK ทุกภาษา (Download Ready-to-Use SDK Files)</span>
            </h3>
            <p className="text-xs text-slate-400 font-mono mt-0.5">
              ไฟล์โค้ด Client พร้อมนำไปใช้งานทันที รองรับ Native AOT, ป้องกันการตรวจจับ (Anti-Sniffing) และมีระบบ Heartbeat ในตัว
            </p>
          </div>
          <span className="text-[10px] font-mono px-2.5 py-1 bg-cyan-500/10 text-cyan-400 border border-cyan-500/20 uppercase tracking-wider">
            All SDKs 2026 Ready
          </span>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 pt-1">
          {/* C# Card */}
          <div className="p-4 bg-[#080C14] border border-[#1E2D4A] flex flex-col justify-between space-y-3 cyber-card-hover">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-purple-400 text-base font-bold flex items-center gap-2 font-mono">
                  <i className="fa-solid fa-hashtag text-purple-400"></i>
                  C# (.NET / AOT)
                </span>
                <span className="text-[10px] px-2 py-0.5 bg-purple-500/10 text-purple-300 border border-purple-500/20 font-mono">
                  .cs
                </span>
              </div>
              <p className="text-xs text-slate-400 leading-relaxed font-sans">
                ไฟล์ <code>AuthClient.cs</code> โครงสร้างแบบ Native AOT ปลอดจาก Reflection และ JIT 100% เหมาะสำหรับ WinForms, WPF และ Console
              </p>
              <div className="flex flex-wrap gap-1 text-[10px] font-mono text-slate-400">
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">Native AOT</span>
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">Zero-Reflection</span>
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">Heartbeat 30s</span>
              </div>
            </div>
            <button
              onClick={() => downloadFile('/downloads/AuthClient.cs', 'AuthClient.cs')}
              className="w-full py-2 bg-purple-600 hover:bg-purple-500 text-white text-xs font-mono font-bold flex items-center justify-center gap-2 transition cyber-btn-interactive"
            >
              <i className="fa-solid fa-download"></i>
              <span>ดาวน์โหลด AuthClient.cs</span>
            </button>
          </div>

          {/* C++ Card */}
          <div className="p-4 bg-[#080C14] border border-[#1E2D4A] flex flex-col justify-between space-y-3 cyber-card-hover">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-blue-400 text-base font-bold flex items-center gap-2 font-mono">
                  <i className="fa-solid fa-file-code text-blue-400"></i>
                  C++ (WinINet)
                </span>
                <span className="text-[10px] px-2 py-0.5 bg-blue-500/10 text-blue-300 border border-blue-500/20 font-mono">
                  .hpp
                </span>
              </div>
              <p className="text-xs text-slate-400 leading-relaxed font-sans">
                ไฟล์ <code>AuthClient.hpp</code> Single Header ดึง WinINet + WinCrypt โดยตรง ไม่ต้องลง Library ภายนอก เชื่อมต่อง่ายในคลิกเดียว
              </p>
              <div className="flex flex-wrap gap-1 text-[10px] font-mono text-slate-400">
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">WinINet</span>
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">WinCrypt</span>
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">Anti-Sniffing</span>
              </div>
            </div>
            <button
              onClick={() => downloadFile('/downloads/AuthClient.hpp', 'AuthClient.hpp')}
              className="w-full py-2 bg-blue-600 hover:bg-blue-500 text-white text-xs font-mono font-bold flex items-center justify-center gap-2 transition cyber-btn-interactive"
            >
              <i className="fa-solid fa-download"></i>
              <span>ดาวน์โหลด AuthClient.hpp</span>
            </button>
          </div>

          {/* Python Card */}
          <div className="p-4 bg-[#080C14] border border-[#1E2D4A] flex flex-col justify-between space-y-3 cyber-card-hover">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-yellow-400 text-base font-bold flex items-center gap-2 font-mono">
                  <i className="fa-brands fa-python text-yellow-400"></i>
                  Python 3
                </span>
                <span className="text-[10px] px-2 py-0.5 bg-yellow-500/10 text-yellow-300 border border-yellow-500/20 font-mono">
                  .py
                </span>
              </div>
              <p className="text-xs text-slate-400 leading-relaxed font-sans">
                ไฟล์ <code>auth_client.py</code> รันได้ทันทีด้วย Pure Standard Library ไม่ต้อง pip install มีระบบสร้าง HWID และ Thread Heartbeat
              </p>
              <div className="flex flex-wrap gap-1 text-[10px] font-mono text-slate-400">
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">Pure Standard</span>
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">Auto-HWID</span>
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">HMAC-SHA256</span>
              </div>
            </div>
            <button
              onClick={() => downloadFile('/downloads/auth_client.py', 'auth_client.py')}
              className="w-full py-2 bg-yellow-600 hover:bg-yellow-500 text-white text-xs font-mono font-bold flex items-center justify-center gap-2 transition cyber-btn-interactive"
            >
              <i className="fa-solid fa-download"></i>
              <span>ดาวน์โหลด auth_client.py</span>
            </button>
          </div>

          {/* Node.js / Electron Card */}
          <div className="p-4 bg-[#080C14] border border-[#1E2D4A] flex flex-col justify-between space-y-3 cyber-card-hover">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-emerald-400 text-base font-bold flex items-center gap-2 font-mono">
                  <i className="fa-brands fa-node-js text-emerald-400"></i>
                  Node.js / Electron
                </span>
                <span className="text-[10px] px-2 py-0.5 bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 font-mono">
                  .js
                </span>
              </div>
              <p className="text-xs text-slate-400 leading-relaxed font-sans">
                ไฟล์ <code>auth_client.js</code> สำหรับ Electron Desktop Loader หรือ Backend Service มีระบบคำนวณ MachineGuid และ Auto-Reconnect
              </p>
              <div className="flex flex-wrap gap-1 text-[10px] font-mono text-slate-400">
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">Electron Ready</span>
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">Built-in Crypto</span>
                <span className="px-1.5 py-0.5 bg-[#0E1626] border border-[#1E2D4A]">Interval Ping</span>
              </div>
            </div>
            <button
              onClick={() => downloadFile('/downloads/auth_client.js', 'auth_client.js')}
              className="w-full py-2 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-mono font-bold flex items-center justify-center gap-2 transition cyber-btn-interactive"
            >
              <i className="fa-solid fa-download"></i>
              <span>ดาวน์โหลด auth_client.js</span>
            </button>
          </div>
        </div>
      </div>

      {/* Code Examples Section */}
      <div className="p-5 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-4 shadow-xl">
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 pb-3 border-b border-[#1E2D4A]">
          <div className="flex items-center gap-2 text-xs font-bold text-white font-mono uppercase">
            <i className="fa-solid fa-laptop-code text-cyan-400"></i>
            <span>โค้ดตัวอย่างพร้อมใช้งาน (Ready-to-Use Code Snippets)</span>
          </div>

          <div className="flex items-center gap-1.5 flex-wrap">
            {[
              { id: 'csharp', name: 'C# (.NET / AOT)', icon: 'fa-hashtag' },
              { id: 'cpp', name: 'C++ (WinINet)', icon: 'fa-file-code' },
              { id: 'python', name: 'Python 3', icon: 'fa-brands fa-python' },
              { id: 'node', name: 'Node.js', icon: 'fa-brands fa-node-js' },
              { id: 'curl', name: 'cURL', icon: 'fa-terminal' }
            ].map(lang => (
              <button
                key={lang.id}
                onClick={() => setSelectedLang(lang.id)}
                className={`px-3 py-1.5 rounded-none text-xs font-mono transition flex items-center gap-1.5 border ${
                  selectedLang === lang.id
                    ? 'bg-[#1D63FF] text-white border-[#1D63FF]'
                    : 'bg-[#080C14] border-[#1E2D4A] text-slate-400 hover:text-white'
                }`}
              >
                <i className={`${lang.icon} text-xs`}></i>
                <span>{lang.name}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Code Box */}
        <div className="relative border border-[#1E2D4A] bg-[#080C14]">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 p-2.5 px-4 bg-[#0B111E] border-b border-[#1E2D4A] text-xs font-mono">
            <span className="text-slate-400 truncate">
              LANGUAGE: <strong className="text-white uppercase">{selectedLang}</strong> &bull; TARGET APP: <strong className="text-cyan-400">{currentApp.name}</strong>
            </span>
            <div className="flex items-center gap-2 shrink-0">
              {fileDownloadMap[selectedLang] && (
                <button
                  onClick={() => downloadFile(fileDownloadMap[selectedLang].url, fileDownloadMap[selectedLang].filename)}
                  className="px-3 py-1 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-mono transition flex items-center gap-1.5 cyber-btn-interactive"
                  title={`ดาวน์โหลด ${fileDownloadMap[selectedLang].filename}`}
                >
                  <i className="fa-solid fa-download text-xs"></i>
                  <span>ดาวน์โหลดไฟล์</span>
                </button>
              )}
              <button
                onClick={() => copyCode(codeExamples[selectedLang], selectedLang.toUpperCase())}
                className="px-3 py-1 bg-[#1D63FF] hover:bg-[#3878FF] text-white text-xs font-mono transition flex items-center gap-1.5 cyber-btn-interactive"
              >
                <i className={`fa-solid ${copiedKey === selectedLang.toUpperCase() ? 'fa-check text-emerald-300' : 'fa-copy'} text-xs`}></i>
                <span>{copiedKey === selectedLang.toUpperCase() ? 'คัดลอกแล้ว!' : 'คัดลอกโค้ด (Copy Code)'}</span>
              </button>
            </div>
          </div>

          <pre className="p-4 text-xs font-mono text-cyan-300/90 overflow-x-auto max-h-[500px] custom-scroll leading-relaxed select-all whitespace-pre">
            {codeExamples[selectedLang]}
          </pre>
        </div>
      </div>
    </div>
  );
};
