"use client";

import { useEffect, useState } from "react";

let ourClientId: string | null = null;

export function useDraftLock(rkey: string): { hasConflict: boolean; canSave: boolean } {
  const lockName = `sidetrail-draft-${rkey}`;
  const [canSave, setCanSave] = useState(false);
  const [hasConflict, setHasConflict] = useState(false);

  useEffect(() => {
    const abortController = new AbortController();

    async function acquireLock() {
      const state = await navigator.locks.query();
      const heldLock = state.held?.find((l) => l.name === lockName);

      if (abortController.signal.aborted) return;

      if (heldLock) {
        if (ourClientId && heldLock.clientId === ourClientId) {
          await navigator.locks.request(lockName, { steal: true }, async () => {
            if (abortController.signal.aborted) return;
            setCanSave(true);
            await new Promise<void>((resolve) => {
              abortController.signal.addEventListener("abort", () => resolve());
            });
          });
        } else {
          setHasConflict(true);
        }
      } else {
        await navigator.locks.request(lockName, { ifAvailable: true }, async (lock) => {
          if (abortController.signal.aborted) return;

          if (lock === null) {
            setHasConflict(true);
            return;
          }

          const newState = await navigator.locks.query();
          const ourLock = newState.held?.find((l) => l.name === lockName);
          if (ourLock) {
            ourClientId = ourLock.clientId ?? null;
          }

          if (abortController.signal.aborted) return;

          setCanSave(true);
          await new Promise<void>((resolve) => {
            abortController.signal.addEventListener("abort", () => resolve());
          });
        });
      }
    }

    acquireLock();

    return () => {
      abortController.abort();
    };
  }, [lockName]);

  return { hasConflict, canSave };
}
