{% extends "base.html" %}

{% block content %}
  <div class="grid two-col">
    <section class="card">
      <div class="kicker">Operations</div>
      <h2>Create Engagement</h2>
      <form action="/dashboard/engagements/create" method="post" class="field-grid">
        <label>
          Name
          <input type="text" name="name" required maxlength="255" placeholder="client-q1-internal" />
        </label>
        <label>
          Description
          <textarea name="description" placeholder="Scope, constraints, and operator notes"></textarea>
        </label>
        <label>
          Metadata JSON
          <textarea name="metadata" class="mono" placeholder='{"owner":"red-team","window":"night"}'></textarea>
        </label>
        <div class="btn-row">
          <button class="btn" type="submit">Create Engagement</button>
        </div>
      </form>

      <div class="kicker" style="margin-top: 20px;">Workspaces</div>
      {% if engagements %}
        <div class="list">
          {% for item in engagements %}
            <a class="list-item" href="/dashboard/engagement/{{ item.id }}">
              <div style="display: flex; justify-content: space-between; gap: 10px;">
                <strong>{{ item.name }}</strong>
                <span class="pill mono">#{{ item.id }}</span>
              </div>
              {% if item.description %}
                <div class="muted" style="margin-top: 4px;">{{ item.description }}</div>
              {% endif %}
            </a>
          {% endfor %}
        </div>
      {% else %}
        <p class="muted">No engagements yet.</p>
      {% endif %}
    </section>

    <section class="grid">
      {% if selected_engagement %}
        <article class="card">
          <div class="kicker">Current Engagement</div>
          <h2>{{ selected_engagement.name }}</h2>
          <div class="muted mono">id={{ selected_engagement.id }} · created={{ selected_engagement.created_at.strftime("%Y-%m-%d %H:%M:%S") }}</div>
          {% if selected_engagement.description %}
            <p class="muted" style="margin-top: 10px;">{{ selected_engagement.description }}</p>
          {% endif %}
          {% if selected_engagement.metadata_json %}
            <div class="card" style="margin-top: 10px; padding: 10px;">
              <div class="kicker">Metadata</div>
              <pre class="mono" style="margin: 0; white-space: pre-wrap;">{{ selected_engagement.metadata_json | tojson(indent=2) }}</pre>
            </div>
          {% endif %}
          {% if coverage %}
            <div class="metric">{{ coverage.coverage_score }}%</div>
            <div class="muted">coverage score</div>
            <div style="margin-top: 8px;">
              <span class="pill">gaps: {{ coverage.gaps|join(", ") if coverage.gaps else "none" }}</span>
            </div>
          {% endif %}
          <div class="btn-row" style="margin-top: 12px;">
            <a class="btn" href="/dashboard/engagement/{{ selected_engagement.id }}">Open Engagement</a>
            <a class="btn secondary" href="/dashboard/report/{{ selected_engagement.id }}">Report</a>
            <a class="btn secondary" href="/dashboard/notes/{{ selected_engagement.id }}">Notes</a>
            <button class="btn secondary" id="sync-gaps-btn" data-engagement-id="{{ selected_engagement.id }}" type="button">
              Convert Gaps To Tasks
            </button>
          </div>
          <div id="sync-gaps-output" class="muted" style="margin-top: 8px;"></div>
        </article>

        <article class="card">
          <div class="kicker">Manual Event Entry</div>
          <h3>Create Event</h3>
          <form action="/dashboard/events/create" method="post" class="field-grid">
            <input type="hidden" name="engagement_id" value="{{ selected_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 (comma-separated)
                <input type="text" name="tags" placeholder="web,auth,internal" />
              </label>
            </div>
            <label>
              Title
              <input type="text" name="title" required maxlength="255" />
            </label>
            <label>
              Description
              <textarea name="content" required placeholder="What happened and why it matters"></textarea>
            </label>
            <label>
              Evidence Paths (optional, comma or newline separated)
              <textarea name="evidence_paths" class="mono" placeholder="reports/nmap/scan01.txt"></textarea>
            </label>
            <div class="btn-row">
              <button class="btn" type="submit">Add Event</button>
            </div>
          </form>
        </article>
      {% else %}
        <article class="card">
          <div class="kicker">Operations</div>
          <h2>No Active Engagement</h2>
          <p class="muted">Create an engagement to start logging events, coverage, reports, and notes.</p>
        </article>
      {% endif %}
    </section>
  </div>

  {% if selected_engagement %}
    <section class="card" style="margin-top: 14px;">
      <div class="kicker">Timeline Snapshot</div>
      <h3>Most Recent Events</h3>
      {% if latest_events %}
        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Timestamp</th>
                <th>Phase</th>
                <th>Severity</th>
                <th>Title</th>
                <th>Source</th>
              </tr>
            </thead>
            <tbody>
              {% for event in latest_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>
                </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
      {% else %}
        <p class="muted">No events yet for this engagement.</p>
      {% endif %}
      <div class="btn-row" style="margin-top: 10px;">
        <a class="btn secondary" href="/dashboard/engagement/{{ selected_engagement.id }}?timeline_mode=chronological">View Full Chronological Timeline</a>
        <a class="btn secondary" href="/dashboard/engagement/{{ selected_engagement.id }}?timeline_mode=grouped">View Grouped Timeline</a>
      </div>
    </section>
  {% endif %}
{% 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 %}
