{% extends "base.html" %}

{% block title %}Send Message — Human Overseer{% 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>
  <a href="/mail/{{ project.slug }}" class="text-slate-600 dark:text-slate-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors">
    {{ project.human_key }}
  </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">Human Overseer</span>
</nav>
{% endblock %}

{% block content %}
<div class="max-w-4xl mx-auto space-y-6 page-transition pb-12" x-data="overseerComposer()" x-init="init()" @keydown.ctrl.enter="sendMessage()" @keydown.meta.enter="sendMessage()">

  <!-- Clean Professional Header -->
  <div class="mb-6">
    <h1 class="text-3xl font-semibold text-slate-900 dark:text-white mb-2">Send Message as Human Overseer</h1>
    <p class="text-slate-600 dark:text-slate-400">
      Send high-priority instructions directly to your agents. Messages are automatically marked as urgent.
    </p>
  </div>

  <!-- Subtle Info Notice -->
  <div class="bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-900 rounded-lg p-4">
    <div class="flex items-start gap-3">
      <i data-lucide="info" class="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5"></i>
      <div class="text-sm text-blue-900 dark:text-blue-100">
        <p class="font-medium mb-1">How Human Overseer messages work</p>
        <p class="text-blue-700 dark:text-blue-300">Agents receive your message with a preamble indicating human guidance. They'll pause current work to prioritize your request, then resume their original tasks.</p>
      </div>
    </div>
  </div>

  <!-- Main Composer Form -->
  <form @submit.prevent="sendMessage()" class="space-y-6">

    <!-- Recipients Section -->
    <div class="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
      <!-- Section Header -->
      <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700">
        <div class="flex items-center justify-between">
          <div>
            <h2 class="text-lg font-semibold text-slate-900 dark:text-white">
              Recipients
              <span class="ml-2 text-sm font-normal" :class="selectedRecipients.length > 100 ? 'text-red-600 dark:text-red-400' : 'text-slate-500 dark:text-slate-400'">
                (<span x-text="selectedRecipients.length"></span> of 100 max)
              </span>
            </h2>
            <p class="text-sm text-slate-600 dark:text-slate-400 mt-1">Select which agents should receive this message</p>
          </div>

          <!-- Quick actions -->
          <div class="flex items-center gap-2">
            <button type="button" @click="selectAll()"
                    class="px-3 py-1.5 text-xs font-medium text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-md transition-colors">
              Select All
            </button>
            <button type="button" @click="selectNone()"
                    class="px-3 py-1.5 text-xs font-medium text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-md transition-colors">
              Clear
            </button>
          </div>
        </div>

        <!-- Search bar for recipients (if many agents) -->
        <div x-show="agents.length > 6" class="mt-4">
          <div class="relative">
            <i data-lucide="search" class="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400"></i>
            <input type="text" x-model="recipientSearch"
                   placeholder="Search agents..."
                   class="w-full pl-10 pr-4 py-2 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all"
                   aria-label="Search agents">
          </div>
        </div>
      </div>

      <!-- Recipients Grid -->
      <div class="p-6">
        {% if agents %}
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
            {% for agent in agents %}
              <label x-show="!recipientSearch || '{{ agent.name|replace('\\', '\\\\')|replace("'", "\\'") }}'.toLowerCase().includes(recipientSearch.toLowerCase())"
                     class="flex items-center gap-3 p-3 bg-slate-50 dark:bg-slate-900/50 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-700 cursor-pointer transition-colors"
                     :class="selectedRecipients.includes('{{ agent.name|replace('\\', '\\\\')|replace("'", "\\'") }}') ? 'ring-2 ring-primary-500 bg-primary-50 dark:bg-primary-900/20' : ''">
                <input type="checkbox"
                       value="{{ agent.name }}"
                       x-model="selectedRecipients"
                       class="w-4 h-4 text-primary-600 bg-white dark:bg-slate-700 border-slate-300 dark:border-slate-600 rounded focus:ring-2 focus:ring-primary-500" />
                <i data-lucide="bot" class="w-4 h-4 text-slate-600 dark:text-slate-400"></i>
                <span class="text-sm font-medium text-slate-900 dark:text-white truncate flex-1">{{ agent.name }}</span>
              </label>
            {% endfor %}
          </div>

          <!-- No search results -->
          <div x-show="recipientSearch && filteredRecipientsCount() === 0" x-transition class="text-center py-8">
            <i data-lucide="search-x" class="w-12 h-12 text-slate-300 dark:text-slate-600 mx-auto mb-3"></i>
            <p class="text-sm font-medium text-slate-600 dark:text-slate-400 mb-1">No matching agents</p>
            <p class="text-xs text-slate-500 dark:text-slate-500">No agent names match your search query</p>
          </div>

        {% else %}
          <div class="text-center py-12">
            <i data-lucide="user-x" class="w-16 h-16 text-slate-300 dark:text-slate-600 mx-auto mb-4"></i>
            <h3 class="text-lg font-semibold text-slate-900 dark:text-white mb-2">No Agents Registered</h3>
            <p class="text-sm text-slate-600 dark:text-slate-400 mb-4">
              No agents are currently registered in this project.
            </p>
            <a href="/mail/{{ project.slug }}"
               class="inline-flex items-center gap-2 px-4 py-2 bg-slate-900 dark:bg-white text-white dark:text-slate-900 hover:bg-slate-800 dark:hover:bg-slate-100 rounded-lg text-sm font-medium transition-colors">
              <i data-lucide="arrow-left" class="w-4 h-4"></i>
              Back to Project
            </a>
          </div>
        {% endif %}
      </div>
    </div>

    <!-- Message Composer Section -->
    <div class="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
      <!-- Section Header -->
      <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700">
        <div class="flex items-center justify-between">
          <div>
            <h2 class="text-lg font-semibold text-slate-900 dark:text-white">Message Content</h2>
            <p class="text-sm text-slate-600 dark:text-slate-400 mt-1">Compose your message in GitHub-flavored Markdown</p>
          </div>

          <!-- View mode toggle -->
          <div class="flex items-center gap-1 p-0.5 bg-slate-100 dark:bg-slate-900 rounded-lg">
            <button type="button" @click="viewMode = 'write'"
                    class="px-3 py-1.5 text-xs font-medium rounded-md transition-all flex items-center gap-1.5"
                    :class="viewMode === 'write' ? 'bg-white dark:bg-slate-800 shadow-sm text-slate-900 dark:text-white' : 'text-slate-600 dark:text-slate-400'">
              <i data-lucide="edit-3" class="w-3.5 h-3.5"></i>
              Write
            </button>
            <button type="button" @click="viewMode = 'preview'"
                    class="px-3 py-1.5 text-xs font-medium rounded-md transition-all flex items-center gap-1.5"
                    :class="viewMode === 'preview' ? 'bg-white dark:bg-slate-800 shadow-sm text-slate-900 dark:text-white' : 'text-slate-600 dark:text-slate-400'">
              <i data-lucide="eye" class="w-3.5 h-3.5"></i>
              Preview
            </button>
            <button type="button" @click="viewMode = 'split'"
                    class="px-3 py-1.5 text-xs font-medium rounded-md transition-all flex items-center gap-1.5"
                    :class="viewMode === 'split' ? 'bg-white dark:bg-slate-800 shadow-sm text-slate-900 dark:text-white' : 'text-slate-600 dark:text-slate-400'">
              <i data-lucide="columns" class="w-3.5 h-3.5"></i>
              Split
            </button>
          </div>
        </div>
      </div>

      <div class="p-6 space-y-4">
        <!-- Subject Line -->
        <div>
          <label for="subject" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
            Subject <span class="text-red-500">*</span>
          </label>
          <input type="text"
                 id="subject"
                 x-model="subject"
                 required
                 maxlength="200"
                 placeholder="e.g., Urgent: Review security vulnerability"
                 class="w-full px-4 py-2.5 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg text-slate-900 dark:text-white placeholder-slate-400 focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all" />
          <p class="mt-1.5 text-xs text-slate-500 dark:text-slate-500">
            <span x-text="subject.length"></span> / 200 characters
          </p>
        </div>

        <!-- Message Body -->
        <div x-show="viewMode === 'write' || viewMode === 'split'" x-transition>
          <label for="body" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
            Message Body <span class="text-red-500">*</span>
          </label>

          <!-- Markdown Toolbar -->
          <div class="flex flex-wrap items-center gap-0.5 p-1.5 bg-slate-100 dark:bg-slate-900 rounded-t-lg border border-b-0 border-slate-200 dark:border-slate-700">
            <button type="button" @click="insertMarkdown('**', '**', 'bold text')"
                    class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 rounded transition-colors" title="Bold" aria-label="Insert bold text">
              <i data-lucide="bold" class="w-4 h-4 text-slate-600 dark:text-slate-400"></i>
            </button>
            <button type="button" @click="insertMarkdown('*', '*', 'italic text')"
                    class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 rounded transition-colors" title="Italic" aria-label="Insert italic text">
              <i data-lucide="italic" class="w-4 h-4 text-slate-600 dark:text-slate-400"></i>
            </button>
            <button type="button" @click="insertMarkdown('`', '`', 'code')"
                    class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 rounded transition-colors" title="Code" aria-label="Insert inline code">
              <i data-lucide="code" class="w-4 h-4 text-slate-600 dark:text-slate-400"></i>
            </button>
            <div class="w-px h-5 bg-slate-300 dark:bg-slate-600 mx-1"></div>
            <button type="button" @click="insertMarkdown('## ', '', 'Heading')"
                    class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 rounded transition-colors" title="Heading" aria-label="Insert heading">
              <i data-lucide="heading" class="w-4 h-4 text-slate-600 dark:text-slate-400"></i>
            </button>
            <button type="button" @click="insertList('- ', 'List item')"
                    class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 rounded transition-colors" title="List" aria-label="Insert list">
              <i data-lucide="list" class="w-4 h-4 text-slate-600 dark:text-slate-400"></i>
            </button>
            <button type="button" @click="insertMarkdown('[', '](url)', 'link text')"
                    class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 rounded transition-colors" title="Link" aria-label="Insert link">
              <i data-lucide="link" class="w-4 h-4 text-slate-600 dark:text-slate-400"></i>
            </button>
            <button type="button" @click="insertMarkdown('```\n', '\n```', 'code block')"
                    class="p-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 rounded transition-colors" title="Code Block" aria-label="Insert code block">
              <i data-lucide="file-code" class="w-4 h-4 text-slate-600 dark:text-slate-400"></i>
            </button>
            <div class="flex-1"></div>
            <span class="text-xs text-slate-500 dark:text-slate-400">
              <kbd class="px-1.5 py-0.5 bg-slate-200 dark:bg-slate-700 rounded text-xs font-mono">Ctrl+Enter</kbd> to send
            </span>
          </div>

          <textarea id="body"
                    x-ref="bodyTextarea"
                    x-model="body"
                    @input="updatePreview()"
                    required
                    maxlength="49600"
                    rows="14"
                    placeholder="Write your message here using Markdown...

Example:
## Action Required

Please investigate the following:
- Check database connections
- Review error logs
- Report back with findings

**Deadline:** End of day"
                    class="w-full px-4 py-3 bg-slate-50 dark:bg-slate-900 border border-t-0 border-slate-200 dark:border-slate-700 rounded-b-lg text-slate-900 dark:text-white placeholder-slate-400 font-mono text-sm focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all resize-none"></textarea>

          <p class="mt-1.5 text-xs text-slate-500 dark:text-slate-500">
            <span x-text="body.length.toLocaleString()"></span> / 49,600 characters • Supports Markdown formatting
          </p>
        </div>

        <!-- Live Preview -->
        <div x-show="viewMode === 'preview' || viewMode === 'split'" x-transition>
          <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Preview</label>
          <div class="p-4 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg min-h-[300px] max-h-[500px] overflow-y-auto">
            <div x-html="renderedPreview" class="prose prose-sm dark:prose-invert max-w-none"></div>
            <div x-show="!body" class="flex items-center justify-center h-48 text-slate-400">
              <p class="text-sm">Your message preview will appear here</p>
            </div>
          </div>
        </div>

        <!-- Thread ID (Optional) -->
        <div>
          <label for="threadId" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
            Thread ID <span class="text-xs font-normal text-slate-500">(Optional)</span>
          </label>
          <input type="text"
                 id="threadId"
                 x-model="threadId"
                 placeholder="e.g., 42 or custom-thread-id"
                 class="w-full px-4 py-2.5 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg text-slate-900 dark:text-white placeholder-slate-400 font-mono text-sm focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all" />
          <p class="mt-1.5 text-xs text-slate-500 dark:text-slate-500">
            Leave blank to start a new conversation
          </p>
        </div>
      </div>
    </div>

    <!-- Preamble Preview (subtle) -->
    <div class="bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg p-4">
      <div class="flex items-start gap-3 mb-3">
        <i data-lucide="eye" class="w-5 h-5 text-slate-600 dark:text-slate-400 flex-shrink-0 mt-0.5"></i>
        <div>
          <h3 class="text-sm font-medium text-slate-900 dark:text-white mb-1">Automatic Preamble</h3>
          <p class="text-xs text-slate-600 dark:text-slate-400">This preamble will be automatically prepended to your message</p>
        </div>
      </div>
      <div class="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg p-4 text-xs space-y-2">
        <p class="font-semibold text-slate-900 dark:text-white">🚨 MESSAGE FROM HUMAN OVERSEER</p>
        <p class="text-slate-700 dark:text-slate-300">This message is from a human operator overseeing this project. Please prioritize the instructions below over your current tasks.</p>
        <p class="text-slate-600 dark:text-slate-400">You should: 1) Temporarily pause your current work, 2) Complete the request described below, 3) Resume your original plans afterward (unless modified by these instructions).</p>
        <p class="text-slate-600 dark:text-slate-400 font-medium">The human's guidance supersedes all other priorities.</p>
      </div>
    </div>

    <!-- Actions (NOT sticky, properly in flow) -->
    <div class="flex items-center justify-between gap-4 pt-2">
      <a href="/mail/{{ project.slug }}"
         class="inline-flex items-center gap-2 px-4 py-2.5 text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg text-sm font-medium transition-colors">
        <i data-lucide="arrow-left" class="w-4 h-4"></i>
        Cancel
      </a>

      <button type="submit"
              :disabled="!canSend()"
              class="inline-flex items-center gap-2 px-6 py-2.5 bg-slate-900 dark:bg-white text-white dark:text-slate-900 hover:bg-slate-800 dark:hover:bg-slate-100 rounded-lg shadow-sm font-medium transition-all disabled:opacity-50 disabled:cursor-not-allowed"
              :class="sending ? 'cursor-wait' : ''">
        <svg x-show="sending" class="animate-spin w-4 h-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        <i x-show="!sending" data-lucide="send" class="w-4 h-4"></i>
        <span x-text="sending ? 'Sending...' : 'Send to ' + selectedRecipients.length + ' agent' + (selectedRecipients.length !== 1 ? 's' : '')">Send Message</span>
      </button>
    </div>
  </form>

  <!-- Success/Error Toast -->
  <template x-if="showToast">
    <div x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0 transform translate-y-4"
         x-transition:enter-end="opacity-100 transform translate-y-0"
         class="fixed bottom-6 right-6 z-[100] max-w-md">
      <div :class="toastType === 'success' ? 'bg-green-600' : 'bg-red-600'"
           class="rounded-lg p-4 shadow-xl text-white flex items-start gap-3">
        <i :data-lucide="toastType === 'success' ? 'check-circle' : 'alert-circle'" class="w-5 h-5 flex-shrink-0"></i>
        <div class="flex-1 min-w-0">
          <h4 class="font-semibold mb-0.5" x-text="toastTitle"></h4>
          <p class="text-sm opacity-90" x-text="toastMessage"></p>
        </div>
        <button @click="showToast = false" class="text-white/80 hover:text-white transition-colors">
          <i data-lucide="x" class="w-5 h-5"></i>
        </button>
      </div>
    </div>
  </template>

  <!-- Send Confirmation Modal -->
  <template x-if="showConfirmModal">
    <div class="fixed inset-0 z-[150] flex items-center justify-center p-4"
         @click.self="showConfirmModal = false"
         @keydown.escape.window="showConfirmModal = false">
      <div x-show="showConfirmModal"
           x-transition:enter="transition ease-out duration-200"
           x-transition:enter-start="opacity-0"
           x-transition:enter-end="opacity-100"
           class="absolute inset-0 bg-slate-900/50 backdrop-blur-sm"></div>

      <div x-show="showConfirmModal"
           x-transition:enter="transition ease-out duration-300"
           x-transition:enter-start="opacity-0 scale-95"
           x-transition:enter-end="opacity-100 scale-100"
           x-init="$nextTick(() => $el.querySelector('button[type=button]:last-of-type').focus())"
           @keydown.tab.prevent="trapModalFocus($event)"
           class="relative w-full max-w-md bg-white dark:bg-slate-800 rounded-xl shadow-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">

        <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700">
          <h3 class="text-lg font-semibold text-slate-900 dark:text-white">Confirm Send</h3>
          <p class="text-sm text-slate-600 dark:text-slate-400 mt-1">Review your message before sending</p>
        </div>

        <div class="p-6 space-y-3">
          <div class="flex items-center justify-between text-sm">
            <span class="text-slate-600 dark:text-slate-400">Recipients:</span>
            <span class="font-medium text-slate-900 dark:text-white" x-text="selectedRecipients.length + ' agent' + (selectedRecipients.length !== 1 ? 's' : '')"></span>
          </div>
          <div class="flex items-start justify-between text-sm gap-3">
            <span class="text-slate-600 dark:text-slate-400 flex-shrink-0">Subject:</span>
            <span class="font-medium text-slate-900 dark:text-white text-right" x-text="subject"></span>
          </div>
          <div class="flex items-center justify-between text-sm">
            <span class="text-slate-600 dark:text-slate-400">Priority:</span>
            <span class="px-2 py-0.5 bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 text-xs font-medium rounded">High</span>
          </div>

          <div class="p-3 bg-amber-50 dark:bg-amber-900/20 rounded-lg border border-amber-200 dark:border-amber-800 mt-4">
            <p class="text-xs text-amber-900 dark:text-amber-100">
              <strong>Important:</strong> Agents will pause their current work to address this message.
            </p>
          </div>
        </div>

        <div class="px-6 py-4 bg-slate-50 dark:bg-slate-900 flex items-center justify-end gap-3 border-t border-slate-200 dark:border-slate-700">
          <button @click="showConfirmModal = false" type="button"
                  class="px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-lg transition-colors">
            Cancel
          </button>
          <button @click="confirmSend()" type="button"
                  :disabled="sending"
                  class="px-4 py-2 text-sm font-medium bg-slate-900 dark:bg-white text-white dark:text-slate-900 hover:bg-slate-800 dark:hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
            Confirm & Send
          </button>
        </div>
      </div>
    </div>
  </template>
