import { showAsyncFlash } from './app-async-flash.js';
import { optionalEl, warnOnce } from '../core/app-dom.js';

const SWITCHER_ROOT_SELECTOR = '[data-tenant-switcher]';
const TENANT_LINK_SELECTOR = '[data-switch-tenant]';

const setPending = (link, pending) => {
  link.style.pointerEvents = pending ? 'none' : '';
  link.style.opacity = pending ? '0.5' : '';
  if (pending) {
    link.setAttribute('aria-busy', 'true');
  } else {
    link.removeAttribute('aria-busy');
  }
};

const switchTenant = async (link) => {
  const tenantId = link.dataset.switchTenant;
  const csrfKey = link.dataset.csrfKey;
  const csrfToken = link.dataset.csrfToken;
  const errorMessage = link.dataset.errorMessage || 'Failed to switch tenant';

  if (!tenantId || !csrfKey || !csrfToken) {
    warnOnce('UI_DATA_MISSING', 'Missing tenant ID or CSRF token', { module: 'tenant-switcher' });
    return;
  }

  // Disable link during request
  setPending(link, true);

  try {
    const body = new URLSearchParams({
      tenant_id: tenantId,
      [csrfKey]: csrfToken
    });

    const response = await fetch('admin/users/switch-tenant', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json',
        'X-Requested-With': 'fetch'
      },
      body
    });

    if (response.ok) {
      const data = await response.json();
      if (data.ok) {
        if (data.theme) {
          document.documentElement.dataset.theme = data.theme;
        }
        window.location.reload();
      } else {
        warnOnce('FETCH_FAILED', 'Tenant switch failed', { module: 'tenant-switcher', error: data.error });
        showAsyncFlash('error', errorMessage);
        setPending(link, false);
      }
    } else {
      warnOnce('FETCH_FAILED', `Tenant switch server error: ${response.status}`, { module: 'tenant-switcher' });
      showAsyncFlash('error', errorMessage);
      setPending(link, false);
    }
  } catch (error) {
    warnOnce('FETCH_ERROR', 'Tenant switch network error', { module: 'tenant-switcher', error });
    showAsyncFlash('error', errorMessage);
    setPending(link, false);
  }
};

const initTenantSwitcher = () => {
  const switcherRoot = optionalEl(SWITCHER_ROOT_SELECTOR);
  if (!switcherRoot) {
    // Single-tenant users do not render a switcher; this is expected.
    return;
  }

  const tenantLinks = Array.from(switcherRoot.querySelectorAll(TENANT_LINK_SELECTOR));
  if (!tenantLinks.length) {
    warnOnce('UI_EL_MISSING', 'Tenant switcher root exists but contains no switch links', { module: 'tenant-switcher' });
    return;
  }

  tenantLinks.forEach(link => {
    link.addEventListener('click', (e) => {
      e.preventDefault();
      switchTenant(link);
    });
  });
};

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initTenantSwitcher);
} else {
  initTenantSwitcher();
}
