'use client';

/**
 * Smart Scan Flow Hook
 * 
 * "Chamäleon Strategy":
 * - Branch A (Android/Chrome): Native TextDetector OCR
 * - Branch B (iOS/Unsupported): System Keyboard with Live Text
 * 
 * This is separate from the OpenRouter/Gemma cloud workflow.
 */

import { useState, useCallback, useEffect, useRef } from 'react';
import '@/types/text-detector.d.ts';

export interface ScanFlowState {
    hasNativeOCR: boolean;
    isIOS: boolean;
    isAndroid: boolean;
    isCameraActive: boolean;
    isFormOpen: boolean;
    detectedTexts: string[];
    isProcessing: boolean;
}

export interface UseScanFlowReturn {
    state: ScanFlowState;
    triggerScan: () => void;
    startCamera: () => void;
    stopCamera: () => void;
    openFormWithFocus: () => void;
    processVideoFrame: (video: HTMLVideoElement) => Promise<string[]>;
}

/**
 * Hook for smart scan flow with device capability detection
 */
export function useScanFlow(): UseScanFlowReturn {
    // Feature detection (run once on mount)
    const [state, setState] = useState<ScanFlowState>({
        hasNativeOCR: false,
        isIOS: false,
        isAndroid: false,
        isCameraActive: false,
        isFormOpen: false,
        detectedTexts: [],
        isProcessing: false,
    });

    const detectorRef = useRef<InstanceType<NonNullable<typeof window.TextDetector>> | null>(null);

    // Initialize feature detection
    useEffect(() => {
        if (typeof window === 'undefined') return;

        const hasNativeOCR = 'TextDetector' in window;
        const ua = navigator.userAgent;
        const isIOS = /iPad|iPhone|iPod/.test(ua) && !(window as any).MSStream;
        const isAndroid = /Android/.test(ua);

        console.log('[ScanFlow] Feature Detection:', {
            hasNativeOCR,
            isIOS,
            isAndroid,
            userAgent: ua.substring(0, 50) + '...',
        });

        setState(prev => ({
            ...prev,
            hasNativeOCR,
            isIOS,
            isAndroid,
        }));

        // Initialize TextDetector if available
        if (hasNativeOCR && window.TextDetector) {
            try {
                detectorRef.current = new window.TextDetector();
                console.log('[ScanFlow] TextDetector initialized');
            } catch (err) {
                console.warn('[ScanFlow] Failed to initialize TextDetector:', err);
            }
        }
    }, []);


    /**
     * Main trigger function - "Chamäleon Strategy"
     */
    const triggerScan = useCallback(() => {
        if (state.hasNativeOCR) {
            // PATH A: Android / Chrome (Automated OCR)
            console.log('[ScanFlow] Branch A: Starting Native TextDetector...');
            setState(prev => ({ ...prev, isCameraActive: true, isFormOpen: false }));
        } else {
            // PATH B: iOS / Fallback (System Keyboard)
            console.log('[ScanFlow] Branch B: Native OCR missing. Fallback to System Keyboard Flow.');
            openFormWithFocus();
        }
    }, [state.hasNativeOCR]);

    /**
     * Start camera for native OCR
     */
    const startCamera = useCallback(() => {
        console.log('[ScanFlow] Starting camera...');
        setState(prev => ({ ...prev, isCameraActive: true }));
    }, []);

    /**
     * Stop camera
     */
    const stopCamera = useCallback(() => {
        console.log('[ScanFlow] Stopping camera...');
        setState(prev => ({ ...prev, isCameraActive: false, detectedTexts: [] }));
    }, []);

    /**
     * Open form and auto-focus first input (iOS Live Text path)
     */
    const openFormWithFocus = useCallback(() => {
        console.log('[ScanFlow] Opening form with auto-focus...');
        setState(prev => ({ ...prev, isFormOpen: true, isCameraActive: false }));

        // UX Hack: Focus the field after a micro-task to ensure Modal is rendered
        setTimeout(() => {
            const inputField = document.querySelector('#field-bottle-name') as HTMLInputElement;
            if (inputField) {
                inputField.focus();
                console.log('[ScanFlow] Focused #field-bottle-name for iOS Live Text');
            } else {
                // Fallback to any input with data-scan-target
                const fallback = document.querySelector('[data-scan-target="true"]') as HTMLInputElement;
                if (fallback) {
                    fallback.focus();
                    console.log('[ScanFlow] Focused fallback scan target');
                }
            }
        }, 150);
    }, []);

    /**
     * Process a video frame using TextDetector
     */
    const processVideoFrame = useCallback(async (video: HTMLVideoElement): Promise<string[]> => {
        if (!detectorRef.current) {
            console.warn('[ScanFlow] TextDetector not available');
            return [];
        }

        setState(prev => ({ ...prev, isProcessing: true }));

        try {
            const imageBitmap = await createImageBitmap(video);
            const detections = await detectorRef.current.detect(imageBitmap);

            const texts = detections
                .map(d => d.rawValue)
                .filter(Boolean)
                .filter(text => text.length >= 2); // Filter very short strings

            console.log('[ScanFlow] Detected texts:', texts);

            setState(prev => ({
                ...prev,
                detectedTexts: texts,
                isProcessing: false,
            }));

            return texts;
        } catch (err) {
            console.error('[ScanFlow] Frame processing error:', err);
            setState(prev => ({ ...prev, isProcessing: false }));
            return [];
        }
    }, []);

    return {
        state,
        triggerScan,
        startCamera,
        stopCamera,
        openFormWithFocus,
        processVideoFrame,
    };
}

/**
 * Utility: Get placeholder text based on device
 */
export function getScanPlaceholder(isIOS: boolean, defaultText: string = 'Bottle Name'): string {
    if (isIOS) {
        return "Tap here & use 'Scan Text' 📷";
    }
    return defaultText;
}
