import { describe, it, expect, beforeEach } from 'vitest';
import '../../core/element.js';
import './fields.js';
import '../field/field.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('fields-ui', () => {
  beforeEach(() => { document.body.innerHTML = ''; });

  it('registers the custom element', () => {
    expect(customElements.get('fields-ui')).toBeDefined();
  });

  it('hosts <field-ui> children without altering them by default', () => {
    const f = mount(`
      <fields-ui>
        <field-ui label="A"><input id="a" /></field-ui>
        <field-ui label="B"><input id="b" /></field-ui>
      </fields-ui>
    `);
    const fields = f.querySelectorAll('field-ui');
    expect(fields).toHaveLength(2);
    // Default — neither child has [inline] propagated.
    expect(fields[0].hasAttribute('inline')).toBe(false);
    expect(fields[1].hasAttribute('inline')).toBe(false);
  });

  it('propagates [inline] to every direct <field-ui> child on connect', async () => {
    const f = mount(`
      <fields-ui inline>
        <field-ui label="A"><input id="a" /></field-ui>
        <field-ui label="B"><input id="b" /></field-ui>
      </fields-ui>
    `);
    await tick();
    const fields = f.querySelectorAll('field-ui');
    for (const child of fields) {
      expect(child.hasAttribute('inline')).toBe(true);
    }
  });

  it('removes inline from children when [inline] is removed from host', async () => {
    const f = mount(`
      <fields-ui inline>
        <field-ui label="A"><input id="a" /></field-ui>
        <field-ui label="B"><input id="b" /></field-ui>
      </fields-ui>
    `);
    await tick();
    f.removeAttribute('inline');
    await tick();
    const fields = f.querySelectorAll('field-ui');
    for (const child of fields) {
      expect(child.hasAttribute('inline')).toBe(false);
    }
  });

  it('re-syncs inline when a new <field-ui> is appended later', async () => {
    const f = mount(`<fields-ui inline></fields-ui>`);
    await tick();
    const child = document.createElement('field-ui');
    child.setAttribute('label', 'Late');
    f.appendChild(child);
    // MutationObserver fires async — give it a microtask.
    await new Promise((r) => setTimeout(r, 0));
    expect(child.hasAttribute('inline')).toBe(true);
  });

  it('does not propagate [inline] to non-field children', async () => {
    const f = mount(`
      <fields-ui inline>
        <field-ui label="A"><input id="a" /></field-ui>
        <span class="separator">—</span>
      </fields-ui>
    `);
    await tick();
    const span = f.querySelector('.separator');
    expect(span.hasAttribute('inline')).toBe(false);
  });
});
