if (import.meta.env.DEV || import.meta.env.VITE_ENABLE_TENANT_SWITCHER === 'true') {
  const CREDENTIALS: Record<string, { login: string; password: string }> = {
    'cust-standard-empty': { login: 'standard-empty@demo.fotospiel', password: 'Demo1234!' },
    'cust-starter-wedding': { login: 'starter-wedding@demo.fotospiel', password: 'Demo1234!' },
    'reseller-s-active': { login: 'partner-active@demo.fotospiel', password: 'Demo1234!' },
    'reseller-s-full': { login: 'partner-full@demo.fotospiel', password: 'Demo1234!' },
  };

  async function loginAs(key: string): Promise<void> {
    const credentials = CREDENTIALS[key];
    if (!credentials) {
      console.warn('[DevAuth] Unknown tenant key', key);
      return;
    }

    try {
      const response = await fetch('/api/v1/tenant-auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: JSON.stringify({
          login: credentials.login,
          password: credentials.password,
        }),
      });

      if (!response.ok) {
        throw new Error(`Login failed with status ${response.status}`);
      }

      const payload = (await response.json()) as { token: string; abilities?: string[] };
      const stored = {
        accessToken: payload.token,
        abilities: Array.isArray(payload.abilities) ? payload.abilities : [],
        issuedAt: Date.now(),
      } satisfies { accessToken: string; abilities: string[]; issuedAt: number };

      try {
        window.localStorage.setItem('tenant_admin.token.v1', JSON.stringify(stored));
      } catch (error) {
        console.warn('[DevAuth] Failed to persist PAT to localStorage', error);
      }

      try {
        window.sessionStorage.setItem('tenant_admin.token.session.v1', JSON.stringify(stored));
      } catch (error) {
        console.warn('[DevAuth] Failed to persist PAT to sessionStorage', error);
      }

      window.location.assign('/event-admin/mobile/dashboard');
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      console.error('[DevAuth] Demo login failed', message);
      throw error instanceof Error ? error : new Error(message);
    }
  }

  const api = {
    loginAs,
    clients: Object.fromEntries(Object.entries(CREDENTIALS).map(([key, value]) => [key, value.login])),
  };
  console.info('[DevAuth] Demo tenant helpers ready', Object.keys(api.clients));

  (window as typeof window & { fotospielDemoAuth?: typeof api }).fotospielDemoAuth = api;
  (globalThis as typeof globalThis & { fotospielDemoAuth?: typeof api }).fotospielDemoAuth = api;
}