</div>

<script>
function overseerComposer() {
  return {
    agents: [{% for agent in agents %}{{ agent.name | tojson }}{% if not loop.last %}, {% endif %}{% endfor %}],
    selectedRecipients: [],
    subject: '',
    body: '',
    threadId: '',
    recipientSearch: '',
    viewMode: 'write',
    renderedPreview: '',
    sending: false,
    showToast: false,
    showConfirmModal: false,
    toastType: 'success',
    toastTitle: '',
    toastMessage: '',

    init() {
      this.updatePreview();
      this.$nextTick(() => {
        if (typeof lucide !== 'undefined') {
          lucide.createIcons();
        }
      });
    },

    selectAll() {
      this.selectedRecipients = [...this.agents];
    },

    selectNone() {
      this.selectedRecipients = [];
    },

    filteredRecipientsCount() {
      if (!this.recipientSearch) return this.agents.length;
      const search = this.recipientSearch.toLowerCase();
      return this.agents.filter(name => name.toLowerCase().includes(search)).length;
    },

    canSend() {
      return this.selectedRecipients.length > 0 &&
             this.selectedRecipients.length <= 100 &&
             this.subject.trim() &&
             this.subject.length <= 200 &&
             this.body.trim() &&
             this.body.length <= 49600 &&
             !this.sending;
    },

    insertMarkdown(before, after, placeholder) {
      const textarea = this.$refs.bodyTextarea;
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const selectedText = this.body.substring(start, end);
      const replacement = selectedText || placeholder;

      this.body = this.body.substring(0, start) + before + replacement + after + this.body.substring(end);

      this.$nextTick(() => {
        const newCursorPos = start + before.length + replacement.length;
        textarea.focus();
        textarea.setSelectionRange(newCursorPos, newCursorPos);
        this.updatePreview();
      });
    },

    insertList(prefix, placeholder) {
      const textarea = this.$refs.bodyTextarea;
      const start = textarea.selectionStart;
      const lineStart = this.body.lastIndexOf('\n', start - 1) + 1;

      this.body = this.body.substring(0, lineStart) + prefix + (placeholder || '') + this.body.substring(start);

      this.$nextTick(() => {
        const newCursorPos = lineStart + prefix.length + (placeholder || '').length;
        textarea.focus();
        textarea.setSelectionRange(newCursorPos, newCursorPos);
        this.updatePreview();
      });
    },

    updatePreview() {
      if (typeof marked !== 'undefined') {
        try {
          // Parse markdown to HTML
          const rawHtml = marked.parse(this.body || '_No content yet..._');

          // Sanitize HTML to prevent XSS (self-XSS protection)
          if (typeof DOMPurify !== 'undefined') {
            this.renderedPreview = DOMPurify.sanitize(rawHtml);
          } else {
            // Fallback if DOMPurify fails to load
            this.renderedPreview = rawHtml;
            console.warn('DOMPurify not loaded - preview may contain unsanitized HTML');
          }

          this.$nextTick(() => {
            if (typeof Prism !== 'undefined') {
              Prism.highlightAll();
            }
          });
        } catch (e) {
          this.renderedPreview = '<p class="text-red-500">Error rendering markdown preview</p>';
        }
      }
    },

    async sendMessage() {
      if (!this.canSend()) return;
      this.showConfirmModal = true;
    },

    async confirmSend() {
      // CRITICAL: Guard against double-clicks during modal transition or network request
      // Without this, rapid clicks during the 300ms x-transition can send duplicate messages
      if (this.sending) return;

      this.showConfirmModal = false;
      this.sending = true;

      try {
        // Use properly escaped project slug for URL safety
        const projectSlug = {{ project.slug | tojson }};
        const response = await fetch(`/mail/${projectSlug}/overseer/send`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            recipients: this.selectedRecipients,
            subject: this.subject.trim(),
            body_md: this.body.trim(),
            thread_id: this.threadId.trim() || null,
          })
        });

        if (!response.ok) {
          const error = await response.json().catch(() => ({}));
          throw new Error(error.detail || error.error || `Server error: ${response.status}`);
        }

        this.toastType = 'success';
        this.toastTitle = 'Message Sent Successfully';
        this.toastMessage = `Delivered to ${this.selectedRecipients.length} agent${this.selectedRecipients.length !== 1 ? 's' : ''}`;
        this.showToast = true;

        setTimeout(() => {
          window.location.href = `/mail/${projectSlug}`;
        }, 2000);

      } catch (error) {
        console.error('Failed to send message:', error);
        this.toastType = 'error';
        this.toastTitle = 'Failed to Send Message';
        this.toastMessage = error.message || 'An unexpected error occurred. Please try again.';
        this.showToast = true;

        // Reset sending state ONLY on error so user can retry
        // On success, we keep sending=true to prevent duplicate sends during 2s redirect
        this.sending = false;

        setTimeout(() => {
          this.showToast = false;
        }, 6000);
      } finally {
        // Don't reset sending here - on success we're about to redirect anyway
        // On error, it's already reset in catch block above
        if (typeof lucide !== 'undefined') {
          try {
            lucide.createIcons();
          } catch (e) {
            console.warn('Failed to render icons:', e);
          }
        }
      }
    },

    trapModalFocus(event) {
      // Get all focusable elements within the modal
      const focusableSelectors = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
      const modal = event.currentTarget;
      const focusableElements = modal.querySelectorAll(focusableSelectors);

      if (focusableElements.length === 0) return;

      const firstElement = focusableElements[0];
      const lastElement = focusableElements[focusableElements.length - 1];

      // If shift+tab on first element, wrap to last
      if (event.shiftKey && document.activeElement === firstElement) {
        lastElement.focus();
      }
      // If tab on last element, wrap to first
      else if (!event.shiftKey && document.activeElement === lastElement) {
        firstElement.focus();
      }
      // Otherwise allow default tab behavior within the modal
      else {
        event.preventDefault();
        const currentIndex = Array.from(focusableElements).indexOf(document.activeElement);

        // Edge case: if focus somehow escaped the modal, recover by focusing first element
        if (currentIndex === -1) {
          firstElement.focus();
          return;
        }

        const nextIndex = event.shiftKey ? currentIndex - 1 : currentIndex + 1;
        if (nextIndex >= 0 && nextIndex < focusableElements.length) {
          focusableElements[nextIndex].focus();
        }
      }
    }
  };
}
</script>
{% endblock %}
