<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Uploader Terintegrasi Kilat Storage</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f8f9fa; }
        .upload-container { max-width: 600px; margin-top: 5rem; }
        #paste-area { border: 2px dashed #0d6efd; padding: 2rem; text-align: center; color: #6c757d; border-radius: .5rem; cursor: pointer; transition: background-color 0.2s ease-in-out; }
        #paste-area:hover { background-color: #e9ecef; }
        #image-preview { max-width: 100%; max-height: 300px; margin: 1rem auto; display: block; border: 1px solid #ddd; padding: 5px; }
        .history-link { word-break: break-all; }
    </style>
</head>
<body>

<div class="container upload-container">
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <h1 class="card-title text-center mb-4">Upload File 🚀</h1>
            <p class="text-center text-muted">Klik area di bawah untuk memilih file, atau <strong>paste (Ctrl+V)</strong> gambar.</p>
            <div id="notification-area" class="mb-3" style="display:none;"></div>
            <form id="uploadForm">
                <div id="paste-area">
                    <span id="paste-area-text">Klik di sini untuk pilih file, atau <b>Ctrl+V</b> untuk menempelkan gambar</span>
                </div>
                <div id="preview-container" class="text-center mt-3"></div>
                
                <input class="d-none" type="file" id="fileToUpload" name="fileToUpload">
                
                <div class="d-grid mt-4">
                    <button type="submit" class="btn btn-primary btn-lg">Upload Sekarang</button>
                </div>
            </form>
        </div>
    </div>

    <div class="text-center mb-4">
        <button class="btn btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseHistory" aria-expanded="false" aria-controls="collapseHistory">
            Tampilkan / Sembunyikan Riwayat 📋
        </button>
    </div>

    <div class="collapse" id="collapseHistory">
        <div id="history-container">
            <h2 class="text-center mb-3">Riwayat Upload Lokal Anda</h2>
            <div id="history-list"></div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('uploadForm');
    const fileInput = document.getElementById('fileToUpload');
    const previewContainer = document.getElementById('preview-container');
    const notificationArea = document.getElementById('notification-area');
    const historyList = document.getElementById('history-list');
    const pasteArea = document.getElementById('paste-area'); // Ambil elemen area paste
    const pasteAreaText = document.getElementById('paste-area-text'); // Ambil elemen teks di dalamnya
    let pastedImageData = null;

    // =================================================================
    // FUNGSI BARU: Saat area paste di-klik, picu klik pada input file
    // =================================================================
    pasteArea.addEventListener('click', () => {
        fileInput.click(); // Memicu dialog pilih file
    });

    // =================================================================
    // FUNGSI BARU: Beri feedback saat file dipilih dari dialog
    // =================================================================
    fileInput.addEventListener('change', () => {
        if (fileInput.files.length > 0) {
            const fileName = fileInput.files[0].name;
            pasteAreaText.innerHTML = `✅ File terpilih: <strong>${fileName}</strong><br><small>Klik lagi untuk mengganti.</small>`;
            pastedImageData = null; // Hapus data paste jika ada
            previewContainer.innerHTML = ''; // Hapus pratinjau gambar jika ada
        }
    });

    const renderHistory = () => { /* ... kode tetap sama ... */
        const history = JSON.parse(localStorage.getItem('uploadHistory')) || [];
        if (history.length === 0) {
            historyList.innerHTML = '<p class="text-center text-muted">Belum ada riwayat upload.</p>';
            return;
        }
        historyList.innerHTML = history.map(item => `
            <div class="card mb-2">
                <div class="card-body">
                    <a href="${item.url}" target="_blank" class="history-link">${item.url}</a>
                    <small class="d-block text-muted mt-1">Diupload pada: ${new Date(item.uploadedAt).toLocaleString('id-ID')}</small>
                </div>
            </div>
        `).join('');
    };
    
    const saveToHistory = (url) => { /* ... kode tetap sama ... */
        let history = JSON.parse(localStorage.getItem('uploadHistory')) || [];
        const newEntry = { url: url, uploadedAt: new Date().toISOString() };
        history.unshift(newEntry);
if (history.length > 10) history.pop();
        localStorage.setItem('uploadHistory', JSON.stringify(history));
    };

    renderHistory();

    document.addEventListener('paste', (e) => {
        const items = e.clipboardData.items;
        for (const item of items) {
            if (item.type.indexOf('image') !== -1) {
                e.preventDefault();
                const blob = item.getAsFile();
                const reader = new FileReader();
                reader.onload = (event) => {
                    pastedImageData = event.target.result;
                    previewContainer.innerHTML = `<p class="text-success">Gambar dari clipboard siap di-upload:</p><img id="image-preview" src="${pastedImageData}" alt="Pratinjau"/>`;
                    fileInput.value = ''; // Hapus pilihan file jika ada
                    pasteAreaText.innerHTML = '🖼️ Gambar berhasil ditempel!<br><small>Klik di sini jika ingin ganti dengan file.</small>';
                };
                reader.readAsDataURL(blob);
                break;
            }
        }
    });

    form.addEventListener('submit', (e) => { /* ... kode tetap sama ... */
        e.preventDefault();
        const formData = new FormData();
        let hasData = false;
        
        if (pastedImageData) {
            formData.append('pastedImage', pastedImageData);
            hasData = true;
        } else if (fileInput.files.length > 0) {
            formData.append('fileToUpload', fileInput.files[0]);
            hasData = true;
        }

        if (!hasData) {
            showNotification('error', 'Silakan pilih file atau tempelkan gambar terlebih dahulu.');
            return;
        }

        showNotification('info', 'Sedang meng-upload, mohon tunggu...');

        fetch('upload.php', { method: 'POST', body: formData })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success' && data.data.url) {
                const publicUrl = data.data.url;
                showNotification('success', `<strong>Berhasil!</strong> File dapat diakses di: <a href="${publicUrl}" target="_blank" class="alert-link">${publicUrl}</a>`);
                saveToHistory(publicUrl);
                renderHistory();
                
                form.reset();
                previewContainer.innerHTML = '';
                pastedImageData = null;
                pasteAreaText.innerHTML = 'Klik di sini untuk pilih file, atau <b>Ctrl+V</b> untuk menempelkan gambar';
            } else {
                showNotification('danger', `<strong>Gagal!</strong> ${data.msg}`);
            }
        })
        .catch(error => {
            showNotification('danger', 'Terjadi error jaringan atau server.');
            console.error('Error:', error);
        });
    });

    function showNotification(type, message) { /* ... kode tetap sama ... */
        let alertClass = 'alert-info';
        if (type === 'success') alertClass = 'alert-success';
        if (type === 'danger' || type === 'error') alertClass = 'alert-danger';
        
        notificationArea.innerHTML = `<div class="alert ${alertClass}" role="alert">${message}</div>`;
        notificationArea.style.display = 'block';
    }
});
</script>

</body>
</html>
