import { describe, expect, it } from 'vitest';
import { hintsLeft, hintGateRemainingMs, hintLockMinutes } from './hints';

// view carries only the field hintsLeft reads (the per-game allowance).
const view = (hintsRemaining: number) => ({ hintsRemaining });

describe('hintsLeft', () => {
  it('is zero without a view', () => {
    expect(hintsLeft(null, 5)).toBe(0);
  });

  it('adds the per-game allowance to the live wallet', () => {
    expect(hintsLeft(view(1), 3)).toBe(4); // allowance 1 + wallet 3
  });

  it('reflects the LIVE wallet, not the view (the staleness fix)', () => {
    // A wallet hint spent in another game since this view was fetched → the live wallet is 2, so the
    // count is 1 + 2 = 3. The wallet is always passed live (from the profile), never read off the view.
    expect(hintsLeft(view(1), 2)).toBe(3);
  });

  it('shows just the wallet when the per-game allowance is used up', () => {
    expect(hintsLeft(view(0), 3)).toBe(3); // allowance 0 + wallet 3
  });

  it('clamps negatives', () => {
    expect(hintsLeft(view(1), -5)).toBe(1); // a negative wallet clamps to 0
    expect(hintsLeft(view(-2), 3)).toBe(3); // a negative allowance clamps to 0
  });
});

describe('hintGateRemainingMs (the vs_ai idle-hint gate, monotonic)', () => {
  it('is 0 when the gate is open — a null anchor (the human first move, or a non-gated game)', () => {
    expect(hintGateRemainingMs(null, 60_000, 5000)).toBe(0);
  });

  it('is the window remaining minus the monotonic time elapsed since the anchor', () => {
    // anchored at mono 1000 with 60s left; 20s of monotonic time later -> 40s left.
    expect(hintGateRemainingMs(1000, 60_000, 1000 + 20_000)).toBe(40_000);
  });

  it('is 0 once the elapsed monotonic time reaches (or passes) the window', () => {
    expect(hintGateRemainingMs(1000, 60_000, 1000 + 60_000)).toBe(0);
    expect(hintGateRemainingMs(1000, 60_000, 1000 + 90_000)).toBe(0);
  });
});

describe('hintLockMinutes (the toast N, rounded up)', () => {
  it('rounds up to whole minutes, so a still-closed gate never reads 0', () => {
    expect(hintLockMinutes(1)).toBe(1);
    expect(hintLockMinutes(60_000)).toBe(1);
    expect(hintLockMinutes(61_000)).toBe(2);
    expect(hintLockMinutes(29 * 60_000)).toBe(29);
  });

  it('is 0 when nothing remains', () => {
    expect(hintLockMinutes(0)).toBe(0);
  });
});
