/**
 * Random Group Generator - History Management
 * LocalStorage based history
 */

// History key
const HISTORY_KEY = 'randomGroupHistory';
const MAX_HISTORY_ITEMS = 20;

// Initialize history on page load
document.addEventListener('DOMContentLoaded', function() {
    loadHistory();
});

// Save to history
function saveToHistory(result) {
    let history = getHistory();

    // Create history item
    const item = {
        id: generateId(),
        timestamp: new Date().toISOString(),
        type: result.type,
        totalNames: result.stats.totalNames,
        groupCount: result.stats.groupCount,
        result: result
    };

    // Add to beginning
    history.unshift(item);

    // Limit history size
    if (history.length > MAX_HISTORY_ITEMS) {
        history = history.slice(0, MAX_HISTORY_ITEMS);
    }

    // Save to localStorage
    localStorage.setItem(HISTORY_KEY, JSON.stringify(history));

    // Update global stats
    const totalGenerated = parseInt(localStorage.getItem('totalGenerated') || '0');
    localStorage.setItem('totalGenerated', totalGenerated + 1);

    const totalNames = parseInt(localStorage.getItem('totalNames') || '0');
    localStorage.setItem('totalNames', totalNames + result.stats.totalNames);

    // Reload display
    loadHistory();
}

// Get history from localStorage
function getHistory() {
    const data = localStorage.getItem(HISTORY_KEY);
    return data ? JSON.parse(data) : [];
}

// Load and display history
function loadHistory() {
    const history = getHistory();
    const historyList = document.getElementById('historyList');
    const clearBtn = document.getElementById('clearHistory');

    if (history.length === 0) {
        historyList.innerHTML = `
            <div class="history-empty">
                <i class="fas fa-inbox"></i>
                <p>Belum ada riwayat generate</p>
            </div>
        `;
        clearBtn.style.display = 'none';
        return;
    }

    clearBtn.style.display = 'block';

    historyList.innerHTML = history.map((item, index) => {
        const date = new Date(item.timestamp);
        const formattedDate = formatDate(date);
        const formattedTime = formatTime(date);

        const typeIcon = item.type === 'group' ? 'users' :
                         item.type === 'order' ? 'list-ol' : 'heart';
        const typeName = item.type === 'group' ? 'Grup' :
                         item.type === 'order' ? 'Urutan' : 'Pasangan';

        return `
            <div class="history-item" data-id="${item.id}">
                <div class="history-info">
                    <h4>
                        <i class="fas fa-${typeIcon}"></i>
                        Generate ${index + 1} - ${typeName}
                    </h4>
                    <p>${item.totalNames} nama • ${item.groupCount} grup • ${formattedDate} ${formattedTime}</p>
                </div>
                <div class="history-actions">
                    <button class="btn btn-sm btn-secondary" onclick="viewHistoryItem(${index})" title="Lihat">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="deleteHistoryItem(${index})" title="Hapus">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }).join('');

    // Setup clear all button
    clearBtn.onclick = clearAllHistory;
}

// View history item
function viewHistoryItem(index) {
    const history = getHistory();
    const item = history[index];

    if (!item) return;

    lastGeneratedResult = item.result;
    displayResults(item.result);

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

    showToast('Riwayat dimuat!', 'info');
}

// Delete history item
function deleteHistoryItem(index) {
    const history = getHistory();
    history.splice(index, 1);
    localStorage.setItem(HISTORY_KEY, JSON.stringify(history));

    loadHistory();
    showToast('Riwayat dihapus!', 'success');
}

// Clear all history
function clearAllHistory() {
    if (confirm('Apakah Anda yakin ingin menghapus semua riwayat?')) {
        localStorage.removeItem(HISTORY_KEY);
        localStorage.setItem('totalGenerated', '0');

        loadHistory();
        updateStats();
        showToast('Semua riwayat dihapus!', 'success');
    }
}

// Generate unique ID
function generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// Format date
function formatDate(date) {
    const options = { day: 'numeric', month: 'short', year: 'numeric' };
    return date.toLocaleDateString('id-ID', options);
}

// Format time
function formatTime(date) {
    return date.toLocaleTimeString('id-ID', {
        hour: '2-digit',
        minute: '2-digit'
    });
}

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

    const totalGeneratedEl = document.getElementById('totalGenerated');
    const totalNamesEl = document.getElementById('totalNames');

    if (totalGeneratedEl) totalGeneratedEl.textContent = totalGenerated;
    if (totalNamesEl) totalNamesEl.textContent = totalNames;
}

// Export history to JSON
function exportHistory() {
    const history = getHistory();
    const data = JSON.stringify(history, null, 2);

    const blob = new Blob([data], { type: 'application/json' });
    const url = URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = 'random-group-history.json';
    a.click();

    URL.revokeObjectURL(url);
    showToast('Riwayat diexport!', 'success');
}

// Import history from JSON
function importHistory(file) {
    const reader = new FileReader();

    reader.onload = function(e) {
        try {
            const imported = JSON.parse(e.target.result);

            if (!Array.isArray(imported)) {
                throw new Error('Invalid format');
            }

            let history = getHistory();
            history = [...imported, ...history];

            // Limit size
            if (history.length > MAX_HISTORY_ITEMS) {
                history = history.slice(0, MAX_HISTORY_ITEMS);
            }

            localStorage.setItem(HISTORY_KEY, JSON.stringify(history));
            loadHistory();

            showToast('Riwayat diimport!', 'success');
        } catch (err) {
            showToast('Format file tidak valid!', 'error');
        }
    };

    reader.readAsText(file);
}

// Auto-cleanup old history (older than 30 days)
function cleanupOldHistory() {
    const history = getHistory();
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const filtered = history.filter(item => {
        return new Date(item.timestamp) > thirtyDaysAgo;
    });

    if (filtered.length !== history.length) {
        localStorage.setItem(HISTORY_KEY, JSON.stringify(filtered));
        loadHistory();
    }
}

// Run cleanup on load
cleanupOldHistory();

