"use client";

import { useEffect, useRef, useCallback } from "react";

/**
 * PanicButton — An invisible panic trigger.
 *
 * Triple-tap anywhere on screen within 1 second triggers a silent alert.
 * Sends GPS location + timestamp to POST /api/safety/panic.
 * Shows NO visual feedback to avoid alerting anyone nearby.
 */
export default function PanicButton() {
  const tapTimestamps = useRef<number[]>([]);
  const cooldownRef = useRef(false);

  const sendPanicAlert = useCallback(async (latitude: number, longitude: number) => {
    try {
      await fetch("/api/safety/panic", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ latitude, longitude }),
      });
    } catch {
      // Silent — no error feedback to the user
    }
  }, []);

  const triggerPanic = useCallback(() => {
    if (cooldownRef.current) return;
    cooldownRef.current = true;

    // Reset cooldown after 10 seconds to prevent accidental re-triggers
    setTimeout(() => {
      cooldownRef.current = false;
    }, 10_000);

    if (typeof navigator !== "undefined" && "geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition(
        (pos) => {
          sendPanicAlert(pos.coords.latitude, pos.coords.longitude);
        },
        () => {
          // If geolocation fails, send with 0,0 coordinates
          sendPanicAlert(0, 0);
        },
        { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }
      );
    } else {
      // No geolocation available
      sendPanicAlert(0, 0);
    }
  }, [sendPanicAlert]);

  useEffect(() => {
    // Check if panic gesture is enabled (stored in localStorage)
    const enabled = localStorage.getItem("panic_gesture_enabled");
    if (enabled === "false") return;

    function handleTap() {
      const now = Date.now();
      tapTimestamps.current.push(now);

      // Keep only taps within the last 1 second
      tapTimestamps.current = tapTimestamps.current.filter(
        (t) => now - t < 1000
      );

      if (tapTimestamps.current.length >= 3) {
        tapTimestamps.current = [];
        triggerPanic();
      }
    }

    // Listen for both touch and click events
    document.addEventListener("touchstart", handleTap, { passive: true });
    document.addEventListener("click", handleTap, { passive: true });

    return () => {
      document.removeEventListener("touchstart", handleTap);
      document.removeEventListener("click", handleTap);
    };
  }, [triggerPanic]);

  // Render nothing — this component is invisible
  return null;
}
