// temp-candidate.js - Add temporary candidates/aliases that only exist for the current poll

// Track temporary candidates and aliases
const tempCandidates = new Set();
const tempAliases = new Map(); // alias -> candidateName (for cleanup)

// Modal element reference
let tempCandidateModal = null;

// Initialize temp candidate UI
function initTempCandidateUI() {
    const widgetContainer2 = document.getElementById('widgetContainer2');
    if (!widgetContainer2) return;

    // Get or create the shared toolbar row
    let toolbarRow = document.getElementById('chartToolbar');
    if (!toolbarRow) {
        toolbarRow = document.createElement('div');
        toolbarRow.id = 'chartToolbar';
        toolbarRow.className = 'd-flex flex-wrap justify-content-center align-items-center gap-0 mb-1 py-1 px-2 border rounded bg-body-tertiary';
        widgetContainer2.appendChild(toolbarRow);
    }

    const tempCandidateDiv = document.createElement('div');
    tempCandidateDiv.className = 'temp-candidate-controls d-flex align-items-center ms-1';
    tempCandidateDiv.innerHTML = `
        <button class="btn btn-sm btn-outline-success" id="addTempCandidate" title="Add temporary candidate or alias">
            <i class="fas fa-plus"></i>
        </button>
        <span id="tempCandidateCount" class="text-muted small"></span>
    `;

    // Insert into toolbar
    toolbarRow.appendChild(tempCandidateDiv);

    // Create the modal
    createTempCandidateModal();

    setupTempCandidateListeners();
    updateTempCandidateCount();
}

