import { useEffect, useRef, useCallback } from "react";
import { useLocation, useNavigate } from "react-router-dom";

/** Same order as the main landing tiles (home → Aktionen → Filiale). */
const MAIN_PAGE_PATHS = ["/", "/aktionen", "/filiale"];

/** No input for this long before the slideshow starts. */
const IDLE_MS = 90_000;

/** Time between automatic page changes once the slideshow is running. */
const SLIDESHOW_STEP_MS = 14_000;

/** Ignore duplicate events (mousemove etc.) within this window. */
const ACTIVITY_THROTTLE_MS = 400;

/**
 * After auto-navigation, ignore user-activity handlers briefly — route changes
 * often emit scroll / mousemove / focus events that would call resetIdle() and
 * clear the slideshow interval (only one slide before stopping).
 */
const POST_NAV_GRACE_MS = 3_000;

/**
 * After idle on /, /aktionen, or /filiale, cycles those routes slowly.
 * Lives outside MainPageLayout so it is not reset when the route changes.
 */
export default function IdleMainPagesSlideshow() {
  const location = useLocation();
  const navigate = useNavigate();
  const idleTimerRef = useRef(null);
  const slideTimerRef = useRef(null);
  const pathRef = useRef(location.pathname);
  const wasOnMainPageRef = useRef(false);
  const lastActivityRef = useRef(0);
  const ignoreActivityUntilRef = useRef(0);

  const resetIdleRef = useRef(() => {});
  const clearTimersRef = useRef(() => {});

  pathRef.current = location.pathname;

  const clearTimers = useCallback(() => {
    if (idleTimerRef.current != null) {
      clearTimeout(idleTimerRef.current);
      idleTimerRef.current = null;
    }
    if (slideTimerRef.current != null) {
      clearInterval(slideTimerRef.current);
      slideTimerRef.current = null;
    }
  }, []);

  clearTimersRef.current = clearTimers;

  const startSlideshow = useCallback(() => {
    let idx = MAIN_PAGE_PATHS.indexOf(pathRef.current);
    if (idx < 0) idx = 0;
    const advance = () => {
      idx = (idx + 1) % MAIN_PAGE_PATHS.length;
      ignoreActivityUntilRef.current = Date.now() + POST_NAV_GRACE_MS;
      navigate(MAIN_PAGE_PATHS[idx], { replace: true });
    };
    slideTimerRef.current = setInterval(advance, SLIDESHOW_STEP_MS);
  }, [navigate]);

  const resetIdle = useCallback(() => {
    clearTimers();
    if (!MAIN_PAGE_PATHS.includes(pathRef.current)) return;
    idleTimerRef.current = setTimeout(() => {
      idleTimerRef.current = null;
      startSlideshow();
    }, IDLE_MS);
  }, [clearTimers, startSlideshow]);

  resetIdleRef.current = resetIdle;

  useEffect(() => {
    const nowMain = MAIN_PAGE_PATHS.includes(location.pathname);
    if (!nowMain) {
      clearTimers();
      wasOnMainPageRef.current = false;
      return;
    }
    if (!wasOnMainPageRef.current) {
      resetIdle();
    }
    wasOnMainPageRef.current = true;
  }, [location.pathname, clearTimers, resetIdle]);

  useEffect(() => {
    const onActivity = () => {
      const now = Date.now();
      if (now < ignoreActivityUntilRef.current) return;
      if (now - lastActivityRef.current < ACTIVITY_THROTTLE_MS) return;
      lastActivityRef.current = now;
      resetIdleRef.current();
    };

    const events = [
      "mousedown",
      "keydown",
      "touchstart",
      "touchmove",
      "wheel",
      "click",
      "scroll",
    ];
    events.forEach((ev) =>
      window.addEventListener(ev, onActivity, { passive: true })
    );
    window.addEventListener("mousemove", onActivity, { passive: true });

    return () => {
      events.forEach((ev) => window.removeEventListener(ev, onActivity));
      window.removeEventListener("mousemove", onActivity);
      clearTimersRef.current();
    };
  }, []);

  return null;
}
