{% extends "base.html" %}

{% block title %}{{ project.human_key }} — Agent Mail{% endblock %}

{% block breadcrumbs %}
<nav class="flex items-center gap-2 text-sm">
  <a href="/mail" class="text-slate-600 dark:text-slate-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors flex items-center gap-1">
    <i data-lucide="home" class="w-3.5 h-3.5"></i>
    Projects
  </a>
  <i data-lucide="chevron-right" class="w-4 h-4 text-slate-400"></i>
  <span class="text-slate-900 dark:text-white font-medium">{{ project.human_key }}</span>
</nav>
{% endblock %}

{% block header_actions %}
<div class="flex items-center gap-3">
  <!-- Human Overseer - Primary Action -->
  <a href="/mail/{{ project.slug }}/overseer/compose"
     class="inline-flex items-center gap-2 px-4 py-2.5 bg-amber-500 hover:bg-amber-600 dark:bg-amber-600 dark:hover:bg-amber-700 text-white font-semibold rounded-lg shadow-sm hover:shadow-md transition-all duration-200"
     aria-label="Send high-priority message as Human Overseer">
    <i data-lucide="megaphone" class="w-4 h-4"></i>
    <span class="text-sm">Human Overseer</span>
  </a>

  <!-- Divider -->
  <div class="w-px h-8 bg-slate-200 dark:bg-slate-700"></div>

  <!-- Secondary Actions -->
  <div class="flex items-center gap-2">
    <!-- File Reservations -->
    <a href="/mail/{{ project.slug }}/file_reservations"
       class="inline-flex items-center gap-2 px-3 py-2 bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-300 font-medium rounded-lg border border-slate-200 dark:border-slate-700 shadow-sm hover:shadow-md transition-all duration-200"
       data-tippy-content="View file coordination signals"
       aria-label="File Reservations">
      <i data-lucide="file-lock" class="w-4 h-4"></i>
      <span class="text-sm">Reservations</span>
    </a>

    <!-- Attachments -->
    <a href="/mail/{{ project.slug }}/attachments"
       class="inline-flex items-center gap-2 px-3 py-2 bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-300 font-medium rounded-lg border border-slate-200 dark:border-slate-700 shadow-sm hover:shadow-md transition-all duration-200"
       data-tippy-content="View shared files"
       aria-label="Attachments">
      <i data-lucide="paperclip" class="w-4 h-4"></i>
      <span class="text-sm">Attachments</span>
    </a>
  </div>
</div>
{% endblock %}

