import React, { setGlobal } from "reactn";
import { StackActions } from "@react-navigation/native";

import { isDesktop } from "../hooks/useLayoutType";
import { Routes } from "./Routes";

export const navigationRef = React.createRef();

export function navigate(name, params) {
  navigationRef.current?.navigate(name, params);
}

export function push(name, params) {
  if (!navigationRef.current) return;
  try {
    navigationRef.current.dispatch(StackActions.push(name, params));
  } catch (e) {
    // Fallback to navigate if push not available
    navigationRef.current?.navigate?.(name, params);
  }
}

export function dispatch(route) {
  navigationRef.current?.dispatch(route);
}

export function reset(route) {
  navigationRef.current?.reset(route);
}

export function goBack() {
  navigationRef.current?.goBack();
}

export const navigateToTask = (taskData = {}) => {
  if (isDesktop) {
    setGlobal({ currentTaskData: taskData });
  } else {
    navigate(Routes.TaskDetails, taskData);
  }
};
