{% extends "base.html" %}
{% load vite_tags %}
{% load waffle_tags %}
{% load cta_tags %}
{% block title %}Gobii | Your AI Team, Always On — Virtual Coworkers That Automate Web Work 24/7{% endblock %}
{% block head_extras %}
  {{ block.super }}
  <meta name="description" content="Gobii agents are virtual coworkers with their own identity, memory, and tools. Email them, text them — they browse the web, collect data, and deliver reports 24/7.">
  {% if immersive_app_assets %}
    {% for href in immersive_app_assets.styles %}
      <link rel="preload" as="style" href="{{ href }}">
    {% endfor %}
    {% for src in immersive_app_assets.scripts %}
      <link rel="modulepreload" href="{{ src }}">
    {% endfor %}
  {% endif %}
{% endblock %}
{% block early_head_styles %}
  {{ block.super }}
  <style>
    .gobii-hero-fish-cursor {
      --fish-cursor-x: 0px;
      --fish-cursor-y: 0px;
      --fish-cursor-rot: 0deg;
      --fish-eye-x: 0px;
      --fish-eye-y: 0px;
      display: inline-block;
      transform: translate3d(var(--fish-cursor-x), var(--fish-cursor-y), 0) rotate(var(--fish-cursor-rot));
      transform-origin: center;
      transition: transform 180ms cubic-bezier(0.22, 1, 0.36, 1);
      will-change: transform;
    }

    .gobii-hero-fish {
      width: clamp(140px, 24vw, 280px);
      animation: gobii-hero-swim-soft 5.6s ease-in-out infinite;
      transform-origin: center;
      will-change: transform;
    }

    .gobii-hero-fish svg {
      width: 100%;
      height: auto;
      display: block;
      overflow: visible;
    }

    .gobii-hero-fish svg #body,
    .gobii-hero-fish svg #top-fin,
    .gobii-hero-fish svg #tail-fin,
    .gobii-hero-fish svg #bottom-left-fin,
    .gobii-hero-fish svg #bottom-right-fin,
    .gobii-hero-fish svg #left-eye,
    .gobii-hero-fish svg #right-eye {
      transform-box: fill-box;
      will-change: transform;
    }

    .gobii-hero-fish svg #body {
      transform-origin: 48% 53%;
      animation: gobii-body-roll-soft 2.8s ease-in-out infinite;
    }

    .gobii-hero-fish svg #top-fin {
      transform-origin: 58% 88%;
      animation: gobii-top-fin-soft 2.2s ease-in-out infinite;
    }

    .gobii-hero-fish svg #tail-fin {
      transform-origin: 12% 50%;
      animation: gobii-tail-fin-soft 1.65s ease-in-out infinite;
    }

    .gobii-hero-fish svg #bottom-left-fin {
      transform-origin: 68% 26%;
      animation: gobii-bottom-left-fin-soft 1.9s ease-in-out infinite;
    }

    .gobii-hero-fish svg #bottom-right-fin {
      transform-origin: 20% 70%;
      animation: gobii-bottom-right-fin-soft 1.85s ease-in-out infinite;
    }

    .gobii-hero-fish svg #left-eye,
    .gobii-hero-fish svg #right-eye {
      transform: translate3d(var(--fish-eye-x), var(--fish-eye-y), 0);
      animation: gobii-eye-glow-soft 3s ease-in-out infinite;
    }

    .gobii-hero-fish svg #left-eye path,
    .gobii-hero-fish svg #right-eye path {
      transform-box: fill-box;
      transform-origin: center;
      animation: gobii-eye-blink-soft 9.6s ease-in-out infinite;
    }

    @keyframes gobii-hero-swim-soft {
      0%, 100% {
        transform: translate3d(0, 0, 0) rotate(0deg);
      }
      25% {
        transform: translate3d(4px, -3px, 0) rotate(-0.7deg);
      }
      50% {
        transform: translate3d(8px, 0, 0) rotate(0.4deg);
      }
      75% {
        transform: translate3d(4px, 3px, 0) rotate(-0.5deg);
      }
    }

    @keyframes gobii-body-roll-soft {
      0%, 100% { transform: translateY(0px) rotate(0deg); }
      50% { transform: translateY(-2px) rotate(-0.5deg); }
    }

    @keyframes gobii-top-fin-soft {
      0%, 100% { transform: rotate(0deg); }
      50% { transform: rotate(-4deg); }
    }

    @keyframes gobii-tail-fin-soft {
      0%, 100% { transform: rotate(0deg); }
      25% { transform: rotate(4.5deg); }
      75% { transform: rotate(-4.5deg); }
    }

    @keyframes gobii-bottom-left-fin-soft {
      0%, 100% { transform: rotate(0deg); }
      50% { transform: rotate(6deg); }
    }

    @keyframes gobii-bottom-right-fin-soft {
      0%, 100% { transform: translate3d(0, 0, 0) rotate(0deg); }
      50% { transform: translate3d(2px, -2px, 0) rotate(-5deg); }
    }

    @keyframes gobii-eye-glow-soft {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.95; }
    }

    @keyframes gobii-eye-blink-soft {
      0%, 86%, 100% { transform: scaleY(1); }
      88% { transform: scaleY(0.14); }
      90% { transform: scaleY(1); }
    }

    @media (prefers-reduced-motion: reduce) {
      .gobii-hero-fish-cursor {
        transition: none !important;
        transform: none !important;
      }

      .gobii-hero-fish,
      .gobii-hero-fish svg #body,
      .gobii-hero-fish svg #top-fin,
      .gobii-hero-fish svg #tail-fin,
      .gobii-hero-fish svg #bottom-left-fin,
      .gobii-hero-fish svg #bottom-right-fin,
      .gobii-hero-fish svg #left-eye,
      .gobii-hero-fish svg #right-eye,
      .gobii-hero-fish svg #left-eye path,
      .gobii-hero-fish svg #right-eye path {
        animation: none !important;
        transition: none !important;
      }
    }

	    .game-of-life-panel {
	      position: relative;
	      overflow: clip;
	      isolation: isolate;
        z-index: 1;
	    }

    .game-of-life-panel::before {
      content: "";
      position: absolute;
      inset: 0;
      background:
        radial-gradient(circle at 20% 25%, rgba(79, 70, 229, 0.16) 0%, rgba(79, 70, 229, 0) 55%),
        radial-gradient(circle at 80% 18%, rgba(14, 165, 233, 0.12) 0%, rgba(14, 165, 233, 0) 60%),
        radial-gradient(circle at 55% 80%, rgba(129, 140, 248, 0.1) 0%, rgba(129, 140, 248, 0) 70%);
      opacity: 0.8;
      filter: blur(40px);
      pointer-events: none;
      z-index: 1;
    }

    .game-of-life-panel::after {
      content: "";
      position: absolute;
      inset: 0;
      background: linear-gradient(180deg, rgba(255, 255, 255, 0.55) 0%, rgba(255, 255, 255, 0.2) 30%, rgba(255, 255, 255, 0.65) 100%);
      pointer-events: none;
      z-index: 2;
      mix-blend-mode: lighten;
    }

    .game-of-life-gradient-bg {
      position: absolute;
      inset: 0;
      pointer-events: none;
      z-index: 0;
      background: linear-gradient(180deg, rgba(99, 102, 241, 0.45) 0%, rgba(129, 140, 248, 0.5) 40%, rgba(59, 130, 246, 0.4) 100%);
      -webkit-mask-image: radial-gradient(ellipse 130% 100% at 50% 0%, black 40%, transparent 100%);
      mask-image: radial-gradient(ellipse 130% 100% at 50% 0%, black 40%, transparent 100%);
    }

    .game-of-life-content {
      position: relative;
      z-index: 20;
    }

    /* Pure white background for input areas */
    .game-of-life-content .bg-white {
      background: #ffffff;
    }

    /* Ensure crisp edges on rounded corners */
    .game-of-life-content .rounded-xl {
      border-radius: 0.75rem;
      transform: translateZ(0);
      -webkit-transform: translateZ(0);
    }

    .magic-cta {
      position: relative;
      overflow: hidden;
      transform: translateZ(0);
      box-shadow: 0 18px 32px -20px rgba(139, 92, 246, 0.55);
      transition: transform 0.3s ease, box-shadow 0.3s ease;
      animation: softPulse 4.2s ease-in-out infinite;
    }

    .magic-cta::before {
      content: "";
      position: absolute;
      inset: -40%;
      background: radial-gradient(circle at center, rgba(196, 181, 253, 0.45), rgba(124, 58, 237, 0));
      opacity: 0.35;
      transform: scale(0.9);
      animation: glowBloom 6s ease-in-out infinite;
      pointer-events: none;
    }

    .magic-cta::after {
      content: "";
      position: absolute;
      top: -160%;
      left: 0;
      width: 35%;
      height: 420%;
      background: linear-gradient(120deg, transparent 0%, rgba(255, 255, 255, 0.15) 30%, rgba(255, 255, 255, 0.65) 50%, rgba(255, 255, 255, 0.15) 70%, transparent 100%);
      transform: translateX(-140%) rotate(18deg);
      animation: shimmerSweep 5.8s ease-in-out infinite;
      pointer-events: none;
    }

    .magic-cta:hover {
      transform: translateY(-1px) scale(1.01);
      box-shadow: 0 20px 38px -18px rgba(109, 40, 217, 0.58);
    }

    @keyframes softPulse {
      0%, 100% {
        filter: brightness(1);
      }
      45% {
        filter: brightness(1.06);
      }
    }

    @keyframes glowBloom {
      0%, 100% {
        opacity: 0.35;
        transform: scale(0.92);
      }
      50% {
        opacity: 0.6;
        transform: scale(1.05);
      }
    }

    @keyframes shimmerSweep {
      0% {
        transform: translateX(-140%) rotate(18deg);
        opacity: 0;
      }
      20% {
        opacity: 0.75;
      }
      45% {
        transform: translateX(140%) rotate(18deg);
        opacity: 0;
      }
      100% {
        transform: translateX(160%) rotate(18deg);
        opacity: 0;
      }
    }

    @media (prefers-reduced-motion: reduce) {
      .magic-cta,
      .magic-cta::before,
      .magic-cta::after {
        animation: none !important;
        transition: none;
      }
    }

    /* Scroll-triggered fade-in animation */
    [data-animate] {
      opacity: 0;
      transform: translateY(24px);
      transition: opacity 0.6s ease, transform 0.6s ease;
    }
    [data-animate].is-visible {
      opacity: 1;
      transform: translateY(0);
    }
    @media (prefers-reduced-motion: reduce) {
      [data-animate] {
        opacity: 1;
        transform: none;
        transition: none;
      }
    }

    {% include "partials/_immersive_overlay_styles.html" %}
  </style>
{% endblock %}
{% block content %}
<main id="main-content" class="relative game-of-life-panel -mt-16 min-h-[420px] sm:min-h-[520px]">
  <div class="game-of-life-gradient-bg" aria-hidden="true"></div>
  
  <!-- Grid pattern overlay -->
  <div class="absolute inset-0 bg-grid-slate-100 bg-[size:var(--bg-size-x)_var(--bg-size-y)] [mask-image:linear-gradient(0deg,transparent,rgba(255,255,255,0.7),transparent)] opacity-20 z-[-1]" style="--bg-size-x:40px; --bg-size-y:40px"></div>
  
  <!-- Seamless Gradient Fade -->
  <div class="absolute bottom-0 left-0 right-0 h-64 bg-gradient-to-t from-white via-white/80 to-transparent pointer-events-none z-10"></div>

  <!-- ========================================================= -->
  <!-- Agent Spawn Hero -->
  <section class="relative pb-8 game-of-life-content z-20">

    <!-- Content container with enhanced styling -->
    <div class="relative max-w-5xl mx-auto px-6 pt-20 sm:pt-28 pb-0">
      
      <!-- Ambient Glow centered on hero + input -->
      <div class="absolute top-16 sm:top-24 left-1/2 -translate-x-1/2 w-[600px] sm:w-[1000px] h-[500px] sm:h-[800px] bg-white blur-[80px] sm:blur-[100px] opacity-90 rounded-full pointer-events-none -z-10"></div>

      <!-- Main Headline -->
      {% include "home/_hero.html" %}

      <!-- Task Usage Warning for logged in users -->
      {% if user.is_authenticated %}
        <div class="max-w-4xl mx-auto mb-4">
          {% include "partials/_task_usage.html" %}
      </div>
      {% endif %}

      <!-- Agent Spawn Form -->
      {% if not user.is_authenticated or account.usage.agents_unlimited is True or account.usage.agents_available > 0 %}
      <div class="max-w-4xl mx-auto relative z-20">
          <form method="post" name="create-agent-form" id="create-agent-form" action="{% url 'pages:home_agent_spawn' %}" data-authenticated="{{ user.is_authenticated|yesno:'true,false' }}" data-requires-trial="{{ home_spawn_requires_trial|yesno:'true,false' }}" data-immersive-form data-analytics-cta-id="home_hero" data-analytics-placement="hero" data-analytics-intent="spawn_agent">
            {% csrf_token %}
            <input type="hidden" name="return_to" id="agent-return-to" value="">
            <input type="hidden" name="embed" id="agent-embed" value="{% if user.is_authenticated %}1{% else %}0{% endif %}">
            <input type="hidden" name="source_page" value="home_hero">
            <input type="hidden" name="trial_onboarding" value="1">
            <input type="hidden" name="trial_onboarding_target" value="agent_ui">
            <div id="homepage-integrations-selected-fields"></div>
            
            <!-- Charter Input with inline CTA button -->
            <div>
              <!-- Unified input + button container -->
              <div class="backdrop-blur-2xl bg-white/50 border border-white/60 focus-within:border-indigo-500 rounded-2xl overflow-visible relative shadow-xl transition-all duration-300">
                <!-- Typing prompt overlay -->
                <div id="charter-ghost" class="pointer-events-none absolute inset-0 flex px-5 py-4 text-base leading-relaxed text-slate-500 transition-opacity duration-200">
                  <div>
                    <span>I want my Gobii to</span>
                    <span id="charter-ghost-text"> find 200 ideal customers and their emails.</span>
                  </div>
                </div>

                <!-- Textarea -->
                {{ agent_charter_form.charter }}

                <!-- Button row -->
                <div class="flex flex-col gap-3 p-3 relative z-[200] sm:flex-row sm:items-center sm:justify-between">
                  <div class="flex min-w-0 items-center gap-2">
                    {% if homepage_integrations_enabled %}
                      <div class="flex items-center gap-2" data-integrations-inline>
                        {% if homepage_integrations_inline_builtins %}
                          <span class="text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400">Apps</span>
                          <div class="flex items-center -space-x-1.5">
                            {% for app in homepage_integrations_inline_builtins %}
                              <span class="relative inline-flex h-7 w-7 items-center justify-center rounded-lg border-2 border-white bg-indigo-50 text-[9px] font-semibold uppercase text-indigo-700 shadow-sm" title="{{ app.name }}">
                                {% if app.inline_icon_url or app.icon_url %}
                                  <img src="{{ app.inline_icon_url|default:app.icon_url }}" alt="{{ app.name }}" width="28" height="28" class="h-full w-full rounded-[8px] object-contain" loading="lazy" decoding="async" />
                                {% else %}
                                  <span>{{ app.name|slice:":2"|upper }}</span>
                                {% endif %}
                              </span>
                            {% endfor %}
                          </div>
                        {% endif %}
                        <button
                          type="button"
                          class="inline-flex h-7 w-7 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:border-indigo-200 hover:text-indigo-600"
                          aria-label="Search more integrations"
                          data-integrations-open
                        >
                          <svg class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                            <circle cx="5" cy="12" r="1.8"></circle>
                            <circle cx="12" cy="12" r="1.8"></circle>
                            <circle cx="19" cy="12" r="1.8"></circle>
                          </svg>
                        </button>
                      </div>
                    {% endif %}
                  </div>

                  <div class="flex items-center justify-end gap-3">
                    {% if llm_intelligence %}
                    <div
                      class="relative"
                      data-intelligence-selector
                      data-intelligence-upgrade="{{ llm_intelligence.upgradeUrl|default_if_none:'' }}"
                      data-intelligence-can-edit="{{ llm_intelligence.canEdit|yesno:'true,false' }}"
                      data-intelligence-disabled="{{ llm_intelligence.disabledReason|default_if_none:''|escape }}"
                      data-intelligence-max-tier="{{ llm_intelligence.maxAllowedTier|default_if_none:'' }}"
                      data-intelligence-max-rank="{{ llm_intelligence.maxAllowedTierRank|default_if_none:'' }}"
                      data-billing-url="{{ billing_url|default_if_none:'' }}"
                    >
                      <input type="hidden" name="preferred_llm_tier" id="preferred-llm-tier" value="{{ preferred_llm_tier }}">
                      <button
                        type="button"
                        class="group flex items-center gap-1.5 rounded-lg bg-transparent px-2 py-1.5 text-xs font-medium text-slate-500 transition-all hover:text-indigo-600"
                        data-intelligence-trigger
                        aria-expanded="false"
                        aria-label="Select intelligence level"
                      >
                        <svg class="h-4 w-4 text-indigo-400 group-hover:text-indigo-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                          <path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"></path>
                          <path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"></path>
                          <path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"></path>
                          <path d="M17.599 6.5a3 3 0 0 0 .399-1.375"></path>
                          <path d="M6.003 5.125A3 3 0 0 0 6.401 6.5"></path>
                          <path d="M3.477 10.896a4 4 0 0 1 .585-.396"></path>
                          <path d="M19.938 10.5a4 4 0 0 1 .585.396"></path>
                          <path d="M6 18a4 4 0 0 1-1.967-.516"></path>
                          <path d="M19.967 17.484A4 4 0 0 1 18 18"></path>
                        </svg>
                        <span data-intelligence-current>{{ preferred_llm_tier_label }}</span>
                        <svg class="h-3 w-3 text-slate-400 transition-transform group-hover:text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true" data-intelligence-chevron>
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                        </svg>
                      </button>
                      <div
                        class="absolute top-full right-0 z-[100] mt-1.5 hidden w-56 origin-top-right rounded-lg border border-slate-200/60 bg-white py-1 shadow-xl shadow-slate-900/10"
                        data-intelligence-menu
                      >
                        {% for option in llm_intelligence.options %}
                          <button
                            type="button"
                            class="grid w-full grid-cols-[20px_1fr_42px] items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-indigo-50/30 {% if option.key == preferred_llm_tier %}bg-indigo-50/40{% endif %}"
                            data-intelligence-option
                            data-tier="{{ option.key }}"
                            data-label="{{ option.label }}"
                            data-multiplier="{{ option.multiplier|floatformat:-1 }}"
                            data-rank="{{ option.rank|default_if_none:'' }}"
                            {% if llm_intelligence.maxAllowedTierRank is not None and option.rank is not None %}
                              data-locked="{% if option.rank > llm_intelligence.maxAllowedTierRank %}true{% else %}false{% endif %}"
                            {% else %}
                              data-locked="{% if not llm_intelligence.canEdit and option.key != preferred_llm_tier %}true{% else %}false{% endif %}"
                            {% endif %}
                          >
                            <span class="w-5 text-center text-sm">{% if option.key == 'standard' %}🌱{% elif option.key == 'premium' %}💭{% elif option.key == 'max' %}💡{% elif option.key == 'ultra' %}⚡{% elif option.key == 'ultra_max' %}🤯{% endif %}</span>
                            <span class="min-w-0 truncate text-[13px] font-medium whitespace-nowrap {% if option.key == preferred_llm_tier %}text-slate-900{% else %}text-slate-600{% endif %}">{{ option.label }}</span>
                            {% if llm_intelligence.maxAllowedTierRank is not None and option.rank is not None %}
                              {% if option.rank > llm_intelligence.maxAllowedTierRank %}
                                <span class="inline-flex items-center justify-end text-amber-600" data-intelligence-lock>
                                  <svg class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                                    <rect x="3" y="11" width="18" height="11" rx="2"></rect>
                                    <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                                  </svg>
                                </span>
                              {% else %}
                                <span class="text-right text-[11px] tabular-nums whitespace-nowrap {% if option.key == preferred_llm_tier %}text-indigo-500 font-medium{% else %}text-slate-400{% endif %}">{{ option.multiplier|floatformat:-1 }}×</span>
                              {% endif %}
                            {% else %}
                              {% if not llm_intelligence.canEdit and option.key != preferred_llm_tier %}
                                <span class="inline-flex items-center justify-end text-amber-600" data-intelligence-lock>
                                  <svg class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                                    <rect x="3" y="11" width="18" height="11" rx="2"></rect>
                                    <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                                  </svg>
                                </span>
                              {% else %}
                                <span class="text-right text-[11px] tabular-nums whitespace-nowrap {% if option.key == preferred_llm_tier %}text-indigo-500 font-medium{% else %}text-slate-400{% endif %}">{{ option.multiplier|floatformat:-1 }}×</span>
                              {% endif %}
                            {% endif %}
                          </button>
                        {% endfor %}
                        {% if llm_intelligence.disabledReason %}
                          <div class="px-3 pt-1 pb-2 text-[11px] text-slate-500">
                            {% if llm_intelligence.upgradeUrl %}
                              <a
                                href="{{ llm_intelligence.upgradeUrl }}"
                                class="font-semibold text-indigo-600 transition hover:text-indigo-500"
                              >
                                Upgrade
                              </a>
                              <span> to adjust intelligence levels.</span>
                            {% else %}
                              <span>Upgrade to adjust intelligence levels.</span>
                            {% endif %}
                          </div>
                        {% endif %}
                      </div>
                    </div>
                    {% endif %}

                    <button
                      type="submit"
                      class="magic-cta group inline-flex items-center justify-center gap-x-2 bg-gradient-to-r from-violet-600 to-purple-500 hover:from-violet-700 hover:to-purple-600 border border-transparent text-white text-sm font-semibold rounded-xl focus:outline-none focus:ring-2 focus:ring-violet-500 focus:ring-offset-2 py-3 px-4 shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-[1.02]"
                    >
                      {% if not user.is_authenticated or home_spawn_requires_trial %}
                        {% cta_text "cta_homepage_launch_btn_unauth" fallback="Start Free Trial" %}
                      {% else %}
                        {% cta_text "cta_homepage_launch_btn_auth" fallback="Spawn Agent" %}
                      {% endif %}
                      <svg class="w-4 h-4 group-hover:translate-x-1 transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 18l6-6-6-6"></path>
                      </svg>
                    </button>
                  </div>
                </div>
              </div>
              
              {% if agent_charter_form.charter.errors %}
                <div class="mt-2 text-red-600 text-sm flex items-center gap-2">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01"></path>
                  </svg>
                  {{ agent_charter_form.charter.errors.0 }}
                </div>
              {% endif %}
            </div>

            </div>
          </form>
      </div>

      <div id="intelligence-gate-modal" class="fixed inset-0 z-[300] hidden" aria-hidden="true">
        <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" data-gate-close></div>
        <div class="relative mx-auto flex min-h-full max-w-xl items-center justify-center p-6">
          <div class="w-full rounded-3xl border border-white/70 bg-white shadow-xl">
            <div class="flex items-start justify-between gap-4 px-6 py-5">
              <div>
                <h3 class="text-xl font-semibold text-slate-900" data-gate-title>Upgrade your plan</h3>
                <p class="mt-1 text-sm text-slate-500" data-gate-message></p>
                <p class="mt-2 text-xs font-medium text-slate-500" data-gate-detail></p>
              </div>
              <button
                type="button"
                class="rounded-full p-2 text-slate-400 hover:text-slate-600"
                aria-label="Close dialog"
                data-gate-close
              >
                <svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                  <line x1="18" y1="6" x2="6" y2="18"></line>
                  <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
              </button>
            </div>
            <div class="px-6 py-5">
              <div class="flex flex-col gap-2 sm:flex-row sm:items-center">
                <button
                  type="button"
                  class="inline-flex items-center justify-center gap-2 rounded-xl bg-indigo-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-indigo-700"
                  data-gate-upgrade
                >
                  Upgrade plan
                </button>
                <button
                  type="button"
                  class="inline-flex items-center justify-center gap-2 rounded-xl border border-indigo-200 px-4 py-2 text-sm font-semibold text-indigo-600 transition hover:border-indigo-300 hover:text-indigo-700"
                  data-gate-add-pack
                >
                  Add task pack
                </button>
                <button
                  type="button"
                  class="inline-flex items-center justify-center gap-2 rounded-xl border border-slate-200 px-4 py-2 text-sm font-semibold text-slate-700 transition hover:border-slate-300 hover:text-slate-800"
                  data-gate-continue
                >
                  Continue
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {% if homepage_integrations_enabled %}
        {{ homepage_integrations_modal_props|json_script:"homepage-integrations-props" }}
        <div
          id="homepage-integrations-root"
          data-props-json-id="homepage-integrations-props"
        ></div>
      {% endif %}

      {% if user.is_authenticated and recent_agents_total|default:0 > 0 %}
      <div class="max-w-4xl mx-auto mt-16 pb-0 px-6 relative z-10">
        <div class="backdrop-blur-2xl bg-white/50 border border-white/60 shadow-sm rounded-3xl overflow-hidden">
          <div class="px-8 py-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-6">
            <div class="text-left">
              <span class="inline-flex items-center text-xs font-bold tracking-[0.25em] uppercase text-indigo-500">Your agents</span>
              <h3 class="mt-2 text-2xl font-medium text-slate-900 tracking-tight">Pick up where you left off</h3>
              <p class="mt-3 text-base text-slate-600 max-w-xl leading-relaxed">Quickly jump into the agents already running for you. Manage schedules, messages, and integrations from the app.</p>
            </div>
            <a href="{{ recent_agents_all_url }}" data-immersive-link class="group inline-flex items-center justify-center gap-2 px-6 py-3 rounded-full bg-white border border-slate-200 text-slate-700 font-semibold hover:border-indigo-300 hover:text-indigo-600 hover:shadow-sm transition-all duration-200">
              View all
              <svg class="w-4 h-4 text-slate-400 group-hover:text-indigo-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
              </svg>
            </a>
          </div>
          <div class="px-8 pb-8">
            <div class="grid gap-5 sm:grid-cols-3">
              {% if recent_agents %}
                {% for agent in recent_agents %}
                <a href="{{ agent.chat_url }}" data-immersive-link class="group relative bg-white border border-slate-200/60 rounded-2xl p-5 shadow-sm hover:shadow-md hover:border-indigo-300 transition-all duration-300 hover:-translate-y-0.5 block text-left">
                  <div class="flex items-center justify-between mb-3">
                    <p class="text-base font-semibold text-slate-900 truncate pr-2">{{ agent.name }}</p>
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider {{ agent.status_class }} ring-1 ring-inset ring-current/10">{{ agent.status_label }}</span>
                  </div>
                  {% if agent.display_schedule %}
                  <div class="flex items-center gap-2 mb-2">
                    <svg class="w-3.5 h-3.5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    <p class="text-xs font-medium text-slate-500">{{ agent.display_schedule }}</p>
                  </div>
                  {% endif %}
                  {% if agent.listing_description_source == "placeholder" %}
                  <p class="text-sm text-slate-400 italic line-clamp-2 leading-relaxed">{{ agent.listing_description }}</p>
                  {% else %}
                  <p class="text-sm text-slate-600 line-clamp-2 leading-relaxed">{{ agent.listing_description }}</p>
                  {% endif %}
                  
                  <div class="absolute inset-0 rounded-2xl ring-1 ring-inset ring-black/0 group-hover:ring-indigo-500/10 transition-all duration-300"></div>
                </a>
                {% endfor %}
              {% else %}
                <div class="rounded-2xl border border-dashed border-slate-300 bg-white/50 p-8 text-center sm:col-span-3">
                  <p class="text-sm text-slate-500 font-medium">Your agents are active in the console. Jump in to review their schedules and conversations.</p>
                </div>
              {% endif %}
            </div>
            {% if recent_agents_remaining > 0 %}
              <div class="mt-6 text-center border-t border-slate-200/50 pt-4">
                <p class="text-xs font-medium text-slate-500">+{{ recent_agents_remaining }} more agent{{ recent_agents_remaining|pluralize }} available in the console.</p>
              </div>
            {% endif %}
          </div>
        </div>
      </div>
      {% endif %}
      {% else %}
      <div class="max-w-4xl mx-auto mt-8 px-4">
        <div class="bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-200 rounded-xl p-8 shadow-lg text-center">
          <!-- Icon -->
          <div class="flex justify-center mb-6">
            <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center">
              <svg class="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4"></path>
              </svg>
            </div>
          </div>

          <!-- Header -->
          <h3 class="text-2xl font-medium text-gray-900 mb-3">No Agents Available</h3>

          <!-- Description -->
          <p class="text-gray-600 mb-6 max-w-2xl mx-auto">
            {% if settings.GOBII_PROPRIETARY_MODE %}
              You've reached your agent limit for your current plan. Upgrade to unlock more agents and take advantage of advanced features to boost your productivity.
            {% else %}
              You've reached your agent limit for this deployment. Adjust deployment settings to allow more agents.
            {% endif %}
          </p>

          <!-- Stats Card -->
          <div class="bg-white rounded-lg p-4 mb-6 border border-blue-100 max-w-md mx-auto">
            <div class="flex items-center justify-between mb-2">
              <span class="text-sm font-medium text-gray-600">Available Agents</span>
              <span class="text-sm font-bold text-blue-600">0/{{ account.usage.agent_limit }}</span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-2">
              <div class="bg-gradient-to-r from-blue-400 to-indigo-500 h-2 rounded-full" style="width: 100%"></div>
            </div>
          </div>

          <!-- CTA Button -->
          {% if settings.GOBII_PROPRIETARY_MODE %}
          <a href="{% url "proprietary:startup_checkout" %}" class="inline-flex items-center justify-center px-8 py-4 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-semibold rounded-lg shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
            </svg>
            Upgrade Your Plan
          </a>
          {% endif %}

          {% if settings.GOBII_PROPRIETARY_MODE %}
          <!-- Benefits Preview -->
          <div class="mt-8 pt-6 border-t border-blue-200">
            <h4 class="text-lg font-semibold text-gray-900 mb-4">What you'll get with an upgrade:</h4>
            <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 max-w-2xl mx-auto">
              <div class="flex flex-col items-center text-center">
                <div class="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center mb-2">
                  <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4"></path>
                  </svg>
                </div>
                <h5 class="font-medium text-gray-900 mb-1">Unlimited Agents</h5>
                <p class="text-sm text-gray-600">Create more agents for all your tasks</p>
              </div>

              <div class="flex flex-col items-center text-center">
                <div class="w-10 h-10 bg-purple-100 rounded-full flex items-center justify-center mb-2">
                  <svg class="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
                  </svg>
                </div>
                <h5 class="font-medium text-gray-900 mb-1">More Tasks</h5>
                <p class="text-sm text-gray-600">Run more tasks each month</p>
              </div>

              <div class="flex flex-col items-center text-center">
                <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center mb-2">
                  <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192L5.636 18.364M12 12h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                  </svg>
                </div>
                <h5 class="font-medium text-gray-900 mb-1">Priority Support</h5>
                <p class="text-sm text-gray-600">Get help when you need it most</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      {% endif %}
      {% endif %}

    </div>
  </section>

  <!-- Value proposition sections (proprietary only) -->
  {% if settings.GOBII_PROPRIETARY_MODE %}
    {% include "home/_flow_strip.html" %}
    {% include "home/_value_sections.html" %}
    {% include "home/_vision_and_trust.html" %}
  {% endif %}

  <!-- OR Divider -->
  <section class="relative">
    <div class="max-w-5xl mx-auto px-6">
      <div class="relative flex items-center justify-center py-8 sm:py-10">
        <div class="h-px bg-gradient-to-r from-transparent via-indigo-200 to-transparent w-full max-w-xs"></div>
        <span class="flex-shrink-0 mx-6 text-xs font-bold tracking-[0.25em] uppercase text-indigo-400">OR</span>
        <div class="h-px bg-gradient-to-r from-transparent via-indigo-200 to-transparent w-full max-w-xs"></div>
      </div>
    </div>
  </section>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const fish = document.querySelector('[data-gobii-fish-cursor]');
      if (!fish) return;

      if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
        return;
      }

      if (window.matchMedia('(pointer: coarse)').matches) {
        return;
      }

      const MAX_X = 11;
      const MAX_Y = 8;
      const MAX_ROT = 3.2;
      const MAX_EYE_X = 6.2;
      const MAX_EYE_Y = 3.6;
      const SMOOTHING = 0.14;

      let targetX = 0;
      let targetY = 0;
      let targetRot = 0;
      let targetEyeX = 0;
      let targetEyeY = 0;
      let currentX = 0;
      let currentY = 0;
      let currentRot = 0;
      let currentEyeX = 0;
      let currentEyeY = 0;
      let rafId = null;

      const applyTransform = () => {
        currentX += (targetX - currentX) * SMOOTHING;
        currentY += (targetY - currentY) * SMOOTHING;
        currentRot += (targetRot - currentRot) * SMOOTHING;
        currentEyeX += (targetEyeX - currentEyeX) * SMOOTHING;
        currentEyeY += (targetEyeY - currentEyeY) * SMOOTHING;

        fish.style.setProperty('--fish-cursor-x', `${currentX.toFixed(2)}px`);
        fish.style.setProperty('--fish-cursor-y', `${currentY.toFixed(2)}px`);
        fish.style.setProperty('--fish-cursor-rot', `${currentRot.toFixed(2)}deg`);
        fish.style.setProperty('--fish-eye-x', `${currentEyeX.toFixed(2)}px`);
        fish.style.setProperty('--fish-eye-y', `${currentEyeY.toFixed(2)}px`);

        const stillMoving =
          Math.abs(targetX - currentX) > 0.02 ||
          Math.abs(targetY - currentY) > 0.02 ||
          Math.abs(targetRot - currentRot) > 0.02 ||
          Math.abs(targetEyeX - currentEyeX) > 0.02 ||
          Math.abs(targetEyeY - currentEyeY) > 0.02;

        if (stillMoving) {
          rafId = window.requestAnimationFrame(applyTransform);
        } else {
          rafId = null;
        }
      };

      const scheduleFrame = () => {
        if (rafId !== null) return;
        rafId = window.requestAnimationFrame(applyTransform);
      };

      const handleMove = (event) => {
        const nx = (event.clientX / window.innerWidth) * 2 - 1;
        const ny = (event.clientY / window.innerHeight) * 2 - 1;
        const nMag = Math.hypot(nx, ny);
        const nScale = nMag > 1 ? 1 / nMag : 1;

        targetX = nx * MAX_X;
        targetY = ny * MAX_Y;
        targetRot = nx * MAX_ROT;
        targetEyeX = nx * nScale * MAX_EYE_X;
        targetEyeY = ny * nScale * MAX_EYE_Y;
        scheduleFrame();
      };

      const reset = () => {
        targetX = 0;
        targetY = 0;
        targetRot = 0;
        targetEyeX = 0;
        targetEyeY = 0;
        scheduleFrame();
      };

      window.addEventListener('mousemove', handleMove, { passive: true });
      document.addEventListener('mouseleave', reset);
      window.addEventListener('blur', reset);
    });
  </script>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const textarea = document.getElementById('id_charter');
      const ghostWrapper = document.getElementById('charter-ghost');
      const ghostText = document.getElementById('charter-ghost-text');

      if (!textarea || !ghostWrapper || !ghostText) {
        return;
      }

      const baseScenarios = [
        ' find 200 ideal customers and their emails.',
        ' keep my Salesforce pipeline clean every day.',
        ' watch new YC and seed startups and add founders to my sheet weekly.',
        ' track competitor pricing and plan changes daily.',
        ' pull fresh contacts from company sites and press releases each night.',
        ' monitor RFP portals for AI and automation opportunities to bid on.',
        " watch job boards for 'Senior Data Engineer' roles and auto-apply with my profile.",
        ' track vendor status pages and alert me when SLAs slip.',
        ' collect buyer intent posts on LinkedIn and Reddit and draft outreach.',
        ' watch competitor changelogs and docs and summarize product moves weekly.',
        ' track ecommerce competitors for stock and price changes daily.',
        ' monitor fintech and regulatory sites and summarize what affects us.',
        ' help me find a new place to rent.',
        ' help me find a vacation house.',
        ' watch for price drops on my wishlist items.',
        " track flights to my destination and alert me when they're cheap."
      ];

      function shuffle(list) {
        const array = [...list];
        for (let i = array.length - 1; i > 0; i -= 1) {
          const j = Math.floor(Math.random() * (i + 1));
          [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
      }

      let scenarioQueue = [];
      let currentScenario = '';
      let lastScenario = '';

      function refillQueue() {
        scenarioQueue = shuffle(baseScenarios);
        if (scenarioQueue.length > 1 && scenarioQueue[0] === lastScenario) {
          [scenarioQueue[0], scenarioQueue[1]] = [scenarioQueue[1], scenarioQueue[0]];
        }
      }

      function pickNextScenario() {
        if (!scenarioQueue.length) {
          refillQueue();
        }
        currentScenario = scenarioQueue.shift();
        lastScenario = currentScenario;
      }

      refillQueue();
      pickNextScenario();

      let charIndex = 0;
      let isDeleting = false;

      ghostText.textContent = '';

      function toggleGhostVisibility() {
        const hasValue = textarea.value.trim().length > 0;
        ghostWrapper.classList.toggle('opacity-0', hasValue);
        ghostWrapper.classList.toggle('invisible', hasValue);
        ghostWrapper.setAttribute('aria-hidden', hasValue ? 'true' : 'false');
      }

      textarea.addEventListener('input', toggleGhostVisibility);
      textarea.addEventListener('focus', toggleGhostVisibility);
      textarea.addEventListener('blur', toggleGhostVisibility);

      toggleGhostVisibility();

      function typeLoop() {
        const hasValue = textarea.value.trim().length > 0;
        if (hasValue) {
          setTimeout(typeLoop, 400);
          return;
        }

        if (!isDeleting && charIndex <= currentScenario.length) {
          ghostText.textContent = currentScenario.slice(0, charIndex);
          charIndex += 1;
          setTimeout(typeLoop, 30 + Math.random() * 15);
          return;
        }

        if (!isDeleting && charIndex > currentScenario.length) {
          isDeleting = true;
          setTimeout(typeLoop, 1500);
          return;
        }

        if (isDeleting && charIndex > 0) {
          charIndex -= 1;
          ghostText.textContent = currentScenario.slice(0, charIndex);
          setTimeout(typeLoop, 18 + Math.random() * 10);
          return;
        }

        if (isDeleting && charIndex === 0) {
          isDeleting = false;
          pickNextScenario();
          setTimeout(typeLoop, 300);
          return;
        }
      }

      setTimeout(typeLoop, 400);
    });
  </script>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const selector = document.querySelector('[data-intelligence-selector]')
	      if (!selector) {
	        return
	      }
	      const trigger = selector.querySelector('[data-intelligence-trigger]')
	      const menu = selector.querySelector('[data-intelligence-menu]')
	      const input = selector.querySelector('input[name="preferred_llm_tier"]')
	      const currentLabel = selector.querySelector('[data-intelligence-current]')
	      const options = Array.from(selector.querySelectorAll('[data-intelligence-option]'))

	      if (!trigger || !menu || !input || options.length === 0) {
	        return
	      }

      const resolveLabel = (tier, fallback = 'this tier') => {
        if (!tier) {
          return fallback
        }
        const option = options.find((item) => item.dataset.tier === tier)
        if (option && option.dataset.label) {
          return option.dataset.label
        }
        return tier
          .split('_')
          .map((segment) => (segment ? segment[0].toUpperCase() + segment.slice(1) : segment))
          .join(' ')
      }

	      const applySelection = (tier) => {
	        const label = resolveLabel(tier)
	        currentLabel.textContent = label
	        options.forEach((item) => {
	          const isSelected = item.dataset.tier === tier
	          const checkIcon = item.querySelector('[data-intelligence-check]')
	          if (checkIcon) {
	            checkIcon.classList.toggle('hidden', !isSelected)
	          }
	          item.classList.toggle('bg-indigo-50/40', isSelected)
	        })
	      }

	      const chevron = selector.querySelector('[data-intelligence-chevron]')

	      // Portal the menu to <body> when opened so it isn't clipped/hidden by sibling stacking contexts.
	      const originalParent = menu.parentNode
	      const originalNextSibling = menu.nextSibling
	      let isOpen = false
	      let rafId = null

	      const positionMenu = () => {
	        if (!isOpen) return
	        const anchorRect = selector.getBoundingClientRect()
	        // Temporarily ensure menu is measurable.
	        const prevVisibility = menu.style.visibility
	        menu.style.visibility = 'hidden'
	        menu.classList.remove('hidden')
	        const menuRect = menu.getBoundingClientRect()
	        menu.style.visibility = prevVisibility

	        const gap = 6 // ~mt-1.5
	        let top = anchorRect.bottom + gap
	        let left = anchorRect.right - menuRect.width

	        const padding = 8
	        const maxLeft = Math.max(padding, window.innerWidth - menuRect.width - padding)
	        left = Math.min(Math.max(padding, left), maxLeft)

	        // If it would go below the viewport, try positioning above.
	        const bottomOverflow = top + menuRect.height + padding - window.innerHeight
	        if (bottomOverflow > 0) {
	          const aboveTop = anchorRect.top - gap - menuRect.height
	          if (aboveTop >= padding) {
	            top = aboveTop
	          }
	        }

	        menu.style.position = 'fixed'
	        menu.style.top = `${Math.round(top)}px`
	        menu.style.left = `${Math.round(left)}px`
	        menu.style.right = 'auto'
	        menu.style.bottom = 'auto'
	        menu.style.marginTop = '0px'
	        menu.style.zIndex = '1000'
	      }

	      const schedulePosition = () => {
	        if (rafId) return
	        rafId = window.requestAnimationFrame(() => {
	          rafId = null
	          positionMenu()
	        })
	      }

	      const openMenu = () => {
	        if (originalParent && menu.parentNode !== document.body) {
	          document.body.appendChild(menu)
	        }
	        isOpen = true
	        positionMenu()
	        menu.classList.remove('hidden')
	        trigger.setAttribute('aria-expanded', 'true')
	        if (chevron) chevron.style.transform = 'rotate(180deg)'
	      }

	      const closeMenu = () => {
	        isOpen = false
	        menu.classList.add('hidden')
	        trigger.setAttribute('aria-expanded', 'false')
	        if (chevron) chevron.style.transform = ''
	        if (originalParent && menu.parentNode === document.body) {
	          if (originalNextSibling) {
	            originalParent.insertBefore(menu, originalNextSibling)
	          } else {
	            originalParent.appendChild(menu)
	          }
	        }
	      }

	      trigger.addEventListener('click', (event) => {
	        event.preventDefault()
	        if (menu.classList.contains('hidden')) {
	          openMenu()
	        } else {
	          closeMenu()
	        }
	      })

	      document.addEventListener('click', (event) => {
	        if (!isOpen) return
	        const target = event.target
	        if (trigger.contains(target) || menu.contains(target)) {
	          return
	        }
	        closeMenu()
	      })

	      document.addEventListener('keydown', (event) => {
	        if (event.key === 'Escape') {
	          closeMenu()
	        }
	      })

	      window.addEventListener('resize', schedulePosition)
	      window.addEventListener('scroll', schedulePosition, { passive: true })

	      options.forEach((option) => {
	        option.addEventListener('click', (event) => {
	          event.preventDefault()
	          const tier = option.dataset.tier
	          if (!tier) {
	            return
	          }
	          input.value = tier
	          applySelection(tier)
	          closeMenu()
	        })
	      })

      const form = document.getElementById('create-agent-form')
      const gateModal = document.getElementById('intelligence-gate-modal')
      const gateTitle = gateModal ? gateModal.querySelector('[data-gate-title]') : null
      const gateMessage = gateModal ? gateModal.querySelector('[data-gate-message]') : null
      const gateDetail = gateModal ? gateModal.querySelector('[data-gate-detail]') : null
      const gateUpgrade = gateModal ? gateModal.querySelector('[data-gate-upgrade]') : null
      const gateAddPack = gateModal ? gateModal.querySelector('[data-gate-add-pack]') : null
      const gateContinue = gateModal ? gateModal.querySelector('[data-gate-continue]') : null
      const gateClose = gateModal ? gateModal.querySelectorAll('[data-gate-close]') : []
      const isAuthenticated = form ? form.dataset.authenticated === 'true' : false
      const requiresTrialFlow = form ? form.dataset.requiresTrial === 'true' : false
      const billingUrl = selector.dataset.billingUrl || '/console/billing/'
      const upgradeUrl = selector.dataset.intelligenceUpgrade || ''
      const maxAllowedTier = selector.dataset.intelligenceMaxTier || 'standard'
      const LOW_CREDIT_DAY_THRESHOLD = 2
      let bypassGate = false
      const submitForm = () => {
        if (!form) return
        if (typeof form.requestSubmit === 'function') {
          form.requestSubmit()
          return
        }
        form.submit()
      }

      const closeGate = () => {
        if (!gateModal) return
        gateModal.classList.add('hidden')
        gateModal.setAttribute('aria-hidden', 'true')
      }

      const openGate = ({ locked, lowCredits, estimatedDaysRemaining, selectedLabel, allowedLabel }) => {
        if (!gateModal || !gateTitle || !gateMessage || !gateContinue) return
        const reason = locked && lowCredits ? 'both' : locked ? 'plan' : 'credits'
        const remainingLabel = estimatedDaysRemaining !== null
          ? (estimatedDaysRemaining < 1 ? 'less than 1' : estimatedDaysRemaining.toFixed(1))
          : 'a few'

        if (reason === 'plan') {
          gateTitle.textContent = `Unlock ${selectedLabel}`
          gateMessage.textContent = `Your plan does not include ${selectedLabel}.`
        } else if (reason === 'credits') {
          gateTitle.textContent = 'Credits running low'
          gateMessage.textContent = `At ${selectedLabel}, you have about ${remainingLabel} days left.`
        } else {
          gateTitle.textContent = `Unlock ${selectedLabel}`
          gateMessage.textContent = `Your plan does not include ${selectedLabel}, and you have about ${remainingLabel} days left.`
        }

        if (gateDetail) {
          gateDetail.textContent = locked
            ? 'Upgrade to Pro or Scale to unlock this tier.'
            : 'Higher tiers burn credits faster.'
        }

        if (gateUpgrade) {
          gateUpgrade.classList.toggle('hidden', !upgradeUrl)
        }
        if (gateAddPack) {
          gateAddPack.classList.toggle('hidden', !billingUrl)
        }
        gateContinue.textContent = locked ? `Use ${allowedLabel}` : 'Continue anyway'
        gateModal.classList.remove('hidden')
        gateModal.setAttribute('aria-hidden', 'false')
      }

      if (gateUpgrade) {
        gateUpgrade.addEventListener('click', () => {
          if (upgradeUrl) {
            window.open(upgradeUrl, '_top')
          }
          closeGate()
        })
      }

      if (gateAddPack) {
        gateAddPack.addEventListener('click', () => {
          if (billingUrl) {
            window.open(billingUrl, '_top')
          }
          closeGate()
        })
      }

      if (gateContinue && form) {
        gateContinue.addEventListener('click', () => {
          const selectedOption = options.find((item) => item.dataset.tier === input.value) || options[0]
          const locked = selectedOption ? selectedOption.dataset.locked === 'true' : false
          if (locked) {
            input.value = maxAllowedTier || 'standard'
            applySelection(input.value)
          }
          bypassGate = true
          closeGate()
          submitForm()
        })
      }

      if (gateClose && gateClose.length) {
        gateClose.forEach((btn) => {
          btn.addEventListener('click', () => closeGate())
        })
      }

      if (form) {
        form.addEventListener('submit', async (event) => {
          if (bypassGate) {
            bypassGate = false
            return
          }

          if (!isAuthenticated) {
            bypassGate = true
            submitForm()
            return
          }

          if (requiresTrialFlow) {
            bypassGate = true
            submitForm()
            return
          }

          event.preventDefault()

          const selectedOption = options.find((item) => item.dataset.tier === input.value) || options[0]
          const selectedLabel = resolveLabel(input.value, 'this tier')
          const allowedLabel = resolveLabel(maxAllowedTier, 'this tier')
          const locked = selectedOption ? selectedOption.dataset.locked === 'true' : false

          let lowCredits = false
          let estimatedDaysRemaining = null
          if (isAuthenticated) {
            try {
              const tierKey = input.value || 'standard'
              const response = await fetch(`/console/api/usage/burn-rate/?tier=${encodeURIComponent(tierKey)}`, { credentials: 'same-origin' })
              if (response.ok) {
                const payload = await response.json()
                const quota = payload ? payload.quota : null
                const projection = payload ? payload.projection : null
                const hasUnlimited = quota ? Boolean(quota.unlimited) : false
                const extraEnabled = Boolean(payload && payload.extra_tasks && payload.extra_tasks.enabled)
                const projectedDays = projection && typeof projection.projected_days_remaining === 'number'
                  ? projection.projected_days_remaining
                  : null
                if (!hasUnlimited && !extraEnabled && projectedDays !== null) {
                  estimatedDaysRemaining = projectedDays
                  lowCredits = estimatedDaysRemaining <= LOW_CREDIT_DAY_THRESHOLD
                }
              }
            } catch (err) {
              lowCredits = false
            }
          }

          if (!locked && !lowCredits) {
            bypassGate = true
            submitForm()
            return
          }

          openGate({ locked, lowCredits, estimatedDaysRemaining, selectedLabel, allowedLabel })
        })
      }

      applySelection(input.value || 'standard')
    })
  </script>

  <!-- Employee Directory Section -->
  <section id="pretrained-workers" class="relative pt-0 pb-16 scroll-mt-32">
    <div class="max-w-6xl mx-auto px-6">
      <div class="text-center mb-8 sm:mb-12">
        <h2 class="text-3xl sm:text-4xl font-light text-slate-900 tracking-tight">Spawn a Pretrained Worker</h2>
        <p class="mt-4 text-base text-slate-500 max-w-2xl mx-auto leading-relaxed">Deploy a proven worker in minutes &mdash; built for research, ops &amp; intelligence.</p>
      </div>

      <div class="space-y-6 mt-12">
        <div class="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4">
          <div class="text-left">
            {% if homepage_pretrained_selected_category or homepage_pretrained_search_term %}
              <p class="text-xs text-slate-400 mt-1">
                Filters:
                {% if homepage_pretrained_selected_category %}{{ homepage_pretrained_selected_category }}{% endif %}
                {% if homepage_pretrained_selected_category and homepage_pretrained_search_term %}, {% endif %}
                {% if homepage_pretrained_search_term %}"{{ homepage_pretrained_search_term }}"{% endif %}
              </p>
            {% endif %}
          </div>
          {% if homepage_pretrained_selected_category or homepage_pretrained_search_term %}
            <a href="{% url 'pages:home' %}#pretrained-workers" class="inline-flex items-center gap-2 self-start sm:self-auto px-4 py-2 rounded-lg border border-slate-200 text-sm font-medium text-slate-600 hover:text-indigo-600 hover:border-indigo-200 transition">
              Reset filters
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
              </svg>
            </a>
          {% endif %}
        </div>

        <form method="get" action="{% url 'pages:home' %}#pretrained-workers" class="flex flex-col gap-4 lg:flex-row lg:items-end bg-white rounded-2xl shadow-xl shadow-slate-200/50 p-6 border border-slate-100 ring-1 ring-slate-200/50">
          <div class="w-full lg:flex-1 text-left">
            <label for="homepage-directory-search" class="block text-sm font-medium text-slate-500">Search</label>
            <div class="mt-2 relative">
              <input id="homepage-directory-search" name="pretrained_search" type="search" value="{{ homepage_pretrained_search_term }}" placeholder="Search skills, focus areas, workflows..." class="w-full rounded-xl border border-slate-200 bg-white/90 px-4 py-3 text-base text-slate-800 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/30 focus:outline-none" />
              {% if homepage_pretrained_search_term %}
                <a href="{% url 'pages:home' %}#pretrained-workers" class="absolute inset-y-0 right-3 flex items-center text-sm text-indigo-600 hover:text-indigo-700">Clear</a>
              {% endif %}
            </div>
          </div>
          <div class="w-full lg:w-64 text-left">
            <label for="homepage-directory-category" class="block text-sm font-medium text-slate-500">Category</label>
            <div class="mt-2 relative">
              <select id="homepage-directory-category" name="pretrained_category" class="w-full rounded-xl border border-slate-200 bg-white/90 px-4 py-3 text-base text-slate-800 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/30 focus:outline-none">
                <option value="">All categories</option>
                {% for category in homepage_pretrained_categories %}
                  <option value="{{ category }}" {% if homepage_pretrained_selected_category == category %}selected{% endif %}>{{ category }}</option>
                {% endfor %}
              </select>
            </div>
          </div>
          {% for key, value in request.GET.items %}
            {% if key != 'pretrained_search' and key != 'pretrained_category' %}
              <input type="hidden" name="{{ key }}" value="{{ value }}" />
            {% endif %}
          {% endfor %}
          <div class="w-full flex justify-end lg:w-auto lg:ml-auto">
            <button type="submit" class="inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-indigo-600 text-white font-medium shadow-lg shadow-indigo-200 hover:bg-indigo-500 transition">
              Search
            </button>
          </div>
        </form>
      </div>

      {% if homepage_pretrained_workers %}
        <div class="mt-12 grid gap-8 md:grid-cols-2 xl:grid-cols-3">
          {% for worker in homepage_pretrained_workers %}
            {% include "pretrained_workers/_card.html" with worker=worker %}
          {% endfor %}
        </div>
      {% else %}
        <div class="mt-12 rounded-2xl border border-dashed border-slate-200 bg-white/70 p-12 text-center shadow-sm">
          <h3 class="text-2xl font-medium text-slate-900">No pretrained workers match those filters yet.</h3>
          <p class="mt-3 text-slate-600">Reset your filters to explore the full directory or reach out to support for a tailored playbook.</p>
          <a href="{% url 'pages:home' %}#pretrained-workers" class="mt-6 inline-flex items-center gap-2 px-5 py-3 bg-indigo-600 text-white font-semibold rounded-xl shadow hover:bg-indigo-500 transition">Clear filters</a>
        </div>
      {% endif %}
    </div>
  </section>





    <script>
      function setPrompt(promptText) {
        const textarea = document.querySelector('textarea[name="charter"]');
        if (textarea) {
          textarea.value = promptText;
          textarea.focus();
          textareaAutoResize(textarea);
        }

        // Analytics CTA
        if (window.analytics && analytics.track) {
          const properties = {
            {% if user.is_authenticated %}user_id: "{{ user }}", {% endif %}
            charter: promptText,
            medium: 'Web',
          };
          analytics.track('{{ analytics.cta.CTA_EXAMPLE_AGENT_CLICKED.value }}', properties);
        }
      }

      // Auto-focus the textarea when page loads
      document.addEventListener('DOMContentLoaded', function() {
        const textarea = document.querySelector('textarea[name="charter"]');
        if (textarea) {
          textarea.focus();
          // Move cursor to the end of the text
          const length = textarea.value.length;
          textarea.setSelectionRange(length, length);
          textareaAutoResize(textarea);
        }
      });

      function textareaAutoResize(el) {
        const maxHeight = parseInt(el.dataset.maxHeight || 400);
        el.style.height = 'auto';
        if (el.scrollHeight <= maxHeight) {
          el.style.height = el.scrollHeight + 'px';
          el.style.overflowY = 'hidden';
        } else {
          el.style.height = maxHeight + 'px';
          el.style.overflowY = 'auto';
        }
      }
    </script>

    {% include "partials/_immersive_overlay.html" %}

    <script>
      document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('create-agent-form');
        if (form) {
          form.addEventListener('submit', function (e) {
            // Optional: fire analytics before submit
            if (window.analytics && analytics.track) {
              const properties = {
                {% if user.is_authenticated %}user_id: "{{ user.id }}", {% endif %}
                charter: document.querySelector('textarea[name="charter"]').value,
                medium: 'Web'
              };

              analytics.track('{{ analytics.cta.CTA_CREATE_AGENT_CLICKED.value }}', properties);
            }
          });
        }
      });
    </script>

    {% include "partials/_immersive_overlay_script.html" %}

    <!-- Scroll-triggered fade-in -->
    <script>
      document.addEventListener('DOMContentLoaded', function () {
        var observer = new IntersectionObserver(function (entries) {
          entries.forEach(function (entry) {
            if (entry.isIntersecting) {
              entry.target.classList.add('is-visible');
              observer.unobserve(entry.target);
            }
          });
        }, { threshold: 0.15 });
        document.querySelectorAll('[data-animate]').forEach(function (el) {
          observer.observe(el);
        });
      });
    </script>
</main>
{% endblock %}

{% block extra_js %}
  {{ block.super }}
  {% if homepage_integrations_enabled %}
    {% vite_asset 'src/homepageIntegrations.tsx' %}
  {% endif %}
{% endblock %}
