import json
import subprocess
from pathlib import Path


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


def test_update_navigation_reuses_new_activity_opens_context_and_focuses_reply():
    script = f"""
const createNavigation = require({json.dumps(str(CONTROLLER))});
class FakeElement {{
  constructor(name) {{
    this.name=name; this.listeners={{}}; this.attributes={{}}; this.open=false;
    this.focuses=0; this.scrolls=[];
  }}
  addEventListener(name, callback) {{ this.listeners[name]=callback; }}
  removeEventListener(name) {{ delete this.listeners[name]; }}
  setAttribute(name, value) {{ this.attributes[name]=value; }}
  removeAttribute(name) {{ delete this.attributes[name]; }}
  focus() {{ this.focuses += 1; }}
  scrollIntoView(options) {{ this.scrolls.push({{...options, openWhenScrolled:this.open}}); }}
}}
const names=['activity','conversation','context','reply'];
const buttons=Object.fromEntries(names.map(name => [name,new FakeElement(name)]));
const targets=Object.fromEntries(['conversation','context','reply'].map(name => [name,new FakeElement(name)]));
const replyComposer=new FakeElement('composer');
let activityJumps=0;
const navigation=createNavigation({{
  buttons, targets, replyComposer,
  jumpToNewActivity() {{ activityJumps += 1; }},
  prefersReducedMotion:() => true,
}});
navigation.start();
navigation.navigate('conversation');
navigation.navigate('context');
const contextOpenAfterNavigation=targets.context.open;
navigation.navigate('reply');
navigation.navigate('activity');
const currentAfterActivity=Object.fromEntries(Object.entries(buttons).map(([name,button]) => [name,button.attributes['aria-current'] || null]));
navigation.reset();
const contextOpenAfterReset=targets.context.open;
const currentAfterReset=Object.fromEntries(Object.entries(buttons).map(([name,button]) => [name,button.attributes['aria-current'] || null]));
navigation.stop();
process.stdout.write(JSON.stringify({{
  activityJumps,
  conversation:targets.conversation.scrolls,
  context:targets.context.scrolls,
  contextOpen:contextOpenAfterNavigation,
  contextOpenAfterReset,
  reply:targets.reply.scrolls,
  replyFocuses:replyComposer.focuses,
  currentAfterActivity,
  currentAfterReset,
  listenersAfterStop:Object.values(buttons).map(button => Object.keys(button.listeners).length),
}}));
"""
    result = subprocess.run(["node", "-e", script], capture_output=True, text=True)

    assert result.returncode == 0, result.stderr
    assert json.loads(result.stdout) == {
        "activityJumps": 1,
        "conversation": [{"block": "start", "behavior": "auto", "openWhenScrolled": False}],
        "context": [{"block": "start", "behavior": "auto", "openWhenScrolled": True}],
        "contextOpen": True,
        "contextOpenAfterReset": False,
        "reply": [{"block": "start", "behavior": "auto", "openWhenScrolled": False}],
        "replyFocuses": 1,
        "currentAfterActivity": {
            "activity": "location",
            "conversation": None,
            "context": None,
            "reply": None,
        },
        "currentAfterReset": {
            "activity": "location",
            "conversation": None,
            "context": None,
            "reply": None,
        },
        "listenersAfterStop": [0, 0, 0, 0],
    }


