{% extends "base.html" %}

{% block content %}
  <div class="grid two-col">
    <section class="card">
      <div class="kicker">Engagement</div>
      <h2>{{ engagement.name }}</h2>
      <div class="muted mono">id={{ engagement.id }} · created={{ engagement.created_at.strftime("%Y-%m-%d %H:%M:%S") }}</div>
      {% if engagement.description %}
        <p class="muted" style="margin-top: 10px;">{{ engagement.description }}</p>
      {% endif %}

      <div class="kicker" style="margin-top: 16px;">Coverage</div>
      <div class="metric">{{ coverage.coverage_score }}%</div>
      <div class="muted">Operational gaps: {{ coverage.gaps|join(", ") if coverage.gaps else "none" }}</div>
      <div class="table-wrap" style="margin-top: 10px;">
        <table>
          <thead>
            <tr>
              <th>Phase</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {% for phase, state in coverage.phases.items() %}
              <tr>
                <td>{{ phase }}</td>
                <td><span class="pill">{{ state }}</span></td>
              </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>

      <div class="btn-row" style="margin-top: 12px;">
        <a class="btn" href="/dashboard/report/{{ engagement.id }}">Report</a>
        <a class="btn secondary" href="/dashboard/notes/{{ engagement.id }}">Notes</a>
        <button class="btn secondary" id="sync-gaps-btn" data-engagement-id="{{ engagement.id }}" type="button">
          Convert Gaps To Tasks
        </button>
      </div>
      <div id="sync-gaps-output" class="muted" style="margin-top: 8px;"></div>
    </section>

    <section class="card">
      <div class="kicker">Event Intake</div>
      <h3>Create Event</h3>
      <form action="/dashboard/events/create" method="post" class="field-grid">
        <input type="hidden" name="engagement_id" value="{{ engagement.id }}" />
        <div class="field-row">
          <label>
            Phase
            <select name="phase" required>
              {% for phase in phase_options %}
                <option value="{{ phase }}">{{ phase }}</option>
              {% endfor %}
            </select>
          </label>
          <label>
            Severity
            <select name="severity" required>
              {% for severity in severity_options %}
                <option value="{{ severity }}">{{ severity }}</option>
              {% endfor %}
            </select>
          </label>
        </div>
        <div class="field-row">
          <label>
            Source
            <input type="text" name="source" value="manual" maxlength="100" />
          </label>
          <label>
            Tags
            <input type="text" name="tags" placeholder="network,credential,internal" />
          </label>
        </div>
        <label>
          Title
          <input type="text" name="title" required maxlength="255" />
        </label>
        <label>
          Description
          <textarea name="content" required placeholder="Observed behavior, impact, and context"></textarea>
        </label>
        <label>
          Evidence Paths (optional)
          <textarea name="evidence_paths" class="mono" placeholder="reports/web/auth-bypass.txt"></textarea>
        </label>
        <div class="btn-row">
          <button class="btn" type="submit">Log Event</button>
        </div>
      </form>
    </section>
  </div>

  <section class="card" style="margin-top: 14px;">
    <div style="display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; align-items: center;">
      <div>
        <div class="kicker">Timeline</div>
        <h3 style="margin: 0;">Execution View</h3>
      </div>
      <div class="btn-row">
        <a class="btn secondary" href="/dashboard/engagement/{{ engagement.id }}?timeline_mode=chronological">Chronological</a>
        <a class="btn secondary" href="/dashboard/engagement/{{ engagement.id }}?timeline_mode=grouped">Grouped</a>
      </div>
    </div>

    {% if timeline_mode == "grouped" and grouped_timeline %}
      <div class="grid" style="margin-top: 12px;">
        {% for phase, entries in grouped_timeline.phases.items() %}
          <article class="card" style="padding: 10px 12px;">
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <strong>{{ phase }}</strong>
              <span class="pill">{{ entries|length }} event(s)</span>
            </div>
            {% if entries %}
              <div class="table-wrap" style="margin-top: 8px;">
                <table>
                  <thead>
                    <tr>
                      <th>Timestamp</th>
                      <th>Severity</th>
                      <th>Title</th>
                      <th>Source</th>
                    </tr>
                  </thead>
                  <tbody>
                    {% for event in entries %}
                      <tr>
                        <td class="mono">{{ event.ts.strftime("%Y-%m-%d %H:%M:%S") if event.ts else "-" }}</td>
                        <td>{{ event.severity.value }}</td>
                        <td>{{ event.title }}</td>
                        <td>{{ event.source }}</td>
                      </tr>
                    {% endfor %}
                  </tbody>
                </table>
              </div>
            {% else %}
              <p class="muted" style="margin: 8px 0 0;">No events in this phase.</p>
            {% endif %}
          </article>
        {% endfor %}
      </div>
    {% else %}
      {% if timeline_events %}
        <div class="table-wrap" style="margin-top: 12px;">
          <table>
            <thead>
              <tr>
                <th>Timestamp</th>
                <th>Phase</th>
                <th>Severity</th>
                <th>Title</th>
                <th>Source</th>
                <th>Tags</th>
              </tr>
            </thead>
            <tbody>
              {% for event in timeline_events %}
                <tr>
                  <td class="mono">{{ event.ts.strftime("%Y-%m-%d %H:%M:%S") if event.ts else "-" }}</td>
                  <td>{{ event.phase.value }}</td>
                  <td>{{ event.severity.value }}</td>
                  <td>{{ event.title }}</td>
                  <td>{{ event.source }}</td>
                  <td>{{ event.tags|join(", ") if event.tags else "-" }}</td>
                </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
      {% else %}
        <p class="muted" style="margin-top: 12px;">No timeline events available.</p>
      {% endif %}
    {% endif %}
  </section>

  <section class="card" style="margin-top: 14px;">
    <div style="display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; align-items: center;">
      <div>
        <div class="kicker">AI Analysis</div>
        <h3 style="margin: 0;">Operator Insight Layer</h3>
      </div>
      <a class="btn" href="/dashboard/engagement/{{ engagement.id }}?run_ai=true&timeline_mode={{ timeline_mode }}">Run AI Analysis</a>
    </div>

    {% if ai_error %}
      <div class="banner error" style="margin-top: 10px;">AI analysis failed: {{ ai_error }}</div>
    {% elif ai_analysis %}
      <div class="grid" style="margin-top: 10px;">
        <article class="card" style="padding: 10px 12px;">
          <h3>Executive Summary</h3>
          <p class="muted">{{ ai_analysis.executive_summary }}</p>
        </article>
        <article class="card" style="padding: 10px 12px;">
          <h3>Next Actions</h3>
          {% if ai_analysis.next_actions %}
            <ul>
              {% for item in ai_analysis.next_actions %}
                <li>{{ item }}</li>
              {% endfor %}
            </ul>
          {% else %}
            <p class="muted">No next actions returned.</p>
          {% endif %}
        </article>
        <article class="card" style="padding: 10px 12px;">
          <h3>Risk Notes</h3>
          {% if ai_analysis.risk_notes %}
            <ul>
              {% for note in ai_analysis.risk_notes %}
                <li>{{ note }}</li>
              {% endfor %}
            </ul>
          {% else %}
            <p class="muted">No risk notes returned.</p>
          {% endif %}
        </article>
      </div>
    {% else %}
      <p class="muted" style="margin-top: 10px;">Run analysis when you need summarized risk posture and action priorities.</p>
    {% endif %}
  </section>
{% endblock %}

{% block page_scripts %}
  <script>
    (() => {
      const button = document.getElementById("sync-gaps-btn")
      const output = document.getElementById("sync-gaps-output")
      if (!button || !output) return

      button.addEventListener("click", async () => {
        const engagementId = button.getAttribute("data-engagement-id")
        if (!engagementId) return
        output.textContent = "Creating tasks from uncovered phases..."
        try {
          const response = await fetch(`/tasks/from-coverage?engagement_id=${encodeURIComponent(engagementId)}`, {
            method: "POST",
          })
          const payload = await response.json()
          if (!response.ok) {
            throw new Error(payload?.detail || `HTTP ${response.status}`)
          }
          const created = (payload.created_tasks || []).length
          const skipped = (payload.skipped_tasks || []).length
          output.textContent = `Task sync complete. created=${created}, skipped=${skipped}.`
        } catch (error) {
          output.textContent = `Task sync failed: ${error instanceof Error ? error.message : String(error)}`
        }
      })
    })()
  </script>
{% endblock %}
