'use client';

import React, { useEffect, useRef, useState, useCallback } from 'react';
import ModalPortal from '@/components/common/ModalPortal';
import { BrowserMultiFormatReader, BarcodeFormat, DecodeHintType } from '@zxing/library';

type Props = {
  isOpen: boolean;
  onClose: () => void;
  onBoxReceived: (result: { message: string; isError: boolean }) => void;
};

type FocusIndicator = {
  x: number;
  y: number;
  status: 'focusing' | 'focused';
};

export default function CameraBarcodeScannerModal({ isOpen, onClose, onBoxReceived }: Props) {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const scanLoopRef = useRef<number | null>(null);
  const zxingReaderRef = useRef<BrowserMultiFormatReader | null>(null);
  const lastScanAttemptRef = useRef<number>(0);
  const lastBarcodeSuccessRef = useRef<number>(Date.now());

  const [hasCameraPermission, setHasCameraPermission] = useState<boolean | null>(null);
  const [errorMessage, setErrorMessage] = useState('');
  const [facingMode, setFacingMode] = useState<'environment' | 'user'>('environment');

  // Torch & Focus & Zoom hardware capabilities
  const [hasTorch, setHasTorch] = useState(false);
  const [torchOn, setTorchOn] = useState(false);
  const [hasAutoFocus, setHasAutoFocus] = useState(false);
  const [hasHardwareZoom, setHasHardwareZoom] = useState(false);
  const [zoomLevel, setZoomLevel] = useState(1);
  const [zoomMin, setZoomMin] = useState(1);
  const [zoomMax, setZoomMax] = useState(4);
  const [zoomStep, setZoomStep] = useState(0.1);

  // Tap-to-Focus UI state
  const [focusIndicator, setFocusIndicator] = useState<FocusIndicator | null>(null);
  const [isFocusing, setIsFocusing] = useState(false);

  // Scanner state
  const [continuousScan, setContinuousScan] = useState(true);
  const [lastScannedCode, setLastScannedCode] = useState<string | null>(null);
  const [scanStatus, setScanStatus] = useState<{ text: string; isError: boolean } | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [scannerEngine, setScannerEngine] = useState<'native' | 'zxing'>('native');

  // Play audio beep upon successful scan
  const playBeep = () => {
    try {
      const AudioCtx = window.AudioContext || (window as any).webkitAudioContext;
      if (!AudioCtx) return;
      const ctx = new AudioCtx();
      const osc = ctx.createOscillator();
      const gain = ctx.createGain();
      osc.type = 'sine';
      osc.frequency.setValueAtTime(880, ctx.currentTime);
      gain.gain.setValueAtTime(0.25, ctx.currentTime);
      gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.15);
      osc.connect(gain);
      gain.connect(ctx.destination);
      osc.start();
      osc.stop(ctx.currentTime + 0.15);
    } catch {
      // Audio permission or failure ignored
    }
  };

  // Trigger hardware autofocus sweep and visual indicator
  const triggerFocus = useCallback(async (coords?: { x: number; y: number }) => {
    let x = coords?.x;
    let y = coords?.y;

    if (x === undefined || y === undefined) {
      if (containerRef.current) {
        const rect = containerRef.current.getBoundingClientRect();
        x = rect.width / 2;
        y = rect.height / 2;
      } else {
        x = 180;
        y = 180;
      }
    }

    setFocusIndicator({ x, y, status: 'focusing' });
    setIsFocusing(true);

    // Subtle haptic feedback if supported on mobile
    if (typeof navigator !== 'undefined' && navigator.vibrate) {
      try {
        navigator.vibrate(40);
      } catch {}
    }

    if (streamRef.current) {
      const track = streamRef.current.getVideoTracks()[0];
      if (track) {
        const caps: any = track.getCapabilities ? track.getCapabilities() : {};
        const focusModes: string[] = caps.focusMode || [];

        try {
          if (focusModes.includes('single-shot')) {
            // Trigger single-shot autofocus sweep
            await (track as any).applyConstraints({
              advanced: [{ focusMode: 'single-shot' }]
            });

            // After lens sweep, return to continuous focus to keep tracking
            setTimeout(async () => {
              if (focusModes.includes('continuous')) {
                try {
                  await (track as any).applyConstraints({
                    advanced: [{ focusMode: 'continuous' }]
                  });
                } catch {}
              }
              setFocusIndicator(prev => (prev ? { ...prev, status: 'focused' } : null));
              setIsFocusing(false);
              setTimeout(() => setFocusIndicator(null), 1200);
            }, 650);
            return;
          } else if (focusModes.includes('continuous')) {
            // Re-applying continuous mode nudges the camera HAL to recalculate focus
            await (track as any).applyConstraints({
              advanced: [{ focusMode: 'continuous' }]
            });
          }
        } catch (err) {
          console.warn('Focus constraint error:', err);
        }
      }
    }

    setTimeout(() => {
      setFocusIndicator(prev => (prev ? { ...prev, status: 'focused' } : null));
      setIsFocusing(false);
      setTimeout(() => setFocusIndicator(null), 1100);
    }, 550);
  }, []);

  // Apply Zoom (hardware zoom if supported, or digital CSS zoom fallback)
  const applyZoom = useCallback(async (newZoom: number) => {
    setZoomLevel(newZoom);
    if (streamRef.current) {
      const track = streamRef.current.getVideoTracks()[0];
      if (track) {
        try {
          await (track as any).applyConstraints({
            advanced: [{ zoom: newZoom }]
          });
        } catch (e) {
          // Hardware zoom unsupported or failed; CSS zoom handles visual scale
          console.warn('Hardware zoom could not be applied:', e);
        }
      }
    }
  }, []);

  // Toggle Torch/Flashlight
  const toggleTorch = async () => {
    if (!streamRef.current) return;
    const track = streamRef.current.getVideoTracks()[0];
    if (track) {
      try {
        const nextState = !torchOn;
        await (track as any).applyConstraints({
          advanced: [{ torch: nextState }]
        });
        setTorchOn(nextState);
      } catch (err) {
        console.error('Torch error:', err);
      }
    }
  };

  // Process detected barcode string
  const handleDetectedCode = useCallback(async (rawCode: string) => {
    const code = rawCode.trim();
    if (!code || isProcessing) return;
    if (code === lastScannedCode) return;

    lastBarcodeSuccessRef.current = Date.now();
    setIsProcessing(true);
    setLastScannedCode(code);
    playBeep();

    setScanStatus({ text: `Procesando caja: ${code}...`, isError: false });

    try {
      const res = await fetch('/api/cold-room', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'SCAN_RECEIVE', code })
      });
      const data = await res.json();

      if (!res.ok) {
        const msg = data.error || 'Código no encontrado o error al recibir';
        setScanStatus({ text: `❌ ${msg}`, isError: true });
        onBoxReceived({ message: msg, isError: true });
      } else {
        const msg = data.message || `Caja ${code} recibida correctamente`;
        setScanStatus({ text: `✅ ${msg}`, isError: false });
        onBoxReceived({ message: msg, isError: false });
        if (!continuousScan) {
          setTimeout(() => {
            onClose();
          }, 1200);
        }
      }
    } catch (err: any) {
      const msg = err.message || 'Error de conexión al registrar código';
      setScanStatus({ text: `❌ ${msg}`, isError: true });
      onBoxReceived({ message: msg, isError: true });
    } finally {
      setTimeout(() => {
        setLastScannedCode(null);
        setIsProcessing(false);
      }, 2200);
    }
  }, [continuousScan, isProcessing, lastScannedCode, onBoxReceived, onClose]);

  // Start Camera with autofocus and high resolution
  const startCamera = async () => {
    stopCamera();
    setErrorMessage('');
    try {
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        throw new Error('La cámara no está disponible en este navegador o dispositivo.');
      }

      // High-resolution request for razor-sharp barcode recognition
      const stream = await navigator.mediaDevices.getUserMedia({
        video: {
          facingMode: { ideal: facingMode },
          width: { ideal: 1920, min: 1280 },
          height: { ideal: 1080, min: 720 },
          aspectRatio: { ideal: 16 / 9 }
        },
        audio: false
      });

      streamRef.current = stream;
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
        await videoRef.current.play();
      }

      setHasCameraPermission(true);

      const track = stream.getVideoTracks()[0];
      if (track) {
        const capabilities: any = track.getCapabilities ? track.getCapabilities() : {};
        const advancedConstraints: any = {};

        // 1. Auto-Focus: Continuous autofocus mode
        if (capabilities.focusMode && Array.isArray(capabilities.focusMode)) {
          if (capabilities.focusMode.includes('continuous')) {
            advancedConstraints.focusMode = 'continuous';
            setHasAutoFocus(true);
          }
        }

        // 2. Continuous Auto-Exposure if available
        if (capabilities.exposureMode && Array.isArray(capabilities.exposureMode)) {
          if (capabilities.exposureMode.includes('continuous')) {
            advancedConstraints.exposureMode = 'continuous';
          }
        }

        // Apply initial camera enhancements
        if (Object.keys(advancedConstraints).length > 0) {
          try {
            await (track as any).applyConstraints({
              advanced: [advancedConstraints]
            });
          } catch (e) {
            console.warn('Initial advanced constraints warning:', e);
          }
        }

        // 3. Torch/Flashlight support
        if (capabilities.torch) {
          setHasTorch(true);
        } else {
          setHasTorch(false);
        }

        // 4. Zoom capabilities
        if (capabilities.zoom) {
          setHasHardwareZoom(true);
          setZoomMin(capabilities.zoom.min || 1);
          setZoomMax(capabilities.zoom.max || 4);
          setZoomStep(capabilities.zoom.step || 0.1);
          const settings: any = track.getSettings ? track.getSettings() : {};
          setZoomLevel(settings.zoom || 1);
        } else {
          setHasHardwareZoom(false);
          setZoomMin(1);
          setZoomMax(3);
          setZoomLevel(1);
        }
      }

      // Initialize scanner engine (Native BarcodeDetector or ZXing fallback)
      if ('BarcodeDetector' in window) {
        setScannerEngine('native');
      } else {
        setScannerEngine('zxing');
      }

      startScanningLoop();

      // Trigger an initial focus sweep so the user sees immediate sharp focus
      setTimeout(() => {
        triggerFocus();
      }, 700);

    } catch (err: any) {
      console.error('Camera error:', err);
      setHasCameraPermission(false);
      setErrorMessage(err.message || 'No se pudo acceder a la cámara. Revisa los permisos de tu dispositivo.');
    }
  };

  // Stop Camera & cleanup
  const stopCamera = () => {
    if (scanLoopRef.current) {
      cancelAnimationFrame(scanLoopRef.current);
      scanLoopRef.current = null;
    }
    if (streamRef.current) {
      streamRef.current.getTracks().forEach(track => {
        track.stop();
      });
      streamRef.current = null;
    }
    if (videoRef.current) {
      videoRef.current.srcObject = null;
    }
    setTorchOn(false);
    setFocusIndicator(null);
  };

  // Dual-Engine Scanning Loop (Native BarcodeDetector + ZXing Fallback)
  const startScanningLoop = () => {
    let nativeDetector: any = null;
    if ('BarcodeDetector' in window) {
      try {
        const BarcodeDetectorClass = (window as any).BarcodeDetector;
        nativeDetector = new BarcodeDetectorClass({
          formats: ['code_128', 'code_39', 'ean_13', 'ean_8', 'qr_code', 'itf', 'upc_a', 'upc_e']
        });
      } catch (e) {
        nativeDetector = null;
      }
    }

    if (!zxingReaderRef.current) {
      const hints = new Map();
      hints.set(DecodeHintType.POSSIBLE_FORMATS, [
        BarcodeFormat.CODE_128,
        BarcodeFormat.CODE_39,
        BarcodeFormat.EAN_13,
        BarcodeFormat.EAN_8,
        BarcodeFormat.ITF,
        BarcodeFormat.QR_CODE
      ]);
      hints.set(DecodeHintType.TRY_HARDER, true);
      zxingReaderRef.current = new BrowserMultiFormatReader(hints);
    }

    const scanFrame = async (timestamp: number) => {
      if (!videoRef.current || videoRef.current.readyState < 2) {
        scanLoopRef.current = requestAnimationFrame(scanFrame);
        return;
      }

      // Throttle detection every 180ms to optimize battery and speed
      if (timestamp - lastScanAttemptRef.current > 180 && !isProcessing) {
        lastScanAttemptRef.current = timestamp;

        let detectedCode: string | null = null;

        // 1. Try Native BarcodeDetector
        if (nativeDetector) {
          try {
            const barcodes = await nativeDetector.detect(videoRef.current);
            if (barcodes && barcodes.length > 0) {
              detectedCode = barcodes[0].rawValue;
            }
          } catch {
            // Frame error, fall through to ZXing
          }
        }

        // 2. Try ZXing if native didn't detect
        if (!detectedCode && zxingReaderRef.current) {
          try {
            const result = zxingReaderRef.current.decode(videoRef.current);
            if (result) {
              detectedCode = result.getText();
            }
          } catch {
            // NotFoundException ignored while scanning
          }
        }

        if (detectedCode) {
          await handleDetectedCode(detectedCode);
        }

        // 3. Auto-Focus Watchdog: If no barcode detected in 6 seconds, gently refresh continuous focus
        if (Date.now() - lastBarcodeSuccessRef.current > 6000 && !isFocusing) {
          lastBarcodeSuccessRef.current = Date.now();
          if (streamRef.current) {
            const track = streamRef.current.getVideoTracks()[0];
            if (track) {
              try {
                (track as any).applyConstraints({
                  advanced: [{ focusMode: 'continuous' }]
                }).catch(() => {});
              } catch {}
            }
          }
        }
      }

      scanLoopRef.current = requestAnimationFrame(scanFrame);
    };

    scanLoopRef.current = requestAnimationFrame(scanFrame);
  };

  // Handle tap anywhere on camera viewport
  const handleViewportTap = (e: React.MouseEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>) => {
    if (!containerRef.current) return;
    const rect = containerRef.current.getBoundingClientRect();
    let clientX = 0;
    let clientY = 0;

    if ('touches' in e && e.touches.length > 0) {
      clientX = e.touches[0].clientX;
      clientY = e.touches[0].clientY;
    } else if ('clientX' in e) {
      clientX = (e as React.MouseEvent).clientX;
      clientY = (e as React.MouseEvent).clientY;
    } else {
      return;
    }

    const x = clientX - rect.left;
    const y = clientY - rect.top;
    triggerFocus({ x, y });
  };

  // Lifecycle
  useEffect(() => {
    if (isOpen) {
      startCamera();
    } else {
      stopCamera();
      setScanStatus(null);
      setLastScannedCode(null);
    }

    return () => {
      stopCamera();
    };
  }, [isOpen, facingMode]);

  if (!isOpen) return null;

  return (
    <ModalPortal>
      <div
        style={{
          position: 'fixed',
          inset: 0,
          background: 'rgba(0, 0, 0, 0.88)',
          zIndex: 9999,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          padding: '0.5rem',
          backdropFilter: 'blur(5px)'
        }}
      >
        {/* Main Card Container */}
        <div
          style={{
            background: '#0f172a',
            color: '#f8fafc',
            borderRadius: '16px',
            width: '100%',
            maxWidth: '560px',
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
            boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.75)',
            border: '1px solid #334155'
          }}
        >
          {/* Header */}
          <div
            style={{
              padding: '0.85rem 1.25rem',
              background: '#1e293b',
              borderBottom: '1px solid #334155',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center'
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
              <span style={{ fontSize: '1.25rem' }}>📷</span>
              <div>
                <h3 style={{ margin: 0, fontSize: '1rem', fontWeight: 800, color: '#38bdf8' }}>
                  Escáner de Cámara — Cuarto Frío
                </h3>
                <span style={{ fontSize: '0.72rem', color: '#94a3b8' }}>
                  Apunta al código de barras de la etiqueta (10x14.5 cm)
                </span>
              </div>
            </div>
            <button
              onClick={onClose}
              style={{
                background: '#334155',
                border: 'none',
                color: '#fff',
                width: '32px',
                height: '32px',
                borderRadius: '50%',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontWeight: 800,
                fontSize: '1rem'
              }}
            >
              ✕
            </button>
          </div>

          {/* Camera Viewport Area */}
          <div
            ref={containerRef}
            onClick={handleViewportTap}
            style={{
              position: 'relative',
              width: '100%',
              height: '380px',
              maxHeight: '52vh',
              background: '#000',
              overflow: 'hidden',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: 'crosshair',
              userSelect: 'none'
            }}
          >
            {hasCameraPermission === false && (
              <div style={{ padding: '1.5rem', textAlign: 'center', color: '#f87171' }}>
                <div style={{ fontSize: '2rem', marginBottom: '0.5rem' }}>⚠️</div>
                <div style={{ fontWeight: 700, fontSize: '0.9rem' }}>Permiso de cámara no disponible</div>
                <div style={{ fontSize: '0.78rem', color: '#cbd5e1', marginTop: '0.4rem' }}>
                  {errorMessage || 'Asegúrate de permitir el acceso a la cámara en tu navegador.'}
                </div>
                <button
                  onClick={startCamera}
                  style={{
                    marginTop: '1rem',
                    padding: '0.5rem 1rem',
                    borderRadius: '8px',
                    border: 'none',
                    background: '#38bdf8',
                    color: '#0f172a',
                    fontWeight: 700,
                    cursor: 'pointer'
                  }}
                >
                  Reintentar Cámara
                </button>
              </div>
            )}

            {/* Video Feed with optional digital zoom scaling */}
            <video
              ref={videoRef}
              playsInline
              muted
              autoPlay
              style={{
                width: '100%',
                height: '100%',
                objectFit: 'cover',
                display: hasCameraPermission ? 'block' : 'none',
                transform: hasHardwareZoom ? 'none' : `scale(${zoomLevel})`,
                transformOrigin: 'center center',
                transition: 'transform 0.25s cubic-bezier(0.4, 0, 0.2, 1)'
              }}
            />

            {/* Tap-to-Focus Animated Reticle Indicator */}
            {focusIndicator && (
              <div
                style={{
                  position: 'absolute',
                  left: focusIndicator.x,
                  top: focusIndicator.y,
                  transform: 'translate(-50%, -50%)',
                  pointerEvents: 'none',
                  zIndex: 30,
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  animation: 'focusReticleScale 0.35s ease-out'
                }}
              >
                <div
                  style={{
                    width: '68px',
                    height: '68px',
                    borderRadius: '8px',
                    border: focusIndicator.status === 'focused' ? '2.5px solid #22c55e' : '2.5px solid #38bdf8',
                    boxShadow: focusIndicator.status === 'focused' ? '0 0 16px #22c55e' : '0 0 16px #38bdf8',
                    position: 'relative',
                    transition: 'all 0.25s ease'
                  }}
                >
                  {/* Center Crosshair Dot */}
                  <div
                    style={{
                      position: 'absolute',
                      left: '50%',
                      top: '50%',
                      transform: 'translate(-50%, -50%)',
                      width: '6px',
                      height: '6px',
                      borderRadius: '50%',
                      background: focusIndicator.status === 'focused' ? '#22c55e' : '#38bdf8'
                    }}
                  />
                  {/* Corner notches */}
                  <div style={{ position: 'absolute', top: -4, left: '50%', transform: 'translateX(-50%)', width: '2px', height: '6px', background: '#fff' }} />
                  <div style={{ position: 'absolute', bottom: -4, left: '50%', transform: 'translateX(-50%)', width: '2px', height: '6px', background: '#fff' }} />
                  <div style={{ position: 'absolute', left: -4, top: '50%', transform: 'translateY(-50%)', width: '6px', height: '2px', background: '#fff' }} />
                  <div style={{ position: 'absolute', right: -4, top: '50%', transform: 'translateY(-50%)', width: '6px', height: '2px', background: '#fff' }} />
                </div>
                <div
                  style={{
                    marginTop: '0.4rem',
                    fontSize: '0.7rem',
                    fontWeight: 800,
                    color: focusIndicator.status === 'focused' ? '#22c55e' : '#38bdf8',
                    background: 'rgba(15, 23, 42, 0.85)',
                    padding: '0.2rem 0.6rem',
                    borderRadius: '12px',
                    border: '1px solid rgba(255,255,255,0.15)',
                    whiteSpace: 'nowrap'
                  }}
                >
                  {focusIndicator.status === 'focused' ? '✅ Lente Enfocado' : '🎯 Enfocando...'}
                </div>
              </div>
            )}

            {/* Scan Reticle & Guide Overlay */}
            {hasCameraPermission && (
              <div
                style={{
                  position: 'absolute',
                  inset: 0,
                  pointerEvents: 'none',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
              >
                {/* Targeting Box */}
                <div
                  style={{
                    width: '84%',
                    height: '190px',
                    border: '2px solid rgba(56, 189, 248, 0.85)',
                    borderRadius: '14px',
                    position: 'relative',
                    boxShadow: '0 0 0 9999px rgba(0, 0, 0, 0.45)',
                    overflow: 'hidden'
                  }}
                >
                  {/* Laser Scanning Line Animation */}
                  <div
                    style={{
                      position: 'absolute',
                      left: 0,
                      right: 0,
                      height: '3px',
                      background: 'linear-gradient(90deg, transparent, #ef4444, transparent)',
                      boxShadow: '0 0 10px #ef4444',
                      animation: 'scanLaser 2s infinite ease-in-out'
                    }}
                  />

                  {/* Corner Accent Markers */}
                  <div style={{ position: 'absolute', top: 0, left: 0, width: '18px', height: '18px', borderTop: '4px solid #38bdf8', borderLeft: '4px solid #38bdf8' }} />
                  <div style={{ position: 'absolute', top: 0, right: 0, width: '18px', height: '18px', borderTop: '4px solid #38bdf8', borderRight: '4px solid #38bdf8' }} />
                  <div style={{ position: 'absolute', bottom: 0, left: 0, width: '18px', height: '18px', borderBottom: '4px solid #38bdf8', borderLeft: '4px solid #38bdf8' }} />
                  <div style={{ position: 'absolute', bottom: 0, right: 0, width: '18px', height: '18px', borderBottom: '4px solid #38bdf8', borderRight: '4px solid #38bdf8' }} />

                  {/* Center Tap-to-Focus Interactive Target Button */}
                  <button
                    type="button"
                    onClick={e => {
                      e.stopPropagation();
                      triggerFocus();
                    }}
                    style={{
                      pointerEvents: 'auto',
                      position: 'absolute',
                      top: '50%',
                      left: '50%',
                      transform: 'translate(-50%, -50%)',
                      background: 'rgba(15, 23, 42, 0.7)',
                      border: '1.5px dashed rgba(56, 189, 248, 0.7)',
                      borderRadius: '24px',
                      padding: '0.35rem 0.85rem',
                      color: '#38bdf8',
                      fontSize: '0.72rem',
                      fontWeight: 800,
                      display: 'flex',
                      alignItems: 'center',
                      gap: '0.35rem',
                      cursor: 'pointer',
                      boxShadow: '0 2px 8px rgba(0,0,0,0.5)'
                    }}
                    title="Toca aquí para auto-enfocar el código"
                  >
                    <span style={{ fontSize: '0.9rem' }}>🎯</span>
                    <span>Toca centro para enfocar</span>
                  </button>
                </div>

                {/* Subtitle instruction */}
                <div
                  style={{
                    marginTop: '0.65rem',
                    background: 'rgba(15, 23, 42, 0.85)',
                    padding: '0.25rem 0.85rem',
                    borderRadius: '20px',
                    fontSize: '0.73rem',
                    color: '#e2e8f0',
                    border: '1px solid rgba(255,255,255,0.1)'
                  }}
                >
                  Centra el código de barras en el recuadro
                </div>
              </div>
            )}

            {/* Top Right Quick Controls: Torch & Camera flip */}
            {hasCameraPermission && (
              <div
                style={{
                  position: 'absolute',
                  top: '10px',
                  right: '10px',
                  display: 'flex',
                  gap: '0.45rem',
                  zIndex: 20
                }}
              >
                {hasTorch && (
                  <button
                    type="button"
                    onClick={e => {
                      e.stopPropagation();
                      toggleTorch();
                    }}
                    style={{
                      background: torchOn ? '#eab308' : 'rgba(15, 23, 42, 0.8)',
                      color: torchOn ? '#000' : '#fff',
                      border: '1px solid rgba(255,255,255,0.25)',
                      borderRadius: '8px',
                      padding: '0.4rem 0.65rem',
                      cursor: 'pointer',
                      fontSize: '0.78rem',
                      fontWeight: 700,
                      boxShadow: '0 2px 6px rgba(0,0,0,0.4)'
                    }}
                    title="Encender / Apagar linterna"
                  >
                    🔦 {torchOn ? 'ON' : 'OFF'}
                  </button>
                )}

                <button
                  type="button"
                  onClick={e => {
                    e.stopPropagation();
                    setFacingMode(prev => (prev === 'environment' ? 'user' : 'environment'));
                  }}
                  style={{
                    background: 'rgba(15, 23, 42, 0.8)',
                    color: '#fff',
                    border: '1px solid rgba(255,255,255,0.25)',
                    borderRadius: '8px',
                    padding: '0.4rem 0.65rem',
                    cursor: 'pointer',
                    fontSize: '0.78rem',
                    fontWeight: 700,
                    boxShadow: '0 2px 6px rgba(0,0,0,0.4)'
                  }}
                  title="Cambiar de cámara trasera / frontal"
                >
                  🔄 Cambiar
                </button>
              </div>
            )}

            {/* Top Left Auto-Focus Active Badge */}
            {hasCameraPermission && (
              <div
                style={{
                  position: 'absolute',
                  top: '10px',
                  left: '10px',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.35rem',
                  background: 'rgba(15, 23, 42, 0.8)',
                  padding: '0.3rem 0.6rem',
                  borderRadius: '16px',
                  fontSize: '0.7rem',
                  fontWeight: 700,
                  color: hasAutoFocus ? '#4ade80' : '#38bdf8',
                  border: '1px solid rgba(255,255,255,0.15)',
                  zIndex: 20
                }}
              >
                <span style={{ fontSize: '0.55rem' }}>●</span>
                <span>{hasAutoFocus ? 'Auto-Enfoque Activo' : 'Enfoque Táctil'}</span>
              </div>
            )}

            {/* Bottom Floating Control Bar: Zoom & Focus Button */}
            {hasCameraPermission && (
              <div
                style={{
                  position: 'absolute',
                  bottom: '10px',
                  left: '10px',
                  right: '10px',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  zIndex: 20
                }}
              >
                {/* Zoom Selector Buttons (1x, 1.5x, 2x, 2.5x) */}
                <div
                  onClick={e => e.stopPropagation()}
                  style={{
                    display: 'flex',
                    background: 'rgba(15, 23, 42, 0.85)',
                    borderRadius: '20px',
                    padding: '3px',
                    border: '1px solid rgba(255,255,255,0.15)',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.4)'
                  }}
                >
                  {[1, 1.5, 2, 2.5].map(lvl => (
                    <button
                      key={lvl}
                      type="button"
                      onClick={() => applyZoom(lvl)}
                      style={{
                        background: zoomLevel === lvl ? '#38bdf8' : 'transparent',
                        color: zoomLevel === lvl ? '#0f172a' : '#cbd5e1',
                        border: 'none',
                        borderRadius: '16px',
                        padding: '0.25rem 0.55rem',
                        fontSize: '0.72rem',
                        fontWeight: 800,
                        cursor: 'pointer',
                        transition: 'all 0.15s ease'
                      }}
                      title={`Zoom ${lvl}x`}
                    >
                      {lvl}x
                    </button>
                  ))}
                </div>

                {/* Prominent Tap to Focus Trigger Button */}
                <button
                  type="button"
                  onClick={e => {
                    e.stopPropagation();
                    triggerFocus();
                  }}
                  style={{
                    background: isFocusing ? '#22c55e' : 'rgba(15, 23, 42, 0.85)',
                    color: isFocusing ? '#0f172a' : '#38bdf8',
                    border: '1px solid rgba(56, 189, 248, 0.5)',
                    borderRadius: '20px',
                    padding: '0.35rem 0.8rem',
                    fontSize: '0.74rem',
                    fontWeight: 800,
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '0.35rem',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.4)',
                    transition: 'all 0.2s ease'
                  }}
                  title="Presiona para re-enfocar el lente en el centro"
                >
                  <span>🎯</span>
                  <span>{isFocusing ? 'Enfocando...' : 'Re-enfocar'}</span>
                </button>
              </div>
            )}
          </div>

          {/* Quick Guidance Tip Banner */}
          <div
            style={{
              padding: '0.45rem 1rem',
              background: '#0c1322',
              borderBottom: '1px solid #1e293b',
              fontSize: '0.72rem',
              color: '#94a3b8',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: '0.4rem',
              textAlign: 'center'
            }}
          >
            <span>💡</span>
            <span>
              <strong>Tip:</strong> Si se ve borroso, toca la pantalla para enfocar o aleja el celular a 20 cm con <strong>Zoom 1.5x / 2x</strong>.
            </span>
          </div>

          {/* Feedback & Status Message */}
          {scanStatus && (
            <div
              style={{
                padding: '0.75rem 1.25rem',
                background: scanStatus.isError ? '#ef4444' : '#10b981',
                color: '#fff',
                fontWeight: 800,
                fontSize: '0.88rem',
                textAlign: 'center',
                transition: 'all 0.2s ease'
              }}
            >
              {scanStatus.text}
            </div>
          )}

          {/* Bottom Settings & Manual Code Entry */}
          <div style={{ padding: '0.9rem 1.25rem', background: '#1e293b', display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '0.5rem' }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '0.82rem', color: '#cbd5e1', cursor: 'pointer' }}>
                <input
                  type="checkbox"
                  checked={continuousScan}
                  onChange={e => setContinuousScan(e.target.checked)}
                  style={{ cursor: 'pointer', width: '16px', height: '16px' }}
                />
                <span>Escanear continuamente sin cerrar</span>
              </label>

              <span
                style={{
                  fontSize: '0.7rem',
                  color: scannerEngine === 'native' ? '#38bdf8' : '#fbbf24',
                  background: 'rgba(0,0,0,0.25)',
                  padding: '0.2rem 0.55rem',
                  borderRadius: '6px',
                  border: '1px solid rgba(255,255,255,0.08)'
                }}
              >
                {scannerEngine === 'native' ? '⚡ Lector Acelerado (GPU)' : '🔍 Motor Multi-Formato ZXing'}
              </span>
            </div>

            {/* Fallback Manual Code Entry Form */}
            <form
              onSubmit={e => {
                e.preventDefault();
                const form = e.currentTarget;
                const input = form.elements.namedItem('manualCode') as HTMLInputElement;
                if (input && input.value.trim()) {
                  handleDetectedCode(input.value.trim());
                  input.value = '';
                }
              }}
              style={{ display: 'flex', gap: '0.5rem' }}
            >
              <input
                name="manualCode"
                placeholder="O escribe / pega el código manual aquí..."
                style={{
                  flex: 1,
                  padding: '0.55rem 0.8rem',
                  borderRadius: '8px',
                  border: '1px solid #475569',
                  background: '#0f172a',
                  color: '#fff',
                  fontSize: '0.85rem',
                  fontFamily: 'monospace'
                }}
              />
              <button
                type="submit"
                style={{
                  padding: '0.55rem 1.1rem',
                  borderRadius: '8px',
                  border: 'none',
                  background: '#0284c7',
                  color: '#fff',
                  fontWeight: 700,
                  fontSize: '0.82rem',
                  cursor: 'pointer'
                }}
              >
                Ingresar
              </button>
            </form>
          </div>
        </div>

        {/* Global Keyframes for Scanner Laser & Reticle */}
        <style jsx global>{`
          @keyframes scanLaser {
            0% {
              top: 5%;
            }
            50% {
              top: 90%;
            }
            100% {
              top: 5%;
            }
          }
          @keyframes focusReticleScale {
            0% {
              transform: translate(-50%, -50%) scale(1.6);
              opacity: 0.5;
            }
            100% {
              transform: translate(-50%, -50%) scale(1);
              opacity: 1;
            }
          }
        `}</style>
      </div>
    </ModalPortal>
  );
}
