// Global variables
let selectedGang = null;
let gangsData = [];
let isDebug = false;
let uiConfig = {
    title: "Gang Selection",
    subtitle: "Choose your allegiance",
    confirmMessage: "Are you sure you want to join",
    cardViewText: "Click to view details",
    viewButtonText: "View",
    joinButtonText: "Join Gang",
    backButtonText: "Go Back",
    cancelButtonText: "Cancel",
    confirmButtonText: "Confirm",
    selectGang: "Select a gang from the list",
    permanentChoice: "This decision is final and cannot be changed later",
    confirmSelection: "Confirm Selection",
    description: "Description",
    about: "About",
    available: "Available",
    chooseGang: "Choose a gang to represent"
};

// Debug function
function debugLog(message) {
    if (isDebug) {
        console.log("[NS-GANG-UI] " + message);
    }
}

// Language texts
let lang = {};

// Initialize event listeners when document is loaded
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
});

// Set up all event listeners
function initializeEventListeners() {
    // Close main UI - Make sure this works
    const closeBtn = document.getElementById('close-btn');
    if (closeBtn) {
        closeBtn.addEventListener('click', function() {
            console.log('Close button clicked');
            closeUI();
        });
    }
    
    // Details modal controls
    document.getElementById('close-detail-btn').addEventListener('click', closeDetailsModal);
    document.getElementById('back-btn').addEventListener('click', closeDetailsModal);
    document.getElementById('join-btn').addEventListener('click', openConfirmModal);
    
    // Confirmation modal controls
    document.getElementById('close-confirm-btn').addEventListener('click', closeConfirmModal);
    document.getElementById('cancel-btn').addEventListener('click', closeConfirmModal);
    document.getElementById('confirm-btn').addEventListener('click', confirmGangSelection);
    
    // Keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            if (document.getElementById('confirm-modal').classList.contains('active')) {
                closeConfirmModal();
            } else if (document.getElementById('details-modal').classList.contains('active')) {
                closeDetailsModal();
            } else {
                closeUI();
            }
        }
    });
    
    // Add global ESC key handler
    window.addEventListener('keyup', function(e) {
        if (e.key === 'Escape') {
            console.log('ESC key pressed');
            if (document.getElementById('confirm-modal').classList.contains('active')) {
                closeConfirmModal();
            } else if (document.getElementById('details-modal').classList.contains('active')) {
                closeDetailsModal();
            } else {
                closeUI();
            }
        }
    });
}

// Get gang logo path from gang data
function getGangLogo(gang) {
    if (gang.logo) {
        return gang.logo;
    }
    
    // Return a placeholder image if no logo is defined
    return 'https://i.imgur.com/KSvQ0XC.png'; // Default fallback
}

// Create all gang cards for the grid
function createGangCards() {
    const gangGrid = document.getElementById('gang-grid');
    gangGrid.innerHTML = ''; // Clear existing cards
    
    gangsData.forEach(gang => {
        const card = document.createElement('div');
        card.className = 'gang-card';
        card.dataset.value = gang.value;
        
        // Create card banner
        const banner = document.createElement('div');
        banner.className = 'card-banner';
        banner.style.backgroundColor = gang.color || '#3498db';
        
        // Create card content
        const content = document.createElement('div');
        content.className = 'card-content';
        
        // Create logo
        const logo = document.createElement('div');
        logo.className = 'card-logo';
        logo.style.backgroundImage = `url('${getGangLogo(gang)}')`;
        
        // Create name
        const name = document.createElement('h3');
        name.className = 'card-name';
        name.textContent = gang.label;
        
        // Create tag
        const tag = document.createElement('span');
        tag.className = 'card-tag';
        tag.textContent = gang.value.toUpperCase();
        
        // Create info section
        const info = document.createElement('div');
        info.className = 'card-info';
        
        const infoText = document.createElement('span');
        infoText.className = 'info-text';
        infoText.textContent = uiConfig.cardViewText || "Click to view details";
        
        const viewBtn = document.createElement('button');
        viewBtn.className = 'view-btn';
        viewBtn.style.setProperty('--gang-color', gang.color || '#3498db');
        viewBtn.innerHTML = `<i class="fas fa-eye"></i> ${uiConfig.viewButtonText || "View"}`;
        
        info.appendChild(infoText);
        info.appendChild(viewBtn);
        
        // Assemble card
        content.appendChild(logo);
        content.appendChild(name);
        content.appendChild(tag);
        content.appendChild(info);
        
        card.appendChild(banner);
        card.appendChild(content);
        
        // Add click event
        card.addEventListener('click', () => openDetailsModal(gang));
        
        gangGrid.appendChild(card);
    });
}

