<!doctype html>
<html lang="en" x-data="darkModeController()" x-init="init()"
      :class="{ 'dark': darkMode }" x-cloak>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{% block title %}Agent Mail{% endblock %}</title>

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">

    <script>
      (function () {
        try {
          const stored = localStorage.getItem('darkMode');
          const prefers = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
          if (stored === 'true' || (stored === null && prefers)) {
            document.documentElement.classList.add('dark');
          } else {
            document.documentElement.classList.remove('dark');
          }
        } catch (error) {
          document.documentElement.classList.remove('dark');
        }
      })();
    </script>

    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
      tailwind.config = {
        darkMode: 'class',
        theme: {
          extend: {
            fontFamily: {
              sans: ['Inter', 'system-ui', '-apple-system', 'sans-serif'],
            },
            colors: {
              primary: {
                50: '#eef2ff',
                100: '#e0e7ff',
                200: '#c7d2fe',
                300: '#a5b4fc',
                400: '#818cf8',
                500: '#6366f1',
                600: '#4f46e5',
                700: '#4338ca',
                800: '#3730a3',
                900: '#312e81',
                950: '#1e1b4b',
              },
              success: {
                50: '#f0fdf4',
                500: '#10b981',
                600: '#059669',
              },
              warning: {
                50: '#fffbeb',
                500: '#f59e0b',
                600: '#d97706',
              },
              danger: {
                50: '#fef2f2',
                500: '#ef4444',
                600: '#dc2626',
              },
            },
            boxShadow: {
              'soft': '0 2px 8px 0 rgba(0, 0, 0, 0.05)',
              'medium': '0 4px 16px 0 rgba(0, 0, 0, 0.08)',
              'large': '0 8px 32px 0 rgba(0, 0, 0, 0.12)',
              'glow': '0 0 20px rgba(99, 102, 241, 0.3)',
            },
            animation: {
              'fade-in': 'fadeIn 0.2s ease-in-out',
              'slide-up': 'slideUp 0.3s ease-out',
              'slide-down': 'slideDown 0.3s ease-out',
              'scale-in': 'scaleIn 0.2s ease-out',
              'shimmer': 'shimmer 2s infinite',
            },
            keyframes: {
              fadeIn: {
                '0%': { opacity: '0' },
                '100%': { opacity: '1' },
              },
              slideUp: {
                '0%': { transform: 'translateY(10px)', opacity: '0' },
                '100%': { transform: 'translateY(0)', opacity: '1' },
              },
              slideDown: {
                '0%': { transform: 'translateY(-10px)', opacity: '0' },
                '100%': { transform: 'translateY(0)', opacity: '1' },
              },
              scaleIn: {
                '0%': { transform: 'scale(0.95)', opacity: '0' },
                '100%': { transform: 'scale(1)', opacity: '1' },
              },
              shimmer: {
                '0%': { backgroundPosition: '-1000px 0' },
                '100%': { backgroundPosition: '1000px 0' },
              },
            },
          },
        },
      }
    </script>

    <!-- Alpine.js -->
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>

    <!-- Lucide Icons -->
    <script defer src="https://unpkg.com/lucide@latest"></script>

    <!-- Prism.js for code highlighting -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-json.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-markdown.min.js"></script>

    <!-- Marked.js for markdown rendering -->
    <script src="https://cdn.jsdelivr.net/npm/marked@11/marked.min.js"></script>

    <!-- DOMPurify for HTML sanitization (prevent XSS in markdown previews) -->
    <script src="https://cdn.jsdelivr.net/npm/dompurify@3/dist/purify.min.js"></script>

    <!-- Day.js for date formatting (lightweight utility) -->
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.10/dayjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.10/plugin/relativeTime.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.10/plugin/calendar.min.js"></script>

    <!-- Tippy.js for beautiful tooltips -->
    <script src="https://unpkg.com/@popperjs/core@2"></script>
    <script src="https://unpkg.com/tippy.js@6"></script>
    <link rel="stylesheet" href="https://unpkg.com/tippy.js@6/dist/tippy.css" />
    <link rel="stylesheet" href="https://unpkg.com/tippy.js@6/themes/light.css" />
    <link rel="stylesheet" href="https://unpkg.com/tippy.js@6/animations/scale.css" />

    <!-- NProgress for loading indicators -->
    <script src="https://unpkg.com/nprogress@0.2.0/nprogress.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/nprogress@0.2.0/nprogress.css" />

    <!-- Chart.js for data visualization -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

    <!-- Anime.js for advanced animations -->
    <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>

    <!-- SortableJS for drag and drop -->
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js"></script>

    <!-- Fuse.js for fuzzy search -->
    <script src="https://cdn.jsdelivr.net/npm/fuse.js@7.0.0/dist/fuse.min.js"></script>

    <!-- Hotkeys.js for keyboard shortcuts -->
    <script src="https://unpkg.com/hotkeys-js@3.13.7/dist/hotkeys.min.js"></script>

    <!-- Particles.js for background effects -->
    <script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script>

    <!-- CountUp.js for number animations -->
    <script src="https://cdn.jsdelivr.net/npm/countup@1.8.2/dist/countUp.min.js"></script>

    <!-- Mo.js for micro-animations -->
    <script src="https://cdn.jsdelivr.net/npm/@mojs/core@1.4.1/build/mo.min.js"></script>

    <!-- Splitting.js for advanced text animations -->
    <script src="https://unpkg.com/splitting@1.0.6/dist/splitting.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/splitting@1.0.6/dist/splitting.css" />

    <!-- Mermaid.js for git graphs and diagrams -->
    <script type="module">
      import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
      window.mermaid = mermaid;
      mermaid.initialize({
        startOnLoad: false,
        theme: 'base',
        themeVariables: {
          primaryColor: '#6366f1',
          primaryTextColor: '#fff',
          primaryBorderColor: '#4f46e5',
          lineColor: '#6366f1',
          secondaryColor: '#818cf8',
          tertiaryColor: '#a5b4fc',
          background: '#ffffff',
          mainBkg: '#6366f1',
          secondBkg: '#818cf8',
          tertiaryBkg: '#a5b4fc'
        },
        gitGraph: {
          rotateCommitLabel: false,
          mainBranchName: 'main',
          showBranches: true,
          showCommitLabel: true
        }
      });
    </script>

    <!-- Diff2Html for beautiful git diffs -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/diff2html@3.4.47/bundles/css/diff2html.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/diff2html@3.4.47/bundles/js/diff2html-ui.min.js"></script>

    <!-- Vis.js for network graphs -->
    <script src="https://unpkg.com/vis-network@9.1.9/dist/vis-network.min.js"></script>
    <link href="https://unpkg.com/vis-network@9.1.9/dist/vis-network.min.css" rel="stylesheet" type="text/css" />

    <style>
      [x-cloak] { display: none !important; }

      /* Tutorial Animations */
      @keyframes shimmer {
        0% { transform: translateX(-100%); }
        100% { transform: translateX(100%); }
      }

      @keyframes gradient-x {
        0%, 100% { background-position: 0% 50%; }
        50% { background-position: 100% 50%; }
      }

      @keyframes wave {
        0%, 100% { transform: rotate(0deg); }
        25% { transform: rotate(20deg); }
        75% { transform: rotate(-20deg); }
      }

      @keyframes bounce-slow {
        0%, 100% { transform: translateY(0); }
        50% { transform: translateY(-10px); }
      }

      .animate-shimmer {
        animation: shimmer 2s infinite;
      }

      .animate-gradient-x {
        background-size: 200% 200%;
        animation: gradient-x 3s ease infinite;
      }

      .animate-wave {
        display: inline-block;
        animation: wave 1s ease-in-out 2;
      }

      .animate-bounce-slow {
        animation: bounce-slow 2s ease-in-out infinite;
      }

      /* Checklist checkbox animation */
      @keyframes check-pop {
        0% { transform: scale(0.8); }
        50% { transform: scale(1.2); }
        100% { transform: scale(1); }
      }

      .checkbox-checked {
        animation: check-pop 0.3s ease-out;
      }

      /* Spotlight pulse */
      @keyframes spotlight-pulse {
        0%, 100% { opacity: 0.9; }
        50% { opacity: 1; }
      }

      .tutorial-spotlight {
        animation: spotlight-pulse 2s ease-in-out infinite;
      }

      /* Smooth transitions - Only apply to interactive elements, let Tailwind utilities handle the rest */
      button, a, input[type="submit"], input[type="button"] {
        transition-property: background-color, border-color, color, fill, stroke, opacity, transform, box-shadow;
        transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
        transition-duration: 150ms;
      }

      /* Scrollbar styling */
      ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
      }

      ::-webkit-scrollbar-track {
        background: transparent;
      }

      ::-webkit-scrollbar-thumb {
        background: rgba(148, 163, 184, 0.5);
        border-radius: 4px;
      }

      ::-webkit-scrollbar-thumb:hover {
        background: rgba(148, 163, 184, 0.7);
      }

      .dark ::-webkit-scrollbar-thumb {
        background: rgba(71, 85, 105, 0.5);
      }

      .dark ::-webkit-scrollbar-thumb:hover {
        background: rgba(71, 85, 105, 0.7);
      }

      /* Glass effect */
      .glass {
        background: rgba(255, 255, 255, 0.8);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(12px);
      }

      .dark .glass {
        background: rgba(15, 23, 42, 0.8);
      }

      /* Gradient backgrounds */
      .gradient-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      .gradient-success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
      }

      .gradient-mesh {
        background:
          radial-gradient(at 40% 20%, rgba(99, 102, 241, 0.15) 0px, transparent 50%),
          radial-gradient(at 80% 0%, rgba(139, 92, 246, 0.15) 0px, transparent 50%),
          radial-gradient(at 0% 50%, rgba(236, 72, 153, 0.15) 0px, transparent 50%),
          radial-gradient(at 80% 50%, rgba(59, 130, 246, 0.15) 0px, transparent 50%);
      }

      /* Prose styling for markdown */
      .prose {
        max-width: none;
      }

      .prose h1 { font-size: 2em; font-weight: 700; margin: 1em 0 0.5em; line-height: 1.2; }
      .prose h2 { font-size: 1.5em; font-weight: 600; margin: 1em 0 0.5em; line-height: 1.3; }
      .prose h3 { font-size: 1.25em; font-weight: 600; margin: 1em 0 0.5em; line-height: 1.4; }
      .prose p { margin: 1em 0; line-height: 1.7; }
      .prose a { color: #6366f1; text-decoration: underline; }
      .prose a:hover { color: #4f46e5; }
      .prose ul, .prose ol { margin: 1em 0; padding-left: 2em; }
      .prose li { margin: 0.5em 0; }
      .prose code {
        background: rgba(99, 102, 241, 0.1);
        padding: 0.2em 0.4em;
        border-radius: 4px;
        font-size: 0.9em;
        font-family: 'Monaco', 'Courier New', monospace;
      }
      .prose pre {
        background: #1e293b;
        padding: 1em;
        border-radius: 8px;
        overflow-x: auto;
        margin: 1em 0;
      }
      .prose pre code {
        background: transparent;
        padding: 0;
        color: #e2e8f0;
      }
      .prose blockquote {
        border-left: 4px solid #6366f1;
        padding-left: 1em;
        margin: 1em 0;
        font-style: italic;
        color: #64748b;
      }
      .prose img {
        border-radius: 8px;
        margin: 1em 0;
        max-width: 100%;
      }

      .dark .prose { color: #e2e8f0; }
      .dark .prose a { color: #818cf8; }
      .dark .prose a:hover { color: #a5b4fc; }
      .dark .prose code { background: rgba(99, 102, 241, 0.2); }
      .dark .prose blockquote { color: #94a3b8; }

      /* Loading skeleton */
      .skeleton {
        background: linear-gradient(90deg, #f1f5f9 25%, #e2e8f0 50%, #f1f5f9 75%);
        background-size: 1000px 100%;
        animation: shimmer 2s infinite;
      }

      .dark .skeleton {
        background: linear-gradient(90deg, #1e293b 25%, #334155 50%, #1e293b 75%);
        background-size: 1000px 100%;
      }

      /* Focus styles for accessibility */
      *:focus-visible {
        outline: 2px solid #6366f1;
        outline-offset: 2px;
        border-radius: 4px;
      }

      /* Button ripple effect */
      .btn-ripple {
        position: relative;
        overflow: hidden;
      }

      .btn-ripple::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 0;
        height: 0;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.5);
        transform: translate(-50%, -50%);
        transition: width 0.6s, height 0.6s;
      }

      .btn-ripple:active::after {
        width: 300px;
        height: 300px;
      }

      /* Badge pulse animation */
      .badge-pulse {
        animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
      }

      @keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.7; }
      }

      /* Premium card hover effects */
      .card-hover {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      }

      .card-hover:hover {
        transform: translateY(-4px) scale(1.01);
      }

      /* Floating animation for hero elements */
      .float {
        animation: float 6s ease-in-out infinite;
      }

      @keyframes float {
        0%, 100% { transform: translateY(0px); }
        50% { transform: translateY(-10px); }
      }

      /* Gradient text shimmer */
      .text-shimmer {
        background-size: 200% auto;
        animation: gradient-shift 3s linear infinite;
      }

      @keyframes gradient-shift {
        0% { background-position: 0% center; }
        100% { background-position: 200% center; }
      }

      /* Custom NProgress styling */
      #nprogress .bar {
        background: linear-gradient(to right, #6366f1, #8b5cf6, #ec4899) !important;
        height: 3px !important;
      }

      #nprogress .peg {
        box-shadow: 0 0 10px #6366f1, 0 0 5px #6366f1 !important;
      }

      #nprogress .spinner-icon {
        border-top-color: #6366f1 !important;
        border-left-color: #6366f1 !important;
      }

      /* Tippy.js custom theme */
      .tippy-box[data-theme~='agent-mail'] {
        background-color: #1e293b;
        color: #f1f5f9;
        font-size: 0.875rem;
        border-radius: 0.5rem;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
      }

      .tippy-box[data-theme~='agent-mail'][data-placement^='top'] > .tippy-arrow::before {
        border-top-color: #1e293b;
      }

      /* Stagger animation for lists */
      .stagger-item {
        opacity: 0;
        animation: staggerIn 0.4s ease-out forwards;
      }

      @keyframes staggerIn {
        from {
          opacity: 0;
          transform: translateY(20px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }

      @keyframes slideInRight {
        from {
          opacity: 0;
          transform: translateX(20px);
        }
        to {
          opacity: 1;
          transform: translateX(0);
        }
      }

      @keyframes fadeOutCollapse {
        0% {
          opacity: 1;
          max-height: 500px;
          transform: scale(1);
        }
        50% {
          opacity: 0;
          max-height: 500px;
          transform: scale(0.95);
        }
        100% {
          opacity: 0;
          max-height: 0;
          transform: scale(0.95);
          margin: 0;
          padding: 0;
        }
      }

      /* Respect user's reduced motion preference */
      @media (prefers-reduced-motion: reduce) {
        /* Disable decorative animations */
        .stagger-item,
        .float,
        .badge-pulse,
        *[class*="animate-"] {
          animation: none !important;
        }

        /* Disable transform-based transitions but keep opacity/color for UX */
        .card-hover {
          transform: none !important;
          transition: opacity 0.15s ease, box-shadow 0.15s ease !important;
        }

        /* Immediately show stagger items */
        .stagger-item {
          opacity: 1 !important;
          transform: none !important;
        }
      }

      /* Smooth page transitions */
      .page-transition {
        animation: pageIn 0.3s ease-out;
      }

      @keyframes pageIn {
        from {
          opacity: 0;
          transform: translateY(10px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }

      /* Premium input focus effects - only apply when not using Tailwind focus utilities */
      input:not([class*="focus:"]):focus,
      textarea:not([class*="focus:"]):focus,
      select:not([class*="focus:"]):focus {
        box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
      }

      /* Glow on hover for interactive elements */
      .glow-on-hover:hover {
        box-shadow: 0 0 20px rgba(99, 102, 241, 0.4);
      }

      /* Stat counter animation */
      .stat-number {
        font-variant-numeric: tabular-nums;
      }

      /* Custom checkbox styling */
      input[type="checkbox"] {
        cursor: pointer;
      }

      input[type="checkbox"]:checked {
        background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e");
      }

      /* Message bubble styles */
      .message-bubble {
        position: relative;
        padding: 1rem;
        border-radius: 1rem;
        background: linear-gradient(135deg, rgba(99, 102, 241, 0.05) 0%, rgba(139, 92, 246, 0.05) 100%);
        border: 1px solid rgba(99, 102, 241, 0.1);
      }

      .dark .message-bubble {
        background: linear-gradient(135deg, rgba(99, 102, 241, 0.1) 0%, rgba(139, 92, 246, 0.1) 100%);
        border: 1px solid rgba(99, 102, 241, 0.2);
      }

      /* Skeleton loader */
      @keyframes skeleton-loading {
        0% {
          background-position: -200% 0;
        }
        100% {
          background-position: 200% 0;
        }
      }

      .skeleton-loader {
        background: linear-gradient(
          90deg,
          rgba(226, 232, 240, 0.2) 0%,
          rgba(226, 232, 240, 0.4) 50%,
          rgba(226, 232, 240, 0.2) 100%
        );
        background-size: 200% 100%;
        animation: skeleton-loading 1.5s ease-in-out infinite;
        border-radius: 0.5rem;
      }

      .dark .skeleton-loader {
        background: linear-gradient(
          90deg,
          rgba(51, 65, 85, 0.2) 0%,
          rgba(51, 65, 85, 0.4) 50%,
          rgba(51, 65, 85, 0.2) 100%
        );
        background-size: 200% 100%;
      }

      /* Enhanced micro-interactions */
      .btn-magnetic {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      }

      .btn-magnetic:hover {
        transform: translateY(-2px) scale(1.02);
        box-shadow: 0 12px 24px -10px currentColor;
      }

      .btn-magnetic:active {
        transform: translateY(0) scale(0.98);
      }

      /* Smooth elevation on hover */
      .elevate-on-hover {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      }

      .elevate-on-hover:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 40px -12px rgba(0, 0, 0, 0.15);
      }

      /* Notification badge pulse */
      @keyframes badge-pulse {
        0%, 100% {
          transform: scale(1);
          opacity: 1;
        }
        50% {
          transform: scale(1.1);
          opacity: 0.9;
        }
      }

      .notification-badge {
        animation: badge-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
      }

      /* Spotlight search effect */
      .search-spotlight {
        position: relative;
        overflow: hidden;
      }

      .search-spotlight::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
        transition: left 0.5s;
      }

      .search-spotlight:focus-within::before {
        left: 100%;
      }

      /* Premium card shimmer */
      @keyframes card-shimmer {
        0% {
          background-position: -1000px 0;
        }
        100% {
          background-position: 1000px 0;
        }
      }

      .card-shimmer {
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.03), transparent);
        background-size: 1000px 100%;
        animation: card-shimmer 3s infinite;
      }

      .dark .card-shimmer {
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.02), transparent);
        background-size: 1000px 100%;
      }

      /* Success checkmark animation */
      @keyframes checkmark-draw {
        0% {
          stroke-dashoffset: 100;
        }
        100% {
          stroke-dashoffset: 0;
        }
      }

      .checkmark-draw {
        stroke-dasharray: 100;
        stroke-dashoffset: 100;
        animation: checkmark-draw 0.6s ease-out forwards;
      }

      /* Loading dots */
      @keyframes loading-dots {
        0%, 20% {
          opacity: 0.3;
          transform: scale(0.8);
        }
        50% {
          opacity: 1;
          transform: scale(1.1);
        }
        100% {
          opacity: 0.3;
          transform: scale(0.8);
        }
      }

      .loading-dot {
        animation: loading-dots 1.4s infinite;
      }

      .loading-dot:nth-child(2) {
        animation-delay: 0.2s;
      }

      .loading-dot:nth-child(3) {
        animation-delay: 0.4s;
      }

      /* Tooltip arrow animations */
      [data-tippy-root] {
        transition: transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);
      }

      /* Enhanced focus states for accessibility */
      *:focus-visible {
        outline: 3px solid #6366f1;
        outline-offset: 3px;
        border-radius: 6px;
      }

      .dark *:focus-visible {
        outline-color: #818cf8;
      }

      /* Skip to content link for accessibility */
      .skip-to-content {
        position: absolute;
        top: -40px;
        left: 0;
        background: #6366f1;
        color: white;
        padding: 8px;
        text-decoration: none;
        z-index: 1000;
      }

      .skip-to-content:focus {
        top: 0;
      }

      /* Progress bar animations */
      @keyframes progress-indeterminate {
        0% {
          left: -35%;
          right: 100%;
        }
        60% {
          left: 100%;
          right: -90%;
        }
        100% {
          left: 100%;
          right: -90%;
        }
      }

      .progress-indeterminate {
        position: relative;
        overflow: hidden;
      }

      .progress-indeterminate::before {
        content: '';
        position: absolute;
        background: currentColor;
        top: 0;
        left: 0;
        bottom: 0;
        will-change: left, right;
        animation: progress-indeterminate 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
      }

      /* Enhanced badge styles */
      .badge-premium {
        position: relative;
        overflow: hidden;
      }

      .badge-premium::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
        animation: badge-shimmer 3s infinite;
      }

      @keyframes badge-shimmer {
        0% {
          left: -100%;
        }
        100% {
          left: 100%;
        }
      }

      /* Particle background container */
      #particles-background {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
        opacity: 0.3;
        pointer-events: none;
      }

      /* Smooth page transitions */
      @keyframes page-fade-in {
        from {
          opacity: 0;
          transform: translateY(20px) scale(0.98);
        }
        to {
          opacity: 1;
          transform: translateY(0) scale(1);
        }
      }

      .page-enter {
        animation: page-fade-in 0.4s cubic-bezier(0.4, 0, 0.2, 1);
      }

      /* Interactive element glow */
      .interactive-glow {
        position: relative;
        transition: all 0.3s ease;
      }

      .interactive-glow::after {
        content: '';
        position: absolute;
        inset: -2px;
        background: linear-gradient(45deg, #6366f1, #8b5cf6, #ec4899, #6366f1);
        background-size: 300% 300%;
        border-radius: inherit;
        opacity: 0;
        z-index: -1;
        animation: gradient-rotate 3s ease infinite;
        filter: blur(8px);
        transition: opacity 0.3s;
      }

      .interactive-glow:hover::after {
        opacity: 0.6;
      }

      @keyframes gradient-rotate {
        0%, 100% {
          background-position: 0% 50%;
        }
        50% {
          background-position: 100% 50%;
        }
      }
    </style>

    {% block head %}{% endblock %}
  </head>

  <body class="bg-gradient-to-br from-slate-50 via-white to-slate-50 dark:from-slate-950 dark:via-slate-900 dark:to-slate-950 text-slate-900 dark:text-slate-100 min-h-screen">
    <!-- Accessibility: Skip to main content -->
    <a href="#main-content" class="skip-to-content">Skip to main content</a>

    <!-- Subtle particle background (optional, can be disabled) -->
    <div id="particles-background" style="display: none;"></div>

    <!-- Command Palette (Cmd/Ctrl+K) -->
    <div x-data="commandPalette()"
         @keydown.window.prevent.meta.k="toggle()"
         @keydown.window.prevent.ctrl.k="toggle()"
         @keydown.escape.window="close()"
         x-show="isOpen"
         x-cloak
         class="fixed inset-0 z-[100] flex items-start justify-center pt-20 px-4"
         style="display: none;">
      <!-- Backdrop -->
      <div @click="close()"
           x-show="isOpen"
           x-transition:enter="transition ease-out duration-200"
           x-transition:enter-start="opacity-0"
           x-transition:enter-end="opacity-100"
           x-transition:leave="transition ease-in duration-150"
           x-transition:leave-start="opacity-100"
           x-transition:leave-end="opacity-0"
           class="absolute inset-0 bg-slate-900/50 backdrop-blur-sm"></div>

      <!-- Command Palette Panel -->
      <div x-show="isOpen"
           x-transition:enter="transition ease-out duration-200"
           x-transition:enter-start="opacity-0 transform scale-95 -translate-y-4"
           x-transition:enter-end="opacity-100 transform scale-100 translate-y-0"
           x-transition:leave="transition ease-in duration-150"
           x-transition:leave-start="opacity-100 transform scale-100"
           x-transition:leave-end="opacity-0 transform scale-95"
           class="relative w-full max-w-2xl glass rounded-2xl shadow-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">

        <!-- Search Input -->
        <div class="relative border-b border-slate-200 dark:border-slate-700">
          <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"></i>
          </div>
          <input x-ref="searchInput"
                 x-model="query"
                 @input="search()"
                 @keydown.down.prevent="selectNext()"
                 @keydown.up.prevent="selectPrevious()"
                 @keydown.enter.prevent="executeSelected()"
                 type="text"
                 placeholder="Search commands, navigate, or type '?' for help..."
                 class="w-full pl-14 pr-4 py-5 bg-transparent border-0 text-slate-900 dark:text-white placeholder-slate-500 dark:placeholder-slate-400 focus:outline-none text-lg"
                 autocomplete="off"
                 aria-label="Command palette search" />
        </div>

        <!-- Results -->
        <div class="max-h-96 overflow-y-auto">
          <template x-if="filteredCommands.length === 0">
            <div class="p-8 text-center text-slate-500 dark:text-slate-400">
              <i data-lucide="inbox" class="w-12 h-12 mx-auto mb-3 opacity-50"></i>
              <p>No commands found. Try different keywords.</p>
            </div>
          </template>

          <template x-for="(command, index) in filteredCommands" :key="command.id">
            <button @click="execute(command)"
                    :class="selectedIndex === index ? 'bg-primary-50 dark:bg-primary-900/20 border-l-4 border-l-primary-500' : 'border-l-4 border-l-transparent'"
                    class="w-full px-6 py-4 flex items-center gap-4 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-all duration-150 text-left group">
              <div :class="command.iconColor || 'text-slate-400'"
                   class="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0"
                   :style="`background: ${command.iconBg || 'rgba(148, 163, 184, 0.1)'}`">
                <i :data-lucide="command.icon" class="w-5 h-5"></i>
              </div>
              <div class="flex-1 min-w-0">
                <div class="font-semibold text-slate-900 dark:text-white group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors"
                     x-text="command.title"></div>
                <div class="text-sm text-slate-600 dark:text-slate-400 truncate"
                     x-text="command.description" x-show="command.description"></div>
              </div>
              <div x-show="command.shortcut"
                   class="flex items-center gap-1 text-xs text-slate-500 dark:text-slate-400">
                <template x-for="key in (command.shortcut || '').split('+')" :key="key">
                  <kbd class="px-2 py-1 bg-slate-100 dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 font-mono" x-text="key"></kbd>
                </template>
              </div>
            </button>
          </template>
        </div>

        <!-- Footer -->
        <div class="px-6 py-3 bg-slate-50 dark:bg-slate-900 border-t border-slate-200 dark:border-slate-700 flex items-center justify-between text-xs text-slate-600 dark:text-slate-400">
          <div class="flex items-center gap-4">
            <div class="flex items-center gap-1">
              <kbd class="px-2 py-1 bg-white dark:bg-slate-800 rounded border border-slate-300 dark:border-slate-600">↑↓</kbd>
              <span>Navigate</span>
            </div>
            <div class="flex items-center gap-1">
              <kbd class="px-2 py-1 bg-white dark:bg-slate-800 rounded border border-slate-300 dark:border-slate-600">↵</kbd>
              <span>Select</span>
            </div>
            <div class="flex items-center gap-1">
              <kbd class="px-2 py-1 bg-white dark:bg-slate-800 rounded border border-slate-300 dark:border-slate-600">Esc</kbd>
              <span>Close</span>
            </div>
          </div>
          <div class="text-slate-500">
            <span x-text="filteredCommands.length"></span> commands
          </div>
        </div>
      </div>
    </div>

    <!-- Interactive Tutorial / Onboarding -->
    <div x-data="tutorialManager()"
         x-init="init()"
         x-show="isActive"
         x-cloak
         class="fixed inset-0 z-[200] flex items-center justify-center p-4"
         style="display: none;">
      <!-- Dynamic Backdrop with spotlight -->
      <div x-show="isActive"
           x-transition:enter="transition ease-out duration-300"
           x-transition:enter-start="opacity-0"
           x-transition:enter-end="opacity-100"
           class="absolute inset-0 bg-slate-900/80 backdrop-blur-md tutorial-backdrop"></div>

      <!-- Spotlight overlay (for highlighting elements) -->
      <div x-show="highlightElement"
           x-transition
           class="absolute inset-0 pointer-events-none"
           style="
             background: radial-gradient(
               circle at var(--spotlight-x, 50%) var(--spotlight-y, 50%),
               transparent 0%,
               transparent var(--spotlight-size, 150px),
               rgba(0, 0, 0, 0.9) calc(var(--spotlight-size, 150px) + 100px)
             );
           "
           :style="`
             --spotlight-x: ${spotlightX}px;
             --spotlight-y: ${spotlightY}px;
             --spotlight-size: ${spotlightSize}px;
           `"></div>

      <!-- Tutorial Panel -->
      <div x-show="isActive"
           x-transition:enter="transition ease-out duration-300"
           x-transition:enter-start="opacity-0 transform scale-95 translate-y-8"
           x-transition:enter-end="opacity-100 transform scale-100 translate-y-0"
           class="relative w-full max-w-3xl glass rounded-2xl shadow-2xl border border-slate-200 dark:border-slate-700 overflow-hidden max-h-[90vh] flex flex-col">

        <!-- Enhanced Progress Bar with percentage -->
        <div class="relative h-2 bg-slate-200 dark:bg-slate-700 overflow-hidden">
          <div class="absolute inset-0 bg-gradient-to-r from-primary-500 via-purple-500 to-pink-500 animate-gradient-x opacity-20"></div>
          <div class="relative h-full bg-gradient-to-r from-primary-500 via-purple-500 to-pink-500 transition-all duration-700 ease-out shadow-glow"
               :style="`width: ${progress}%`">
            <!-- Shimmer effect -->
            <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/30 to-transparent animate-shimmer"></div>
          </div>
          <!-- Percentage indicator -->
          <div class="absolute right-2 -top-8 px-2 py-1 bg-gradient-to-r from-primary-600 to-purple-600 text-white text-xs font-bold rounded-full shadow-lg"
               x-show="progress > 0 && progress < 100"
               x-transition>
            <span x-text="Math.round(progress)"></span>%
          </div>
        </div>

        <!-- Header -->
        <div class="px-8 py-6 bg-gradient-to-r from-primary-500 via-purple-600 to-pink-600 text-white">
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-4">
              <div class="w-14 h-14 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-sm float">
                <i :data-lucide="steps[currentStep]?.icon || 'help-circle'" class="w-7 h-7"></i>
              </div>
              <div>
                <div class="text-sm font-medium text-primary-100 mb-1">
                  Step <span x-text="currentStep + 1"></span> of <span x-text="steps.length"></span>
                </div>
                <h2 class="text-2xl font-bold" x-text="steps[currentStep]?.title"></h2>
              </div>
            </div>
            <button @click="skip()"
                    class="w-10 h-10 bg-white/20 hover:bg-white/30 rounded-lg flex items-center justify-center transition-colors"
                    data-tippy-content="Skip tutorial">
              <i data-lucide="x" class="w-5 h-5"></i>
            </button>
          </div>
        </div>

        <!-- Content -->
        <div class="flex-1 overflow-y-auto p-8">
          <!-- Welcome Step -->
          <template x-if="currentStep === 0">
            <div class="space-y-6 animate-fade-in">
              <div class="text-center mb-8">
                <!-- Animated icon with pulse effect -->
                <div class="relative inline-block mb-6">
                  <div class="absolute inset-0 bg-gradient-to-br from-primary-500 to-purple-600 rounded-3xl blur-xl opacity-50 animate-pulse"></div>
                  <div class="relative inline-flex items-center justify-center w-24 h-24 bg-gradient-to-br from-primary-500 to-purple-600 rounded-3xl shadow-large float">
                    <i data-lucide="mail" class="w-12 h-12 text-white"></i>
                  </div>
                </div>

                <h3 class="text-4xl font-bold bg-gradient-to-r from-primary-600 via-purple-600 to-pink-600 bg-clip-text text-transparent mb-4">
                  Welcome to Agent Mail! 👋
                </h3>
                <p class="text-xl text-slate-600 dark:text-slate-400 max-w-2xl mx-auto mb-6">
                  Think of this as <strong class="text-slate-900 dark:text-white">Slack for AI assistants</strong> working on your code.
                </p>

                <!-- Quick stats -->
                <div class="flex items-center justify-center gap-8 text-sm text-slate-500 dark:text-slate-400 mb-8">
                  <div class="flex items-center gap-2">
                    <i data-lucide="clock" class="w-4 h-4"></i>
                    <span>2 min tour</span>
                  </div>
                  <div class="flex items-center gap-2">
                    <i data-lucide="layers" class="w-4 h-4"></i>
                    <span>8 steps</span>
                  </div>
                  <div class="flex items-center gap-2">
                    <i data-lucide="zap" class="w-4 h-4"></i>
                    <span>Interactive</span>
                  </div>
                </div>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="p-6 bg-gradient-to-br from-primary-50 to-purple-50 dark:from-primary-900/20 dark:to-purple-900/20 rounded-xl border border-primary-200 dark:border-primary-800">
                  <div class="w-12 h-12 bg-primary-500 rounded-xl flex items-center justify-center mb-4">
                    <i data-lucide="users" class="w-6 h-6 text-white"></i>
                  </div>
                  <h4 class="font-bold text-slate-900 dark:text-white mb-2">Multiple AI Assistants</h4>
                  <p class="text-sm text-slate-600 dark:text-slate-400">
                    Run Claude, GPT, Gemini, or other AI assistants simultaneously on the same codebase.
                  </p>
                </div>

                <div class="p-6 bg-gradient-to-br from-success-50 to-emerald-50 dark:from-success-900/20 dark:to-emerald-900/20 rounded-xl border border-success-200 dark:border-success-800">
                  <div class="w-12 h-12 bg-success-500 rounded-xl flex items-center justify-center mb-4">
                    <i data-lucide="message-square" class="w-6 h-6 text-white"></i>
                  </div>
                  <h4 class="font-bold text-slate-900 dark:text-white mb-2">Coordinate & Communicate</h4>
                  <p class="text-sm text-slate-600 dark:text-slate-400">
                    Agents message each other, share context, and avoid stepping on each other's toes.
                  </p>
                </div>

                <div class="p-6 bg-gradient-to-br from-warning-50 to-orange-50 dark:from-warning-900/20 dark:to-orange-900/20 rounded-xl border border-warning-200 dark:border-warning-800">
                  <div class="w-12 h-12 bg-warning-500 rounded-xl flex items-center justify-center mb-4">
                    <i data-lucide="shield-check" class="w-6 h-6 text-white"></i>
                  </div>
                  <h4 class="font-bold text-slate-900 dark:text-white mb-2">Prevent Conflicts</h4>
                  <p class="text-sm text-slate-600 dark:text-slate-400">
                    Agents can "reserve" files they're editing, like putting a sticky note: "I'm working here!"
                  </p>
                </div>

                <div class="p-6 bg-gradient-to-br from-pink-50 to-rose-50 dark:from-pink-900/20 dark:to-rose-900/20 rounded-xl border border-pink-200 dark:border-pink-800">
                  <div class="w-12 h-12 bg-pink-500 rounded-xl flex items-center justify-center mb-4">
                    <i data-lucide="git-branch" class="w-6 h-6 text-white"></i>
                  </div>
                  <h4 class="font-bold text-slate-900 dark:text-white mb-2">Everything Tracked</h4>
                  <p class="text-sm text-slate-600 dark:text-slate-400">
                    All messages and coordination saved in Git, so you can review what happened.
                  </p>
                </div>
              </div>
            </div>
          </template>

          <!-- Step 1: Projects -->
          <template x-if="currentStep === 1">
            <div class="space-y-6 animate-fade-in">
              <div class="aspect-video bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-900 rounded-xl border border-slate-300 dark:border-slate-700 p-8 flex items-center justify-center">
                <div class="text-center">
                  <i data-lucide="folder" class="w-20 h-20 text-primary-500 mx-auto mb-4"></i>
                  <div class="text-lg font-semibold text-slate-700 dark:text-slate-300">Visual: Project List</div>
                </div>
              </div>

              <div class="prose dark:prose-invert max-w-none">
                <h3 class="text-2xl font-bold text-slate-900 dark:text-white mb-4">What's a Project?</h3>
                <p class="text-lg text-slate-600 dark:text-slate-400 mb-4">
                  A <strong>project</strong> is simply your <strong>code repository</strong> or workspace. Think of it as a folder where your AI assistants collaborate.
                </p>

                <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mb-4">
                  <div class="flex items-start gap-3">
                    <i data-lucide="lightbulb" class="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0"></i>
                    <div class="text-sm text-blue-900 dark:text-blue-100">
                      <strong>Example:</strong> You might have a "backend" project and a "frontend" project. Each has its own set of AI assistants working on it.
                    </div>
                  </div>
                </div>

                <p class="text-slate-600 dark:text-slate-400">
                  Each project shows:
                </p>
                <ul class="space-y-2 text-slate-600 dark:text-slate-400">
                  <li>✅ How many AI assistants are registered</li>
                  <li>✅ How many messages have been exchanged</li>
                  <li>✅ When it was created</li>
                </ul>
              </div>
            </div>
          </template>

          <!-- Step 2: Related Projects (Siblings) -->
          <template x-if="currentStep === 2">
            <div class="space-y-6 animate-fade-in">
              <div class="aspect-video bg-gradient-to-br from-violet-100 to-purple-200 dark:from-violet-900/30 dark:to-purple-900/30 rounded-xl border border-violet-300 dark:border-violet-700 p-8 flex items-center justify-center">
                <div class="flex items-center gap-6">
                  <div class="text-center">
                    <div class="w-20 h-20 bg-gradient-to-br from-primary-500 to-primary-700 rounded-2xl flex items-center justify-center shadow-lg">
                      <i data-lucide="folder" class="w-10 h-10 text-white"></i>
                    </div>
                    <div class="text-sm font-semibold text-slate-700 dark:text-slate-300 mt-2">Frontend</div>
                  </div>
                  <div class="flex flex-col items-center gap-2">
                    <i data-lucide="git-branch" class="w-8 h-8 text-violet-500"></i>
                    <div class="text-xs font-semibold text-violet-600 dark:text-violet-400">linked</div>
                  </div>
                  <div class="text-center">
                    <div class="w-20 h-20 bg-gradient-to-br from-emerald-500 to-teal-600 rounded-2xl flex items-center justify-center shadow-lg">
                      <i data-lucide="folder" class="w-10 h-10 text-white"></i>
                    </div>
                    <div class="text-sm font-semibold text-slate-700 dark:text-slate-300 mt-2">Backend</div>
                  </div>
                </div>
              </div>

              <div class="prose dark:prose-invert max-w-none">
                <h3 class="text-2xl font-bold text-slate-900 dark:text-white mb-4">Discover Related Projects</h3>
                <p class="text-lg text-slate-600 dark:text-slate-400 mb-4">
                  Agent Mail can <strong>automatically detect</strong> when projects are related and should work together!
                </p>

                <div class="bg-gradient-to-br from-violet-50 to-purple-50 dark:from-violet-900/20 dark:to-purple-900/20 border border-violet-200 dark:border-violet-800 rounded-lg p-5 mb-4">
                  <div class="flex items-start gap-3">
                    <div class="w-10 h-10 bg-gradient-to-br from-violet-500 to-purple-600 rounded-xl flex items-center justify-center flex-shrink-0">
                      <i data-lucide="sparkles" class="w-5 h-5 text-white"></i>
                    </div>
                    <div class="flex-1">
                      <h4 class="font-bold text-violet-900 dark:text-violet-100 mb-2">Smart Suggestions</h4>
                      <p class="text-sm text-violet-800 dark:text-violet-200 mb-3">
                        Using AI, we analyze your projects and suggest which ones should be linked based on:
                      </p>
                      <ul class="space-y-1.5 text-sm text-violet-700 dark:text-violet-300">
                        <li class="flex items-center gap-2">
                          <i data-lucide="check" class="w-4 h-4 text-violet-600 dark:text-violet-400"></i>
                          <span>Similar code patterns and dependencies</span>
                        </li>
                        <li class="flex items-center gap-2">
                          <i data-lucide="check" class="w-4 h-4 text-violet-600 dark:text-violet-400"></i>
                          <span>Shared file structures (like frontend + backend)</span>
                        </li>
                        <li class="flex items-center gap-2">
                          <i data-lucide="check" class="w-4 h-4 text-violet-600 dark:text-violet-400"></i>
                          <span>Common naming conventions</span>
                        </li>
                      </ul>
                    </div>
                  </div>
                </div>

                <div class="bg-gradient-to-br from-amber-50 to-yellow-50 dark:from-amber-900/20 dark:to-yellow-900/20 border-2 border-amber-300 dark:border-amber-700 rounded-xl p-5 mb-6">
                  <div class="flex items-start gap-3">
                    <div class="w-10 h-10 bg-amber-500 rounded-xl flex items-center justify-center flex-shrink-0">
                      <i data-lucide="shield-check" class="w-5 h-5 text-white"></i>
                    </div>
                    <div class="flex-1">
                      <h4 class="font-bold text-amber-900 dark:text-amber-100 mb-2">Important: Discovery ≠ Messaging Permission</h4>
                      <p class="text-sm text-amber-800 dark:text-amber-200 mb-3">
                        Confirming a link <strong>only updates your UI</strong> with handy navigation badges. It does <strong>not</strong> let agents automatically message across projects.
                      </p>
                      <div class="bg-white/60 dark:bg-slate-800/60 rounded-lg p-3 text-xs text-amber-900 dark:text-amber-100 space-y-2">
                        <div class="flex items-start gap-2">
                          <span class="text-emerald-600 dark:text-emerald-400 font-bold">✓</span>
                          <span><strong>What confirmation does:</strong> Adds badges for quick navigation between related projects</span>
                        </div>
                        <div class="flex items-start gap-2">
                          <span class="text-red-600 dark:text-red-400 font-bold">✗</span>
                          <span><strong>What it doesn't do:</strong> Grant agents permission to send messages across projects</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 border border-blue-200 dark:border-blue-800 rounded-xl p-5">
                  <div class="flex items-start gap-3">
                    <div class="w-10 h-10 bg-blue-500 rounded-xl flex items-center justify-center flex-shrink-0">
                      <i data-lucide="lock" class="w-5 h-5 text-white"></i>
                    </div>
                    <div class="flex-1">
                      <h4 class="font-bold text-blue-900 dark:text-blue-100 mb-2">Why Keep Them Separate?</h4>
                      <p class="text-sm text-blue-800 dark:text-blue-200 mb-3">
                        <strong>Agent Mail uses agent-centric messaging</strong> — every message requires explicit permission. This ensures:
                      </p>
                      <div class="space-y-2 text-sm text-blue-700 dark:text-blue-300">
                        <div class="flex items-center gap-2">
                          <i data-lucide="shield" class="w-4 h-4 text-blue-600 dark:text-blue-400"></i>
                          <span><strong>Security:</strong> No surprise deliveries to unintended recipients</span>
                        </div>
                        <div class="flex items-center gap-2">
                          <i data-lucide="eye" class="w-4 h-4 text-blue-600 dark:text-blue-400"></i>
                          <span><strong>Transparency:</strong> You always know who can message whom</span>
                        </div>
                        <div class="flex items-center gap-2">
                          <i data-lucide="check-square" class="w-4 h-4 text-blue-600 dark:text-blue-400"></i>
                          <span><strong>Control:</strong> You approve every communication path</span>
                        </div>
                      </div>
                      <div class="mt-3 pt-3 border-t border-blue-200 dark:border-blue-700">
                        <p class="text-xs text-blue-700 dark:text-blue-300 italic">
                          Think of it like LinkedIn: The system suggests connections (discovery), but only you decide who can send messages (authorization).
                        </p>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="mt-6 bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700 rounded-lg p-4">
                  <div class="flex items-start gap-3">
                    <i data-lucide="info" class="w-5 h-5 text-slate-600 dark:text-slate-400 mt-0.5 flex-shrink-0"></i>
                    <div class="text-sm text-slate-700 dark:text-slate-300">
                      <strong>Where to find it:</strong> Look for the "Related Projects" section on your project cards. You'll see suggestions with confidence scores and AI-generated explanations!
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <!-- Step 3: Agents -->
          <template x-if="currentStep === 3">
            <div class="space-y-6 animate-fade-in">
              <div class="aspect-video bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-900 rounded-xl border border-slate-300 dark:border-slate-700 p-8 flex items-center justify-center">
                <div class="flex items-center gap-8">
                  <div class="text-center">
                    <div class="w-20 h-20 bg-gradient-to-br from-success-500 to-success-700 rounded-2xl flex items-center justify-center mb-3">
                      <i data-lucide="bot" class="w-10 h-10 text-white"></i>
                    </div>
                    <div class="text-sm font-semibold text-slate-700 dark:text-slate-300">Claude</div>
                  </div>
                  <i data-lucide="message-circle" class="w-8 h-8 text-slate-400"></i>
                  <div class="text-center">
                    <div class="w-20 h-20 bg-gradient-to-br from-purple-500 to-purple-700 rounded-2xl flex items-center justify-center mb-3">
                      <i data-lucide="bot" class="w-10 h-10 text-white"></i>
                    </div>
                    <div class="text-sm font-semibold text-slate-700 dark:text-slate-300">GPT-4</div>
                  </div>
                  <i data-lucide="message-circle" class="w-8 h-8 text-slate-400"></i>
                  <div class="text-center">
                    <div class="w-20 h-20 bg-gradient-to-br from-blue-500 to-blue-700 rounded-2xl flex items-center justify-center mb-3">
                      <i data-lucide="bot" class="w-10 h-10 text-white"></i>
                    </div>
                    <div class="text-sm font-semibold text-slate-700 dark:text-slate-300">Gemini</div>
                  </div>
                </div>
              </div>

              <div class="prose dark:prose-invert max-w-none">
                <h3 class="text-2xl font-bold text-slate-900 dark:text-white mb-4">What are Agents?</h3>
                <p class="text-lg text-slate-600 dark:text-slate-400 mb-4">
                  <strong>Agents</strong> are just <strong>AI assistants</strong> (like Claude, GPT, Gemini) working on your code. Each one gets a unique, memorable name.
                </p>

                <div class="bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded-lg p-4 mb-4">
                  <div class="flex items-start gap-3">
                    <i data-lucide="sparkles" class="w-5 h-5 text-purple-600 mt-0.5 flex-shrink-0"></i>
                    <div class="text-sm text-purple-900 dark:text-purple-100">
                      <strong>Fun fact:</strong> Agents get names like "BlueLake" or "GreenCastle" - much easier than "agent_7492_claude"!
                    </div>
                  </div>
                </div>

                <p class="text-slate-600 dark:text-slate-400">
                  You can:
                </p>
                <ul class="space-y-2 text-slate-600 dark:text-slate-400">
                  <li>📬 View each agent's inbox (messages sent to them)</li>
                  <li>👤 See what program/model they're using (e.g., "claude-code" with "opus-4.1")</li>
                  <li>📋 Copy their name to use in commands</li>
                </ul>
              </div>
            </div>
          </template>

          <!-- Step 4: Messages -->
          <template x-if="currentStep === 4">
            <div class="space-y-6 animate-fade-in">
              <div class="space-y-3">
                <div class="bg-white dark:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-700 p-4">
                  <div class="flex items-start gap-3 mb-2">
                    <div class="w-10 h-10 bg-gradient-to-br from-success-500 to-success-700 rounded-lg flex items-center justify-center flex-shrink-0">
                      <i data-lucide="user" class="w-5 h-5 text-white"></i>
                    </div>
                    <div class="flex-1">
                      <div class="font-semibold text-slate-900 dark:text-white">BlueLake</div>
                      <div class="text-sm text-slate-600 dark:text-slate-400">2 minutes ago</div>
                    </div>
                  </div>
                  <div class="ml-13 bg-slate-50 dark:bg-slate-900 rounded-lg p-3 text-sm text-slate-700 dark:text-slate-300">
                    Hey GreenCastle, I'm working on the authentication system. Can you handle the database migrations?
                  </div>
                </div>

                <div class="bg-white dark:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-700 p-4">
                  <div class="flex items-start gap-3 mb-2">
                    <div class="w-10 h-10 bg-gradient-to-br from-primary-500 to-primary-700 rounded-lg flex items-center justify-center flex-shrink-0">
                      <i data-lucide="user" class="w-5 h-5 text-white"></i>
                    </div>
                    <div class="flex-1">
                      <div class="font-semibold text-slate-900 dark:text-white">GreenCastle</div>
                      <div class="text-sm text-slate-600 dark:text-slate-400">1 minute ago</div>
                    </div>
                  </div>
                  <div class="ml-13 bg-slate-50 dark:bg-slate-900 rounded-lg p-3 text-sm text-slate-700 dark:text-slate-300">
                    Sure! I'll create the migration files. I'm reserving the db/migrations folder so we don't conflict.
                  </div>
                </div>
              </div>

              <div class="prose dark:prose-invert max-w-none">
                <h3 class="text-2xl font-bold text-slate-900 dark:text-white mb-4">How Agents Communicate</h3>
                <p class="text-lg text-slate-600 dark:text-slate-400 mb-4">
                  Agents send <strong>messages</strong> to each other, just like email or Slack. They can:
                </p>

                <ul class="space-y-2 text-slate-600 dark:text-slate-400">
                  <li>💬 Share what they're working on</li>
                  <li>🤝 Coordinate who does what</li>
                  <li>📝 Document decisions and changes</li>
                  <li>⚠️ Flag urgent issues</li>
                  <li>🔗 Continue conversations in threads</li>
                </ul>

                <div class="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4 mt-4">
                  <div class="flex items-start gap-3">
                    <i data-lucide="check-circle" class="w-5 h-5 text-green-600 mt-0.5 flex-shrink-0"></i>
                    <div class="text-sm text-green-900 dark:text-green-100">
                      <strong>Why this matters:</strong> Instead of agents silently stepping on each other's work, they communicate and coordinate like a team!
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <!-- Step 5: Human Overseer -->
          <template x-if="currentStep === 5">
            <div class="space-y-6 animate-fade-in">
              <!-- Eye-catching header -->
              <div class="relative overflow-hidden bg-gradient-to-br from-amber-500 via-orange-500 to-red-500 rounded-2xl p-8 shadow-2xl">
                <!-- Animated background -->
                <div class="absolute inset-0 opacity-20">
                  <div class="absolute top-0 right-0 w-64 h-64 bg-white rounded-full blur-3xl animate-pulse"></div>
                  <div class="absolute bottom-0 left-0 w-48 h-48 bg-yellow-200 rounded-full blur-3xl animate-pulse" style="animation-delay: 1s;"></div>
                </div>

                <div class="relative flex items-start gap-6">
                  <div class="w-16 h-16 bg-white/20 backdrop-blur-sm rounded-2xl flex items-center justify-center shadow-xl flex-shrink-0 float border border-white/30">
                    <i data-lucide="shield-alert" class="w-9 h-9 text-white"></i>
                  </div>
                  <div class="flex-1 text-white">
                    <div class="inline-flex items-center gap-2 px-3 py-1 bg-white/20 backdrop-blur-sm rounded-full text-xs font-bold mb-3 border border-white/30">
                      <i data-lucide="sparkles" class="w-3 h-3"></i>
                      <span>NEW FEATURE</span>
                    </div>
                    <h3 class="text-3xl font-bold mb-3">
                      You Can Guide Agents Directly!
                    </h3>
                    <p class="text-amber-50 text-lg leading-relaxed">
                      Sometimes you need to jump in and redirect your AI team. The <strong class="text-white">Human Overseer</strong> feature lets you send high-priority messages that agents will prioritize immediately.
                    </p>
                  </div>
                </div>
              </div>

              <div class="prose dark:prose-invert max-w-none">
                <h3 class="text-2xl font-bold text-slate-900 dark:text-white mb-4">When to Use Human Overseer</h3>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 not-prose mb-6">
                  <div class="bg-red-50 dark:bg-red-900/20 border-2 border-red-200 dark:border-red-800 rounded-xl p-5">
                    <div class="flex items-center gap-3 mb-3">
                      <div class="w-10 h-10 bg-red-500 rounded-lg flex items-center justify-center flex-shrink-0">
                        <i data-lucide="alert-triangle" class="w-5 h-5 text-white"></i>
                      </div>
                      <h4 class="font-bold text-red-900 dark:text-red-100 text-lg">Urgent Issues</h4>
                    </div>
                    <p class="text-sm text-red-800 dark:text-red-200">
                      "Stop everything! The production database is down. Everyone investigate the connection pool immediately."
                    </p>
                  </div>

                  <div class="bg-orange-50 dark:bg-orange-900/20 border-2 border-orange-200 dark:border-orange-800 rounded-xl p-5">
                    <div class="flex items-center gap-3 mb-3">
                      <div class="w-10 h-10 bg-orange-500 rounded-lg flex items-center justify-center flex-shrink-0">
                        <i data-lucide="zap" class="w-5 h-5 text-white"></i>
                      </div>
                      <h4 class="font-bold text-orange-900 dark:text-orange-100 text-lg">Priority Change</h4>
                    </div>
                    <p class="text-sm text-orange-800 dark:text-orange-200">
                      "New requirement from CEO: pause the dashboard and focus on the mobile app authentication first."
                    </p>
                  </div>

                  <div class="bg-blue-50 dark:bg-blue-900/20 border-2 border-blue-200 dark:border-blue-800 rounded-xl p-5">
                    <div class="flex items-center gap-3 mb-3">
                      <div class="w-10 h-10 bg-blue-500 rounded-lg flex items-center justify-center flex-shrink-0">
                        <i data-lucide="message-circle" class="w-5 h-5 text-white"></i>
                      </div>
                      <h4 class="font-bold text-blue-900 dark:text-blue-100 text-lg">Clarification</h4>
                    </div>
                    <p class="text-sm text-blue-800 dark:text-blue-200">
                      "I see you're debating API approaches. Go with REST for now - we can add GraphQL later if needed."
                    </p>
                  </div>

                  <div class="bg-purple-50 dark:bg-purple-900/20 border-2 border-purple-200 dark:border-purple-800 rounded-xl p-5">
                    <div class="flex items-center gap-3 mb-3">
                      <div class="w-10 h-10 bg-purple-500 rounded-lg flex items-center justify-center flex-shrink-0">
                        <i data-lucide="target" class="w-5 h-5 text-white"></i>
                      </div>
                      <h4 class="font-bold text-purple-900 dark:text-purple-100 text-lg">Course Correction</h4>
                    </div>
                    <p class="text-sm text-purple-800 dark:text-purple-200">
                      "The refactoring you're doing is going too deep. Focus on just the auth module for now."
                    </p>
                  </div>
                </div>

                <h3 class="text-2xl font-bold text-slate-900 dark:text-white mb-4 mt-8">How It Works</h3>

                <div class="bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-800 dark:to-slate-900 rounded-xl p-6 border-2 border-slate-200 dark:border-slate-700 not-prose mb-6">
                  <div class="space-y-4">
                    <div class="flex items-start gap-4">
                      <div class="w-8 h-8 bg-gradient-to-br from-amber-500 to-orange-600 rounded-full flex items-center justify-center text-white font-bold flex-shrink-0 shadow-md">
                        1
                      </div>
                      <div class="flex-1">
                        <div class="font-bold text-slate-900 dark:text-white mb-1">Visit Any Project</div>
                        <div class="text-sm text-slate-600 dark:text-slate-400">
                          Click the bright orange <strong>"Send Message"</strong> button with the Overseer badge
                        </div>
                      </div>
                    </div>

                    <div class="flex items-start gap-4">
                      <div class="w-8 h-8 bg-gradient-to-br from-amber-500 to-orange-600 rounded-full flex items-center justify-center text-white font-bold flex-shrink-0 shadow-md">
                        2
                      </div>
                      <div class="flex-1">
                        <div class="font-bold text-slate-900 dark:text-white mb-1">Select Recipients</div>
                        <div class="text-sm text-slate-600 dark:text-slate-400">
                          Choose which agents should receive your message. You can send to all or just specific agents.
                        </div>
                      </div>
                    </div>

                    <div class="flex items-start gap-4">
                      <div class="w-8 h-8 bg-gradient-to-br from-amber-500 to-orange-600 rounded-full flex items-center justify-center text-white font-bold flex-shrink-0 shadow-md">
                        3
                      </div>
                      <div class="flex-1">
                        <div class="font-bold text-slate-900 dark:text-white mb-1">Write Your Message</div>
                        <div class="text-sm text-slate-600 dark:text-slate-400">
                          Use the rich Markdown editor with live preview. Your message will get a special preamble.
                        </div>
                      </div>
                    </div>

                    <div class="flex items-start gap-4">
                      <div class="w-8 h-8 bg-gradient-to-br from-amber-500 to-orange-600 rounded-full flex items-center justify-center text-white font-bold flex-shrink-0 shadow-md">
                        4
                      </div>
                      <div class="flex-1">
                        <div class="font-bold text-slate-900 dark:text-white mb-1">Agents Pause & Prioritize</div>
                        <div class="text-sm text-slate-600 dark:text-slate-400">
                          Agents see it's from the Human Overseer and will pause their work to address your request first.
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="bg-amber-50 dark:bg-amber-900/20 border-2 border-amber-300 dark:border-amber-700 rounded-xl p-5 not-prose">
                  <div class="flex items-start gap-3">
                    <i data-lucide="info" class="w-6 h-6 text-amber-600 mt-0.5 flex-shrink-0"></i>
                    <div class="text-sm text-amber-900 dark:text-amber-100">
                      <p class="font-semibold mb-2">What happens to their current work?</p>
                      <p class="leading-relaxed">
                        Agents are instructed to <strong>temporarily pause</strong> their current tasks, complete your request, then <strong>resume their original plans</strong> unless you've changed the direction. Think of it like a polite interruption, not a hard reset!
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <!-- Step 6: File Reservations -->
          <template x-if="currentStep === 6">
            <div class="space-y-6 animate-fade-in">
              <div class="bg-gradient-to-br from-warning-50 to-orange-50 dark:from-warning-900/20 dark:to-orange-900/20 border border-warning-200 dark:border-warning-800 rounded-xl p-6">
                <div class="flex items-start gap-4 mb-4">
                  <div class="w-14 h-14 bg-warning-500 rounded-xl flex items-center justify-center flex-shrink-0">
                    <i data-lucide="file-lock" class="w-7 h-7 text-white"></i>
                  </div>
                  <div>
                    <h4 class="text-xl font-bold text-warning-900 dark:text-warning-100 mb-2">
                      File Reservations
                    </h4>
                    <p class="text-warning-800 dark:text-warning-200">
                      Think of it like putting a sticky note on a file: "I'm working here - please wait!"
                    </p>
                  </div>
                </div>

                <div class="bg-white dark:bg-slate-800 rounded-lg p-4 space-y-3">
                  <div class="flex items-center gap-3">
                    <i data-lucide="file-text" class="w-5 h-5 text-slate-400"></i>
                    <span class="flex-1 font-mono text-sm text-slate-700 dark:text-slate-300">src/auth/*.ts</span>
                    <span class="px-3 py-1 bg-success-100 dark:bg-success-900/30 text-success-700 dark:text-success-300 text-xs font-bold rounded-full flex items-center gap-1.5">
                      <i data-lucide="lock" class="w-3 h-3"></i>
                      Reserved by BlueLake
                    </span>
                  </div>
                  <div class="flex items-center gap-3">
                    <i data-lucide="file-text" class="w-5 h-5 text-slate-400"></i>
                    <span class="flex-1 font-mono text-sm text-slate-700 dark:text-slate-300">db/migrations/*</span>
                    <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 flex items-center gap-1.5">
                      <i data-lucide="lock" class="w-3 h-3"></i>
                      Reserved by GreenCastle
                    </span>
                  </div>
                </div>
              </div>

              <div class="prose dark:prose-invert max-w-none">
                <h3 class="text-2xl font-bold text-slate-900 dark:text-white mb-4">Preventing Edit Conflicts</h3>
                <p class="text-lg text-slate-600 dark:text-slate-400 mb-4">
                  When an agent is editing files, they can <strong>"reserve" them temporarily</strong>. This tells other agents:
                </p>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 not-prose">
                  <div class="bg-success-50 dark:bg-success-900/20 border border-success-200 dark:border-success-800 rounded-lg p-4">
                    <div class="flex items-center gap-2 mb-2">
                      <i data-lucide="check" class="w-5 h-5 text-success-600"></i>
                      <span class="font-bold text-success-900 dark:text-success-100">What it DOES:</span>
                    </div>
                    <ul class="text-sm text-success-800 dark:text-success-200 space-y-1 list-disc list-inside">
                      <li>Signals "I'm editing this"</li>
                      <li>Prevents accidental conflicts</li>
                      <li>Auto-expires after set time</li>
                      <li>Tracked in Git for transparency</li>
                    </ul>
                  </div>

                  <div class="bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg p-4">
                    <div class="flex items-center gap-2 mb-2">
                      <i data-lucide="info" class="w-5 h-5 text-slate-600"></i>
                      <span class="font-bold text-slate-900 dark:text-slate-100">What it DOESN'T:</span>
                    </div>
                    <ul class="text-sm text-slate-600 dark:text-slate-400 space-y-1 list-disc list-inside">
                      <li>Lock files permanently</li>
                      <li>Block you from editing</li>
                      <li>Require approval to use</li>
                      <li>Cause merge conflicts</li>
                    </ul>
                  </div>
                </div>

                <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mt-4">
                  <div class="flex items-start gap-3">
                    <i data-lucide="lightbulb" class="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0"></i>
                    <div class="text-sm text-blue-900 dark:text-blue-100">
                      <strong>Think of it like:</strong> When you see a "Reserved" parking spot with someone's name on it. You <em>can</em> park there if needed, but the sign helps you know someone else might be using it soon!
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <!-- Step 7: Features -->
          <template x-if="currentStep === 7">
            <div class="space-y-6 animate-fade-in">
              <div class="prose dark:prose-invert max-w-none">
                <h3 class="text-2xl font-bold text-slate-900 dark:text-white mb-6 text-center">Powerful Features Built In</h3>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl p-6">
                  <div class="flex items-center gap-3 mb-3">
                    <div class="w-10 h-10 bg-primary-100 dark:bg-primary-900/30 rounded-lg flex items-center justify-center">
                      <i data-lucide="search" class="w-5 h-5 text-primary-600"></i>
                    </div>
                    <h4 class="font-bold text-slate-900 dark:text-white">Search Everything</h4>
                  </div>
                  <p class="text-sm text-slate-600 dark:text-slate-400 mb-3">
                    Find any message, conversation, or file reservation across all projects instantly.
                  </p>
                  <div class="flex items-center gap-2 text-xs text-slate-500">
                    <kbd class="px-2 py-1 bg-slate-100 dark:bg-slate-700 rounded">⌘K</kbd>
                    <span>or</span>
                    <kbd class="px-2 py-1 bg-slate-100 dark:bg-slate-700 rounded">/</kbd>
                  </div>
                </div>

                <div class="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl p-6">
                  <div class="flex items-center gap-3 mb-3">
                    <div class="w-10 h-10 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
                      <i data-lucide="keyboard" class="w-5 h-5 text-purple-600"></i>
                    </div>
                    <h4 class="font-bold text-slate-900 dark:text-white">Keyboard Shortcuts</h4>
                  </div>
                  <p class="text-sm text-slate-600 dark:text-slate-400 mb-3">
                    Navigate at lightning speed with Gmail-style keyboard shortcuts.
                  </p>
                  <div class="flex items-center gap-2 text-xs text-slate-500">
                    <kbd class="px-2 py-1 bg-slate-100 dark:bg-slate-700 rounded">?</kbd>
                    <span>to see all shortcuts</span>
                  </div>
                </div>

                <div class="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl p-6">
                  <div class="flex items-center gap-3 mb-3">
                    <div class="w-10 h-10 bg-success-100 dark:bg-success-900/30 rounded-lg flex items-center justify-center">
                      <i data-lucide="filter" class="w-5 h-5 text-success-600"></i>
                    </div>
                    <h4 class="font-bold text-slate-900 dark:text-white">Smart Filtering</h4>
                  </div>
                  <p class="text-sm text-slate-600 dark:text-slate-400">
                    Filter by unread, urgent, sender, or search across all messages in an inbox.
                  </p>
                </div>

                <div class="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl p-6">
                  <div class="flex items-center gap-3 mb-3">
                    <div class="w-10 h-10 bg-warning-100 dark:bg-warning-900/30 rounded-lg flex items-center justify-center">
                      <i data-lucide="git-branch" class="w-5 h-5 text-warning-600"></i>
                    </div>
                    <h4 class="font-bold text-slate-900 dark:text-white">Git-Backed</h4>
                  </div>
                  <p class="text-sm text-slate-600 dark:text-slate-400">
                    Every message and reservation is saved in Git. Review the full history anytime.
                  </p>
                </div>
              </div>
            </div>
          </template>

          <!-- Final Step with Celebration -->
          <template x-if="currentStep === 8">
            <div class="space-y-6 animate-fade-in text-center" x-init="celebrateCompletion()">
              <!-- Confetti canvas -->
              <canvas id="confetti-canvas" class="fixed inset-0 pointer-events-none z-50" style="display: none;"></canvas>

              <!-- Animated success icon -->
              <div class="relative inline-block mb-6">
                <div class="absolute inset-0 bg-gradient-to-br from-success-500 to-emerald-600 rounded-3xl blur-2xl opacity-60 animate-ping" style="animation-duration: 2s;"></div>
                <div class="relative inline-flex items-center justify-center w-32 h-32 bg-gradient-to-br from-success-500 to-emerald-600 rounded-3xl shadow-2xl animate-bounce-slow">
                  <i data-lucide="check-circle" class="w-16 h-16 text-white"></i>
                </div>
              </div>

              <div>
                <h3 class="text-5xl font-bold mb-2">
                  <span class="bg-gradient-to-r from-success-600 via-emerald-600 to-green-600 bg-clip-text text-transparent">
                    You're All Set!
                  </span>
                  <span class="inline-block animate-wave text-4xl ml-2">🎉</span>
                </h3>
                <p class="text-xl text-slate-600 dark:text-slate-400 max-w-2xl mx-auto mb-6">
                  You now understand how Agent Mail helps AI assistants work together smoothly!
                </p>

                <!-- Achievement badge -->
                <div class="inline-flex items-center gap-3 px-6 py-3 bg-gradient-to-r from-success-50 to-emerald-50 dark:from-success-900/20 dark:to-emerald-900/20 border-2 border-success-200 dark:border-success-800 rounded-full shadow-lg mb-8">
                  <i data-lucide="award" class="w-5 h-5 text-success-600"></i>
                  <span class="font-bold text-success-900 dark:text-success-100">Tutorial Complete</span>
                  <i data-lucide="sparkles" class="w-5 h-5 text-success-600"></i>
                </div>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
                <div class="bg-primary-50 dark:bg-primary-900/20 border border-primary-200 dark:border-primary-800 rounded-xl p-4">
                  <div class="text-4xl mb-2">⌘K</div>
                  <div class="font-semibold text-slate-900 dark:text-white">Command Palette</div>
                  <div class="text-xs text-slate-600 dark:text-slate-400">Quick navigation</div>
                </div>

                <div class="bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded-xl p-4">
                  <div class="text-4xl mb-2">?</div>
                  <div class="font-semibold text-slate-900 dark:text-white">Keyboard Help</div>
                  <div class="text-xs text-slate-600 dark:text-slate-400">See all shortcuts</div>
                </div>

                <div class="bg-success-50 dark:bg-success-900/20 border border-success-200 dark:border-success-800 rounded-xl p-4">
                  <div class="text-4xl mb-2">💡</div>
                  <div class="font-semibold text-slate-900 dark:text-white">Tooltips Everywhere</div>
                  <div class="text-xs text-slate-600 dark:text-slate-400">Hover for help</div>
                </div>
              </div>

              <div class="bg-gradient-to-r from-primary-50 to-purple-50 dark:from-primary-900/20 dark:to-purple-900/20 border border-primary-200 dark:border-primary-800 rounded-xl p-6">
                <div class="flex items-start gap-3 text-left">
                  <i data-lucide="info" class="w-5 h-5 text-primary-600 mt-0.5 flex-shrink-0"></i>
                  <div class="text-sm text-primary-900 dark:text-primary-100">
                    <strong>Need help later?</strong> Click the <i data-lucide="help-circle" class="w-4 h-4 inline-block"></i> button in the header to access the Help Center, or press <kbd class="px-1.5 py-0.5 bg-white dark:bg-slate-700 rounded text-xs">?</kbd> for shortcuts!
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>

        <!-- Footer with Navigation -->
        <div class="px-8 py-6 bg-slate-50 dark:bg-slate-900 border-t border-slate-200 dark:border-slate-700 flex items-center justify-between">
          <button @click="previous()"
                  x-show="currentStep > 0"
                  class="px-6 py-3 bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-300 font-semibold rounded-lg border border-slate-300 dark:border-slate-600 transition-all duration-200 flex items-center gap-2">
            <i data-lucide="chevron-left" class="w-4 h-4"></i>
            Back
          </button>

          <div class="flex items-center gap-2">
            <template x-for="(step, index) in steps" :key="index">
              <button @click="currentStep = index"
                      :class="index === currentStep ? 'w-8 bg-primary-600' : 'w-2 bg-slate-300 dark:bg-slate-600 hover:bg-slate-400 dark:hover:bg-slate-500'"
                      class="h-2 rounded-full transition-all duration-300"
                      :aria-label="'Go to step ' + (index + 1)"></button>
            </template>
          </div>

          <button @click="next()"
                  class="px-6 py-3 bg-gradient-to-r from-primary-600 to-purple-600 hover:from-primary-700 hover:to-purple-700 text-white font-semibold rounded-lg shadow-md hover:shadow-lg transition-all duration-300 flex items-center gap-2 btn-ripple">
            <span x-text="currentStep < steps.length - 1 ? 'Next' : 'Get Started'"></span>
            <i data-lucide="chevron-right" class="w-4 h-4" x-show="currentStep < steps.length - 1"></i>
            <i data-lucide="check" class="w-4 h-4" x-show="currentStep === steps.length - 1"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- Keyboard Shortcuts Help Panel -->
    <div x-data="{ showShortcuts: false }"
         @keydown.window.prevent.shift.question="showShortcuts = !showShortcuts"
         @keydown.escape.window="showShortcuts = false"
         x-show="showShortcuts"
         x-cloak
         class="fixed inset-0 z-[100] flex items-center justify-center p-4"
         style="display: none;">
      <!-- Backdrop -->
      <div @click="showShortcuts = false"
           x-show="showShortcuts"
           x-transition:enter="transition ease-out duration-200"
           x-transition:enter-start="opacity-0"
           x-transition:enter-end="opacity-100"
           x-transition:leave="transition ease-in duration-150"
           x-transition:leave-start="opacity-100"
           x-transition:leave-end="opacity-0"
           class="absolute inset-0 bg-slate-900/50 backdrop-blur-sm"></div>

      <!-- Shortcuts Panel -->
      <div x-show="showShortcuts"
           x-transition:enter="transition ease-out duration-200"
           x-transition:enter-start="opacity-0 transform scale-95"
           x-transition:enter-end="opacity-100 transform scale-100"
           x-transition:leave="transition ease-in duration-150"
           x-transition:leave-start="opacity-100 transform scale-100"
           x-transition:leave-end="opacity-0 transform scale-95"
           class="relative w-full max-w-3xl glass rounded-2xl shadow-2xl border border-slate-200 dark:border-slate-700 overflow-hidden max-h-[80vh] flex flex-col">

        <!-- Header -->
        <div class="px-8 py-6 bg-gradient-to-r from-primary-500 to-primary-700 text-white flex items-center justify-between">
          <div class="flex items-center gap-4">
            <div class="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
              <i data-lucide="keyboard" class="w-6 h-6"></i>
            </div>
            <div>
              <h2 class="text-2xl font-bold">Keyboard Shortcuts</h2>
              <p class="text-primary-100 text-sm">Work faster with keyboard navigation</p>
            </div>
          </div>
          <button @click="showShortcuts = false"
                  class="w-10 h-10 bg-white/20 hover:bg-white/30 rounded-lg flex items-center justify-center transition-colors">
            <i data-lucide="x" class="w-5 h-5"></i>
          </button>
        </div>

        <!-- Shortcuts List -->
        <div class="flex-1 overflow-y-auto p-8">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- Global Shortcuts -->
            <div>
              <h3 class="text-sm font-bold text-slate-900 dark:text-white uppercase tracking-wide mb-4 flex items-center gap-2">
                <i data-lucide="globe" class="w-4 h-4 text-primary-600"></i>
                Global
              </h3>
              <div class="space-y-3">
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Command palette</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">⌘K</kbd>
                </div>
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">This help panel</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">?</kbd>
                </div>
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Focus search</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">/</kbd>
                </div>
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Go to projects</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">G+P</kbd>
                </div>
              </div>
            </div>

            <!-- Navigation -->
            <div>
              <h3 class="text-sm font-bold text-slate-900 dark:text-white uppercase tracking-wide mb-4 flex items-center gap-2">
                <i data-lucide="compass" class="w-4 h-4 text-success-600"></i>
                Navigation
              </h3>
              <div class="space-y-3">
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Next item</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">J</kbd>
                </div>
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Previous item</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">K</kbd>
                </div>
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Open item</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">Enter</kbd>
                </div>
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Go back</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">Esc</kbd>
                </div>
              </div>
            </div>

            <!-- Actions -->
            <div>
              <h3 class="text-sm font-bold text-slate-900 dark:text-white uppercase tracking-wide mb-4 flex items-center gap-2">
                <i data-lucide="zap" class="w-4 h-4 text-warning-600"></i>
                Actions
              </h3>
              <div class="space-y-3">
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Refresh</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">R</kbd>
                </div>
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Copy to clipboard</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">⌘C</kbd>
                </div>
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Toggle dark mode</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">D</kbd>
                </div>
              </div>
            </div>

            <!-- Message Actions -->
            <div>
              <h3 class="text-sm font-bold text-slate-900 dark:text-white uppercase tracking-wide mb-4 flex items-center gap-2">
                <i data-lucide="mail" class="w-4 h-4 text-danger-600"></i>
                Messages
              </h3>
              <div class="space-y-3">
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Reply</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">Shift+R</kbd>
                </div>
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Forward</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">Shift+F</kbd>
                </div>
                <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
                  <span class="text-sm text-slate-700 dark:text-slate-300">Mark as read</span>
                  <kbd class="px-2 py-1 bg-white dark:bg-slate-700 rounded border border-slate-300 dark:border-slate-600 text-xs">E</kbd>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Enhanced Toast Notification Container with Progress Bars -->
    <div x-data="toastManager()" @toast.window="show($event.detail)"
         class="fixed top-4 right-4 z-50 space-y-3 max-w-md"
         role="region" aria-label="Notifications">
      <template x-for="toast in toasts" :key="toast.id">
        <div x-show="toast.visible"
             x-transition:enter="transition ease-out duration-300 transform"
             x-transition:enter-start="opacity-0 translate-x-full scale-95"
             x-transition:enter-end="opacity-100 translate-x-0 scale-100"
             x-transition:leave="transition ease-in duration-200 transform"
             x-transition:leave-start="opacity-100 translate-x-0 scale-100"
             x-transition:leave-end="opacity-0 translate-x-full scale-95"
             class="glass rounded-xl shadow-2xl border border-slate-200 dark:border-slate-700 overflow-hidden elevate-on-hover"
             :class="{
               'border-l-4 border-l-success-500': toast.type === 'success',
               'border-l-4 border-l-danger-500': toast.type === 'error',
               'border-l-4 border-l-warning-500': toast.type === 'warning',
               'border-l-4 border-l-primary-500': toast.type === 'info'
             }"
             role="alert"
             :aria-live="toast.type === 'error' ? 'assertive' : 'polite'">

          <!-- Toast Content -->
          <div class="p-4">
            <div class="flex items-start gap-3">
              <!-- Icon with animation -->
              <div class="flex-shrink-0 mt-0.5">
                <div class="w-10 h-10 rounded-lg flex items-center justify-center"
                     :class="{
                       'bg-success-100 dark:bg-success-900/30': toast.type === 'success',
                       'bg-danger-100 dark:bg-danger-900/30': toast.type === 'error',
                       'bg-warning-100 dark:bg-warning-900/30': toast.type === 'warning',
                       'bg-primary-100 dark:bg-primary-900/30': toast.type === 'info'
                     }">
                  <template x-if="toast.type === 'success'">
                    <i data-lucide="check-circle" class="w-5 h-5 text-success-600 dark:text-success-400"></i>
                  </template>
                  <template x-if="toast.type === 'error'">
                    <i data-lucide="alert-circle" class="w-5 h-5 text-danger-600 dark:text-danger-400"></i>
                  </template>
                  <template x-if="toast.type === 'warning'">
                    <i data-lucide="alert-triangle" class="w-5 h-5 text-warning-600 dark:text-warning-400"></i>
                  </template>
                  <template x-if="toast.type === 'info'">
                    <i data-lucide="info" class="w-5 h-5 text-primary-600 dark:text-primary-400"></i>
                  </template>
                </div>
              </div>

              <!-- Content -->
              <div class="flex-1 min-w-0">
                <div x-show="toast.title" class="text-sm font-bold text-slate-900 dark:text-white mb-1" x-text="toast.title"></div>
                <p class="text-sm text-slate-700 dark:text-slate-300" :class="{ 'font-medium': !toast.title }" x-text="toast.message"></p>

                <!-- Optional action button -->
                <div x-show="toast.action" class="mt-3">
                  <button @click="executeAction(toast)"
                          class="text-xs font-semibold px-3 py-1.5 rounded-lg transition-all duration-200"
                          :class="{
                            'bg-success-600 hover:bg-success-700 text-white': toast.type === 'success',
                            'bg-danger-600 hover:bg-danger-700 text-white': toast.type === 'error',
                            'bg-warning-600 hover:bg-warning-700 text-white': toast.type === 'warning',
                            'bg-primary-600 hover:bg-primary-700 text-white': toast.type === 'info'
                          }"
                          x-text="toast.actionText || 'Action'">
                  </button>
                </div>
              </div>

              <!-- Close button -->
              <button @click="remove(toast.id)"
                      class="flex-shrink-0 p-1 rounded-lg text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
                      aria-label="Close notification">
                <i data-lucide="x" class="w-4 h-4"></i>
              </button>
            </div>
          </div>

          <!-- Progress bar -->
          <div x-show="toast.showProgress" class="h-1 bg-slate-200 dark:bg-slate-700 relative overflow-hidden">
            <div class="absolute inset-y-0 left-0 transition-all duration-100 ease-linear"
                 :class="{
                   'bg-success-500': toast.type === 'success',
                   'bg-danger-500': toast.type === 'error',
                   'bg-warning-500': toast.type === 'warning',
                   'bg-primary-500': toast.type === 'info'
                 }"
                 :style="`width: ${toast.progress}%`">
            </div>
          </div>
        </div>
      </template>
    </div>

    <!-- Navigation Header -->
    <nav class="glass sticky top-0 z-40 border-b border-slate-200/80 dark:border-slate-700/80">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <!-- Logo and Brand -->
          <div class="flex items-center gap-8">
            <a href="/mail" class="flex items-center gap-3 group">
              <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-primary-500 to-primary-700 flex items-center justify-center shadow-medium group-hover:shadow-glow transition-all duration-300">
                <i data-lucide="mail" class="w-5 h-5 text-white"></i>
              </div>
              <span class="text-xl font-bold bg-gradient-to-r from-primary-600 to-primary-800 dark:from-primary-400 dark:to-primary-600 bg-clip-text text-transparent">
                Agent Mail
              </span>
            </a>

            <!-- Breadcrumbs -->
            {% block breadcrumbs %}{% endblock %}
          </div>

          <!-- Right side actions -->
          <div class="flex items-center gap-3">
            {% block header_actions %}{% endblock %}

            <!-- Help Button -->
            <button onclick="window.restartTutorial()"
                    class="p-2 rounded-lg hover:bg-primary-100 dark:hover:bg-primary-900/30 text-primary-600 dark:text-primary-400 transition-all duration-200 relative group"
                    data-tippy-content="Show interactive tutorial"
                    aria-label="Show help">
              <i data-lucide="help-circle" class="w-5 h-5"></i>
              <!-- Pulsing indicator for first-time users -->
              <span class="absolute -top-1 -right-1 w-3 h-3 bg-success-500 rounded-full animate-pulse"
                    style="display: none;"
                    id="help-indicator"></span>
            </button>

            <!-- Dark Mode Toggle -->
            <button @click="toggleDarkMode()"
                    class="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
                    data-tippy-content="Toggle dark/light mode"
                    aria-label="Toggle dark mode">
              <svg x-show="!darkMode" xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-slate-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
                <path stroke-linecap="round" stroke-linejoin="round" d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
              </svg>
              <svg x-show="darkMode" xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-yellow-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
                <circle cx="12" cy="12" r="4" />
                <path stroke-linecap="round" stroke-linejoin="round" d="M12 2v2m0 16v2m10-10h-2M6 12H4m15.364 6.364-1.414-1.414M6.05 6.05 4.636 4.636m12.728 0-1.414 1.414M6.05 17.95l-1.414 1.414" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- Main Content -->
    <main id="main-content" class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 page-enter">
      {% block content %}{% endblock %}
    </main>

    <!-- Footer -->
    <footer class="border-t border-slate-200 dark:border-slate-800 mt-16">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div class="flex items-center justify-between text-sm text-slate-500 dark:text-slate-400">
          <p>MCP Agent Mail &copy; 2025</p>
          <div class="flex items-center gap-4">
            <!-- Footer links commented out until destinations are available -->
            <!-- <a href="#" class="hover:text-primary-600 dark:hover:text-primary-400 transition-colors">Documentation</a> -->
            <!-- <a href="#" class="hover:text-primary-600 dark:hover:text-primary-400 transition-colors">API</a> -->
            <!-- <a href="#" class="hover:text-primary-600 dark:hover:text-primary-400 transition-colors">Support</a> -->
          </div>
        </div>
      </div>
    </footer>

    <!-- Alpine.js Components -->
    <script>
      function darkModeController() {
        return {
          darkMode: document.documentElement.classList.contains('dark'),
          init() {
            try {
              const stored = localStorage.getItem('darkMode');
              if (stored === null) {
                localStorage.setItem('darkMode', String(this.darkMode));
              } else {
                this.darkMode = stored === 'true';
              }
            } catch (error) {
              this.darkMode = document.documentElement.classList.contains('dark');
            }
            const apply = (value) => {
              document.documentElement.classList.toggle('dark', value);
              try {
                localStorage.setItem('darkMode', String(value));
              } catch (error) {
                // ignore storage failures (e.g., private mode)
              }
            };
            apply(this.darkMode);
            this.$watch('darkMode', (value) => {
              apply(value);
              window.dispatchEvent(new CustomEvent('darkmode-change', { detail: { darkMode: value } }));
            });
            window.setDarkMode = (value) => {
              this.darkMode = Boolean(value);
            };
            window.toggleDarkMode = () => {
              this.darkMode = !this.darkMode;
            };
          },
          toggleDarkMode() {
            this.darkMode = !this.darkMode;
          },
        };
      }

      // Tutorial Manager
      function tutorialManager() {
        return {
          isActive: false,
          currentStep: 0,
          highlightElement: false,
          spotlightX: 0,
          spotlightY: 0,
          spotlightSize: 150,
          completedActions: [],
          // Cleanup tracking
          eventListeners: [],
          animationCleanup: null,
          steps: [
            { title: 'Welcome to Agent Mail', icon: 'mail', actions: [] },
            { title: 'What are Projects?', icon: 'folder', actions: ['viewed_projects'] },
            { title: 'Related Projects', icon: 'git-branch', actions: ['learned_siblings'] },
            { title: 'What are Agents?', icon: 'bot', actions: ['learned_agents'] },
            { title: 'How Agents Communicate', icon: 'message-square', actions: ['learned_messages'] },
            { title: 'Human Overseer', icon: 'shield-alert', actions: ['learned_overseer'] },
            { title: 'File Reservations', icon: 'file-lock', actions: ['learned_reservations'] },
            { title: 'Powerful Features', icon: 'sparkles', actions: ['learned_features'] },
            { title: 'You\'re All Set!', icon: 'check-circle', actions: [] }
          ],

          // Computed progress with divide-by-zero protection
          get progress() {
            if (this.steps.length === 0) return 0;
            return ((this.currentStep + 1) / this.steps.length) * 100;
          },

          init() {
            // Check if user has seen tutorial
            const hasSeenTutorial = localStorage.getItem('agentmail_tutorial_completed');

            // Load completed actions
            const savedActions = localStorage.getItem('agentmail_tutorial_actions');
            if (savedActions) {
              try {
                this.completedActions = JSON.parse(savedActions);
              } catch (e) {
                this.completedActions = [];
              }
            }

            if (!hasSeenTutorial) {
              // Show tutorial on first visit (with slight delay for page to render)
              setTimeout(() => {
                this.isActive = true;
                this.$nextTick(() => lucide.createIcons());
              }, 800);
            }

            // Listen for restart event (track for cleanup)
            const restartHandler = () => { this.restart(); };
            window.addEventListener('restart-tutorial', restartHandler);
            this.eventListeners.push({ target: window, event: 'restart-tutorial', handler: restartHandler });

            // Listen for user actions
            this.trackUserActions();
          },

          destroy() {
            // Clean up all event listeners
            this.eventListeners.forEach(({ target, event, handler }) => {
              target.removeEventListener(event, handler);
            });
            this.eventListeners = [];

            // Clean up animation timers
            if (this.animationCleanup) {
              this.animationCleanup();
              this.animationCleanup = null;
            }
          },

          next() {
            if (this.currentStep < this.steps.length - 1) {
              // Mark current step actions as complete
              const currentActions = this.steps[this.currentStep].actions;
              currentActions.forEach(action => {
                if (!this.completedActions.includes(action)) {
                  this.completedActions.push(action);
                }
              });
              this.saveProgress();

              this.currentStep++;
              this.$nextTick(() => lucide.createIcons());
            } else {
              this.complete();
            }
          },

          previous() {
            if (this.currentStep > 0) {
              this.currentStep--;
              this.$nextTick(() => lucide.createIcons());
            }
          },

          skip() {
            this.complete();
          },

          complete() {
            // Clean up any running animations
            if (this.animationCleanup) {
              this.animationCleanup();
              this.animationCleanup = null;
            }

            localStorage.setItem('agentmail_tutorial_completed', 'true');
            this.saveProgress();
            this.isActive = false;
            window.showToast('Tutorial completed! Press ? for keyboard shortcuts anytime.', 'success', 4000);
          },

          restart() {
            this.currentStep = 0;
            this.isActive = true;
            this.completedActions = [];
            localStorage.removeItem('agentmail_tutorial_completed');
            this.$nextTick(() => lucide.createIcons());
          },

          saveProgress() {
            localStorage.setItem('agentmail_tutorial_actions', JSON.stringify(this.completedActions));
          },

          // Track user actions to detect when they actually try features
          trackUserActions() {
            // Detect command palette usage (track for cleanup)
            const keydownHandler = (e) => {
              if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
                this.markActionComplete('used_command_palette');
              }
              if (e.shiftKey && e.key === '?') {
                this.markActionComplete('viewed_shortcuts');
              }
            };
            document.addEventListener('keydown', keydownHandler);
            this.eventListeners.push({ target: document, event: 'keydown', handler: keydownHandler });
          },

          markActionComplete(action) {
            if (!this.completedActions.includes(action)) {
              this.completedActions.push(action);
              this.saveProgress();
              // Show micro-feedback
              if (this.isActive) {
                this.showMicroFeedback(action);
              }
            }
          },

          showMicroFeedback(action) {
            // Small toast or sparkle effect
            const messages = {
              'used_command_palette': '✨ Nice! You used the command palette!',
              'viewed_shortcuts': '⌨️ Great! You checked the shortcuts!',
              'clicked_inbox': '📬 You found the inbox!',
              'searched_messages': '🔍 You tried searching!'
            };

            if (messages[action]) {
              window.showToast(messages[action], 'success', 2000);
            }
          },

          // Highlight a specific element with spotlight
          highlightUIElement(selector) {
            const element = document.querySelector(selector);
            if (element) {
              const rect = element.getBoundingClientRect();
              // Account for page scroll position
              const scrollX = window.pageXOffset || document.documentElement.scrollLeft;
              const scrollY = window.pageYOffset || document.documentElement.scrollTop;

              this.spotlightX = rect.left + scrollX + rect.width / 2;
              this.spotlightY = rect.top + scrollY + rect.height / 2;
              this.spotlightSize = Math.max(rect.width, rect.height) / 2 + 20;
              this.highlightElement = true;

              // Add pulse class to element
              element.classList.add('tutorial-spotlight');
            }
          },

          clearHighlight() {
            this.highlightElement = false;
            document.querySelectorAll('.tutorial-spotlight').forEach(el => {
              el.classList.remove('tutorial-spotlight');
            });
          },

          // Confetti celebration
          celebrateCompletion() {
            // Use $nextTick to ensure canvas is rendered before trying to use it
            this.$nextTick(() => {
              // Wait one more tick for DOM to fully settle
              setTimeout(() => {
                this.launchConfetti();
                lucide.createIcons();
              }, 100);
            });
          },

          launchConfetti() {
            const canvas = document.getElementById('confetti-canvas');
            if (!canvas) {
              console.warn('Confetti canvas not found - skipping animation');
              return;
            }

            // Clean up any existing animation first
            if (this.animationCleanup) {
              this.animationCleanup();
            }

            canvas.style.display = 'block';
            const ctx = canvas.getContext('2d');
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            const confetti = [];
            const confettiCount = 150;
            const colors = ['#6366f1', '#8b5cf6', '#ec4899', '#10b981', '#f59e0b'];

            for (let i = 0; i < confettiCount; i++) {
              confetti.push({
                x: Math.random() * canvas.width,
                y: Math.random() * canvas.height - canvas.height,
                r: Math.random() * 6 + 4,
                d: Math.random() * confettiCount,
                color: colors[Math.floor(Math.random() * colors.length)],
                tilt: Math.random() * 10 - 10,
                tiltAngleIncremental: Math.random() * 0.07 + 0.05,
                tiltAngle: 0
              });
            }

            let animationFrame;
            let timeoutId;
            const draw = () => {
              ctx.clearRect(0, 0, canvas.width, canvas.height);

              confetti.forEach((c, i) => {
                ctx.beginPath();
                ctx.lineWidth = c.r / 2;
                ctx.strokeStyle = c.color;
                ctx.moveTo(c.x + c.tilt + c.r / 3, c.y);
                ctx.lineTo(c.x + c.tilt, c.y + c.tilt + c.r / 5);
                ctx.stroke();

                c.tiltAngle += c.tiltAngleIncremental;
                c.y += (Math.cos(c.d) + 3 + c.r / 2) / 2;
                c.x += Math.sin(c.d);
                c.tilt = Math.sin(c.tiltAngle - i / 3) * 15;

                if (c.y > canvas.height) {
                  confetti[i] = {
                    x: Math.random() * canvas.width,
                    y: -10,
                    r: c.r,
                    d: c.d,
                    color: c.color,
                    tilt: c.tilt,
                    tiltAngleIncremental: c.tiltAngleIncremental,
                    tiltAngle: c.tiltAngle
                  };
                }
              });

              animationFrame = requestAnimationFrame(draw);
            };

            draw();

            // Stop after 5 seconds and track for cleanup
            timeoutId = setTimeout(() => {
              cancelAnimationFrame(animationFrame);
              canvas.style.display = 'none';
              this.animationCleanup = null;
            }, 5000);

            // Store cleanup function
            this.animationCleanup = () => {
              if (animationFrame) cancelAnimationFrame(animationFrame);
              if (timeoutId) clearTimeout(timeoutId);
              if (canvas) canvas.style.display = 'none';
            };
          }
        };
      }

      // Make tutorial restart available globally
      window.restartTutorial = function() {
        window.dispatchEvent(new CustomEvent('restart-tutorial'));
      };

      // Command Palette
      function commandPalette() {
        return {
          isOpen: false,
          query: '',
          selectedIndex: 0,
          commands: [
            // Navigation Commands
            {
              id: 'nav-projects',
              title: 'Go to Projects',
              description: 'View all projects',
              icon: 'folder',
              iconBg: 'rgba(99, 102, 241, 0.1)',
              iconColor: 'text-primary-600',
              shortcut: 'G+P',
              action: () => window.location.href = '/mail',
              keywords: 'projects home list'
            },
            {
              id: 'nav-search',
              title: 'Search Messages',
              description: 'Find messages across projects',
              icon: 'search',
              iconBg: 'rgba(139, 92, 246, 0.1)',
              iconColor: 'text-purple-600',
              shortcut: '/',
              action: () => {
                const input = document.querySelector('input[type="search"], input[name="q"]');
                if (input) { input.focus(); input.select(); }
              },
              keywords: 'search find query messages'
            },
            {
              id: 'toggle-dark',
              title: 'Toggle Dark Mode',
              description: 'Switch between light and dark themes',
              icon: 'moon',
              iconBg: 'rgba(234, 179, 8, 0.1)',
              iconColor: 'text-yellow-600',
              shortcut: 'D',
              action: () => {
                if (window.toggleDarkMode) {
                  window.toggleDarkMode();
                } else {
                  const html = document.documentElement;
                  const next = !html.classList.contains('dark');
                  html.classList.toggle('dark', next);
                  localStorage.setItem('darkMode', String(next));
                }
              },
              keywords: 'dark mode theme light toggle'
            },
            {
              id: 'refresh',
              title: 'Refresh Page',
              description: 'Reload current page',
              icon: 'refresh-cw',
              iconBg: 'rgba(16, 185, 129, 0.1)',
              iconColor: 'text-success-600',
              shortcut: 'R',
              action: () => window.location.reload(),
              keywords: 'refresh reload update'
            },
            {
              id: 'show-shortcuts',
              title: 'Keyboard Shortcuts',
              description: 'View all keyboard shortcuts',
              icon: 'keyboard',
              iconBg: 'rgba(236, 72, 153, 0.1)',
              iconColor: 'text-pink-600',
              shortcut: '?',
              action: () => {
                this.close();
                // Trigger the shortcuts panel
                window.dispatchEvent(new KeyboardEvent('keydown', { key: '?', shiftKey: true }));
              },
              keywords: 'help shortcuts keyboard keys commands'
            },
            {
              id: 'show-tutorial',
              title: 'Interactive Tutorial',
              description: 'Learn how Agent Mail works',
              icon: 'graduation-cap',
              iconBg: 'rgba(16, 185, 129, 0.1)',
              iconColor: 'text-success-600',
              action: () => {
                this.close();
                setTimeout(() => window.restartTutorial(), 200);
              },
              keywords: 'help tutorial guide learning onboarding walkthrough intro'
            },
            // Action Commands
            {
              id: 'copy-url',
              title: 'Copy Page URL',
              description: 'Copy current page URL to clipboard',
              icon: 'link',
              iconBg: 'rgba(59, 130, 246, 0.1)',
              iconColor: 'text-blue-600',
              action: () => {
                navigator.clipboard.writeText(window.location.href);
                window.showToast('URL copied to clipboard!', 'success', 2000);
              },
              keywords: 'copy url link clipboard share'
            }
          ],
          filteredCommands: [],

          init() {
            this.filteredCommands = this.commands;

            // Watch for open state changes
            this.$watch('isOpen', (value) => {
              if (value) {
                // Focus search input when opened
                this.$nextTick(() => {
                  this.$refs.searchInput?.focus();
                });
              } else {
                // Reset when closed
                this.query = '';
                this.selectedIndex = 0;
                this.filteredCommands = this.commands;
              }
            });
          },

          toggle() {
            this.isOpen = !this.isOpen;
          },

          close() {
            this.isOpen = false;
          },

          search() {
            if (!this.query.trim()) {
              this.filteredCommands = this.commands;
              this.selectedIndex = 0;
              return;
            }

            // Use Fuse.js for fuzzy search if available
            if (typeof Fuse !== 'undefined') {
              const fuse = new Fuse(this.commands, {
                keys: ['title', 'description', 'keywords'],
                threshold: 0.4,
                includeScore: true
              });

              const results = fuse.search(this.query);
              this.filteredCommands = results.map(r => r.item);
            } else {
              // Fallback: simple string matching
              const query = this.query.toLowerCase();
              this.filteredCommands = this.commands.filter(cmd => {
                return cmd.title.toLowerCase().includes(query) ||
                       (cmd.description && cmd.description.toLowerCase().includes(query)) ||
                       (cmd.keywords && cmd.keywords.toLowerCase().includes(query));
              });
            }

            this.selectedIndex = 0;
          },

          selectNext() {
            this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredCommands.length - 1);
          },

          selectPrevious() {
            this.selectedIndex = Math.max(this.selectedIndex - 1, 0);
          },

          executeSelected() {
            if (this.filteredCommands[this.selectedIndex]) {
              this.execute(this.filteredCommands[this.selectedIndex]);
            }
          },

          execute(command) {
            if (command && command.action) {
              command.action();
              this.close();
            }
          }
        };
      }

      // Enhanced Toast Manager with Progress Bars and Actions
      function toastManager() {
        return {
          toasts: [],
          nextId: 1,
          maxToasts: 5,

          show(detail) {
            const id = this.nextId++;
            const duration = detail.duration || 5000;
            const showProgress = detail.showProgress !== false;

            const toast = {
              id,
              message: detail.message,
              title: detail.title || null,
              type: detail.type || 'info',
              visible: true,
              showProgress,
              progress: 100,
              action: detail.action || null,
              actionText: detail.actionText || 'Action',
              pausedAt: null
            };

            // Limit number of toasts
            if (this.toasts.length >= this.maxToasts) {
              this.remove(this.toasts[0].id);
            }

            this.toasts.push(toast);

            // Progress bar countdown
            if (showProgress && duration > 0) {
              const startTime = Date.now();
              const interval = setInterval(() => {
                if (!this.toasts.find(t => t.id === id)) {
                  clearInterval(interval);
                  return;
                }

                const elapsed = Date.now() - startTime;
                const remaining = duration - elapsed;
                toast.progress = Math.max(0, (remaining / duration) * 100);

                if (remaining <= 0) {
                  clearInterval(interval);
                }
              }, 50);
            }

            // Auto-remove after duration
            if (duration > 0) {
              setTimeout(() => {
                this.remove(id);
              }, duration);
            }

            // Re-initialize icons for the new toast
            this.$nextTick(() => {
              if (typeof lucide !== 'undefined') {
                lucide.createIcons();
              }
            });
          },

          remove(id) {
            const index = this.toasts.findIndex(t => t.id === id);
            if (index > -1) {
              this.toasts[index].visible = false;
              setTimeout(() => {
                this.toasts.splice(index, 1);
              }, 300);
            }
          },

          executeAction(toast) {
            if (toast.action && typeof toast.action === 'function') {
              toast.action();
            }
            this.remove(toast.id);
          },

          pauseToast(id) {
            const toast = this.toasts.find(t => t.id === id);
            if (toast && !toast.pausedAt) {
              toast.pausedAt = Date.now();
            }
          },

          resumeToast(id) {
            const toast = this.toasts.find(t => t.id === id);
            if (toast && toast.pausedAt) {
              toast.pausedAt = null;
            }
          }
        }
      }

      // Initialize Lucide icons after page load
      document.addEventListener('DOMContentLoaded', () => {
        if (typeof lucide !== 'undefined') {
          lucide.createIcons();

          // Re-initialize on Alpine mutations with throttling for performance
          let iconUpdateTimeout;
          const observer = new MutationObserver(() => {
            clearTimeout(iconUpdateTimeout);
            iconUpdateTimeout = setTimeout(() => {
              if (typeof lucide !== 'undefined') {
                lucide.createIcons();
              }
            }, 100); // Throttle to max once per 100ms
          });

          observer.observe(document.body, {
            childList: true,
            subtree: true
          });
        }
      });

      // Enhanced helper function to show toast from anywhere with optional features
      window.showToast = function(message, type = 'info', duration = 5000, options = {}) {
        const detail = {
          message,
          type,
          duration,
          title: options.title || null,
          showProgress: options.showProgress !== false,
          action: options.action || null,
          actionText: options.actionText || 'Action'
        };

        window.dispatchEvent(new CustomEvent('toast', { detail }));
      };

      // Show toast with action button
      window.showToastWithAction = function(message, type, actionText, actionCallback, duration = 5000) {
        window.showToast(message, type, duration, {
          actionText,
          action: actionCallback
        });
      };

      // Show loading toast (doesn't auto-dismiss)
      window.showLoadingToast = function(message, title = null) {
        window.showToast(message, 'info', 0, {
          title: title || 'Loading',
          showProgress: true
        });
      };

      // Initialize Day.js plugins
      // Note: Day.js plugins from CDN auto-register, so manual extension is not needed
      // They're available immediately after script load

      // NProgress configuration
      if (typeof NProgress !== 'undefined') {
        NProgress.configure({
          showSpinner: false,
          trickleSpeed: 200,
          minimum: 0.1
        });

        // Initialize in DOMContentLoaded for consistency
        document.addEventListener('DOMContentLoaded', () => {
          let progressTimeout; // Store timeout to prevent accumulation

          // Show progress on internal link clicks
          document.addEventListener('click', (e) => {
            const link = e.target.closest('a');
            if (link && link.href && !link.target && !link.download) {
              try {
                const url = new URL(link.href);
                // Only for same-origin links that aren't hash-only or javascript:
                if (url.origin === window.location.origin &&
                    url.pathname !== window.location.pathname &&
                    url.protocol !== 'javascript:') {
                  clearTimeout(progressTimeout); // Clear any existing timeout
                  NProgress.start();
                  // Safety: complete after 3s if navigation doesn't complete
                  progressTimeout = setTimeout(() => NProgress.done(), 3000);
                }
              } catch (e) {
                // Invalid URL, ignore
                console.debug('Invalid URL for NProgress:', link.href);
              }
            }
          });

          // Complete on page load
          window.addEventListener('load', () => {
            NProgress.done();
          });

          // Intercept fetch requests
          const originalFetch = window.fetch;
          window.fetch = function(...args) {
            NProgress.start();
            return originalFetch.apply(this, args)
              .finally(() => NProgress.done());
          };
        });
      }

      // Initialize Tippy.js tooltips
      document.addEventListener('DOMContentLoaded', () => {
        if (typeof tippy !== 'undefined') {
          // Function to initialize tooltips
          const initTooltips = () => {
            const elements = document.querySelectorAll('[data-tippy-content]');
            elements.forEach(el => {
              // Skip if already has tippy instance
              if (el._tippy) return;

              tippy(el, {
                theme: 'agent-mail',
                animation: 'scale',
                duration: [200, 150],
                arrow: true,
                placement: 'top',
                allowHTML: true,  // Enable HTML in tooltips
                interactive: el.getAttribute('data-tippy-interactive') === 'true',  // Allow hover for complex tooltips
                maxWidth: el.getAttribute('data-tippy-max-width') || 350
              });
            });
          };

          // Initial initialization
          initTooltips();

          // Auto-initialize on new elements with debouncing
          let tooltipTimeout;
          const observer = new MutationObserver(() => {
            clearTimeout(tooltipTimeout);
            tooltipTimeout = setTimeout(initTooltips, 100);
          });

          observer.observe(document.body, {
            childList: true,
            subtree: true
          });
        }

        // Stagger animation for list items - only for items without inline delays
        const staggerElements = document.querySelectorAll('.stagger-item:not([style*="animation-delay"])');
        staggerElements.forEach((el, index) => {
          el.style.animationDelay = `${Math.min(index * 0.05, 1.0)}s`;
        });

        // Animate stat numbers on scroll
        const observerOptions = {
          threshold: 0.5,
          rootMargin: '0px'
        };

        const statObserver = new IntersectionObserver((entries) => {
          entries.forEach(entry => {
            if (entry.isIntersecting && !entry.target.dataset.animated) {
              const target = entry.target;
              // Remove commas and other formatting before parsing
              const cleanText = target.textContent.replace(/[,\s]/g, '');
              const finalValue = parseInt(cleanText, 10);

              // Only animate if valid number and element is part of animated content
              if (!isNaN(finalValue) && finalValue > 0) {
                target.dataset.animated = 'true';

                // Only animate if element is currently hidden to avoid flash
                const computedStyle = window.getComputedStyle(target);
                const isHidden = parseFloat(computedStyle.opacity) === 0 ||
                                computedStyle.visibility === 'hidden';

                if (isHidden) {
                  // Element is hidden, safe to animate from 0
                  requestAnimationFrame(() => {
                    target.textContent = '0';
                    animateValue(target, 0, finalValue, 1000);
                  });
                }
                // Otherwise, element is visible - don't animate to avoid flash
              }
            }
          });
        }, observerOptions);

        document.querySelectorAll('.stat-number').forEach(el => {
          statObserver.observe(el);
        });

        // Smooth scroll to anchors
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
          anchor.addEventListener('click', function (e) {
            const href = this.getAttribute('href');
            if (href !== '#' && href !== '#!') {
              e.preventDefault();
              const target = document.querySelector(href);
              if (target) {
                target.scrollIntoView({
                  behavior: 'smooth',
                  block: 'start'
                });
              }
            }
          });
        });
      });

      // Animate number counter
      function animateValue(element, start, end, duration) {
        const range = end - start;
        const increment = range / (duration / 16); // 60fps
        let current = start;

        const timer = setInterval(() => {
          // Check if element still exists in DOM
          if (!document.body.contains(element)) {
            clearInterval(timer);
            return;
          }

          current += increment;
          if ((increment > 0 && current >= end) || (increment < 0 && current <= end)) {
            current = end;
            clearInterval(timer);
          }
          element.textContent = Math.floor(current).toLocaleString();
        }, 16);
      }

      // Enhanced keyboard shortcuts
      document.addEventListener('keydown', (e) => {
        // Don't trigger shortcuts when typing in input fields (except for special cases)
        const isTyping = e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable;

        // Ctrl/Cmd + K for command palette (handled by Alpine, but keep for legacy)
        if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
          e.preventDefault();
          return;
        }

        // Shift + ? for keyboard shortcuts help
        if (e.shiftKey && e.key === '?') {
          e.preventDefault();
          return;
        }

        // Escape to close modals/dropdowns
        if (e.key === 'Escape') {
          window.dispatchEvent(new CustomEvent('close-all-dropdowns'));
          return;
        }

        // Skip other shortcuts when typing
        if (isTyping) return;

        // / for search
        if (e.key === '/') {
          e.preventDefault();
          const searchInput = document.querySelector('input[type="search"], input[name="q"]');
          if (searchInput) {
            searchInput.focus();
            searchInput.select();
          }
        }

        // R for refresh
        if (e.key === 'r' || e.key === 'R') {
          if (!e.ctrlKey && !e.metaKey && !e.shiftKey) {
            e.preventDefault();
            window.location.reload();
          }
        }

        // D for dark mode toggle
        if (e.key === 'd' || e.key === 'D') {
          if (!e.ctrlKey && !e.metaKey && !e.shiftKey) {
            e.preventDefault();
            if (window.toggleDarkMode) {
              window.toggleDarkMode();
            } else {
              const html = document.documentElement;
              const next = !html.classList.contains('dark');
              html.classList.toggle('dark', next);
              localStorage.setItem('darkMode', String(next));
            }
          }
        }

        // G then P for projects (Gmail-style)
        if (e.key === 'g' || e.key === 'G') {
          // Set a flag and wait for next key
          window._lastKeyG = true;
          setTimeout(() => { window._lastKeyG = false; }, 1000);
        }

        if ((e.key === 'p' || e.key === 'P') && window._lastKeyG) {
          e.preventDefault();
          window.location.href = '/mail';
          window._lastKeyG = false;
        }

        // J/K navigation (Gmail-style)
        if (e.key === 'j' || e.key === 'J') {
          e.preventDefault();
          // Navigate to next item (implement per-page)
          window.dispatchEvent(new CustomEvent('navigate-next'));
        }

        if (e.key === 'k' || e.key === 'K') {
          e.preventDefault();
          // Navigate to previous item (implement per-page)
          window.dispatchEvent(new CustomEvent('navigate-previous'));
        }
      });

      // Add visual feedback for copy actions with fallback
      window.copyToClipboard = async function(text, successMessage = 'Copied to clipboard!') {
        // Modern clipboard API (requires HTTPS)
        if (navigator.clipboard && window.isSecureContext) {
          try {
            await navigator.clipboard.writeText(text);
            window.showToast(successMessage, 'success', 2000);
            return true;
          } catch (err) {
            console.error('Clipboard API failed:', err);
          }
        }

        // Fallback for HTTP or older browsers
        try {
          const textArea = document.createElement('textarea');
          textArea.value = text;
          textArea.style.position = 'fixed';
          textArea.style.left = '-999999px';
          textArea.style.top = '-999999px';
          document.body.appendChild(textArea);
          textArea.focus();
          textArea.select();
          const successful = document.execCommand('copy');
          document.body.removeChild(textArea);

          if (successful) {
            window.showToast(successMessage, 'success', 2000);
            return true;
          } else {
            throw new Error('execCommand failed');
          }
        } catch (err) {
          console.error('Fallback copy failed:', err);
          window.showToast('Failed to copy', 'error', 2000);
          return false;
        }
      };

      // Relative time formatting helper
      window.formatRelativeTime = function(dateString) {
        if (typeof dayjs === 'undefined') return dateString;
        try {
          const result = dayjs(dateString).fromNow();
          return result || dateString;
        } catch (e) {
          console.error('formatRelativeTime error:', e);
          return dateString;
        }
      };

      // Calendar time formatting helper
      window.formatCalendarTime = function(dateString) {
        if (typeof dayjs === 'undefined') return dateString;
        try {
          const result = dayjs(dateString).calendar();
          return result || dateString;
        } catch (e) {
          console.error('formatCalendarTime error:', e);
          return dateString;
        }
      };
    </script>

    {% block scripts %}{% endblock %}
  </body>
</html>
