// auto-close.js - Automatic poll closing functionality

let autoCloseEnabled = false;
let autoCloseDuration = 60000; // Default: 60 seconds
let autoCloseTimer = null;
let countdownInterval = null;
let remainingTime = 0;

// Initialize auto-close functionality
function initAutoClose() {
    // Create the UI elements
    createAutoCloseUI();

    // Load saved settings
    loadAutoCloseSettings();

    // Hook into the existing poll toggle system
    hookIntoPollSystem();
}

// Create the UI elements for auto-close
function createAutoCloseUI() {
    const widgetContainer = document.getElementById('widgetContainer') || document.getElementById('penis');

    if (widgetContainer) {
        const autoCloseDiv = document.createElement('div');
        autoCloseDiv.className = 'auto-close-container mb-3 p-2 border rounded bg-body-tertiary';
        autoCloseDiv.innerHTML = `
            <!-- Single row: checkbox, duration, quick select -->
            <div class="d-flex flex-wrap align-items-center gap-2">
                <div class="form-check mb-0">
                    <input class="form-check-input" type="checkbox" id="autoCloseEnabled">
                    <label class="form-check-label" for="autoCloseEnabled">
                        <i class="fas fa-clock"></i> Auto-Close
                    </label>
                </div>
                <div class="d-flex align-items-center gap-1">
                    <input type="number" class="form-control form-control-sm" id="autoCloseDuration"
                           value="60000" min="1000" step="1000" style="width: 90px;" title="Duration (ms)">
                    <div class="btn-group btn-group-sm" role="group">
                        <button type="button" class="btn btn-outline-secondary" data-duration="10000">10s</button>
                        <button type="button" class="btn btn-outline-secondary" data-duration="30000">30s</button>
                        <button type="button" class="btn btn-outline-secondary" data-duration="60000">1m</button>
                        <button type="button" class="btn btn-outline-secondary" data-duration="180000">3m</button>
                    </div>
                </div>
                <button type="button" class="btn btn-sm btn-outline-danger" id="cancelAutoClose" style="display: none;">
                    <i class="fas fa-times"></i> Cancel
                </button>
            </div>
            <!-- Countdown bar (hidden until timer starts) -->
            <div id="countdownDisplay" class="mt-2" style="display: none;">
                <div class="d-flex align-items-center gap-2">
                    <span id="countdownContent" class="small text-muted"></span>
                </div>
                <div id="countdownProgressContainer" class="progress mt-1" style="height: 6px;">
                    <div id="countdownProgress" class="progress-bar bg-success" role="progressbar" style="width: 100%"></div>
                </div>
            </div>
        `;

        widgetContainer.appendChild(autoCloseDiv);

        // Add event listeners
        setupAutoCloseEventListeners();
    }
}

// Set up event listeners for auto-close functionality
function setupAutoCloseEventListeners() {
    // Enable/disable checkbox
    const enabledCheckbox = document.getElementById('autoCloseEnabled');
    if (enabledCheckbox) {
        enabledCheckbox.addEventListener('change', function () {
            autoCloseEnabled = this.checked;
            saveAutoCloseSettings();

            // If poll is currently open and auto-close was just enabled, start timer
            if (autoCloseEnabled && typeof isOpen !== 'undefined' && isOpen) {
                startAutoCloseTimer();
            } else if (!autoCloseEnabled) {
                stopAutoCloseTimer();
                // Reset button text to normal when auto-close is disabled
                updateNormalButtonStates();
            } else {
                // Update the status message when auto-close is enabled but poll is closed
                hideCountdownContent();
            }
        });
    }

    // Duration input
    const durationInput = document.getElementById('autoCloseDuration');
    if (durationInput) {
        durationInput.addEventListener('change', function () {
            const newDuration = parseInt(this.value);
            if (newDuration >= 1000) {
                autoCloseDuration = newDuration;
                saveAutoCloseSettings();

                // If timer is currently running, restart it with new duration
                if (autoCloseTimer && typeof isOpen !== 'undefined' && isOpen) {
                    stopAutoCloseTimer();
                    startAutoCloseTimer();
                }
            }
        });
    }

    // Quick select buttons
    document.querySelectorAll('[data-duration]').forEach(button => {
        button.addEventListener('click', function () {
            const duration = parseInt(this.getAttribute('data-duration'));
            autoCloseDuration = duration;

            // Update the input field
            const durationInput = document.getElementById('autoCloseDuration');
            if (durationInput) {
                durationInput.value = duration;
            }

            saveAutoCloseSettings();

            // If timer is running, restart with new duration
            if (autoCloseTimer && typeof isOpen !== 'undefined' && isOpen) {
                stopAutoCloseTimer();
                startAutoCloseTimer();
            }
        });
    });

    // Cancel auto-close button
    const cancelButton = document.getElementById('cancelAutoClose');
    if (cancelButton) {
        cancelButton.addEventListener('click', function () {
            stopAutoCloseTimer();
        });
    }
}

