const scope = "home-inspection:demo";

const runtime =
    window.ensureInspectionOfflineRuntime(scope);

const queue =
    runtime.queue;

const inspectionPage =
    pageObj;

const saveButton =
    inspectionPage.getItemButton("add_save");

const photosByRow =
    new WeakMap();

let saving = false;


function findingRow(element) {
    const row =
        element.closest("tr");

    if (!row) {
        return null;
    }

    const room = row.querySelector(
        "select[id^='value_room_']"
    );

    const description = row.querySelector(
        "textarea[id^='value_description_']"
    );

    return room && description
        ? row
        : null;
}


function photoInputFor(element) {
    const cell =
        element.closest("td");

    if (!cell) {
        return null;
    }

    const input = cell.querySelector(
        "input[type='file'][name='files[]']"
    );

    return input && findingRow(input)
        ? input
        : null;
}


function setPhotos(input, files) {
    const row =
        findingRow(input);

    if (!row) {
        return;
    }

    const selected =
        Array.from(files);

    photosByRow.set(
        row,
        selected
    );

    const cell =
        input.closest("td");

    let preview = cell.querySelector(
        "[data-offline-photo-list]"
    );

    if (!preview) {
        preview =
            document.createElement("div");

        preview.setAttribute(
            "data-offline-photo-list",
            ""
        );

        preview.setAttribute(
            "aria-live",
            "polite"
        );

        preview.style.cssText =
            "display:flex;" +
            "flex-wrap:wrap;" +
            "gap:8px;" +
            "margin-top:8px;";

        cell.append(preview);
    }

    preview.replaceChildren();

    for (const file of selected) {
        const item =
            document.createElement("div");

        const image =
            document.createElement("img");

        const url =
            URL.createObjectURL(file);

        image.alt =
            file.name;

        image.title =
            file.name;

        image.style.cssText =
            "width:112px;" +
            "height:84px;" +
            "object-fit:contain;" +
            "border:1px solid #ddd;";

        image.onload = function () {
            URL.revokeObjectURL(url);
        };

        image.onerror = function () {
            URL.revokeObjectURL(url);

            item.textContent =
                file.name +
                " (preview unavailable)";
        };

        item.append(image);
        preview.append(item);

        image.src = url;
    }

    /*
     * Clear PHPRunner's file input so mfhandler.php does
     * not upload the image immediately. The File objects
     * remain available through photosByRow.
     */
    input.value = "";
}


document.addEventListener(
    "change",
    function (event) {
        const input =
            event.target;

        if (
            !input.matches(
                "input[type='file'][name='files[]']"
            ) ||
            !findingRow(input)
        ) {
            return;
        }

        event.stopImmediatePropagation();

        if (!saving) {
            setPhotos(
                input,
                input.files
            );
        }
    },
    true
);


document.addEventListener(
    "dragover",
    function (event) {
        if (photoInputFor(event.target)) {
            event.preventDefault();
            event.stopImmediatePropagation();
        }
    },
    true
);


document.addEventListener(
    "drop",
    function (event) {
        const input =
            photoInputFor(event.target);

        if (!input) {
            return;
        }

        event.preventDefault();
        event.stopImmediatePropagation();

        if (
            !saving &&
            event.dataTransfer.files.length
        ) {
            setPhotos(
                input,
                event.dataTransfer.files
            );
        }
    },
    true
);


inspectionPage.on(
    "beforeSave",
    function () {
        if (!saving) {
            saving = true;
            void saveOffline();
        }

        /*
         * Always cancel PHPRunner's ordinary Add request.
         * saveOffline() writes to IndexedDB first.
         */
        return false;
    }
);


async function saveOffline() {
    let submissionId;

    try {
        const address =
            document.querySelector(
                "#value_property_address_" +
                pageid
            ) ||
            document.querySelector(
                "#value_property_address_1"
            );

        const date =
            document.querySelector(
                "#value_inspection_date_" +
                pageid
            ) ||
            document.querySelector(
                "#value_inspection_date_1"
            );

        const notes =
            document.querySelector(
                "#value_notes_" +
                pageid
            ) ||
            document.querySelector(
                "#value_notes_1"
            );

        if (
            !address ||
            !date ||
            !notes
        ) {
            throw new Error(
                "The inspection fields could not be found on this page."
            );
        }

        if (
            !address.value.trim() ||
            !date.value.trim()
        ) {
            throw new Error(
                "Enter a property address and inspection date."
            );
        }

        const findings = [];
        const rowsToClear = [];

        const roomControls =
            document.querySelectorAll(
                "select[id^='value_room_']"
            );

        for (const room of roomControls) {
            const row =
                findingRow(room);

            if (
                !row ||
                !row.getClientRects().length
            ) {
                continue;
            }

            const description =
                row.querySelector(
                    "textarea[id^='value_description_']"
                );

            const photos =
                photosByRow.get(row) || [];

            if (
                !room.value &&
                !description.value.trim() &&
                photos.length === 0
            ) {
                continue;
            }

            if (
                !room.value ||
                !description.value.trim()
            ) {
                throw new Error(
                    "Enter a room and description for each finding."
                );
            }

            const rowId = Number(
                room.id.slice(
                    "value_room_".length
                )
            );

            if (
                !Number.isSafeInteger(rowId) ||
                rowId <= 0
            ) {
                throw new Error(
                    "Could not identify a finding row."
                );
            }

            findings.push({
                rowId: rowId,
                room: room.value,
                description:
                    description.value.trim(),
                photos: photos
            });

            rowsToClear.push({
                row: row,
                room: room,
                description: description
            });
        }

        /*
         * IndexedDB is always written first, regardless of
         * whether the server is currently available.
         */
        submissionId = await queue.enqueue(
            "inspections",
            {
                property_address:
                    address.value.trim(),

                inspection_date:
                    date.value.trim(),

                notes:
                    notes.value,

                findings:
                    findings
            }
        );

        /*
         * Try synchronization immediately. If unavailable,
         * online/focus events and the 30-second timer will
         * try again later from any application page.
         */
        await runtime.sync();

        const pending =
            await queue.pending();

        const stillQueued = pending.some(
            entry =>
                entry.id === submissionId
        );

        if (stillQueued) {
            runtime.showWaitingCount(
                pending.length
            );
        } else {
            runtime.showStatus(
                "Inspection saved to the server.",
                "success"
            );
        }

        const addressControl =
            Runner.getControl(
                pageid,
                "property_address"
            );

        const dateControl =
            Runner.getControl(
                pageid,
                "inspection_date"
            );

        const notesControl =
            Runner.getControl(
                pageid,
                "notes"
            );

        if (addressControl) {
            addressControl.setValue("");
        } else {
            address.value = "";
        }

        if (dateControl) {
            dateControl.setValue("");
        } else {
            date.value = "";
        }

        if (notesControl) {
            notesControl.setValue("");
        } else {
            notes.value = "";
        }

        for (
            const item of rowsToClear
        ) {
            item.room.value = "";
            item.description.value = "";

            photosByRow.delete(
                item.row
            );

            const preview =
                item.row.querySelector(
                    "[data-offline-photo-list]"
                );

            if (preview) {
                preview.remove();
            }
        }
    } catch (error) {
        if (submissionId) {
            runtime.showStatus(
                "Saved on this device. " +
                "The server save workflow did not finish.",
                "warning"
            );
        } else {
            runtime.showStatus(
                error.message ||
                "Could not save the inspection on this device.",
                "danger"
            );
        }
    } finally {
        saving = false;

        if (saveButton) {
            saveButton.removeClass(
                "disabled"
            );
        }
    }
}
