"""Verify the dock-from-floating fix."""
import asyncio
from playwright.async_api import async_playwright


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            executable_path="/root/.cache/ms-playwright/chromium-1223/chrome-linux/chrome",
            args=["--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu"],
        )
        ctx = await browser.new_context(viewport={"width": 1400, "height": 900})
        page = await ctx.new_page()
        await page.goto("http://localhost:8765/demo/admin-launcher-test.html", wait_until="networkidle", timeout=10000)
        await page.wait_for_selector("#buttonGrid .btn", timeout=10000)
        await page.wait_for_timeout(300)

        # Open the first panel (Pages) which spawns as floating
        await page.evaluate("""() => {
            const btn = document.querySelectorAll('#buttonGrid .btn')[0];
            btn.click();
        }""")
        await page.wait_for_timeout(200)

        # Dock it on the right
        await page.evaluate("window.PanelManager.get().dock('fvcms-admin-pages', 'right')")
        await page.wait_for_timeout(200)

        # Now detach it (becomes floating, pill stays on right)
        await page.evaluate("window.PanelManager.get().detach('fvcms-admin-pages')")
        await page.wait_for_timeout(200)

        # Now dock it on the LEFT
        await page.evaluate("window.PanelManager.get().dock('fvcms-admin-pages', 'left')")
        await page.wait_for_timeout(300)

        # Inspect: how many pills are in each dock?
        info = await page.evaluate("""() => {
            const docks = document.querySelectorAll('.fvcms-dock');
            return Array.from(docks).map(d => ({
                edge: d.getAttribute('data-dock-edge'),
                pillCount: d.querySelectorAll('.fvcms-dock-pill').length,
                pills: Array.from(d.querySelectorAll('.fvcms-dock-pill')).map(p => p.getAttribute('data-pm-panel-id')),
            }));
        }""")
        print("Docks after dock-right → detach → dock-left:")
        for d in info:
            print(f"  edge={d['edge']} pillCount={d['pillCount']} pills={d['pills']}")
        pages_locations = sum(1 for d in info if 'fvcms-admin-pages' in (d['pills'] or []))
        total_pills = sum(d['pillCount'] for d in info)
        if pages_locations == 1 and total_pills == 1:
            print(f"  PASS: Pages pill in exactly 1 dock (left), no duplication")
        else:
            print(f"  FAIL: Pages in {pages_locations} docks, total pills = {total_pills}")

        await page.screenshot(path="/workspace/freshvibe-cms/aux-tests/launcher/state-audit/dock-fix-verify.png")
        print("  Saved dock-fix-verify.png")
        await browser.close()


asyncio.run(main())