// Start the auto-close timer
function startAutoCloseTimer() {
    if (!autoCloseEnabled) return;

    // Clear any existing timer
    stopAutoCloseTimer();

    remainingTime = autoCloseDuration;
    const startTime = Date.now();
    const endTime = startTime + autoCloseDuration;

    // Set progress bar to 100% BEFORE showing it
    const countdownProgress = document.getElementById('countdownProgress');
    if (countdownProgress) {
        countdownProgress.style.width = '100%';
        countdownProgress.className = 'progress-bar bg-success';
    }

    // Show countdown content
    showCountdownContent();

    // Update countdown every 100ms for smooth progress bar
    countdownInterval = setInterval(() => {
        const now = Date.now();
        remainingTime = Math.max(0, endTime - now);

        updateCountdownDisplay();

        if (remainingTime <= 0) {
            // Time's up! Close the poll
            stopAutoCloseTimer();
            closePollAutomatically();
        }
    }, 100);

    // Set the main timer to close the poll
    autoCloseTimer = setTimeout(() => {
        closePollAutomatically();
    }, autoCloseDuration);

    // Do initial update after a small delay to ensure smooth start
    setTimeout(() => {
        updateCountdownDisplay();
    }, 50);
}

// Show countdown content
function showCountdownContent() {
    const countdownDisplay = document.getElementById('countdownDisplay');
    const countdownContent = document.getElementById('countdownContent');
    const cancelButton = document.getElementById('cancelAutoClose');

    if (countdownDisplay) {
        countdownDisplay.style.display = 'block';
    }

    if (countdownContent) {
        countdownContent.innerHTML = `<i class="fas fa-hourglass-half"></i> Closes in: <strong><span id="countdownTime">--:--</span></strong>`;
    }

    if (cancelButton) {
        cancelButton.style.display = 'inline-block';
    }
}

// Hide countdown content
function hideCountdownContent() {
    const countdownDisplay = document.getElementById('countdownDisplay');
    const countdownProgress = document.getElementById('countdownProgress');
    const cancelButton = document.getElementById('cancelAutoClose');

    if (countdownDisplay) {
        countdownDisplay.style.display = 'none';
    }

    // Reset progress bar to full
    if (countdownProgress) {
        countdownProgress.style.width = '100%';
        countdownProgress.className = 'progress-bar bg-success';
    }

    if (cancelButton) {
        cancelButton.style.display = 'none';
    }
}

// Stop the auto-close timer
function stopAutoCloseTimer() {
    if (autoCloseTimer) {
        clearTimeout(autoCloseTimer);
        autoCloseTimer = null;
    }

    if (countdownInterval) {
        clearInterval(countdownInterval);
        countdownInterval = null;
    }

    // Hide countdown content (but keep container visible)
    hideCountdownContent();

    // Reset button text to normal (remove countdown)
    updateNormalButtonStates();
}

// Update the countdown display
function updateCountdownDisplay() {
    const countdownTime = document.getElementById('countdownTime');
    const countdownProgress = document.getElementById('countdownProgress');

    // Format time as MM:SS (rounded up to nearest second)
    const totalSeconds = Math.ceil(remainingTime / 1000);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

    if (countdownTime) {
        countdownTime.textContent = timeString;
    }

    if (countdownProgress) {
        // Update progress bar
        const percentage = (remainingTime / autoCloseDuration) * 100;
        countdownProgress.style.width = `${percentage}%`;

        // Change color as time runs out
        if (percentage > 50) {
            countdownProgress.className = 'progress-bar bg-success';
        } else if (percentage > 25) {
            countdownProgress.className = 'progress-bar bg-warning';
        } else {
            countdownProgress.className = 'progress-bar bg-danger';
        }
    }

    // Update poll button text with countdown
    updatePollButtonsWithCountdown(timeString);
}

// Update poll button text to include countdown
function updatePollButtonsWithCountdown(timeString) {
    const toggleButton = document.getElementById('toggleButton');
    const toggleButton2 = document.getElementById('toggleButton2');

    if (typeof isOpen !== 'undefined' && isOpen && autoCloseEnabled && autoCloseTimer) {
        // Poll is open and auto-close is active - show countdown in buttons
        const buttonText = `OPEN (${timeString})`;

        if (toggleButton) {
            toggleButton.textContent = buttonText;
        }
        if (toggleButton2) {
            toggleButton2.textContent = buttonText;
        }
    } else {
        // Normal button state - no countdown
        updateNormalButtonStates();
    }
}

