import { useRef, useState } from 'react';
import { useMatrixClient } from './useMatrixClient';
import { useTauriEvent } from './useTauri';

/** Detail shape of the `network-changed` event emitted by the native side. */
type NetworkChangedDetail = {
  online: boolean;
};

/**
 * P5-49 — Network awareness (desktop). Subscribes to the native
 * `network-changed` event (Windows Network List Manager poll, `{ online }`) and,
 * on a transition back to online, calls `mx.retryImmediately()` so the sync loop
 * retries its backed-off `/sync` at once instead of waiting out the backoff
 * timer. Returns the last known connectivity (`undefined` until the first
 * event). Inert in the browser, since `useTauriEvent` only listens under Tauri.
 */
export function useTauriNetwork(): boolean | undefined {
  const mx = useMatrixClient();
  const [online, setOnline] = useState<boolean | undefined>(undefined);
  // Track the previous value in a ref so we can detect an offline -> online
  // transition without adding it to a dependency list.
  const onlineRef = useRef<boolean | undefined>(undefined);

  useTauriEvent<NetworkChangedDetail>('network-changed', ({ online: next }) => {
    const previous = onlineRef.current;
    onlineRef.current = next;
    setOnline(next);
    // Only nudge the client when connectivity is (re)gained. The initial event
    // (previous === undefined) also triggers a retry, which is safe: it's a
    // no-op if nothing is backed off.
    if (next && previous !== true) {
      mx.retryImmediately();
    }
  });

  return online;
}
