/**
 * Random Group Generator - Main Generator Logic
 */

// Global state
let currentMode = 'group';
let currentInputMethod = 'manual';
let lastGeneratedResult = null;

// DOM Elements
const namesInput = document.getElementById('namesInput');
const namesCount = document.getElementById('namesCount');
const groupCountInput = document.getElementById('groupCount');
const peoplePerGroupInput = document.getElementById('peoplePerGroup');
const randomLeaderCheckbox = document.getElementById('randomLeader');
const animationToggle = document.getElementById('animationToggle');
const generateBtn = document.getElementById('generateBtn');
const resultsSection = document.getElementById('resultsSection');
const groupsContainer = document.getElementById('groupsContainer');
const generateAgainBtn = document.getElementById('generateAgain');

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
    updateStats();
});

// Event Listeners
function initializeEventListeners() {
    // Input methods
    document.querySelectorAll('.method-btn').forEach(btn => {
        btn.addEventListener('click', () => switchInputMethod(btn.dataset.method));
    });

    // Mode selector
    document.querySelectorAll('.mode-btn').forEach(btn => {
        btn.addEventListener('click', () => switchMode(btn.dataset.mode));
    });

    // Names input
    if (namesInput) {
        namesInput.addEventListener('input', updateNamesCount);
    }

    // Clear input
    document.getElementById('clearInput')?.addEventListener('click', () => {
        if (namesInput) {
            namesInput.value = '';
            updateNamesCount();
        }
    });

    // Sample names
    document.getElementById('sampleNames')?.addEventListener('click', loadSampleNames);

    // File input
    document.getElementById('fileInput')?.addEventListener('change', handleFileUpload);

    // Generate button
    generateBtn?.addEventListener('click', generate);

    // Generate again
    generateAgainBtn?.addEventListener('click', generate);

    // Result actions
    document.getElementById('copyResult')?.addEventListener('click', copyResult);
    document.getElementById('downloadPdf')?.addEventListener('click', downloadPDF);
    document.getElementById('downloadExcel')?.addEventListener('click', downloadExcel);
    document.getElementById('shareResult')?.addEventListener('click', shareResult);


    // Keyboard shortcuts
    document.addEventListener('keydown', (e) => {
        if (e.ctrlKey && e.key === 'Enter') {
            generate();
        }
    });
}

// Switch input method
function switchInputMethod(method) {
    currentInputMethod = method;

    // Update button states
    document.querySelectorAll('.method-btn').forEach(btn => {
        btn.classList.toggle('active', btn.dataset.method === method);
    });

    // Show/hide appropriate input
    const inputArea = document.querySelector('.input-area');
    const fileInputArea = document.getElementById('fileInputArea');

    if (method === 'txt' || method === 'csv') {
        inputArea.style.display = 'none';
        fileInputArea.style.display = 'block';
    } else {
        inputArea.style.display = 'block';
        fileInputArea.style.display = 'none';
    }
}

// Switch mode
function switchMode(mode) {
    currentMode = mode;

    // Update button states
    document.querySelectorAll('.mode-btn').forEach(btn => {
        btn.classList.toggle('active', btn.dataset.mode === mode);
    });

    // Show/hide people per group setting
    const peoplePerGroupSetting = document.getElementById('peoplePerGroupSetting');
    if (mode === 'order' || mode === 'pair') {
        peoplePerGroupSetting.style.display = 'none';
    } else {
        peoplePerGroupSetting.style.display = 'block';
    }

    // Update button text
    if (mode === 'group') {
        generateBtn.innerHTML = '<i class="fas fa-random"></i> GENERATE RANDOM GROUP';
    } else if (mode === 'order') {
        generateBtn.innerHTML = '<i class="fas fa-random"></i> GENERATE RANDOM ORDER';
    } else if (mode === 'pair') {
        generateBtn.innerHTML = '<i class="fas fa-random"></i> GENERATE PAIRS';
    }
}

// Update names count
function updateNamesCount() {
    const names = getNamesFromInput();
    namesCount.textContent = names.length;
}

