// vote-filters-ui.js - UI controls for vote filtering options

// Initialize vote filter UI
function initVoteFiltersUI() {
    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 filtersDiv = document.createElement('div');
    filtersDiv.className = 'vote-filters-controls d-flex align-items-center ms-1';
    filtersDiv.innerHTML = `
        <button class="btn btn-sm btn-outline-secondary filter-toggle-btn active-glow" id="strictVoteBtn" title="Strict voting (exact matches only)">
            <i class="fas fa-bullseye"></i>
        </button>
        <button class="btn btn-sm btn-outline-secondary filter-toggle-btn live-tooltip" id="oneVoteFilterBtn" data-tooltip="One vote per user: LOCK (first vote only)">
            <i class="fas fa-lock"></i>
        </button>
    `;

    toolbarRow.appendChild(filtersDiv);

    // Add CSS for glow effect
    addGlowStyles();

    setupFilterListeners();
    loadFilterSettings();

    // Ensure one-vote button shows correct initial state (if no saved settings)
    const oneVoteBtn = document.getElementById('oneVoteFilterBtn');
    if (oneVoteBtn && typeof oneVotePerUserConfig !== 'undefined') {
        updateOneVoteButtonAppearance(oneVoteBtn, oneVotePerUserConfig.mode);
    }
}

// Add CSS for the glow effect on active buttons
function addGlowStyles() {
    if (document.getElementById('filter-glow-styles')) return;

    const style = document.createElement('style');
    style.id = 'filter-glow-styles';
    style.textContent = `
        .filter-toggle-btn.active-glow {
            background-color: #0d6efd;
            border-color: #0d6efd;
            color: white;
            box-shadow: 0 0 8px rgba(13, 110, 253, 0.6);
        }
        .filter-toggle-btn:not(.active-glow) {
            background-color: transparent;
            color: #6c757d;
        }
        .source-split-btn.active-glow {
            background-color: #6f42c1;
            border-color: #6f42c1;
            color: white;
            box-shadow: 0 0 8px rgba(111, 66, 193, 0.6);
        }
        .source-split-btn:not(.active-glow) {
            background-color: transparent;
            color: #6c757d;
        }
        .combo-toggle-btn.active-glow {
            background-color: #0dcaf0;
            border-color: #0dcaf0;
            color: black;
            box-shadow: 0 0 8px rgba(13, 202, 240, 0.6);
        }
        .combo-toggle-btn:not(.active-glow) {
            background-color: transparent;
            color: #6c757d;
        }
        .filter-toggle-btn.one-vote-lock.active-glow {
            background-color: #0d6efd;
            border-color: #0d6efd;
            color: white;
            box-shadow: 0 0 8px rgba(13, 110, 253, 0.6);
        }
        .filter-toggle-btn.one-vote-change.active-glow {
            background-color: #198754;
            border-color: #198754;
            color: white;
            box-shadow: 0 0 8px rgba(25, 135, 84, 0.6);
        }
        .live-tooltip {
            position: relative;
        }
        .live-tooltip[data-tooltip]:hover::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: calc(100% + 6px);
            left: 50%;
            transform: translateX(-50%);
            background: rgba(33, 37, 41, 0.95);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            white-space: nowrap;
            z-index: 1060;
            pointer-events: none;
        }
    `;
    document.head.appendChild(style);
}

// One vote mode states: off -> lock -> change -> off
const oneVoteModes = ['off', 'lock', 'change'];

// Get the next mode in the cycle
function getNextOneVoteMode(currentMode) {
    const currentIndex = oneVoteModes.indexOf(currentMode);
    const nextIndex = (currentIndex + 1) % oneVoteModes.length;
    return oneVoteModes[nextIndex];
}

// Update the one-vote button appearance based on current mode
function updateOneVoteButtonAppearance(btn, mode) {
    if (!btn) return;

    // Remove all mode classes first
    btn.classList.remove('active-glow', 'one-vote-lock', 'one-vote-change');

    const icon = btn.querySelector('i');

    btn.removeAttribute('title');

    switch (mode) {
        case 'off':
            btn.setAttribute('data-tooltip', 'One vote per user: OFF (unlimited voting)');
            if (icon) icon.className = 'fas fa-user';
            break;
        case 'lock':
            btn.classList.add('active-glow', 'one-vote-lock');
            btn.setAttribute('data-tooltip', 'One vote per user: LOCK (first vote only)');
            if (icon) icon.className = 'fas fa-lock';
            break;
        case 'change':
            btn.classList.add('active-glow', 'one-vote-change');
            btn.setAttribute('data-tooltip', 'One vote per user: CHANGE (can change vote)');
            if (icon) icon.className = 'fas fa-sync-alt';
            break;
    }
}

