<div class="row">
  <!-- システム情報カード -->
  <div class="col-lg-6">
    <div class="card shadow mb-4">
      <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">システム情報</h6>
      </div>
      <div class="card-body">
        <table class="table">
          <tbody>
            <tr>
              <th>Node.jsバージョン</th>
              <td><%= systemInfo.nodeVersion %></td>
            </tr>
            <tr>
              <th>プラットフォーム</th>
              <td><%= systemInfo.platform %></td>
            </tr>
            <tr>
              <th>環境</th>
              <td><%= systemInfo.env || 'development' %></td>
            </tr>
            <tr>
              <th>稼働時間</th>
              <td id="uptime"><%= formatUptime(systemInfo.uptime) %></td>
            </tr>
            <tr>
              <th>メモリ使用量 (RSS)</th>
              <td id="memory-rss"><%= formatMemory(systemInfo.memory.rss) %></td>
            </tr>
            <tr>
              <th>メモリ使用量 (ヒープ合計)</th>
              <td id="memory-heap-total"><%= formatMemory(systemInfo.memory.heapTotal) %></td>
            </tr>
            <tr>
              <th>メモリ使用量 (ヒープ使用)</th>
              <td id="memory-heap-used"><%= formatMemory(systemInfo.memory.heapUsed) %></td>
            </tr>
          </tbody>
        </table>
        
        <div class="d-grid gap-2 mt-3">
          <button id="refreshSystemInfo" class="btn btn-primary">
            <i class="fas fa-sync-alt"></i> 情報を更新
          </button>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 環境変数カード -->
  <div class="col-lg-6">
    <div class="card shadow mb-4">
      <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">環境変数</h6>
      </div>
      <div class="card-body">
        <div class="alert alert-warning">
          <i class="fas fa-exclamation-triangle"></i> セキュリティ上の理由から、一部の環境変数は表示されません。
        </div>
        
        <table class="table">
          <tbody>
            <tr>
              <th>PORT</th>
              <td><%= process.env.PORT || '3000 (デフォルト)' %></td>
            </tr>
            <tr>
              <th>NODE_ENV</th>
              <td><%= process.env.NODE_ENV || 'development (デフォルト)' %></td>
            </tr>
            <tr>
              <th>LINE_CHANNEL_ACCESS_TOKEN</th>
              <td><%= process.env.LINE_CHANNEL_ACCESS_TOKEN ? '設定済み（値は非表示）' : '未設定' %></td>
            </tr>
            <tr>
              <th>DIFY_API_KEY</th>
              <td><%= process.env.DIFY_API_KEY ? '設定済み（値は非表示）' : '未設定' %></td>
            </tr>
            <tr>
              <th>DIFY_API_ENDPOINT</th>
              <td><%= process.env.DIFY_API_ENDPOINT || '未設定' %></td>
            </tr>
            <tr>
              <th>MONGODB_URI</th>
              <td><%= process.env.MONGODB_URI ? '設定済み（値は非表示）' : '未設定' %></td>
            </tr>
            <tr>
              <th>ADMIN_USERNAME</th>
              <td><%= process.env.ADMIN_USERNAME ? '設定済み（値は非表示）' : '未設定' %></td>
            </tr>
            <tr>
              <th>ADMIN_PASSWORD</th>
              <td><%= process.env.ADMIN_PASSWORD ? '設定済み（値は非表示）' : '未設定' %></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- サーバー操作カード -->
<div class="card shadow mb-4">
  <div class="card-header py-3">
    <h6 class="m-0 font-weight-bold text-primary">サーバー操作</h6>
  </div>
  <div class="card-body">
    <div class="row">
      <div class="col-md-4 mb-3">
        <div class="d-grid gap-2">
          <button id="clearCacheBtn" class="btn btn-warning">
            <i class="fas fa-broom"></i> キャッシュクリア
          </button>
        </div>
      </div>
      <div class="col-md-4 mb-3">
        <div class="d-grid gap-2">
          <button id="testDifyBtn" class="btn btn-info">
            <i class="fas fa-vial"></i> Dify API接続テスト
          </button>
        </div>
      </div>
      <div class="col-md-4 mb-3">
        <div class="d-grid gap-2">
          <button id="testLineBtn" class="btn btn-success">
            <i class="fas fa-comment"></i> LINE API接続テスト
          </button>
        </div>
      </div>
    </div>
    
    <div id="operationResult" class="mt-3" style="display: none;">
      <div class="card">
        <div class="card-header">
          操作結果
        </div>
        <div class="card-body">
          <pre id="operationResultContent"></pre>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ログ表示カード -->