// Update buttons to normal state (without countdown)
function updateNormalButtonStates() {
    const toggleButton = document.getElementById('toggleButton');
    const toggleButton2 = document.getElementById('toggleButton2');

    if (typeof isOpen !== 'undefined') {
        const text = isOpen ? 'OPEN' : 'CLOSED';
        const className = isOpen ? 'button' : 'button off';

        if (toggleButton) {
            toggleButton.textContent = text;
            toggleButton.className = className;
        }
        if (toggleButton2) {
            toggleButton2.textContent = text;
            toggleButton2.className = className;
        }
    }
}

// Close the poll automatically
function closePollAutomatically() {
    if (typeof isOpen !== 'undefined' && isOpen) {
        // Use the existing toggle function if available
        if (typeof togglePoll === 'function') {
            togglePoll();
        } else {
            // Fallback: directly manipulate the global state
            isOpen = false;

            // Update toggle buttons to normal closed state
            updateNormalButtonStates();
        }

        // Log the auto-close event
        const outputContainer = document.getElementById('outputContainer');
        if (outputContainer && typeof logToPage === 'function') {
            logToPage(outputContainer, '🔒 Poll automatically closed by timer');
        }
    }

    stopAutoCloseTimer();
}

// Hook into the existing poll system
function hookIntoPollSystem() {
    // Store original toggle function if it exists
    let originalTogglePoll = null;

    // Wait for the toggle system to load, then hook into it
    setTimeout(() => {
        // Override the global togglePoll function if it exists
        if (typeof window.togglePoll === 'function') {
            originalTogglePoll = window.togglePoll;
            window.togglePoll = function () {
                const wasOpen = typeof isOpen !== 'undefined' ? isOpen : false;

                // Call original toggle function
                originalTogglePoll();

                // Handle auto-close logic
                const isNowOpen = typeof isOpen !== 'undefined' ? isOpen : false;

                if (!wasOpen && isNowOpen && autoCloseEnabled) {
                    // Poll was just opened, start auto-close timer
                    startAutoCloseTimer();
                } else if (wasOpen && !isNowOpen) {
                    // Poll was just closed, stop auto-close timer
                    stopAutoCloseTimer();
                }
            };
        }

        // Also hook into direct button clicks as fallback
        const toggleButton = document.getElementById('toggleButton');
        const toggleButton2 = document.getElementById('toggleButton2');

        function addAutoCloseHook(button) {
            if (button && !button.hasAutoCloseHook) {
                button.hasAutoCloseHook = true;

                button.addEventListener('click', function () {
                    setTimeout(() => {
                        if (typeof isOpen !== 'undefined') {
                            if (isOpen && autoCloseEnabled) {
                                startAutoCloseTimer();
                            } else {
                                stopAutoCloseTimer();
                            }
                        }
                    }, 50); // Small delay to let the toggle complete
                });
            }
        }

        addAutoCloseHook(toggleButton);
        addAutoCloseHook(toggleButton2);

    }, 200); // Wait for other scripts to load
}

// Save auto-close settings to localStorage
function saveAutoCloseSettings() {
    const settings = {
        enabled: autoCloseEnabled,
        duration: autoCloseDuration
    };
    localStorage.setItem('autoCloseSettings', JSON.stringify(settings));
}

// Load auto-close settings from localStorage
function loadAutoCloseSettings() {
    const saved = localStorage.getItem('autoCloseSettings');
    if (saved) {
        try {
            const settings = JSON.parse(saved);
            autoCloseEnabled = settings.enabled || false;
            autoCloseDuration = settings.duration || 10000;

            // Update UI elements
            const enabledCheckbox = document.getElementById('autoCloseEnabled');
            const durationInput = document.getElementById('autoCloseDuration');

            if (enabledCheckbox) {
                enabledCheckbox.checked = autoCloseEnabled;
            }
            if (durationInput) {
                durationInput.value = autoCloseDuration;
            }

            // Update countdown content based on current state
            hideCountdownContent();
        } catch (e) {
            console.error('Failed to load auto-close settings:', e);
        }
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', function () {
    initAutoClose();
});

// Export functions for external use
window.autoClose = {
    isEnabled: () => autoCloseEnabled,
    getDuration: () => autoCloseDuration,
    getRemainingTime: () => remainingTime,
    enable: () => {
        autoCloseEnabled = true;
        document.getElementById('autoCloseEnabled').checked = true;
        saveAutoCloseSettings();
    },
    disable: () => {
        autoCloseEnabled = false;
        document.getElementById('autoCloseEnabled').checked = false;
        stopAutoCloseTimer();
        saveAutoCloseSettings();
    },
    setDuration: (duration) => {
        autoCloseDuration = duration;
        document.getElementById('autoCloseDuration').value = duration;
        saveAutoCloseSettings();
    },
    start: startAutoCloseTimer,
    stop: stopAutoCloseTimer
};