import { describe, it, expect, beforeEach } from 'vitest';
import '../../core/element.js';
import './agent-artifact.js';

const tick = () => new Promise((r) => queueMicrotask(r));

function mount(html) {
  const wrap = document.createElement('div');
  wrap.innerHTML = html;
  document.body.appendChild(wrap);
  return wrap.firstElementChild;
}

describe('agent-artifact-ui', () => {
  beforeEach(() => { document.body.innerHTML = ''; });

  // Baseline — static slot="primary"/"secondary" buttons route into the header
  // actions cluster, and the default-slot content lands in the body.
  it('routes static action buttons into the header actions cluster (not the body)', async () => {
    const a = mount(`
      <agent-artifact-ui title="Build">
        <button-ui slot="primary">Run</button-ui>
        <button-ui slot="secondary">Cancel</button-ui>
        <p>Body content</p>
      </agent-artifact-ui>
    `);
    await tick();
    const actions = a.querySelector('[data-artifact-actions]');
    const body = a.querySelector('[data-artifact-body]');
    expect(actions).toBeTruthy();
    expect(actions.querySelectorAll('[slot="primary"], [slot="secondary"]').length).toBe(2);
    expect(body.querySelectorAll('[slot="primary"], [slot="secondary"]').length).toBe(0);
    expect(body.textContent).toContain('Body content');
  });

  // Wrapper-trap regression (audit-wrapper-trap arm 2): action buttons rendered
  // via `.map()`/`repeat()` arrive nested in the template engine's
  // display:contents / role="presentation" wrapper spans. The old `:scope >
  // [slot="primary"]` direct-child grab missed them, so `innerHTML = ''`
  // stranded them in the body. They must reach the actions cluster.
  it('routes WRAPPED (interpolated) action buttons into the actions cluster, not the body', async () => {
    const a = mount(`
      <agent-artifact-ui title="Build">
        <span style="display:contents" role="presentation">
          <span style="display:contents" role="presentation"><button-ui slot="primary">Run</button-ui></span>
          <span style="display:contents" role="presentation"><button-ui slot="secondary">Cancel</button-ui></span>
        </span>
        <p>Body content</p>
      </agent-artifact-ui>
    `);
    await tick();
    const actions = a.querySelector('[data-artifact-actions]');
    const body = a.querySelector('[data-artifact-body]');
    expect(actions.querySelectorAll('[slot="primary"], [slot="secondary"]').length).toBe(2);
    // The regression: before the wrapper-pierce fix these landed in the body.
    expect(body.querySelectorAll('[slot="primary"], [slot="secondary"]').length).toBe(0);
    expect(body.textContent).toContain('Body content');
    // No empty wrapper spans left dangling — they're flattened, not re-appended.
    expect(a.querySelectorAll('[role="presentation"]').length).toBe(0);
  });
});
