import json
import subprocess
from pathlib import Path


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


def run_navigation(scenario: str) -> dict:
    script = f"""
const createNavigation = require({json.dumps(str(CONTROLLER))});
class FakeElement {{
  constructor(name, offsetTop=0) {{
    this.name=name; this.offsetTop=offsetTop; 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]; }}
  scrollTo(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_plan_today_navigation_scrolls_the_planner_and_tracks_sections():
    result = run_navigation("""
const names=['fit','today','available'];
const buttons=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const targets={fit:new FakeElement('fit',120),today:new FakeElement('today',620),available:new FakeElement('available',1120)};
const root=new FakeElement('panel',100);
let callback; let observedRoot; let disconnected=0; let now=1000;
const navigation=createNavigation({
  buttons,targets,root,prefersReducedMotion:()=>true,now:()=>now,
  observe(handler,observed,rootOption){callback=handler; observedRoot=rootOption; return {disconnect(){disconnected++;}};},
});
navigation.start();
buttons.today.click();
now=1600;
callback([{target:targets.today,isIntersecting:true,intersectionRatio:.2},{target:targets.available,isIntersecting:true,intersectionRatio:.8}]);
const selected=Object.fromEntries(Object.entries(buttons).map(([name,button])=>[name,button.attributes['aria-current']||null]));
navigation.stop();
process.stdout.write(JSON.stringify({scrolls:root.scrolls,selected,observedRoot:observedRoot.name,disconnected,listeners:Object.values(buttons).map(button=>Object.keys(button.listeners).length)}));
""")

    assert result == {
        "scrolls": [{"top": 520, "behavior": "auto"}],
        "selected": {"fit": None, "today": None, "available": "location"},
        "observedRoot": "panel",
        "disconnected": 1,
        "listeners": [0, 0, 0],
    }


def test_mobile_plan_today_navigation_preserves_selection_until_a_fresh_open():
    result = run_navigation("""
const names=['fit','today','available'];
const buttons=Object.fromEntries(names.map(name=>[name,new FakeElement(name)]));
const targets=Object.fromEntries(names.map((name,index)=>[name,new FakeElement(name,index*400)]));
const root=new FakeElement('panel');
const navigation=createNavigation({buttons,targets,root,prefersReducedMotion:()=>false,observe:()=>null});
navigation.start();
buttons.available.click();
const afterRerender=Object.fromEntries(Object.entries(buttons).map(([name,button])=>[name,button.attributes['aria-current']||null]));
navigation.reset();
const afterOpen=Object.fromEntries(Object.entries(buttons).map(([name,button])=>[name,button.attributes['aria-current']||null]));
process.stdout.write(JSON.stringify({scrolls:root.scrolls,afterRerender,afterOpen}));
""")

    assert result == {
        "scrolls": [{"top": 800, "behavior": "smooth"}],
        "afterRerender": {"fit": None, "today": None, "available": "location"},
        "afterOpen": {"fit": "location", "today": None, "available": None},
    }


def test_plan_today_ships_mobile_navigation_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()

    assert '<nav class="mobile-plan-today-nav"' in html
    assert 'aria-label="Plan Today sections"' in html
    for name, label in (("fit", "Fit"), ("today", "Today"), ("available", "Available")):
        assert f'data-plan-today-section="{name}"' in html
        assert f">{label}</button>" in html
    assert 'id="plan-today-fit"' in html
    assert 'id="plan-today-selected"' in html
    assert 'id="plan-today-available-work"' in html
    assert '<script src="static/mobile-plan-today-nav.js"></script>' in html
    assert '"static/mobile-plan-today-nav.js"' in bundle
    assert "static/mobile-plan-today-nav.js" in service_worker
    assert ".mobile-plan-today-nav" in css
    assert "grid-template-columns:repeat(3,minmax(0,1fr))" in css
    assert "min-height:44px" in css
    assert "@media (min-width:601px)" in css
