/**
 * Camera component using expo-camera (works in Expo Go).
 */

import React, { forwardRef, useImperativeHandle, useRef } from "react";
import { StyleSheet } from "react-native";
import { CameraView } from "expo-camera";

export interface CameraHandle {
  takePhoto: () => Promise<{ uri: string }>;
}

interface ExpoCameraProps {
  flashEnabled?: boolean;
}

export const ExpoCamera = forwardRef<CameraHandle, ExpoCameraProps>(
  ({ flashEnabled = false }, ref) => {
    const cameraRef = useRef<CameraView>(null);

    useImperativeHandle(ref, () => ({
      takePhoto: async () => {
        if (!cameraRef.current) {
          throw new Error("Camera not ready");
        }
        const photo = await cameraRef.current.takePictureAsync({
          quality: 0.8,
          base64: false,
        });
        if (!photo) {
          throw new Error("Failed to capture photo");
        }
        return { uri: photo.uri };
      },
    }));

    return (
      <CameraView
        ref={cameraRef}
        style={StyleSheet.absoluteFill}
        facing="back"
        flash={flashEnabled ? "on" : "off"}
      />
    );
  }
);

ExpoCamera.displayName = "ExpoCamera";
