<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NexusAI Admin — Image Studio Control Center</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
<style>
:root {
  --bg-0: #0a0a0f;
  --bg-1: #12121a;
  --bg-2: #191924;
  --bg-3: #222232;
  --line: #2a2a3c;
  --text-0: #f4f4fa;
  --text-1: #b5b3cd;
  --text-2: #757393;
  --purple: #8b5cf6;
  --purple-glow: rgba(139,92,246,.25);
  --teal: #2dd4bf;
  --amber: #fbbf24;
  --red: #f87171;
  --grad-brand: linear-gradient(135deg, #7c3aed 0%, #c084fc 60%, #f472b6 100%);
  --radius: 12px;
  font-family: 'Inter', system-ui, sans-serif;
}
* { margin:0; padding:0; box-sizing:border-box; }
body { background: var(--bg-0); color: var(--text-0); font-size: 14px; min-height: 100vh; display: flex; flex-direction: column; }
button, input, select, textarea { font-family: inherit; }
button { cursor: pointer; }

/* Shell */
.topbar {
  height: 60px; background: var(--bg-1); border-bottom: 1px solid var(--line);
  padding: 0 24px; display: flex; align-items: center; justify-content: space-between;
}
.brand { display: flex; align-items: center; gap: 12px; font-weight: 800; font-size: 16px; }
.brand-icon { width: 34px; height: 34px; border-radius: 10px; background: var(--grad-brand); display: flex; align-items: center; justify-content: center; color: #fff; }
.nav-links { display: flex; gap: 6px; }
.nav-btn {
  background: transparent; border: none; color: var(--text-1); padding: 8px 16px; border-radius: 8px;
  font-size: 13px; font-weight: 600; display: flex; align-items: center; gap: 8px; transition: .15s;
}
.nav-btn:hover { background: var(--bg-2); color: #fff; }
.nav-btn.active { background: var(--purple-glow); color: var(--purple); border: 1px solid rgba(139,92,246,.4); }

.container { max-width: 1280px; width: 100%; margin: 0 auto; padding: 28px 24px; flex: 1; }

.section { display: none; flex-direction: column; gap: 20px; }
.section.active { display: flex; }

.header-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
.header-row h1 { font-size: 20px; font-weight: 800; letter-spacing: -.4px; }
.header-row p { color: var(--text-2); font-size: 13px; margin-top: 2px; }

/* Buttons */
.btn {
  background: var(--bg-2); border: 1px solid var(--line); color: var(--text-0);
  padding: 9px 16px; border-radius: 10px; font-size: 13px; font-weight: 700;
  display: inline-flex; align-items: center; gap: 8px; transition: .15s;
}
.btn:hover { background: var(--bg-3); border-color: var(--purple); }
.btn-primary { background: var(--grad-brand); border: none; color: #fff; box-shadow: 0 4px 14px rgba(124,58,237,.4); }
.btn-primary:hover { filter: brightness(1.1); transform: translateY(-1px); }
.btn-danger { background: rgba(248,113,113,.15); border-color: rgba(248,113,113,.3); color: var(--red); }
.btn-danger:hover { background: rgba(248,113,113,.25); }

/* Table */
.card { background: var(--bg-1); border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; }
table { width: 100%; border-collapse: collapse; text-align: left; }
th, td { padding: 14px 18px; border-bottom: 1px solid var(--line); }
th { background: var(--bg-2); color: var(--text-2); font-size: 11px; text-transform: uppercase; font-weight: 700; letter-spacing: .6px; }
td { color: var(--text-1); font-size: 13px; vertical-align: middle; }
tr:last-child td { border-bottom: none; }
tr:hover td { background: rgba(255,255,255,.015); }

.thumb-preview { width: 44px; height: 44px; border-radius: 8px; object-fit: cover; background: var(--bg-3); display: block; }
.badge { padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase; }
.badge-purple { background: rgba(139,92,246,.15); color: var(--purple); border: 1px solid rgba(139,92,246,.3); }
.badge-teal { background: rgba(45,212,191,.15); color: var(--teal); border: 1px solid rgba(45,212,191,.3); }

/* Analytics grid */
.stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; }
.stat-card { background: var(--bg-1); border: 1px solid var(--line); border-radius: var(--radius); padding: 18px; display: flex; flex-direction: column; gap: 6px; }
.stat-card .val { font-size: 26px; font-weight: 900; color: #fff; }
.stat-card .lbl { font-size: 12px; color: var(--text-2); font-weight: 600; text-transform: uppercase; }

/* Modal */
.modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,.75); backdrop-filter: blur(6px); display: none; align-items: center; justify-content: center; z-index: 1000; padding: 20px; }
.modal-overlay.active { display: flex; }
.modal { background: var(--bg-1); border: 1px solid var(--line); border-radius: 16px; max-width: 540px; width: 100%; padding: 24px; display: flex; flex-direction: column; gap: 16px; box-shadow: 0 20px 50px rgba(0,0,0,.8); }
.modal-title { font-size: 16px; font-weight: 800; display: flex; align-items: center; justify-content: space-between; }
.form-field { display: flex; flex-direction: column; gap: 6px; }
.form-field label { font-size: 11.5px; font-weight: 700; color: var(--text-2); text-transform: uppercase; }
.form-field input, .form-field select, .form-field textarea {
  background: var(--bg-2); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; color: #fff; font-size: 13px; outline: none;
}
.form-field input:focus, .form-field textarea:focus { border-color: var(--purple); }

.code-font { font-family: 'JetBrains Mono', monospace; font-size: 12px; }
</style>
</head>
<body>

<div class="topbar">
  <div class="brand">
    <div class="brand-icon"><i class="fa-solid fa-layer-group"></i></div>
    <span>NexusAI Studio <span style="color:var(--purple)">Admin</span></span>
  </div>
  <div class="nav-links">
    <button class="nav-btn active" onclick="showTab('styles')"><i class="fa-solid fa-palette"></i> Art Styles</button>
    <button class="nav-btn" onclick="showTab('prompts')"><i class="fa-solid fa-book-bookmark"></i> Prompt Library</button>
    <button class="nav-btn" onclick="showTab('builder')"><i class="fa-solid fa-wand-magic-sparkles"></i> Prompt Builder</button>
    <button class="nav-btn" onclick="showTab('keycodes')"><i class="fa-solid fa-key"></i> Keycodes</button>
    <button class="nav-btn" onclick="showTab('analytics')"><i class="fa-solid fa-chart-line"></i> Analytics & Logs</button>
  </div>
</div>

<div class="container">
  
  <!-- TAB 1: STYLES -->
  <div id="tab-styles" class="section active">
    <div class="header-row">
      <div>
        <h1>Art Style Management</h1>
        <p>Define presets, prompts, and thumbnail covers for studio users.</p>
      </div>
      <button class="btn btn-primary" onclick="openStyleModal()"><i class="fa-solid fa-plus"></i> Add New Style</button>
    </div>

    <div class="card">
      <table>
        <thead>
          <tr>
            <th>Thumb</th>
            <th>Style Name</th>
            <th>Category</th>
            <th>System Style Prompt</th>
            <th>Featured</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody id="stylesTableBody">
          <tr><td colspan="6" style="text-align:center;padding:40px;">Loading styles...</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  <!-- TAB 2: PROMPT LIBRARY -->
  <div id="tab-prompts" class="section">
    <div class="header-row">
      <div>
        <h1>Prompt Library</h1>
        <p>Curated master-class prompts for single-click injection in studio.</p>
      </div>
      <button class="btn btn-primary" onclick="openPromptModal()"><i class="fa-solid fa-plus"></i> Add Prompt Template</button>
    </div>

    <div class="card">
      <table>
        <thead>
          <tr>
            <th>Title</th>
            <th>Category</th>
            <th>Prompt Text</th>
            <th>Tags</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody id="promptsTableBody">
          <tr><td colspan="5" style="text-align:center;padding:40px;">Loading prompts...</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  <!-- TAB 3: PROMPT BUILDER PRESETS -->
  <div id="tab-builder" class="section">
    <div class="header-row">
      <div>
        <h1>Visual Prompt Builder Presets</h1>
        <p>Configure tags & parameters for Subject, Medium, Lighting, Camera, and Quality.</p>
      </div>
      <button class="btn btn-primary" onclick="openBuilderModal()"><i class="fa-solid fa-plus"></i> Add Builder Preset</button>
    </div>

    <div class="card">
      <table>
        <thead>
          <tr>
            <th>Category</th>
            <th>Preset Name</th>
            <th>Injected Value</th>
            <th>Icon</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody id="builderTableBody">
          <tr><td colspan="5" style="text-align:center;padding:40px;">Loading builder presets...</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  <!-- TAB 4: KEYCODES -->
  <div id="tab-keycodes" class="section">
    <div class="header-row">
      <div>
        <h1>Keycodes & Credits</h1>
        <p>Active keycodes, credit balances, and usage tracking.</p>
      </div>
    </div>

    <div class="card">
      <table>
        <thead>
          <tr>
            <th>Keycode</th>
            <th>Credit Limit</th>
            <th>Used Credits</th>
            <th>Remaining</th>
            <th>Status</th>
            <th>Last Active</th>
          </tr>
        </thead>
        <tbody id="keycodesTableBody">
          <tr><td colspan="6" style="text-align:center;padding:40px;">Loading keycodes...</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  <!-- TAB 5: ANALYTICS -->
  <div id="tab-analytics" class="section">
    <div class="header-row">
      <div>
        <h1>Analytics & API Logs</h1>
        <p>Real-time system stats, top art styles, and API call inspection.</p>
      </div>
    </div>

    <div class="stats-grid">
      <div class="stat-card">
        <div class="lbl">Total Generations Logged</div>
        <div class="val" id="statTotalCalls">0</div>
      </div>
      <div class="stat-card">
        <div class="lbl">Total Credits Consumed</div>
        <div class="val" id="statTotalCredits">0</div>
      </div>
      <div class="stat-card">
        <div class="lbl">Active Keycodes</div>
        <div class="val" id="statActiveKeys">0</div>
      </div>
      <div class="stat-card">
        <div class="lbl">Total Art Styles</div>
        <div class="val" id="statTotalStyles">0</div>
      </div>
    </div>

    <div class="header-row" style="margin-top:10px;">
      <h2>Recent API Call Logs</h2>
    </div>
    <div class="card">
      <table>
        <thead>
          <tr>
            <th>Time</th>
            <th>IP Address</th>
            <th>Action / Tool</th>
            <th>Keycode</th>
            <th>Status</th>
            <th>Cost</th>
          </tr>
        </thead>
        <tbody id="logsTableBody">
          <tr><td colspan="6" style="text-align:center;padding:40px;">Loading logs...</td></tr>
        </tbody>
      </table>
    </div>
  </div>

</div>

<!-- STYLE MODAL -->
<div class="modal-overlay" id="styleModal">
  <div class="modal">
    <div class="modal-title">
      <span id="styleModalTitle">Add Art Style</span>
      <button class="btn" style="padding:4px 8px;" onclick="closeModal('styleModal')"><i class="fa-solid fa-xmark"></i></button>
    </div>
    <input type="hidden" id="styleId">
    <div class="form-field">
      <label>Style Name</label>
      <input type="text" id="styleName" placeholder="e.g. Cyberpunk Neon">
    </div>
    <div class="form-field">
      <label>Category</label>
      <input type="text" id="styleCategory" placeholder="e.g. Medium-Based, Artistic, Digital">
    </div>
    <div class="form-field">
      <label>System Style Prompt</label>
      <textarea id="stylePrompt" rows="3" placeholder="e.g. cyberpunk style, vivid neon glow, dark futuristic environment"></textarea>
    </div>
    <div class="form-field">
      <label>Thumbnail Cover Image URL</label>
      <div style="display:flex;gap:8px;">
        <input type="text" id="styleImage" style="flex:1;" placeholder="https://...">
        <input type="file" id="styleImageFile" style="display:none;" onchange="uploadThumbnail(this)">
        <button class="btn" onclick="document.getElementById('styleImageFile').click()"><i class="fa-solid fa-upload"></i></button>
      </div>
    </div>
    <div style="display:flex;gap:12px;align-items:center;">
      <input type="checkbox" id="styleFeatured" checked>
      <label for="styleFeatured" style="font-size:13px;cursor:pointer;">Feature on main studio carousel</label>
    </div>
    <div style="display:flex;justify-content:flex-end;gap:10px;margin-top:10px;">
      <button class="btn" onclick="closeModal('styleModal')">Cancel</button>
      <button class="btn btn-primary" onclick="saveStyle()">Save Style</button>
    </div>
  </div>
</div>

<!-- PROMPT MODAL -->
<div class="modal-overlay" id="promptModal">
  <div class="modal">
    <div class="modal-title">
      <span id="promptModalTitle">Add Prompt Template</span>
      <button class="btn" style="padding:4px 8px;" onclick="closeModal('promptModal')"><i class="fa-solid fa-xmark"></i></button>
    </div>
    <input type="hidden" id="promptId">
    <div class="form-field">
      <label>Title</label>
      <input type="text" id="promptTitle" placeholder="e.g. Cybernetic Dragon Masterpiece">
    </div>
    <div class="form-field">
      <label>Category</label>
      <input type="text" id="promptCategory" placeholder="Fantasy, Portrait, Landscape">
    </div>
    <div class="form-field">
      <label>Prompt Text</label>
      <textarea id="promptText" rows="4" placeholder="Full prompt detailed string..."></textarea>
    </div>
    <div class="form-field">
      <label>Tags (comma separated)</label>
      <input type="text" id="promptTags" placeholder="dragon, cyberpunk, 8k, portrait">
    </div>
    <div style="display:flex;justify-content:flex-end;gap:10px;margin-top:10px;">
      <button class="btn" onclick="closeModal('promptModal')">Cancel</button>
      <button class="btn btn-primary" onclick="savePrompt()">Save Prompt</button>
    </div>
  </div>
</div>

<!-- BUILDER MODAL -->
<div class="modal-overlay" id="builderModal">
  <div class="modal">
    <div class="modal-title">
      <span>Add Builder Preset Option</span>
      <button class="btn" style="padding:4px 8px;" onclick="closeModal('builderModal')"><i class="fa-solid fa-xmark"></i></button>
    </div>
    <input type="hidden" id="builderId">
    <div class="form-field">
      <label>Category</label>
      <select id="builderCategory">
        <option value="Medium">Medium (Art Style / Rendering)</option>
        <option value="Lighting">Lighting & Atmosphere</option>
        <option value="Camera">Camera Angle & Framing</option>
        <option value="Quality">Quality Boosters</option>
      </select>
    </div>
    <div class="form-field">
      <label>Display Name</label>
      <input type="text" id="builderName" placeholder="e.g. Golden Hour">
    </div>
    <div class="form-field">
      <label>Injected Prompt Value</label>
      <textarea id="builderValue" rows="2" placeholder="e.g. golden hour sunlight, warm ambient glow"></textarea>
    </div>
    <div class="form-field">
      <label>FontAwesome Icon Class</label>
      <input type="text" id="builderIcon" value="fa-wand-magic-sparkles" placeholder="fa-sun">
    </div>
    <div style="display:flex;justify-content:flex-end;gap:10px;margin-top:10px;">
      <button class="btn" onclick="closeModal('builderModal')">Cancel</button>
      <button class="btn btn-primary" onclick="saveBuilderPreset()">Save Preset</button>
    </div>
  </div>
</div>

<script>
const API = './api.php';

function showTab(name) {
  document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
  document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
  
  event.currentTarget.classList.add('active');
  document.getElementById('tab-' + name).classList.add('active');

  if (name === 'styles') loadStyles();
  if (name === 'prompts') loadPrompts();
  if (name === 'builder') loadBuilderPresets();
  if (name === 'keycodes') loadKeycodes();
  if (name === 'analytics') loadAnalytics();
}

function openModal(id) { document.getElementById(id).classList.add('active'); }
function closeModal(id) { document.getElementById(id).classList.remove('active'); }

// Load Styles
async function loadStyles() {
  try {
    const res = await fetch(API + '?action=get_styles');
    const data = await res.json();
    document.getElementById('statTotalStyles').textContent = data.length || 0;

    const tbody = document.getElementById('stylesTableBody');
    if (!data.length) {
      tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:30px;">No styles found. Add one above!</td></tr>';
      return;
    }
    tbody.innerHTML = data.map(s => `
      <tr>
        <td><img src="${s.image || 'https://via.placeholder.com/44'}" class="thumb-preview"></td>
        <td><b>${escapeHtml(s.name)}</b></td>
        <td><span class="badge badge-purple">${escapeHtml(s.category || 'General')}</span></td>
        <td class="code-font" style="max-width:300px;word-break:break-word;">${escapeHtml(s.prompt)}</td>
        <td>${s.is_featured ? '<span class="badge badge-teal">Yes</span>' : '<span style="color:var(--text-2)">No</span>'}</td>
        <td>
          <button class="btn" style="padding:4px 8px;" onclick="editStyle('${s.id}')"><i class="fa-solid fa-pen"></i></button>
          <button class="btn btn-danger" style="padding:4px 8px;" onclick="deleteStyle('${s.id}')"><i class="fa-solid fa-trash"></i></button>
        </td>
      </tr>
    `).join('');
    window._cacheStyles = data;
  } catch(e) {
    console.error(e);
  }
}

function openStyleModal() {
  document.getElementById('styleId').value = '';
  document.getElementById('styleName').value = '';
  document.getElementById('styleCategory').value = 'General';
  document.getElementById('stylePrompt').value = '';
  document.getElementById('styleImage').value = '';
  document.getElementById('styleModalTitle').textContent = 'Add Art Style';
  openModal('styleModal');
}

function editStyle(id) {
  const s = (window._cacheStyles || []).find(x => x.id === id);
  if (!s) return;
  document.getElementById('styleId').value = s.id;
  document.getElementById('styleName').value = s.name;
  document.getElementById('styleCategory').value = s.category || 'General';
  document.getElementById('stylePrompt').value = s.prompt;
  document.getElementById('styleImage').value = s.image || '';
  document.getElementById('styleFeatured').checked = !!s.is_featured;
  document.getElementById('styleModalTitle').textContent = 'Edit Art Style';
  openModal('styleModal');
}

async function saveStyle() {
  const payload = {
    action: 'save_style',
    id: document.getElementById('styleId').value,
    name: document.getElementById('styleName').value,
    category: document.getElementById('styleCategory').value,
    prompt: document.getElementById('stylePrompt').value,
    image: document.getElementById('styleImage').value,
    is_featured: document.getElementById('styleFeatured').checked ? 1 : 0
  };
  await fetch(API, { method: 'POST', body: JSON.stringify(payload) });
  closeModal('styleModal');
  loadStyles();
}

async function deleteStyle(id) {
  if (!confirm('Are you sure you want to delete this style?')) return;
  await fetch(API, { method: 'POST', body: JSON.stringify({ action: 'delete_style', id }) });
  loadStyles();
}

async function uploadThumbnail(input) {
  if (!input.files[0]) return;
  const fd = new FormData();
  fd.append('action', 'upload_image');
  fd.append('image', input.files[0]);
  const res = await fetch(API, { method: 'POST', body: fd });
  const data = await res.json();
  if (data.url) document.getElementById('styleImage').value = data.url;
}

// Load Prompts
async function loadPrompts() {
  const res = await fetch(API + '?action=get_prompts');
  const data = await res.json();
  const tbody = document.getElementById('promptsTableBody');
  if (!data.length) {
    tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;padding:30px;">No prompt templates found.</td></tr>';
    return;
  }
  tbody.innerHTML = data.map(p => `
    <tr>
      <td><b>${escapeHtml(p.title)}</b></td>
      <td><span class="badge badge-purple">${escapeHtml(p.category || 'General')}</span></td>
      <td class="code-font" style="max-width:350px;">${escapeHtml(p.prompt)}</td>
      <td>${escapeHtml(p.tags || '-')}</td>
      <td>
        <button class="btn btn-danger" style="padding:4px 8px;" onclick="deletePrompt('${p.id}')"><i class="fa-solid fa-trash"></i></button>
      </td>
    </tr>
  `).join('');
}

function openPromptModal() { openModal('promptModal'); }

async function savePrompt() {
  const payload = {
    action: 'save_prompt',
    title: document.getElementById('promptTitle').value,
    category: document.getElementById('promptCategory').value,
    prompt: document.getElementById('promptText').value,
    tags: document.getElementById('promptTags').value
  };
  await fetch(API, { method: 'POST', body: JSON.stringify(payload) });
  closeModal('promptModal');
  loadPrompts();
}

async function deletePrompt(id) {
  if (!confirm('Delete prompt template?')) return;
  await fetch(API, { method: 'POST', body: JSON.stringify({ action: 'delete_prompt', id }) });
  loadPrompts();
}

// Load Builder Presets
async function loadBuilderPresets() {
  const res = await fetch(API + '?action=get_builder_presets');
  const data = await res.json();
  const tbody = document.getElementById('builderTableBody');
  tbody.innerHTML = data.map(b => `
    <tr>
      <td><span class="badge badge-purple">${escapeHtml(b.category)}</span></td>
      <td><b>${escapeHtml(b.name)}</b></td>
      <td class="code-font">${escapeHtml(b.value)}</td>
      <td><i class="fa-solid ${escapeHtml(b.icon || 'fa-tag')}"></i></td>
      <td>
        <button class="btn btn-danger" style="padding:4px 8px;" onclick="deleteBuilderPreset('${b.id}')"><i class="fa-solid fa-trash"></i></button>
      </td>
    </tr>
  `).join('');
}

function openBuilderModal() { openModal('builderModal'); }

async function saveBuilderPreset() {
  const payload = {
    action: 'save_builder_preset',
    category: document.getElementById('builderCategory').value,
    name: document.getElementById('builderName').value,
    value: document.getElementById('builderValue').value,
    icon: document.getElementById('builderIcon').value
  };
  await fetch(API, { method: 'POST', body: JSON.stringify(payload) });
  closeModal('builderModal');
  loadBuilderPresets();
}

async function deleteBuilderPreset(id) {
  if (!confirm('Delete builder preset?')) return;
  await fetch(API, { method: 'POST', body: JSON.stringify({ action: 'delete_builder_preset', id }) });
  loadBuilderPresets();
}

// Load Analytics & Keycodes
async function loadAnalytics() {
  const res = await fetch(API + '?action=get_analytics');
  const data = await res.json();
  
  document.getElementById('statTotalCalls').textContent = data.logs ? data.logs.length : 0;
  const totalCost = (data.logs || []).reduce((sum, l) => sum + (parseInt(l.credits_cost)||0), 0);
  document.getElementById('statTotalCredits').textContent = totalCost;

  const logsTbody = document.getElementById('logsTableBody');
  logsTbody.innerHTML = (data.logs || []).slice(0, 50).map(l => `
    <tr>
      <td class="code-font">${new Date(l.timestamp * 1000).toLocaleString()}</td>
      <td class="code-font">${escapeHtml(l.ip)}</td>
      <td><b>${escapeHtml(l.tool)}</b></td>
      <td class="code-font">${l.keycode ? '•••• ' + l.keycode.slice(-4) : '-'}</td>
      <td><span class="badge ${l.status_code === 200 ? 'badge-teal' : 'badge-purple'}">${l.status_code}</span></td>
      <td><b>${l.credits_cost}</b></td>
    </tr>
  `).join('') || '<tr><td colspan="6" style="text-align:center;">No logs recorded yet.</td></tr>';
}

async function loadKeycodes() {
  const res = await fetch(API + '?action=get_analytics');
  const data = await res.json();
  document.getElementById('statActiveKeys').textContent = (data.keycodes || []).length;
  
  const tbody = document.getElementById('keycodesTableBody');
  tbody.innerHTML = (data.keycodes || []).map(k => `
    <tr>
      <td class="code-font"><b>${escapeHtml(k.keycode)}</b></td>
      <td>${k.credit_limit}</td>
      <td>${k.used_credits}</td>
      <td><b>${k.credit_limit - k.used_credits}</b></td>
      <td><span class="badge badge-teal">${k.status}</span></td>
      <td class="code-font">${k.last_active ? new Date(k.last_active * 1000).toLocaleTimeString() : '-'}</td>
    </tr>
  `).join('') || '<tr><td colspan="6" style="text-align:center;">No keycode usage logged yet.</td></tr>';
}

function escapeHtml(str) {
  if (!str) return '';
  return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

// Initial load
loadStyles();
</script>
</body>
</html>
