{% load waffle_tags %}

{% flag "organizations" %}
<!-- Context Switcher Component -->
<div class="relative" x-data="contextSwitcher()">
  <!-- Trigger Button -->
  <button @click="open = !open" 
          @click.away="open = false"
          class="flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 hover:text-blue-600 bg-white/80 hover:bg-white/90 rounded-lg border border-gray-200 transition-all duration-200 min-w-[200px]">
    <div class="flex items-center gap-2 flex-1">
      <!-- Icon for context type -->
      <template x-if="currentContext.type === 'personal'">
        <i aria-hidden="true" data-lucide="user-round" class="w-4 h-4 text-gray-500"></i>
      </template>
      <template x-if="currentContext.type === 'organization'">
        <i aria-hidden="true" data-lucide="users" class="w-4 h-4 text-gray-500"></i>
      </template>
      
      <!-- Context Name -->
      <span class="truncate" x-text="currentContext.name"></span>
    </div>
    
    <!-- Dropdown Arrow -->
    <i aria-hidden="true" data-lucide="chevron-down" class="w-4 h-4 text-gray-400 transition-transform duration-200" :class="{'rotate-180': open}"></i>
  </button>
  
  <!-- Dropdown Menu -->
  <div x-show="open" 
       x-transition:enter="transition ease-out duration-200"
       x-transition:enter-start="opacity-0 scale-95"
       x-transition:enter-end="opacity-100 scale-100"
       x-transition:leave="transition ease-in duration-150"
       x-transition:leave-start="opacity-100 scale-100"
       x-transition:leave-end="opacity-0 scale-95"
       class="absolute left-0 mt-2 w-72 bg-white rounded-lg shadow-lg border border-gray-200 z-50"
       x-cloak>
    
    <!-- Personal Account Section -->
    <div class="p-2 border-b border-gray-100">
      <div class="text-xs font-semibold text-gray-500 uppercase tracking-wider px-2 py-1">Personal Account</div>
      <button @click="switchContext('personal', '{{ user.id }}', '{{ user.get_full_name|default:user.username }}')"
              class="w-full flex items-center gap-3 px-2 py-2 text-sm rounded-md hover:bg-blue-50 transition-colors"
              :class="{'bg-blue-50 text-blue-600': currentContext.type === 'personal'}">
        <i aria-hidden="true" data-lucide="user-round" class="w-4 h-4 flex-shrink-0" :class="{'text-blue-600': currentContext.type === 'personal', 'text-gray-500': currentContext.type !== 'personal'}"></i>
        <span class="flex-1 text-left">{{ user.get_full_name|default:user.username }}</span>
        <template x-if="currentContext.type === 'personal'">
          <i aria-hidden="true" data-lucide="check" class="w-4 h-4 text-blue-600"></i>
        </template>
      </button>
    </div>
    
    {% flag "organizations" %}
    {% if user_organizations %}
    <!-- Organizations Section -->
    <div class="p-2 border-b border-gray-100">
      <div class="text-xs font-semibold text-gray-500 uppercase tracking-wider px-2 py-1">Organizations</div>
      {% for membership in user_organizations %}
      <button @click="switchContext('organization', '{{ membership.org.id }}', '{{ membership.org.name }}')"
              class="w-full flex items-center gap-3 px-2 py-2 text-sm rounded-md hover:bg-blue-50 transition-colors"
              :class="{'bg-blue-50 text-blue-600': currentContext.type === 'organization' && currentContext.id === '{{ membership.org.id }}'}">
        <i aria-hidden="true" data-lucide="users" class="w-4 h-4 flex-shrink-0" :class="{'text-blue-600': currentContext.type === 'organization' && currentContext.id === '{{ membership.org.id }}', 'text-gray-500': !(currentContext.type === 'organization' && currentContext.id === '{{ membership.org.id }}')}"></i>
        <div class="flex-1 text-left">
          <div class="font-medium">{{ membership.org.name }}</div>
          <div class="text-xs text-gray-500">{{ membership.get_role_display }}</div>
        </div>
        <template x-if="currentContext.type === 'organization' && currentContext.id === '{{ membership.org.id }}'">
          <i aria-hidden="true" data-lucide="check" class="w-4 h-4 text-blue-600"></i>
        </template>
      </button>
      {% endfor %}
    </div>
    {% endif %}
    {% endflag %}
    
    <!-- Actions Section -->
    <div class="p-2">
      {% flag "organizations" %}
      <a href="{% url 'organizations' %}" 
         class="flex items-center gap-3 px-2 py-2 text-sm text-gray-700 rounded-md hover:bg-gray-50 transition-colors">
        <i aria-hidden="true" data-lucide="plus" class="w-4 h-4 text-gray-500"></i>
        <span>Create or Join Organization</span>
      </a>
      {% endflag %}
    </div>
  </div>
