import React, { useEffect, useRef, useState } from "react";
import { Text, TextInput, View } from "react-native";

export default function HiddenScannerListener({ onScan }: { onScan: any }) {
	const [buffer, setBuffer] = useState("");
	const inputRef = useRef<TextInput>(null);

	// Keep focusing the invisible input
	useEffect(() => {
		const timer = setInterval(() => {
			if (inputRef.current) inputRef.current.focus();
		}, 500);
		return () => clearInterval(timer);
	}, []);

	const handleChange = (text: string) => {
		// Most scanners append '\n' (Enter) or '\t'; trim and send
		if (text.endsWith("\n") || text.endsWith("\t")) {
			const code = text.trim();
			if (code) onScan?.(code);
			setBuffer("");
		} else {
			setBuffer(text);
		}
	};

	return (
		<TextInput
			ref={inputRef}
			value={buffer}
			onChangeText={handleChange}
			autoFocus
			style={{
				position: "absolute",
				opacity: 0, // invisible
				height: 0, // takes no space
				width: 0,
			}}
		/>
	);
}
