<% layout = 'layouts/main' %>
<% title = 'Run: ' + (typeof run !== 'undefined' && run && run.id ? run.id.substring(0, 16) : 'Details') %>

<div class="page-header">
  <h1>Run Details</h1>
  <div class="header-actions">
    <% if (typeof run !== 'undefined' && run && run.result) { %>
      <span class="badge <%= run.result.success ? 'badge-pass' : 'badge-fail' %>" style="font-size:0.85rem;padding:0.4rem 1rem;">
        <%= run.result.success ? '✅ PASSED' : (run.result.success === null ? '⏳ RUNNING' : '❌ FAILED') %>
      </span>
    <% } %>
    <a href="/runs?project=<%= (typeof project !== 'undefined' && project) ? project.id : '' %>" class="btn btn-sm">← Back to Runs</a>
  </div>
</div>

<% if (typeof run === 'undefined' || !run || !run.result) { %>
<div class="empty-state">
  <p>Aucun résultat d'exécution trouvé pour ce run.</p>
  <a href="/runs?project=<%= (typeof project !== 'undefined' && project) ? project.id : '' %>" class="btn btn-primary" style="margin-top:0.5rem;">Retour aux runs</a>
</div>
<% } else { %>

<div class="row">
  <!-- Left Side: Summary & Actions -->
  <div class="col col-30">
    <div class="card card-cream">
      <h3>📊 Run Summary</h3>
      <table class="info-table">
        <tr>
          <td>Status</td>
          <td><strong><%= run.result.success ? 'Passed' : (run.result.success === null ? 'In Progress' : 'Failed') %></strong></td>
        </tr>
        <tr>
          <td>Duration</td>
          <td><strong><%= run.result.duration ? (run.result.duration / 1000).toFixed(1) + 's' : 'N/A' %></strong></td>
        </tr>
        <tr>
          <td>Test Suite</td>
          <td><code style="font-family:var(--font-mono);font-size:0.78rem;"><%= run.result.test || 'All' %></code></td>
        </tr>
        <tr>
          <td>Timestamp</td>
          <td><%= run.result.timestamp ? new Date(run.result.timestamp).toLocaleString() : 'N/A' %></td>
        </tr>
        <tr>
          <td>Failures</td>
          <td>
            <span style="font-weight:600;color:<%= run.result.failedTests && run.result.failedTests.length > 0 ? 'var(--danger)' : 'var(--success)' %>">
              <%= run.result.failedTests ? run.result.failedTests.length : 0 %>
            </span>
          </td>
        </tr>
      </table>
    </div>

    <div class="card">
      <h3>📂 Report Actions</h3>
      <div class="action-buttons-vertical">
        <button class="btn btn-sm btn-primary" onclick="rerunRun('<%= project.id %>', '<%= run.id %>')" style="margin-bottom:0.5rem;">🔄 Rerun This Test</button>
        <% if (run.report) { %>
          <a href="/export/report/<%= run.id %>?project=<%= project.id %>" class="btn btn-sm" target="_blank">📥 Export HTML Report</a>
          <a href="/export/pdf/<%= run.id %>?project=<%= project.id %>" class="btn btn-sm">📥 Download Raw (.txt)</a>
        <% } else { %>
          <p style="color:var(--text-disabled);font-size:0.85rem;margin-bottom:0.5rem;">No summary report generated yet.</p>
        <% } %>
        <button class="btn btn-sm" onclick="generateReport('<%= project.id %>', '<%= run.id %>')" style="margin-top:0.25rem;">📝 Generate Report</button>
        <% if (run.hasAllure) { %>
          <a href="/allure-report?project=<%= project.id %>" class="btn btn-sm" target="_blank" style="background-color:var(--brand-ochre);color:var(--text);border-color:var(--border-strong);margin-top:0.5rem;">📈 Open Allure Report ↗</a>
          <button class="btn btn-sm" onclick="regenerateAllure('<%= project.id %>')" style="margin-top:0.25rem;">🔄 Regenerate Allure</button>
        <% } else { %>
          <button class="btn btn-sm" onclick="regenerateAllure('<%= project.id %>')" style="margin-top:0.25rem;">📈 Generate Allure Report</button>
        <% } %>
      </div>
    </div>

    <% if (run.healing) { %>
    <div class="card card-lavender">
      <h3>🛠️ Self-Healing Status</h3>
      <table class="info-table" style="margin-bottom:1rem;">
        <tr>
          <td>Attempts</td>
          <td><strong><%= run.healing.healingAttempts ? run.healing.healingAttempts.length : 0 %></strong></td>
        </tr>
        <tr>
          <td>Healed</td>
          <td><strong><%= run.healing.totalHealed || 0 %></strong></td>
        </tr>
        <tr>
          <td>Remaining</td>
          <td><strong><%= run.healing.totalRemaining || 0 %></strong></td>
        </tr>
      </table>
      
      <% if (run.healing.healingAttempts && run.healing.healingAttempts.length > 0) { %>
        <h4 style="font-size:0.9rem;margin-top:1rem;margin-bottom:0.5rem;font-weight:600;">Healing Log</h4>
        <% run.healing.healingAttempts.forEach(a => { %>
          <div class="heal-attempt" style="margin-bottom:0.5rem;font-size:0.85rem;">
            <strong>Attempt <%= a.attempt %></strong>: <%= a.healed ? a.healed.length : 0 %> auto-fixed, <%= a.stillFailing ? a.stillFailing.length : 0 %> failing.
          </div>
        <% }) %>
      <% } %>
    </div>
    <% } %>
  </div>

  <!-- Right Side: Failures, Reports, Output -->
  <div class="col col-70">
    <% if (run.result.failedTests && run.result.failedTests.length > 0) { %>
    <div class="card card-peach">
      <h3>❌ Failed Tests & Traces</h3>
      <ul class="fail-list" style="padding-left:1.25rem;">
        <% run.result.failedTests.forEach(ft => { %>
          <li style="margin-bottom:1rem;">
            <strong style="font-family:var(--font-mono);font-size:0.9rem;color:var(--danger);"><%= ft.test || ft.file || 'Test failure' %></strong>
            <% if (ft.error) { %>
              <pre style="margin-top:0.5rem;background:rgba(255,255,255,0.4);border:1px solid rgba(0,0,0,0.1);padding:0.75rem;border-radius:var(--radius-sm);font-family:var(--font-mono);font-size:0.78rem;overflow-x:auto;white-space:pre-wrap;color:var(--text);"><%= ft.error %></pre>
            <% } %>
          </li>
        <% }) %>
      </ul>
    </div>
    <% } %>

    <% if (run.report) { %>
    <div class="card">
      <h3>📝 Test Execution Report</h3>
      <div id="run-report-md" style="display:none;"><%= run.report %></div>
      <div class="markdown-content" id="run-report-rendered"></div>
    </div>
    <% } %>

    <div class="card">
      <h3>💻 Raw Execution Console Output</h3>
      <pre class="code-block" style="font-size:0.78rem;max-height:400px;overflow-y:auto;"><%= run.result.output || 'No console output captured.' %></pre>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
  const reportRaw = document.getElementById('run-report-md');
  const reportRendered = document.getElementById('run-report-rendered');
  if (reportRaw && reportRendered && typeof marked !== 'undefined') {
    reportRendered.innerHTML = marked.parse(reportRaw.textContent || '');
  }
});

