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

<div class="page-header">
  <h1><%= story.name.replace('.md', '') %></h1>
  <span class="badge badge-project"><%= project.name %></span>
</div>

<!-- ─── Phase Workflow Buttons ─── -->
<div class="card" style="margin-bottom:1.5rem;">
  <h3>⚡ Pipeline Workflow</h3>
  <p style="color:var(--text-muted);font-size:0.85rem;margin-bottom:1rem;">Execute each phase in order. Verify the output before proceeding to the next step.</p>
  <div style="display:flex;gap:0.75rem;flex-wrap:wrap;align-items:center;">
    <button class="btn btn-sm" id="btn-plan" onclick="triggerPhase('plan')" <%= story.plan ? 'disabled style="opacity:0.5;"' : '' %>>
      <%= story.plan ? '✅ Planned' : '📋 1. Plan' %>
    </button>
    <span style="color:var(--text-disabled);">→</span>
    <button class="btn btn-sm" id="btn-generate" onclick="triggerPhase('generate')" <%= !story.plan || story.spec ? 'disabled style="opacity:0.5;"' : '' %>>
      <%= story.spec ? '✅ Generated' : '🧪 2. Generate' %>
    </button>
    <span style="color:var(--text-disabled);">→</span>
    <button class="btn btn-sm btn-primary" id="btn-execute" onclick="triggerPhase('execute')" <%= !story.spec ? 'disabled style="opacity:0.5;"' : '' %>>
      ▶ 3. Execute
    </button>
    <span style="color:var(--text-disabled);">→</span>
    <button class="btn btn-sm" id="btn-report" onclick="triggerPhase('report')" <%= !story.hasRun ? 'disabled style="opacity:0.5;"' : '' %>>
      📊 4. Report
    </button>
    <% if (story.hasAllure) { %>
    <a href="/allure-report?project=<%= project.id %>" class="btn btn-sm" target="_blank" style="background-color:var(--brand-ochre);">📈 Allure</a>
    <% } %>
  </div>
  <div id="pulse-indicator" 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 running...</span>
  </div>
  <div id="phase-output" class="output-box" style="display:none;margin-top:1rem;"></div>
</div>

<!-- ─── Tabs: Story | Test Plan | Test Code | Results ─── -->
<div class="card">
  <div style="display:flex;gap:1rem;border-bottom:2px solid var(--border);margin-bottom:1.5rem;padding-bottom:0.5rem;">
    <button class="btn btn-sm tab-btn active-tab" data-tab="story-tab" style="border-bottom:2px solid var(--primary);border-radius:0;">📝 Story</button>
    <button class="btn btn-sm tab-btn" data-tab="plan-tab" style="border-radius:0;">📋 Test Plan</button>
    <button class="btn btn-sm tab-btn" data-tab="spec-tab" style="border-radius:0;">🧪 Test Code</button>
    <button class="btn btn-sm tab-btn" data-tab="results-tab" style="border-radius:0;">⚡ Results</button>
  </div>

  <!-- Tab: Story Content -->
  <div id="story-tab" class="tab-content">
    <div id="story-content-md" style="display:none;"><%= story.content %></div>
    <div class="markdown-content" id="story-content-rendered"></div>
  </div>

  <!-- Tab: Test Plan -->
  <div id="plan-tab" class="tab-content" style="display:none;">
    <% if (story.plan) { %>
      <div id="story-plan-md" style="display:none;"><%= story.plan %></div>
      <div class="markdown-content" id="story-plan-rendered"></div>
    <% } else { %>
      <div class="empty-state" style="padding:2rem;">
        <p>No test plan yet. Click <strong>"📋 1. Plan"</strong> above to generate one.</p>
      </div>
    <% } %>
  </div>

  <!-- Tab: Test Code -->
  <div id="spec-tab" class="tab-content" style="display:none;">
    <% if (story.spec) { %>
      <pre class="code-block" style="max-height:500px;"><%= story.spec %></pre>
      <div style="margin-top:1rem;">
        <a href="/data?project=<%= project.id %>" class="btn btn-sm">View All Test Files</a>
      </div>
    <% } else { %>
      <div class="empty-state" style="padding:2rem;">
        <p>No test code yet. Complete the <strong>Plan</strong> phase first, then click <strong>"🧪 2. Generate"</strong>.</p>
      </div>
    <% } %>
  </div>

  <!-- Tab: Results -->
  <div id="results-tab" class="tab-content" style="display:none;">
    <% if (story.results && story.results.length > 0) { %>
      <table class="info-table">
        <thead><tr><th>Run</th><th>Status</th><th>Duration</th><th>Passed</th><th>Failed</th><th>Actions</th></tr></thead>
        <tbody>
          <% story.results.slice(0, 5).forEach(r => { %>
          <tr>
            <td><%= r.id.substring(0, 20) %></td>
            <td><%= r.success ? '✅ Passed' : (r.success === null ? '⏳ Running' : '❌ Failed') %></td>
            <td><%= r.duration ? (r.duration / 1000).toFixed(1) + 's' : 'N/A' %></td>
            <td><%= r.passedCount %></td>
            <td><%= r.failedCount %></td>
            <td><a href="/runs/<%= r.id %>?project=<%= project.id %>" class="btn btn-sm">View</a></td>
          </tr>
          <% }) %>
        </tbody>
      </table>
      <div style="margin-top:1rem;">
        <a href="/runs?project=<%= project.id %>" class="btn btn-sm">All Runs →</a>
        <a href="/export/report/latest?project=<%= project.id %>" class="btn btn-sm" target="_blank">📥 Download Report</a>
      </div>
    <% } else { %>
      <div class="empty-state" style="padding:2rem;">
        <p>No execution results yet. Click <strong>"▶ 3. Execute"</strong> above to run the tests.</p>
      </div>
    <% } %>
  </div>
