window.onload = function() {
    const input = document.getElementById('qr-input');
    const generateBtn = document.getElementById('generate-btn');
    const qrResult = document.getElementById('qr-result');
    const qrcodeContainer = document.getElementById('qrcode');
    const downloadBtn = document.getElementById('download-btn');

    generateBtn.addEventListener('click', function() {
        const value = input.value.trim();

        if (value === "") {
            alert("Silakan masukkan teks atau URL terlebih dahulu!");
            return;
        }

        // Hapus QR lama jika ada
        qrcodeContainer.innerHTML = "";

        // Buat QR Code baru
        try {
            new QRCode(qrcodeContainer, {
                text: value,
                width: 200,
                height: 200,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });

            // Munculkan kontainer hasil dan tombol download
            qrResult.style.display = "block";
        } catch (error) {
            console.error("Gagal membuat QR Code:", error);
            alert("Terjadi kesalahan teknis saat membuat QR Code.");
        }
    });

    // Logika Download
    downloadBtn.addEventListener('click', function() {
        const img = qrcodeContainer.querySelector('img');
        if (img) {
            const link = document.createElement('a');
            link.href = img.src;
            link.download = 'qrcode.png';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } else {
            alert("Gambar QR belum siap diunduh.");
        }
    });
};