import { useEffect, useState } from "react";
import { App as CapacitorApp } from "@capacitor/app";
import { Network } from "@capacitor/network";
import { request } from "../../app/api.js";
import { createConnectionRecoveryCoordinator } from "./connection-recovery.js";

export function useConnectionRecovery() {
  const [state, setState] = useState("online");
  const [recoveryVersion, setRecoveryVersion] = useState(0);

  useEffect(() => {
    let active = true;
    const handles = [];
    const coordinator = createConnectionRecoveryCoordinator({
      verify: () => request("/health"),
      recover: () => { if (active) setRecoveryVersion((current) => current + 1); },
      onState: (next) => { if (active) setState(next); }
    });
    const networkChanged = (status) => coordinator.networkChanged(Boolean(status.connected));
    const online = () => void coordinator.networkChanged(true);
    const offline = () => void coordinator.networkChanged(false);

    const keepHandle = (handle) => active ? handles.push(handle) : void handle.remove();
    void Network.addListener("networkStatusChange", networkChanged).then(keepHandle);
    void CapacitorApp.addListener("appStateChange", ({ isActive }) => coordinator.appStateChanged(isActive)).then(keepHandle);
    void Network.getStatus().then(networkChanged).catch(() => {});
    globalThis.addEventListener?.("online", online);
    globalThis.addEventListener?.("offline", offline);

    return () => {
      active = false;
      coordinator.dispose();
      for (const handle of handles) void handle.remove();
      globalThis.removeEventListener?.("online", online);
      globalThis.removeEventListener?.("offline", offline);
    };
  }, []);

  return { state, recoveryVersion };
}
