<% layout='layouts/main' %>
<% title=project ? 'Analytics - ' + project.name : 'Analytics Dashboard' %>

<div class="page-header">
  <h1>Analytics Dashboard</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='/analytics?project='+this.value">
        <% projects.forEach(p=> { %>
          <option value="<%= p.id %>" <%=project && project.id===p.id ? 'selected' : '' %>><%= p.name %></option>
        <% }) %>
      </select>
    <% } %>
    <% if (project) { %>
      <a href="/projects/<%= project.id %>" class="btn">Back to Project</a>
    <% } %>
  </div>
</div>

<% if (!project) { %>
  <div class="empty-state">
    <h3>No project selected</h3>
    <p>Add a project first or select one from the dropdown menu to see analytics.</p>
  </div>
<% } else if (stats.totalRuns===0) { %>
  <div class="empty-state">
    <h3>No runs for <%= project.name %></h3>
    <p>Execute the pipeline from the Stories page to view analytics data.</p>
    <a href="/projects/<%= project.id %>" class="btn btn-primary">Go to Project</a>
  </div>
<% } else { %>

  <!-- Real Stats Cards aligned with Clay palette -->
  <div class="row" style="margin-bottom:2rem;">
    <div class="col">
      <div class="card stat-card">
        <div class="stat-number"><%= stats.totalRuns %></div>
        <div class="stat-label">Total Runs</div>
      </div>
    </div>
    <div class="col">
      <div class="card stat-card card-lavender">
        <div class="stat-number"><%= stats.passRate %>%</div>
        <div class="stat-label">Pass Rate</div>
      </div>
    </div>
    <div class="col">
      <div class="card stat-card card-peach">
        <div class="stat-number"><%= stats.totalHealed %></div>
        <div class="stat-label">Tests Healed</div>
      </div>
    </div>
    <div class="col">
      <div class="card stat-card card-ochre">
        <div class="stat-number"><%= stats.healRate %>%</div>
        <div class="stat-label">Heal Rate</div>
      </div>
    </div>
    <div class="col">
      <div class="card stat-card" style="background-color:var(--danger-bg-soft);border-color:var(--danger);">
        <div class="stat-number" style="color:var(--danger);"><%= stats.totalDefects %></div>
        <div class="stat-label" style="color:var(--danger);">Defects Found</div>
      </div>
    </div>
    <div class="col">
      <div class="card stat-card">
        <div class="stat-number"><%= stats.avgDuration > 0 ? (stats.avgDuration / 1000).toFixed(1) + 's' : '—' %></div>
        <div class="stat-label">Avg Duration</div>
      </div>
    </div>
  </div>

  <!-- Charts layout -->
  <div class="row" style="margin-bottom:2rem;">
    <div class="col-60">
      <div class="card">
        <h3>📈 Pass Rate Trend</h3>
        <canvas id="passRateChart" height="200"></canvas>
      </div>
    </div>
    <div class="col-40">
      <div class="card">
        <h3>🍕 Failure Breakdown</h3>
        <canvas id="failureChart" height="200"></canvas>
      </div>
    </div>
  </div>

  <div class="row" style="margin-bottom:2rem;">
    <div class="col-50">
      <div class="card">
        <h3>⏳ Duration Trend</h3>
        <canvas id="durationChart" height="150"></canvas>
      </div>
    </div>
    <div class="col-50">
      <div class="card">
        <h3>🛠️ Healing vs Defects</h3>
        <canvas id="healingChart" height="150"></canvas>
      </div>
    </div>
  </div>

  <!-- Run History Table -->
  <div class="card" style="overflow-x:auto;">
    <h3 style="margin-bottom:1.5rem;">📜 Run History</h3>
    <table class="info-table">
      <thead>
        <tr>
          <th>Run ID</th>
          <th>Test Suite</th>
          <th>Status</th>
          <th>Duration</th>
          <th>Failures</th>
          <th>Healed</th>
          <th>Defects</th>
          <th>Export</th>
        </tr>
      </thead>
      <tbody>
        <% runs.forEach(r=> { %>
          <tr>
            <td><code style="font-family:var(--font-mono);font-size:0.8rem;"><%= r.id.substring(0, 16) %>...</code></td>
            <td><%= r.testName %></td>
            <td><span class="badge <%= r.success ? 'badge-pass' : 'badge-fail' %>"><%= r.success ? 'PASS' : 'FAIL' %></span></td>
            <td><%= r.duration ? (r.duration / 1000).toFixed(1) + 's' : 'N/A' %></td>
            <td><%= r.failures %></td>
            <td><%= r.healed %></td>
            <td><%= r.defects %></td>
            <td>
              <a href="/export/report/<%= r.id %>?project=<%= project.id %>" class="btn btn-sm" target="_blank">HTML</a>
              <a href="/export/pdf/<%= r.id %>?project=<%= project.id %>" class="btn btn-sm">TXT</a>
            </td>
          </tr>
        <% }) %>
      </tbody>
    </table>
  </div>

  <!-- Client-side data storage to prevent server EJS tags in script blocks -->
  <div id="chart-data" 
       style="display: none;"
       data-labels='<%- JSON.stringify(runs.map(r => r.id.substring(0, 10)).reverse()) %>'
       data-passrates='<%- JSON.stringify(runs.map(r => r.total > 0 ? parseFloat(((r.total - r.failures) / r.total * 100).toFixed(1)) : 0).reverse()) %>'
       data-failures='<%- JSON.stringify(runs.map(r => r.failures).reverse()) %>'
       data-durations='<%- JSON.stringify(runs.map(r => r.duration ? parseFloat((r.duration / 1000).toFixed(1)) : 0).reverse()) %>'
       data-healed='<%- JSON.stringify(runs.map(r => r.healed).reverse()) %>'
       data-defects='<%- JSON.stringify(runs.map(r => r.defects).reverse()) %>'
       data-passedruns="<%= stats.passedRuns %>"
       data-totalhealed="<%= stats.totalHealed %>"
       data-totaldefects="<%= stats.totalDefects %>">
  </div>

  <script>
    const chartDataEl = document.getElementById('chart-data');
    const runLabels = JSON.parse(chartDataEl.dataset.labels || '[]');
    const passRates = JSON.parse(chartDataEl.dataset.passrates || '[]');
    const failures = JSON.parse(chartDataEl.dataset.failures || '[]');
    const durations = JSON.parse(chartDataEl.dataset.durations || '[]');
    const healed = JSON.parse(chartDataEl.dataset.healed || '[]');
    const defects = JSON.parse(chartDataEl.dataset.defects || '[]');
    const passedRuns = parseInt(chartDataEl.dataset.passedruns || '0', 10);
    const totalHealed = parseInt(chartDataEl.dataset.totalhealed || '0', 10);
    const totalDefects = parseInt(chartDataEl.dataset.totaldefects || '0', 10);

    // 1. Pass Rate Trend Chart (Vibrant Pink & Teal fill)
    new Chart(document.getElementById('passRateChart'), {
      type: 'line',
      data: {
        labels: runLabels,
        datasets: [{
          label: 'Pass Rate %',
          data: passRates,
          borderColor: '#ff4d8b',
          backgroundColor: 'rgba(255, 77, 139, 0.08)',
          fill: true,
          tension: 0.4,
          borderWidth: 3
        }]
      },
      options: { 
        responsive: true, 
        plugins: { 
          legend: { labels: { color: '#0a0a0a', font: { family: 'Inter', weight: 600 } } } 
        }, 
        scales: { 
          x: { grid: { display: false }, ticks: { color: '#3a3a3a' } }, 
          y: { min: 0, max: 100, ticks: { color: '#3a3a3a' } } 
        } 
      }
    });

    // 2. Failure Breakdown Pie Chart (Clay Brand Colors)
    new Chart(document.getElementById('failureChart'), {
      type: 'pie',
      data: {
        labels: ['Passed', 'Healed', 'Defects'],
        datasets: [{
          data: [passedRuns, totalHealed, totalDefects],
          backgroundColor: ['#22c55e', '#ffb084', '#ff4d8b'],
          borderColor: '#fffaf0',
          borderWidth: 2
        }]
      },
      options: { 
        responsive: true, 
        plugins: { 
          legend: { labels: { color: '#0a0a0a', font: { family: 'Inter', weight: 600 } } } 
        } 
      }
    });

    // 3. Duration Trend Bar Chart (Deep Teal)
    new Chart(document.getElementById('durationChart'), {
      type: 'bar',
      data: {
        labels: runLabels,
        datasets: [{
          label: 'Duration (s)',
          data: durations,
          backgroundColor: '#1a3a3a',
          borderRadius: 6
        }]
      },
      options: { 
        responsive: true, 
        plugins: { 
          legend: { labels: { color: '#0a0a0a', font: { family: 'Inter', weight: 600 } } } 
        }, 
        scales: { 
          x: { grid: { display: false }, ticks: { color: '#3a3a3a' } }, 
          y: { ticks: { color: '#3a3a3a' } } 
        } 
      }
    });

    // 4. Healing vs Defects Double Bar Chart (Peach & Pink)
    new Chart(document.getElementById('healingChart'), {
      type: 'bar',
      data: {
        labels: runLabels,
        datasets: [
          { label: 'Healed', data: healed, backgroundColor: '#ffb084', borderRadius: 4 },
          { label: 'Defects', data: defects, backgroundColor: '#ff4d8b', borderRadius: 4 }
        ]
      },
      options: { 
        responsive: true, 
        plugins: { 
          legend: { labels: { color: '#0a0a0a', font: { family: 'Inter', weight: 600 } } } 
        }, 
        scales: { 
          x: { grid: { display: false }, ticks: { color: '#3a3a3a' } }, 
          y: { ticks: { color: '#3a3a3a' } } 
        } 
      }
    });
  </script>

<% } %>