/* === FILE UPLOAD PREVIEW === */
document.addEventListener('DOMContentLoaded', () => {
    const uploadZones = document.querySelectorAll('.file-upload-zone');
    
    uploadZones.forEach(zone => {
        const input = zone.querySelector('input[type="file"]');
        if (!input) return;

        zone.addEventListener('click', () => input.click());

        zone.addEventListener('dragover', (e) => {
            e.preventDefault();
            zone.classList.add('dragover');
        });

        zone.addEventListener('dragleave', () => {
            zone.classList.remove('dragover');
        });

        zone.addEventListener('drop', (e) => {
            e.preventDefault();
            zone.classList.remove('dragover');
            
            if (e.dataTransfer.files.length) {
                input.files = e.dataTransfer.files;
                handleFiles(input.files, zone);
            }
        });

        input.addEventListener('change', () => {
            if (input.files.length) {
                handleFiles(input.files, zone);
            }
        });
    });

    function handleFiles(files, zone) {
        let previewContainer = zone.nextElementSibling;
        if (!previewContainer || !previewContainer.classList.contains('file-preview-grid')) {
            previewContainer = document.createElement('div');
            previewContainer.className = 'file-preview-grid mt-3 d-grid';
            previewContainer.style.gridTemplateColumns = 'repeat(auto-fill, minmax(100px, 1fr))';
            previewContainer.style.gap = '12px';
            zone.parentNode.insertBefore(previewContainer, zone.nextSibling);
        } else {
            previewContainer.innerHTML = '';
        }

        Array.from(files).forEach(file => {
            const item = document.createElement('div');
            item.className = 'file-preview-item';
            
            if (file.type.startsWith('image/')) {
                const img = document.createElement('img');
                img.src = URL.createObjectURL(file);
                img.style.width = '100%';
                img.style.height = '100%';
                img.style.objectFit = 'cover';
                item.appendChild(img);
            } else {
                item.innerHTML = `
                    <div class="d-flex flex-col align-center justify-center h-full p-2 bg-light border text-center">
                        <i class="fas fa-file text-muted mb-1" style="font-size: 24px;"></i>
                        <span class="text-xs truncate-text w-full">${file.name}</span>
                    </div>
                `;
            }
            
            previewContainer.appendChild(item);
        });
    }
});

// Fetch wrapper for CSRF
window.apiFetch = function(url, options = {}) {
    const token = document.querySelector('meta[name="csrf-token"]')?.content;
    const headers = new Headers(options.headers || {});
    if (token) headers.append('X-CSRF-Token', token);
    
    if (!(options.body instanceof FormData)) {
        headers.append('Content-Type', 'application/json');
    }
    
    options.headers = headers;
    return fetch(url, options);
};

// Form helpers
window.showFieldError = function(inputEl, message) {
    clearFieldError(inputEl);
    inputEl.classList.add('is-invalid');
    const err = document.createElement('div');
    err.className = 'form-error';
    err.innerText = message;
    inputEl.parentNode.appendChild(err);
};

window.clearFieldError = function(inputEl) {
    inputEl.classList.remove('is-invalid');
    const err = inputEl.parentNode.querySelector('.form-error');
    if(err) err.remove();
};
