/**
 * Random Group Generator - Export Functions
 * Copy, PDF, Excel, Share functionality
 */

// Copy result to clipboard
function copyResult() {
    if (!lastGeneratedResult) {
        showToast('Belum ada hasil untuk disalin!', 'error');
        return;
    }

    let text = '';

    if (lastGeneratedResult.type === 'group') {
        text = 'Hasil Random Group Generator\n';
        text += '==========================\n\n';

        lastGeneratedResult.groups.forEach((group, index) => {
            const isGroupObject = typeof group === 'object' && group.members;
            const members = isGroupObject ? group.members : group;
            const leader = isGroupObject ? group.leader : null;

            text += `Grup ${index + 1}`;
            if (leader) text += ` (Ketua: ${leader})`;
            text += '\n';
            text += '-'.repeat(20) + '\n';

            members.forEach(member => {
                text += `• ${member}\n`;
            });

            text += '\n';
        });
    } else if (lastGeneratedResult.type === 'order') {
        text = 'Hasil Random Urutan\n';
        text += '==================\n\n';

        lastGeneratedResult.orderedNames.forEach((name, index) => {
            text += `${index + 1}. ${name}\n`;
        });
    } else if (lastGeneratedResult.type === 'pair') {
        text = 'Hasil Random Pairs\n';
        text += '==================\n\n';

        lastGeneratedResult.pairs.forEach((pair, index) => {
            text += `Pasangan ${index + 1}: ${pair.join(' - ')}\n`;
        });
    }

    text += '\n--------------------------\n';
    text += `Generated by RandomGroup Pro`;

    navigator.clipboard.writeText(text).then(() => {
        showToast('Hasil disalin ke clipboard!', 'success');
    }).catch(err => {
        // Fallback for older browsers
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        showToast('Hasil disalin ke clipboard!', 'success');
    });
}

// Download as PDF
function downloadPDF() {
    if (!lastGeneratedResult) {
        showToast('Belum ada hasil untuk didownload!', 'error');
        return;
    }

    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();

    // Title
    doc.setFontSize(20);
    doc.setTextColor(15, 23, 42); // #0F172A
    doc.text('Random Group Generator', 105, 20, { align: 'center' });

    doc.setFontSize(10);
    doc.setTextColor(100, 116, 139);
    doc.text('Generated by RandomGroup Pro', 105, 28, { align: 'center' });

    // Line
    doc.setDrawColor(255, 215, 0);
    doc.setLineWidth(0.5);
    doc.line(20, 35, 190, 35);

    let yPos = 45;

    if (lastGeneratedResult.type === 'group') {
        lastGeneratedResult.groups.forEach((group, index) => {
            const isGroupObject = typeof group === 'object' && group.members;
            const members = isGroupObject ? group.members : group;
            const leader = isGroupObject ? group.leader : null;

            // Check if we need a new page
            if (yPos > 250) {
                doc.addPage();
                yPos = 20;
            }

            // Group header
            doc.setFontSize(14);
            doc.setTextColor(255, 215, 0); // Gold
            doc.text(`Grup ${index + 1}`, 20, yPos);

            if (leader) {
                doc.setFontSize(10);
                doc.setTextColor(245, 158, 11);
                doc.text(`Ketua: ${leader}`, 20, yPos + 7);
                yPos += 10;
            } else {
                yPos += 7;
            }

            // Members
            doc.setFontSize(11);
            doc.setTextColor(51, 65, 85);

            members.forEach(member => {
                if (yPos > 280) {
                    doc.addPage();
                    yPos = 20;
                }
                doc.text(`• ${member}`, 25, yPos);
                yPos += 7;
            });

            yPos += 10;
        });
    } else if (lastGeneratedResult.type === 'order') {
        lastGeneratedResult.orderedNames.forEach((name, index) => {
            if (yPos > 270) {
                doc.addPage();
                yPos = 20;
            }

            doc.setFontSize(11);
            doc.setTextColor(51, 65, 85);
            doc.text(`${index + 1}. ${name}`, 20, yPos);
            yPos += 10;
        });
    } else if (lastGeneratedResult.type === 'pair') {
        lastGeneratedResult.pairs.forEach((pair, index) => {
            if (yPos > 270) {
                doc.addPage();
                yPos = 20;
            }

            doc.setFontSize(12);
            doc.setTextColor(255, 215, 0);
            doc.text(`Pasangan ${index + 1}:`, 20, yPos);

            doc.setFontSize(11);
            doc.setTextColor(51, 65, 85);
            doc.text(pair.join(' - '), 30, yPos + 7);

            yPos += 17;
        });
    }

    // Footer stats
    const pageCount = doc.internal.getNumberOfPages();
    for (let i = 1; i <= pageCount; i++) {
        doc.setPage(i);
        doc.setFontSize(9);
        doc.setTextColor(148, 163, 184);
        doc.text(
            `Halaman ${i} dari ${pageCount} | Total: ${lastGeneratedResult.stats.totalNames} nama | ${lastGeneratedResult.stats.groupCount} grup`,
            105, 290, { align: 'center' }
        );
    }

    doc.save('random-group-result.pdf');
    showToast('PDF berhasil didownload!', 'success');
}