async function rerunRun(projectId, runId) {
  if (!confirm('Rerun this test?')) return;
  const output = document.querySelector('.output-box') || document.createElement('div');
  output.textContent = '🔄 Rerunning...';
  output.className = 'output-box output-running';
  output.style.display = 'block';
  try {
    const res = await fetch(`/runs/${runId}/rerun?project=${projectId}`, { method: 'POST' });
    const data = await res.json();
    output.textContent = data.output || data.error || 'Done';
    output.className = `output-box ${data.success ? 'output-success' : 'output-error'}`;
    if (data.success && data.runId) {
      output.textContent += `\n\nNew run: ${data.runId}`;
      setTimeout(() => { window.location.href = `/runs/${data.runId}?project=${projectId}`; }, 2000);
    }
  } catch (err) {
    output.textContent = 'Error: ' + err.message;
    output.className = 'output-box output-error';
  }
}

async function generateReport(projectId, runId) {
  const output = document.querySelector('.output-box') || document.createElement('div');
  output.textContent = '📝 Generating report...';
  output.className = 'output-box output-running';
  output.style.display = 'block';
  try {
    const res = await fetch(`/projects/${projectId}/report`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ runId }) });
    const data = await res.json();
    output.textContent = data.output || data.error || 'Done';
    output.className = `output-box ${data.success ? 'output-success' : 'output-error'}`;
    if (data.success) setTimeout(() => location.reload(), 1500);
  } catch (err) {
    output.textContent = 'Error: ' + err.message;
    output.className = 'output-box output-error';
  }
}

async function regenerateAllure(projectId) {
  const output = document.querySelector('.output-box') || document.createElement('div');
  output.textContent = '📈 Regenerating Allure report...';
  output.className = 'output-box output-running';
  output.style.display = 'block';
  try {
    const res = await fetch(`/runs/allure-regenerate?project=${projectId}`, { method: 'POST' });
    const data = await res.json();
    output.textContent = data.output || data.error || 'Done';
    output.className = `output-box ${data.success ? 'output-success' : 'output-error'}`;
    if (data.success) setTimeout(() => location.reload(), 1500);
  } catch (err) {
    output.textContent = 'Error: ' + err.message;
    output.className = 'output-box output-error';
  }
}
</script>

<% } %>