// Image compression utility — shared by NewFolder & FolderDetail.
// Resizes large camera photos before upload so we don't ship 5-10 MB JPEGs
// across the network (and into the DB as base64).
//
// Defaults tuned for the My Truck use case:
//   - longest side: 1600 px (still readable for damage details)
//   - JPEG quality: 0.78 (visually lossless for damage reports, ~80% size cut)
export async function resizeImage(file, maxDim = 1600, quality = 0.78) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            const img = new Image();
            img.onload = () => {
                let { width, height } = img;
                if (width > maxDim || height > maxDim) {
                    if (width > height) {
                        height = Math.round(height * (maxDim / width));
                        width = maxDim;
                    } else {
                        width = Math.round(width * (maxDim / height));
                        height = maxDim;
                    }
                }
                const canvas = document.createElement('canvas');
                canvas.width = width;
                canvas.height = height;
                const ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0, width, height);
                resolve(canvas.toDataURL('image/jpeg', quality));
            };
            img.onerror = reject;
            img.src = e.target.result;
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}
