<% layout = 'layouts/main' %>
<% title = project.name %>

<div class="page-header">
  <h1><%= project.name %></h1>
  <div class="header-actions">
    <a href="/stories?project=<%= project.id %>" class="btn">Stories</a>
    <a href="/runs?project=<%= project.id %>" class="btn">Runs</a>
    <a href="/analytics?project=<%= project.id %>" class="btn">Analytics</a>
    <a href="/data?project=<%= project.id %>" class="btn">Test Data</a>
  </div>
</div>

<div style="margin-bottom:2rem;">
  <p style="font-family:var(--font-mono);color:var(--text-disabled);font-size:0.88rem;"><%= project.path %></p>
</div>

<div class="row" style="margin-bottom:2rem;">
  <div class="col">
    <div class="card card-lavender">
      <h3>📝 User Stories</h3>
      <div class="big-number"><%= list.stories.length %></div>
    </div>
  </div>
  <div class="col">
    <div class="card card-peach">
      <h3>📋 Test Plans</h3>
      <div class="big-number"><%= list.plans.length %></div>
    </div>
  </div>
  <div class="col">
    <div class="card card-ochre">
      <h3>🧪 Test Specs</h3>
      <div class="big-number"><%= list.specs.length %></div>
    </div>
  </div>
</div>

<!-- ─── Liste des Stories avec Pipeline Status ─── -->
<div class="card">
  <h3>📋 Stories Pipeline</h3>
  <% if (storiesWithStatus && storiesWithStatus.length > 0) { %>
  <table class="info-table">
    <thead>
      <tr>
        <th>User Story</th>
        <th>Plan</th>
        <th>Test</th>
        <th>Run</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <% storiesWithStatus.forEach(s => { %>
      <tr>
        <td><a href="/stories/<%= s.name %>?project=<%= project.id %>" style="font-weight:600;"><%= s.baseName %></a></td>
        <td><% if (s.hasPlan) { %><span class="badge badge-plan">✅</span><% } else { %><span class="badge badge-draft">—</span><% } %></td>
        <td><% if (s.hasSpec) { %><span class="badge badge-spec">✅</span><% } else { %><span class="badge badge-draft">—</span><% } %></td>
        <td><% if (s.hasRun) { %><span class="badge badge-pass">✅</span><% } else { %><span class="badge badge-draft">—</span><% } %></td>
        <td>
          <div style="display:flex;gap:0.4rem;flex-wrap:wrap;">
            <button class="btn btn-sm" onclick="runPipelineAction('<%= project.id %>', '<%= s.name %>', 'plan')" <%= s.hasPlan ? 'disabled style="opacity:0.5;"' : '' %>>📋 Plan</button>
            <button class="btn btn-sm" onclick="runPipelineAction('<%= project.id %>', '<%= s.name %>', 'generate')" <%= !s.hasPlan || s.hasSpec ? 'disabled style="opacity:0.5;"' : '' %>>🧪 Generate</button>
            <button class="btn btn-sm btn-primary" onclick="runPipelineAction('<%= project.id %>', '<%= s.name %>', 'execute')" <%= !s.hasSpec ? 'disabled style="opacity:0.5;"' : '' %>>▶ Execute</button>
            <a href="/stories/<%= s.name %>?project=<%= project.id %>" class="btn btn-sm">View →</a>
          </div>
        </td>
      </tr>
      <% }) %>
    </tbody>
  </table>
  <% } else { %>
    <p style="color:var(--text-muted);">Aucune user story trouvée. Ajoutez des fichiers <code>.md</code> dans <code>user-story/</code>.</p>
  <% } %>
  <div id="pipeline-stream-output" class="output-box" style="display:none;margin-top:1rem;"></div>
  <div id="pipeline-stream-pulse" class="terminal-pulse" style="display:none;margin-top:0.75rem;">
    <span class="pulse-dot"></span><span class="pulse-dot"></span><span class="pulse-dot"></span>
    <span class="pulse-text">Running...</span>
  </div>
</div>

<!-- ─── Quick Actions ─── -->
<div class="card">
  <h3>⚡ Orchestrator Actions</h3>
  <div class="action-buttons" style="margin-bottom:1rem;">
    <button class="btn btn-sm" onclick="runQuickAction('<%= project.id %>', 'status')">📊 Status</button>
    <button class="btn btn-sm btn-primary" onclick="runQuickAction('<%= project.id %>', 'report')">📝 Generate Report</button>
    <% if (hasAllure) { %>
    <a href="/allure-report?project=<%= project.id %>" class="btn btn-sm" target="_blank">📈 Allure Report</a>
    <% } %>
    <a href="/export/report/latest?project=<%= project.id %>" class="btn btn-sm" target="_blank">📥 Download Latest Report</a>
  </div>
  <div id="quick-output" class="output-box" style="display:none;"></div>
</div>

<script>
async function runPipelineAction(projectId, storyName, action) {
  const output = document.getElementById('pipeline-stream-output');
  const pulse = document.getElementById('pipeline-stream-pulse');
  output.style.display = 'block';
  output.textContent = `🚀 Running ${action} for ${storyName}...\n`;
  output.className = 'output-box output-running';
  pulse.style.display = 'flex';

  try {
    const res = await fetch(`/stories/${encodeURIComponent(storyName)}/${action}?project=${projectId}`, { method: 'POST' });
    if (!res.body) { output.textContent += '\nError: No response stream'; pulse.style.display = 'none'; return; }
    const reader = res.body.getReader();
    const decoder = new TextDecoder('utf-8');
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      output.textContent += decoder.decode(value, { stream: true });
      output.scrollTop = output.scrollHeight;
    }
    pulse.style.display = 'none';
    output.className = output.textContent.toLowerCase().includes('finished: success') ? 'output-box output-success' : 'output-box output-error';
    if (output.textContent.toLowerCase().includes('finished: success')) {
      setTimeout(() => location.reload(), 2000);
    }
  } catch (err) {
    output.textContent += `\nError: ${err.message}`;
    output.className = 'output-box output-error';
    pulse.style.display = 'none';
  }
}

async function runQuickAction(projectId, action) {
  const output = document.getElementById('quick-output');
  output.style.display = 'block';
  output.textContent = `Running ${action}...`;
  output.className = 'output-box output-running';
  try {
    const res = await fetch(`/projects/${projectId}/${action}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
    if (!res.ok) throw new Error(`HTTP Error ${res.status}`);
    const data = await res.json();
    output.textContent = data.output || data.error || 'Done';
    output.className = `output-box ${data.success ? 'output-success' : 'output-error'}`;
  } catch (err) {
    output.textContent = 'Error: ' + err.message;
    output.className = 'output-box output-error';
  }
}
</script>