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

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

<div class="row">
  <div class="col col-40">
    <div class="card card-cream">
      <h3>📝 User Story</h3>
      <div id="story-content-md" style="display:none;"><%= story.content %></div>
      <div class="markdown-content" id="story-content-rendered"></div>
    </div>

    <div class="card">
      <h3>⚡ Pipeline Controls</h3>
      <p style="color:var(--text-muted);font-size:0.85rem;margin-bottom:1rem;">Trigger step-by-step or launch the fully automated agentic sequence.</p>
      <div class="action-buttons-vertical">
        <button class="btn btn-sm btn-primary" onclick="triggerExecute('<%= story.name %>')">▶ Execute Tests</button>
        <a href="/runs?project=<%= project.id %>" class="btn btn-sm" style="margin-top:0.5rem;justify-content:center;">View Test Results →</a>
      </div>
      
      <!-- Streaming console output box -->
      <div id="pipeline-status" class="output-box" style="display:none;"></div>
      
      <!-- Neon loader pulse indicator -->
      <div id="pipeline-pulse" class="terminal-pulse" style="display:none;margin-top:1rem;">
        <span class="pulse-dot"></span>
        <span class="pulse-dot"></span>
        <span class="pulse-dot"></span>
        <span class="pulse-text">AI Agent is running...</span>
      </div>
    </div>
  </div>

  <div class="col col-60">
    <% if (story.plan) { %>
    <div class="card">
      <h3>📋 Test Plan <a href="/stories/<%= story.name %>?project=<%= project.id %>&tab=plan" class="btn btn-sm" style="margin-left:auto;">Refresh</a></h3>
      <div id="story-plan-md" style="display:none;"><%= story.plan %></div>
      <div class="markdown-content" id="story-plan-rendered"></div>
    </div>
    <% } %>

    <% if (story.spec) { %>
    <div class="card">
      <h3>🧪 Test Spec: <%= story.specName %></h3>
      <pre class="code-block"><%= story.spec %></pre>
    </div>
    <% } %>
  </div>
</div>

<script>
// Parse Markdown on Client-Side for extremely high-fidelity tables, checkmarks, list layout
document.addEventListener('DOMContentLoaded', () => {
  const contentRaw = document.getElementById('story-content-md');
  const contentRendered = document.getElementById('story-content-rendered');
  if (contentRaw && contentRendered) {
    contentRendered.innerHTML = marked.parse(contentRaw.textContent || '');
  }

  const planRaw = document.getElementById('story-plan-md');
  const planRendered = document.getElementById('story-plan-rendered');
  if (planRaw && planRendered) {
    planRendered.innerHTML = marked.parse(planRaw.textContent || '');
  }
});

async function callPipeline(action, storyName) {
  const status = document.getElementById('pipeline-status');
  const pulse = document.getElementById('pipeline-pulse');
  
  // Reset and show containers
  status.style.display = 'block';
  status.textContent = `🚀 Initializing QA agent action [${action}]...\n\n`;
  status.className = 'output-box output-running';
  pulse.style.display = 'flex';

  try {
    const res = await fetch(`/stories/${encodeURIComponent(storyName)}/${action}?project=<%= project.id %>`, { method: 'POST' });
    
    if (!res.body) {
      status.textContent += "\nError: The server did not return a readable 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;
      
      const chunk = decoder.decode(value, { stream: true });
      status.textContent += chunk;
      status.scrollTop = status.scrollHeight; // Force Autoscroll
    }

    // Hide pulse loader once done
    pulse.style.display = 'none';

    // Parse final status
    const finishedText = status.textContent.toLowerCase();
    if (finishedText.includes('[finished: success]')) {
      status.className = 'output-box output-success';
      // Reload page to reflect new plans/specs in EJS
      setTimeout(() => { location.reload(); }, 2000);
    } else {
      status.className = 'output-box output-error';
    }

  } catch (error) {
    status.textContent += `\n\nNetwork or server connection error: ${error.message}`;
    status.className = 'output-box output-error';
    pulse.style.display = 'none';
  }
}

function triggerPlan(s) { callPipeline('plan', s); }
function triggerGenerate(s) { callPipeline('generate', s); }
function triggerExecute(s) { callPipeline('execute', s); }
function triggerFull(s) { callPipeline('full-pipeline', s); }

document.addEventListener('DOMContentLoaded', () => {
  const urlParams = new URLSearchParams(window.location.search);
  if (urlParams.get('autoRun') === 'true') {
    // Nettoyer l'URL afin qu'un rechargement manuel ne relance pas le processus
    const newUrl = window.location.pathname + '?project=' + urlParams.get('project');
    window.history.replaceState({}, '', newUrl);
    
    // Déclencher l'exécution des tests
    triggerExecute('<%= story.name %>');
  }
});
</script>
