{% extends "base.html" %}

{% block title %}{{ message.subject }} — 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">
    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 truncate max-w-xs">{{ message.subject }}</span>
</nav>
{% endblock %}

{% block header_actions %}
<div class="flex items-center gap-2">
  <button disabled
          class="px-4 py-2 text-sm font-medium text-slate-400 dark:text-slate-500 bg-slate-100 dark:bg-slate-800 rounded-lg flex items-center gap-2 opacity-60 cursor-not-allowed relative"
          data-tippy-content="Coming soon - Reply to this message"
          aria-label="Reply (Coming Soon)">
    <i data-lucide="reply" class="w-4 h-4"></i>
    Reply
    <span class="absolute -top-1 -right-1 px-1 py-0.5 bg-amber-500 text-white text-[9px] font-bold rounded-full shadow-sm">Soon</span>
  </button>
  <button disabled
          class="px-4 py-2 text-sm font-medium text-slate-400 dark:text-slate-500 bg-slate-100 dark:bg-slate-800 rounded-lg flex items-center gap-2 opacity-60 cursor-not-allowed relative"
          data-tippy-content="Coming soon - Forward this message"
          aria-label="Forward (Coming Soon)">
    <i data-lucide="forward" class="w-4 h-4"></i>
    Forward
    <span class="absolute -top-1 -right-1 px-1 py-0.5 bg-amber-500 text-white text-[9px] font-bold rounded-full shadow-sm">Soon</span>
  </button>
</div>
{% endblock %}

