import axios from 'axios';
import { getCurrentInstance } from 'vue'

const navigate = async ({ page }) => {
  try {
    // Show loading spinner if you want
    loading.value = true;

    // Request page data from server
    const response = await axios.get(`/${page}`);
    const data = response.data;

    // Expected server response:
    // { component: 'Home', props: {...} }
    currentPage.value = data.component;
    currentProps.value = data.props || {};
  } catch (error) {
    console.error('Navigation error', error);
    currentPage.value = 'NotFound';
    currentProps.value = {};
  } finally {
    loading.value = false;
  }
};

/**
 * Reloads the current SPA page
 * without changing history.
 *
 * Vue replacement for legacy ReloadPage()
 */
export function reloadPage() {
  const instance = getCurrentInstance()

  const navigate =
    instance?.proxy?.$navigate ||
    window.$navigate

  if (!navigate) {
    console.warn('No SPA navigator available')
    return
  }

  navigate({
    page: instance.proxy.currentPage,
    props: instance.proxy.currentProps,
    nohistory: true,
    redundantpage: true
  })
}