<?php
// task-comms/pages/task-dashboard.php for CC-DEV

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once dirname(__DIR__) . '/functions.php';

/**
 * Strongly discourage page caching for gateway pages
 */
if (!defined('DONOTCACHEPAGE')) define('DONOTCACHEPAGE', true);
if (!defined('DONOTCACHEDB')) define('DONOTCACHEDB', true);
if (!defined('DONOTMINIFY')) define('DONOTMINIFY', true);
if (function_exists('nocache_headers')) nocache_headers();
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

/**
 * Resolve token (be resilient if query_var is missing)
 */
$token =
    get_query_var('asana_comms_token')
    ?? ($_GET['asana_comms_token'] ?? null);

if (!$token) {
    // Fallback: parse from /task-dashboard/{token} if needed
    $uri = (string)($_SERVER['REQUEST_URI'] ?? '');
    if (preg_match('~/task-dashboard/([a-f0-9]{12,64})~i', $uri, $m)) {
        $token = $m[1];
    }
}

$token             = $token ? sanitize_text_field($token) : '';
$asana_comms_token = $token;

/**
 * Token -> Task mapping
 */
$task_gid = $token ? afb_get_task_id_by_token($token) : '';

// NOTE: Task completion no longer auto-closes the gateway.
// Gateway stays open for client feedback, then closes after feedback submission.
// afb_maybe_expire_gateway_if_completed() is only called after feedback is submitted.

/**
 * Expired / invalid branch
 * We tailor messaging if:
 * - a reason transient was set during refresh invalidation, OR
 * - the URL carries a signed task_gid + key (HMAC) so we can probe Asana safely
 */
if (!$token || !$task_gid) {

    $reason = '';
    if ($token) {
        $reason = (string) get_transient("afb_token_reason_{$token}");
    }

    $signed_task_gid = sanitize_text_field($_GET['task_gid'] ?? '');
    $signed_key      = sanitize_text_field($_GET['key'] ?? '');

    $can_probe = ($signed_task_gid && ctype_digit($signed_task_gid) && $signed_key);

    // Only probe if the signature is valid (prevents using this page as an oracle)
    if (!$reason && $can_probe) {
        $expected = hash_hmac('sha256', $signed_task_gid, AUTH_SALT);

        if (hash_equals($expected, $signed_key)) {

            $asana_token = get_option('asana_access_token');

            if ($asana_token) {
                $probe_url = "https://app.asana.com/api/1.0/tasks/{$signed_task_gid}?opt_fields=gid";

                $rsp = wp_remote_get($probe_url, [
                    'headers' => ['Authorization' => "Bearer {$asana_token}"],
                    'timeout' => 8,
                ]);

                if (!is_wp_error($rsp)) {
                    $code = (int) wp_remote_retrieve_response_code($rsp);

                    // Deleted / access removed (treat as non-recoverable)
                    if (in_array($code, [403, 404, 410], true)) {
                        $reason = 'deleted';
                        if ($token) {
                            set_transient("afb_token_reason_{$token}", 'deleted', DAY_IN_SECONDS);
                        }
                    }
                }
            }
        }
    }

    $is_deleted            = ($reason === 'deleted');
    $is_feedback_submitted = ($reason === 'feedback_submitted');
    $is_completed          = ($reason === 'completed');

    header('Content-Type: text/html; charset=utf-8'); ?>
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Client Gateway</title>
      <script src="https://cdn.tailwindcss.com"></script>
    </head>
    <body class="bg-zinc-50 min-h-screen flex items-center justify-center font-sans text-gray-900">
      <div class="bg-white border border-zinc-200 rounded-xl max-w-xl w-full p-8 text-center shadow-sm">

        <div class="mx-auto mb-4 flex h-10 w-10 items-center justify-center rounded-lg bg-red-50 ring-1 ring-red-100">
          <svg viewBox="0 0 24 24" class="h-5 w-5 text-red-700" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M12 9v4m0 4h.01M10.29 3.86l-7.4 12.82A2 2 0 004.62 20h14.76a2 2 0 001.73-3.32l-7.4-12.82a2 2 0 00-3.42 0z"/>
          </svg>
        </div>

        <h2 class="text-xl font-semibold text-zinc-900 mb-2">
          <?= $is_deleted
              ? 'This Client Gateway is no longer available'
              : ($is_feedback_submitted
                  ? 'This Client Gateway is now closed'
                  : ($is_completed
                      ? 'This Client Gateway is closed'
                      : 'This Client Gateway link has expired')); ?>
        </h2>

        <?php if ($is_deleted) : ?>
          <p class="text-sm text-zinc-700 mb-2">
            The Asana task for this link was deleted or you no longer have access.
          </p>
          <p class="text-sm text-zinc-600">
            Please contact Strategic Communications Branch if you need any further information.
          </p>
        <?php elseif ($is_feedback_submitted) : ?>
          <p class="text-sm text-zinc-700 mb-2">
            Thank you for your feedback. This Client Gateway is now closed.
          </p>
          <p class="text-sm text-zinc-600">
            If you need our team to investigate anything further for this task, please refer to the original task emails.
          </p>
        <?php elseif ($is_completed) : ?>
          <p class="text-sm text-zinc-700 mb-2">
            This request has been marked complete in Asana, so the Client Gateway has been closed.
          </p>
          <p class="text-sm text-zinc-600">
            Use the Create Client Gateway link on the Asana task if a new gateway is required.
          </p>
        <?php else : ?>
          <p class="text-sm text-zinc-700 mb-2">
            The link you are trying to access is no longer valid.
          </p>
          <p class="text-sm text-zinc-600">
            Please return to the Asana task, delete the old Client Gateway link, and click <strong>Create Client Gateway</strong> again.
          </p>
        <?php endif; ?>

      </div>
    </body>
    </html>
<?php
    exit;
}

