"use client";

// The payment currently open in the gateway tab. Two ways back:
//   1. deep link rangook://payment/result → /payment/result, which settles it;
//   2. the tab is closed without a result → back to `returnTo` (the course page).
// Both can fire for one return, so (2) waits briefly and yields to (1).

const DEEP_LINK_GRACE_MS = 800;

let pending: { returnTo: string } | null = null;

export function beginPayment(returnTo: string): void {
    pending = { returnTo };
}

/** A result arrived by deep link: nothing left to do on close. */
export function settlePayment(): void {
    pending = null;
}

/** The gateway tab closed: go to the return route unless a deep link settles it first. */
export function onGatewayClosed(navigate: (route: string) => void): void {
    if (!pending) return;

    setTimeout(() => {
        const unresolved = pending;
        pending = null;
        if (unresolved) navigate(unresolved.returnTo);
    }, DEEP_LINK_GRACE_MS);
}
