async function compressImageFile(file, maxWidth = 1280, quality = 0.72) {
    if (!file || !file.type || !file.type.startsWith("image/")) {
        return file;
    }

    const imageUrl = URL.createObjectURL(file);
    const img = new Image();

    await new Promise((resolve, reject) => {
        img.onload = resolve;
        img.onerror = reject;
        img.src = imageUrl;
    });

    let width = img.naturalWidth || img.width;
    let height = img.naturalHeight || img.height;

    if (width > maxWidth) {
        height = Math.round(height * maxWidth / width);
        width = maxWidth;
    }

    const canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    canvas.getContext("2d").drawImage(img, 0, 0, width, height);
    URL.revokeObjectURL(imageUrl);

    const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/jpeg", quality));
    if (!blob) {
        return file;
    }

    return new File([blob], file.name.replace(/\.[^.]+$/, "") + ".jpg", { type: "image/jpeg" });
}

async function uploadCompressedImage(input) {
    const file = input.files && input.files[0];
    const targetSelector = input.dataset.target;
    const endpoint = input.dataset.uploadEndpoint || "../api/visitor/upload_image.php";
    const status = document.querySelector(input.dataset.status || "");
    const target = targetSelector ? document.querySelector(targetSelector) : null;

    if (!file || !target) {
        return;
    }

    if (status) {
        status.textContent = "Compressing image...";
        status.className = "upload-status";
    }

    try {
        const compressed = await compressImageFile(file);
        const formData = new FormData();
        formData.append("image", compressed);
        formData.append("field", input.name || "image");

        if (status) {
            status.textContent = "Uploading image...";
        }

        const response = await fetch(endpoint, {
            method: "POST",
            body: formData
        });

        const data = await response.json();
        if (!response.ok || !data.status) {
            throw new Error(data.message || "Image upload failed.");
        }

        target.value = data.path;
        input.dataset.uploaded = "1";

        if (status) {
            const kb = Math.max(1, Math.round((data.size || compressed.size) / 1024));
            status.textContent = "Uploaded and compressed (" + kb + " KB).";
            status.className = "upload-status is-success";
        }
    } catch (error) {
        target.value = "";
        input.dataset.uploaded = "";
        if (status) {
            status.textContent = error.message || "Image upload failed.";
            status.className = "upload-status is-error";
        }
    }
}

function initAjaxImageUploads() {
    document.querySelectorAll(".js-image-upload").forEach(input => {
        input.addEventListener("change", () => uploadCompressedImage(input));
    });
}

function showAppModal(id) {
    const modal = document.getElementById(id);
    if (modal) {
        modal.classList.add("is-open");
    }
}

function hideAppModal(id) {
    const modal = document.getElementById(id);
    if (modal) {
        modal.classList.remove("is-open");
    }
}

document.addEventListener("DOMContentLoaded", initAjaxImageUploads);
