{% 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>
      <p class="mt-1 text-sm text-slate-500">
        {{ board.client.client_name if board.client else 'Unlinked Client' }}
        {% if board.client and board.client.client_code %} · {{ board.client.client_code }}{% endif %}
      </p>
    </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="/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 Workspace</a>
      <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>
    </div>
  </div>


  {% if request.query_params.get('paused') %}<div class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">Engagement workflow paused and the assigned Manager was notified.</div>{% endif %}
  {% if request.query_params.get('resumed') %}<div class="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">Engagement workflow resumed.</div>{% endif %}
  {% if request.query_params.get('pause_error') or request.query_params.get('resume_error') %}<div class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800">The workflow status could not be changed. Confirm the reason and that the engagement is not locked.</div>{% endif %}

  <section class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
    <div class="af-metric-card"><div class="text-xs font-semibold uppercase text-slate-500">Weighted Progress</div><div class="mt-2 text-3xl font-semibold">{{ board.progress_percent }}%</div><div class="mt-1 text-xs text-slate-500">{{ board.weighted_progress.completed_weight }} of {{ board.weighted_progress.total_weight }} weighted points</div></div>
    <div class="af-metric-card"><div class="text-xs font-semibold uppercase text-slate-500">SLA &amp; Ageing</div><div class="mt-2 text-lg font-semibold {% if board.sla.status == 'breached' %}text-red-700{% elif board.sla.status in ['critical','warning'] %}text-amber-700{% else %}text-emerald-700{% endif %}">{{ board.sla.label }}</div><div class="mt-1 text-xs text-slate-500">Age {{ board.sla.age_days }} day(s){% if board.sla.due_date %} · Due {{ board.sla.due_date }}{% endif %}</div></div>
    <div class="af-metric-card md:col-span-2"><div class="text-xs font-semibold uppercase text-slate-500">Engagement Team</div><div class="mt-3 flex flex-wrap gap-2">{% for member in board.engagement_team %}<span class="rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-xs"><strong>{{ member.role }}:</strong> {{ member.name }}</span>{% else %}<span class="text-sm text-slate-500">No engagement team assigned.</span>{% endfor %}</div></div>
  </section>

  {% if request.query_params.get('escalated') %}<div class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-800">Escalation alert sent successfully.</div>{% endif %}
  {% if request.query_params.get('escalation_error') %}<div class="rounded-2xl border border-red-200 bg-red-50 p-4 text-sm text-red-800">Escalation could not be sent. Confirm the selected reviewer is assigned and enter details.</div>{% endif %}

  {% if board.workflow_blocker %}
  <div class="rounded-2xl border {% if board.workflow_blocker.type == 'manual' %}border-amber-300 bg-amber-50{% else %}border-violet-300 bg-violet-50{% endif %} p-4">
    <div class="font-semibold text-slate-900">{{ board.workflow_blocker.label }}</div>
    {% if board.workflow_blocker.notes %}<div class="mt-1 text-sm text-slate-700">{{ board.workflow_blocker.notes }}</div>{% endif %}
    {% if board.workflow_blocker.follow_up_date %}<div class="mt-2 text-sm font-medium text-amber-900">Follow-up date: {{ board.workflow_blocker.follow_up_date }}</div>{% endif %}
    {% if board.workflow_blocker.type == 'automatic' %}<div class="mt-2 text-xs text-violet-700">This blocker is derived automatically from the existing AQMM/review workflow.</div>{% endif %}
  </div>
  {% endif %}

  <div id="pause-workflow-panel" class="hidden rounded-2xl border border-amber-300 bg-white p-5 shadow-soft">
    <h3 class="font-semibold text-slate-900">Pause / Hold Engagement</h3>
    <form method="post" action="/employee/work/engagements/{{ board.engagement_id }}/pause" class="mt-4 grid gap-4 md:grid-cols-3">
      <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
      <div><label class="mb-2 block text-sm font-medium text-slate-700">Reason</label><select name="reason" required class="w-full rounded-xl border border-slate-300 px-4 py-2 text-sm"><option value="">Select reason</option>{% for code, label in board.hold_reasons.items() %}<option value="{{ code }}">{{ label }}</option>{% endfor %}</select></div>
      <div><label class="mb-2 block text-sm font-medium text-slate-700">Follow-up Date</label><input type="date" name="follow_up_date" class="w-full rounded-xl border border-slate-300 px-4 py-2 text-sm"></div>
      <div class="md:col-span-3"><label class="mb-2 block text-sm font-medium text-slate-700">Remarks / Dependency Details</label><textarea name="notes" rows="3" class="w-full rounded-xl border border-slate-300 px-4 py-2 text-sm" placeholder="Documents pending, query details, reviewer dependency or other follow-up information"></textarea></div>
      <div class="md:col-span-3 flex justify-end"><button type="submit" class="rounded-xl bg-amber-600 px-4 py-2 text-sm font-semibold text-white hover:bg-amber-700">Pause and Notify Manager</button></div>
    </form>
  </div>

  {% if request.query_params.get('saved') %}
  <div class="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">Task response saved successfully.</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 the required response, remarks and evidence, and confirm that the task is not locked.</div>
  {% endif %}

  <div class="grid gap-4 md:grid-cols-5">
    <div class="rounded-2xl border border-slate-200 bg-white p-4 shadow-soft">
      <div class="text-xs font-semibold uppercase text-slate-500">Overall Progress</div>
      <div class="mt-1 text-2xl font-semibold text-slate-900">{{ board.progress_percent }}%</div>
      <div class="mt-3 h-2 overflow-hidden rounded-full bg-slate-100"><div class="h-full rounded-full bg-brand-600" style="width: {{ board.progress_percent }}%"></div></div>
    </div>
    <div class="rounded-2xl border border-slate-200 bg-white p-4 shadow-soft"><div class="text-xs font-semibold uppercase text-slate-500">Total</div><div class="mt-1 text-2xl font-semibold">{{ board.summary.total }}</div></div>
    <div class="rounded-2xl border border-blue-200 bg-blue-50 p-4 shadow-soft"><div class="text-xs font-semibold uppercase text-blue-600">In Progress</div><div class="mt-1 text-2xl font-semibold text-blue-700">{{ board.summary.in_progress }}</div></div>
    <div class="rounded-2xl border border-rose-200 bg-rose-50 p-4 shadow-soft"><div class="text-xs font-semibold uppercase text-rose-600">Blocked</div><div class="mt-1 text-2xl font-semibold text-rose-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 text-emerald-600">Completed</div><div class="mt-1 text-2xl font-semibold text-emerald-700">{{ board.summary.completed }}</div></div>
  </div>

  <div class="grid gap-6 xl:grid-cols-[360px_minmax(0,1fr)]">
    <aside class="space-y-4">
      <div class="rounded-2xl border border-slate-200 bg-white p-4 shadow-soft">
        <div class="mb-4">
          <h3 class="font-semibold text-slate-900">Workflow Groups</h3>
          <p class="mt-1 text-sm text-slate-500">Tasks assigned to you, grouped by task category.</p>
        </div>
        <div class="space-y-3">
          {% for category in board.categories %}
          <div class="rounded-xl border {% if category.name == board.active_category %}border-brand-300 bg-brand-50{% else %}border-slate-200 bg-white{% endif %} p-3">
            <div class="flex items-start justify-between gap-3">
              <div>
                <div class="text-sm font-semibold text-slate-900">{{ category.name }}</div>
                <div class="mt-1 text-xs text-slate-500">{{ category.completed }} of {{ category.total }} completed</div>
              </div>
              <span class="rounded-full px-2 py-1 text-[11px] font-semibold {% if category.status == 'completed' %}bg-emerald-100 text-emerald-700{% elif category.status == 'blocked' %}bg-rose-100 text-rose-700{% elif category.status == 'in_progress' %}bg-blue-100 text-blue-700{% else %}bg-slate-100 text-slate-600{% endif %}">{{ category.status.replace('_', ' ').title() }}</span>
            </div>
            <div class="mt-3 h-1.5 overflow-hidden rounded-full bg-slate-100"><div class="h-full rounded-full bg-brand-600" style="width: {{ category.progress_percent }}%"></div></div>
            <div class="mt-3 space-y-1.5">
              {% for task in category.tasks %}
              <a href="/employee/work/engagements/{{ board.engagement_id }}?task_id={{ task.id }}" class="flex items-center justify-between gap-2 rounded-lg px-2 py-2 text-xs {% if board.active_task and task.id == board.active_task.id %}bg-white font-semibold text-brand-700 shadow-sm{% else %}text-slate-600 hover:bg-slate-50{% endif %}">
                <span class="min-w-0 truncate">#{{ task.sequence_no }} {{ task.task_name }}</span>
                <span class="shrink-0 rounded-full px-1.5 py-0.5 {% if task.status == 'completed' %}bg-emerald-100 text-emerald-700{% elif task.status == 'blocked' %}bg-rose-100 text-rose-700{% elif task.status == 'in_progress' %}bg-blue-100 text-blue-700{% else %}bg-slate-100 text-slate-500{% endif %}">{{ (task.status or 'pending').replace('_',' ').title() }}</span>
              </a>
              {% endfor %}
            </div>
          </div>
          {% endfor %}
        </div>
      </div>
    </aside>

    <main class="space-y-4">
      {% set task = board.active_task %}
      {% if task %}
      <section class="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
        <div class="flex flex-wrap items-start justify-between gap-4">
          <div>
            <div class="text-xs font-semibold uppercase tracking-wide text-brand-700">{{ board.active_category }}</div>
            <h3 class="mt-1 text-lg font-semibold text-slate-900">{{ task.task_name }}</h3>
            {% if task.description %}<p class="mt-2 whitespace-pre-line text-sm leading-6 text-slate-600">{{ task.description }}</p>{% endif %}
          </div>
          <div class="flex flex-wrap gap-2 text-xs font-semibold">
            <span class="rounded-full bg-slate-100 px-3 py-1 text-slate-700">Task #{{ task.sequence_no }}</span>
            {% if task.response_required %}<span class="rounded-full bg-indigo-100 px-3 py-1 text-indigo-700">Response Required</span>{% endif %}
            {% if task.evidence_required or task.aqmm_evidence_required %}<span class="rounded-full bg-amber-100 px-3 py-1 text-amber-700">Evidence Required</span>{% endif %}
            {% if task.is_locked or (task.subscription and task.subscription.is_locked) %}<span class="rounded-full bg-slate-200 px-3 py-1 text-slate-700">Locked</span>{% endif %}
          </div>
        </div>

        <form method="post" action="/employee/work/engagements/{{ board.engagement_id }}/tasks/{{ task.id }}/save" class="mt-6 space-y-5">
          <input type="hidden" name="csrf_token" value="{{ csrf_token }}">

          <div class="grid gap-4 md:grid-cols-2">
            <div>
              <label class="mb-2 block text-sm font-medium text-slate-700">Task Status</label>
              <select name="status" class="w-full rounded-xl border border-slate-300 px-4 py-2 text-sm" {% if task.is_locked or (task.subscription and task.subscription.is_locked) %}disabled{% endif %}>
                <option value="pending" {% if task.status == 'pending' %}selected{% endif %}>Pending</option>
                <option value="in_progress" {% if task.status == 'in_progress' %}selected{% endif %}>In Progress</option>
                <option value="blocked" {% if task.status == 'blocked' %}selected{% endif %}>Blocked</option>
                <option value="completed" {% if task.status == 'completed' %}selected{% endif %}>Completed</option>
              </select>
            </div>
            <div>
              <label class="mb-2 block text-sm font-medium text-slate-700">Work Remark / Block Reason</label>
              <input type="text" name="remarks" value="{{ task.remarks or '' }}" class="w-full rounded-xl border border-slate-300 px-4 py-2 text-sm" placeholder="Work performed, pending document or hold reason" {% if task.is_locked or (task.subscription and task.subscription.is_locked) %}disabled{% endif %}>
            </div>
          </div>

          {% set response_type = task.response_type or 'NONE' %}
          {% if response_type != 'NONE' or task.response_required %}
          <div class="rounded-2xl border border-indigo-200 bg-indigo-50 p-4">
            <div class="mb-4">
              <h4 class="font-semibold text-indigo-950">Checklist Response</h4>
              <p class="mt-1 text-xs text-indigo-700">Save a draft at any stage. Required controls are enforced when the task is marked Completed.</p>
            </div>

            {% if response_type in ['YES_NO_NA', 'YES_NO'] %}
            <div>
              <label class="mb-2 block text-sm font-medium text-slate-700">Response{% if task.response_required %} *{% endif %}</label>
              <select name="checklist_response" class="w-full rounded-xl border border-indigo-200 bg-white px-4 py-2 text-sm" {% if task.is_locked or (task.subscription and task.subscription.is_locked) %}disabled{% endif %}>
                <option value="">Select response</option>
                <option value="YES" {% if task.checklist_response == 'YES' %}selected{% endif %}>Yes</option>
                <option value="NO" {% if task.checklist_response == 'NO' %}selected{% endif %}>No</option>
                {% if response_type == 'YES_NO_NA' %}<option value="NA" {% if task.checklist_response == 'NA' %}selected{% endif %}>Not Applicable</option>{% endif %}
              </select>
            </div>
            {% elif response_type == 'TEXT' %}
            <div>
              <label class="mb-2 block text-sm font-medium text-slate-700">Text Response{% if task.response_required %} *{% endif %}</label>
              <textarea name="checklist_text_response" rows="4" class="w-full rounded-xl border border-indigo-200 bg-white px-4 py-2 text-sm" {% if task.is_locked or (task.subscription and task.subscription.is_locked) %}disabled{% endif %}>{{ task.checklist_text_response or '' }}</textarea>
            </div>
            {% elif response_type == 'NUMBER' %}
            <div>
              <label class="mb-2 block text-sm font-medium text-slate-700">Number Response{% if task.response_required %} *{% endif %}</label>
              <input type="number" step="any" name="checklist_number_response" value="{{ task.checklist_number_response if task.checklist_number_response is not none else '' }}" class="w-full rounded-xl border border-indigo-200 bg-white px-4 py-2 text-sm" {% if task.is_locked or (task.subscription and task.subscription.is_locked) %}disabled{% endif %}>
            </div>
            {% elif response_type == 'DATE' %}
            <div>
              <label class="mb-2 block text-sm font-medium text-slate-700">Date Response{% if task.response_required %} *{% endif %}</label>
              <input type="date" name="checklist_date_response" value="{{ task.checklist_date_response or '' }}" class="w-full rounded-xl border border-indigo-200 bg-white px-4 py-2 text-sm" {% if task.is_locked or (task.subscription and task.subscription.is_locked) %}disabled{% endif %}>
            </div>
            {% endif %}

            <div class="mt-4">
              <label class="mb-2 block text-sm font-medium text-slate-700">Checklist Remarks{% if task.remarks_required_if_no %} · mandatory for No{% endif %}</label>
              <textarea name="checklist_remarks" rows="4" class="w-full rounded-xl border border-indigo-200 bg-white px-4 py-2 text-sm" placeholder="Document conclusion, exception, NA rationale or follow-up" {% if task.is_locked or (task.subscription and task.subscription.is_locked) %}disabled{% endif %}>{{ task.checklist_remarks or '' }}</textarea>
            </div>
          </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 class="rounded-2xl border border-slate-200 bg-slate-50 p-4">
            <div class="flex flex-wrap items-center justify-between gap-3">
              <div>
                <h4 class="font-semibold text-slate-900">Evidence and Communication</h4>
                <p class="mt-1 text-sm text-slate-500">Use the existing document and timeline controls. Uploaded task documents remain linked to this task and engagement.</p>
              </div>
              <div class="flex flex-wrap gap-2">
                <a href="/documents/tasks/{{ task.id }}" class="rounded-xl border border-indigo-300 bg-white px-4 py-2 text-sm font-semibold text-indigo-700 hover:bg-indigo-50">Open Evidence</a>
                <a href="/employee/work/tasks/{{ task.id }}/communication" class="rounded-xl border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50">Communication Timeline{% if task.comment_count %} · {{ task.comment_count }}{% endif %}</a>
              </div>
            </div>
          </div>

          <div class="flex flex-wrap items-center justify-between gap-3 border-t border-slate-200 pt-5">
            <details class="w-full rounded-xl border border-amber-200 bg-amber-50 p-3 text-left">
              <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="3" maxlength="1000" required class="w-full rounded-xl border border-amber-300 bg-white px-3 py-2 text-sm" placeholder="Explain the dependency, ageing or review delay"></textarea>
                <button type="submit" class="rounded-xl border border-amber-300 bg-white px-4 py-2 text-sm font-semibold text-amber-900">Send Escalation</button>
              </form>
            </details>
            <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 Workspace</a>
            <div class="flex flex-wrap gap-2">
              <button type="submit" name="workflow_action" value="save" class="rounded-xl border border-brand-300 bg-white px-4 py-2 text-sm font-semibold text-brand-700 hover:bg-brand-50" {% if task.is_locked or (task.subscription and task.subscription.is_locked) %}disabled{% endif %}>Save</button>
              <button type="submit" name="workflow_action" value="save_next" class="rounded-xl bg-brand-600 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-50" {% if task.is_locked or (task.subscription and task.subscription.is_locked) %}disabled{% endif %}>Save &amp; Next</button>
            </div>
          </div>
        </form>
      </section>
      {% else %}
      <div class="rounded-2xl border border-dashed border-slate-300 bg-white p-10 text-center text-sm text-slate-500">No assigned workflow task is available.</div>
      {% endif %}

      <section class="rounded-2xl border border-slate-200 bg-white p-5 shadow-soft">
        <div class="flex 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 details 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>
    </main>
  </div>
</div>
{% endblock %}
