import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { intersectionObserver } from './intersection-observer.js';
import { mountHost, connectTrait, resetDOM } from '../test-helpers.js';

describe('intersection-observer', () => {
  let originalIO;

  beforeEach(() => {
    resetDOM();
    originalIO = globalThis.IntersectionObserver;
  });

  afterEach(() => {
    if (originalIO) globalThis.IntersectionObserver = originalIO;
    else delete globalThis.IntersectionObserver;
  });

  it('without IntersectionObserver: gracefully no-ops on connect', () => {
    delete globalThis.IntersectionObserver;
    const host = mountHost();
    expect(() => connectTrait(intersectionObserver, host)).not.toThrow();
  });

  it('with mocked IntersectionObserver: observe() is called on connect', () => {
    const observe = vi.fn();
    const ioDisconnect = vi.fn();
    globalThis.IntersectionObserver = function MockIO() {
      this.observe = observe;
      this.disconnect = ioDisconnect;
      this.unobserve = vi.fn();
    };
    const host = mountHost('div', { 'data-intersection-threshold': '0.5' });
    const inst = connectTrait(intersectionObserver, host);
    expect(observe).toHaveBeenCalledWith(host);
    inst.disconnect(host);
    expect(ioDisconnect).toHaveBeenCalled();
  });
});
