import React, { createContext, useEffect, useState } from "react";
import { App as CapacitorApp } from "@capacitor/app";
import { platformRuntime } from "../platform/runtime.js";
import { createBackNavigation } from "./back-navigation.js";

export const BackNavigationContext = createContext(null);

export function BackNavigationProvider({ children }) {
  const [navigation] = useState(() => createBackNavigation({
    history: globalThis.history,
    eventTarget: globalThis
  }));
  useEffect(() => () => navigation.dispose(), [navigation]);
  useEffect(() => {
    if (!platformRuntime.isAndroid) return undefined;
    let listener;
    void CapacitorApp.addListener("backButton", () => {
      if (!navigation.back()) void CapacitorApp.minimizeApp();
    }).then((handle) => { listener = handle; });
    return () => { void listener?.remove(); };
  }, [navigation]);
  return <BackNavigationContext.Provider value={navigation}>{children}</BackNavigationContext.Provider>;
}