/*
 * PIN gate for public gateway access
 */
$pin_error = '';
if ($token && function_exists('afb_gateway_has_pin') && afb_gateway_has_pin($token)) {
    $is_authorized = function_exists('afb_gateway_pin_is_authorized')
        ? afb_gateway_pin_is_authorized($token)
        : false;

    if (!$is_authorized && function_exists('afb_gateway_verify_magic_link')) {
        $magic_signature = sanitize_text_field((string) ($_GET['ml'] ?? ''));
        $magic_expires = (int) ($_GET['ml_exp'] ?? 0);

        if (
            $magic_signature !== ''
            && $magic_expires > 0
            && afb_gateway_verify_magic_link($token, (string) $task_gid, $magic_signature, $magic_expires)
        ) {
            if (function_exists('afb_gateway_pin_clear_failures')) {
                afb_gateway_pin_clear_failures($token);
            }
            if (function_exists('afb_gateway_pin_mark_authorized')) {
                afb_gateway_pin_mark_authorized($token);
            }

            $redirect_url = remove_query_arg(['ml', 'ml_exp']);
            wp_safe_redirect($redirect_url);
            exit;
        }
    }

    if (!$is_authorized) {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['afb_gateway_pin_submit'])) {
            $posted_pin = sanitize_text_field((string) ($_POST['gateway_pin'] ?? ''));

            if (function_exists('afb_gateway_pin_is_locked') && afb_gateway_pin_is_locked($token)) {
                $pin_error = 'Too many incorrect attempts. Please wait 15 minutes and try again.';
            } elseif (function_exists('afb_gateway_verify_pin') && afb_gateway_verify_pin($token, $posted_pin)) {
                if (function_exists('afb_gateway_pin_clear_failures')) {
                    afb_gateway_pin_clear_failures($token);
                }
                if (function_exists('afb_gateway_pin_mark_authorized')) {
                    afb_gateway_pin_mark_authorized($token);
                }

                wp_safe_redirect($_SERVER['REQUEST_URI']);
                exit;
            } else {
                if (function_exists('afb_gateway_pin_record_failure')) {
                    afb_gateway_pin_record_failure($token);
                }
                $pin_error = 'Incorrect PIN. Please try again.';
            }
        }

        header('Content-Type: text/html; charset=utf-8'); ?>
        <!doctype html>
        <html lang="en">
        <head>
          <meta charset="utf-8">
          <title>Client Gateway PIN</title>
          <script src="https://cdn.tailwindcss.com"></script>
        </head>
        <body class="bg-zinc-50 min-h-screen flex items-center justify-center font-sans text-gray-900">
          <div class="bg-white border border-zinc-200 rounded-xl max-w-md w-full p-8 shadow-sm">
            <h2 class="text-xl font-semibold text-zinc-900 mb-2">Enter Client Gateway PIN</h2>
            <p class="text-sm text-zinc-600 mb-5">This request is protected. Enter the PIN shared in your gateway email.</p>

            <?php if (!empty($pin_error)) : ?>
              <div class="mb-4 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                <?= esc_html($pin_error) ?>
              </div>
            <?php endif; ?>

            <form method="post" autocomplete="off">
              <label for="gateway_pin" class="block text-sm font-medium text-zinc-700 mb-1">Gateway PIN</label>
              <input
                id="gateway_pin"
                name="gateway_pin"
                type="password"
                inputmode="numeric"
                pattern="[0-9]*"
                maxlength="12"
                class="w-full rounded-md border border-zinc-300 px-3 py-2 text-sm mb-4 focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              >

              <button
                type="submit"
                name="afb_gateway_pin_submit"
                value="1"
                class="w-full rounded-md bg-blue-700 text-white py-2.5 text-sm font-medium hover:bg-blue-800 transition"
              >
                Continue
              </button>
            </form>
          </div>
        </body>
        </html>
