<% layout = 'layouts/main' %>
<% title = project ? 'Test Data - ' + project.name : 'Test Data Management' %>

<div class="page-header">
  <h1>Test Data & Artifacts</h1>
  <div class="header-actions">
    <% if (typeof projects !== 'undefined' && projects.length > 1) { %>
    <select id="project-select" class="form-input" style="width:auto;" onchange="window.location='/data?project='+this.value">
      <% projects.forEach(p => { %>
      <option value="<%= p.id %>" <%= project && project.id === p.id ? 'selected' : '' %>><%= p.name %></option>
      <% }) %>
    </select>
    <% } %>
    <% if (project) { %>
    <a href="/projects/<%= project.id %>" class="btn">Back</a>
    <% } %>
  </div>
</div>

<% if (project) { %>
<!-- ─── Test Specs ─── -->
<% if (testSpecs && testSpecs.length > 0) { %>
<div class="card card-lavender">
  <h3>🧪 Test Spec Files <span class="badge badge-project" style="margin-left:0.5rem;"><%= testSpecs.length %></span></h3>
  <% testSpecs.forEach(spec => { %>
  <details style="margin-bottom:0.75rem;border:1px solid var(--border);border-radius:var(--radius-md);padding:0.75rem;">
    <summary style="cursor:pointer;font-weight:600;font-family:var(--font-mono);font-size:0.9rem;">
      <%= spec.name %>
      <a href="/data/spec/<%= spec.name %>?project=<%= project.id %>" class="btn btn-sm" style="margin-left:0.5rem;" download>📥 Download</a>
      <a href="/stories?project=<%= project.id %>" class="btn btn-sm">▶ Execute</a>
    </summary>
    <pre class="code-block" style="margin-top:0.75rem;max-height:400px;font-size:0.75rem;"><%= spec.content %></pre>
  </details>
  <% }) %>
</div>
<% } else { %>
<div class="card">
  <h3>🧪 Test Spec Files</h3>
  <p style="color:var(--text-muted);">Aucun fichier de test trouvé. Générez des tests depuis la page <a href="/stories?project=<%= project.id %>">Stories</a>.</p>
</div>
<% } %>

<!-- ─── Test Plans ─── -->
<% if (testPlans && testPlans.length > 0) { %>
<div class="card card-peach">
  <h3>📋 Test Plan Files <span class="badge badge-project" style="margin-left:0.5rem;"><%= testPlans.length %></span></h3>
  <% testPlans.forEach(plan => { %>
  <details style="margin-bottom:0.75rem;border:1px solid var(--border);border-radius:var(--radius-md);padding:0.75rem;">
    <summary style="cursor:pointer;font-weight:600;font-family:var(--font-mono);font-size:0.9rem;">
      <%= plan.name %>
      <a href="/data/plan/<%= plan.name %>?project=<%= project.id %>" class="btn btn-sm" style="margin-left:0.5rem;" download>📥 Download</a>
    </summary>
    <div class="markdown-content" style="margin-top:0.75rem;font-size:0.85rem;" data-md="<%= encodeURIComponent(plan.content) %>"></div>
  </details>
  <% }) %>
</div>
<% } %>
<% } %>

<!-- ─── Generate Test Data ─── -->
<div class="row" style="margin-bottom:2rem;">
  <div class="col col-40">
    <div class="card card-cream">
      <h3>⚡ Generate Test Data</h3>
      <p style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 1.25rem;">
        Auto-generate synthetic mock datasets for your QA pipeline.
      </p>
      <form id="data-form" class="form">
        <div class="form-group">
          <label>Data Type</label>
          <select id="data-type" class="form-input">
            <option value="users">Users Accounts</option>
            <option value="transactions">Transactions Logs</option>
          </select>
        </div>
        <div class="form-group">
          <label>Record Count</label>
          <input type="number" id="data-count" class="form-input" value="5" min="1" max="100">
        </div>
        <button type="submit" class="btn btn-primary" style="width:100%;margin-top:0.5rem;">Generate Dataset</button>
      </form>
      <div id="data-output" class="output-box" style="display:none;margin-top:1rem;"></div>
    </div>
  </div>
  <div class="col col-60">
    <div class="card">
      <h3>📂 Generated Data Files</h3>
      <% if (dataFiles.length === 0) { %>
      <div class="empty-state" style="padding:2rem 0;">
        <p>No data files generated yet</p>
      </div>
      <% } else { %>
      <table class="info-table">
        <tr><th>File Name</th><th>Size</th><th>Last Modified</th><th>Action</th></tr>
        <% dataFiles.sort((a,b) => new Date(b.modified) - new Date(a.modified)).forEach(f => { %>
        <tr>
          <td><code style="font-family:var(--font-mono);font-size:0.8rem;"><%= f.name %></code></td>
          <td><%= f.size > 1024 ? (f.size / 1024).toFixed(1) + ' KB' : f.size + ' B' %></td>
          <td><%= new Date(f.modified).toLocaleString() %></td>
          <td><button class="btn btn-sm btn-danger" onclick="deleteFile('<%= f.name %>')">Delete</button></td>
        </tr>
        <% }) %>
      </table>
      <% } %>
    </div>
  </div>
</div>

<div class="card">
  <h3>ℹ️ About Test Data</h3>
  <p style="color: var(--text-muted); font-size: 0.88rem; line-height:1.5;">
    Test spec files (<code>.spec.ts</code>) and plans (<code>.md</code>) are read directly from your project. 
    Generated datasets are stored in <code>qa-dashboard/data/</code> as JSON files.
  </p>
</div>

<script>
document.getElementById('data-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  const type = document.getElementById('data-type').value;
  const count = document.getElementById('data-count').value;
  const output = document.getElementById('data-output');
  output.style.display = 'block';
  output.textContent = 'Generating...';
  output.className = 'output-box output-running';
  const res = await fetch('/data/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type, count }) });
  const data = await res.json();
  if (data.success) {
    output.textContent = `Generated ${data.count} records → ${data.file}`;
    output.className = 'output-box output-success';
    setTimeout(() => location.reload(), 1500);
  } else {
    output.textContent = 'Error: ' + data.error;
    output.className = 'output-box output-error';
  }
});

async function deleteFile(name) {
  if (!confirm(`Delete ${name}?`)) return;
  const res = await fetch('/data/' + encodeURIComponent(name), { method: 'DELETE' });
  const data = await res.json();
  if (data.success) location.reload();
  else alert('Delete failed');
}

// Render markdown for plans
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('[data-md]').forEach(el => {
    if (typeof marked !== 'undefined') {
      el.innerHTML = marked.parse(decodeURIComponent(el.dataset.md));
    }
  });
});
</script>