import json
import subprocess
from pathlib import Path


CONTROLLER = Path(__file__).resolve().parents[1] / "frontend" / "mobile-find-work-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.hidden=false; this.disabled=false; this.focused=0; }}
  addEventListener(name, callback) {{ (this.listeners[name] ||= []).push(callback); }}
  removeEventListener(name, callback) {{ this.listeners[name]=(this.listeners[name]||[]).filter(item=>item!==callback); }}
  click() {{ for (const callback of this.listeners.click||[]) callback({{preventDefault(){{}}}}); }}
  setAttribute(name,value) {{ this.attributes[name]=value; }}
  removeAttribute(name) {{ delete this.attributes[name]; }}
  focus() {{ this.focused++; }}
}}
class FakeEvents {{
  constructor() {{ this.listeners={{}}; }}
  addEventListener(name, callback) {{ (this.listeners[name] ||= []).push(callback); }}
  removeEventListener(name, callback) {{ this.listeners[name]=(this.listeners[name]||[]).filter(item=>item!==callback); }}
  emit(name,event) {{ for (const callback of this.listeners[name]||[]) callback(event); }}
}}
{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_find_work_navigation_gates_review_and_fit_until_work_is_selected():
    result = run_navigation("""
const names=['discover','review','fit'];
const buttons=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const sections=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const events=new FakeEvents();
const history={state:{taskOverlay:'find'}, pushes:[], backs:0,
 pushState(state){this.state=state;this.pushes.push(state);}, back(){this.backs++;}};
const navigation=createNavigation({buttons,sections,history,eventTarget:events,onStageChange:()=>{}});
navigation.start();
const initial={stage:navigation.stage(),reviewDisabled:buttons.review.disabled,fitDisabled:buttons.fit.disabled,hidden:Object.fromEntries(names.map(name=>[name,sections[name].hidden]))};
navigation.sync({selectedCount:2,recovery:false});
buttons.review.click();
buttons.fit.click();
process.stdout.write(JSON.stringify({initial,stage:navigation.stage(),pushes:history.pushes,selected:Object.fromEntries(names.map(name=>[name,buttons[name].attributes['aria-current']||null]))}));
""")

    assert result == {
        "initial": {
            "stage": "discover",
            "reviewDisabled": True,
            "fitDisabled": True,
            "hidden": {"discover": False, "review": True, "fit": True},
        },
        "stage": "fit",
        "pushes": [
            {"taskOverlay": "find", "findWorkStage": "review"},
            {"taskOverlay": "find", "findWorkStage": "fit"},
        ],
        "selected": {"discover": None, "review": None, "fit": "step"},
    }


def test_browser_back_moves_fit_to_review_to_discover_without_losing_selection():
    result = run_navigation("""
const names=['discover','review','fit'];
const buttons=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const sections=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const events=new FakeEvents(); const changes=[];
const history={state:{taskOverlay:'find'},pushState(state){this.state=state;},back(){}};
const navigation=createNavigation({buttons,sections,history,eventTarget:events,onStageChange:stage=>changes.push(stage)});
navigation.start(); navigation.sync({selectedCount:1,recovery:false}); navigation.go('review'); navigation.go('fit');
events.emit('popstate',{state:{taskOverlay:'find',findWorkStage:'review'}});
const afterFirst=navigation.stage();
events.emit('popstate',{state:{taskOverlay:'find'}});
process.stdout.write(JSON.stringify({afterFirst,afterSecond:navigation.stage(),changes,reviewDisabled:buttons.review.disabled,fitDisabled:buttons.fit.disabled}));
""")

    assert result == {
        "afterFirst": "review",
        "afterSecond": "discover",
        "changes": ["discover", "review", "fit", "review", "discover"],
        "reviewDisabled": False,
        "fitDisabled": False,
    }


def test_reopening_restores_progress_but_completion_resets_to_discovery():
    result = run_navigation("""
const names=['discover','review','fit'];
const buttons=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const sections=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const events=new FakeEvents();
const history={state:{taskOverlay:'find',findWorkStage:'review'},replaced:[],pushState(state){this.state=state;},replaceState(state){this.state=state;this.replaced.push(state);},back(){}};
const navigation=createNavigation({buttons,sections,history,eventTarget:events,onStageChange:()=>{}});
navigation.start(); navigation.sync({selectedCount:1,recovery:false}); navigation.open();
const restored=navigation.stage();
navigation.complete();
process.stdout.write(JSON.stringify({restored,completed:navigation.stage(),state:history.state,replaced:history.replaced}));
""")

    assert result == {
        "restored": "review",
        "completed": "discover",
        "state": {"taskOverlay": "find"},
        "replaced": [{"taskOverlay": "find"}],
    }


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

    assert '<nav class="mobile-find-work-nav"' in html
    assert 'aria-label="Find Work steps"' in html
    for name, label in (("discover", "Discover"), ("review", "Review"), ("fit", "Fit &amp; assign")):
        assert f'data-find-work-stage="{name}"' in html
        assert f">{label}</button>" in html
        assert f'id="find-work-{name}-stage"' in html
    assert 'id="find-work-review-list"' in html
    assert 'id="continue-find-work-fit"' in html
    assert '<script src="static/mobile-find-work-nav.js"></script>' in html
    assert '"static/mobile-find-work-nav.js"' in bundle
    assert "static/mobile-find-work-nav.js" in service_worker
    assert ".mobile-find-work-nav" in css
    assert "min-height:44px" in css
    assert "createMobileFindWorkNavigation" in dashboard
    assert "findWorkNavigation?.sync" in dashboard
