// PhotoCapture — camera + file upload, sends image to Gemini vision.
// Opens as an overlay; on close, returns { imageUrl, analysis } via onResult.

function PhotoCapture({ accent, goal, profile, onClose, onResult }) {
  const protocol = goal ? GOAL_PROTOCOLS[goal] : null;
  const [phase, setPhase] = React.useState('camera'); // camera | preview | analyzing | done | error
  const [stream, setStream] = React.useState(null);
  const [imageBlob, setImageBlob] = React.useState(null);
  const [imageUrl, setImageUrl] = React.useState(null);
  const [analysis, setAnalysis] = React.useState('');
  const [error, setError] = React.useState('');
  const videoRef = React.useRef(null);
  const fileInputRef = React.useRef(null);

  // Start camera on mount
  React.useEffect(() => {
    let cancelled = false;
    let s = null;
    (async () => {
      if (location.protocol === 'file:' || !navigator.mediaDevices?.getUserMedia) {
        // file:// blocks getUserMedia. User can still upload a file.
        return;
      }
      try {
        s = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: { ideal: 'environment' } },
          audio: false,
        });
        if (cancelled) { s.getTracks().forEach((t) => t.stop()); return; }
        setStream(s);
        if (videoRef.current) {
          videoRef.current.srcObject = s;
          videoRef.current.play().catch(() => {});
        }
      } catch (e) {
        // Camera blocked or unavailable — that's fine, user can upload a file.
        console.warn('[Pepagent] camera unavailable:', e.message);
      }
    })();
    return () => {
      cancelled = true;
      if (s) s.getTracks().forEach((t) => t.stop());
    };
  }, []);

  const stopCamera = () => {
    if (stream) {
      stream.getTracks().forEach((t) => t.stop());
      setStream(null);
    }
  };

  const capture = () => {
    const v = videoRef.current;
    if (!v || !v.videoWidth) return;
    const canvas = document.createElement('canvas');
    canvas.width = v.videoWidth;
    canvas.height = v.videoHeight;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(v, 0, 0);
    canvas.toBlob((blob) => {
      if (!blob) return;
      setImageBlob(blob);
      setImageUrl(URL.createObjectURL(blob));
      setPhase('preview');
      stopCamera();
    }, 'image/jpeg', 0.9);
  };

  const onFile = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    setImageBlob(f);
    setImageUrl(URL.createObjectURL(f));
    setPhase('preview');
    stopCamera();
  };

  const retake = () => {
    if (imageUrl) URL.revokeObjectURL(imageUrl);
    setImageBlob(null);
    setImageUrl(null);
    setAnalysis('');
    setError('');
    setPhase('camera');
    // Restart camera
    (async () => {
      try {
        const s = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: { ideal: 'environment' } },
          audio: false,
        });
        setStream(s);
        if (videoRef.current) {
          videoRef.current.srcObject = s;
          videoRef.current.play().catch(() => {});
        }
      } catch (e) {}
    })();
  };

  const analyze = async () => {
    if (!imageBlob) return;
    setPhase('analyzing');
    setError('');
    try {
      const text = await window.geminiAnalyzePeptidePhoto(imageBlob, { goal, profile, protocol });
      setAnalysis(text);
      setPhase('done');
    } catch (e) {
      console.warn('[Pepagent] photo analysis failed:', e);
      setError(e.message || 'Analysis failed');
      setPhase('error');
    }
  };

  const close = (deliver) => {
    stopCamera();
    if (deliver && imageUrl && analysis) {
      onResult?.({ imageUrl, analysis });
    } else if (imageUrl) {
      URL.revokeObjectURL(imageUrl);
    }
    onClose();
  };

  return (
    <div className="photo-overlay">
      <div className="photo-shell">
        <div className="photo-head">
          <div>
            <div className="photo-eyebrow">// VISION</div>
            <div className="photo-title">
              {phase === 'camera' && 'Aim camera or upload'}
              {phase === 'preview' && 'Confirm shot'}
              {phase === 'analyzing' && 'Analyzing image…'}
              {phase === 'done' && 'Analysis'}
              {phase === 'error' && 'Something went wrong'}
            </div>
            <div className="photo-sub">
              {phase === 'camera' && 'Vial, box, injection site, or progress photo — Pepagent figures it out.'}
              {phase === 'preview' && 'Looks good? Send it for analysis.'}
              {phase === 'analyzing' && 'Reading the image with Gemini vision…'}
              {phase === 'done' && 'Educational only — confirm with a clinician.'}
              {phase === 'error' && error}
            </div>
          </div>
          <button className="photo-x" onClick={() => close(false)} aria-label="Close">×</button>
        </div>

        <div className="photo-body">
          {phase === 'camera' && (
            <div className="photo-cam">
              {stream ? (
                <video ref={videoRef} className="photo-video" playsInline muted />
              ) : (
                <div className="photo-no-cam">
                  <div className="photo-no-cam-title">Camera unavailable</div>
                  <div className="photo-no-cam-sub">
                    {location.protocol === 'file:'
                      ? 'Browsers block the camera on file:// pages. Run a local server (e.g. python -m http.server 8000) and open http://localhost:8000/Pepagent.html — or upload a photo from your device for now.'
                      : 'Upload a photo from your device instead.'}
                  </div>
                </div>
              )}
              <Crosshairs />
            </div>
          )}

          {(phase === 'preview' || phase === 'analyzing' || phase === 'done' || phase === 'error') && imageUrl && (
            <div className="photo-preview-wrap">
              <img src={imageUrl} className="photo-preview" alt="captured" />
              {phase === 'analyzing' && (
                <div className="photo-scan">
                  <span className="photo-scan-line" style={{ background: accent }} />
                </div>
              )}
              <Crosshairs />
            </div>
          )}

          {phase === 'done' && (
            <div className="photo-analysis">
              <div className="photo-analysis-eyebrow">PEPAGENT</div>
              <div className="photo-analysis-text">{analysis}</div>
            </div>
          )}
        </div>

        <div className="photo-actions">
          <input
            type="file"
            accept="image/*"
            ref={fileInputRef}
            onChange={onFile}
            style={{ display: 'none' }}
          />

          {phase === 'camera' && (
            <>
              <button className="ghost" onClick={() => fileInputRef.current?.click()}>
                UPLOAD
              </button>
              <button
                className="cta"
                style={{ '--accent': accent }}
                onClick={capture}
                disabled={!stream}
              >
                CAPTURE <Icon.arrow />
              </button>
            </>
          )}

          {phase === 'preview' && (
            <>
              <button className="ghost" onClick={retake}>RETAKE</button>
              <button className="cta" style={{ '--accent': accent }} onClick={analyze}>
                ANALYZE <Icon.arrow />
              </button>
            </>
          )}

          {phase === 'analyzing' && (
            <button className="ghost" disabled>WORKING…</button>
          )}

          {phase === 'done' && (
            <>
              <button className="ghost" onClick={retake}>NEW SHOT</button>
              <button className="cta" style={{ '--accent': accent }} onClick={() => close(true)}>
                ADD TO CHAT <Icon.arrow />
              </button>
            </>
          )}

          {phase === 'error' && (
            <>
              <button className="ghost" onClick={() => close(false)}>CLOSE</button>
              <button className="cta" style={{ '--accent': accent }} onClick={analyze}>
                RETRY
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

window.PhotoCapture = PhotoCapture;
