// zeus-video.jsx — Cámara siempre visible, grabación con preview en vivo y valoración IA

function VideoCapture({ t, onPhotosExtracted, onClose }) {
  const MODE = { SELECT:'select', CAMERA:'camera', FRAMES:'frames' };

  const [mode,      setMode]      = React.useState(MODE.SELECT);
  const [recording, setRecording] = React.useState(false);
  const [seconds,   setSeconds]   = React.useState(0);      // contador de grabación
  const [frames,    setFrames]    = React.useState([]);
  const [selected,  setSelected]  = React.useState([]);
  const [progress,  setProgress]  = React.useState(0);
  const [error,     setError]     = React.useState('');
  const [videoUrl,  setVideoUrl]  = React.useState(null);
  const [aiValuations, setAiVal]  = React.useState({});   // { frameIndex: {price, desc, condition} }
  const [valuating, setValuating] = React.useState(false);
  const [camReady,  setCamReady]  = React.useState(false); // cámara lista

  const videoRef    = React.useRef(null);
  const canvasRef   = React.useRef(null);
  const mediaRecRef = React.useRef(null);
  const chunksRef   = React.useRef([]);
  const streamRef   = React.useRef(null);
  const timerRef    = React.useRef(null);

  // Limpiar al desmontar
  React.useEffect(() => {
    return () => {
      stopStream();
      clearInterval(timerRef.current);
      if (videoUrl) URL.revokeObjectURL(videoUrl);
    };
  }, []);

  // ── Iniciar cámara INMEDIATAMENTE al entrar en modo CAMERA ────────
  React.useEffect(() => {
    if (mode === MODE.CAMERA) startCamera();
    else stopStream();
  }, [mode]);

  const startCamera = async () => {
    setError('');
    setCamReady(false);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: { ideal: 'environment' }, width: { ideal: 1280 }, height: { ideal: 720 } },
        audio: false,
      });
      streamRef.current = stream;
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
        videoRef.current.onloadedmetadata = () => {
          videoRef.current.play().then(() => setCamReady(true));
        };
      }
    } catch (e) {
      setError('No se pudo acceder a la cámara. Permite el acceso en el navegador.');
      setMode(MODE.SELECT);
    }
  };

  const stopStream = () => {
    if (streamRef.current) {
      streamRef.current.getTracks().forEach(t => t.stop());
      streamRef.current = null;
    }
    setCamReady(false);
  };

  // ── Empezar grabación ─────────────────────────────────────────────
  const startRecording = () => {
    if (!streamRef.current) return;
    chunksRef.current = [];
    const mime = getSupportedMime();
    const rec  = new MediaRecorder(streamRef.current, { mimeType: mime });
    rec.ondataavailable = e => { if (e.data.size > 0) chunksRef.current.push(e.data); };
    rec.onstop = () => {
      const blob = new Blob(chunksRef.current, { type: mime });
      const url  = URL.createObjectURL(blob);
      setVideoUrl(url);
      stopStream();
      clearInterval(timerRef.current);
      setMode(MODE.FRAMES);
      extractFrames(url);
    };
    rec.start(200);
    mediaRecRef.current = rec;
    setRecording(true);
    setSeconds(0);
    timerRef.current = setInterval(() => setSeconds(s => s + 1), 1000);
  };

  // ── Parar grabación ───────────────────────────────────────────────
  const stopRecording = () => {
    mediaRecRef.current?.stop();
    setRecording(false);
    clearInterval(timerRef.current);
  };

  // ── Subir vídeo ───────────────────────────────────────────────────
  const handleUpload = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 300 * 1024 * 1024) { setError('Vídeo demasiado grande (máx 300 MB)'); return; }
    const url = URL.createObjectURL(file);
    setVideoUrl(url);
    setMode(MODE.FRAMES);
    extractFrames(url);
  };

  // ── Extraer fotogramas ────────────────────────────────────────────
  const extractFrames = async (url) => {
    setFrames([]);
    setSelected([]);
    setAiVal({});
    setProgress(0);

    const video = document.createElement('video');
    video.src = url;
    video.muted = true;
    video.playsInline = true;

    await new Promise((res, rej) => {
      video.onloadedmetadata = res;
      video.onerror = rej;
      video.load();
    });

    const dur   = video.duration;
    const count = Math.min(20, Math.max(8, Math.floor(dur)));
    const times = Array.from({ length: count }, (_, i) => (i / (count - 1)) * dur * 0.96 + 0.02);

    const canvas = canvasRef.current || document.createElement('canvas');
    const ctx    = canvas.getContext('2d');
    const extracted = [];

    for (let i = 0; i < times.length; i++) {
      await seekTo(video, times[i]);
      canvas.width  = video.videoWidth  || 640;
      canvas.height = video.videoHeight || 360;
      ctx.drawImage(video, 0, 0);
      const dataUrl = canvas.toDataURL('image/jpeg', 0.85);
      extracted.push({ dataUrl, time: times[i] });
      setProgress(Math.round(((i + 1) / times.length) * 100));
      await new Promise(r => setTimeout(r, 30));
    }

    setFrames(extracted);
    setProgress(100);
  };

  const seekTo = (video, time) => new Promise(res => {
    const fn = () => { video.removeEventListener('seeked', fn); res(); };
    video.addEventListener('seeked', fn);
    video.currentTime = time;
  });

  const getSupportedMime = () => {
    const types = ['video/mp4', 'video/webm;codecs=vp9', 'video/webm;codecs=vp8', 'video/webm'];
    return types.find(t => MediaRecorder.isTypeSupported(t)) || 'video/webm';
  };

  // ── Selección de fotogramas ───────────────────────────────────────
  const toggleFrame = (i) => {
    setSelected(prev =>
      prev.includes(i) ? prev.filter(x => x !== i) : prev.length < 6 ? [...prev, i] : prev
    );
  };

  // ── Valoración IA de los frames seleccionados ─────────────────────
  const valorarConIA = async () => {
    if (selected.length === 0) return;
    setValuating(true);

    try {
      const results = {};
      for (const idx of selected) {
        const frame  = frames[idx];
        const base64 = frame.dataUrl.split(',')[1];

        const resp = await fetch('https://api.anthropic.com/v1/messages', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            model: 'claude-sonnet-4-20250514',
            max_tokens: 300,
            messages: [{
              role: 'user',
              content: [
                {
                  type: 'image',
                  source: { type: 'base64', media_type: 'image/jpeg', data: base64 },
                },
                {
                  type: 'text',
                  text: `Eres un experto tasador de objetos de segunda mano en España.
Analiza esta imagen y responde SOLO con JSON (sin texto extra):
{
  "objeto": "nombre del objeto en 3-5 palabras",
  "condicion": "Nuevo | Buen estado | Normal | Usado",
  "precioMin": numero en euros,
  "precioMax": numero en euros,
  "descripcion": "descripcion atractiva de 2 frases para vender el objeto",
  "consejo": "consejo de 1 frase para mejorar la foto o el anuncio"
}
Si la imagen no muestra un objeto vendible, devuelve { "objeto": "no_detectado" }.`,
                },
              ],
            }],
          }),
        });

        const data = await resp.json();
        const text = data.content?.[0]?.text || '';
        try {
          const clean = text.replace(/```json|```/g, '').trim();
          const parsed = JSON.parse(clean);
          if (parsed.objeto !== 'no_detectado') results[idx] = parsed;
        } catch {}
      }
      setAiVal(results);
    } catch (e) {
      setError('Error al valorar con IA: ' + e.message);
    }
    setValuating(false);
  };

  // ── Confirmar y enviar fotos al formulario ────────────────────────
  const confirmSelection = () => {
    if (selected.length === 0) return;

    // Tomar los datos de la IA del primer frame que tenga valoración
    const firstValIdx = selected.find(i => aiValuations[i]);
    const aiData = firstValIdx !== undefined ? aiValuations[firstValIdx] : null;

    const photos = selected.map(i => ({
      dataUrl: frames[i].dataUrl,
      base64:  frames[i].dataUrl.split(',')[1],
      source:  'video',
    }));

    onPhotosExtracted(photos, aiData);
  };

  const fmtSec = (s) => `${Math.floor(s / 60).toString().padStart(2,'0')}:${(s % 60).toString().padStart(2,'0')}`;

  // ─────────────────────────────────────────────────────────────────────
  //  RENDER
  // ─────────────────────────────────────────────────────────────────────
  return (
    <div style={{ position:'fixed', inset:0, zIndex:2000, background:'rgba(0,0,0,0.96)', display:'flex', flexDirection:'column', overflowY:'auto' }}>
      <canvas ref={canvasRef} style={{ display:'none' }} />

      {/* Header */}
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'14px 18px', background:'rgba(255,255,255,0.05)', flexShrink:0 }}>
        <div style={{ fontSize:17, fontWeight:900, color:'#fff', fontFamily:'Outfit,sans-serif' }}>
          {mode === MODE.SELECT ? '🎬 Cómo quieres grabar' : mode === MODE.CAMERA ? '📷 Cámara' : '🖼 Elige tus fotos'}
        </div>
        <button onClick={() => { stopStream(); onClose(); }}
          style={{ background:'rgba(255,255,255,0.12)', border:'none', color:'#fff', borderRadius:8, padding:'6px 14px', fontSize:14, cursor:'pointer', fontFamily:'Outfit,sans-serif' }}>
          ✕ Cerrar
        </button>
      </div>

      {/* ── PANTALLA SELECCIÓN ── */}
      {mode === MODE.SELECT && (
        <div style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'24px 20px', gap:14 }}>
          <div style={{ fontSize:44, marginBottom:4 }}>🎬</div>
          <div style={{ fontSize:20, fontWeight:900, color:'#fff', textAlign:'center', fontFamily:'Outfit,sans-serif' }}>Obtén fotos de un vídeo</div>
          <div style={{ fontSize:14, color:'rgba(255,255,255,0.55)', textAlign:'center', marginBottom:8, fontFamily:'Outfit,sans-serif' }}>
            Graba o sube un vídeo y la IA extrae y valora los mejores fotogramas
          </div>

          <button onClick={() => setMode(MODE.CAMERA)} style={{ width:'100%', maxWidth:380, padding:'18px 22px', background:'#3d5740', color:'#fff', border:'none', borderRadius:14, fontSize:16, fontWeight:800, cursor:'pointer', fontFamily:'Outfit,sans-serif', display:'flex', alignItems:'center', gap:14 }}>
            <span style={{ fontSize:28 }}>📷</span>
            <div style={{ textAlign:'left' }}>
              <div>Grabar con la cámara</div>
              <div style={{ fontSize:12, fontWeight:400, opacity:0.8 }}>Se abre la cámara trasera con preview en directo</div>
            </div>
          </button>

          <label style={{ width:'100%', maxWidth:380, padding:'18px 22px', background:'rgba(255,255,255,0.08)', color:'#fff', border:'2px solid rgba(255,255,255,0.18)', borderRadius:14, fontSize:16, fontWeight:800, cursor:'pointer', fontFamily:'Outfit,sans-serif', display:'flex', alignItems:'center', gap:14, boxSizing:'border-box' }}>
            <span style={{ fontSize:28 }}>📁</span>
            <div style={{ textAlign:'left' }}>
              <div>Subir vídeo existente</div>
              <div style={{ fontSize:12, fontWeight:400, opacity:0.8 }}>MP4, MOV, WebM · Máx 300 MB</div>
            </div>
            <input type="file" accept="video/*" onChange={handleUpload} style={{ display:'none' }} />
          </label>

          {error && <div style={{ background:'#c62828', borderRadius:10, padding:12, color:'#fff', fontSize:13, textAlign:'center', maxWidth:380, fontFamily:'Outfit,sans-serif' }}>{error}</div>}

          <div style={{ maxWidth:380, background:'rgba(255,255,255,0.06)', borderRadius:12, padding:14, fontSize:13, color:'rgba(255,255,255,0.8)', fontFamily:'Outfit,sans-serif', lineHeight:1.6 }}>
            💡 Graba 10-20 segundos dando una vuelta lenta al objeto con buena luz. La IA detectará automáticamente el tipo de objeto, su condición y el precio de mercado.
          </div>
        </div>
      )}

      {/* ── PANTALLA CÁMARA ── */}
      {mode === MODE.CAMERA && (
        <div style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', padding:'12px 16px 24px' }}>

          {/* Visor — siempre visible, con overlay si no está lista */}
          <div style={{ width:'100%', maxWidth:500, borderRadius:16, overflow:'hidden', background:'#111', position:'relative', marginBottom:16, aspectRatio:'16/9', flexShrink:0 }}>
            <video
              ref={videoRef}
              playsInline
              muted
              autoPlay
              style={{ width:'100%', height:'100%', objectFit:'cover', display:'block' }}
            />

            {/* Overlay "Iniciando cámara" mientras carga */}
            {!camReady && (
              <div style={{ position:'absolute', inset:0, background:'rgba(0,0,0,0.7)', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:10 }}>
                <div style={{ width:36, height:36, border:'3px solid rgba(255,255,255,0.3)', borderTop:'3px solid #fff', borderRadius:'50%', animation:'spin 1s linear infinite' }} />
                <div style={{ color:'rgba(255,255,255,0.8)', fontSize:14, fontFamily:'Outfit,sans-serif' }}>Iniciando cámara...</div>
              </div>
            )}

            {/* Indicador REC en esquina superior izquierda */}
            {recording && (
              <div style={{ position:'absolute', top:12, left:12, display:'flex', alignItems:'center', gap:6, background:'rgba(0,0,0,0.6)', borderRadius:20, padding:'4px 10px' }}>
                <div style={{ width:10, height:10, borderRadius:'50%', background:'#ef4444', animation:'pulse 1s infinite' }} />
                <span style={{ color:'#fff', fontSize:13, fontWeight:800, fontFamily:'Outfit,sans-serif' }}>REC {fmtSec(seconds)}</span>
              </div>
            )}

            {/* Contador duración máxima recomendada */}
            {recording && seconds >= 20 && (
              <div style={{ position:'absolute', top:12, right:12, background:'rgba(239,68,68,0.85)', borderRadius:8, padding:'4px 10px', color:'#fff', fontSize:12, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
                Puedes parar ya
              </div>
            )}
          </div>

          {/* Instrucción */}
          {!recording && camReady && (
            <div style={{ color:'rgba(255,255,255,0.6)', fontSize:13, marginBottom:14, textAlign:'center', fontFamily:'Outfit,sans-serif' }}>
              Da una vuelta lenta al objeto · 10-20 segundos es suficiente
            </div>
          )}

          {/* Botón REC / STOP */}
          <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:10 }}>
            {!recording ? (
              <button onClick={startRecording} disabled={!camReady}
                style={{ width:72, height:72, borderRadius:'50%', background: camReady ? '#ef4444' : '#555', border:'4px solid #fff', cursor: camReady ? 'pointer' : 'not-allowed', fontSize:28, boxShadow: camReady ? '0 4px 20px rgba(239,68,68,0.5)' : 'none', transition:'all 0.3s' }}>
                ⏺
              </button>
            ) : (
              <button onClick={stopRecording}
                style={{ width:72, height:72, borderRadius:16, background:'#ef4444', border:'4px solid #fff', cursor:'pointer', fontSize:22, color:'#fff', boxShadow:'0 4px 20px rgba(239,68,68,0.5)' }}>
                ⏹
              </button>
            )}
            <div style={{ color:'rgba(255,255,255,0.5)', fontSize:12, fontFamily:'Outfit,sans-serif' }}>
              {recording ? `Grabando ${fmtSec(seconds)}` : 'Toca para grabar'}
            </div>
          </div>

          {error && <div style={{ background:'#c62828', borderRadius:10, padding:12, color:'#fff', fontSize:13, textAlign:'center', marginTop:12, fontFamily:'Outfit,sans-serif' }}>{error}</div>}
        </div>
      )}

      {/* ── PANTALLA FOTOGRAMAS ── */}
      {mode === MODE.FRAMES && (
        <div style={{ flex:1, display:'flex', flexDirection:'column', padding:'14px 14px 24px', overflowY:'auto' }}>

          {/* Barra progreso extracción */}
          {progress < 100 && (
            <div style={{ marginBottom:16 }}>
              <div style={{ color:'#fff', fontSize:14, fontWeight:700, marginBottom:8, textAlign:'center', fontFamily:'Outfit,sans-serif' }}>
                Extrayendo fotogramas... {progress}%
              </div>
              <div style={{ height:8, background:'rgba(255,255,255,0.15)', borderRadius:100 }}>
                <div style={{ height:'100%', width:`${progress}%`, background:'#3d5740', borderRadius:100, transition:'width 0.3s' }} />
              </div>
            </div>
          )}

          {progress === 100 && frames.length > 0 && (
            <>
              <div style={{ marginBottom:12 }}>
                <div style={{ color:'#fff', fontSize:16, fontWeight:900, marginBottom:2, fontFamily:'Outfit,sans-serif' }}>
                  {frames.length} fotogramas extraídos
                </div>
                <div style={{ color:'rgba(255,255,255,0.55)', fontSize:12, fontFamily:'Outfit,sans-serif' }}>
                  Selecciona hasta 6 fotos · luego valora con IA
                </div>
              </div>

              {/* Grid fotogramas */}
              <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:8, marginBottom:16 }}>
                {frames.map((f, i) => {
                  const isSel  = selected.includes(i);
                  const selIdx = selected.indexOf(i);
                  const val    = aiValuations[i];
                  return (
                    <div key={i} onClick={() => toggleFrame(i)} style={{ position:'relative', borderRadius:10, overflow:'hidden', cursor:'pointer', border: isSel ? '3px solid #3d5740' : '3px solid transparent', transition:'border 0.15s' }}>
                      <img src={f.dataUrl} alt="" style={{ width:'100%', aspectRatio:'16/9', objectFit:'cover', display:'block' }} />

                      {/* Overlay seleccionado */}
                      {isSel && (
                        <div style={{ position:'absolute', inset:0, background:'rgba(61,87,64,0.3)', display:'flex', alignItems:'flex-start', justifyContent:'flex-end', padding:5 }}>
                          <div style={{ width:22, height:22, borderRadius:'50%', background:'#3d5740', color:'#fff', fontSize:12, fontWeight:900, display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'Outfit,sans-serif' }}>
                            {selIdx + 1}
                          </div>
                        </div>
                      )}

                      {/* Badge IA con precio */}
                      {val && (
                        <div style={{ position:'absolute', bottom:4, left:4, right:4, background:'rgba(0,0,0,0.75)', borderRadius:6, padding:'3px 6px' }}>
                          <div style={{ color:'#4ade80', fontSize:10, fontWeight:900, fontFamily:'Outfit,sans-serif' }}>
                            {val.precioMin}–{val.precioMax}€ · {val.condicion}
                          </div>
                        </div>
                      )}

                      {/* Timestamp */}
                      {!val && (
                        <div style={{ position:'absolute', bottom:4, left:5, background:'rgba(0,0,0,0.6)', color:'#fff', fontSize:9, borderRadius:4, padding:'2px 5px', fontFamily:'Outfit,sans-serif' }}>
                          {Math.floor(f.time)}s
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              {/* Valoraciones IA detalladas */}
              {Object.keys(aiValuations).length > 0 && (
                <div style={{ background:'rgba(255,255,255,0.06)', borderRadius:14, padding:14, marginBottom:16 }}>
                  <div style={{ color:'#fff', fontSize:14, fontWeight:800, marginBottom:10, fontFamily:'Outfit,sans-serif' }}>
                    Valoración IA
                  </div>
                  {selected.filter(i => aiValuations[i]).slice(0,1).map(i => {
                    const v = aiValuations[i];
                    return (
                      <div key={i}>
                        <div style={{ color:'#4ade80', fontSize:18, fontWeight:900, marginBottom:4, fontFamily:'Outfit,sans-serif' }}>{v.objeto}</div>
                        <div style={{ color:'rgba(255,255,255,0.8)', fontSize:13, marginBottom:6, fontFamily:'Outfit,sans-serif', lineHeight:1.5 }}>{v.descripcion}</div>
                        <div style={{ display:'flex', gap:10, flexWrap:'wrap', marginBottom:6 }}>
                          <div style={{ background:'rgba(74,222,128,0.15)', borderRadius:8, padding:'4px 10px', color:'#4ade80', fontSize:12, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
                            Precio: {v.precioMin}–{v.precioMax}€
                          </div>
                          <div style={{ background:'rgba(255,255,255,0.1)', borderRadius:8, padding:'4px 10px', color:'rgba(255,255,255,0.8)', fontSize:12, fontFamily:'Outfit,sans-serif' }}>
                            {v.condicion}
                          </div>
                        </div>
                        {v.consejo && <div style={{ color:'#fbbf24', fontSize:12, fontFamily:'Outfit,sans-serif', lineHeight:1.5 }}>💡 {v.consejo}</div>}
                      </div>
                    );
                  })}
                </div>
              )}

              {/* Botones de acción */}
              <div style={{ flexShrink:0, display:'flex', flexDirection:'column', gap:10 }}>

                {/* Valorar con IA */}
                {selected.length > 0 && Object.keys(aiValuations).length === 0 && (
                  <button onClick={valorarConIA} disabled={valuating}
                    style={{ width:'100%', padding:14, borderRadius:12, background: valuating ? '#555' : '#7c3aed', color:'#fff', border:'none', fontSize:15, fontWeight:800, cursor: valuating ? 'not-allowed' : 'pointer', fontFamily:'Outfit,sans-serif' }}>
                    {valuating ? '⏳ Valorando con IA...' : `✨ Valorar ${selected.length} foto${selected.length > 1 ? 's' : ''} con IA`}
                  </button>
                )}

                {/* Confirmar selección */}
                <button onClick={confirmSelection} disabled={selected.length === 0}
                  style={{ width:'100%', padding:14, borderRadius:12, background: selected.length > 0 ? '#3d5740' : 'rgba(255,255,255,0.1)', color:'#fff', border:'none', fontSize:15, fontWeight:800, cursor: selected.length > 0 ? 'pointer' : 'not-allowed', fontFamily:'Outfit,sans-serif' }}>
                  {selected.length > 0 ? `Usar ${selected.length} foto${selected.length > 1 ? 's' : ''} en el anuncio` : 'Selecciona al menos 1 foto'}
                </button>

                <button onClick={() => { setMode(MODE.SELECT); setFrames([]); setSelected([]); setProgress(0); setAiVal({}); }}
                  style={{ width:'100%', padding:12, borderRadius:12, background:'transparent', color:'rgba(255,255,255,0.5)', border:'1px solid rgba(255,255,255,0.15)', fontSize:13, cursor:'pointer', fontFamily:'Outfit,sans-serif' }}>
                  Grabar otro vídeo
                </button>
              </div>
            </>
          )}
        </div>
      )}

      {/* CSS animaciones */}
      <style>{`
        @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.3} }
        @keyframes spin  { to{transform:rotate(360deg)} }
      `}</style>
    </div>
  );
}

Object.assign(window, { VideoCapture });
