<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>强制广告管理系统</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <style>
    :root {
      --primary-color: #3b82f6; /* 清爽蓝 */
      --bg-color: #f9fafb; /* 极简白灰 */
      --card-bg: #ffffff; /* 纯白卡片 */
      --text-color: #111827; /* 深灰黑文字 */
      --border-color: #e5e7eb; /* 浅灰边框 */
    }
    
    body {
      font-family: -apple-system, "Microsoft YaHei", "PingFang SC", BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      background-color: var(--bg-color);
      background-image: none;
      color: var(--text-color);
      min-height: 100vh;
      line-height: 1.6;
      -webkit-font-smoothing: antialiased;
    }

    /* 移除动态粒子背景容器 */
    #canvas-container {
      display: none;
    }

    .container {
      max-width: 1400px;
      padding-top: 3rem;
    }

    h1 {
      color: var(--text-color);
      font-weight: 700;
      margin-bottom: 3rem;
      text-align: center;
      letter-spacing: -0.015em;
      background: none;
      -webkit-text-fill-color: initial;
      text-shadow: none;
      font-size: 1.75rem;
    }

    .card {
      background: var(--card-bg);
      backdrop-filter: none;
      -webkit-backdrop-filter: none;
      border: 1px solid var(--border-color);
      border-radius: 12px;
      box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
      transition: none;
    }

    .card:hover {
      transform: none;
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
      border-color: var(--border-color);
    }

    .card-header {
      background: #ffffff;
      border-bottom: 1px solid var(--border-color);
      color: var(--text-color);
      border-radius: 12px 12px 0 0;
      height: 80px;
      display: flex;
      align-items: center;
      padding: 0 2rem;
    }

    .card-header h2 {
      font-size: 1.125rem;
      font-weight: 600;
      margin: 0;
      letter-spacing: 0;
      color: #111827;
    }

    .btn-primary {
      background-color: #111827; /* 黑色按钮 */
      border: none;
      border-radius: 6px;
      padding: 6px 16px;
      font-size: 0.875rem;
      font-weight: 500;
      color: #fff;
      box-shadow: none;
      transition: all 0.2s ease;
    }

    .btn-primary:hover {
      transform: none;
      background-color: #374151;
      box-shadow: none;
      color: #fff;
    }

    .btn-danger {
      background-color: #fff;
      border: 1px solid #ef4444;
      color: #ef4444;
      border-radius: 8px;
      padding: 4px 12px;
      font-weight: 500;
      box-shadow: none;
    }

    .btn-danger:hover {
      transform: none;
      background-color: #fef2f2;
      box-shadow: none;
    }
    
    .btn-light {
      background-color: #f3f4f6;
      border: 1px solid #e5e7eb;
    }

    .table {
      color: var(--text-color);
      margin-bottom: 0;
    }

    .table thead th {
      background-color: #f9fafb;
      color: #4b5563;
      border-bottom: 1px solid var(--border-color);
      font-weight: 600;
      text-transform: uppercase;
      font-size: 0.75rem;
      letter-spacing: 0.05em;
      padding: 0.75rem 1.5rem;
    }

    .table td {
      padding: 0.875rem 1.5rem;
      vertical-align: middle;
      border-top: none;
      font-size: 0.875rem;
      color: #111827;
      font-weight: 400;
    }

    .form-control {
      background-color: #fff;
      border: 1px solid #d1d5db;
      color: #111827;
      border-radius: 8px;
      padding-left: 12px;
      box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    }

    .form-control:focus {
      background-color: #fff;
      border-color: #3b82f6;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
      color: #111827;
    }

    .form-control::placeholder {
      color: #9ca3af;
    }

    .stats-badge {
      background: #f3f4f6;
      border: 1px solid #e5e7eb;
      color: #374151;
      padding: 2px 8px;
      border-radius: 6px;
      font-size: 0.75rem;
      font-weight: 500;
      margin-left: 8px;
    }
    
    .stats-badge.active {
      color: #059669;
      background: #ecfdf5;
      border-color: #a7f3d0;
      box-shadow: none;
    }
    
    .stats-badge.inactive {
      color: #dc2626;
      background: #fef2f2;
      border-color: #fecaca;
      box-shadow: none;
    }

    /* 自定义滚动条 - 极简 */
    ::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }
    ::-webkit-scrollbar-track {
      background: transparent;
    }
    ::-webkit-scrollbar-thumb {
      background: #d1d5db;
      border-radius: 3px;
    }
    ::-webkit-scrollbar-thumb:hover {
      background: #9ca3af;
    }

    .card-body {
      display: flex;
      flex-direction: column;
      flex-grow: 1;
      padding: 0;
    }
    
    .table-responsive {
      overflow-x: auto;
      overflow-y: auto;
      flex-grow: 1;
      height: 0;
      padding: 0;
    }
    
    .row {
      height: 75vh; /* 稍微减小高度，更紧凑 */
    }
    .col-md-6 {
      height: 100%;
    }
    @media (max-width: 768px) {
      .row {
        height: auto;
      }
      .col-md-6 {
        height: auto;
        margin-bottom: 2rem;
      }
      .table-responsive {
        height: 500px;
      }
    }

    /* 模态框样式 - 极简 */
    .modal-content {
      background: #ffffff;
      color: #111827;
      border: none;
      box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
      border-radius: 12px;
    }
    
    .modal-header {
      border-bottom: 1px solid #e5e7eb;
      background: transparent;
      padding: 1.5rem;
    }
    
    .modal-body {
      padding: 1.5rem;
    }

    .modal-footer {
      border-top: 1px solid #e5e7eb;
      padding: 1.5rem;
    }
    
    .btn-close {
      filter: none;
    }
    
    .form-select {
      background-color: #fff;
      border: 1px solid #d1d5db;
      color: #111827;
      border-radius: 8px;
    }
    
    .form-select:focus {
      background-color: #fff;
      border-color: #3b82f6;
      color: #111827;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
    
    .btn-secondary {
      background-color: #fff;
      border: 1px solid #d1d5db;
      color: #374151;
    }
    
    .btn-secondary:hover {
      background-color: #f9fafb;
      border-color: #d1d5db;
      color: #111827;
    }
  </style>
</head>
<body>
  <canvas id="canvas-container"></canvas>
  <div class="container mt-5">
    <h1 class="text-center mb-5">强制广告管理系统</h1>
    
    <!-- 主要内容区 -->
    <div class="row">
      <!-- 左侧：游戏管理 -->
      <div class="col-md-6">
        <div class="card h-100">
          <div class="card-header">
            <div class="d-flex justify-content-between align-items-center w-100">
              <div class="d-flex align-items-center">
                <h2>游戏管理</h2>
                <span class="stats-badge" id="totalGamesBadge">总数: 0</span>
              </div>
              <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addGameModal">添加游戏</button>
            </div>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-bordered table-hover">
                <thead>
                  <tr>
                    <th>游戏ID</th>
                    <th>游戏名称</th>
                    <th>平台</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody id="gameList">
                  <!-- 游戏列表将通过JavaScript动态添加 -->
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧：广告配置管理 -->
      <div class="col-md-6">
        <div class="card h-100">
          <div class="card-header">
            <div class="d-flex justify-content-between align-items-center w-100">
              <div class="d-flex align-items-center">
                <h2>广告配置管理</h2>
                <span class="stats-badge active" id="enabledConfigsBadge">开启: 0</span>
                <span class="stats-badge inactive" id="disabledConfigsBadge">未开启: 0</span>
              </div>
              <div class="d-flex align-items-center gap-2">
                <button class="btn btn-light btn-sm" id="enableAllBtn" type="button" onclick="setAllConfigsEnabled(1)" data-default-text="全部开启">全部开启</button>
                <button class="btn btn-light btn-sm" id="disableAllBtn" type="button" onclick="setAllConfigsEnabled(0)" data-default-text="全部关闭">全部关闭</button>
                <div class="input-group" style="width: 300px;">
                  <input type="text" id="searchInput" class="form-control" placeholder="搜索游戏名称或ID...">
                  <button class="btn btn-light" type="button" onclick="searchConfigs()">搜索</button>
                </div>
              </div>
            </div>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-bordered table-hover">
                <thead>
                  <tr>
                    <th>游戏ID</th>
                    <th>游戏名称</th>
                    <th>是否启用</th>
                    <th>延迟(ms)</th>
                    <th>目标用户</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody id="configList">
                  <!-- 配置列表将通过JavaScript动态添加 -->
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 添加游戏模态框 -->
  <div class="modal fade" id="addGameModal" tabindex="-1" aria-labelledby="addGameModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="addGameModalLabel">添加游戏</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="addGameForm">
            <div class="mb-3">
              <label for="gameId" class="form-label">游戏ID</label>
              <input type="text" class="form-control" id="gameId" required>
            </div>
            <div class="mb-3">
              <label for="gameName" class="form-label">游戏名称</label>
              <input type="text" class="form-control" id="gameName" required>
            </div>
            <div class="mb-3">
              <label for="platform" class="form-label">平台</label>
              <select class="form-select" id="platform" required>
                <option value="kuaishou">快手</option>
                <option value="wechat">微信</option>
                <option value="tt">字节跳动</option>
                <option value="oppo">OPPO</option>
                <option value="vivo">vivo</option>
              </select>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
          <button type="button" class="btn btn-primary" onclick="addGame()">保存</button>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 编辑配置模态框 -->
  <div class="modal fade" id="editConfigModal" tabindex="-1" aria-labelledby="editConfigModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="editConfigModalLabel">编辑广告配置</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="editConfigForm">
            <input type="hidden" id="editGameId">
            <div class="mb-3">
              <label class="form-label">游戏ID</label>
              <input type="text" class="form-control" id="editGameIdDisplay" disabled>
            </div>
            <div class="mb-3">
              <label for="editEnabled" class="form-label">是否启用</label>
              <select class="form-select" id="editEnabled">
                <option value="1">启用</option>
                <option value="0">禁用</option>
              </select>
            </div>
            <div class="mb-3">
              <label for="editDelay" class="form-label">延迟时间(毫秒)</label>
              <input type="number" class="form-control" id="editDelay" min="0" required>
            </div>
            <div class="mb-3">
              <label for="editUserType" class="form-label">目标用户</label>
              <select class="form-select" id="editUserType">
                <option value="1">新用户</option>
                <option value="2">老用户</option>
                <option value="3">所有用户</option>
              </select>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
          <button type="button" class="btn btn-primary" onclick="updateConfig()">保存</button>
        </div>
      </div>
    </div>
  </div>
  
  <script>
    // API基础URL
    // 自动判断当前路径，支持子目录部署
    // 如果当前页面在 /backend/public/admin.html，那么 API 应该在 /backend/api/force-ad
    // 算法：取当前 URL 路径，去掉 /public/admin.html，加上 /api/force-ad
    let currentPath = window.location.pathname;
    // 移除文件名
    let basePath = currentPath.substring(0, currentPath.lastIndexOf('/'));
    // 如果 basePath 包含 /public，则移除它
    if (basePath.endsWith('/public')) {
        basePath = basePath.substring(0, basePath.lastIndexOf('/public'));
    }
    // 如果是根目录，basePath 为空
    if (basePath === '/') basePath = '';
    
    const apiBaseUrl = basePath + '/api/force-ad';
    
    let allGames = []; // 存储所有游戏数据
    let isBatchUpdating = false;

    // 页面加载完成后获取游戏列表和配置
    $(document).ready(function() {
      loadGames();
      loadConfigs();
      initParticles(); // 初始化粒子效果
      
      // 监听搜索框回车事件
      $('#searchInput').on('keypress', function(e) {
        if (e.which === 13) {
          searchConfigs();
        }
      });
      
      // 监听搜索框输入事件（可选：实时搜索）
      $('#searchInput').on('input', function() {
        searchConfigs();
      });
    });
    
    // 加载游戏列表
    function loadGames() {
      $.ajax({
        url: apiBaseUrl + '/games',
        type: 'GET',
        cache: false,
        headers: {
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
        },
        success: function(response) {
          if (response.data) {
            allGames = response.data; // 保存所有游戏数据
            renderGameList(allGames);
          }
        },
        error: function(xhr, status, error) {
            console.error("加载游戏列表失败:", error);
        }
      });
    }

    // 渲染游戏列表
    function renderGameList(games) {
      const gameList = $('#gameList');
      gameList.empty();
      
      // 更新游戏总数统计
      $('#totalGamesBadge').text(`总数: ${games.length}`);
      
      games.forEach(game => {
        gameList.append(`
          <tr>
            <td>${game.game_id}</td>
            <td>${game.game_name}</td>
            <td>${game.platform}</td>
            <td>
              <button class="btn btn-danger btn-sm" onclick="deleteGame('${game.game_id}')">删除</button>
            </td>
          </tr>
        `);
      });
    }
    
    // 加载配置列表
    function loadConfigs() {
      $.ajax({
        url: apiBaseUrl + '/games',
        type: 'GET',
        cache: false,
        headers: {
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
        },
        success: function(response) {
          if (response.data) {
            allGames = response.data; // 更新全局游戏数据
            renderConfigList(allGames);
          }
        }
      });
    }

    // 渲染配置列表
    function renderConfigList(games) {
      const configList = $('#configList');
      configList.empty();
      
      // 重置统计数据
      let enabledCount = 0;
      let disabledCount = 0;
      let processedCount = 0; // 用于追踪已处理的请求数量
      const totalGames = games.length;
      
      if (totalGames === 0) {
        configList.append('<tr><td colspan="6" class="text-center">没有找到相关游戏</td></tr>');
        $('#enabledConfigsBadge').text(`开启: 0`);
        $('#disabledConfigsBadge').text(`未开启: 0`);
        return;
      }

      games.forEach(game => {
        // 获取每个游戏的配置
        $.ajax({
          url: apiBaseUrl + '/config',
          type: 'GET',
          cache: false,
          headers: {
              'Cache-Control': 'no-cache, no-store, must-revalidate',
              'Pragma': 'no-cache',
              'Expires': '0'
          },
          data: { game_id: game.game_id, platform: game.platform },
          success: function(configResponse) {
            if (configResponse.data) {
              const config = configResponse.data;
              const userTypeText = config.user_type == 1 ? '新用户' : (config.user_type == 2 ? '老用户' : '所有用户');
              
              // 更新统计数据
              if (config.enabled == 1) {
                enabledCount++;
              } else {
                disabledCount++;
              }
              
              // 每次请求完成后更新UI统计
              processedCount++;
              if (processedCount === totalGames || processedCount % 5 === 0) { // 减少DOM操作频率
                 $('#enabledConfigsBadge').text(`开启: ${enabledCount}`);
                 $('#disabledConfigsBadge').text(`未开启: ${disabledCount}`);
              }

              // 根据 enabled 状态生成不同颜色的徽章
              const enabledBadge = config.enabled == 1 
                ? `<span class="badge bg-danger rounded-pill px-3 py-2 cursor-pointer" onclick="editConfig('${game.game_id}', ${config.enabled}, ${config.delay}, ${config.user_type})" style="cursor: pointer;">是</span>` 
                : `<span class="badge bg-success rounded-pill px-3 py-2 cursor-pointer" onclick="editConfig('${game.game_id}', ${config.enabled}, ${config.delay}, ${config.user_type})" style="cursor: pointer;">否</span>`;
              
              // 使用 data-game-id 属性方便后续可能的DOM操作
              const rowId = `config-row-${game.game_id.replace(/[^a-zA-Z0-9]/g, '')}`;
              
              configList.append(`
                <tr id="${rowId}">
                  <td>${game.game_id}</td>
                  <td>${game.game_name}</td>
                  <td>${enabledBadge}</td>
                  <td>${config.delay}</td>
                  <td>${userTypeText}</td>
                  <td>
                    <button class="btn btn-primary btn-sm" onclick="editConfig('${game.game_id}', ${config.enabled}, ${config.delay}, ${config.user_type})">编辑</button>
                  </td>
                </tr>
              `);
            }
          }
        });
      });
    }

    // 搜索功能
    function getFilteredGamesBySearchText(searchText) {
      if (!searchText) {
        return allGames;
      }
      return allGames.filter(game => {
        return (game.game_name && game.game_name.toLowerCase().includes(searchText)) || 
               (game.game_id && game.game_id.toLowerCase().includes(searchText));
      });
    }

    function searchConfigs() {
      const searchText = $('#searchInput').val().toLowerCase().trim();
      const filteredGames = getFilteredGamesBySearchText(searchText);
      renderConfigList(filteredGames);
    }

    function updateBatchButtonsState() {
      const buttons = $('#enableAllBtn, #disableAllBtn');
      buttons.prop('disabled', isBatchUpdating);
      buttons.each(function() {
        const defaultText = $(this).data('default-text');
        $(this).text(isBatchUpdating ? '处理中...' : defaultText);
      });
    }

    async function setAllConfigsEnabled(enabled) {
      if (isBatchUpdating) {
        return;
      }

      const searchText = $('#searchInput').val().toLowerCase().trim();
      const targetGames = getFilteredGamesBySearchText(searchText);
      const actionText = enabled === 1 ? '开启' : '关闭';

      if (targetGames.length === 0) {
        alert('当前没有可操作的游戏配置');
        return;
      }

      if (!confirm(`确定要${actionText}${targetGames.length}个游戏的广告配置吗？`)) {
        return;
      }

      isBatchUpdating = true;
      updateBatchButtonsState();

      let successCount = 0;
      let failedCount = 0;

      for (const game of targetGames) {
        try {
          const configResponse = await $.ajax({
            url: apiBaseUrl + '/config',
            type: 'GET',
            cache: false,
            headers: {
              'Cache-Control': 'no-cache, no-store, must-revalidate',
              'Pragma': 'no-cache',
              'Expires': '0'
            },
            data: {
              game_id: game.game_id,
              platform: game.platform
            }
          });

          const config = configResponse && configResponse.data ? configResponse.data : {};
          const delay = Number.isFinite(parseInt(config.delay, 10)) ? parseInt(config.delay, 10) : 1000;
          const userType = Number.isFinite(parseInt(config.user_type, 10)) ? parseInt(config.user_type, 10) : 3;

          await $.ajax({
            url: apiBaseUrl + '/config',
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify({
              game_id: game.game_id,
              enabled: enabled,
              delay: delay,
              user_type: userType
            })
          });
          successCount++;
        } catch (error) {
          failedCount++;
          console.error(`批量${actionText}失败:`, game.game_id, error);
        }
      }

      isBatchUpdating = false;
      updateBatchButtonsState();

      if (failedCount === 0) {
        alert(`已${actionText}${successCount}个游戏配置`);
      } else {
        alert(`批量${actionText}完成：成功${successCount}个，失败${failedCount}个`);
      }

      loadConfigs();
    }
    
    // 添加游戏
    function addGame() {
      const gameId = $('#gameId').val();
      const gameName = $('#gameName').val();
      const platform = $('#platform').val();
      
      $.ajax({
        url: apiBaseUrl + '/games',
        type: 'POST',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({
          game_id: gameId,
          game_name: gameName,
          platform: platform
        }),
        success: function(response) {
          if (response.success) {
            alert('游戏添加成功');
            $('#addGameModal').modal('hide');
            $('#addGameForm')[0].reset();
            // 强制刷新页面以确保数据最新
            location.reload(true);
          } else {
            alert('添加失败: ' + response.error);
          }
        },
        error: function(jqXHR, textStatus, errorThrown) {
          alert('请求失败: ' + textStatus + ' - ' + errorThrown);
          console.error('AJAX Error:', jqXHR.responseText);
        }
      });
    }
    
    // 删除游戏
    function deleteGame(gameId) {
      if (confirm('确定要删除这个游戏吗？')) {
        $.ajax({
          url: apiBaseUrl + '/games/' + gameId,
          type: 'DELETE',
          success: function(response) {
            if (response.success) {
              alert('游戏删除成功');
              // 强制刷新页面
              location.reload(true);
            } else {
              alert('删除失败: ' + response.error);
            }
          }
        });
      }
    }
    
    // 编辑配置
    function editConfig(gameId, enabled, delay, userType) {
      $('#editGameId').val(gameId);
      $('#editGameIdDisplay').val(gameId);
      $('#editEnabled').val(enabled);
      $('#editDelay').val(delay);
      $('#editUserType').val(userType);
      $('#editConfigModal').modal('show');
    }
    
    // 更新配置
    function updateConfig() {
      const gameId = $('#editGameId').val();
      const enabled = parseInt($('#editEnabled').val());
      const delay = parseInt($('#editDelay').val());
      const userType = parseInt($('#editUserType').val());
      
      $.ajax({
        url: apiBaseUrl + '/config',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({
          game_id: gameId,
          enabled: enabled,
          delay: delay,
          user_type: userType
        }),
        success: function(response) {
          if (response.success) {
            alert('配置更新成功');
            // 强制刷新当前页面，忽略缓存
            location.reload(true);
          } else {
            alert('更新失败: ' + response.error);
          }
        },
        error: function(jqXHR, textStatus, errorThrown) {
          alert('请求失败: ' + textStatus + ' - ' + errorThrown);
          console.error('AJAX Error:', jqXHR.responseText);
        }
      });
    }

    // 粒子背景动画脚本
    function initParticles() {
      const canvas = document.getElementById('canvas-container');
      const ctx = canvas.getContext('2d');
      let width, height;
      let particles = [];

      function resize() {
        width = window.innerWidth;
        height = window.innerHeight;
        canvas.width = width;
        canvas.height = height;
      }

      window.addEventListener('resize', resize);
      resize();

      class Particle {
        constructor() {
          this.x = Math.random() * width;
          this.y = Math.random() * height;
          this.vx = (Math.random() - 0.5) * 0.5;
          this.vy = (Math.random() - 0.5) * 0.5;
          this.size = Math.random() * 2 + 1;
        }

        update() {
          this.x += this.vx;
          this.y += this.vy;

          if (this.x < 0) this.x = width;
          if (this.x > width) this.x = 0;
          if (this.y < 0) this.y = height;
          if (this.y > height) this.y = 0;
        }

        draw() {
          ctx.beginPath();
          ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
          ctx.fillStyle = 'rgba(0, 242, 254, 0.5)';
          ctx.fill();
        }
      }

      for (let i = 0; i < 100; i++) {
        particles.push(new Particle());
      }

      function animate() {
        ctx.clearRect(0, 0, width, height);
        
        for (let i = 0; i < particles.length; i++) {
          particles[i].update();
          particles[i].draw();
          
          for (let j = i; j < particles.length; j++) {
            const dx = particles[i].x - particles[j].x;
            const dy = particles[i].y - particles[j].y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance < 100) {
              ctx.beginPath();
              ctx.strokeStyle = `rgba(0, 242, 254, ${0.1 - distance/1000})`;
              ctx.lineWidth = 0.5;
              ctx.moveTo(particles[i].x, particles[i].y);
              ctx.lineTo(particles[j].x, particles[j].y);
              ctx.stroke();
            }
          }
        }
        requestAnimationFrame(animate);
      }

      animate();
    }
  </script>
</body>
</html>
