import { cellToChildren, cellToLatLng, latLngToCell } from 'h3-js';
import { describe, expect, it } from 'vitest';
import type { HexagonData } from '../types';
import { findOverlappingSelectableHexagon, hasMatchingHexagonAtResolution } from './h3-selection';

function hexagonData(h3: string, count: number): HexagonData {
  const [lat, lon] = cellToLatLng(h3);
  return { h3, count, lat, lon };
}

describe('h3 selection helpers', () => {
  it('prefers a matching higher-resolution hexagon that overlaps the previous hexagon', () => {
    const parent = latLngToCell(51.5, -0.1, 8);
    const children = cellToChildren(parent, 9);
    const selected = findOverlappingSelectableHexagon(
      parent,
      [hexagonData(children[0], 0), hexagonData(children[1], 4)],
      9
    );

    expect(selected?.h3).toBe(children[1]);
  });

  it('falls back to a selectable no-match candidate when there is no matching overlap', () => {
    const parent = latLngToCell(51.5, -0.1, 8);
    const nearbyChild = cellToChildren(parent, 9)[0];
    const distant = latLngToCell(52.2, -0.1, 9);

    expect(
      findOverlappingSelectableHexagon(
        parent,
        [hexagonData(nearbyChild, 0), hexagonData(distant, 12)],
        9
      )
    ).toEqual(hexagonData(nearbyChild, 0));
  });

  it('detects when target-resolution matching data is loaded', () => {
    const parent = latLngToCell(51.5, -0.1, 8);
    const child = cellToChildren(parent, 9)[0];

    expect(hasMatchingHexagonAtResolution([hexagonData(child, 1)], 9)).toBe(true);
    expect(hasMatchingHexagonAtResolution([hexagonData(child, 0)], 9)).toBe(false);
    expect(hasMatchingHexagonAtResolution([hexagonData(parent, 1)], 9)).toBe(false);
  });
});