// Download as Excel
function downloadExcel() {
    if (!lastGeneratedResult) {
        showToast('Belum ada hasil untuk didownload!', 'error');
        return;
    }

    const wb = XLSX.utils.book_new();

    if (lastGeneratedResult.type === 'group') {
        // Create sheet for each group
        lastGeneratedResult.groups.forEach((group, index) => {
            const isGroupObject = typeof group === 'object' && group.members;
            const members = isGroupObject ? group.members : group;
            const leader = isGroupObject ? group.leader : null;

            const wsData = [
                [`Grup ${index + 1}${leader ? ` (Ketua: ${leader})` : ''}`],
                ['No', 'Nama'],
                ...members.map((name, i) => [i + 1, name])
            ];

            const ws = XLSX.utils.aoa_to_sheet(wsData);

            // Set column width
            ws['!cols'] = [{ wch: 5 }, { wch: 30 }];

            XLSX.utils.book_append_sheet(wb, ws, `Grup ${index + 1}`);
        });

        // Summary sheet
        const summaryData = [
            ['Random Group Generator - Summary'],
            [''],
            ['Total Nama', lastGeneratedResult.stats.totalNames],
            ['Jumlah Grup', lastGeneratedResult.stats.groupCount],
            ['Rata-rata per Grup', lastGeneratedResult.stats.avgPerGroup],
            [''],
            ['Detail Nama per Grup'],
            ['Grup', 'Jumlah', 'Anggota']
        ];

        lastGeneratedResult.groups.forEach((group, index) => {
            const isGroupObject = typeof group === 'object' && group.members;
            const members = isGroupObject ? group.members : group;
            summaryData.push([
                `Grup ${index + 1}`,
                members.length,
                members.join(', ')
            ]);
        });

        const wsSummary = XLSX.utils.aoa_to_sheet(summaryData);
        wsSummary['!cols'] = [{ wch: 15 }, { wch: 10 }, { wch: 50 }];
        XLSX.utils.book_append_sheet(wb, wsSummary, 'Summary');

    } else if (lastGeneratedResult.type === 'order') {
        const wsData = [
            ['Random Urutan'],
            [''],
            ['No', 'Nama'],
            ...lastGeneratedResult.orderedNames.map((name, i) => [i + 1, name])
        ];

        const ws = XLSX.utils.aoa_to_sheet(wsData);
        ws['!cols'] = [{ wch: 5 }, { wch: 30 }];
        XLSX.utils.book_append_sheet(wb, ws, 'Urutan');

    } else if (lastGeneratedResult.type === 'pair') {
        const wsData = [
            ['Random Pairs'],
            [''],
            ['No', 'Pasangan'],
            ...lastGeneratedResult.pairs.map((pair, i) => [i + 1, pair.join(' - ')])
        ];

        const ws = XLSX.utils.aoa_to_sheet(wsData);
        ws['!cols'] = [{ wch: 5 }, { wch: 30 }];
        XLSX.utils.book_append_sheet(wb, ws, 'Pairs');
    }

    XLSX.writeFile(wb, 'random-group-result.xlsx');
    showToast('Excel berhasil didownload!', 'success');
}

