<?php $comments = !empty($comments) ? array_reverse($comments) : []; ?>
<div id="comments-timeline" class="gateway-card">
  <p class="gateway-label" style="margin-bottom:1rem">Comment Timeline</p>

  <?php
  $visible = [];
  foreach ($comments as $c) {
    $text = trim($c['text'] ?? '');
    $type = $c['type'] ?? 'comment';
    $name = $c['created_by']['name'] ?? 'System';
    if ($text === '' || $type !== 'comment' || strtolower($name) === 'system') continue;
    $visible[] = $c;
  }
  ?>

  <?php if (!empty($visible)): ?>
  <div style="max-height:32rem;overflow-y:auto;padding-right:.25rem">
    <?php
    $bgPalette = [
      ['#4f46e5','#e0e7ff'], ['#16a34a','#dcfce7'], ['#d97706','#fef3c7'],
      ['#dc2626','#fee2e2'], ['#7c3aed','#f3e8ff'], ['#db2777','#fce7f3'],
      ['#0891b2','#cffafe'],
    ];
    foreach ($visible as $c):
      $text     = trim($c['text'] ?? '');
      $name     = $c['created_by']['name'] ?? 'System';
      $is_guest        = stripos($text, '[guest]') === 0;
      $is_guest_upload = !$is_guest && stripos($text, 'Guest upload:') === 0;
      $upload_filename = $is_guest_upload ? trim(substr($text, strlen('Guest upload:'))) : '';
      $clean    = $is_guest ? trim(str_ireplace('[guest]', '', $text)) : $text;
      $time     = date('M j, Y g:i a', strtotime($c['created_at']));
      $parts    = preg_split('/\s+/u', trim($name));
      $initials = mb_strtoupper(mb_substr($parts[0] ?? 'U',0,1) . (isset($parts[1]) ? mb_substr(end($parts),0,1) : ''));
      [$avatarBg, $avatarRing] = $bgPalette[abs(crc32($name)) % count($bgPalette)];

      // Parse guest name, email, and body from "[Guest] *Name* (email) wrote:\n\nbody"
      $guest_display_name  = '';
      $guest_display_email = '';
      $message_body        = $clean;
      if ($is_guest) {
        if (preg_match('/^\*([^*]+)\*\s*\(([^)]+)\)\s*wrote:\s*/is', $clean, $gm)) {
          $guest_display_name  = trim($gm[1]);
          $guest_display_email = trim($gm[2]);
          $message_body        = trim(substr($clean, strlen($gm[0])));
        } elseif (preg_match('/^\*([^*]+)\*\s*wrote:\s*/is', $clean, $gm)) {
          $guest_display_name  = trim($gm[1]);
          $message_body        = trim(substr($clean, strlen($gm[0])));
        } elseif (preg_match('/^\(([^)]+)\)\s*wrote:\s*/is', $clean, $gm)) {
          $guest_display_email = trim($gm[1]);
          $message_body        = trim(substr($clean, strlen($gm[0])));
        } elseif (preg_match('/^\*\s*\*\s*\(\s*\)\s*wrote:\s*/is', $clean, $gm)) {
          $message_body = trim(substr($clean, strlen($gm[0])));
        } elseif (preg_match('/^wrote:\s*/is', $clean, $gm)) {
          $message_body = trim(substr($clean, strlen($gm[0])));
        }
      }

      $formatted_html = $is_guest
          ? nl2br(esc_html($message_body))
          : ($is_guest_upload
              ? ''
              : ($c['html_text'] ?? nl2br(esc_html($clean))));
      if (!$is_guest && !$is_guest_upload) {
        $formatted_html = preg_replace_callback(
          '/<a ([^>]*?href="([^"]+?)"[^>]*)>(.*?)<\/a>/i',
          fn($m) => '<a ' . $m[1] . ' style="color:#4f46e5;font-weight:600;text-decoration:underline">' . esc_html($m[3]) . '</a>',
          $formatted_html
        );
      }
    ?>
    <div class="gateway-comment">
      <div class="gateway-comment-avatar" style="background:<?= $avatarBg ?>;box-shadow:0 0 0 2px <?= $avatarRing ?>"><?= esc_html($initials) ?></div>
      <div class="gateway-comment-bubble<?= ($is_guest || $is_guest_upload) ? ' is-guest' : '' ?>" style="flex:1">

        <?php if ($is_guest_upload): ?>
          <!-- Guest upload header -->
          <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:.5rem;margin-bottom:.6rem">
            <div style="display:flex;align-items:center;gap:.5rem">
              <span style="font-size:.625rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;background:#dcfce7;color:#15803d;padding:.15rem .5rem;border-radius:9999px">Guest Upload</span>
            </div>
            <span style="font-size:.6875rem;color:#94a3b8;white-space:nowrap;padding-top:.1rem"><?= esc_html($time) ?></span>
          </div>
          <div style="border-top:1px solid #e0e7ff;margin-bottom:.6rem"></div>

        <?php elseif ($is_guest): ?>
          <!-- Guest comment header -->
          <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:.5rem;margin-bottom:.6rem">
            <div>
              <div style="display:flex;align-items:center;gap:.5rem;margin-bottom:.3rem">
                <span style="font-size:.625rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;background:#dbeafe;color:#1d4ed8;padding:.15rem .5rem;border-radius:9999px">Guest Comment</span>
              </div>
              <?php if ($guest_display_name): ?>
                <p style="font-size:.8125rem;font-weight:600;color:#1e293b;margin:0 0 .15rem"><?= esc_html($guest_display_name) ?></p>
              <?php endif; ?>
              <?php if ($guest_display_email): ?>
                <p style="font-size:.75rem;color:#64748b;margin:0">
                  <a href="mailto:<?= esc_attr($guest_display_email) ?>" style="color:#2563eb;text-decoration:none"><?= esc_html($guest_display_email) ?></a>
                </p>
              <?php endif; ?>
            </div>
            <span style="font-size:.6875rem;color:#94a3b8;white-space:nowrap;padding-top:.1rem"><?= esc_html($time) ?></span>
          </div>
          <div style="border-top:1px solid #e0e7ff;margin-bottom:.6rem"></div>

        <?php else: ?>
          <!-- Staff comment header -->
          <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:.5rem;margin-bottom:.35rem">
            <span style="font-size:.8125rem;font-weight:600;color:#1e293b"><?= esc_html($name) ?></span>
            <span style="font-size:.6875rem;color:#94a3b8;white-space:nowrap;margin-left:auto"><?= esc_html($time) ?></span>
          </div>
        <?php endif; ?>

        <?php if ($is_guest_upload): ?>
          <div style="display:flex;align-items:center;gap:.5rem;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:.375rem;padding:.5rem .75rem">
            <svg xmlns="http://www.w3.org/2000/svg" style="width:1rem;height:1rem;color:#15803d;flex-shrink:0" 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>
            <span style="font-size:.8125rem;color:#15803d;font-weight:500;word-break:break-all"><?= esc_html($upload_filename) ?></span>
          </div>
        <?php else: ?>
          <div style="font-size:.875rem;color:#334155;line-height:1.65"><?= wp_kses_post($formatted_html) ?></div>
        <?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php else: ?>
    <div style="text-align:center;padding:2.5rem 1rem">
      <div style="width:2.75rem;height:2.75rem;background:#f1f5f9;border-radius:9999px;display:flex;align-items:center;justify-content:center;margin:0 auto .75rem">
        <svg xmlns="http://www.w3.org/2000/svg" style="width:1.25rem;height:1.25rem;color:#94a3b8" 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>
      </div>
      <p style="font-size:.875rem;color:#94a3b8">No comments yet.</p>
    </div>
  <?php endif; ?>
</div>