// Get names from input
function getNamesFromInput() {
    const value = namesInput.value.trim();
    if (!value) return [];

    return value
        .split('\n')
        .map(name => name.trim())
        .filter(name => name.length > 0);
}

// Load sample names
function loadSampleNames() {
    const sampleNames = [
        'Andi', 'Budi', 'Citra', 'Dedi', 'Eka',
        'Fajar', 'Gina', 'Hadi', 'Indra', 'Joko',
        'Kartika', 'Lina', 'Mega', 'Nina', 'Olivia',
        'Putri', 'Rina', 'Siti', 'Tika', 'Umar'
    ];

    namesInput.value = sampleNames.join('\n');
    updateNamesCount();

    showToast('Sample names loaded!', 'success');
}

// Handle file upload
function handleFileUpload(e) {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();

    reader.onload = function(event) {
        const content = event.target.result;

        if (file.name.endsWith('.csv')) {
            // Parse CSV
            const names = parseCSV(content);
            namesInput.value = names.join('\n');
        } else {
            // Parse TXT (one name per line)
            const names = content
                .split('\n')
                .map(line => line.trim())
                .filter(line => line.length > 0);
            namesInput.value = names.join('\n');
        }

        updateNamesCount();
        showToast(`Loaded ${file.name}`, 'success');
    };

    reader.readAsText(file);
}

// Parse CSV
function parseCSV(content) {
    const lines = content.split('\n');
    const names = [];

    lines.forEach(line => {
        // Handle comma or semicolon separated
        const parts = line.split(/[,;]/);
        parts.forEach(part => {
            const name = part.trim();
            if (name) names.push(name);
        });
    });

    return names;
}