<div class="card shadow mb-4">
  <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
    <h6 class="m-0 font-weight-bold text-primary">最新のログ</h6>
    <div>
      <button id="refreshLogsBtn" class="btn btn-sm btn-primary">
        <i class="fas fa-sync-alt"></i> 更新
      </button>
    </div>
  </div>
  <div class="card-body">
    <div id="logsContainer" style="max-height: 300px; overflow-y: auto;">
      <div class="text-center py-3">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">Loading...</span>
        </div>
        <p>ログを読み込み中...</p>
      </div>
    </div>
  </div>
</div>

<script>
  $(document).ready(function() {
    // システム情報の更新
    function updateSystemInfo() {
      $.get('/admin/api/system-info', function(data) {
        $('#uptime').text(formatUptime(data.uptime));
        $('#memory-rss').text(formatMemory(data.memory.rss));
        $('#memory-heap-total').text(formatMemory(data.memory.heapTotal));
        $('#memory-heap-used').text(formatMemory(data.memory.heapUsed));
      });
    }
    
    // 更新ボタンのクリックイベント
    $('#refreshSystemInfo').click(function() {
      updateSystemInfo();
    });
    
    // 1分ごとに自動更新
    setInterval(updateSystemInfo, 60000);
    
    // キャッシュクリアボタンのクリックイベント
    $('#clearCacheBtn').click(function() {
      if (confirm('キャッシュをクリアしますか？')) {
        $.post('/admin/api/clear-cache', function(data) {
          $('#operationResultContent').text(JSON.stringify(data, null, 2));
          $('#operationResult').show();
        });
      }
    });
    
    // Dify API接続テストボタンのクリックイベント
    $('#testDifyBtn').click(function() {
      $('#operationResultContent').text('Dify API接続テスト中...');
      $('#operationResult').show();
      
      $.get('/admin/api/test-dify', function(data) {
        $('#operationResultContent').text(JSON.stringify(data, null, 2));
      });
    });
    
    // LINE API接続テストボタンのクリックイベント
    $('#testLineBtn').click(function() {
      $('#operationResultContent').text('LINE API接続テスト中...');
      $('#operationResult').show();
      
      $.get('/admin/api/test-line', function(data) {
        $('#operationResultContent').text(JSON.stringify(data, null, 2));
      });
    });
    
    // ログの読み込み
    function loadLogs() {
      $.get('/admin/api/logs', function(data) {
        let html = '';
        
        if (data.logs && data.logs.length > 0) {
          html = '<div class="list-group">';
          
          data.logs.forEach(function(log) {
            let levelClass = 'list-group-item-info';
            
            if (log.level === 'error') {
              levelClass = 'list-group-item-danger';
            } else if (log.level === 'warn') {
              levelClass = 'list-group-item-warning';
            }
            
            html += `<div class="list-group-item ${levelClass}">`;
            html += `<div class="d-flex w-100 justify-content-between">`;
            html += `<h6 class="mb-1">${log.message}</h6>`;
            html += `<small>${new Date(log.timestamp).toLocaleString('ja-JP')}</small>`;
            html += `</div>`;
            
            if (log.details) {
              html += `<pre class="mb-1 small">${log.details}</pre>`;
            }
            
            html += `</div>`;
          });
          
          html += '</div>';
        } else {
          html = '<div class="alert alert-info">ログはありません</div>';
        }
        
        $('#logsContainer').html(html);
      });
    }
    
    // 初回ログ読み込み
    loadLogs();
    
    // ログ更新ボタンのクリックイベント
    $('#refreshLogsBtn').click(function() {
      $('#logsContainer').html(`
        <div class="text-center py-3">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
          <p>ログを読み込み中...</p>
        </div>
      `);
      
      loadLogs();
    });
  });
  
  // 稼働時間のフォーマット
  function formatUptime(seconds) {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    
    let result = '';
    if (days > 0) result += `${days}日 `;
    if (hours > 0 || days > 0) result += `${hours}時間 `;
    result += `${minutes}分`;
    
    return result;
  }
  
  // メモリ使用量のフォーマット
  function formatMemory(bytes) {
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
  }
</script>