var _useState_LHMP = React.useState;
var _useEffect_LHMP = React.useEffect;
var _useMemo_LHMP = React.useMemo;
var _useRef_LHMP = React.useRef;

/**
 * LocalHeatmapPanel — "Where the AI Looked" gradient saliency visualisation.
 *
 * PERFORMANCE OPTIMIZED: Fixed memory leaks by implementing proper image cleanup,
 * memoized computations, and deferred loading. Prevents base64 accumulation
 * and Image object leaks that caused browser crashes.
 *
 * Reusable component. Displays the original image alongside the AI attention
 * overlay, a jet colourbar legend, a plain-English insight card, and an
 * attention pattern badge.
 *
 * Jet colourbar colours preserved from reference app: blue (low) → red (high).
 *
 * Props:
 *   heatmapDataURL  string   — base64 JPEG of the overlay canvas (from LocalCNNService)
 *   originalDataURL string   — persisted image to show alongside the heatmap.
 *                              In AnalysisPage: pass imageData.previewURL (in-memory).
 *                              In ScanDetails:  pass scan.thumbnail (persisted ~140px JPEG).
 *   isMould         boolean
 *   saliencyLevel   string   — 'HIGH' | 'MODERATE' | 'DIFFUSE'
 *   isShortcut      boolean  — border attention warning
 *   speciesLabel    string   — top species label (optional, for insight text)
 *   className       string   — optional extra wrapper classes
 */
