// Captures images pasted from the clipboard inside the item editor and forwards the bytes to .NET.
// Used by Components/Wishlists/ItemEditor.razor.

export function registerPaste(zoneId, dotNetRef) {
    const zone = document.getElementById(zoneId);
    if (!zone) return null;

    const readAsBase64 = (file) => new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
            const result = reader.result || '';
            const comma = result.indexOf(',');
            resolve(comma >= 0 ? result.substring(comma + 1) : result);
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });

    const handler = async (e) => {
        const items = e.clipboardData?.items;
        if (!items) return;
        for (const item of items) {
            if (item.type && item.type.startsWith('image/')) {
                const file = item.getAsFile();
                if (!file) continue;
                e.preventDefault();
                const base64 = await readAsBase64(file);
                await dotNetRef.invokeMethodAsync('OnImagePasted', base64, item.type);
                return;
            }
        }
    };

    // Listen on the document so a paste anywhere while the editor is open is captured.
    document.addEventListener('paste', handler);
    return {
        dispose: () => document.removeEventListener('paste', handler)
    };
}
