import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
import { BackHandler } from "react-native";

export type Route = "home" | "text" | "image" | "datacards" | "settings";

interface RouterContextValue {
  route: Route;
  navigate: (to: Route) => void;
  goBack: () => boolean;
}

const RouterContext = createContext<RouterContextValue | null>(null);

export function RouterProvider({ children }: { children: React.ReactNode }) {
  const [route, setRoute] = useState<Route>("home");
  const history = useRef<Route[]>([]);

  const navigate = useCallback((to: Route) => {
    setRoute((prev) => {
      history.current.push(prev);
      return to;
    });
  }, []);

  const goBack = useCallback((): boolean => {
    const prev = history.current.pop();
    if (prev !== undefined) {
      setRoute(prev);
      return true;
    }
    return false;
  }, []);

  useEffect(() => {
    const sub = BackHandler.addEventListener("hardwareBackPress", goBack);
    return () => sub.remove();
  }, [goBack]);

  return (
    <RouterContext.Provider value={{ route, navigate, goBack }}>
      {children}
    </RouterContext.Provider>
  );
}

export function useRouter(): RouterContextValue {
  const ctx = useContext(RouterContext);
  if (!ctx) throw new Error("useRouter must be used inside <RouterProvider>");
  return ctx;
}