{% block content %}
<div class="space-y-6 animate-fade-in">
  <!-- Message Header Card -->
  <div class="bg-white dark:bg-slate-800 rounded-xl p-8 shadow-soft border border-slate-200 dark:border-slate-700">
    <!-- Subject -->
    <div class="mb-6">
      <div class="flex items-start justify-between gap-4 mb-3">
        <h1 class="text-3xl font-bold text-slate-900 dark:text-white">
          {{ message.subject }}
        </h1>

        <!-- Importance Badge -->
        {% if message.importance == 'urgent' %}
          <span class="px-3 py-1.5 bg-danger-100 dark:bg-danger-900/30 text-danger-700 dark:text-danger-300 text-sm font-semibold rounded-full flex items-center gap-1.5 badge-pulse">
            <i data-lucide="alert-circle" class="w-4 h-4"></i>
            Urgent
          </span>
        {% elif message.importance == 'high' %}
          <span class="px-3 py-1.5 bg-warning-100 dark:bg-warning-900/30 text-warning-700 dark:text-warning-300 text-sm font-semibold rounded-full flex items-center gap-1.5">
            <i data-lucide="alert-triangle" class="w-4 h-4"></i>
            High Priority
          </span>
        {% elif message.importance == 'low' %}
          <span class="px-3 py-1.5 bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400 text-sm font-medium rounded-full">
            Low Priority
          </span>
        {% endif %}
      </div>

      <!-- Metadata -->
      <div class="flex items-center gap-6 text-sm text-slate-600 dark:text-slate-400 flex-wrap">
        <div class="flex items-center gap-2">
          <i data-lucide="user" class="w-4 h-4"></i>
          <span class="font-medium text-slate-900 dark:text-white">{{ message.sender }}</span>
        </div>
        <div class="flex items-center gap-2">
          <i data-lucide="calendar" class="w-4 h-4"></i>
          <span>{{ message.created }}</span>
        </div>
        {% if message.thread_id %}
          <a href="/mail/{{ project.slug }}/thread/{{ message.thread_id }}"
             class="inline-flex items-center gap-2 px-3 py-1.5 bg-primary-100 dark:bg-primary-900/30 hover:bg-primary-200 dark:hover:bg-primary-800/40 text-primary-700 dark:text-primary-300 rounded-lg transition-all duration-200 font-medium">
            <i data-lucide="messages-square" class="w-4 h-4"></i>
            <span class="text-sm">View Thread</span>
            <span class="font-mono text-xs opacity-75">#{{ message.thread_id }}</span>
            <i data-lucide="arrow-right" class="w-3.5 h-3.5"></i>
          </a>
        {% endif %}
        {% if commit_sha %}
          <div class="flex items-center gap-2">
            <i data-lucide="git-commit" class="w-4 h-4"></i>
            <a href="/mail/archive/commit/{{ commit_sha }}"
               class="font-mono text-xs text-primary-600 dark:text-primary-400 hover:underline flex items-center gap-1"
               title="View commit in archive">
              Commit: {{ commit_sha[:8] }}
              <i data-lucide="external-link" class="w-3 h-3"></i>
            </a>
          </div>
        {% endif %}
      </div>
    </div>

    <!-- Recipients -->
    {% if recipients %}
      <div class="border-t border-slate-200 dark:border-slate-700 pt-6">
        <h3 class="text-sm font-semibold text-slate-700 dark:text-slate-300 mb-3">Recipients</h3>
        <div class="flex flex-wrap gap-2">
          {% for r in recipients %}
            <span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium
              {% if r.kind == 'to' %}
                bg-primary-100 dark:bg-primary-900/30 text-primary-700 dark:text-primary-300
              {% elif r.kind == 'cc' %}
                bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-300
              {% elif r.kind == 'bcc' %}
                bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400
              {% endif %}">
              {% if r.kind == 'to' %}
                <i data-lucide="mail" class="w-3.5 h-3.5"></i>
              {% elif r.kind == 'cc' %}
                <i data-lucide="mail-open" class="w-3.5 h-3.5"></i>
              {% elif r.kind == 'bcc' %}
                <i data-lucide="mail-x" class="w-3.5 h-3.5"></i>
              {% endif %}
              <span class="uppercase text-xs font-bold">{{ r.kind }}</span>
              <span>{{ r.name }}</span>
            </span>
          {% endfor %}
        </div>
      </div>
    {% endif %}
  </div>

  <!-- Message Body -->
  <div class="bg-white dark:bg-slate-800 rounded-xl p-8 shadow-soft border border-slate-200 dark:border-slate-700">
    <div class="prose prose-slate dark:prose-invert max-w-none">
      {% if message.body_html %}
        <!-- SECURITY: Using | safe assumes backend properly sanitizes HTML to prevent XSS -->
        <div id="message-body">{{ message.body_html | safe }}</div>
      {% else %}
        <div id="message-body" class="markdown-content"></div>
        <script>
          // Render markdown on client side for better security and features
          document.addEventListener('DOMContentLoaded', () => {
            const markdownContent = {{ message.body_md | tojson }};
            const bodyEl = document.getElementById('message-body');

            try {
              marked.setOptions({
                breaks: true,
                gfm: true,
                headerIds: true,
                mangle: false
              });
              bodyEl.innerHTML = marked.parse(markdownContent);
            } catch (error) {
              console.error('Markdown parsing failed:', error);
              bodyEl.textContent = markdownContent;
            }

            // Highlight code blocks when Prism is available
            if (typeof Prism !== 'undefined') {
              bodyEl.querySelectorAll('pre code').forEach((block) => {
                Prism.highlightElement(block);
              });
            }

            // Add copy buttons to code blocks with graceful fallbacks
            bodyEl.querySelectorAll('pre').forEach((pre) => {
              if (pre.parentNode.classList.contains('relative')) {
                return; // Button already attached
              }

              const wrapper = document.createElement('div');
              wrapper.className = 'relative group';
              pre.parentNode.insertBefore(wrapper, pre);
              wrapper.appendChild(pre);

              const button = document.createElement('button');
              button.innerHTML = '<i data-lucide="copy" class="w-4 h-4"></i>';
              button.className = 'absolute top-2 right-2 p-2 bg-slate-700 hover:bg-slate-600 text-white rounded-lg opacity-0 group-hover:opacity-100 transition-opacity';
              button.onclick = async () => {
                try {
                  if (navigator.clipboard && navigator.clipboard.writeText) {
                    await navigator.clipboard.writeText(pre.textContent);
                    button.innerHTML = '<i data-lucide="check" class="w-4 h-4"></i>';
                    if (typeof showToast === 'function') {
                      showToast('Code copied!', 'success');
                    }
                    setTimeout(() => {
                      button.innerHTML = '<i data-lucide="copy" class="w-4 h-4"></i>';
                      if (typeof lucide !== 'undefined') {
                        lucide.createIcons();
                      }
                    }, 2000);
                  } else {
                    throw new Error('Clipboard API not available');
                  }
                } catch (err) {
                  console.error('Copy failed:', err);
                  if (typeof showToast === 'function') {
                    showToast('Failed to copy code', 'error');
                  }
                }
              };
              wrapper.appendChild(button);
              if (typeof lucide !== 'undefined') {
                lucide.createIcons();
              }
            });
          });
        </script>
      {% endif %}
    </div>
  </div>

  <!-- Thread Quick Info - Link to Full Thread View -->
  {% if thread_items and thread_items|length > 1 %}
    <div class="bg-gradient-to-r from-primary-50 to-primary-100 dark:from-primary-900/20 dark:to-primary-800/20 rounded-xl border-2 border-primary-200 dark:border-primary-800 overflow-hidden">
      <div class="p-6">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-4">
            <div class="w-12 h-12 bg-primary-600 rounded-xl flex items-center justify-center shadow-md">
              <i data-lucide="messages-square" class="w-6 h-6 text-white"></i>
            </div>
            <div>
              <h3 class="text-lg font-semibold text-slate-900 dark:text-white mb-1">
                Part of a Conversation Thread
              </h3>
              <p class="text-sm text-slate-700 dark:text-slate-300">
                This message is part of a thread with <span class="font-bold">{{ thread_items|length }} messages</span>
              </p>
            </div>
          </div>

          <a href="/mail/{{ project.slug }}/thread/{{ message.thread_id }}"
             class="inline-flex items-center gap-2 px-6 py-3 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg shadow-md hover:shadow-xl transform hover:scale-105 transition-all duration-200">
            <i data-lucide="eye" class="w-4 h-4"></i>
            View Full Thread
            <i data-lucide="arrow-right" class="w-4 h-4"></i>
          </a>
        </div>

        <!-- Quick preview of other messages in thread -->
        <div class="mt-4 pt-4 border-t border-primary-200 dark:border-primary-700">
          <div class="flex items-center gap-2 text-xs text-slate-600 dark:text-slate-400 mb-2">
            <i data-lucide="layers" class="w-3.5 h-3.5"></i>
            <span class="font-medium">Other messages in this thread:</span>
          </div>
          <div class="flex flex-wrap gap-2">
            {% for t in thread_items[:5] %}
              {% if t.id != message.id %}
                <a href="/mail/{{ project.slug }}/message/{{ t.id }}"
                   class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-300 rounded-lg border border-primary-200 dark:border-primary-700 transition-colors text-xs">
                  <i data-lucide="mail" class="w-3 h-3"></i>
                  <span class="font-medium">{{ t.from or 'Unknown' }}</span>
                  <span class="opacity-60">•</span>
                  <span class="truncate max-w-[200px]">
                    {% if t.subject %}
                      {{ t.subject[:40] }}{% if t.subject|length > 40 %}...{% endif %}
                    {% else %}
                      <em>No subject</em>
                    {% endif %}
                  </span>
                </a>
              {% endif %}
            {% endfor %}
            {% if thread_items|length > 5 %}
              <span class="inline-flex items-center px-3 py-1.5 text-xs text-slate-500 dark:text-slate-400">
                +{{ thread_items|length - 5 }} more
              </span>
            {% endif %}
          </div>
        </div>
      </div>
    </div>
  {% endif %}
</div>
{% endblock %}
