'use client';

import { useEffect, useRef } from 'react';
import { useImageProcessor } from '@/hooks/useImageProcessor';
import { db } from '@/lib/db';
import { FEATURES } from '@/config/features';

/**
 * Global handler for background AI image processing.
 * Mount this in root layout to ensure processing continues in background.
 * It also scans for unprocessed local images on load.
 */
export default function BackgroundRemovalHandler() {
    const { addToQueue } = useImageProcessor();
    const hasScannedRef = useRef(false);

    useEffect(() => {
        if (!FEATURES.ENABLE_AI_BG_REMOVAL) return;
        if (hasScannedRef.current) return;
        hasScannedRef.current = true;

        const scanAndQueue = async () => {
            try {
                // 1. Check pending_scans (offline scans)
                const pendingScans = await db.pending_scans
                    .filter(scan => !scan.bgRemoved)
                    .toArray();

                for (const scan of pendingScans) {
                    if (scan.imageBase64 && scan.temp_id) {
                        // Convert base64 back to blob for the worker
                        const res = await fetch(scan.imageBase64);
                        const blob = await res.blob();
                        addToQueue(scan.temp_id, blob);
                    }
                }

                // 2. Check cache_bottles (successfully saved bottles)
                const cachedBottles = await db.cache_bottles
                    .filter(bottle => !bottle.bgRemoved)
                    .limit(10) // Limit to avoid overwhelming on start
                    .toArray();

                for (const bottle of cachedBottles) {
                    if (bottle.image_url && bottle.id) {
                        try {
                            const res = await fetch(bottle.image_url);
                            const blob = await res.blob();
                            addToQueue(bottle.id, blob);
                        } catch (e) {
                            console.warn(`[BG-Removal] Failed to fetch image for bottle ${bottle.id}:`, e);
                        }
                    }
                }
            } catch (err) {
                console.error('[BG-Removal] Initial scan error:', err);
            }
        };

        // Delay slightly to not block initial app boot
        const timer = setTimeout(scanAndQueue, 3000);
        return () => clearTimeout(timer);
    }, [addToQueue]);

    return null; // Logic-only component
}
