{% extends "ui/templates/base/layout.html" %}
{% block content %}
<div class="space-y-6">
  {% include "modules/employees/templates/employees/_my_workspace_tabs.html" %}

  <div class="flex flex-wrap items-start justify-between gap-3">
    <div>
      <h2 class="text-xl font-semibold text-slate-900">{{ board.label }}</h2>
      {% set scope_display = board.scope_display or {} %}
      <p class="mt-1 text-sm text-slate-600">
        <span class="font-semibold">{{ scope_display.primary or (board.client.trade_name if board.client and board.client.trade_name else (board.client.client_name if board.client else 'Unlinked Client')) }}</span>
        {% if scope_display.secondary %} · {{ scope_display.secondary }}{% elif board.client and board.client.client_code %} · {{ board.client.client_code }}{% endif %}
      </p>
      {% if scope_display.context %}<p class="mt-1 text-xs text-slate-400">{{ scope_display.context }}</p>{% endif %}
    </div>
    <div class="flex flex-wrap gap-2">
      {% if board.manual_blocker %}
      <form method="post" action="/employee/work/engagements/{{ board.engagement_id }}/resume">
        <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
        <button type="submit" class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700">Resume Workflow</button>
      </form>
      {% elif not (board.subscription and board.subscription.is_locked) %}
      <button type="button" onclick="document.getElementById('pause-workflow-panel').classList.toggle('hidden')" class="rounded-xl border border-amber-300 bg-amber-50 px-4 py-2 text-sm font-semibold text-amber-800 hover:bg-amber-100">Pause / Hold</button>
      {% endif %}
      <a href="/documents/engagements/{{ board.engagement_id }}" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50">Engagement Documents</a>
      <a href="/employee/work" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50">Close</a>
    </div>
  </div>

  {% if request.query_params.get('quick_saved') %}
  <div class="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">Checklist updated.</div>
  {% endif %}
  {% if request.query_params.get('quick_error') %}
  <div class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800">{{ request.query_params.get('quick_error')|replace('+', ' ') }}</div>
  {% endif %}
  {% if request.query_params.get('workflow_error') %}
  <div class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800">The task could not be saved. Complete any required response/evidence or resolve the approval gate.</div>
  {% endif %}

  {% if board.manual_blocker %}
  <div class="rounded-2xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900">
    <div class="font-semibold">Engagement on hold — {{ board.manual_blocker.label }}</div>
    {% if board.manual_blocker.notes %}<div class="mt-1">{{ board.manual_blocker.notes }}</div>{% endif %}
    {% if board.manual_blocker.follow_up_date %}<div class="mt-1 font-medium">Follow-up: {{ board.manual_blocker.follow_up_date }}</div>{% endif %}
  </div>
  {% endif %}

  <div id="pause-workflow-panel" class="hidden rounded-2xl border border-amber-200 bg-white p-5 shadow-soft">
    <form method="post" action="/employee/work/engagements/{{ board.engagement_id }}/pause" class="grid gap-3 md:grid-cols-3">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      <div>
        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Hold Reason</label>
        <select name="reason" class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm" required>
          {% for code, label in board.hold_reasons.items() %}<option value="{{ code }}">{{ label }}</option>{% endfor %}
        </select>
      </div>
      <div>
        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Follow-up Date</label>
        <input type="date" name="follow_up_date" class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm">
      </div>
      <div class="md:col-span-3">
        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Note</label>
        <input type="text" name="notes" class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm" placeholder="Optional hold note">
      </div>
      <div class="md:col-span-3"><button class="rounded-xl bg-amber-600 px-4 py-2 text-sm font-semibold text-white">Put Engagement on Hold</button></div>
    </form>
  </div>

  <section class="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
    <div class="rounded-2xl border border-slate-200 bg-white p-4 shadow-soft">
      <div class="text-xs font-semibold uppercase tracking-wide text-slate-500">Progress</div>
      <div class="mt-2 text-2xl font-semibold text-slate-900">{{ board.progress_percent }}%</div>
      <div class="mt-1 text-xs text-slate-500">{{ board.summary.completed }} / {{ board.summary.total }} closed</div>
    </div>
    <div class="rounded-2xl border border-slate-200 bg-white p-4 shadow-soft">
      <div class="text-xs font-semibold uppercase tracking-wide text-slate-500">Pending</div>
      <div class="mt-2 text-2xl font-semibold text-slate-900">{{ board.summary.pending }}</div>
    </div>
    <div class="rounded-2xl border border-blue-200 bg-blue-50 p-4 shadow-soft">
      <div class="text-xs font-semibold uppercase tracking-wide text-blue-600">In Progress</div>
      <div class="mt-2 text-2xl font-semibold text-blue-700">{{ board.summary.in_progress }}</div>
    </div>
    <div class="rounded-2xl border border-amber-200 bg-amber-50 p-4 shadow-soft">
      <div class="text-xs font-semibold uppercase tracking-wide text-amber-600">Blocked</div>
      <div class="mt-2 text-2xl font-semibold text-amber-700">{{ board.summary.blocked }}</div>
    </div>
    <div class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 shadow-soft">
      <div class="text-xs font-semibold uppercase tracking-wide text-emerald-600">Completed / N.A.</div>
      <div class="mt-2 text-2xl font-semibold text-emerald-700">{{ board.summary.completed }}</div>
    </div>
  </section>

  <section class="rounded-2xl border border-slate-200 bg-white shadow-soft">
    <div class="border-b border-slate-200 px-5 py-4">
      <div class="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h3 class="font-semibold text-slate-900">Engagement Checklist</h3>
          <p class="mt-1 text-sm text-slate-500">Routine work is one click. Open Details only when a response, evidence, remark or communication is needed.</p>
        </div>
        <div class="flex flex-wrap gap-2 text-xs font-medium">
          <span class="rounded-full bg-emerald-50 px-3 py-1 text-emerald-700">✓ Done</span>
          <span class="rounded-full bg-amber-50 px-3 py-1 text-amber-700">! Blocked</span>
          <span class="rounded-full bg-red-50 px-3 py-1 text-red-700">✕ N/A</span>
          <span class="rounded-full bg-indigo-50 px-3 py-1 text-indigo-700">◆ Approval</span>
        </div>
      </div>
    </div>

    <div class="divide-y divide-slate-100">
      {% for category in board.categories %}
      <div class="bg-slate-50 px-5 py-2 text-xs font-semibold uppercase tracking-wide text-slate-500">
        {{ category.name }} · {{ category.completed }}/{{ category.total }}
      </div>

      {% for task in category.tasks %}
      {% set status = task.i1_status or (task.status or 'pending') %}
      <div id="task-{{ task.id }}" class="px-4 py-3 sm:px-5">
        <div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
          <div class="min-w-0 flex-1">
            <div class="flex items-start gap-3">
              <div class="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-base font-bold
                {% if status == 'completed' %}bg-emerald-100 text-emerald-700
                {% elif status == 'not_applicable' %}bg-red-100 text-red-700
                {% elif status == 'blocked' %}bg-amber-100 text-amber-700
                {% elif status == 'in_progress' %}bg-blue-100 text-blue-700
                {% else %}bg-slate-100 text-slate-500{% endif %}">
                {% if status == 'completed' %}✓{% elif status == 'not_applicable' %}✕{% elif status == 'blocked' %}!{% elif status == 'in_progress' %}•{% else %}○{% endif %}
              </div>
              <div class="min-w-0">
                <div class="flex flex-wrap items-center gap-2">
                  <span class="text-xs font-semibold text-slate-400">#{{ task.sequence_no }}</span>
                  <h4 class="font-semibold text-slate-900">{{ task.task_name }}</h4>
                  {% if task.i1_review_label %}
                    {% if task.i1_review_label == 'Approved' %}
                    <span class="rounded-full bg-emerald-50 px-2 py-1 text-[11px] font-semibold text-emerald-700">◆ Approved</span>
                    {% elif task.i1_review_label == 'Returned for correction' %}
                    <span class="rounded-full bg-red-50 px-2 py-1 text-[11px] font-semibold text-red-700">↩ Returned</span>
                    {% else %}
                    <span class="rounded-full bg-indigo-50 px-2 py-1 text-[11px] font-semibold text-indigo-700">◆ {{ task.i1_review_label }}</span>
                    {% endif %}
                  {% endif %}
                  {% if task.i1_needs_evidence %}
                  <span class="rounded-full bg-violet-50 px-2 py-1 text-[11px] font-semibold text-violet-700">Evidence required</span>
                  {% endif %}
                </div>
                {% if task.description %}<p class="mt-1 text-sm text-slate-500">{{ task.description }}</p>{% endif %}
                {% if task.i1_approval_blocker %}
                <div class="mt-2 inline-flex items-center gap-2 rounded-lg bg-indigo-50 px-3 py-1.5 text-xs font-medium text-indigo-700">
                  🔒 {{ task.i1_approval_blocker.label }} — {{ task.i1_approval_blocker.task_name }}
                </div>
                {% endif %}
                {% if status == 'blocked' and task.remarks %}
                <div class="mt-2 text-sm font-medium text-amber-700">! {{ task.remarks }}</div>
                {% elif status == 'not_applicable' and task.remarks %}
                <div class="mt-2 text-sm text-red-600">N/A: {{ task.remarks }}</div>
                {% endif %}
              </div>
            </div>
          </div>

          <div class="flex flex-wrap items-center gap-2 lg:justify-end">
            {% if not task.i1_approval_blocker and not task.is_locked and not (task.subscription and task.subscription.is_locked) %}
              {% if status not in ['completed', 'not_applicable'] %}
                {% if task.i1_quick_complete %}
                <form method="post" action="/employee/work/engagements/{{ board.engagement_id }}/tasks/{{ task.id }}/quick-action">
                  <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                  <input type="hidden" name="action" value="done">
                  <button type="submit" class="rounded-xl bg-emerald-600 px-3 py-2 text-sm font-bold text-white hover:bg-emerald-700" title="Mark Done">✓ Done</button>
                </form>
                {% else %}
                <a href="/documents/tasks/{{ task.id }}" class="rounded-xl border border-violet-200 bg-violet-50 px-3 py-2 text-sm font-semibold text-violet-700 hover:bg-violet-100">
                  {% if task.i1_needs_evidence and not task.i1_has_evidence %}Upload Evidence{% else %}Complete Details{% endif %}
                </a>
                {% endif %}

                <details class="relative" data-i1-quick-popup>
                  <summary class="list-none cursor-pointer rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm font-bold text-amber-700 hover:bg-amber-100">! Blocked</summary>
                  <form method="post" action="/employee/work/engagements/{{ board.engagement_id }}/tasks/{{ task.id }}/quick-action" class="absolute right-0 z-20 mt-2 w-80 rounded-xl border border-amber-200 bg-white p-3 shadow-xl">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                    <input type="hidden" name="action" value="blocked">
                    <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Reason</label>
                    <select name="reason" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" required>
                      <option value="">Select reason</option>
                      {% for code, label in board.hold_reasons.items() %}<option value="{{ label }}">{{ label }}</option>{% endfor %}
                    </select>
                    <button type="submit" class="mt-2 w-full rounded-lg bg-amber-600 px-3 py-2 text-sm font-semibold text-white">Mark Blocked</button>
                  </form>
                </details>

                <details class="relative" data-i1-quick-popup>
                  <summary class="list-none cursor-pointer rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm font-bold text-red-700 hover:bg-red-100">✕ N/A</summary>
                  <form method="post" action="/employee/work/engagements/{{ board.engagement_id }}/tasks/{{ task.id }}/quick-action" class="absolute right-0 z-20 mt-2 w-80 rounded-xl border border-red-200 bg-white p-3 shadow-xl">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                    <input type="hidden" name="action" value="na">
                    <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Short reason</label>
                    <input type="text" name="reason" maxlength="500" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" placeholder="Why is this not applicable?" required>
                    <button type="submit" class="mt-2 w-full rounded-lg bg-red-600 px-3 py-2 text-sm font-semibold text-white">Mark N/A</button>
                  </form>
                </details>
              {% endif %}
            {% else %}
            <span class="rounded-xl bg-slate-100 px-3 py-2 text-sm font-semibold text-slate-500">🔒 Locked</span>
            {% endif %}

            <button type="button"
                    data-i1-panel-trigger="documents"
                    data-i1-task-id="{{ task.id }}"
                    class="rounded-xl border border-violet-200 bg-violet-50 text-violet-700 hover:bg-violet-100 px-3 py-2 text-sm font-semibold">
              Documents{% if task.i1_documents %} · {{ task.i1_documents|length }}{% endif %}
            </button>

            <button type="button"
                    data-i1-panel-trigger="messages"
                    data-i1-task-id="{{ task.id }}"
                    class="rounded-xl border border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-100 px-3 py-2 text-sm font-semibold">
              Message / Clarification{% if task.i1_communications %} · {{ task.i1_communications|length }}{% endif %}
            </button>

            <button type="button"
                    data-i1-panel-trigger="details"
                    data-i1-task-id="{{ task.id }}"
                    class="rounded-xl border border-slate-300 bg-white text-slate-700 hover:bg-slate-50 px-3 py-2 text-sm font-semibold">
              Details
            </button>
          </div>
        </div>

        <div class="mt-3 space-y-3" data-i1-panels-for-task="{{ task.id }}">
          <div data-i1-panel="documents" class="hidden w-full rounded-2xl border border-violet-200 bg-violet-50/40 p-4">
                <div class="flex flex-wrap items-start justify-between gap-3">
                  <div>
                    <h5 class="font-semibold text-slate-900">Task Documents</h5>
                    <p class="mt-1 text-xs text-slate-500">Files stay linked to this task and engagement.</p>
                  </div>
                  <a href="/documents/tasks/{{ task.id }}?return_to=/employee/work/engagements/{{ board.engagement_id }}%3Ftask_id%3D{{ task.id }}%23task-{{ task.id }}" class="text-xs font-semibold text-violet-700 hover:underline">Open full document view</a>
                </div>

                {% if task.i1_documents %}
                <div class="mt-3 divide-y divide-slate-100 rounded-xl border border-slate-200">
                  {% for doc in task.i1_documents[:5] %}
                  {% set latest = doc.versions[0] if doc.versions else none %}
                  <div class="flex flex-wrap items-center justify-between gap-2 px-3 py-2 text-sm">
                    <div class="min-w-0">
                      <div class="truncate font-medium text-slate-800">{{ doc.title }}</div>
                      <div class="truncate text-xs text-slate-500">{{ latest.original_filename if latest else doc.document_type }}{% if latest %} · v{{ latest.version_no }}{% endif %}</div>
                    </div>
                    {% if latest %}<a href="/documents/{{ doc.id }}/download" class="text-xs font-semibold text-brand-700 hover:underline">Download</a>{% endif %}
                  </div>
                  {% endfor %}
                </div>
                {% else %}
                <div class="mt-3 rounded-xl border border-dashed border-slate-300 px-4 py-3 text-sm text-slate-500">No document attached yet.</div>
                {% endif %}

                <form method="post" action="/documents/tasks/{{ task.id }}/upload" enctype="multipart/form-data" class="mt-3 flex flex-col gap-2 sm:flex-row sm:items-end">
                  <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                  <input type="hidden" name="title" value="">
                  <input type="hidden" name="document_type" value="GENERAL">
                  <input type="hidden" name="return_to" value="/employee/work/engagements/{{ board.engagement_id }}?task_id={{ task.id }}#task-{{ task.id }}">
                  <label class="min-w-0 flex-1 text-xs font-semibold uppercase tracking-wide text-slate-500">Add file
                    <input type="file" name="file" required class="mt-1 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm">
                  </label>
                  <button type="submit" class="rounded-lg bg-violet-600 px-4 py-2 text-sm font-semibold text-white hover:bg-violet-700">Upload</button>
                </form>
              </div>
          <div data-i1-panel="messages" class="hidden w-full rounded-2xl border border-sky-200 bg-sky-50/40 p-4">
                <div class="flex flex-wrap items-start justify-between gap-3">
                  <div>
                    <h5 class="font-semibold text-slate-900">Messages / Clarifications</h5>
                    <p class="mt-1 text-xs text-slate-500">Add a note, clarification or client/consultant communication.</p>
                  </div>
                  <a href="/employee/work/tasks/{{ task.id }}/communication?return_to=/employee/work/engagements/{{ board.engagement_id }}%3Ftask_id%3D{{ task.id }}%23task-{{ task.id }}" class="text-xs font-semibold text-sky-700 hover:underline">Open full timeline</a>
                </div>

                {% if task.i1_communications %}
                <div class="mt-3 max-h-52 divide-y divide-slate-100 overflow-y-auto rounded-xl border border-slate-200">
                  {% for item in task.i1_communications[:5] %}
                  <div class="px-3 py-2">
                    <div class="flex flex-wrap items-center justify-between gap-2 text-[11px] text-slate-500">
                      <span>{{ item.comment_type.replace('_',' ').title() }} · {{ item.visibility.replace('_',' ').title() }}</span>
                      <span>{{ item.created_at_utc }}</span>
                    </div>
                    <div class="mt-1 whitespace-pre-wrap text-sm text-slate-800">{{ item.message }}</div>
                    <div class="mt-1 text-[11px] text-slate-400">By {{ item.created_by.full_name if item.created_by else 'System/User' }}</div>
                  </div>
                  {% endfor %}
                </div>
                {% else %}
                <div class="mt-3 rounded-xl border border-dashed border-slate-300 px-4 py-3 text-sm text-slate-500">No message or clarification yet.</div>
                {% endif %}

                <form method="post" action="/employee/work/tasks/{{ task.id }}/communication" class="mt-3 grid gap-2 sm:grid-cols-2">
                  <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                  <input type="hidden" name="return_to" value="/employee/work/engagements/{{ board.engagement_id }}?task_id={{ task.id }}#task-{{ task.id }}">
                  <select name="comment_type" class="rounded-lg border border-slate-300 px-3 py-2 text-sm">
                    {% for code, label in board.communication_types %}<option value="{{ code }}">{{ label }}</option>{% endfor %}
                  </select>
                  <select name="visibility" class="rounded-lg border border-slate-300 px-3 py-2 text-sm">
                    {% for code, label in board.communication_visibilities %}<option value="{{ code }}">{{ label }}</option>{% endfor %}
                  </select>
                  <textarea name="message" rows="2" required class="sm:col-span-2 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" placeholder="Type message or clarification"></textarea>
                  <div class="sm:col-span-2 flex justify-end"><button type="submit" class="rounded-lg bg-sky-600 px-4 py-2 text-sm font-semibold text-white hover:bg-sky-700">Send</button></div>
                </form>
              </div>
          <div data-i1-panel="details" class="hidden w-full rounded-2xl border border-slate-200 bg-slate-50 p-4">
                <form method="post" action="/employee/work/engagements/{{ board.engagement_id }}/tasks/{{ task.id }}/save" class="space-y-4">
                  <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                  <input type="hidden" name="status" value="{{ task.status or 'pending' }}">
                  <input type="hidden" name="workflow_action" value="save">

                  {% set response_type = task.response_type or 'NONE' %}
                  {% if response_type != 'NONE' or task.response_required %}
                  <div class="rounded-xl border border-indigo-200 bg-white p-3">
                    <div class="text-sm font-semibold text-indigo-900">Checklist Response{% if task.response_required %} *{% endif %}</div>
                    {% if response_type in ['YES_NO_NA', 'YES_NO'] %}
                    <div class="mt-2 flex flex-wrap gap-2">
                      <label class="cursor-pointer"><input type="radio" class="peer sr-only" name="checklist_response" value="YES" {% if task.checklist_response == 'YES' %}checked{% endif %}><span class="inline-flex rounded-lg border px-3 py-2 text-sm peer-checked:border-emerald-500 peer-checked:bg-emerald-50 peer-checked:text-emerald-700">Yes</span></label>
                      <label class="cursor-pointer"><input type="radio" class="peer sr-only" name="checklist_response" value="NO" {% if task.checklist_response == 'NO' %}checked{% endif %}><span class="inline-flex rounded-lg border px-3 py-2 text-sm peer-checked:border-red-500 peer-checked:bg-red-50 peer-checked:text-red-700">No</span></label>
                      {% if response_type == 'YES_NO_NA' %}<label class="cursor-pointer"><input type="radio" class="peer sr-only" name="checklist_response" value="NA" {% if task.checklist_response == 'NA' %}checked{% endif %}><span class="inline-flex rounded-lg border px-3 py-2 text-sm peer-checked:border-slate-500 peer-checked:bg-slate-100">N/A</span></label>{% endif %}
                    </div>
                    {% elif response_type == 'TEXT' %}
                    <textarea name="checklist_text_response" rows="2" class="mt-2 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">{{ task.checklist_text_response or '' }}</textarea>
                    {% elif response_type == 'NUMBER' %}
                    <input type="number" step="any" name="checklist_number_response" value="{{ task.checklist_number_response if task.checklist_number_response is not none else '' }}" class="mt-2 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                    {% elif response_type == 'DATE' %}
                    <input type="date" name="checklist_date_response" value="{{ task.checklist_date_response or '' }}" class="mt-2 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                    {% endif %}
                    <textarea name="checklist_remarks" rows="2" class="mt-2 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" placeholder="Checklist remark only when needed">{{ task.checklist_remarks or '' }}</textarea>
                  </div>
                  {% else %}
                  <input type="hidden" name="checklist_response" value="">
                  <input type="hidden" name="checklist_text_response" value="">
                  <input type="hidden" name="checklist_number_response" value="">
                  <input type="hidden" name="checklist_date_response" value="">
                  <input type="hidden" name="checklist_remarks" value="">
                  {% endif %}

                  <div>
                    <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-500">Work Remark</label>
                    <input type="text" name="remarks" value="{{ task.remarks or '' }}" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" placeholder="Optional">
                  </div>

                  <div class="flex flex-wrap items-center justify-between gap-2">
                    <div class="text-xs text-slate-500">Documents and messages can be added directly from this checklist row.</div>
                    <button type="submit" class="rounded-lg bg-brand-600 px-4 py-2 text-sm font-semibold text-white">Save Details</button>
                  </div>
                </form>
              </div>
        </div>
      </div>
      {% endfor %}
      {% endfor %}
    </div>
  </section>

  <details class="rounded-2xl border border-amber-200 bg-amber-50 p-4">
    <summary class="cursor-pointer text-sm font-semibold text-amber-900">Escalate dependency or review delay</summary>
    <form method="post" action="/employee/work/engagements/{{ board.engagement_id }}/escalate" class="mt-3 grid gap-3">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      <select name="level" class="w-full rounded-xl border border-amber-300 bg-white px-3 py-2 text-sm" required>{% for code, label in board.escalation_levels.items() %}<option value="{{ code }}">{{ label }}</option>{% endfor %}</select>
      <textarea name="message" rows="2" maxlength="1000" required class="w-full rounded-xl border border-amber-300 bg-white px-3 py-2 text-sm" placeholder="Explain the dependency or review delay"></textarea>
      <button type="submit" class="w-fit rounded-xl border border-amber-300 bg-white px-4 py-2 text-sm font-semibold text-amber-900">Send Escalation</button>
    </form>
  </details>

  <section class="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
    <div class="flex flex-wrap items-center justify-between gap-3">
      <div>
        <h3 class="font-semibold text-slate-900">Engagement Summary</h3>
        <p class="mt-1 text-sm text-slate-500">Existing engagement, team and document controls remain unchanged.</p>
      </div>
      <a href="/documents/engagements/{{ board.engagement_id }}" class="text-sm font-semibold text-brand-700 hover:text-brand-800">Open Documents</a>
    </div>
    <dl class="mt-4 grid gap-3 text-sm sm:grid-cols-2 lg:grid-cols-4">
      <div class="rounded-xl bg-slate-50 p-3"><dt class="text-slate-500">Engagement Status</dt><dd class="mt-1 font-medium text-slate-900">{{ board.subscription.status if board.subscription else '-' }}</dd></div>
      <div class="rounded-xl bg-slate-50 p-3"><dt class="text-slate-500">Financial Year</dt><dd class="mt-1 font-medium text-slate-900">{{ board.subscription.financial_year if board.subscription else '-' }}</dd></div>
      <div class="rounded-xl bg-slate-50 p-3"><dt class="text-slate-500">Due Date</dt><dd class="mt-1 font-medium text-slate-900">{{ board.subscription.current_due_date if board.subscription else '-' }}</dd></div>
      <div class="rounded-xl bg-slate-50 p-3"><dt class="text-slate-500">Review Partner</dt><dd class="mt-1 font-medium text-slate-900">{{ board.subscription.review_partner.full_name if board.subscription and board.subscription.review_partner else '-' }}</dd></div>
    </dl>
  </section>