// Share result
function shareResult() {
    if (!lastGeneratedResult) {
        showToast('Belum ada hasil untuk dishare!', 'error');
        return;
    }

    // Create share text
    let shareText = '🎲 Hasil Random Group Generator\n\n';

    if (lastGeneratedResult.type === 'group') {
        lastGeneratedResult.groups.forEach((group, index) => {
            const isGroupObject = typeof group === 'object' && group.members;
            const members = isGroupObject ? group.members : group;

            shareText += `📋 Grup ${index + 1}:\n`;
            members.forEach(member => {
                shareText += `• ${member}\n`;
            });
            shareText += '\n';
        });
    } else if (lastGeneratedResult.type === 'order') {
        shareText += '📝 Urutan Acak:\n';
        lastGeneratedResult.orderedNames.forEach((name, index) => {
            shareText += `${index + 1}. ${name}\n`;
        });
    } else if (lastGeneratedResult.type === 'pair') {
        shareText += '💑 Pasangan:\n';
        lastGeneratedResult.pairs.forEach((pair, index) => {
            shareText += `Pasangan ${index + 1}: ${pair.join(' - ')}\n`;
        });
    }

    shareText += '\n✨ Generated by RandomGroup Pro';

    // Try Web Share API first
    if (navigator.share) {
        navigator.share({
            title: 'Random Group Generator',
            text: shareText
        }).then(() => {
            showToast('Berhasil dishare!', 'success');
        }).catch(err => {
            // Fallback to clipboard
            copyToClipboard(shareText);
        });
    } else {
        // Fallback to clipboard
        copyToClipboard(shareText);
    }
}

// Copy to clipboard helper
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        showToast('Hasil disalin ke clipboard!', 'success');
    }).catch(err => {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        showToast('Hasil disalin ke clipboard!', 'success');
    });
}

function saveToolHistory(type, payload) {
    if (typeof addToHistory === 'function') {
        addToHistory(type, payload);
    }
}


// Export functions for additional tools
// Random Name Picker
document.getElementById('pickWinner')?.addEventListener('click', function() {
    const input = document.getElementById('pickerInput').value.trim();
    if (!input) {
        showToast('Masukkan nama untuk diundi!', 'error');
        return;
    }

    const names = input.split('\n').filter(n => n.trim());
    if (names.length === 0) {
        showToast('Masukkan nama untuk diundi!', 'error');
        return;
    }

    const winner = pickRandomWinner(names);

    const resultDiv = document.getElementById('pickerResult');
    resultDiv.innerHTML = `<i class="fas fa-trophy"></i> ${escapeHTML(winner)}`;
    resultDiv.style.display = 'block';

    saveToolHistory('picker', {
        title: 'Random Name Picker',
        inputCount: names.length,
        winner
    });

    // Update stats
    const totalNames = parseInt(localStorage.getItem('totalNames') || '0');
    localStorage.setItem('totalNames', totalNames + names.length);
    updateStats();

    showToast('Pemenang terpilih!', 'success');
});

// Generate Pairs
document.getElementById('generatePairs')?.addEventListener('click', function() {
    const input = document.getElementById('pairInput').value.trim();
    if (!input) {
        showToast('Masukkan nama untuk dibuat pasangan!', 'error');
        return;
    }

    const names = input.split('\n').filter(n => n.trim());
    if (names.length < 2) {
        showToast('Masukkan setidaknya 2 nama!', 'error');
        return;
    }

    const pairs = generateRandomPairs(names);

    const resultDiv = document.getElementById('pairsResult');
    resultDiv.innerHTML = pairs.map((pair, index) => {
        const left = pair[0] || '-';
        const right = pair[1] || '(tanpa pasangan)';
        return `
        <div class="pair-item">
            <span>Pasangan ${index + 1}:</span>
            <strong>${escapeHTML(left)}</strong>
            <i class="fas fa-heart"></i>
            <strong>${escapeHTML(right)}</strong>
        </div>
    `;
    }).join('');

    resultDiv.style.display = 'block';

    saveToolHistory('pair', {
        title: 'Random Pair Generator',
        inputCount: names.length,
        pairs
    });

    showToast('Pasangan berhasil dibuat!', 'success');
});