def test_update_navigation_tracks_visible_sections_and_disconnects_observer():
    script = f"""
const createNavigation = require({json.dumps(str(CONTROLLER))});
const makeElement=name => ({{
  name, attributes:{{}},
  addEventListener() {{}}, removeEventListener() {{}},
  setAttribute(key,value) {{ this.attributes[key]=value; }},
  removeAttribute(key) {{ delete this.attributes[key]; }},
}});
const buttons=Object.fromEntries(['activity','conversation','context','reply'].map(name => [name,makeElement(name)]));
const targets=Object.fromEntries(['conversation','context','reply'].map(name => [name,makeElement(name)]));
let callback;
let disconnected=0;
const navigation=createNavigation({{
  buttons, targets,
  observe(handler) {{ callback=handler; return {{disconnect() {{ disconnected += 1; }}}}; }},
}});
navigation.start();
callback([
  {{target:targets.conversation,isIntersecting:true,intersectionRatio:.2}},
  {{target:targets.reply,isIntersecting:true,intersectionRatio:.8}},
]);
const current=Object.fromEntries(Object.entries(buttons).map(([name,button]) => [name,button.attributes['aria-current'] || null]));
navigation.stop();
process.stdout.write(JSON.stringify({{current,disconnected}}));
"""
    result = subprocess.run(["node", "-e", script], capture_output=True, text=True)

    assert result.returncode == 0, result.stderr
    assert json.loads(result.stdout) == {
        "current": {
            "activity": None,
            "conversation": None,
            "context": None,
            "reply": "location",
        },
        "disconnected": 1,
    }


def test_update_navigation_routes_taps_and_scrolls_without_focusing_on_restore():
    script = f"""
const createNavigation=require({json.dumps(str(CONTROLLER))});
const element=name => ({{name,listeners:{{}},attributes:{{}},focuses:0,open:false,
  addEventListener(key,fn) {{ this.listeners[key]=fn; }}, removeEventListener() {{}},
  setAttribute(key,value) {{ this.attributes[key]=value; }}, removeAttribute(key) {{ delete this.attributes[key]; }},
  scrollIntoView() {{}}, focus() {{ this.focuses += 1; }},
}});
const names=['activity','conversation','context','reply'];
const buttons=Object.fromEntries(names.map(name => [name,element(name)]));
const targets=Object.fromEntries(['conversation','context','reply'].map(name => [name,element(name)]));
const composer=element('composer'); const changes=[]; let observer;
const navigation=createNavigation({{buttons,targets,replyComposer:composer,jumpToNewActivity() {{}},
  onSectionChange:(name,options)=>changes.push([name,options.replace]),
  observe(handler) {{ observer=handler; return {{disconnect() {{}}}}; }},
}});
navigation.start();
buttons.reply.listeners.click({{preventDefault() {{}}}});
observer([{{target:targets.context,isIntersecting:true,intersectionRatio:1}}]);
navigation.navigate('reply',{{focus:false}});
process.stdout.write(JSON.stringify({{changes,focuses:composer.focuses,current:buttons.reply.attributes['aria-current']}}));
"""
    result = subprocess.run(["node", "-e", script], capture_output=True, text=True)

    assert result.returncode == 0, result.stderr
    assert json.loads(result.stdout) == {
        "changes": [["reply", False], ["context", True]],
        "focuses": 1,
        "current": "location",
    }


def test_update_sheet_wires_a_mobile_only_safe_area_navigation_rail():
    html = (FRONTEND / "index.html").read_text()
    css = (FRONTEND / "dashboard.css").read_text()
    dashboard_js = (FRONTEND / "dashboard.js").read_text()
    service_worker = (FRONTEND / "service-worker.js").read_text()

    assert '<nav class="mobile-update-detail-nav" aria-label="Update sections">' in html
    for name, label in (
        ("activity", "New activity"),
        ("conversation", "Conversation"),
        ("context", "Subject context"),
        ("reply", "Reply"),
    ):
        assert f'data-update-section="{name}"' in html
        assert f">{label}</button>" in html
    assert 'id="update-conversation"' in html
    assert 'id="update-subject-context"' in html
    assert 'id="update-reply-workspace"' in html
    assert '<script src="static/mobile-update-detail-nav.js"></script>' in html
    assert "createMobileUpdateDetailNavigation({" in dashboard_js
    assert "jumpToNewActivity:() => updateReadPosition.jump()" in dashboard_js
    assert "mobileUpdateDetailNavigation.reset();" in dashboard_js
    assert ".mobile-update-detail-nav" in css
    assert "position:sticky" in css
    assert "min-height:44px" in css
    assert "env(safe-area-inset-top)" in css
    assert "@media (min-width:601px)" in css
    assert "BASE + 'static/mobile-update-detail-nav.js'" in service_worker