// Set up event listeners for filter toggles
function setupFilterListeners() {
    const strictVoteBtn = document.getElementById('strictVoteBtn');
    const oneVoteBtn = document.getElementById('oneVoteFilterBtn');

    if (strictVoteBtn) {
        strictVoteBtn.addEventListener('click', function() {
            if (typeof strictVotingConfig !== 'undefined') {
                strictVotingConfig.enabled = !strictVotingConfig.enabled;
                this.classList.toggle('active-glow', strictVotingConfig.enabled);
                saveFilterSettings();

                if (typeof window.logToConsole === 'function') {
                    window.logToConsole(`Strict voting: ${strictVotingConfig.enabled ? 'ON' : 'OFF'}`);
                }
            }
        });
    }

    if (oneVoteBtn) {
        oneVoteBtn.addEventListener('click', function() {
            // Check if poll is currently open - show error popup if so
            if (typeof isOpen !== 'undefined' && isOpen) {
                if (typeof showInputError === 'function') {
                    showInputError(this, 'Cannot change while poll is open');
                }
                return;
            }

            if (typeof oneVotePerUserConfig !== 'undefined') {
                // Cycle to the next mode
                const nextMode = getNextOneVoteMode(oneVotePerUserConfig.mode);
                oneVotePerUserConfig.mode = nextMode;
                updateOneVoteButtonAppearance(this, nextMode);
                saveFilterSettings();

                const modeDescriptions = {
                    'off': 'OFF (unlimited)',
                    'lock': 'LOCK (first vote only)',
                    'change': 'CHANGE (can update vote)'
                };

                if (typeof window.logToConsole === 'function') {
                    window.logToConsole(`One vote per user: ${modeDescriptions[nextMode]}`);
                }
            }
        });
    }
}

// Save filter settings to localStorage
function saveFilterSettings() {
    try {
        const settings = {
            strictVotingEnabled: typeof strictVotingConfig !== 'undefined' ? strictVotingConfig.enabled : true,
            oneVoteMode: typeof oneVotePerUserConfig !== 'undefined' ? oneVotePerUserConfig.mode : 'lock'
        };
        localStorage.setItem('voteFilterSettings', JSON.stringify(settings));
    } catch (e) {
        // Ignore localStorage errors
    }
}

// Load filter settings from localStorage
function loadFilterSettings() {
    try {
        const saved = localStorage.getItem('voteFilterSettings');
        if (saved) {
            const settings = JSON.parse(saved);

            // Apply strict voting setting (also check legacy wordCountEnabled for migration)
            const strictEnabled = settings.strictVotingEnabled !== undefined
                ? settings.strictVotingEnabled
                : (settings.wordCountEnabled !== false);
            if (typeof strictVotingConfig !== 'undefined') {
                strictVotingConfig.enabled = strictEnabled;
            }
            const strictVoteBtn = document.getElementById('strictVoteBtn');
            if (strictVoteBtn) {
                strictVoteBtn.classList.toggle('active-glow', strictEnabled);
            }

            // Apply one vote per user mode setting
            // Handle legacy boolean format (oneVoteEnabled) and new mode format
            let mode = 'lock'; // Default
            if (settings.oneVoteMode) {
                mode = settings.oneVoteMode;
            } else if (settings.oneVoteEnabled === false) {
                mode = 'off';
            }

            if (typeof oneVotePerUserConfig !== 'undefined') {
                oneVotePerUserConfig.mode = mode;
            }
            const oneVoteBtn = document.getElementById('oneVoteFilterBtn');
            updateOneVoteButtonAppearance(oneVoteBtn, mode);
        }
    } catch (e) {
        // Ignore localStorage errors
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
        initVoteFiltersUI();
    }, 150); // Last in toolbar - after temp-candidate (105ms) and combo mode (120ms)
});

// Export for external use
window.voteFiltersUI = {
    isStrictVotingEnabled: () => typeof strictVotingConfig !== 'undefined' ? strictVotingConfig.enabled : true,
    getOneVoteMode: () => typeof oneVotePerUserConfig !== 'undefined' ? oneVotePerUserConfig.mode : 'lock',
    setStrictVotingEnabled: (enabled) => {
        if (typeof strictVotingConfig !== 'undefined') {
            strictVotingConfig.enabled = enabled;
            const btn = document.getElementById('strictVoteBtn');
            if (btn) btn.classList.toggle('active-glow', enabled);
            saveFilterSettings();
        }
    },
    setOneVoteMode: (mode) => {
        if (typeof oneVotePerUserConfig !== 'undefined' && oneVoteModes.includes(mode)) {
            oneVotePerUserConfig.mode = mode;
            const btn = document.getElementById('oneVoteFilterBtn');
            updateOneVoteButtonAppearance(btn, mode);
            saveFilterSettings();
        }
    }
};