var LocalHeatmapPanel = function (props) {
    var heatmapDataURL  = props.heatmapDataURL;
    var originalDataURL = props.originalDataURL;
    var isMould         = props.isMould;
    var saliencyLevel   = props.saliencyLevel;
    var isShortcut      = props.isShortcut;
    var speciesLabel    = props.speciesLabel || '';
    var className       = props.className || '';

    // PERFORMANCE FIX: Image lifecycle management to prevent memory leaks
    var heatmapImgRef = _useRef_LHMP(null);
    var originalImgRef = _useRef_LHMP(null);
    var containerRef = _useRef_LHMP(null);
    
    // PERFORMANCE FIX: Deferred loading state to reduce initial memory pressure
    var loadedState = _useState_LHMP(false);
    var isLoaded = loadedState[0]; var setIsLoaded = loadedState[1];
    
    // PERFORMANCE FIX: Intersection observer for deferred loading
    _useEffect_LHMP(function() {
        if (!containerRef.current || isLoaded) return;
        
        var observer = new IntersectionObserver(function(entries) {
            if (entries[0].isIntersecting) {
                setIsLoaded(true);
                observer.disconnect();
            }
        }, { threshold: 0.1 });
        
        observer.observe(containerRef.current);
        
        return function() {
            observer.disconnect();
        };
    }, [isLoaded]);
    
    // PERFORMANCE FIX: Image cleanup on unmount or URL change
    _useEffect_LHMP(function() {
        return function() {
            // Cleanup Image objects to prevent memory accumulation
            if (heatmapImgRef.current) {
                heatmapImgRef.current.onload = null;
                heatmapImgRef.current.onerror = null;
                heatmapImgRef.current.src = '';
                heatmapImgRef.current = null;
            }
            if (originalImgRef.current) {
                originalImgRef.current.onload = null;
                originalImgRef.current.onerror = null;
                originalImgRef.current.src = '';
                originalImgRef.current = null;
            }
        };
    }, [heatmapDataURL, originalDataURL]);

    // PERFORMANCE FIX: Memoize expensive computation
    var isLocalised = _useMemo_LHMP(function() {
        return saliencyLevel === 'HIGH' || saliencyLevel === 'MODERATE';
    }, [saliencyLevel]);

    // ── Insight segments ──────────────────────────────────────────────────────
    // PERFORMANCE FIX: Memoize insight computation to prevent recalculation
    var segments = _useMemo_LHMP(function() {
        var segs = [];

        if (isMould) {
            if (speciesLabel) {
                segs.push([
                    { text: 'The AI focused on the areas shown in ' },
                    { text: 'warm colours (yellow–red)', bold: true },
                    { text: ' when identifying this as ' },
                    { text: speciesLabel, bold: true },
                    { text: '. These are the visual features that most influenced the result.' }
                ]);
            } else {
                segs.push([
                    { text: 'The AI focused on the areas shown in ' },
                    { text: 'warm colours (yellow–red)', bold: true },
                    { text: ' when detecting mould. These are the visual features that most influenced the result.' }
                ]);
            }
            if (isLocalised && !isShortcut) {
                segs.push([
                    { text: 'A ' },
                    { text: 'small, localised area of interest', bold: true },
                    { text: ' was detected. This pattern is consistent with an early-stage or small mould colony.' }
                ]);
            }
            if (isShortcut) {
                segs.push([
                    { text: 'The attention is concentrated near the ' },
                    { text: 'edges of the image', bold: true },
                    { text: ' rather than the centre. Try cropping the image to focus on the surface area.' }
                ]);
            } else if (!isLocalised) {
                segs.push([
                    { text: 'The attention is spread across the ' },
                    { text: 'main surface area', bold: true },
                    { text: ', suggesting the AI is responding to real surface features.' }
                ]);
            }
        } else {
            if (isLocalised && !isShortcut) {
                segs.push([
                    { text: 'The AI found a ' },
                    { text: 'small area of interest', bold: true },
                    { text: ' (shown in red/yellow), but overall confidence did not reach the detection threshold. If you can see a small spot, try photographing it more closely.' }
                ]);
            } else {
                segs.push([
                    { text: 'The AI found ' },
                    { text: 'no strong mould signals', bold: true },
                    { text: ' in this image. Cool colours (blue) indicate areas with little influence on the result.' }
                ]);
            }
        }
        
        return segs;
    }, [isMould, speciesLabel, isLocalised, isShortcut]);

    // ── Badge config ──────────────────────────────────────────────────────────
    // PERFORMANCE FIX: Memoize badge configuration
    var badgeConfig = _useMemo_LHMP(function() {
        var text = '';
        var style = '';
        if (isMould) {
            if (isShortcut) {
                text = '⚠️ Attention near edges';
                style = 'bg-warning-light text-warning border border-warning/20';
            } else if (isLocalised) {
                text = '🔍 Localised hotspot detected';
                style = 'bg-[#FFF8E1] text-[#d4a373] border border-[#d4a373]/20';
            } else {
                text = '✅ Attention on surface';
                style = 'bg-[#E8F5E9] text-primary border border-primary/20';
            }
        } else if (isLocalised && !isShortcut) {
            text = '🔍 Small area of interest — consider a closer photo';
            style = 'bg-[#FFF8E1] text-[#d4a373] border border-[#d4a373]/20';
        }
        return { text: text, style: style };
    }, [isMould, isShortcut, isLocalised]);

    // Early return must come AFTER every hook: if heatmapDataURL arrives on a
    // later render (hybrid enrichment / on-demand load), returning above a
    // hook would change the hook count and crash React.
    if (!heatmapDataURL) return null;

    return (
        <div ref={containerRef} className={'bio-bg bio-bg-20 rounded-xl border border-stone-100/50 shadow-soft overflow-hidden ' + className}>
            {/* Header */}
            <div className="px-4 pt-4 pb-2 text-center">
                <span className="text-[10px] font-black text-forest uppercase tracking-[0.15em]">Where the AI Looked</span>
                <p className="text-[11px] font-medium text-forest mt-1 leading-relaxed">
                    {isMould
                        ? 'The highlighted areas show which parts of the image the AI focused on when detecting mould.'
                        : 'The highlighted areas show which parts of the image the AI examined when checking for mould.'}
                </p>
            </div>

            {/* Canvas grid — original + overlay */}
            <div className="grid grid-cols-2 gap-3 px-4 mb-3">
                <div className="flex flex-col items-center gap-1.5">
                    {isLoaded && originalDataURL ? (
                        <img
                            ref={originalImgRef}
                            src={originalDataURL}
                            alt="Your image"
                            className="w-full rounded-lg border border-stone-200 object-cover"
                            style={{ aspectRatio: '1/1' }}
                            loading="lazy"
                            onLoad={function() {
                                // PERFORMANCE FIX: Clear reference to prevent memory buildup
                                if (originalImgRef.current) {
                                    originalImgRef.current.onload = null;
                                }
                            }}
                        />
                    ) : (
                        <div className="w-full aspect-square rounded-lg bg-background-light border border-stone-200 flex items-center justify-center">
                            <span className="material-symbols-outlined text-forest text-2xl">image</span>
                        </div>
                    )}
                    <span className="text-[10px] font-black text-forest uppercase tracking-wider">Your Image</span>
                </div>
                <div className="flex flex-col items-center gap-1.5">
                    {isLoaded ? (
                        <img
                            ref={heatmapImgRef}
                            src={heatmapDataURL}
                            alt="AI attention heatmap"
                            className="w-full rounded-lg border border-stone-200 object-cover"
                            style={{ imageRendering: 'pixelated', aspectRatio: '1/1' }}
                            loading="lazy"
                            onLoad={function() {
                                // PERFORMANCE FIX: Clear reference to prevent memory buildup
                                if (heatmapImgRef.current) {
                                    heatmapImgRef.current.onload = null;
                                }
                            }}
                        />
                    ) : (
                        <div className="w-full aspect-square rounded-lg bg-background-light border border-stone-200 flex items-center justify-center">
                            <span className="material-symbols-outlined text-forest text-2xl animate-pulse">psychology</span>
                        </div>
                    )}
                    <span className="text-[10px] font-black text-forest uppercase tracking-wider">AI Attention</span>
                </div>
            </div>

            {/* Jet colourbar — preserving reference app blue→red colours */}
            <div className="flex items-center gap-2 px-4 mb-3">
                <span className="text-[10px] font-bold text-forest shrink-0">Low</span>
                <div
                    className="flex-1 h-2 rounded-full"
                    style={{ background: 'linear-gradient(to right, #0000ff, #00ffff, #00ff00, #ffff00, #ff0000)' }}
                />
                <span className="text-[10px] font-bold text-forest shrink-0">High</span>
            </div>

            {/* Insight card */}
            <div className="mx-4 mb-3 p-4 bg-surface rounded-xl border border-stone-100/50">
                <p className="text-[10px] font-black text-forest uppercase tracking-[0.12em] mb-2">What this means</p>
                {segments.map(function (tokens, si) {
                    return (
                        <p key={si} className="text-[12px] font-medium text-forest leading-relaxed mb-1.5 last:mb-0">
                            {tokens.map(function (token, ti) {
                                return token.bold
                                    ? <strong key={ti} className="font-extrabold text-forest">{token.text}</strong>
                                    : <span key={ti}>{token.text}</span>;
                            })}
                        </p>
                    );
                })}
                {badgeConfig.text && (
                    <div className={'inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-bold mt-2 ' + badgeConfig.style}>
                        {badgeConfig.text}
                    </div>
                )}
            </div>

            {/* Disclaimer */}
            <p className="px-4 pb-4 text-[10px] font-medium text-forest leading-relaxed border-t border-sage/10 pt-3">
                This map shows what the AI examined — not a medical or scientific diagnosis. For definitive mould identification, professional laboratory testing is recommended.
            </p>
        </div>
    );
};

window.LocalHeatmapPanel = LocalHeatmapPanel;
