        class AdminApp {
            constructor() {
                this.adminApiUrl = 'http://localhost:8082/sandi/admin';
                this.currentEditingClient = null;
                this.pendingConfirmAction = null;

                this.initializeEventListeners();
                this.loadClients();
            }

            initializeEventListeners() {
                // Show/hide configuration row when create collection checkbox changes
                document.getElementById('createCollection').addEventListener('change', (e) => {
                    document.getElementById('configurationRow').style.display = e.target.checked ? 'block' : 'none';
                });

                // Add keyboard navigation for confirmation dialog
                document.addEventListener('keydown', (e) => {
                    const confirmationModal = document.getElementById('confirmationModal');
                    if (confirmationModal.style.display === 'block') {
                        if (e.key === 'Escape') {
                            e.preventDefault();
                            this.hideConfirmationModal();
                        } else if (e.key === 'Enter') {
                            e.preventDefault();
                            // Trigger click on focused button
                            const focusedElement = document.activeElement;
                            if (focusedElement && focusedElement.classList.contains('admin-btn')) {
                                if (focusedElement.id === 'confirmActionBtn') {
                                    this.confirmAction();
                                } else {
                                    focusedElement.click();
                                }
                            }
                        }
                    }
                });
            }

            generateRequestId() {
                return 'admin-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
            }

            // Tab switching
            switchTab(tabName) {
                // Hide all tabs
                document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
                document.querySelectorAll('.nav-tab').forEach(tab => tab.classList.remove('active'));

                // Show selected tab
                document.getElementById(tabName).classList.add('active');
                event.target.classList.add('active');

                // Load data for the selected tab
                if (tabName === 'clients') {
                    this.loadClients();
                } else if (tabName === 'collections') {
                    this.loadCollections();
                } else if (tabName === 'configurations') {
                    this.loadConfigurations();
                } else if (tabName === 'synonyms') {
                    this.loadSynonyms();
                }
            }

            // Client management
            async loadClients() {
                this.showLoading('clients', true);
                this.clearMessages();

                try {
                    const response = await fetch(`${this.adminApiUrl}/clients?requestId=${this.generateRequestId()}`);

                    if (response.ok) {
                        const clients = await response.json();
                        this.displayClients(clients);
                    } else {
                        this.showError('Failed to load clients');
                    }
                } catch (error) {
                    console.error('Load clients error:', error);
                    this.showError('Failed to connect to admin API. Please check if the index API is running on port 8082.');
                } finally {
                    this.showLoading('clients', false);
                }
            }

            displayClients(clients) {
                const container = document.getElementById('clientsTable');

                if (!clients || clients.length === 0) {
                    container.innerHTML = '<div class="no-data"><h3>No clients found</h3><p>Create your first client using the form above</p></div>';
                    return;
                }

                let tableHtml = `
                    <div class="data-table">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Client ID</th>
                                    <th>Name</th>
                                    <th>Collection</th>
                                    <th>Active</th>
                                    <th>Legacy</th>
                                    <th>Search Processing</th>
                                    <th>Index Processing</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                `;

                clients.forEach(client => {
                    tableHtml += `
                        <tr>
                            <td><strong>${this.escapeHtml(client.clientId)}</strong></td>
                            <td>${this.escapeHtml(client.name || '')}</td>
                            <td>${this.escapeHtml(client.collection || '')}</td>
                            <td>${client.active ? '✓' : '✗'}</td>
                            <td>${client.legacy ? '✓' : '✗'}</td>
                            <td>${client.clientSearchProcessing ? '✓' : '✗'}</td>
                            <td>${client.clientIndexProcessing ? '✓' : '✗'}</td>
                            <td class="actions-cell">
                                <button class="admin-btn action-btn secondary" onclick="adminApp.editClient('${client.clientId}')">Edit</button>
                                <button class="admin-btn action-btn danger" onclick="adminApp.deleteClient('${client.clientId}')">Delete</button>
                            </td>
                        </tr>
                    `;
                });

                tableHtml += '</tbody></table></div>';
                container.innerHTML = tableHtml;
            }

            showClientModal(clientId = null) {
                this.currentEditingClient = clientId;
                const modal = document.getElementById('clientModal');
                const title = document.getElementById('clientModalTitle');

                if (clientId) {
                    title.textContent = 'Edit Client';
                    this.loadClientForEdit(clientId);
                } else {
                    title.textContent = 'Add New Client';
                    this.resetClientForm();
                }

                modal.style.display = 'block';
            }

            hideClientModal() {
                document.getElementById('clientModal').style.display = 'none';
                this.currentEditingClient = null;
                this.resetClientForm();
            }

            resetClientForm() {
                document.getElementById('clientForm').reset();
                document.getElementById('clientActive').checked = true;
                document.getElementById('configurationRow').style.display = 'none';
            }

            async loadClientForEdit(clientId) {
                try {
                    const response = await fetch(`${this.adminApiUrl}/clients/${encodeURIComponent(clientId)}?requestId=${this.generateRequestId()}`);

                    if (response.ok) {
                        const client = await response.json();
                        this.populateClientForm(client);
                    } else {
                        this.showError('Failed to load client details');
                    }
                } catch (error) {
                    console.error('Load client error:', error);
                    this.showError('Failed to load client details');
                }
            }

            populateClientForm(client) {
                document.getElementById('clientId').value = client.clientId || '';
                document.getElementById('clientId').readOnly = true; // Prevent editing client ID
                document.getElementById('clientName').value = client.name || '';
                document.getElementById('clientCollection').value = client.collection || '';
                document.getElementById('clientSynonyms').value = client.synonyms || '';
                document.getElementById('clientFieldsHigh').value = client.fieldsHigh ? client.fieldsHigh.join(', ') : '';
                document.getElementById('clientFieldsLow').value = client.fieldsLow ? client.fieldsLow.join(', ') : '';
                document.getElementById('clientFieldsContent').value = client.fieldsContent ? client.fieldsContent.join(', ') : '';
                document.getElementById('clientEmbServiceUrl').value = client.embServiceUrl || '';
                document.getElementById('clientLlmServiceUrl').value = client.llmServiceUrl || '';
                document.getElementById('clientNlpServiceUrl').value = client.nlpServiceUrl || '';
                document.getElementById('clientRerServiceUrl').value = client.rerServiceUrl || '';
                document.getElementById('clientActive').checked = client.active || false;
                document.getElementById('clientLegacy').checked = client.legacy || false;
                document.getElementById('clientSearchProcessing').checked = client.clientSearchProcessing || false;
                document.getElementById('clientIndexProcessing').checked = client.clientIndexProcessing || false;
            }

            async saveClient() {
                const clientData = {
                    clientId: document.getElementById('clientId').value.trim(),
                    name: document.getElementById('clientName').value.trim(),
                    collection: document.getElementById('clientCollection').value.trim(),
                    synonyms: document.getElementById('clientSynonyms').value.trim(),
                    fieldsHigh: document.getElementById('clientFieldsHigh').value,
                    fieldsLow: document.getElementById('clientFieldsLow').value,
                    fieldsContent: document.getElementById('clientFieldsContent').value,
                    embServiceUrl: document.getElementById('clientEmbServiceUrl').value.trim(),
                    llmServiceUrl: document.getElementById('clientLlmServiceUrl').value.trim(),
                    nlpServiceUrl: document.getElementById('clientNlpServiceUrl').value.trim(),
                    rerServiceUrl: document.getElementById('clientRerServiceUrl').value.trim(),
                    active: document.getElementById('clientActive').checked,
                    legacy: document.getElementById('clientLegacy').checked,
                    clientSearchProcessing: document.getElementById('clientSearchProcessing').checked,
                    clientIndexProcessing: document.getElementById('clientIndexProcessing').checked,
                    createCollection: document.getElementById('createCollection').checked,
                    configuration: document.getElementById('clientConfiguration').value.trim()
                };

                if (!clientData.clientId) {
                    this.showError('Client ID is required');
                    return;
                }

                if (!clientData.name) {
                    this.showError('Client name is required');
                    return;
                }

                try {
                    const response = await fetch(`${this.adminApiUrl}/clients?requestId=${this.generateRequestId()}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(clientData)
                    });

                    if (response.ok) {
                        const adminResponse = await response.json();
                        if (adminResponse.status === 'SUCCESS') {
                            this.showSuccess(adminResponse.message);
                            this.hideClientModal();
                            this.loadClients();
                        } else {
                            this.showError(adminResponse.message || 'Failed to save client');
                        }
                    } else {
                        const adminResponse = await response.json();
                        this.showError(adminResponse.message || 'Failed to save client');
                    }
                } catch (error) {
                    console.error('Save client error:', error);
                    this.showError('Failed to save client');
                }
            }

            parseFields(fieldsString) {
                if (!fieldsString || !fieldsString.trim()) return null;
                return fieldsString.split(',').map(field => field.trim()).filter(field => field.length > 0);
            }

            editClient(clientId) {
                this.showClientModal(clientId);
            }

            deleteClient(clientId) {
                // Bind the context to avoid 'this' issues in the callback
                const self = this;
                this.showConfirmationDialog(
                    'Delete Client',
                    `<strong>Client ID:</strong> ${this.escapeHtml(clientId)}<br><strong>Operation:</strong> Delete client and all associated data`,
                    async function() {
                        try {
                            const response = await fetch(`${self.adminApiUrl}/clients/${encodeURIComponent(clientId)}?requestId=${self.generateRequestId()}`, {
                                method: 'DELETE'
                            });

                            if (response.ok) {
                                const adminResponse = await response.json();
                                if (adminResponse.status === 'SUCCESS') {
                                    self.showSuccess(adminResponse.message);
                                    self.loadClients();
                                } else {
                                    self.showError(adminResponse.message || 'Failed to delete client');
                                }
                            } else {
                                const adminResponse = await response.json();
                                self.showError(adminResponse.message || 'Failed to delete client');
                            }
                        } catch (error) {
                            console.error('Delete client error:', error);
                            self.showError('Failed to delete client');
                        }
                    }
                );
            }

            // Collection management
            async loadCollections() {
                this.showLoading('collections', true);
                this.clearMessages();

                try {
                    const response = await fetch(`${this.adminApiUrl}/collections?requestId=${this.generateRequestId()}`);

                    if (response.ok) {
                        const collections = await response.json();
                        this.displayCollections(collections);
                    } else {
                        this.showError('Failed to load collections');
                    }
                } catch (error) {
                    console.error('Load collections error:', error);
                    this.showError('Failed to connect to admin API. Please check if the index API is running on port 8082.');
                } finally {
                    this.showLoading('collections', false);
                }
            }

            displayCollections(collections) {
                const container = document.getElementById('collectionsTable');

                if (!collections || collections.length === 0) {
                    container.innerHTML = '<div class="no-data"><h3>No collections found</h3><p>Create your first collection using the form above</p></div>';
                    return;
                }

                let tableHtml = `
                    <div class="data-table">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Collection Name</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                `;

                collections.forEach(collectionName => {
                    tableHtml += `
                        <tr>
                            <td><strong>${this.escapeHtml(collectionName)}</strong></td>
                            <td class="actions-cell">
                                <button class="admin-btn action-btn secondary" onclick="adminApp.editCollection('${collectionName}')">Edit</button>
                                <button class="admin-btn action-btn danger" onclick="adminApp.deleteCollection('${collectionName}')">Delete</button>
                            </td>
                        </tr>
                    `;
                });

                tableHtml += '</tbody></table></div>';
                container.innerHTML = tableHtml;
            }

            showCollectionModal() {
                document.getElementById('collectionModal').style.display = 'block';
                this.resetCollectionForm();
            }

            hideCollectionModal() {
                document.getElementById('collectionModal').style.display = 'none';
                this.resetCollectionForm();
            }

            resetCollectionForm() {
                document.getElementById('collectionForm').reset();
                document.getElementById('collectionShards').value = '1';
                document.getElementById('collectionReplicas').value = '1';
            }

            async saveCollection() {
                const collectionData = {
                    name: document.getElementById('collectionName').value.trim(),
                    configuration: document.getElementById('collectionConfiguration').value.trim(),
                    shards: parseInt(document.getElementById('collectionShards').value) || 1,
                    replicas: parseInt(document.getElementById('collectionReplicas').value) || 1
                };

                if (!collectionData.name) {
                    this.showError('Collection name is required');
                    return;
                }

                try {
                    const response = await fetch(`${this.adminApiUrl}/collections?requestId=${this.generateRequestId()}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(collectionData)
                    });

                    if (response.ok) {
                        const adminResponse = await response.json();
                        if (adminResponse.status === 'SUCCESS') {
                            this.showSuccess(adminResponse.message);
                            this.hideCollectionModal();
                            this.loadCollections();
                        } else {
                            this.showError(adminResponse.message || 'Failed to create collection');
                        }
                    } else {
                        const adminResponse = await response.json();
                        this.showError(adminResponse.message || 'Failed to create collection');
                    }
                } catch (error) {
                    console.error('Create collection error:', error);
                    this.showError('Failed to create collection');
                }
            }

            async viewCollection(collectionName) {
                try {
                    const response = await fetch(`${this.adminApiUrl}/collections/${encodeURIComponent(collectionName)}?requestId=${this.generateRequestId()}`);

                    if (response.ok) {
                        const collection = await response.json();
                        this.showCollectionDetailsModal(collection, false);
                    } else {
                        this.showError('Failed to load collection details');
                    }
                } catch (error) {
                    console.error('View collection error:', error);
                    this.showError('Failed to load collection details');
                }
            }

            async editCollection(collectionName) {
                try {
                    const response = await fetch(`${this.adminApiUrl}/collections/${encodeURIComponent(collectionName)}?requestId=${this.generateRequestId()}`);

                    if (response.ok) {
                        const collection = await response.json();
                        this.showCollectionDetailsModal(collection, true);
                    } else {
                        this.showError('Failed to load collection details');
                    }
                } catch (error) {
                    console.error('Edit collection error:', error);
                    this.showError('Failed to load collection details');
                }
            }

            showCollectionDetailsModal(collection, isEditing = false) {
                document.getElementById('detailCollectionName').value = collection.name || '';
                document.getElementById('detailCollectionConfiguration').value = collection.configuration || '';
                document.getElementById('detailCollectionShards').value = collection.shards || 0;
                document.getElementById('detailCollectionReplicas').value = collection.replicas || 0;

                // Set modal title and button visibility based on mode
                const title = document.getElementById('collectionDetailsModalTitle');
                const updateBtn = document.getElementById('updateCollectionBtn');
                const cancelBtn = document.querySelector('#collectionDetailsModal .admin-btn.secondary');

                if (isEditing) {
                    title.textContent = 'Edit Collection';
                    updateBtn.style.display = 'inline-block';
                    cancelBtn.textContent = 'Cancel';
                    // Only configuration should be editable
                    document.getElementById('detailCollectionConfiguration').readOnly = false;
                } else {
                    title.textContent = 'Collection Details';
                    updateBtn.style.display = 'none';
                    cancelBtn.textContent = 'Close';
                    // All fields readonly in view mode
                    document.getElementById('detailCollectionConfiguration').readOnly = true;
                }

                // Store collection name for update operation
                this.currentEditingCollection = isEditing ? collection.name : null;

                document.getElementById('collectionDetailsModal').style.display = 'block';
            }

            hideCollectionDetailsModal() {
                document.getElementById('collectionDetailsModal').style.display = 'none';
                this.currentEditingCollection = null;
            }

            async updateCollection() {
                const collectionName = this.currentEditingCollection;
                if (!collectionName) {
                    this.showError('No collection selected for update');
                    return;
                }

                const collectionData = {
                    configuration: document.getElementById('detailCollectionConfiguration').value.trim()
                };

                try {
                    const response = await fetch(`${this.adminApiUrl}/collections/${encodeURIComponent(collectionName)}?requestId=${this.generateRequestId()}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(collectionData)
                    });

                    if (response.ok) {
                        const adminResponse = await response.json();
                        if (adminResponse.status === 'SUCCESS') {
                            this.showSuccess(adminResponse.message);
                            this.hideCollectionDetailsModal();
                            this.loadCollections();
                        } else {
                            this.showError(adminResponse.message || 'Failed to update collection');
                        }
                    } else {
                        const adminResponse = await response.json();
                        this.showError(adminResponse.message || 'Failed to update collection');
                    }
                } catch (error) {
                    console.error('Update collection error:', error);
                    this.showError('Failed to update collection');
                }
            }

            deleteCollection(collectionName) {
                // Bind the context to avoid 'this' issues in the callback
                const self = this;
                this.showConfirmationDialog(
                    'Delete Collection',
                    `<strong>Collection Name:</strong> ${this.escapeHtml(collectionName)}<br><strong>Operation:</strong> Delete collection and all indexed documents`,
                    async function() {
                        try {
                            const response = await fetch(`${self.adminApiUrl}/collections/${encodeURIComponent(collectionName)}?requestId=${self.generateRequestId()}`, {
                                method: 'DELETE'
                            });

                            if (response.ok) {
                                const adminResponse = await response.json();
                                if (adminResponse.status === 'SUCCESS') {
                                    self.showSuccess(adminResponse.message);
                                    self.loadCollections();
                                } else {
                                    self.showError(adminResponse.message || 'Failed to delete collection');
                                }
                            } else {
                                const adminResponse = await response.json();
                                self.showError(adminResponse.message || 'Failed to delete collection');
                            }
                        } catch (error) {
                            console.error('Delete collection error:', error);
                            self.showError('Failed to delete collection');
                        }
                    }
                );
            }

            // Configuration management
            async loadConfigurations() {
                this.showLoading('configurations', true);
                this.clearMessages();

                try {
                    const response = await fetch(`${this.adminApiUrl}/configurations?requestId=${this.generateRequestId()}`);

                    if (response.ok) {
                        const configurations = await response.json();
                        this.displayConfigurations(configurations);
                    } else {
                        this.showError('Failed to load configurations');
                    }
                } catch (error) {
                    console.error('Load configurations error:', error);
                    this.showError('Failed to connect to admin API. Please check if the index API is running on port 8082.');
                } finally {
                    this.showLoading('configurations', false);
                }
            }

            displayConfigurations(configurations) {
                const container = document.getElementById('configurationsTable');

                if (!configurations || configurations.length === 0) {
                    container.innerHTML = '<div class="no-data"><h3>No configurations found</h3><p>Upload your first configuration using the form above</p></div>';
                    return;
                }

                let tableHtml = `
                    <div class="data-table">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Configuration Name</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                `;

                configurations.forEach(configName => {
                    tableHtml += `
                        <tr>
                            <td><strong>${this.escapeHtml(configName)}</strong></td>
                            <td class="actions-cell">
                                <button class="admin-btn action-btn danger" onclick="adminApp.deleteConfiguration('${configName}')">Delete</button>
                            </td>
                        </tr>
                    `;
                });

                tableHtml += '</tbody></table></div>';
                container.innerHTML = tableHtml;
            }

            async uploadConfiguration() {
                const configurationName = document.getElementById('uploadConfigurationName').value.trim();

                if (!configurationName) {
                    this.showError('Configuration name is required');
                    return;
                }

                try {
                    const requestId = this.generateRequestId();
                    const url = `${this.adminApiUrl}/configurations/${encodeURIComponent(configurationName)}?requestId=${requestId}`;

                    const response = await fetch(url, {
                        method: 'POST'
                    });

                    if (response.ok) {
                        const adminResponse = await response.json();
                        if (adminResponse.status === 'SUCCESS') {
                            this.showSuccess(adminResponse.message);
                            document.getElementById('uploadConfigurationName').value = '';
                            this.loadConfigurations();
                        } else {
                            this.showError(adminResponse.message || 'Failed to upload configuration');
                        }
                    } else {
                        try {
                            const adminResponse = await response.json();
                            this.showError(adminResponse.message || 'Failed to upload configuration');
                        } catch (parseError) {
                            this.showError(`Failed to upload configuration: HTTP ${response.status}`);
                        }
                    }
                } catch (error) {
                    this.showError(`Failed to upload configuration: ${error.message}`);
                }
            }

            deleteConfiguration(configurationName) {
                const self = this;
                this.showConfirmationDialog(
                    'Delete Configuration',
                    `<strong>Configuration Name:</strong> ${this.escapeHtml(configurationName)}<br><strong>Operation:</strong> Delete configuration schema`,
                    () => {
                        self.executeDeleteConfiguration(configurationName);
                    }
                );
            }

            async executeDeleteConfiguration(configurationName) {
                try {
                    const requestId = this.generateRequestId();
                    const url = `${this.adminApiUrl}/configurations/${encodeURIComponent(configurationName)}?requestId=${requestId}`;

                    const response = await fetch(url, {
                        method: 'DELETE'
                    });

                    if (response.ok) {
                        const adminResponse = await response.json();
                        if (adminResponse.status === 'SUCCESS') {
                            this.showSuccess(adminResponse.message);
                            this.loadConfigurations();
                        } else {
                            this.showError(adminResponse.message || 'Failed to delete configuration');
                        }
                    } else {
                        try {
                            const adminResponse = await response.json();
                            this.showError(adminResponse.message || 'Failed to delete configuration');
                        } catch (parseError) {
                            this.showError(`Failed to delete configuration: HTTP ${response.status}`);
                        }
                    }
                } catch (error) {
                    this.showError(`Failed to delete configuration: ${error.message}`);
                }
            }

            // Synonym management
            async loadSynonyms() {
                this.showLoading('synonyms', true);
                this.clearMessages();

                try {
                    const response = await fetch(`${this.adminApiUrl}/synonyms?requestId=${this.generateRequestId()}`);

                    if (response.ok) {
                        const synonyms = await response.json();
                        this.displaySynonyms(synonyms);
                    } else {
                        this.showError('Failed to load synonyms');
                    }
                } catch (error) {
                    console.error('Load synonyms error:', error);
                    this.showError('Failed to connect to admin API. Please check if the index API is running on port 8082.');
                } finally {
                    this.showLoading('synonyms', false);
                }
            }

            displaySynonyms(synonyms) {
                const container = document.getElementById('synonymsTable');

                if (!synonyms || synonyms.length === 0) {
                    container.innerHTML = '<div class="no-data"><h3>No synonym sets found</h3><p>Upload your first synonym set using the form above</p></div>';
                    return;
                }

                let tableHtml = `
                    <div class="data-table">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Synonym Set Name</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                `;

                synonyms.forEach(synonymName => {
                    tableHtml += `
                        <tr>
                            <td><strong>${this.escapeHtml(synonymName)}</strong></td>
                            <td class="actions-cell">
                                <button class="admin-btn action-btn danger" onclick="adminApp.deleteSynonyms('${synonymName}')">Delete</button>
                            </td>
                        </tr>
                    `;
                });

                tableHtml += '</tbody></table></div>';
                container.innerHTML = tableHtml;
            }

            async uploadSynonyms() {
                const synonymName = document.getElementById('uploadSynonymName').value.trim();
                const fileName = document.getElementById('uploadSynonymFileName').value.trim();
                const language = document.getElementById('uploadSynonymLanguage').value.trim();

                if (!synonymName) {
                    this.showError('Synonym set name is required');
                    return;
                }

                if (!fileName) {
                    this.showError('Synonym file name is required');
                    return;
                }

                if (!language) {
                    this.showError('Language is required');
                    return;
                }

                try {
                    const requestId = this.generateRequestId();
                    const url = `${this.adminApiUrl}/synonyms/${encodeURIComponent(synonymName)}?fileName=${encodeURIComponent(fileName)}&language=${encodeURIComponent(language)}&requestId=${requestId}`;

                    const response = await fetch(url, {
                        method: 'POST'
                    });

                    if (response.ok) {
                        const adminResponse = await response.json();
                        if (adminResponse.status === 'SUCCESS') {
                            this.showSuccess(adminResponse.message);
                            document.getElementById('uploadSynonymName').value = '';
                            document.getElementById('uploadSynonymFileName').value = '';
                            document.getElementById('uploadSynonymLanguage').value = '';
                            this.loadSynonyms();
                        } else {
                            this.showError(adminResponse.message || 'Failed to upload synonyms');
                        }
                    } else {
                        try {
                            const adminResponse = await response.json();
                            this.showError(adminResponse.message || 'Failed to upload synonyms');
                        } catch (parseError) {
                            this.showError(`Failed to upload synonyms: HTTP ${response.status}`);
                        }
                    }
                } catch (error) {
                    this.showError(`Failed to upload synonyms: ${error.message}`);
                }
            }

            deleteSynonyms(synonymName) {
                const self = this;
                this.showConfirmationDialog(
                    'Delete Synonyms',
                    `<strong>Synonym Set Name:</strong> ${this.escapeHtml(synonymName)}<br><strong>Operation:</strong> Delete synonym set`,
                    () => {
                        self.executeDeleteSynonyms(synonymName);
                    }
                );
            }

            async executeDeleteSynonyms(synonymName) {
                try {
                    const requestId = this.generateRequestId();
                    const url = `${this.adminApiUrl}/synonyms/${encodeURIComponent(synonymName)}?requestId=${requestId}`;

                    const response = await fetch(url, {
                        method: 'DELETE'
                    });

                    if (response.ok) {
                        const adminResponse = await response.json();
                        if (adminResponse.status === 'SUCCESS') {
                            this.showSuccess(adminResponse.message);
                            this.loadSynonyms();
                        } else {
                            this.showError(adminResponse.message || 'Failed to delete synonyms');
                        }
                    } else {
                        try {
                            const adminResponse = await response.json();
                            this.showError(adminResponse.message || 'Failed to delete synonyms');
                        } catch (parseError) {
                            this.showError(`Failed to delete synonyms: HTTP ${response.status}`);
                        }
                    }
                } catch (error) {
                    this.showError(`Failed to delete synonyms: ${error.message}`);
                }
            }

            showConfirmationDialog(title, details, confirmAction, buttonText = 'Confirm', isDanger = true) {
                document.getElementById('confirmationTitle').textContent = title;
                document.getElementById('confirmationDetails').innerHTML = details;
                this.pendingConfirmAction = confirmAction;

                const confirmBtn = document.getElementById('confirmActionBtn');
                confirmBtn.textContent = buttonText;
                confirmBtn.className = isDanger ? 'admin-btn danger' : 'admin-btn';

                document.getElementById('confirmationModal').style.display = 'block';

                // Focus on Cancel button by default for safety
                setTimeout(() => {
                    const cancelBtn = document.querySelector('#confirmationModal .admin-btn.secondary');
                    if (cancelBtn) {
                        cancelBtn.focus();
                    }
                }, 100);
            }

            hideConfirmationModal() {
                document.getElementById('confirmationModal').style.display = 'none';
                this.pendingConfirmAction = null;
            }

            confirmAction() {
                if (this.pendingConfirmAction) {
                    // Store the action before hiding modal (which clears it)
                    const actionToExecute = this.pendingConfirmAction;
                    this.hideConfirmationModal();

                    try {
                        actionToExecute();
                    } catch (error) {
                        this.showError('An error occurred while executing the action');
                    }
                } else {
                    this.hideConfirmationModal();
                }
            }

            // Utility methods
            showLoading(section, show) {
                document.getElementById(`${section}LoadingIndicator`).style.display = show ? 'block' : 'none';
            }

            showError(message) {
                document.getElementById('errorContainer').innerHTML = `
                    <div class="error">${this.escapeHtml(message)}</div>
                `;
                document.getElementById('successContainer').innerHTML = '';
            }

            showSuccess(message) {
                document.getElementById('successContainer').innerHTML = `
                    <div class="success">${this.escapeHtml(message)}</div>
                `;
                document.getElementById('errorContainer').innerHTML = '';
            }

            clearMessages() {
                document.getElementById('errorContainer').innerHTML = '';
                document.getElementById('successContainer').innerHTML = '';
            }

            escapeHtml(text) {
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }
        }

        // Global functions for tab switching
        function switchTab(tabName) {
            adminApp.switchTab(tabName);
        }

        function showClientModal() {
            adminApp.showClientModal();
        }

        function hideClientModal() {
            adminApp.hideClientModal();
        }

        function saveClient() {
            adminApp.saveClient();
        }

        function showCollectionModal() {
            adminApp.showCollectionModal();
        }

        function hideCollectionModal() {
            adminApp.hideCollectionModal();
        }

        function saveCollection() {
            adminApp.saveCollection();
        }

        function loadConfigurations() {
            adminApp.loadConfigurations();
        }

        function uploadConfiguration() {
            adminApp.uploadConfiguration();
        }

        function loadSynonyms() {
            adminApp.loadSynonyms();
        }

        function uploadSynonyms() {
            adminApp.uploadSynonyms();
        }

        function loadClients() {
            adminApp.loadClients();
        }

        function loadCollections() {
            adminApp.loadCollections();
        }

        function hideCollectionDetailsModal() {
            adminApp.hideCollectionDetailsModal();
        }

        function hideConfirmationModal() {
            adminApp.hideConfirmationModal();
        }

        function confirmAction() {
            if (adminApp) {
                adminApp.confirmAction();
            }
        }

        function updateCollection() {
            adminApp.updateCollection();
        }

        // Initialize the admin app
        const adminApp = new AdminApp();

        // Close modals when clicking outside
        window.onclick = function(event) {
            const clientModal = document.getElementById('clientModal');
            const collectionModal = document.getElementById('collectionModal');
            const collectionDetailsModal = document.getElementById('collectionDetailsModal');
            const confirmationModal = document.getElementById('confirmationModal');

            if (event.target === clientModal) {
                adminApp.hideClientModal();
            }
            if (event.target === collectionModal) {
                adminApp.hideCollectionModal();
            }
            if (event.target === collectionDetailsModal) {
                adminApp.hideCollectionDetailsModal();
            }
            if (event.target === confirmationModal) {
                adminApp.hideConfirmationModal();
            }
        }