</div>

<script>
(function initConsoleContextSwitcher() {
  if (!window.CONSOLE_CONTEXT_STORAGE_KEYS) {
    window.CONSOLE_CONTEXT_STORAGE_KEYS = {
      type: 'gobii:console:context-type',
      id: 'gobii:console:context-id',
      name: 'gobii:console:context-name'
    };
  }

  if (!window.writeConsoleContext) {
    window.writeConsoleContext = function writeConsoleContext(type, id, name) {
      localStorage.setItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.type, type);
      localStorage.setItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.id, id);
      localStorage.setItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.name, name);
      try {
        sessionStorage.setItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.type, type);
        sessionStorage.setItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.id, id);
        sessionStorage.setItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.name, name);
      } catch (error) {
        console.warn('Unable to update session console context storage.', error);
      }
    };
  }

  if (!window.readInitialConsoleContext) {
    window.readInitialConsoleContext = function readInitialConsoleContext() {
      try {
        const sessionType = sessionStorage.getItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.type);
        const sessionId = sessionStorage.getItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.id);
        const sessionName = sessionStorage.getItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.name);
        if (sessionType && sessionId) {
          return { type: sessionType, id: sessionId, name: sessionName || '' };
        }
      } catch (error) {
        console.warn('Unable to read session console context storage.', error);
      }

      return {
        type: localStorage.getItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.type) || localStorage.getItem('contextType') || '{{ current_context.type|default:"personal" }}',
        id: localStorage.getItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.id) || localStorage.getItem('contextId') || '{{ current_context.id|default:user.id }}',
        name: localStorage.getItem(window.CONSOLE_CONTEXT_STORAGE_KEYS.name) || localStorage.getItem('contextName') || '{{ current_context.name|default:user.get_full_name|default:user.username|escapejs }}'
      };
    };
  }

  window.contextSwitcher = function contextSwitcher() {
    return {
      open: false,
      currentContext: window.readInitialConsoleContext(),

      init() {
        // Sync localStorage with server session context if they differ
        const serverType = '{{ current_context.type|default:"personal" }}';
        const serverId = '{{ current_context.id|default:user.id }}';
        const serverName = '{{ current_context.name|default:user.get_full_name|default:user.username|escapejs }}';

        if (this.currentContext.type !== serverType || this.currentContext.id !== serverId) {
          window.writeConsoleContext(serverType, serverId, serverName);
          this.currentContext = { type: serverType, id: serverId, name: serverName };
        }
      },

      async switchContext(type, id, name) {
        // Save to browser storage for immediate UI updates
        window.writeConsoleContext(type, id, name);

        // Update current context
        this.currentContext = { type, id, name };

        // Close dropdown
        this.open = false;

        // Save to server session
        try {
          const response = await fetch('{% url "switch_context" %}', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-CSRFToken': getCsrfTokenValue()
            },
            body: JSON.stringify({ type, id, name })
          });

          if (response.ok) {
            // If currently on an agent detail page, redirect to the agents list
            const isAgentDetail = /\/console\/agents\/[^/]+\/$/.test(window.location.pathname);
            if (isAgentDetail) {
              window.location = '{% url "agents" %}';
              return;
            }

            // If currently on an organization detail page, redirect to the selected org
            const isOrgDetail = /^\/console\/organizations\/[^/]+\/$/.test(window.location.pathname);
            if (isOrgDetail && type === 'organization') {
              window.location = `/console/organizations/${id}/`;
              return;
            }

            // Default: reload current page to reflect context change
            window.location.reload();
          } else {
            console.error('Failed to switch context');
            // On failure, reload to show current (unchanged) context
            window.location.reload();
          }
        } catch (error) {
          console.error('Error switching context:', error);
          window.location.reload();
        }
      }
    };
  };
})();
</script>
{% endflag %}
