<% layout = 'layouts/main' %>
<% title = 'Terminal' %>

<div class="page-header">
  <h1>🖥️ Terminal</h1>
  <div class="header-actions">
    <% if (typeof projects !== 'undefined' && projects.length > 1) { %>
    <select id="project-select" class="form-input" style="width:auto;" onchange="window.location='/terminal?project='+this.value">
      <% projects.forEach(p => { %>
      <option value="<%= p.id %>" <%= project && project.id === p.id ? 'selected' : '' %>><%= p.name %></option>
      <% }) %>
    </select>
    <% } %>
    <button class="btn btn-sm btn-danger" onclick="clearTerminal()">🗑️ Clear</button>
  </div>
</div>

<div class="card">
  <h3>⚡ Quick Commands</h3>
  <div style="display:flex;gap:0.5rem;flex-wrap:wrap;margin-bottom:1rem;">
    <button class="btn btn-sm" onclick="runCommand('npx playwright test')">▶ Run All Tests</button>
    <button class="btn btn-sm" onclick="runCommand('npm run qa:report')">📝 Generate Report</button>
    <button class="btn btn-sm" onclick="runCommand('npx allure generate allure-results --clean -o allure-report')">📈 Generate Allure</button>
    <button class="btn btn-sm" onclick="runCommand('npm run qa:status')">📊 Status</button>
    <button class="btn btn-sm" onclick="runCommand('npx playwright show-report')">📋 Open HTML Report</button>
  </div>
  <form id="terminal-form" style="display:flex;gap:0.5rem;">
    <input type="text" id="cmd-input" class="form-input" placeholder="Enter a command (e.g., npx playwright test)" style="flex:1;font-family:var(--font-mono);font-size:0.85rem;" autofocus>
    <button type="submit" class="btn btn-primary" style="white-space:nowrap;">▶ Run</button>
  </form>
</div>

<div class="card" style="padding:0;overflow:hidden;">
  <div style="background:var(--surface-dark);padding:0.75rem 1.25rem;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid var(--border-strong);">
    <span style="color:#e5e7eb;font-family:var(--font-mono);font-size:0.8rem;font-weight:600;">Console Output</span>
    <span id="terminal-status" style="color:var(--text-disabled);font-family:var(--font-mono);font-size:0.75rem;">Ready</span>
  </div>
  <pre id="terminal-output" class="code-block" style="border:none;border-radius:0;max-height:500px;min-height:200px;margin:0;font-size:0.8rem;"><%= project ? `Ready — project: ${project.name}\nType a command or click a quick action above.` : 'No project configured.' %></pre>
</div>

<script>
document.getElementById('terminal-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  const cmd = document.getElementById('cmd-input').value.trim();
  if (!cmd) return;
  runCommand(cmd);
});

async function runCommand(command) {
  const output = document.getElementById('terminal-output');
  const status = document.getElementById('terminal-status');
  const input = document.getElementById('cmd-input');

  output.textContent += `\n\n$ ${command}\n`;
  status.textContent = '⏳ Running...';
  output.scrollTop = output.scrollHeight;

  try {
    const res = await fetch('/terminal/run?project=<%= project ? project.id : '' %>', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ command }),
    });

    if (!res.body) {
      output.textContent += 'Error: No response stream\n';
      status.textContent = '❌ Error';
      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;
    }

    const lastLine = output.textContent.split('\n').pop() || '';
    if (lastLine.includes('SUCCESS')) {
      status.textContent = '✅ Completed';
    } else if (lastLine.includes('FAILED')) {
      status.textContent = '❌ Failed';
    } else {
      status.textContent = '✅ Done';
    }

    if (input) input.value = '';
  } catch (err) {
    output.textContent += `\nConnection error: ${err.message}\n`;
    status.textContent = '❌ Error';
  }
}

function clearTerminal() {
  document.getElementById('terminal-output').textContent = 'Terminal cleared.';
  document.getElementById('terminal-status').textContent = 'Ready';
}
</script>