// Wheel Spinner (Canvas-based)
let wheelAngle = 0;
let wheelVelocity = 0;
let isSpinning = false;
let wheelAnimationFrame = null;
let wheelWinners = []; // Track winners

const wheelInputEl = document.getElementById('wheelInput');
const wheelCanvas = document.getElementById('wheelCanvas');
const wheelCtx = wheelCanvas ? wheelCanvas.getContext('2d') : null;

function parseWheelNames() {
    if (!wheelInputEl) return [];
    return wheelInputEl.value
        .split('\n')
        .map(n => n.trim())
        .filter(Boolean);
}

function getWheelFontSize(count) {
    if (count <= 3) return 42;
    if (count <= 6) return 34;
    if (count <= 10) return 26;
    if (count <= 16) return 20;
    return 16;
}

function drawWheel(names) {
    if (!wheelCanvas || !wheelCtx) return;

    const ctx = wheelCtx;
    const w = wheelCanvas.width;
    const h = wheelCanvas.height;
    const cx = w / 2;
    const cy = h / 2;
    const radius = Math.min(w, h) / 2;

    ctx.clearRect(0, 0, w, h);

    // base background if empty
    if (!names || names.length === 0) {
        const bg = ctx.createRadialGradient(cx * 0.7, cy * 0.7, 20, cx, cy, radius);
        bg.addColorStop(0, '#1E293B');
        bg.addColorStop(1, '#020617');
        ctx.fillStyle = bg;
        ctx.beginPath();
        ctx.arc(cx, cy, radius, 0, Math.PI * 2);
        ctx.fill();
        return;
    }

    const colors = ['#E11D48', '#2563EB', '#16A34A', '#FACC15'];
    const segAngle = (Math.PI * 2) / names.length;
    const fontSize = getWheelFontSize(names.length);

    for (let i = 0; i < names.length; i++) {
        const start = i * segAngle + wheelAngle;
        const end = start + segAngle;

        // slice
        ctx.beginPath();
        ctx.moveTo(cx, cy);
        ctx.arc(cx, cy, radius, start, end);
        ctx.closePath();
        ctx.fillStyle = colors[i % colors.length];
        ctx.fill();

        // border separator
        ctx.lineWidth = 2;
        ctx.strokeStyle = 'rgba(255,255,255,0.9)';
        ctx.stroke();

        // text
        const rawName = names[i].replace(/\s+/g, ' ').trim();
        const maxChars = names.length <= 4 ? 18 : names.length <= 8 ? 14 : names.length <= 16 ? 10 : 8;
        const label = rawName.length > maxChars ? `${rawName.slice(0, maxChars)}…` : rawName;

        const mid = start + (segAngle / 2);
        const textRadius = radius * 0.72;

        ctx.save();
        ctx.translate(cx, cy);
        ctx.rotate(mid);

        // text setup (lebih stabil agar selalu terlihat)
        ctx.textBaseline = 'middle';
        ctx.fillStyle = '#ffffff';
        ctx.strokeStyle = 'rgba(0,0,0,0.95)';
        ctx.lineJoin = 'round';
        ctx.lineWidth = Math.max(2, fontSize * 0.1);
        ctx.font = `700 ${fontSize}px Arial, sans-serif`;

        // keep text upright
        if (mid > Math.PI / 2 && mid < Math.PI * 1.5) {
            ctx.rotate(Math.PI);
            ctx.textAlign = 'left';
            ctx.strokeText(label, -textRadius, 0);
            ctx.fillText(label, -textRadius, 0);
        } else {
            ctx.textAlign = 'right';
            ctx.strokeText(label, textRadius, 0);
            ctx.fillText(label, textRadius, 0);
        }

        ctx.restore();
    }

    // center hub
    ctx.beginPath();
    ctx.arc(cx, cy, radius * 0.18, 0, Math.PI * 2);
    ctx.fillStyle = '#ffffff';
    ctx.fill();
    ctx.lineWidth = 5;
    ctx.strokeStyle = 'rgba(0,0,0,0.25)';
    ctx.stroke();
}