// Open details modal for a specific gang
function openDetailsModal(gang) {
    selectedGang = gang;
    
    // Update details in modal
    document.getElementById('detail-logo').style.backgroundImage = `url('${getGangLogo(gang)}')`;
    document.getElementById('detail-name').textContent = gang.label;
    document.getElementById('detail-tag').textContent = gang.value.toUpperCase();
    document.getElementById('detail-description').textContent = gang.description || "No description available for this gang.";
    
    // Update modal headings with language
    const descriptionHeader = document.querySelector('.description-box h3');
    if (descriptionHeader) {
        descriptionHeader.innerHTML = `<i class="fas fa-info-circle"></i> ${uiConfig.about || "About"}`;
    }
    
    // Style the join button with gang color
    const joinBtn = document.getElementById('join-btn');
    joinBtn.style.backgroundColor = gang.color || '#3498db';
    joinBtn.innerHTML = `<i class="fas fa-user-plus"></i> ${uiConfig.joinButtonText || "Join Gang"}`;
    
    // Update back button text
    document.getElementById('back-btn').innerHTML = `<i class="fas fa-arrow-left"></i> ${uiConfig.backButtonText || "Back"}`;
    
    // Show the modal
    document.getElementById('details-modal').classList.add('active');
    
    // Set the modal custom property for colors
    document.documentElement.style.setProperty('--gang-color', gang.color || '#3498db');
}

// Close the details modal
function closeDetailsModal() {
    document.getElementById('details-modal').classList.remove('active');
}

// Open confirmation modal
function openConfirmModal() {
    if (!selectedGang) return;
    
    const confirmMessage = document.getElementById('confirm-message');
    confirmMessage.textContent = `${uiConfig.confirmMessage || "Are you sure you want to join"} the ${selectedGang.label}?`;
    
    // Update warning text
    const warningText = document.querySelector('.warning span');
    if (warningText) {
        warningText.textContent = uiConfig.permanentChoice || "This decision is final and cannot be changed later.";
    }
    
    // Update header text
    const confirmHeader = document.querySelector('.confirm-header h3');
    if (confirmHeader) {
        confirmHeader.textContent = uiConfig.confirmSelection || "Confirm Selection";
    }
    
    // Update button texts
    document.getElementById('cancel-btn').textContent = uiConfig.cancelButtonText || "Cancel";
    document.getElementById('confirm-btn').textContent = uiConfig.confirmButtonText || "Confirm";
    
    document.getElementById('confirm-modal').classList.add('active');
}

// Close confirmation modal
function closeConfirmModal() {
    document.getElementById('confirm-modal').classList.remove('active');
}

// Confirm gang selection
function confirmGangSelection() {
    if (!selectedGang) return;
    
    closeConfirmModal();
    
    // Send selection to Lua
    fetch(`https://${GetParentResourceName()}/selectGang`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            gang: selectedGang.value
        })
    });
    
    closeUI();
}

