import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { LockClosedIcon, LockOpen1Icon } from "@radix-ui/react-icons"; import { useEffect, useState } from "react"; import "../styles/locked-content.css"; import type { Generated } from "kysely"; import { onLocationError } from "@/lib/error"; const incrementCounter = async (id: string | Generated) => await fetch(`http://localhost:3000/api/location/increment/${id}`, { method: "PATCH", }); const LocationButton = ({ contentId = "", imageUrl = "#", location = "", }: { contentId?: string | Generated; imageUrl?: string; location?: string; }) => { const [atTarget, setAtTarget] = useState(false); const [contentVisible, setContentVisible] = useState(false); const [hasPermission, setHasPermission] = useState(false); const [watchId, setWatchId] = useState(); const [distanceRemain, setDistanceRemain] = useState(""); const targetCoordinates = JSON.parse(location); const targetPos = { lat: targetCoordinates[0], lng: targetCoordinates[1], }; const startWatchingLocation = () => { setHasPermission(true); if (!watchId) { const id = navigator.geolocation.watchPosition( (position: GeolocationPosition) => { const pos = { lat: position.coords.latitude, lng: position.coords.longitude, }; // @ts-expect-error 3rd party script const targetLatLng = L.latLng(targetPos); // @ts-expect-error 3rd party script const currentLatLng = L.latLng(pos); const betweenMeters = currentLatLng.distanceTo(targetLatLng); if (betweenMeters > 1000) { setDistanceRemain(`${(betweenMeters / 1000).toFixed()} KM`); } else if (betweenMeters > 100) { setDistanceRemain(`${betweenMeters.toFixed(0)} M`); } else { navigator.geolocation.clearWatch(id); setAtTarget(true); } }, (err) => onLocationError(err), { enableHighAccuracy: true, timeout: 27000, maximumAge: 10000 } ); setWatchId(id); } }; const handleUnlock = async () => { setContentVisible(true); await incrementCounter(contentId); }; useEffect(() => { navigator.permissions .query({ name: "geolocation" }) .then((permissionStatus) => { if (permissionStatus.state === "granted") { setHasPermission(true); startWatchingLocation(); } }); }, []); if (contentVisible) { return (
); } else { return ( <>
{atTarget ? (
İçeriği görmek için butona bas!
) : (
{hasPermission ? (

İçeriği görmek için konuma gitmelisin!

{distanceRemain && `Kalan mesafe: ${distanceRemain}`}

) : (
Ne kadar yaklaştığını görmek için aşağıdaki butona bas.
)}
)}
); } }; export default LocationButton;