// Create the modal for adding temp candidates
function createTempCandidateModal() {
    // Don't create if already exists
    if (document.getElementById('tempCandidateModal')) return;

    const modal = document.createElement('div');
    modal.className = 'modal fade';
    modal.id = 'tempCandidateModal';
    modal.tabIndex = -1;
    modal.setAttribute('aria-labelledby', 'tempCandidateModalLabel');
    modal.setAttribute('aria-hidden', 'true');
    modal.innerHTML = `
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="tempCandidateModalLabel">Add Temporary Candidate / Alias</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="text-muted small mb-2">
                        <strong>New candidate:</strong> <code>Robert, Rob, Bob</code><br>
                        <strong>Add alias to existing:</strong> <code>pon, pwn</code>
                    </p>
                    <input type="text" class="form-control" id="tempCandidateInput"
                           placeholder="Name, alias1, alias2, ..." autocomplete="off">
                    <div id="tempCandidateError" class="text-danger small mt-2 d-none"></div>
                    <div id="tempCandidateInfo" class="text-info small mt-2 d-none"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success" id="confirmTempCandidate">Add</button>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(modal);

    // Set up modal event listeners
    const input = document.getElementById('tempCandidateInput');
    const confirmBtn = document.getElementById('confirmTempCandidate');
    const errorDiv = document.getElementById('tempCandidateError');
    const infoDiv = document.getElementById('tempCandidateInfo');

    // Handle Enter key in input
    input.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            confirmBtn.click();
        }
    });

    // Handle confirm button
    confirmBtn.addEventListener('click', function() {
        const result = processTempCandidateInput(input.value);
        if (result.error) {
            errorDiv.textContent = result.error;
            errorDiv.classList.remove('d-none');
            infoDiv.classList.add('d-none');
        } else {
            // Success - close modal
            errorDiv.classList.add('d-none');
            infoDiv.classList.add('d-none');
            input.value = '';
            bootstrap.Modal.getInstance(document.getElementById('tempCandidateModal')).hide();

            if (result.existingCandidate) {
                // Add aliases to existing candidate
                addTempAliases(result.existingCandidate, result.aliases);
            } else {
                // Create new temp candidate
                addTempCandidate(result.name, result.aliases);
            }
        }
    });

    // Clear input and error when modal is shown
    modal.addEventListener('show.bs.modal', function() {
        input.value = '';
        errorDiv.classList.add('d-none');
        infoDiv.classList.add('d-none');
    });

    // Focus input when modal is shown
    modal.addEventListener('shown.bs.modal', function() {
        input.focus();
    });

    tempCandidateModal = new bootstrap.Modal(modal);
}

// Process the input string and validate
function processTempCandidateInput(input) {
    if (!input || !input.trim()) {
        return { error: 'Please enter a candidate name.' };
    }

    // Split by comma
    const parts = input.split(',').map(s => s.trim()).filter(s => s);

    if (parts.length === 0) {
        return { error: 'Please enter a candidate name.' };
    }

    const firstItem = parts[0];
    const otherItems = parts.slice(1);

    // Check if first item matches an existing candidate or alias
    const existingCandidate = translate.get(firstItem.toLowerCase());

    if (existingCandidate) {
        // First item is an existing candidate/alias - add the rest as new aliases
        if (otherItems.length === 0) {
            return { error: `"${firstItem}" already exists. Add aliases after it: "${firstItem}, new-alias"` };
        }

        // Check if any of the new aliases already exist
        for (const alias of otherItems) {
            if (translate.has(alias.toLowerCase())) {
                const existingTarget = translate.get(alias.toLowerCase());
                return { error: `"${alias}" already exists as an alias for "${existingTarget}".` };
            }
        }

        return { existingCandidate, aliases: otherItems };
    }

    // First item is a new candidate
    if (tempCandidates.has(firstItem)) {
        // It's a temp candidate - allow adding aliases to it
        if (otherItems.length === 0) {
            return { error: `"${firstItem}" is already a temporary candidate. Add aliases after it.` };
        }

        // Check for conflicts
        for (const alias of otherItems) {
            if (translate.has(alias.toLowerCase())) {
                return { error: `"${alias}" already exists in the registry.` };
            }
        }

        return { existingCandidate: firstItem, aliases: otherItems };
    }

    // Creating a new candidate - check aliases for conflicts
    for (const alias of otherItems) {
        if (translate.has(alias.toLowerCase())) {
            return { error: `"${alias}" already exists in the registry.` };
        }
    }

    return { name: firstItem, aliases: otherItems };
}

// Set up event listeners
function setupTempCandidateListeners() {
    const addBtn = document.getElementById('addTempCandidate');
    if (addBtn) {
        addBtn.addEventListener('click', showTempCandidateModal);
    }
}

// Show the modal
function showTempCandidateModal() {
    if (tempCandidateModal) {
        tempCandidateModal.show();
    }
}

// Add temporary aliases to an existing candidate
function addTempAliases(candidateName, aliases) {
    aliases.forEach(alias => {
        translate.set(alias.toLowerCase(), candidateName);
        tempAliases.set(alias.toLowerCase(), candidateName);
    });

    // Log to console
    if (typeof window.logToConsole === 'function') {
        window.logToConsole(`Added temp aliases to "${candidateName}": ${aliases.join(', ')}`);
    }
}

// Add a temporary candidate
function addTempCandidate(name, aliases = []) {
    // Track as temp candidate
    tempCandidates.add(name);

    // Add to translate map (the main name and all aliases point to the candidate name)
    translate.set(name.toLowerCase(), name);
    aliases.forEach(alias => {
        translate.set(alias.toLowerCase(), name);
        tempAliases.set(alias.toLowerCase(), name);
    });

    // Check if source tracking is enabled
    const useSourceTracking = (typeof window !== 'undefined' &&
        typeof window.sourceTracking !== 'undefined' &&
        window.sourceTracking.isEnabled());

    // Add to stats with zero votes
    if (useSourceTracking) {
        stats.set(name, {
            total: 0,
            youtube: 0,
            twitch: 0,
            unknown: 0
        });
    } else {
        stats.set(name, 0);
    }

    // Refresh chart
    if (typeof VoteChart !== 'undefined') {
        VoteChart.setData(stats);
        VoteChart.render();
    }

    updateTempCandidateCount();

    // Log to console
    const aliasText = aliases.length > 0 ? ` (aliases: ${aliases.join(', ')})` : '';
    if (typeof window.logToConsole === 'function') {
        window.logToConsole(`Added temp candidate: ${name}${aliasText}`);
    }
}

// Remove all temp candidates and aliases (called when poll closes/resets)
function clearTempCandidates() {
    // Remove temp candidates
    tempCandidates.forEach(name => {
        // Remove from translate (the candidate name itself)
        translate.delete(name.toLowerCase());
        // Remove from stats
        stats.delete(name);
    });

    // Remove temp aliases (including aliases of temp candidates AND aliases added to existing candidates)
    tempAliases.forEach((candidateName, alias) => {
        translate.delete(alias);
    });

    tempCandidates.clear();
    tempAliases.clear();
    updateTempCandidateCount();
}

// Update the count display
function updateTempCandidateCount() {
    const countSpan = document.getElementById('tempCandidateCount');
    if (countSpan) {
        const tempCount = tempCandidates.size;
        const aliasCount = tempAliases.size;

        if (tempCount > 0 || aliasCount > 0) {
            const parts = [];
            if (tempCount > 0) {
                parts.push(`${tempCount} candidate${tempCount > 1 ? 's' : ''}`);
            }
            if (aliasCount > 0) {
                parts.push(`${aliasCount} alias${aliasCount > 1 ? 'es' : ''}`);
            }
            countSpan.textContent = `Temp: ${parts.join(', ')}`;

            // Build detailed tooltip
            const tooltipParts = [];
            if (tempCandidates.size > 0) {
                tooltipParts.push(`Candidates: ${Array.from(tempCandidates).join(', ')}`);
            }
            if (tempAliases.size > 0) {
                const aliasDetails = Array.from(tempAliases.entries())
                    .map(([alias, candidate]) => `${alias} → ${candidate}`)
                    .join(', ');
                tooltipParts.push(`Aliases: ${aliasDetails}`);
            }
            countSpan.title = tooltipParts.join('\n');
        } else {
            countSpan.textContent = '';
            countSpan.title = '';
        }
    }
}

// Check if a candidate is temporary
function isTempCandidate(name) {
    return tempCandidates.has(name);
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', function () {
    setTimeout(() => {
        initTempCandidateUI();
    }, 105); // First in toolbar - before combo mode (120ms) and vote filters (150ms)
});

// Export for external use
window.tempCandidate = {
    add: addTempCandidate,
    addAliases: addTempAliases,
    clear: clearTempCandidates,
    isTemp: isTempCandidate,
    getAll: () => Array.from(tempCandidates),
    getAllAliases: () => new Map(tempAliases),
    showModal: showTempCandidateModal
};