</div>

<script>
document.addEventListener("click", function (event) {
  const trigger = event.target.closest("[data-i1-panel-trigger]");
  if (!trigger) return;

  const taskId = trigger.getAttribute("data-i1-task-id");
  const panelName = trigger.getAttribute("data-i1-panel-trigger");
  const container = document.querySelector('[data-i1-panels-for-task="' + taskId + '"]');
  if (!container) return;

  const requested = container.querySelector('[data-i1-panel="' + panelName + '"]');
  if (!requested) return;

  const wasOpen = !requested.classList.contains("hidden");

  container.querySelectorAll("[data-i1-panel]").forEach(function (panel) {
    panel.classList.add("hidden");
  });

  if (!wasOpen) {
    requested.classList.remove("hidden");
  }
});


document.addEventListener("click", function (event) {
  const clickedPopup = event.target.closest("[data-i1-quick-popup]");
  const clickedSummary = event.target.closest("[data-i1-quick-popup] > summary");

  document.querySelectorAll("[data-i1-quick-popup][open]").forEach(function (popup) {
    if (clickedPopup === popup) {
      return;
    }
    popup.removeAttribute("open");
  });

  if (clickedSummary) {
    const popup = clickedSummary.parentElement;
    document.querySelectorAll("[data-i1-quick-popup][open]").forEach(function (otherPopup) {
      if (otherPopup !== popup) {
        otherPopup.removeAttribute("open");
      }
    });
  }
});

document.addEventListener("keydown", function (event) {
  if (event.key !== "Escape") return;
  document.querySelectorAll("[data-i1-quick-popup][open]").forEach(function (popup) {
    popup.removeAttribute("open");
  });
});
</script>

{% endblock %}