// Main generate function
function generate() {
    const names = getNamesFromInput();

    if (names.length === 0) {
        showToast('Masukkan setidaknya 1 nama!', 'error');
        namesInput.focus();
        return;
    }

    let result;

    if (currentMode === 'group') {
        result = generateGroupResult(names);
    } else if (currentMode === 'order') {
        result = generateOrderResult(names);
    } else if (currentMode === 'pair') {
        result = generatePairResult(names);
    }

    lastGeneratedResult = result;

    // Show results
    displayResults(result);

    // Save to history
    saveToHistory(result);

    // Update stats
    updateStats();

    // Scroll to results
    resultsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// Generate group result
function generateGroupResult(names) {
    const groupCount = parseInt(groupCountInput.value) || 4;
    const peoplePerGroup = parseInt(peoplePerGroupInput.value) || 0;
    const useRandomLeader = randomLeaderCheckbox.checked;

    let groups;

    if (peoplePerGroup > 0) {
        groups = generateGroupsByPeoplePerGroup(names, peoplePerGroup);
    } else {
        groups = generateGroups(names, groupCount);
    }

    // Add leaders if enabled
    if (useRandomLeader) {
        groups = groups.map(group => ({
            members: group,
            leader: getRandomLeader(group)
        }));
    }

    const stats = calculateStats(names, groups);

    return {
        type: 'group',
        names,
        groups,
        stats
    };
}

// Generate order result
function generateOrderResult(names) {
    const orderedNames = generateRandomOrder(names);

    return {
        type: 'order',
        names,
        orderedNames,
        stats: {
            totalNames: names.length,
            groupCount: 1,
            avgPerGroup: names.length
        }
    };
}

// Generate pair result
function generatePairResult(names) {
    const pairs = generateRandomPairs(names);

    return {
        type: 'pair',
        names,
        pairs,
        stats: {
            totalNames: names.length,
            groupCount: pairs.length,
            avgPerGroup: (names.length / pairs.length).toFixed(1)
        }
    };
}

// Display results
function displayResults(result) {
    resultsSection.style.display = 'block';

    // Update statistics
    document.getElementById('statTotal').textContent = result.stats.totalNames;
    document.getElementById('statGroups').textContent = result.stats.groupCount;
    document.getElementById('statAvg').textContent = result.stats.avgPerGroup;

    // Clear container
    groupsContainer.innerHTML = '';

    // Display based on type
    if (result.type === 'group') {
        displayGroups(result.groups);
    } else if (result.type === 'order') {
        displayOrder(result.orderedNames);
    } else if (result.type === 'pair') {
        displayPairs(result.pairs);
    }

    // Add animation
    if (animationToggle.checked) {
        animateResults();
    }
}

// Display groups
function displayGroups(groups) {
    groups.forEach((group, index) => {
        const delay = index * 0.1;

        const groupCard = document.createElement('div');
        groupCard.className = 'group-card';
        groupCard.style.animationDelay = `${delay}s`;

        const isGroupObject = typeof group === 'object' && group.members;
        const members = isGroupObject ? group.members : group;
        const leader = isGroupObject ? group.leader : null;

        let membersHTML = members.map(member => `<li>${escapeHTML(member)}</li>`).join('');

        groupCard.innerHTML = `
            <div class="group-header">
                <span class="group-title">Grup ${index + 1}</span>
                ${leader ? `<span class="group-leader"><i class="fas fa-crown"></i> ${escapeHTML(leader)}</span>` : ''}
            </div>
            <ul class="group-members">
                ${membersHTML}
            </ul>
        `;

        groupsContainer.appendChild(groupCard);
    });
}

// Display order
function displayOrder(orderedNames) {
    const groupCard = document.createElement('div');
    groupCard.className = 'group-card order-card';
    groupCard.style.animationDelay = '0s';

    const membersHTML = orderedNames.map((name, index) =>
        `<li><span class="order-number">${index + 1}.</span> <span class="order-name">${escapeHTML(name)}</span></li>`
    ).join('');

    groupCard.innerHTML = `
        <div class="group-header">
            <span class="group-title">Urutan Acak</span>
        </div>
        <ul class="group-members order-members">
            ${membersHTML}
        </ul>
    `;

    groupsContainer.appendChild(groupCard);
}

// Display pairs
function displayPairs(pairs) {
    pairs.forEach((pair, index) => {
        const delay = index * 0.1;

        const groupCard = document.createElement('div');
        groupCard.className = 'group-card';
        groupCard.style.animationDelay = `${delay}s`;

        let membersHTML;
        if (pair.length === 2) {
            membersHTML = `
                <li>${escapeHTML(pair[0])}</li>
                <li><i class="fas fa-heart" style="color: #EF4444; margin-right: 8px;"></i> ${escapeHTML(pair[1])}</li>
            `;
        } else {
            membersHTML = pair.map(member => `<li>${escapeHTML(member)}</li>`).join('');
        }

        groupCard.innerHTML = `
            <div class="group-header">
                <span class="group-title">Pasangan ${index + 1}</span>
            </div>
            <ul class="group-members">
                ${membersHTML}
            </ul>
        `;

        groupsContainer.appendChild(groupCard);
    });
}

// Animate results
function animateResults() {
    const cards = groupsContainer.querySelectorAll('.group-card');

    cards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(30px)';

        setTimeout(() => {
            card.style.transition = 'all 0.5s ease';
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, index * 100);
    });
}

// Escape HTML
function escapeHTML(str) {
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}

// Show toast notification
function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');

    const toast = document.createElement('div');
    toast.className = `toast ${type}`;

    const icon = type === 'success' ? 'check-circle' :
                 type === 'error' ? 'exclamation-circle' : 'info-circle';

    toast.innerHTML = `
        <i class="fas fa-${icon}"></i>
        <span>${escapeHTML(message)}</span>
    `;

    container.appendChild(toast);

    setTimeout(() => {
        toast.style.animation = 'slideInRight 0.3s ease reverse';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// Update global stats
function updateStats() {
    const totalGenerated = parseInt(localStorage.getItem('totalGenerated') || '0');
    const totalNames = parseInt(localStorage.getItem('totalNames') || '0');

    document.getElementById('totalGenerated').textContent = totalGenerated;
    document.getElementById('totalNames').textContent = totalNames;
}

