<% layout = 'layouts/main' %>
<% title = 'User Stories' %>

<div class="page-header">
  <h1>User Stories</h1>
  <span class="badge badge-project"><%= project.name %></span>
</div>

<% if (stories.length === 0) { %>
<div class="empty-state">
  <div style="font-size: 3rem; margin-bottom: 1rem;">📝</div>
  <h3>Aucune User Story</h3>
  <p>Ajoutez des fichiers Markdown <code>.md</code> dans le dossier <code>user-story/</code> de votre projet pour commencer.</p>
</div>
<% } else { %>
<div class="story-list">
  <% const cardColors = ['card-lavender', 'card-peach', 'card-cream']; %>
  <% stories.forEach((s, idx) => { %>
  <div class="story-card <%= cardColors[idx % cardColors.length] %>" style="margin-bottom:1.25rem;">
    <div class="story-header">
      <a href="/stories/<%= s.name %>?project=<%= project.id %>" class="story-title" style="text-decoration:none;font-weight:600;"><%= s.name.replace('.md', '') %></a>
      <div class="story-badges">
        <% if (s.hasPlan && s.hasSpec) { %><span class="badge badge-spec">✅ Planned & Tested</span>
        <% } else if (s.hasPlan) { %><span class="badge badge-plan">📋 Planned</span>
        <% } else { %><span class="badge badge-draft">📝 Draft</span><% } %>
      </div>
    </div>
    <div class="story-preview" style="margin:1rem 0;">
      <% if (s.content) { %>
      <% const lines = s.content.split('\n').filter(l => l.startsWith('##') || l.startsWith('**') || l.startsWith('-') || l.trim().length > 0) %>
      <% lines.slice(0, 3).forEach(l => { %>
        <p style="margin:0.25rem 0;font-size:0.9rem;opacity:0.85;"><%= l.replace(/\*\*|##/g, '').substring(0, 100) %></p>
      <% }) %>
      <% } %>
    </div>
    <div class="story-actions" style="border-top:1px solid var(--border);padding-top:1rem;">
      <div style="display:flex;align-items:center;gap:0.5rem;flex-wrap:wrap;">
        <button class="btn btn-sm" onclick="callPipelineAction('<%= project.id %>', '<%= s.name %>', 'plan')" <%= s.hasPlan ? 'disabled style="opacity:0.5;"' : '' %>>📋 Plan</button>
        <button class="btn btn-sm" onclick="callPipelineAction('<%= project.id %>', '<%= s.name %>', 'generate')" <%= !s.hasPlan || s.hasSpec ? 'disabled style="opacity:0.5;"' : '' %>>🧪 Generate</button>
        <button class="btn btn-sm btn-primary" onclick="callPipelineAction('<%= 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 Details →</a>
      </div>
      <div class="story-action-output" style="margin-top:0.5rem;"></div>
    </div>
  </div>
  <% }) %>
</div>
<% } %>

<script>
async function callPipelineAction(projectId, storyName, action) {
  const card = event.target.closest('.story-card');
  const outputDiv = card.querySelector('.story-action-output');
  outputDiv.innerHTML = `<div class="output-box output-running" style="margin-top:0.5rem;padding:0.75rem;font-size:0.8rem;max-height:200px;">🚀 Running ${action}...</div>`;

  try {
    const res = await fetch(`/stories/${encodeURIComponent(storyName)}/${action}?project=${projectId}`, { method: 'POST' });
    if (!res.body) { outputDiv.innerHTML = '<div class="output-box output-error" style="margin-top:0.5rem;padding:0.75rem;font-size:0.8rem;">Error: No stream</div>'; return; }
    const reader = res.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let text = '';
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      text += decoder.decode(value, { stream: true });
      outputDiv.innerHTML = `<div class="output-box output-running" style="margin-top:0.5rem;padding:0.75rem;font-size:0.8rem;max-height:200px;overflow-y:auto;">${text.replace(/\n/g, '<br>')}</div>`;
    }
    const isSuccess = text.toLowerCase().includes('finished: success');
    outputDiv.innerHTML = `<div class="output-box ${isSuccess ? 'output-success' : 'output-error'}" style="margin-top:0.5rem;padding:0.75rem;font-size:0.8rem;max-height:200px;overflow-y:auto;">${text.replace(/\n/g, '<br>')}</div>`;
    if (isSuccess) setTimeout(() => location.reload(), 2000);
  } catch (err) {
    outputDiv.innerHTML = `<div class="output-box output-error" style="margin-top:0.5rem;padding:0.75rem;font-size:0.8rem;">Error: ${err.message}</div>`;
  }
}
</script>