import { describe, it, expect, beforeEach } from 'vitest';
import { useDevIndices } from '../../resources/js/composables/useDevIndices';

describe('useDevIndices', () => {
    beforeEach(() => {
        // Composable uses module-level singleton — reset for test isolation
        useDevIndices().reset();
    });

    it('initial state: no target, overlay off', () => {
        const dx = useDevIndices();
        expect(dx.currentId.value).toBeNull();
        expect(dx.currentTarget.value).toBeNull();
        expect(dx.overlayMode.value).toBe(false);
    });

    it('setTarget extracts data-dx attribute', () => {
        const dx = useDevIndices();
        const el = document.createElement('div');
        el.setAttribute('data-dx', '1030');
        dx.setTarget(el);
        expect(dx.currentTarget.value).toBe(el);
        expect(dx.currentId.value).toBe(1030);
    });

    it('setTarget(null) clears state', () => {
        const dx = useDevIndices();
        const el = document.createElement('div');
        el.setAttribute('data-dx', '5');
        dx.setTarget(el);
        dx.setTarget(null);
        expect(dx.currentId.value).toBeNull();
    });

    it('toggleOverlay flips overlayMode', () => {
        const dx = useDevIndices();
        expect(dx.overlayMode.value).toBe(false);
        dx.toggleOverlay();
        expect(dx.overlayMode.value).toBe(true);
        dx.toggleOverlay();
        expect(dx.overlayMode.value).toBe(false);
    });

    it('walkToParent finds nearest ancestor with data-dx', () => {
        const dx = useDevIndices();
        const grand = document.createElement('div');
        grand.setAttribute('data-dx', '100');
        const parent = document.createElement('span');
        // parent has NO data-dx — should skip
        const child = document.createElement('button');
        child.setAttribute('data-dx', '200');
        parent.appendChild(child);
        grand.appendChild(parent);
        dx.setTarget(child);
        dx.walkToParent();
        expect(dx.currentId.value).toBe(100);
        expect(dx.currentTarget.value).toBe(grand);
    });

    it('walkToChild finds first descendant with data-dx (DFS/BFS)', () => {
        const dx = useDevIndices();
        const root = document.createElement('div');
        root.setAttribute('data-dx', '1');
        const inner = document.createElement('span');
        inner.setAttribute('data-dx', '2');
        root.appendChild(inner);
        dx.setTarget(root);
        dx.walkToChild();
        expect(dx.currentId.value).toBe(2);
    });

    it('walkToParent at root does nothing', () => {
        const dx = useDevIndices();
        const el = document.createElement('div');
        el.setAttribute('data-dx', '1');
        dx.setTarget(el);
        dx.walkToParent();
        expect(dx.currentId.value).toBe(1);
    });
});