<?php
        exit;
    }
}

$tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'task';

/**
 * Cache helpers — CC-DEV improvement:
 * - Read from ALL supported cache locations (prevents false "missing" when path differs)
 * - Do NOT delete token on cache miss (allow recovery via Refresh)
 */
if (!function_exists('afb__cache_paths_for_token')) {
    function afb__cache_paths_for_token($tok) {
        $root = defined('AFB_PLUGIN_DIR')
            ? trailingslashit(AFB_PLUGIN_DIR)
            : trailingslashit(dirname(__DIR__, 3)); // pages -> task-comms -> includes -> plugin root

        return array_unique([
            $root . 'cache/tasks-summary-' . $tok . '.json',
            $root . 'includes/cache/tasks-summary-' . $tok . '.json',
            $root . 'includes/task-comms/cache/tasks-summary-' . $tok . '.json',
            trailingslashit(dirname(__DIR__, 2)) . 'cache/tasks-summary-' . $tok . '.json',
        ]);
    }
}

if (!function_exists('afb__read_cache_for_token')) {
    function afb__read_cache_for_token($tok) {
        foreach (afb__cache_paths_for_token($tok) as $p) {
            if (is_readable($p)) {
                $raw = @file_get_contents($p);
                if ($raw !== false) {
                    $data = json_decode($raw, true);
                    if (is_array($data) && !empty($data)) {
                        return $data;
                    }
                }
            }
        }
        return [];
    }
}

/**
 * Load cached snapshot
 * Wrapper key written by generator: parent/task
 */
$cached    = afb__read_cache_for_token($token);
$task_data = $cached['parent'] ?? $cached['task'] ?? $cached;

/**
 * Refresh URL: rebuild cache then reload
 */
$refresh_url = esc_url(add_query_arg(
    ['token' => $token, 'force' => 1],
    home_url('/wp-content/plugins/asana-form-builder/tools/generate-dashboard-summary.php')
));
$auto_refresh_gateway = !empty($_GET['refresh']) || !empty($_GET['autorefresh']);

/**
 * If cache missing/corrupt — show recover page with Refresh that rebuilds + reloads
 */
