{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Gobii – First Run Setup</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="csrf-cookie-name" content="{{ settings.CSRF_COOKIE_NAME|default:'csrftoken' }}">
  {% include "partials/_csrf_helpers.html" %}
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link rel="stylesheet" href="{% static 'css/custom_fonts.css' %}">
  <link rel="stylesheet" href="{% static 'css/globals.css' %}">
  <script src="https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,container-queries"></script>
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            brand: {
              50: '#eef2ff',
              100: '#e0e7ff',
              200: '#c7d2fe',
              300: '#a5b4fc',
              400: '#818cf8',
              500: '#6366f1',
              600: '#4f46e5',
              700: '#4338ca',
            },
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', '-apple-system', 'BlinkMacSystemFont', 'Segoe UI', 'sans-serif'],
          },
          boxShadow: {
            panel: '0 48px 96px -48px rgba(79, 70, 229, 0.55)',
            subtle: '0 14px 32px -20px rgba(15, 23, 42, 0.35)',
            badge: '0 14px 32px rgba(99, 102, 241, 0.25)',
          },
        },
      },
    };
  </script>
  <style>
    body {
      font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    }
  </style>
</head>
<body class="min-h-screen bg-gradient-to-br from-[#f6f8ff] via-white to-[#e6f2ff] text-slate-800">
  <div class="relative overflow-hidden">
    <div class="pointer-events-none absolute inset-0 -z-10">
      <div class="absolute -top-24 left-[8%] h-72 w-72 rounded-full bg-brand-200/45 blur-3xl"></div>
      <div class="absolute bottom-[-8%] right-[12%] h-[26rem] w-[26rem] rounded-full bg-sky-200/45 blur-3xl"></div>
    </div>

    <main class="relative mx-auto max-w-6xl px-4 py-12 sm:px-8 sm:py-16 lg:px-12 lg:py-20">
      <div class="rounded-[2.5rem] border border-white/70 bg-white/95 p-8 shadow-panel ring-1 ring-brand-50/50 backdrop-blur-xl sm:p-12 lg:p-14">
        <header class="mb-12 space-y-6">
          {% if fish_collateral_enabled %}
            <img src="{% static 'images/gobii_fish_with_text_purple_nav.png' %}" alt="Gobii Fish" class="h-9 w-auto">
          {% else %}
            <img src="{% static 'images/noBgBlue.png' %}" alt="Gobii" class="h-9 w-auto">
          {% endif %}
          <div class="space-y-2">
            <p class="text-[11px] font-medium uppercase tracking-[0.32em] text-brand-400">First-run setup</p>
            <h1 class="text-3xl font-medium tracking-tight text-slate-900/90 sm:text-[2.5rem]">Welcome to Gobii</h1>
            <p class="max-w-2xl text-[15px] leading-relaxed text-slate-600">Let’s get your self-hosted instance ready. Complete the admin login and choose an LLM provider for orchestrator and browser agents.</p>
          </div>
        </header>

        <div class="flex flex-col gap-16 lg:grid lg:grid-cols-[minmax(0,1fr)_300px] lg:items-start lg:gap-20">
          <form id="setup-form" method="post" novalidate class="space-y-16 lg:-mt-1">
            {% csrf_token %}

            <section class="space-y-6 lg:!mt-0">
              <div class="flex items-center gap-3">
                <span class="flex h-9 w-9 items-center justify-center rounded-full border border-brand-100 text-sm font-medium text-brand-500">1</span>
                <div>
                  <h2 class="text-xl font-medium text-slate-900/90">Admin Account</h2>
                  <p class="text-sm text-slate-500">Create the Django superuser credentials for your instance.</p>
                </div>
              </div>

              <div class="grid gap-6 sm:grid-cols-2">
                <div class="space-y-2 sm:col-span-2">
                  <label for="{{ superuser_form.email.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ superuser_form.email.label }}</label>
                  {{ superuser_form.email }}
                  {% if superuser_form.email.help_text %}
                    <p class="text-sm text-slate-500">{{ superuser_form.email.help_text }}</p>
                  {% endif %}
                  {% if superuser_form.email.errors %}
                    {% for error in superuser_form.email.errors %}
                      <p class="text-sm text-rose-600">{{ error }}</p>
                    {% endfor %}
                  {% endif %}
                </div>
                <div class="space-y-2">
                  <label for="{{ superuser_form.password1.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ superuser_form.password1.label }}</label>
                  {{ superuser_form.password1 }}
                  {% if superuser_form.password1.errors %}
                    {% for error in superuser_form.password1.errors %}
                      <p class="text-sm text-rose-600">{{ error }}</p>
                    {% endfor %}
                  {% endif %}
                </div>
                <div class="space-y-2">
                  <label for="{{ superuser_form.password2.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ superuser_form.password2.label }}</label>
                  {{ superuser_form.password2 }}
                  {% if superuser_form.password2.errors %}
                    {% for error in superuser_form.password2.errors %}
                      <p class="text-sm text-rose-600">{{ error }}</p>
                    {% endfor %}
                  {% endif %}
                </div>
              </div>
            </section>

            <section class="space-y-6">
              <div class="flex items-center gap-3">
                <span class="flex h-9 w-9 items-center justify-center rounded-full border border-brand-100 text-sm font-medium text-brand-500">2</span>
                <div>
                  <h2 class="text-xl font-medium text-slate-900/90">Primary Agents LLM</h2>
                  <p class="text-sm text-slate-500">Configure the orchestrator provider and model that powers your agents.</p>
                </div>
              </div>

              <div class="grid gap-6 sm:grid-cols-2">
                <div class="space-y-2">
                  <label for="{{ llm_form.orchestrator_provider.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ llm_form.orchestrator_provider.label }}</label>
                  {{ llm_form.orchestrator_provider }}
                  {% if llm_form.orchestrator_provider.errors %}
                    {% for error in llm_form.orchestrator_provider.errors %}
                      <p class="text-sm text-rose-600">{{ error }}</p>
                    {% endfor %}
                  {% endif %}
                </div>
                <div class="space-y-2">
                  <label for="{{ llm_form.orchestrator_api_key.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ llm_form.orchestrator_api_key.label }}</label>
                  {{ llm_form.orchestrator_api_key }}
                  <p class="text-sm text-slate-500">{{ llm_form.orchestrator_api_key.help_text }}</p>
                  {% if llm_form.orchestrator_api_key.errors %}
                    {% for error in llm_form.orchestrator_api_key.errors %}
                      <p class="text-sm text-rose-600">{{ error }}</p>
                    {% endfor %}
                  {% endif %}
                </div>
                <div class="space-y-2">
                  <label for="{{ llm_form.orchestrator_model.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ llm_form.orchestrator_model.label }}</label>
                  {{ llm_form.orchestrator_model }}
                  {% if llm_form.orchestrator_model.help_text %}
                    <p class="text-sm text-slate-500">{{ llm_form.orchestrator_model.help_text }}</p>
                  {% endif %}
                  {% if llm_form.orchestrator_model.errors %}
                    {% for error in llm_form.orchestrator_model.errors %}
                      <p class="text-sm text-rose-600">{{ error }}</p>
                    {% endfor %}
                  {% endif %}
                </div>
                <div class="space-y-2">
                  <label for="{{ llm_form.orchestrator_api_base.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ llm_form.orchestrator_api_base.label }}</label>
                  {{ llm_form.orchestrator_api_base }}
                  {% if llm_form.orchestrator_api_base.help_text %}
                    <p class="text-sm text-slate-500">{{ llm_form.orchestrator_api_base.help_text }}</p>
                  {% endif %}
                  {% if llm_form.orchestrator_api_base.errors %}
                    {% for error in llm_form.orchestrator_api_base.errors %}
                      <p class="text-sm text-rose-600">{{ error }}</p>
                    {% endfor %}
                  {% endif %}
                </div>
                <div class="space-y-2">
                  <label for="{{ llm_form.orchestrator_custom_name.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ llm_form.orchestrator_custom_name.label }}</label>
                  {{ llm_form.orchestrator_custom_name }}
                  {% if llm_form.orchestrator_custom_name.help_text %}
                    <p class="text-sm text-slate-500">{{ llm_form.orchestrator_custom_name.help_text }}</p>
                  {% endif %}
                  {% if llm_form.orchestrator_custom_name.errors %}
                    {% for error in llm_form.orchestrator_custom_name.errors %}
                      <p class="text-sm text-rose-600">{{ error }}</p>
                    {% endfor %}
                  {% endif %}
                </div>
                <div class="space-y-4 rounded-3xl border border-slate-200/70 p-6">
                  <p class="text-sm font-medium text-slate-700/90">Advanced options</p>
                  <div class="space-y-4">
                    <label for="{{ llm_form.orchestrator_supports_vision.id_for_label }}" class="flex items-center gap-3 text-sm font-medium text-slate-700/90">
                      {{ llm_form.orchestrator_supports_vision }}
                      <span>{{ llm_form.orchestrator_supports_vision.label }}</span>
                    </label>
                    {% if llm_form.orchestrator_supports_vision.errors %}
                      {% for error in llm_form.orchestrator_supports_vision.errors %}
                        <p class="text-sm text-rose-600">{{ error }}</p>
                      {% endfor %}
                    {% endif %}
                    <label for="{{ llm_form.orchestrator_supports_tool_choice.id_for_label }}" class="flex items-center gap-3 text-sm font-medium text-slate-700/90">
                      {{ llm_form.orchestrator_supports_tool_choice }}
                      <span>{{ llm_form.orchestrator_supports_tool_choice.label }}</span>
                    </label>
                    {% if llm_form.orchestrator_supports_tool_choice.errors %}
                      {% for error in llm_form.orchestrator_supports_tool_choice.errors %}
                        <p class="text-sm text-rose-600">{{ error }}</p>
                      {% endfor %}
                    {% endif %}
                    <label for="{{ llm_form.orchestrator_use_parallel_tools.id_for_label }}" class="flex items-center gap-3 text-sm font-medium text-slate-700/90">
                      {{ llm_form.orchestrator_use_parallel_tools }}
                      <span>{{ llm_form.orchestrator_use_parallel_tools.label }}</span>
                    </label>
                    {% if llm_form.orchestrator_use_parallel_tools.errors %}
                      {% for error in llm_form.orchestrator_use_parallel_tools.errors %}
                        <p class="text-sm text-rose-600">{{ error }}</p>
                      {% endfor %}
                    {% endif %}
                  </div>
                </div>
              </div>
              <div class="rounded-3xl border border-slate-200/70 bg-white/70 px-5 py-4">
                <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                  <div>
                    <p class="text-sm font-medium text-slate-700/90">Connection test</p>
                    <p class="text-xs text-slate-500">Verify this configuration by running a quick completion.</p>
                  </div>
                  <button type="button" data-llm-test="orchestrator" class="inline-flex items-center rounded-2xl bg-brand-500/90 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-brand-600 focus:outline-none focus:ring-4 focus:ring-brand-200/70 disabled:opacity-60">
                    Test primary model
                  </button>
                </div>
                <p class="mt-2 text-sm text-slate-500" data-test-status="orchestrator">Not tested yet.</p>
              </div>
            </section>

            <section class="space-y-6">
              <div class="flex items-center gap-3">
                <span class="flex h-9 w-9 items-center justify-center rounded-full border border-brand-100 text-sm font-medium text-brand-500">3</span>
                <div>
                  <h2 class="text-xl font-medium text-slate-900/90">Browser Automations</h2>
                  <p class="text-sm text-slate-500">Reuse the orchestrator provider or specify a dedicated model for browser agents.</p>
                </div>
              </div>

              <div class="space-y-3">
                <label for="{{ llm_form.browser_same_as_orchestrator.id_for_label }}" class="flex items-center gap-3 rounded-3xl border border-slate-200/70 px-5 py-4 text-sm font-medium text-slate-700/90">
                  {{ llm_form.browser_same_as_orchestrator }}
                  <span>{{ llm_form.browser_same_as_orchestrator.label }}</span>
                </label>
                {% if llm_form.browser_same_as_orchestrator.errors %}
                  {% for error in llm_form.browser_same_as_orchestrator.errors %}
                    <p class="text-sm text-rose-600">{{ error }}</p>
                  {% endfor %}
                {% endif %}
              </div>

              <div id="browser-extra" class="space-y-6 rounded-3xl border border-slate-200/70 p-6 hidden">
                <div class="grid gap-6 sm:grid-cols-2">
                  <div class="space-y-2">
                    <label for="{{ llm_form.browser_provider.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ llm_form.browser_provider.label }}</label>
                    {{ llm_form.browser_provider }}
                    {% if llm_form.browser_provider.errors %}
                      {% for error in llm_form.browser_provider.errors %}
                        <p class="text-sm text-rose-600">{{ error }}</p>
                      {% endfor %}
                    {% endif %}
                  </div>
                  <div class="space-y-2">
                    <label for="{{ llm_form.browser_api_key.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ llm_form.browser_api_key.label }}</label>
                    {{ llm_form.browser_api_key }}
                    {% if llm_form.browser_api_key.errors %}
                      {% for error in llm_form.browser_api_key.errors %}
                        <p class="text-sm text-rose-600">{{ error }}</p>
                      {% endfor %}
                    {% endif %}
                  </div>
                  <div class="space-y-2">
                    <label for="{{ llm_form.browser_model.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ llm_form.browser_model.label }}</label>
                    {{ llm_form.browser_model }}
                    {% if llm_form.browser_model.help_text %}
                      <p class="text-sm text-slate-500">{{ llm_form.browser_model.help_text }}</p>
                    {% endif %}
                    {% if llm_form.browser_model.errors %}
                      {% for error in llm_form.browser_model.errors %}
                        <p class="text-sm text-rose-600">{{ error }}</p>
                      {% endfor %}
                    {% endif %}
                  </div>
                  <div class="space-y-2">
                    <label for="{{ llm_form.browser_api_base.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ llm_form.browser_api_base.label }}</label>
                    {{ llm_form.browser_api_base }}
                    {% if llm_form.browser_api_base.errors %}
                      {% for error in llm_form.browser_api_base.errors %}
                        <p class="text-sm text-rose-600">{{ error }}</p>
                      {% endfor %}
                    {% endif %}
                  </div>
                  <div class="space-y-2">
                    <label for="{{ llm_form.browser_custom_name.id_for_label }}" class="text-sm font-medium text-slate-700/90">{{ llm_form.browser_custom_name.label }}</label>
                    {{ llm_form.browser_custom_name }}
                    {% if llm_form.browser_custom_name.errors %}
                      {% for error in llm_form.browser_custom_name.errors %}
                        <p class="text-sm text-rose-600">{{ error }}</p>
                      {% endfor %}
                    {% endif %}
                  </div>
                </div>
                <div id="browser-test-block" class="rounded-3xl border border-slate-200/70 bg-white/70 px-5 py-4">
                  <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                      <p class="text-sm font-medium text-slate-700/90">Browser test</p>
                      <p class="text-xs text-slate-500">Verify the dedicated browser model responds.</p>
                    </div>
                    <button type="button" data-llm-test="browser" class="inline-flex items-center rounded-2xl bg-brand-500/90 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-brand-600 focus:outline-none focus:ring-4 focus:ring-brand-200/70 disabled:opacity-60">
                      Test browser model
                    </button>
                  </div>
                  <p class="mt-2 text-sm text-slate-500" data-test-status="browser">Not tested yet.</p>
                </div>
              </div>
              <div class="space-y-4 rounded-3xl border border-slate-200/70 p-6">
                <p class="text-sm font-medium text-slate-700/90">Browser advanced options</p>
                <div class="space-y-4">
                  <label for="{{ llm_form.browser_supports_vision.id_for_label }}" class="flex items-center gap-3 text-sm font-medium text-slate-700/90">
                    {{ llm_form.browser_supports_vision }}
                    <span>{{ llm_form.browser_supports_vision.label }}</span>
                  </label>
                  {% if llm_form.browser_supports_vision.errors %}
                    {% for error in llm_form.browser_supports_vision.errors %}
                      <p class="text-sm text-rose-600">{{ error }}</p>
                    {% endfor %}
                  {% endif %}
                </div>
              </div>
            </section>
          </form>

          <aside class="lg:pl-12 lg:self-start">
            <h3 class="text-base font-medium text-slate-900/90">What happens next?</h3>
            <ul class="mt-5 space-y-5 text-sm text-slate-600">
              <li class="flex gap-3">
                <span class="mt-0.5 inline-flex h-7 w-7 items-center justify-center rounded-full border border-brand-100 text-xs font-medium text-brand-500">1</span>
                <span><strong class="block font-medium text-slate-800/90">Secure admin access</strong> The email and password become your Django superuser credentials.</span>
              </li>
              <li class="flex gap-3">
                <span class="mt-0.5 inline-flex h-7 w-7 items-center justify-center rounded-full border border-brand-100 text-xs font-medium text-brand-500">2</span>
                <span><strong class="block font-medium text-slate-800/90">Provision LLM providers</strong> Keys are stored encrypted and defaults match your selection.</span>
              </li>
              <li class="flex gap-3">
                <span class="mt-0.5 inline-flex h-7 w-7 items-center justify-center rounded-full border border-brand-100 text-xs font-medium text-brand-500">3</span>
                <span><strong class="block font-medium text-slate-800/90">Launch agents</strong> Orchestrator and browser agents are ready for workflows right after saving.</span>
              </li>
            </ul>
            <div class="mt-6 rounded-2xl border border-dashed border-brand-200/70 p-4 text-xs text-brand-700">
              <p class="font-semibold">Need to use environment variables instead?</p>
              <p class="mt-1 leading-relaxed">Skip keys here and set <code class="rounded bg-white/80 px-1 py-0.5 text-[11px] text-slate-700 shadow-sm">GOBII_LLM_* </code> values before restarting the app. <a href="https://docs.gobii.ai" target="_blank" rel="noreferrer" class="text-brand-600 underline decoration-brand-200 underline-offset-4 hover:text-brand-700">See docs</a></p>
            </div>
          </aside>
        </div>

        <div class="mt-12 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <p class="text-sm text-slate-500">You can adjust any of these settings later from the admin console.</p>
          <button type="submit" form="setup-form" class="inline-flex items-center justify-center gap-2 rounded-2xl bg-brand-500 px-7 py-3 text-base font-semibold text-white shadow-sm transition hover:bg-brand-600 focus:outline-none focus:ring-4 focus:ring-brand-200/70 focus:ring-offset-1">
            Save &amp; Launch Gobii
          </button>
        </div>
      </div>
    </main>
  </div>

  <script>
    const llmTestUrl = "{% url 'setup:test_llm' %}";
    const browserToggle = document.getElementById('id_browser_same_as_orchestrator');
    const browserExtra = document.getElementById('browser-extra');
    const orchestratorProvider = document.getElementById('id_orchestrator_provider');
    const orchestratorVision = document.getElementById('id_orchestrator_supports_vision');
    const browserProvider = document.getElementById('id_browser_provider');
    const browserVision = document.getElementById('id_browser_supports_vision');
    const testButtons = document.querySelectorAll('[data-llm-test]');

    const VISION_DEFAULT_PROVIDERS = ['openai', 'anthropic', 'google'];
    const STATUS_TONES = {
      idle: 'text-slate-500',
      pending: 'text-slate-500',
      success: 'text-emerald-600',
      error: 'text-rose-600',
    };

    function setTestStatus(target, tone, message) {
      const el = document.querySelector(`[data-test-status="${target}"]`);
      if (!el) return;
      Object.values(STATUS_TONES).forEach((cls) => el.classList.remove(cls));
      el.classList.add(STATUS_TONES[tone] || STATUS_TONES.idle);
      el.textContent = message;
    }

    function resetStatus(target) {
      setTestStatus(target, 'idle', 'Not tested yet.');
    }

    function buildTestPayload(target) {
      const form = document.getElementById('setup-form');
      if (!form) {
        return { ok: false, error: 'Form not ready yet.' };
      }
      const formData = new FormData(form);
      if (target === 'browser') {
        if (browserToggle && browserToggle.checked) {
          return { ok: false, error: 'Browser automations reuse the primary LLM.' };
        }
        const provider = formData.get('browser_provider');
        const model = (formData.get('browser_model') || '').trim();
        if (!provider || !model) {
          return { ok: false, error: 'Fill in the browser provider and model first.' };
        }
        return {
          ok: true,
          payload: {
            target: 'browser',
            provider,
            model,
            api_key: formData.get('browser_api_key') || '',
            api_base: (formData.get('browser_api_base') || '').trim(),
          },
        };
      }
      const provider = formData.get('orchestrator_provider');
      const model = (formData.get('orchestrator_model') || '').trim();
      if (!provider || !model) {
        return { ok: false, error: 'Select a primary provider and model first.' };
      }
      return {
        ok: true,
        payload: {
          target: 'orchestrator',
          provider,
          model,
          api_key: formData.get('orchestrator_api_key') || '',
          api_base: (formData.get('orchestrator_api_base') || '').trim(),
        },
      };
    }

    async function handleTestClick(target) {
      const buildResult = buildTestPayload(target);
      if (!buildResult.ok) {
        setTestStatus(target, 'error', buildResult.error);
        return;
      }
      const button = document.querySelector(`[data-llm-test="${target}"]`);
      if (button) button.disabled = true;
      setTestStatus(target, 'pending', 'Testing…');
      try {
        const response = await fetch(llmTestUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': window.getCsrfTokenValue ? window.getCsrfTokenValue() : '',
          },
          credentials: 'same-origin',
          body: JSON.stringify(buildResult.payload),
        });
        const data = await response.json();
        if (response.ok && data.ok) {
          const pieces = [];
          if (data.model) pieces.push(data.model);
          if (data.total_tokens) pieces.push(`${data.total_tokens} tokens`);
          const summary = pieces.length ? `Success (${pieces.join(' · ')})` : 'Success';
          const preview = data.preview ? ` – ${data.preview}` : '';
          setTestStatus(target, 'success', `${summary}${preview}`);
        } else {
          setTestStatus(target, 'error', data.message || 'Test failed.');
        }
      } catch (error) {
        setTestStatus(target, 'error', 'Network error while testing.');
      } finally {
        if (button) button.disabled = false;
      }
    }

    if (testButtons && testButtons.length) {
      testButtons.forEach((btn) => {
        btn.addEventListener('click', () => {
          if (btn.dataset.llmTest) {
            handleTestClick(btn.dataset.llmTest);
          }
        });
      });
    }

    function attachStatusReset(inputs, target) {
      inputs.forEach((element) => {
        if (!element) return;
        const eventName = element.tagName === 'SELECT' ? 'change' : 'input';
        element.addEventListener(eventName, () => resetStatus(target));
      });
    }

    attachStatusReset(
      [document.getElementById('id_orchestrator_provider'), document.getElementById('id_orchestrator_model')],
      'orchestrator',
    );
    attachStatusReset(
      [document.getElementById('id_browser_provider'), document.getElementById('id_browser_model')],
      'browser',
    );

    function updateBrowserVisibility() {
      if (!browserToggle || !browserExtra) return;
      browserExtra.classList.toggle('hidden', browserToggle.checked);
      if (browserToggle.checked) {
        resetStatus('browser');
      }
    }

    function maybeSyncBrowserVision() {
      if (!browserToggle || !browserVision) return;
      if (!browserToggle.checked) return;
      if (browserVision.dataset.userEdited === 'true') return;
      if (orchestratorVision) {
        browserVision.checked = orchestratorVision.checked;
      }
    }

    function attachVisionDefaults(providerSelect, checkbox) {
      if (!providerSelect || !checkbox) return;

      const applyDefault = () => {
        const value = providerSelect.value;
        if (!value || checkbox.dataset.userEdited === 'true') {
          return;
        }
        const shouldEnable = VISION_DEFAULT_PROVIDERS.includes(value);
        checkbox.checked = shouldEnable;
      };

      providerSelect.addEventListener('change', () => {
        checkbox.dataset.userEdited = '';
        applyDefault();
        maybeSyncBrowserVision();
      });

      checkbox.addEventListener('change', () => {
        checkbox.dataset.userEdited = 'true';
      });

      applyDefault();
    }

    attachVisionDefaults(orchestratorProvider, orchestratorVision);
    attachVisionDefaults(browserProvider, browserVision);
    maybeSyncBrowserVision();

    if (browserToggle) {
      updateBrowserVisibility();
      browserToggle.addEventListener('change', () => {
        updateBrowserVisibility();
        maybeSyncBrowserVision();
      });
    }

    if (orchestratorVision) {
      orchestratorVision.addEventListener('change', () => {
        maybeSyncBrowserVision();
      });
    }

    if (orchestratorProvider) {
      orchestratorProvider.addEventListener('change', () => {
        maybeSyncBrowserVision();
      });
    }
  </script>
</body>
</html>
