"use client";

import { useCallback, useEffect, useRef } from "react";
import type { HumanSignals } from "@/lib/human";

/**
 * Tracks pointer / scroll / keyboard / touch to distinguish humans from scripts.
 * Detects robotic scroll (near-constant intervals with no pointer).
 */
export function useHumanSignals() {
  const startedAt = useRef(Date.now());
  const honeypot = useRef("");
  const counts = useRef({
    pointer_moves: 0,
    scrolls: 0,
    keys: 0,
    touches: 0,
    focuses: 0,
    scroll_robotic: 0,
  });
  const lastScrollAt = useRef(0);
  const scrollGaps = useRef<number[]>([]);

  useEffect(() => {
    startedAt.current = Date.now();

    const onPointer = () => {
      counts.current.pointer_moves += 1;
    };
    const onKey = () => {
      counts.current.keys += 1;
    };
    const onTouch = () => {
      counts.current.touches += 1;
    };
    const onFocus = () => {
      counts.current.focuses += 1;
    };
    const onScroll = () => {
      counts.current.scrolls += 1;
      const now = Date.now();
      if (lastScrollAt.current) {
        const gap = now - lastScrollAt.current;
        scrollGaps.current.push(gap);
        if (scrollGaps.current.length > 12) scrollGaps.current.shift();
        // Robotic: several consecutive gaps within ~40–80ms of each other and tiny variance
        if (scrollGaps.current.length >= 5) {
          const sample = scrollGaps.current.slice(-5);
          const avg = sample.reduce((a, b) => a + b, 0) / sample.length;
          const variance =
            sample.reduce((a, b) => a + (b - avg) ** 2, 0) / sample.length;
          if (avg > 8 && avg < 120 && variance < 80) {
            counts.current.scroll_robotic += 1;
          }
        }
      }
      lastScrollAt.current = now;
    };

    window.addEventListener("pointermove", onPointer, { passive: true });
    window.addEventListener("keydown", onKey, { passive: true });
    window.addEventListener("touchstart", onTouch, { passive: true });
    window.addEventListener("focusin", onFocus, { passive: true });
    window.addEventListener("scroll", onScroll, { passive: true });

    return () => {
      window.removeEventListener("pointermove", onPointer);
      window.removeEventListener("keydown", onKey);
      window.removeEventListener("touchstart", onTouch);
      window.removeEventListener("focusin", onFocus);
      window.removeEventListener("scroll", onScroll);
    };
  }, []);

  const setHoneypot = useCallback((value: string) => {
    honeypot.current = value;
  }, []);

  const snapshot = useCallback((): HumanSignals => {
    return {
      website: honeypot.current,
      started_at: startedAt.current,
      pointer_moves: counts.current.pointer_moves,
      scrolls: counts.current.scrolls,
      keys: counts.current.keys,
      touches: counts.current.touches,
      focuses: counts.current.focuses,
      scroll_robotic: counts.current.scroll_robotic,
    };
  }, []);

  return { snapshot, setHoneypot };
}