if (empty($task_data) || !is_array($task_data)) {
    header('Content-Type: text/html; charset=utf-8'); ?>
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Dashboard Data Unavailable</title>
      <script src="https://cdn.tailwindcss.com"></script>
    </head>
    <body class="bg-zinc-50 min-h-screen flex items-center justify-center font-sans text-gray-900">
      <div class="bg-white border border-red-200 rounded-xl w-full max-w-md px-6 py-8 text-center shadow-sm">
        <h2 class="text-xl font-semibold text-red-700 mb-2">Dashboard data is missing</h2>
        <p class="text-sm text-gray-700 mb-4">The cached snapshot could not be found. You can rebuild it now.</p>

        <button id="afb-refresh-missing"
                type="button"
                class="inline-flex bg-white border items-center gap-2 px-4 py-2 text-sm font-medium rounded-md transition hover:bg-blue-50 border-gray-300">
          <span class="afb-label">Refresh & Reload</span>
        </button>

        <p class="text-xs text-gray-500 mt-4">
          If this task was deleted or access was removed, rebuilding will expire this gateway automatically.
        </p>
      </div>

      <script>
      (function(){
        var btn = document.getElementById('afb-refresh-missing');
        if (!btn) return;

        var label = btn.querySelector('.afb-label');
        var orig = label ? label.textContent : 'Refresh & Reload';
        var url = <?= json_encode($refresh_url, JSON_UNESCAPED_SLASHES); ?>;

        function setState(t, dis){
          if (label) label.textContent = t;
          btn.disabled = !!dis;
          btn.classList.toggle('cursor-wait', !!dis);
          btn.classList.toggle('opacity-60', !!dis);
        }

        btn.addEventListener('click', function(){
          setState('Rebuilding...', true);

          fetch(url + '&ts=' + Date.now(), { credentials: 'same-origin', cache: 'no-store' })
            .then(function(){ window.location.reload(); })
            .catch(function(){
              setState('Error, try again', false);
              setTimeout(function(){ setState(orig, false); }, 1600);
            });
        });
      })();
      </script>
    </body>
    </html>
<?php
    exit;
}

/**
 * Build quick index of custom fields
 */
$field_index = [];
foreach ($task_data['custom_fields'] ?? [] as $f) {
    if (!empty($f['name'])) $field_index[$f['name']] = $f;
}

/**
 * Titles / meta (purely from cache)
 */
$request_title   = $task_data['name'] ?? afb_get_request_title_by_token($token) ?? '(Untitled)';
$primary_project = $task_data['projects'][0]['name'] ?? '';
$due_date        = $task_data['due_on'] ?? null;
$assignee        = $task_data['assignee']['name'] ?? 'Unassigned';
$created_at      = $task_data['created_at'] ?? '';
$modified_at     = $task_data['modified_at'] ?? '';
$job_number      = '';
$job_field_candidates = ['Job Number (SCB)', 'Job Number (COPFM)', 'Job Number'];

foreach ($job_field_candidates as $candidate) {
  if (!empty($field_index[$candidate])) {
    $job_num_field = $field_index[$candidate];
    $job_number = (string)($job_num_field['text_value'] ?? $job_num_field['number_value'] ?? '');
    if ($job_number !== '') {
      break;
    }
  }
}

if ($job_number === '') {
  foreach ($task_data['custom_fields'] ?? [] as $cf) {
    $cf_name = strtolower(trim((string)($cf['name'] ?? '')));
    if ($cf_name === '' || strpos($cf_name, 'job number') === false) {
      continue;
    }

    $job_number = (string)($cf['text_value'] ?? $cf['number_value'] ?? '');
    if ($job_number !== '') {
      break;
    }
  }
}

/**
 * Followers
 */
$followers = implode(', ', array_map(
    fn($f) => $f['name'] ?? '',
    $task_data['followers'] ?? []
));

/**
 * Extract submitted fields (ignore “Triage Summary”)
 */
$submitted_fields = [];
$submitter_name   = '';
$submitter_email  = '';
$submitter_first_name = '';
$submitter_last_name = '';

foreach ($task_data['custom_fields'] ?? [] as $field) {
    $label = $field['name'] ?? '';
  if (!$label || strtolower($label) === 'triage summary' || strtolower($label) === 'client gateway pin (scb)') continue;

    $value = match ($field['type'] ?? '') {
        'text'       => $field['text_value'] ?? '',
        'number'     => $field['number_value'] ?? '',
        'enum'       => $field['enum_value']['name'] ?? '',
        'multi_enum' => !empty($field['multi_enum_values'])
            ? array_map(fn($v) => $v['name'] ?? '', $field['multi_enum_values'])
            : '',
        default      => '',
    };

    if ($value === '' || $value === []) continue;

    $submitted_fields[$label] = $value;
}

  if (function_exists('afb_get_submitter_identity_from_task')) {
    $resolved_identity = afb_get_submitter_identity_from_task($task_data);
    $submitter_first_name = (string) ($resolved_identity['first_name'] ?? '');
    $submitter_last_name = (string) ($resolved_identity['last_name'] ?? '');

    if (!empty($resolved_identity['name'])) {
      $submitter_name = (string) $resolved_identity['name'];
    }

    if (!empty($resolved_identity['email'])) {
      $submitter_email = (string) $resolved_identity['email'];
    }
  }

