import json
import subprocess
from pathlib import Path


CONTROLLER = Path(__file__).resolve().parents[1] / "frontend" / "mobile-create-issue-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.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); }}
}}
{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_create_issue_navigation_gates_file_and_navigates_with_reduced_motion():
    result = run_navigation("""
const buttons=Object.fromEntries(['describe','evidence','file'].map(name=>[name,new FakeElement(name)]));
const targets=Object.fromEntries(['describe','evidence','file'].map(name=>[name,new FakeElement(name)]));
targets.file.hidden=true;
const navigation=createNavigation({buttons,targets,filing:targets.file,prefersReducedMotion:()=>true});
navigation.start();
const initiallyDisabled=buttons.file.attributes['aria-disabled'];
buttons.file.click();
const beforeReveal=targets.file.scrolls.length;
targets.file.hidden=false;
navigation.setFilingAvailable(true);
buttons.file.click();
const selected=Object.fromEntries(Object.entries(buttons).map(([name,button])=>[name,button.attributes['aria-current']||null]));
navigation.stop();
process.stdout.write(JSON.stringify({initiallyDisabled,beforeReveal,scrolls:targets.file.scrolls,selected,listeners:Object.values(buttons).map(button=>Object.keys(button.listeners).length)}));
""")

    assert result == {
        "initiallyDisabled": "true",
        "beforeReveal": 0,
        "scrolls": [{"block": "start", "behavior": "auto"}],
        "selected": {"describe": None, "evidence": None, "file": "location"},
        "listeners": [0, 0, 0],
    }


def test_mobile_create_issue_navigation_tracks_visible_panel_sections_and_resets():
    result = run_navigation("""
const buttons=Object.fromEntries(['describe','evidence','file'].map(name=>[name,new FakeElement(name)]));
const targets=Object.fromEntries(['describe','evidence','file'].map(name=>[name,new FakeElement(name)]));
let callback; let observedRoot; let disconnected=0;
const root=new FakeElement('panel');
const navigation=createNavigation({buttons,targets,root,filing:targets.file,observe(handler,observed,rootOption){callback=handler; observedRoot=rootOption; return {disconnect(){disconnected++;}};}});
navigation.start();
callback([{target:targets.describe,isIntersecting:true,intersectionRatio:.2},{target:targets.evidence,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,fileDisabled:buttons.file.attributes['aria-disabled'],observedRoot:observedRoot.name,disconnected}));
""")

    assert result == {
        "selected": {"describe": "location", "evidence": None, "file": None},
        "fileDisabled": "true",
        "observedRoot": "panel",
        "disconnected": 1,
    }


def test_new_issue_sheet_ships_mobile_navigation_in_lazy_offline_feature():
    html = (FRONTEND / "index.html").read_text()
    css = (FRONTEND / "dashboard.css").read_text()
    dashboard_js = (FRONTEND / "dashboard.js").read_text()
    navigation_js = CONTROLLER.read_text()
    bundle = (FRONTEND.parent / "src" / "frontend_bundle.py").read_text()

    assert '<nav class="mobile-create-issue-nav"' in html
    assert 'aria-label="New issue sections"' in html
    for name, label in (("describe", "Describe"), ("evidence", "Evidence"), ("file", "File")):
        assert f'data-create-issue-section="{name}"' in html
        assert f">{label}</button>" in html
    assert 'id="create-issue-describe"' in html
    assert 'id="create-issue-attachment"' in html
    assert 'id="create-issue-filing"' in html
    assert '<script src="static/mobile-create-issue-nav.js"></script>' in html
    assert '"static/mobile-create-issue-nav.js"' in bundle
    assert "attachMobileCreateIssueNavigation({document, window})" in navigation_js
    assert "attachMobileCreateIssueNavigation({document, window})" not in dashboard_js
    assert "attributeFilter:['hidden']" in navigation_js
    assert "setTimeout(() => navigation.navigate('file'), 0)" in navigation_js
    assert "navigation.navigate('file')" in navigation_js
    assert "navigation.reset(" in navigation_js
    assert ".mobile-create-issue-nav" in css
    assert "position:sticky" in css
    assert "min-height:44px" in css
    assert "grid-template-columns:repeat(3,minmax(0,1fr))" in css
    assert "env(safe-area-inset-top)" in css
