import json
import subprocess
from pathlib import Path


CONTROLLER = Path(__file__).resolve().parents[1] / "frontend" / "mobile-search-preview-nav.js"
FRONTEND = CONTROLLER.parent


def run_navigation(scenario: str) -> dict:
    script = f"""
const createNavigation = require({json.dumps(str(CONTROLLER))});
class FakeElement {{
  constructor(name) {{
    this.name=name; this.listeners={{}}; this.attributes={{}}; this.scrolls=[];
    this.focuses=0; this.hidden=false;
  }}
  addEventListener(name, callback) {{ this.listeners[name]=callback; }}
  removeEventListener(name) {{ delete this.listeners[name]; }}
  click() {{ this.listeners.click?.({{preventDefault() {{}}}}); }}
  setAttribute(name,value) {{ this.attributes[name]=value; }}
  removeAttribute(name) {{ delete this.attributes[name]; }}
  scrollIntoView(options) {{ this.scrolls.push(options); }}
  focus(options) {{ this.focuses += 1; this.focusOptions=options; }}
}}
{scenario}
"""
    result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
    assert result.returncode == 0, result.stderr
    return json.loads(result.stdout)


def test_mobile_search_preview_navigation_completes_the_workflow_and_gates_reply():
    result = run_navigation("""
const names=['overview','conversation','reply','actions'];
const buttons=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const targets=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const navigation=createNavigation({buttons,targets,prefersReducedMotion:()=>true});
navigation.start();
navigation.setReplyAvailable(false);
buttons.reply.click();
const unavailableScrolls=targets.reply.scrolls.length;
navigation.setReplyAvailable(true);
buttons.conversation.click();
buttons.reply.click();
buttons.actions.click();
const selected=Object.fromEntries(Object.entries(buttons).map(([name,button])=>[name,button.attributes['aria-current']||null]));
navigation.stop();
process.stdout.write(JSON.stringify({
  unavailableScrolls,
  replyDisabled:buttons.reply.attributes['aria-disabled']||null,
  conversation:targets.conversation.scrolls,
  reply:targets.reply.scrolls,
  replyFocuses:targets.reply.focuses,
  actions:targets.actions.scrolls,
  selected,
  listeners:Object.values(buttons).map(button=>Object.keys(button.listeners).length),
}));
""")

    assert result == {
        "unavailableScrolls": 0,
        "replyDisabled": None,
        "conversation": [{"block": "start", "behavior": "auto"}],
        "reply": [{"block": "start", "behavior": "auto"}],
        "replyFocuses": 1,
        "actions": [{"block": "start", "behavior": "auto"}],
        "selected": {
            "overview": None,
            "conversation": None,
            "reply": None,
            "actions": "location",
        },
        "listeners": [0, 0, 0, 0],
    }


def test_mobile_search_preview_navigation_tracks_panel_sections_and_resets_for_next_result():
    result = run_navigation("""
const names=['overview','conversation','reply','actions'];
const buttons=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const targets=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const root=new FakeElement('panel');
let callback; let observedRoot; let disconnected=0;
const navigation=createNavigation({
  buttons,targets,root,
  observe(handler,observed,rootOption){callback=handler; observedRoot=rootOption; return {disconnect(){disconnected++;}};},
});
navigation.start();
callback([{target:targets.overview,isIntersecting:true,intersectionRatio:.2},{target:targets.conversation,isIntersecting:true,intersectionRatio:.8}]);
navigation.reset(false);
const selected=Object.fromEntries(Object.entries(buttons).map(([name,button])=>[name,button.attributes['aria-current']||null]));
navigation.stop();
process.stdout.write(JSON.stringify({selected,replyDisabled:buttons.reply.attributes['aria-disabled'],observedRoot:observedRoot.name,disconnected}));
""")

    assert result == {
        "selected": {"overview": "location", "conversation": None, "reply": None, "actions": None},
        "replyDisabled": "true",
        "observedRoot": "panel",
        "disconnected": 1,
    }


def test_search_preview_ships_mobile_navigation_in_the_offline_bundle():
    html = (FRONTEND / "index.html").read_text()
    css = (FRONTEND / "dashboard.css").read_text()
    navigation_js = CONTROLLER.read_text()
    bundle = (FRONTEND.parent / "src" / "frontend_bundle.py").read_text()
    service_worker = (FRONTEND / "service-worker.js").read_text()

    assert '<nav class="mobile-search-preview-nav"' in html
    assert 'aria-label="Search preview sections"' in html
    for name, label in (
        ("overview", "Overview"),
        ("conversation", "Conversation"),
        ("reply", "Reply"),
        ("actions", "Act"),
    ):
        assert f'data-search-preview-section="{name}"' in html
        assert f">{label}</button>" in html
    assert 'id="search-preview-overview"' in html
    assert 'id="search-preview-reply-workspace"' in html
    assert 'id="search-preview-actions"' in html
    assert '<script src="static/mobile-search-preview-nav.js"></script>' in html
    assert '"static/mobile-search-preview-nav.js"' in bundle
    assert "attachMobileSearchPreviewNavigation({document, window})" in navigation_js
    assert "navigation.reset(!reply.hidden)" in navigation_js
    assert "attributeFilter:['hidden']" in navigation_js
    assert "static/mobile-search-preview-nav.js" in service_worker
    assert ".mobile-search-preview-nav" in css
    assert "grid-template-columns:repeat(4,minmax(0,1fr))" in css
    assert "min-height:44px" in css
    assert "env(safe-area-inset-top)" in css
    assert "#search-preview-actions { position:static" in css
