// ar-overlay.jsx — Mode AR overlay sur la caméra (web)
// Composant <AROverlayMode visit={...} /> qui :
// 1. Demande accès caméra (getUserMedia)
// 2. Capture un frame toutes les 3s
// 3. Envoie à /api/visite/ar/detect (Claude Vision)
// 4. Affiche les bounding boxes overlay sur la vidéo live

const { useState: _arS, useEffect: _arE, useRef: _arR } = React;

function AROverlayMode({ visit, onClose }) {
  const videoRef = _arR(null);
  const canvasRef = _arR(null);
  const streamRef = _arR(null);
  const sessionId = _arR(`ar-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
  const [detections, setDetections] = _arS([]);
  const [busy, setBusy] = _arS(false);
  const [error, setError] = _arS(null);
  const [stats, setStats] = _arS({ analyzed: 0, equipments: 0 });
  const intervalRef = _arR(null);
  const API = (window.AE_API && window.AE_API.BASE) || '';

  _arE(() => {
    (async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: 'environment', width: { ideal: 1280 }, height: { ideal: 720 } },
          audio: false,
        });
        streamRef.current = stream;
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
          await videoRef.current.play();
        }
        // Lance le scan auto
        intervalRef.current = setInterval(captureAndAnalyze, 3500);
      } catch (e) {
        setError('Accès caméra refusé : ' + e.message);
      }
    })();

    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
      if (streamRef.current) streamRef.current.getTracks().forEach(t => t.stop());
    };
  }, []);

  async function captureAndAnalyze() {
    if (busy || !videoRef.current || !canvasRef.current) return;
    const video = videoRef.current;
    const canvas = canvasRef.current;
    if (video.readyState < 2) return;

    canvas.width = video.videoWidth || 640;
    canvas.height = video.videoHeight || 480;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    const dataUrl = canvas.toDataURL('image/jpeg', 0.7);

    setBusy(true);
    try {
      const r = await fetch(`${API}/api/visite/ar/detect`, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ imageBase64: dataUrl, sessionId: sessionId.current }),
      }).then(r => r.json());
      if (r.ok && r.detections) {
        setDetections(r.detections);
        setStats(s => ({ analyzed: s.analyzed + 1, equipments: r.detections.length }));
      }
    } catch (e) {
      console.warn('[AR] detect failed:', e.message);
    } finally {
      setBusy(false);
    }
  }

  async function saveDetections() {
    if (!visit?.id || !detections.length) return;
    try {
      const r = await fetch(`${API}/api/visite/ar/save`, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ visitId: visit.id, detections }),
      }).then(r => r.json());
      if (r.ok) {
        window.toast?.success(`✓ ${r.count} équipement(s) sauvegardé(s)`);
      } else {
        window.toast?.error(r.error || 'Erreur sauvegarde');
      }
    } catch (e) { window.toast?.error(e.message); }
  }

  if (error) {
    return (
      <div style={{ position: 'fixed', inset: 0, background: 'var(--paper)', zIndex: 9990, padding: 30, display: 'grid', placeItems: 'center' }}>
        <div style={{ textAlign: 'center', maxWidth: 380 }}>
          <div style={{ fontSize: 48, marginBottom: 16 }}>📷</div>
          <h2 style={{ fontSize: 18, marginBottom: 8 }}>Mode AR indisponible</h2>
          <p style={{ fontSize: 13, color: 'var(--ink-3)' }}>{error}</p>
          <button onClick={onClose} style={{ marginTop: 16, padding: '10px 20px', background: 'var(--ink)', color: 'var(--paper)', border: 'none', borderRadius: 6 }}>Fermer</button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ position: 'fixed', inset: 0, background: '#000', zIndex: 9990 }}>
      <video
        ref={videoRef}
        playsInline
        autoPlay
        muted
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}
      />
      <canvas ref={canvasRef} style={{ display: 'none' }} />

      {/* Overlays bounding boxes */}
      <svg viewBox={`0 0 ${canvasRef.current?.width || 640} ${canvasRef.current?.height || 480}`}
        preserveAspectRatio="xMidYMid slice"
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }}>
        {detections.map((d, i) => {
          const w = canvasRef.current?.width || 640;
          const h = canvasRef.current?.height || 480;
          const x = d.bbox.x * w, y = d.bbox.y * h, bw = d.bbox.w * w, bh = d.bbox.h * h;
          return (
            <g key={i} style={{ animation: 'fadeIn 200ms ease-out both' }}>
              <rect x={x} y={y} width={bw} height={bh}
                fill="rgba(63,224,124,0.10)"
                stroke="#3FE07C" strokeWidth="3" />
              <rect x={x} y={y - 22} width={bw} height={22} fill="#3FE07C" />
              <text x={x + 5} y={y - 7} fontSize="13" fontWeight="700" fill="#0E1010">
                {d.label} {d.brand ? `· ${d.brand}` : ''} · {Math.round((d.confidence || 0) * 100)}%
              </text>
            </g>
          );
        })}
      </svg>

      {/* HUD top */}
      <div style={{ position: 'absolute', top: 20, left: 20, right: 20, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
        <div style={{ padding: '6px 12px', background: 'rgba(0,0,0,0.7)', color: '#fff', borderRadius: 14, fontSize: 11, fontFamily: 'var(--font-mono)' }}>
          🔍 AR scan · {busy ? 'analyse…' : 'auto 3s'}
        </div>
        <div style={{ padding: '6px 12px', background: 'rgba(63,224,124,0.85)', color: '#0E1010', borderRadius: 14, fontSize: 11, fontWeight: 700 }}>
          {detections.length} équipement{detections.length > 1 ? 's' : ''}
        </div>
        <div style={{ padding: '6px 12px', background: 'rgba(0,0,0,0.7)', color: '#fff', borderRadius: 14, fontSize: 11 }}>
          Frames analysées : {stats.analyzed}
        </div>
        <span style={{ flex: 1 }} />
        <button onClick={onClose} style={{
          width: 36, height: 36, borderRadius: 18, background: 'rgba(0,0,0,0.7)',
          color: '#fff', fontSize: 18, border: 'none', cursor: 'pointer',
        }}>✕</button>
      </div>

      {/* HUD bottom — actions */}
      <div style={{ position: 'absolute', bottom: 30, left: 20, right: 20, display: 'flex', gap: 10, justifyContent: 'center' }}>
        <button onClick={captureAndAnalyze} disabled={busy} style={{
          padding: '12px 24px', fontSize: 13, fontWeight: 600,
          background: 'rgba(255,255,255,0.95)', color: '#0E1010',
          border: 'none', borderRadius: 8, cursor: busy ? 'wait' : 'pointer',
        }}>
          {busy ? '⏳ Analyse…' : '🔍 Scan immédiat'}
        </button>
        {detections.length > 0 && visit?.id && (
          <button onClick={saveDetections} style={{
            padding: '12px 24px', fontSize: 13, fontWeight: 700,
            background: 'var(--signal)', color: '#0E1010',
            border: 'none', borderRadius: 8, cursor: 'pointer',
          }}>
            💾 Sauvegarder {detections.length} équipement{detections.length > 1 ? 's' : ''}
          </button>
        )}
      </div>
    </div>
  );
}

window.AROverlayMode = AROverlayMode;