// Close the entire UI
function closeUI() {
    const container = document.getElementById('gang-selection-container');
    container.classList.remove('active');
    
    // Immediately send the close message to Lua instead of delaying
    fetch(`https://${GetParentResourceName()}/close`, {
        method: 'POST'
    }).catch(error => console.error('Error closing UI:', error));
    
    // Hide the container completely after animation
    setTimeout(() => {
        container.style.display = 'none';
    }, 300);
}

// Update UI elements with translations
function updateUITexts() {
    // Update subtitle if exists
    const uiSubtitle = document.getElementById('ui-subtitle');
    if (uiSubtitle) {
        uiSubtitle.textContent = uiConfig.chooseGang || uiConfig.subtitle || "Choose a gang to represent";
    }
}

// Update UI with translation texts
function updateUIWithTranslations() {
    debugLog("Updating UI with translations");
    
    // Update the main title
    const titleElement = document.getElementById('ui-title');
    if (titleElement) {
        titleElement.textContent = uiConfig.title || "Gang Selection";
        debugLog("Set title to: " + titleElement.textContent);
    }
    
    // IMPORTANT: Update subtitle with the correct key
    const subtitleElement = document.getElementById('ui-subtitle');
    if (subtitleElement) {
        subtitleElement.textContent = uiConfig.chooseGang || "Choose a gang to represent";
        debugLog("Set subtitle to: " + subtitleElement.textContent);
    }
    
    // Update other UI elements as needed
    const placeholderMessage = document.querySelector('.placeholder-message p');
    if (placeholderMessage) {
        placeholderMessage.textContent = uiConfig.selectGang || "Select a gang from the list";
    }
}

// Open the UI with data
function openUI(data) {
    debugLog("Opening UI");
    
    // Save gangs data
    gangsData = data.gangs || [];
    
    // Get debug setting from server
    isDebug = data.debug === true;
    
    // Update UI config with language settings
    if (data.uiConfig) {
        debugLog("Received UI config: " + JSON.stringify(data.uiConfig));
        uiConfig = {...uiConfig, ...data.uiConfig};
        
        // Debug the translations we received
        if (data.uiConfig.chooseGang) {
            debugLog("Received chooseGang translation: " + data.uiConfig.chooseGang);
        } else {
            debugLog("Warning: chooseGang translation missing");
        }
    }
    
    // Debug the language code
    if (data.language && isDebug) {
        console.log("Using language: " + data.language);
    }
    
    // Set main logo if available
    if (uiConfig.mainLogo) {
        const mainLogo = document.getElementById('main-logo');
        if (mainLogo) {
            mainLogo.style.backgroundImage = `url('${uiConfig.mainLogo}')`;
        }
    }
    
    // Update UI with translations
    updateUIWithTranslations();
    
    // Create gang cards
    createGangCards();
    
    // Reset selection
    selectedGang = null;
    
    // FORCE UPDATE the subtitle text - only log if in debug mode
    const subtitleContainer = document.querySelector('.panel-subtitle');
    if (subtitleContainer && uiConfig && uiConfig.chooseGang) {
        // Replace the entire element to ensure it updates
        subtitleContainer.innerHTML = `<p id="ui-subtitle">${uiConfig.chooseGang}</p>`;
        if (isDebug) {
            console.log("Force updated subtitle to:", uiConfig.chooseGang);
        }
    }
    
    // Show the UI
    const container = document.getElementById('gang-selection-container');
    container.style.display = 'block';
    setTimeout(() => {
        container.classList.add('active');
    }, 10);
}

// Listen for messages from Lua
window.addEventListener('message', function(event) {
    const data = event.data;
    
    if (data.action === 'open') {
        // Update debug setting from the message
        isDebug = data.debug === true;
        
        debugLog("Received open message from Lua");
        openUI(data);
    }
});

// Initialize on load
window.onload = function() {
    // Wait to see if debug is enabled before logging
    if (isDebug) {
        console.log("[NS-GANG-UI] UI script initialized");
    }
    
    // Initialize event listeners
    initializeEventListeners();
};