function getWinnerIndex(names) {
    if (!names.length) return -1;
    const segAngle = (Math.PI * 2) / names.length;

    // Pointer ada di atas (sudut -90deg pada canvas)
    const pointerAngle = -Math.PI / 2;

    // Cari index segmen yang sedang berada tepat di bawah ujung runcing pointer
    let normalized = (pointerAngle - wheelAngle) % (Math.PI * 2);
    if (normalized < 0) normalized += Math.PI * 2;

    return Math.floor(normalized / segAngle) % names.length;
}

function renderWheelPreview() {
    drawWheel(parseWheelNames());
}

wheelInputEl?.addEventListener('input', renderWheelPreview);
renderWheelPreview();

document.getElementById('spinWheel')?.addEventListener('click', function() {
    const names = parseWheelNames();

    if (!names.length) {
        showToast('Masukkan nama untuk spinner!', 'error');
        return;
    }

    if (names.length < 2) {
        showToast('Masukkan setidaknya 2 nama!', 'error');
        return;
    }

    if (isSpinning) return;
    isSpinning = true;

    const resultDiv = document.getElementById('wheelResult');
    wheelVelocity = (Math.random() * 0.12) + 0.32; // initial angular velocity
    const friction = 0.988;

    const animate = () => {
        wheelAngle += wheelVelocity;
        wheelVelocity *= friction;

        drawWheel(names);

        if (wheelVelocity > 0.002) {
            wheelAnimationFrame = requestAnimationFrame(animate);
            return;
        }

        isSpinning = false;
        if (wheelAnimationFrame) cancelAnimationFrame(wheelAnimationFrame);

        const winnerIndex = getWinnerIndex(names);
        const winner = names[winnerIndex] || '-';
        resultDiv.innerHTML = `<i class="fas fa-star"></i> ${escapeHTML(winner)}`;

        // Add winner to winners list
        wheelWinners.push(winner);

        // Remove winner from input
        const remainingNames = names.filter((_, i) => i !== winnerIndex);
        if (wheelInputEl) {
            wheelInputEl.value = remainingNames.join('\n');
        }

        // Update winners display
        updateWheelWinnersDisplay();

        // Re-render wheel with remaining names
        drawWheel(remainingNames);

        saveToolHistory('wheel', {
            title: 'Wheel Spinner',
            inputCount: names.length,
            winner,
            winnerIndex
        });

        showToast('Pemenang: ' + winner, 'success');
    };

    animate();
});

// Update winners display function
function updateWheelWinnersDisplay() {
    const winnersContainer = document.getElementById('wheelWinners');
    if (!winnersContainer) return;

    if (wheelWinners.length === 0) {
        winnersContainer.innerHTML = '';
        return;
    }

    winnersContainer.innerHTML = `
        <div style="margin-top: 20px; padding: 15px; background: rgba(255, 215, 0, 0.1); border-radius: 12px; border: 1px solid rgba(255, 215, 0, 0.3);">
            <h4 style="color: var(--accent); margin-bottom: 10px;"><i class="fas fa-trophy"></i> Daftar Pemenang</h4>
            <ol style="padding-left: 20px; color: var(--text-primary);">
                ${wheelWinners.map((w, i) => `<li><strong>${escapeHTML(w)}</strong></li>`).join('')}
            </ol>
        </div>
    `;
}

// 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;
}

