"""Test: draw TWO lines and verify the second line's modal shows the SECOND
line's data, not the first line's."""
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 = r"""
const canvas = document.getElementById('sketchCanvas');
if (!canvas) return 'no-canvas';
canvas.setPointerCapture = function(){};
canvas.releasePointerCapture = function(){};
canvas.hasPointerCapture = function(){ return false; };
const rect = canvas.getBoundingClientRect();
const sx = rect.left + rect.width * arguments[0];
const sy = rect.top + rect.height * arguments[1];
const ex = rect.left + rect.width * arguments[2];
const ey = rect.top + rect.height * arguments[3];
const down = new PointerEvent('pointerdown', { bubbles: true, cancelable: true, pointerId: 1, pointerType: 'touch', isPrimary: true, clientX: sx, clientY: sy });
canvas.dispatchEvent(down);
for (let i = 1; i <= 5; i++) {
  const x = sx + (ex - sx) * i / 5;
  const y = sy + (ey - sy) * i / 5;
  canvas.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, cancelable: true, pointerId: 1, pointerType: 'touch', isPrimary: true, clientX: x, clientY: y }));
}
canvas.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, cancelable: true, pointerId: 1, pointerType: 'touch', isPrimary: true, clientX: ex, clientY: ey }));
return 'ok';
"""


def setup(d):
    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)


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:
        setup(d)

        # ---- Draw line 1 ----
        print("== Drawing line 1 ==")
        r1 = d.execute_script(DRAW_JS, 0.2, 0.3, 0.4, 0.5)
        print("draw1 result:", r1)
        time.sleep(1)
        print("lines after draw1:", d.execute_script(
            "const T=window.__test; return T.state.jobs[0].sketches[0].lines.length"))
        overlay = d.find_elements(By.CSS_SELECTOR, ".sheet-overlay")
        print("line1 modal present:", len(overlay) > 0)
        print("line1 pinModal:", d.execute_script(
            "const T=window.__test; return JSON.stringify(T.ui.pinModal)"))

        # Type a value in line 1's modal
        d.execute_script("""
            const inp = document.getElementById('quickTotalInches');
            if (inp) { inp.value = '24'; inp.dispatchEvent(new Event('input', { bubbles: true })); }
        """)
        time.sleep(0.5)
        print("line1 value:", d.execute_script(
            "const T=window.__test; const l=T.state.jobs[0].sketches[0].lines[0]; return JSON.stringify({feet:l.feet, inches:l.inches, sixteenths:l.sixteenths});"))

        # Close line 1's modal with Done
        print("suppressUntil before close:", d.execute_script(
            "const T=window.__test; return T.ui._suppressClickUntil"))
        print("now before close:", d.execute_script("return performance.now()"))
        # Use JS click to avoid any Selenium scroll/overlay issues
        d.execute_script("""
            const btns = document.querySelectorAll('[data-action="closesheet"]');
            const done = Array.from(btns).find(b => b.textContent.trim() === 'Done');
            if (done) done.click();
            return done ? 'clicked' : 'no-done-btn';
        """)
        time.sleep(0.8)
        print("after close, overlay count:", len(d.find_elements(By.CSS_SELECTOR, ".sheet-overlay")))
        print("pinModal after close:", d.execute_script(
            "const T=window.__test; return JSON.stringify(T.ui.pinModal)"))

        # ---- Draw line 2 ----
        print("== Drawing line 2 (fast draw starting NEAR line 1) ==")
        # line 1 was drawn from (0.2,0.3) to (0.4,0.5).
        # Start line 2 at (0.35, 0.45) — within 34px of line 1's midpoint —
        # and draw FAST (no long hold), so it creates a new line rather than
        # arming the line-move gesture.
        r2 = d.execute_script("""
            const canvas = document.getElementById('sketchCanvas');
            canvas.setPointerCapture = function(){};
            canvas.releasePointerCapture = function(){};
            canvas.hasPointerCapture = function(){ return false; };
            const rect = canvas.getBoundingClientRect();
            const sx = rect.left + rect.width * 0.35;
            const sy = rect.top + rect.height * 0.45;
            const ex = rect.left + rect.width * 0.7;
            const ey = rect.top + rect.height * 0.6;
            const down = new PointerEvent('pointerdown', { bubbles: true, cancelable: true, pointerId: 2, pointerType: 'touch', isPrimary: true, clientX: sx, clientY: sy });
            canvas.dispatchEvent(down);
            for (let i = 1; i <= 5; i++) {
              const x = sx + (ex - sx) * i / 5;
              const y = sy + (ey - sy) * i / 5;
              canvas.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, cancelable: true, pointerId: 2, pointerType: 'touch', isPrimary: true, clientX: x, clientY: y }));
            }
            canvas.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, cancelable: true, pointerId: 2, pointerType: 'touch', isPrimary: true, clientX: ex, clientY: ey }));
            return 'drawn';
        """)
        print("draw2 result:", r2)
        print("draft after draw:", d.execute_script(
            "const T=window.__test; return JSON.stringify(T.ui.sketchDraft)"))
        time.sleep(1)
        overlay2 = d.find_elements(By.CSS_SELECTOR, ".sheet-overlay")
        print("line2 modal present:", len(overlay2) > 0)
        print("line2 pinModal:", d.execute_script(
            "const T=window.__test; return JSON.stringify(T.ui.pinModal)"))
        print("lines count:", d.execute_script(
            "const T=window.__test; return T.state.jobs[0].sketches[0].lines.length"))
        print("line states:", d.execute_script(
            "const T=window.__test; return JSON.stringify(T.state.jobs[0].sketches[0].lines.map(l => ({id:l.id, feet:l.feet, inches:l.inches})))"))

        # Dump DBG logs
        dbg = d.execute_script("return window.__dbgLogs ? window.__dbgLogs.join('\\n') : '(none)'")
        print("== DBG ==")
        print(dbg)
    finally:
        d.quit()


if __name__ == "__main__":
    main()