"use client";

import { useEffect } from "react";
import { Capacitor } from "@capacitor/core";
import { App } from "@capacitor/app";
import { useUIStore } from "@/lib/ui-store";

/**
 * Maps the Android hardware back button to in-app navigation:
 * go back a screen, or exit the app when already at home.
 * No-op on web (Capacitor.isNativePlatform() is false).
 */
export function CapacitorBack() {
  useEffect(() => {
    if (!Capacitor.isNativePlatform()) return;
    let remove: (() => void) | undefined;
    App.addListener("backButton", () => {
      if (useUIStore.getState().screen === "home") {
        App.exitApp();
      } else {
        window.history.back();
      }
    }).then((h) => {
      remove = () => h.remove();
    });
    return () => remove?.();
  }, []);
  return null;
}