/**
 * Check task completion and feedback status
 * If task is completed but feedback not yet submitted, show feedback form
 */
$task_is_completed = !empty($task_data['completed']);
$feedback_submitted = $task_is_completed && afb_has_feedback_submission($task_data);
$show_feedback_only = $task_is_completed && !$feedback_submitted;

get_header(); ?>
<style> body { background-color: #f8fafc !important; } </style>

<div id="afb-root">

  <!-- Global loading overlay -->
  <div id="afb-loading-overlay"
       class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/70">
    <div class="text-center">
      <svg class="animate-spin h-8 w-8 text-white mx-auto mb-3" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
      </svg>
      <p class="text-sm font-medium" style="color:rgba(255,255,255,0.85)">Loading&hellip;</p>
    </div>
  </div>

  <!-- ═══════════════════════════════════════════════════════ -->
  <!-- HERO HEADER                                            -->
  <!-- ═══════════════════════════════════════════════════════ -->
  <?php if (!$show_feedback_only): ?>
  <header class="gateway-hero">
    <div class="max-w-6xl mx-auto px-4 sm:px-6 pt-8 pb-0">

      <!-- Brand row + Refresh -->
      <div class="flex items-start justify-between gap-4 mb-5">

        <div class="flex items-center gap-2 flex-wrap min-w-0">
          <!-- Icon -->
          <div class="w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0"
              style="background:#e0f2fe;border:1px solid #bae6fd">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" style="color:#0369a1"
                 fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
              <path stroke-linecap="round" stroke-linejoin="round"
                    d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25z" />
            </svg>
          </div>
          <span class="text-xs font-bold uppercase"
                style="color:#0f172a;letter-spacing:0.12em">Client Gateway</span>
          <?php if ($primary_project): ?>
            <span style="color:#cbd5e1">&middot;</span>
            <span class="text-xs truncate"
                  style="color:#64748b;max-width:20rem"><?= esc_html($primary_project) ?></span>
          <?php endif; ?>
        </div>

        <div class="flex items-center gap-2">
          <?php if (!empty($task_data['gid'])): ?>
            <a href="https://app.asana.com/0/0/<?= esc_attr($task_data['gid']) ?>"
               target="_blank"
               class="gateway-asana-btn gateway-asana-btn--header">
              <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" viewBox="0 0 24 24" fill="currentColor" style="flex-shrink:0">
                <path d="M11.93 14.69A2.76 2.76 0 109.17 11.93a2.76 2.76 0 002.76 2.76zm5.77-2.76a2.76 2.76 0 102.76 2.76 2.76 2.76 0 00-2.76-2.76zM7 17.45a2.76 2.76 0 10-2.76 2.76A2.76 2.76 0 007 17.45z"/>
              </svg>
              View in Asana
            </a>
          <?php endif; ?>

          <button id="afb-refresh" type="button" class="gateway-btn-ghost flex-shrink-0">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none"
                 viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" style="flex-shrink:0">
              <path stroke-linecap="round" stroke-linejoin="round"
                    d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
            </svg>
            <span class="afb-label">Refresh</span>
          </button>
        </div>

      </div><!-- /brand row -->

      <!-- Task title -->
      <h1 class="font-bold leading-tight mb-4"
          style="color:#0f172a;font-size:clamp(1.25rem,3.5vw,1.875rem);padding-right:3rem">
        <?= esc_html($request_title) ?>
      </h1>

      <!-- Meta chips -->
      <?php
        $status_name   = $field_index['Status (SCB)']['enum_value']['name'] ?? '';
        $status_cfg = [
          'Completed'   => ['rgba(52,211,153,0.14)',  'rgba(52,211,153,0.35)',  '#6ee7b7'],
          'In Progress' => ['rgba(96,165,250,0.14)',  'rgba(96,165,250,0.35)',  '#93c5fd'],
          'On Hold'     => ['rgba(251,191,36,0.14)',  'rgba(251,191,36,0.35)',  '#fde68a'],
          'Cancelled'   => ['rgba(248,113,113,0.14)', 'rgba(248,113,113,0.35)','#fca5a5'],
        ];
      ?>
      <div class="flex flex-wrap items-center gap-2 mb-7">

        <?php if ($job_number): ?>
          <span class="gateway-chip-gold"># <?= esc_html($job_number) ?></span>
        <?php endif; ?>

        <?php if ($status_name):
          [$sBg, $sBorder, $sText] = $status_cfg[$status_name] ?? ['rgba(148,163,184,0.14)', 'rgba(148,163,184,0.35)', '#94a3b8'];
        ?>
          <span class="gateway-chip"
                style="background:<?= $sBg ?>;border-color:<?= $sBorder ?>;color:<?= $sText ?>">
            <span style="width:.5rem;height:.5rem;border-radius:9999px;background:currentColor;opacity:.8;display:inline-block;flex-shrink:0"></span>
            <?= esc_html($status_name) ?>
          </span>
        <?php endif; ?>

        <?php if ($due_date): ?>
          <span class="gateway-chip">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none"
                 viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"
                 style="opacity:.7;flex-shrink:0">
              <path stroke-linecap="round" stroke-linejoin="round"
                    d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5"/>
            </svg>
            Due <?= esc_html(date_i18n('M j, Y', strtotime($due_date))) ?>
          </span>
        <?php endif; ?>

        <span class="gateway-chip">
            <span class="w-4 h-4 rounded-full flex items-center justify-center text-[9px] font-bold"
                  style="background:rgba(0,133,195,.55);color:white;flex-shrink:0">
              <?php
                $a_parts = preg_split('/\s+/u', trim($assignee));
                echo esc_html(mb_strtoupper(mb_substr($a_parts[0] ?? 'U', 0, 1) . (count($a_parts) > 1 ? mb_substr(end($a_parts), 0, 1) : '')));
              ?>
            </span>
            <span style="opacity:.65;font-size:.7rem">Assigned:</span>
          <?= esc_html($assignee) ?>
        </span>

      </div><!-- /meta chips -->

      <!-- Tab navigation -->
      <nav class="gateway-tabs-nav" role="tablist">
        <?php
          $tabs = [
            'task'     => ['Task Overview',
              '<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25z"/></svg>'],
            'comments' => ['Comments',
              '<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M8.625 12a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H8.25m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H12m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0h-.375M21 12c0 4.556-4.03 8.25-9 8.25a9.764 9.764 0 01-2.555-.337A5.972 5.972 0 015.41 20.97a5.969 5.969 0 01-.474-.065 4.48 4.48 0 00.978-2.025c.09-.457-.133-.901-.467-1.226C3.93 16.178 3 14.189 3 12c0-4.556 4.03-8.25 9-8.25s9 3.694 9 8.25z"/></svg>'],
            'uploads'  => ['Uploads',
              '<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13"/></svg>'],
            'subtasks' => ['Subtasks',
              '<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M8.25 6.75h12M8.25 12h12m-12 5.25h12M3.75 6.75h.007v.008H3.75V6.75zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zM3.75 12h.007v.008H3.75V12zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm-.375 5.25h.007v.008H3.75v-.008zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"/></svg>'],
            'timeline' => ['Gantt Chart',
              '<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z"/></svg>'],
            'settings' => ['Settings',
              '<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>'],
          ];

          foreach ($tabs as $key => [$label, $icon]) {
            $url = add_query_arg(['asana_comms_token' => $token, 'tab' => $key]);
            echo '<a data-afb-nav href="' . esc_url($url) . '" class="gateway-tab ' . ($tab === $key ? 'active' : '') . '" role="tab">'
               . $icon . '<span>' . esc_html($label) . '</span></a>';
          }
        ?>
      </nav><!-- /tabs -->

    </div>
  </header><!-- /gateway-hero -->
  <?php endif; ?>

  <!-- ═══════════════════════════════════════════════════════ -->
  <!-- MAIN CONTENT                                           -->
  <!-- ═══════════════════════════════════════════════════════ -->
  <main class="max-w-6xl mx-auto px-4 sm:px-6 <?= $show_feedback_only ? 'py-6' : 'py-8' ?>">

    <?php
      // If task completed but feedback not submitted, show feedback form only
      if ($show_feedback_only) {
        include plugin_dir_path(__FILE__) . '../partials/layout/feedback-form.php';
      } elseif ($feedback_submitted) {
        // Task completed and feedback submitted - show thank you
        include plugin_dir_path(__FILE__) . '../partials/layout/feedback-thanks.php';
      } elseif ($tab === 'task') {

          include plugin_dir_path(__FILE__) . '../partials/layout/overview-details.php';

      } elseif ($tab === 'comments') {

          $comments = afb_get_asana_task_comments($task_gid);

          echo '<div class="flex flex-col lg:flex-row gap-6 items-start">';
            echo '<div class="w-full lg:w-3/5 order-2 lg:order-1">';
              include plugin_dir_path(__FILE__) . '../partials/layout/comments-timeline.php';
            echo '</div>';
            echo '<div class="w-full lg:w-2/5 order-1 lg:order-2">';
              include plugin_dir_path(__FILE__) . '../partials/layout/comment-form.php';
            echo '</div>';
          echo '</div>';

      } elseif ($tab === 'uploads') {

          $attachments = afb_get_asana_task_attachments($task_gid);

          echo '<div class="flex flex-col lg:flex-row gap-6 items-start">';
            echo '<div id="afb-attachments-panel" class="w-full lg:w-3/5 order-2 lg:order-1">';
              include plugin_dir_path(__FILE__) . '../partials/layout/attachments.php';
            echo '</div>';
            echo '<div class="w-full lg:w-2/5 order-1 lg:order-2">';
              include plugin_dir_path(__FILE__) . '../partials/layout/upload-attachments.php';
            echo '</div>';
          echo '</div>';

      } elseif ($tab === 'subtasks') {

          $parent_task_gid = $task_gid;
          include plugin_dir_path(__FILE__) . '../partials/layout/subtasks.php';

      } elseif ($tab === 'timeline') {

          $parent_task_gid = $task_gid;
          include plugin_dir_path(__FILE__) . '../partials/layout/timeline.php';

      } elseif ($tab === 'settings') {

          include plugin_dir_path(__FILE__) . '../partials/layout/settings.php';

      }
    ?>

  </main>
</div><!-- /#afb-root -->

<script>
(function(){
  var overlay = document.getElementById('afb-loading-overlay');

  document.querySelectorAll('a[data-afb-nav]').forEach(function(a){
    a.addEventListener('click', function(){
      if (!overlay) return;
      overlay.classList.remove('hidden');
    });
  });

  var btn = document.getElementById('afb-refresh');
  var labelEl = btn ? btn.querySelector('.afb-label') : null;
  var orig = labelEl ? labelEl.textContent : 'Refresh';
  var url  = <?= json_encode($refresh_url, JSON_UNESCAPED_SLASHES); ?>;
  var autoRefreshRequested = <?= json_encode((bool)$auto_refresh_gateway); ?>;

  function setState(text, disabled) {
    if (labelEl) labelEl.textContent = text;
    if (!btn) return;
    btn.disabled = !!disabled;
    btn.classList.toggle('cursor-wait', !!disabled);
    btn.classList.toggle('opacity-60', !!disabled);
  }

  function runRefresh(isAuto) {
    if (!isAuto) {
      setState('Refreshing\u2026', true);
    }

    fetch(url + '&ts=' + Date.now(), { credentials: 'same-origin', cache: 'no-store' })
      .then(function(res){
        if (res && (res.status === 410 || res.status === 404 || res.status === 403)) {
          window.location.reload();
          return;
        }
        if (!res.ok) throw new Error('HTTP ' + res.status);
        if (isAuto) {
          window.location.reload();
          return;
        }
        setState('Done \u2713', false);
        setTimeout(function(){ window.location.reload(); }, 350);
      })
      .catch(function(){
        if (isAuto) {
          window.location.reload();
          return;
        }
        setState('Error', false);
        setTimeout(function(){ setState(orig, false); }, 1600);
      });
  }

  if (btn) {
    btn.addEventListener('click', function(){
      runRefresh(false);
    });
  }

  if (autoRefreshRequested) {
    try {
      var current = new URL(window.location.href);
      current.searchParams.delete('refresh');
      current.searchParams.delete('autorefresh');
      if (window.history && window.history.replaceState) {
        window.history.replaceState({}, '', current.toString());
      }
    } catch (e) {
      // no-op
    }
    runRefresh(true);
  }
})();
</script>

<?php get_footer(); ?>