{% block content %}
<div class="space-y-8 page-transition">
  <!-- Project Hero Header -->
  <div class="relative overflow-hidden bg-white dark:bg-slate-800 rounded-2xl p-6 shadow-soft border border-slate-200 dark:border-slate-700">
    <div class="flex items-start justify-between">
      <div class="flex-1">
        <div class="flex items-center gap-4 mb-4">
          <div class="w-16 h-16 bg-primary-600 rounded-xl flex items-center justify-center shadow-md">
            <i data-lucide="git-branch" class="w-8 h-8 text-white"></i>
          </div>
          <div>
            <h1 class="text-4xl font-bold text-slate-900 dark:text-white mb-2">
              {{ project.human_key }}
            </h1>
            <div class="flex items-center gap-3 text-sm">
              <div class="flex items-center gap-1.5 text-slate-600 dark:text-slate-400">
                <i data-lucide="hash" class="w-4 h-4"></i>
                <span class="font-mono">{{ project.slug }}</span>
              </div>
              <span class="text-slate-300 dark:text-slate-600">•</span>
              <div class="flex items-center gap-1.5 px-3 py-1 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 rounded-full font-medium text-xs">
                <span class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
                <span>Active</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Subtle accent -->
    <div class="absolute top-0 right-0 w-64 h-64 bg-gradient-to-br from-primary-500/5 to-purple-500/5 rounded-full blur-3xl pointer-events-none"></div>
  </div>

  <!-- Enhanced Search Section -->
  <div class="bg-white dark:bg-slate-800 rounded-2xl p-8 shadow-soft border border-slate-200 dark:border-slate-700"
       x-data="{ scope: {{ (scope or '')|tojson }}, order: {{ (order or 'relevance')|tojson }}, query: {{ (q or '')|tojson }}, isExpanded: {{ 'true' if (q is not none and q != '') else 'false' }} }">

    <div class="flex items-center justify-between mb-6">
      <div class="flex items-center gap-3">
        <div class="w-12 h-12 bg-primary-600 rounded-xl flex items-center justify-center shadow-md">
          <i data-lucide="search" class="w-6 h-6 text-white"></i>
        </div>
        <div>
          <h2 class="text-2xl font-bold text-slate-900 dark:text-white">Search Messages</h2>
          <p class="text-sm text-slate-600 dark:text-slate-400">Scan subjects and bodies from every message in this project.</p>
        </div>
      </div>
      <button @click="isExpanded = !isExpanded"
              class="px-4 py-2 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-300 rounded-lg transition-all duration-200 flex items-center gap-2"
              data-tippy-content="Toggle advanced search filters">
        <i x-show="!isExpanded" data-lucide="chevron-down" class="w-4 h-4" x-cloak></i>
        <i x-show="isExpanded" data-lucide="chevron-up" class="w-4 h-4" x-cloak></i>
        <span x-text="isExpanded ? 'Hide Advanced Filters' : 'Show Advanced Filters'" class="text-sm font-medium"></span>
      </button>
    </div>

    <div class="mb-4 space-y-2 text-sm text-slate-600 dark:text-slate-400">
      <p>By default we match both subject and body text. Add filters below to narrow the scope or change how results are ranked.</p>
      <p>
        <span class="font-semibold text-slate-700 dark:text-slate-200">Example:</span>
        <code class="px-2 py-1 bg-slate-100 dark:bg-slate-900 rounded text-xs font-mono border border-slate-300 dark:border-slate-700">urgent status update</code>
        &mdash; prioritizes messages whose subject or body mentions that phrase.
      </p>
    </div>

    <form method="get" action="/mail/{{ project.slug }}" class="space-y-6">
      <!-- Search Input -->
      <div class="relative group">
        <div class="absolute inset-y-0 left-0 pl-5 flex items-center pointer-events-none">
          <i data-lucide="search" class="w-5 h-5 text-slate-400 group-focus-within:text-primary-500 transition-colors"></i>
        </div>
        <input
          type="text"
          id="q"
          name="q"
          x-model="query"
          value="{{ q or '' }}"
          placeholder="Search by subject, body, or use filters like subject:keyword..."
          class="w-full pl-14 pr-4 py-4 bg-slate-50 dark:bg-slate-900 border-2 border-slate-200 dark:border-slate-700 focus:border-primary-500 dark:focus:border-primary-500 rounded-xl text-slate-900 dark:text-white placeholder-slate-500 dark:placeholder-slate-400 transition-all duration-200 font-medium"
          autocomplete="off"
          aria-label="Search project messages"
        />
        <input type="hidden" id="scope" name="scope" x-model="scope" />
        <input type="hidden" id="order" name="order" x-model="order" />

        <!-- Keyboard shortcut hint (cross-platform) -->
        <div class="absolute inset-y-0 right-0 pr-4 flex items-center pointer-events-none">
          <kbd class="hidden sm:inline-flex items-center gap-1 px-2 py-1 bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-400 text-xs font-mono rounded border border-slate-300 dark:border-slate-600" id="search-shortcut">
            <span class="shortcut-key">⌘</span><span>K</span>
          </kbd>
        </div>
      </div>

      <p class="text-xs text-slate-500 dark:text-slate-500">Tip: searches are case-insensitive and support phrases in quotes, e.g. <code class="px-1 py-0.5 bg-slate-100 dark:bg-slate-900 rounded border border-slate-200 dark:border-slate-700">"weekly sync"</code>.</p>

      <!-- Advanced Filters -->
      <div x-show="isExpanded" x-transition:enter="transition ease-out duration-200"
           x-transition:enter-start="opacity-0 transform -translate-y-2"
           x-transition:enter-end="opacity-100 transform translate-y-0"
           class="grid grid-cols-1 md:grid-cols-2 gap-6 p-6 bg-slate-50 dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-700">
        <!-- Scope Filters -->
        <div class="space-y-3">
          <label class="text-sm font-semibold text-slate-700 dark:text-slate-300 flex items-center gap-2">
            <i data-lucide="filter" class="w-4 h-4"></i>
            Choose where to search
          </label>
          <div class="flex flex-wrap gap-2">
            <button
              type="button"
              @click="scope = ''"
              :class="scope === '' ? 'bg-primary-600 text-white ring-2 ring-primary-500 ring-offset-2 dark:ring-offset-slate-900' : 'bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:border-primary-300 dark:hover:border-primary-700'"
              class="px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 flex items-center gap-2">
              <i data-lucide="align-justify" class="w-4 h-4"></i>
              Subject + body (default)
            </button>
            <button
              type="button"
              @click="scope = 'subject'"
              :class="scope === 'subject' ? 'bg-primary-600 text-white ring-2 ring-primary-500 ring-offset-2 dark:ring-offset-slate-900' : 'bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:border-primary-300 dark:hover:border-primary-700'"
              class="px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 flex items-center gap-2">
              <i data-lucide="heading" class="w-4 h-4"></i>
              Subject only
            </button>
            <button
              type="button"
              @click="scope = 'body'"
              :class="scope === 'body' ? 'bg-primary-600 text-white ring-2 ring-primary-500 ring-offset-2 dark:ring-offset-slate-900' : 'bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:border-primary-300 dark:hover:border-primary-700'"
              class="px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 flex items-center gap-2">
              <i data-lucide="file-text" class="w-4 h-4"></i>
              Body only
            </button>
          </div>
          <p class="text-xs text-slate-500 dark:text-slate-500">Limit matching to the subject line or body when you need a tighter query.</p>
        </div>

        <!-- Order Filters -->
        <div class="space-y-3">
          <label class="text-sm font-semibold text-slate-700 dark:text-slate-300 flex items-center gap-2">
            <i data-lucide="arrow-up-down" class="w-4 h-4"></i>
            Sort results
          </label>
          <div class="flex flex-wrap gap-2">
            <button
              type="button"
              @click="order = 'relevance'"
              :class="order === 'relevance' ? 'bg-primary-600 text-white ring-2 ring-primary-500 ring-offset-2 dark:ring-offset-slate-900' : 'bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:border-primary-300 dark:hover:border-primary-700'"
              class="px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 flex items-center gap-2">
              <i data-lucide="star" class="w-4 h-4"></i>
              Best match first
            </button>
            <button
              type="button"
              @click="order = 'time'"
              :class="order === 'time' ? 'bg-primary-600 text-white ring-2 ring-primary-500 ring-offset-2 dark:ring-offset-slate-900' : 'bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:border-primary-300 dark:hover:border-primary-700'"
              class="px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 flex items-center gap-2">
              <i data-lucide="clock" class="w-4 h-4"></i>
              Newest first
            </button>
          </div>
          <p class="text-xs text-slate-500 dark:text-slate-500">Switch to chronological sorting when you need the latest updates at the top.</p>
        </div>

        <!-- Additional Options -->
        <div class="md:col-span-2 flex items-center justify-between pt-4 border-t border-slate-200 dark:border-slate-700">
          <label class="flex items-center gap-3 cursor-pointer group">
            <input type="checkbox" id="boostSubject" name="boost" value="1"
                   class="w-4 h-4 text-primary-600 bg-white dark:bg-slate-800 border-slate-300 dark:border-slate-600 rounded focus:ring-2 focus:ring-primary-500 transition-all duration-200"
                   {% if boost %}checked{% endif %}>
            <span class="text-sm font-medium text-slate-700 dark:text-slate-300 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
              Prioritize subject matches in rankings
            </span>
          </label>

          <button
            type="submit"
            class="px-6 py-3 bg-gradient-to-r from-primary-600 to-primary-700 hover:from-primary-700 hover:to-primary-800 text-white font-semibold rounded-lg shadow-medium hover:shadow-large transition-all duration-300 flex items-center gap-2 btn-ripple">
            <i data-lucide="search" class="w-4 h-4"></i>
            <span>Search</span>
          </button>
        </div>
        <p class="md:col-span-2 text-xs text-slate-500 dark:text-slate-500">Subject prioritization nudges messages whose subject matches your query higher without hiding relevant body matches.</p>
      </div>
    </form>

    <!-- Search Results -->
    {% if results is defined and results %}
      <div class="mt-8 space-y-4">
        <div class="flex items-center justify-between">
          <h3 class="text-lg font-semibold text-slate-900 dark:text-white flex items-center gap-2">
            <i data-lucide="list-checks" class="w-5 h-5 text-primary-600 dark:text-primary-400"></i>
            Found <span class="text-primary-600 dark:text-primary-400">{{ results|length }}</span> result{{ 's' if results|length != 1 else '' }}
          </h3>
        </div>

        <div class="space-y-3">
          {% for r in results %}
            <a href="/mail/{{ project.slug }}/message/{{ r.id }}"
               class="block group bg-slate-50 dark:bg-slate-900 hover:bg-white dark:hover:bg-slate-800 rounded-xl p-5 border-2 border-slate-200 dark:border-slate-700 hover:border-primary-400 dark:hover:border-primary-600 transition-all duration-300 shadow-sm hover:shadow-md stagger-item"
               style="animation-delay: {{ [loop.index0 * 0.05, 1.0]|min }}s;">
              <div class="flex items-start justify-between mb-3">
                <h4 class="text-lg font-semibold text-slate-900 dark:text-white group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors line-clamp-1">
                  {{ r.subject }}
                </h4>
                {% if r.hits %}
                  <span class="px-3 py-1 bg-primary-100 dark:bg-primary-900/30 text-primary-700 dark:text-primary-300 text-xs font-bold rounded-full whitespace-nowrap ml-4">
                    {{ r.hits }} match{{ 'es' if r.hits != 1 else '' }}
                  </span>
                {% endif %}
              </div>

              <div class="flex items-center gap-4 text-sm text-slate-600 dark:text-slate-400 mb-3">
                <div class="flex items-center gap-1.5">
                  <i data-lucide="user" class="w-4 h-4"></i>
                  <span class="font-medium">{{ r.sender }}</span>
                </div>
                <span class="text-slate-300 dark:text-slate-600">•</span>
                <div class="flex items-center gap-1.5">
                  <i data-lucide="calendar" class="w-4 h-4"></i>
                  <span>{{ r.created }}</span>
                </div>
                {% if r.thread_id %}
                  <span class="text-slate-300 dark:text-slate-600">•</span>
                  <div class="flex items-center gap-1.5" data-tippy-content="Canonical thread identifier shared across agents" title="Canonical thread identifier shared across agents">
                    <i data-lucide="message-circle" class="w-4 h-4"></i>
                    <span class="text-xs uppercase tracking-wide text-slate-500 dark:text-slate-500">Thread</span>
                    <span class="font-mono text-xs">{{ r.thread_id }}</span>
                  </div>
                {% endif %}
              </div>

              {% if r.snippet %}
                <div class="text-sm text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-800 rounded-lg p-3 line-clamp-2 border border-slate-200 dark:border-slate-700">
                  {{ r.snippet | safe }}
                </div>
              {% endif %}
            </a>
          {% endfor %}
        </div>
      </div>
    {% elif results is defined %}
      <div class="mt-8 text-center py-12 bg-slate-50 dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-700">
        <div class="w-16 h-16 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mx-auto mb-4">
          <i data-lucide="search-x" class="w-8 h-8 text-slate-400"></i>
        </div>
        <h3 class="text-lg font-semibold text-slate-900 dark:text-white mb-2">No matching messages</h3>
        <p class="text-sm text-slate-600 dark:text-slate-400">No messages in this project match your search criteria. Try using different keywords, checking for typos, or broadening your search terms.</p>
      </div>
    {% endif %}
  </div>

  <!-- Agents Section -->
  <div>
    <div class="flex items-center justify-between mb-6">
      <div class="flex items-center gap-3">
        <div class="w-1 h-10 bg-gradient-to-b from-success-600 to-success-800 rounded-full"></div>
        <div>
          <h2 class="text-2xl font-bold text-slate-900 dark:text-white">Registered Agents</h2>
          <p class="text-sm text-slate-600 dark:text-slate-400">Active collaborators in this project</p>
        </div>
      </div>
      {% if agents %}
        <span class="px-4 py-2 bg-success-100 dark:bg-success-900/30 text-success-700 dark:text-success-300 text-sm font-bold rounded-full flex items-center gap-2">
          <span class="w-2 h-2 bg-success-500 rounded-full animate-pulse"></span>
          {{ agents|length }} active
        </span>
      {% endif %}
    </div>

    {% if agents %}
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
        {% for a in agents %}
          <div class="group relative bg-white dark:bg-slate-800 rounded-2xl p-6 shadow-soft border-2 border-slate-200 dark:border-slate-700 hover:border-success-400 dark:hover:border-success-600 transition-all duration-300 card-hover overflow-hidden stagger-item"
               style="animation-delay: {{ [loop.index0 * 0.05, 1.0]|min }}s;">

            <!-- Decorative gradient blob -->
            <div class="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-success-500/10 to-emerald-500/10 rounded-full blur-3xl group-hover:scale-150 transition-transform duration-500 pointer-events-none"></div>

            <!-- Agent Header -->
            <div class="relative flex items-center gap-4 mb-5">
              <div class="w-14 h-14 bg-gradient-to-br from-success-500 to-success-700 rounded-2xl flex items-center justify-center shadow-medium group-hover:shadow-glow group-hover:scale-110 transition-all duration-300">
                <i data-lucide="bot" class="w-7 h-7 text-white"></i>
              </div>
              <div class="flex-1 min-w-0">
                <h3 class="text-lg font-bold text-slate-900 dark:text-white truncate group-hover:text-success-600 dark:group-hover:text-success-400 transition-colors">
                  {{ a.name }}
                </h3>
                <div class="flex items-center gap-2 text-xs text-slate-600 dark:text-slate-400 mt-1">
                  <span class="truncate">{{ a.program }}</span>
                  <span class="text-slate-300 dark:text-slate-600">•</span>
                  <span class="truncate">{{ a.model }}</span>
                </div>
              </div>
            </div>

            <!-- Agent Actions -->
            <div class="relative flex items-center gap-2">
              <a href="/mail/{{ project.slug }}/inbox/{{ a.name }}"
                 class="flex-1 px-4 py-2.5 bg-gradient-to-r from-success-600 to-success-700 hover:from-success-700 hover:to-success-800 text-white text-sm font-semibold rounded-lg shadow-medium hover:shadow-large transition-all duration-300 text-center flex items-center justify-center gap-2 btn-ripple">
                <i data-lucide="inbox" class="w-4 h-4"></i>
                <span>Inbox</span>
              </a>
              <button onclick="copyToClipboard(this.dataset.agentName, 'Agent name copied!')"
                      data-agent-name="{{ a.name }}"
                      class="p-2.5 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-300 rounded-lg transition-all duration-200 shadow-sm hover:shadow-md"
                      data-tippy-content="Copy agent name"
                      aria-label="Copy agent name">
                <i data-lucide="copy" class="w-4 h-4"></i>
              </button>
            </div>
          </div>
        {% endfor %}
      </div>

    {% else %}
      <!-- Premium Empty State for Agents -->
      <div class="bg-gradient-to-br from-white to-slate-50 dark:from-slate-800 dark:to-slate-800/50 rounded-2xl p-16 shadow-soft border border-slate-200 dark:border-slate-700 text-center">
        <div class="relative inline-flex mb-6">
          <div class="absolute inset-0 flex items-center justify-center">
            <div class="w-32 h-32 bg-success-500/10 rounded-full animate-pulse"></div>
          </div>
          <div class="relative w-20 h-20 bg-gradient-to-br from-success-500 to-success-700 rounded-2xl flex items-center justify-center shadow-large float">
            <i data-lucide="user-plus" class="w-10 h-10 text-white"></i>
          </div>
        </div>

        <h3 class="text-2xl font-bold text-slate-900 dark:text-white mb-3">
          No agents registered yet
        </h3>
        <p class="text-slate-600 dark:text-slate-400 max-w-md mx-auto mb-6">
          Agents will appear here once they register with this project using the MCP tools.
        </p>

        <div class="inline-flex items-center gap-2 px-4 py-2 bg-slate-100 dark:bg-slate-800 rounded-lg text-sm text-slate-700 dark:text-slate-300">
          <i data-lucide="info" class="w-4 h-4"></i>
          <span>Use <code class="px-2 py-0.5 bg-white dark:bg-slate-900 rounded font-mono text-xs">register_agent</code> to add agents</span>
        </div>
      </div>
    {% endif %}
  </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', () => {
    // Update keyboard shortcut display based on platform (with modern API fallback)
    const shortcutKey = document.querySelector('.shortcut-key');
    if (shortcutKey) {
      // Use modern API if available, fall back to legacy navigator.platform / userAgent
      const platform = (navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || '';
      const ua = navigator.userAgent || '';
      const isMac = /mac/i.test(platform) || /mac|iphone|ipad|ipod/i.test(ua);

      if (!isMac) {
        shortcutKey.textContent = 'Ctrl';
      }
    }

    // Debounced search - disabled by default to avoid too many requests
    // Uncomment the form.submit() line below to enable auto-search as you type
    const form = document.querySelector('form');
    const input = document.getElementById('q');
    let timeout;

    input?.addEventListener('input', () => {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        if (input.value.length >= 3) {
          // Uncomment to enable live search (searches after 3+ characters)
          // form.submit();
        }
      }, 800);
    });
  });
</script>
{% endblock %}
