import { describe, it, expect, beforeEach } from 'vitest';
import { logicalChildren, logicalSlotted } from './logical-children.js';

function host(html) {
  const el = document.createElement('div');
  el.innerHTML = html;
  return el;
}

describe('logical-children', () => {
  beforeEach(() => { document.body.innerHTML = ''; });

  it('returns static direct children as-is', () => {
    const h = host(`<button slot="primary">A</button><p>body</p><button slot="secondary">B</button>`);
    expect(logicalChildren(h).map((e) => e.tagName)).toEqual(['BUTTON', 'P', 'BUTTON']);
    expect(logicalSlotted(h, 'primary').length).toBe(1);
    expect(logicalSlotted(h, 'secondary')[0].textContent).toBe('B');
    expect(logicalSlotted(h, 'missing').length).toBe(0);
  });

  it('pierces a single display:contents/role=presentation wrapper', () => {
    const h = host(`
      <span style="display:contents" role="presentation"><button slot="primary">A</button></span>
      <p>body</p>
    `);
    // Without piercing, h.querySelector(':scope > [slot="primary"]') would be null:
    expect(h.querySelector(':scope > [slot="primary"]')).toBeNull();
    // With the helper, it's found:
    expect(logicalSlotted(h, 'primary').length).toBe(1);
    expect(logicalChildren(h).map((e) => e.tagName)).toEqual(['BUTTON', 'P']);
  });

  it('pierces NESTED wrappers (the .map() shape)', () => {
    const h = host(`
      <span style="display:contents" role="presentation">
        <span style="display:contents" role="presentation"><button slot="act">A</button></span>
        <span style="display:contents" role="presentation"><button slot="act">B</button></span>
      </span>
    `);
    expect(logicalSlotted(h, 'act').map((e) => e.textContent)).toEqual(['A', 'B']);
  });

  it('does NOT pierce non-wrapper elements (logical = direct, wrappers aside)', () => {
    const h = host(`<div><button slot="primary">nested-in-real-div</button></div>`);
    // The button is inside a real <div>, not a transparent wrapper → not a logical child.
    expect(logicalSlotted(h, 'primary').length).toBe(0);
    expect(logicalChildren(h).map((e) => e.tagName)).toEqual(['DIV']);
  });

  it('tolerates a null host', () => {
    expect(logicalChildren(null)).toEqual([]);
    expect(logicalSlotted(null, 'x')).toEqual([]);
  });
});