</div>

<script>
// ─── Tab switching ───
document.addEventListener('DOMContentLoaded', () => {
  // Render markdown
  const contentRaw = document.getElementById('story-content-md');
  const contentRendered = document.getElementById('story-content-rendered');
  if (contentRaw && contentRendered && typeof marked !== 'undefined') {
    contentRendered.innerHTML = marked.parse(contentRaw.textContent || '');
  }
  const planRaw = document.getElementById('story-plan-md');
  const planRendered = document.getElementById('story-plan-rendered');
  if (planRaw && planRendered && typeof marked !== 'undefined') {
    planRendered.innerHTML = marked.parse(planRaw.textContent || '');
  }

  // Tab click handlers
  document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.tab-btn').forEach(b => { b.style.borderBottom = '2px solid transparent'; b.style.color = 'var(--text-muted)'; });
      btn.style.borderBottom = '2px solid var(--primary)';
      btn.style.color = 'var(--text)';
      document.querySelectorAll('.tab-content').forEach(tc => tc.style.display = 'none');
      document.getElementById(btn.dataset.tab).style.display = 'block';
    });
  });
});

// ─── Phase execution ───
async function triggerPhase(action) {
  const output = document.getElementById('phase-output');
  const pulse = document.getElementById('pulse-indicator');
  output.style.display = 'block';
  output.textContent = `🚀 Running ${action}...\n`;
  output.className = 'output-box output-running';
  pulse.style.display = 'flex';

  try {
    const res = await fetch(`/stories/<%= story.name %>/${action}?project=<%= project.id %>`, { method: 'POST' });
    if (!res.body) { output.textContent += '\nError: No 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';
    const isSuccess = output.textContent.toLowerCase().includes('finished: success');
    output.className = `output-box ${isSuccess ? 'output-success' : 'output-error'}`;
    if (isSuccess) setTimeout(() => location.reload(), 2000);
  } catch (err) {
    output.textContent += `\nError: ${err.message}`;
    output.className = 'output-box output-error';
    pulse.style.display = 'none';
  }
}

// ─── Auto-execute on load ───
document.addEventListener('DOMContentLoaded', () => {
  const urlParams = new URLSearchParams(window.location.search);
  if (urlParams.get('autoRun') === 'true') {
    const newUrl = window.location.pathname + '?project=' + urlParams.get('project');
    window.history.replaceState({}, '', newUrl);
    triggerPhase('execute');
  }
});
</script>