"""Verify the toolbar redesign:
1. Bottom toolbar has Tags / Snap / Undo / Camera / Gallery (no Draw/View)
2. Tags toggle hides/shows L1 tag on the canvas
3. Drawing still works after removing Draw/View toggle
"""
import os
import sys
import time

sys.stdout.reconfigure(encoding="utf-8", errors="replace")

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service

HERE = os.path.dirname(os.path.abspath(__file__))
GECKODRIVER = os.path.join(HERE, "geckodriver.exe")
BASE = "http://localhost:8000/field-capture.html?debug"

DRAW_JS = """
(function(){
  const canvas = document.getElementById('sketchCanvas');
  canvas.setPointerCapture = function(){};
  canvas.releasePointerCapture = function(){};
  canvas.hasPointerCapture = function(){ return false; };
  const rect = canvas.getBoundingClientRect();
  const opts = { bubbles: true, cancelable: true, pointerId: 1, pointerType: 'touch', isPrimary: true };
  const sx = rect.left + rect.width*0.3, sy = rect.top + rect.height*0.4;
  const ex = rect.left + rect.width*0.7, ey = rect.top + rect.height*0.6;
  canvas.dispatchEvent(new PointerEvent('pointerdown', Object.assign({}, opts, {clientX: sx, clientY: sy})));
  for (let i = 1; i <= 5; i++) canvas.dispatchEvent(new PointerEvent('pointermove', Object.assign({}, opts, {clientX: sx+(ex-sx)*i/5, clientY: sy+(ey-sy)*i/5})));
  canvas.dispatchEvent(new PointerEvent('pointerup', Object.assign({}, opts, {clientX: ex, clientY: ey})));
  return 'drawn';
})();
"""


def main():
    opts = Options()
    opts.headless = False
    svc = Service(executable_path=GECKODRIVER)
    d = webdriver.Firefox(options=opts, service=svc)
    d.set_window_size(480, 900)
    try:
        d.get(BASE)
        time.sleep(2)
        d.find_element(By.CSS_SELECTOR, '[data-action="newjob"]').click()
        time.sleep(0.8)
        d.find_element(By.CSS_SELECTOR, '[data-action="opensketch"]').click()
        time.sleep(0.8)
        d.execute_script("""
            const T = window.__test;
            const job = T.state.jobs[0];
            const sk = job.sketches[0];
            const c = document.createElement('canvas');
            c.width = 200; c.height = 150;
            const ctx = c.getContext('2d');
            ctx.fillStyle = '#cccccc'; ctx.fillRect(0,0,200,150);
            sk.photo = { dataUrl: c.toDataURL('image/jpeg', 0.8), width: 200, height: 150 };
            T.saveState();
        """)
        d.execute_script(
            "const T=window.__test; T.ui.screen='sketch'; T.ui.sketchId=T.state.jobs[0].sketches[0].id; T.render();"
        )
        time.sleep(0.8)

        # 1. Toolbar buttons present, no Draw/View
        print("toolbar buttons:", d.execute_script("""
            return JSON.stringify(Array.from(document.querySelectorAll('.sketch-toolbar .sketch-tool')).map(b => b.textContent.trim()));
        """))

        # 2. Draw a line, check tag drawn
        print("draw:", d.execute_script(DRAW_JS))
        time.sleep(0.8)
        # Close the quick sheet that auto-opens after drawing
        d.execute_script('document.querySelector(".sheet-minimal [data-action=closesheet]").click()')
        time.sleep(0.5)

        # Check canvas pixels for the tag — simplest: check ui.tagMode + toggle behavior
        print("tagMode default:", d.execute_script("const T=window.__test; return T.ui.tagMode;"))
        print("tags btn label:", d.execute_script(
            "const b = document.querySelector('[data-action=\"toggle-tags\"]'); return b ? b.textContent.trim() : 'missing';"
        ))
        print("tags btn active:", d.execute_script(
            "const b = document.querySelector('[data-action=\"toggle-tags\"]'); return b ? b.classList.contains('active') : 'missing';"
        ))

        # Toggle: tags -> numbers
        d.find_element(By.CSS_SELECTOR, '[data-action="toggle-tags"]').click()
        time.sleep(0.5)
        print("tagMode after click 1:", d.execute_script("const T=window.__test; return T.ui.tagMode;"))
        print("tags btn label after:", d.execute_script(
            "const b = document.querySelector('[data-action=\"toggle-tags\"]'); return b ? b.textContent.trim() : 'missing';"
        ))
        print("tags btn active after:", d.execute_script(
            "const b = document.querySelector('[data-action=\"toggle-tags\"]'); return b ? b.classList.contains('active') : 'missing';"
        ))

        # Toggle: numbers -> off
        d.find_element(By.CSS_SELECTOR, '[data-action="toggle-tags"]').click()
        time.sleep(0.5)
        print("tagMode after click 2:", d.execute_script("const T=window.__test; return T.ui.tagMode;"))
        print("tags btn active after 2:", d.execute_script(
            "const b = document.querySelector('[data-action=\"toggle-tags\"]'); return b ? b.classList.contains('active') : 'missing';"
        ))

        # Toggle back to tags (wrap)
        d.find_element(By.CSS_SELECTOR, '[data-action="toggle-tags"]').click()
        time.sleep(0.5)
        print("tagMode after click 3:", d.execute_script("const T=window.__test; return T.ui.tagMode;"))

        # 3. Drawing still works after controls change
        print("draw2:", d.execute_script(DRAW_JS))
        time.sleep(0.8)
        print("lines count:", d.execute_script(
            "const T=window.__test; return T.state.jobs[0].sketches[0].lines.length;"
        ))
    finally:
        d.quit()


if __name__ == "__main__":
    main()