/**
 * Capacitor / WebView platform helpers (#24 / #22).
 * Prefer window.Capacitor so unit tests and web builds need no Capacitor package.
 */

/**
 * @returns {boolean}
 */
export function isNativePlatform() {
  if (typeof window === "undefined") {
    return false;
  }
  const Cap = window.Capacitor;
  if (!Cap) {
    return false;
  }
  if (typeof Cap.isNativePlatform === "function") {
    return Cap.isNativePlatform();
  }
  return Cap.isNative === true;
}

/**
 * Absolute in-app path for full page navigations.
 * Native Capacitor builds use HashRouter (#24); web keeps BrowserRouter paths.
 *
 * @param {string} path e.g. "/signin/"
 * @returns {string}
 */
export function appHref(path) {
  const normalized = path.startsWith("/") ? path : `/${path}`;
  if (isNativePlatform()) {
    return `/#${normalized}`;
  }
  return normalized;
}

/**
 * Navigate the top-level window to an in-app route (auth failure, forced logout).
 * @param {string} path
 */
export function redirectToAppPath(path) {
  if (typeof window === "undefined") {
    return;
  }
  if (isNativePlatform()) {
    const normalized = path.startsWith("/") ? path : `/${path}`;
    window.location.hash = `#${normalized}`;
    return;
  }
  window.location.href = appHref(path);
}

/**
 * Router class for the current runtime.
 * HashRouter on Capacitor so nested routes reload without a server rewrite.
 * BrowserRouter on web (nginx already rewrites to index.html).
 *
 * @returns {typeof import('react-router-dom').HashRouter | typeof import('react-router-dom').BrowserRouter}
 */
export function getAppRouter() {
  // Lazy require keeps this module usable from axios (no React import cycle in tests).
  const { BrowserRouter, HashRouter } = require("react-router-dom");
  return isNativePlatform() ? HashRouter : BrowserRouter;
}
