"""Bug fix (code-review 5.15): modalul de detaliu trebuie sa se deschida la
click/Enter pe randul SLIM.

US-004 a redenumit randul listei in `class="trimitere-slim"` (ID-ul ramane
`trimitere-row-{id}`). Handler-ele JS din base.html verificau doar
`classList.contains('trimitere-row')` -> nu se mai potriveau pe randul slim,
deci modalul nu se mai deschidea. Testul asserteaza ca JS-ul randat (pagina
completa /) trateaza explicit clasa `trimitere-slim` in AMBELE handler:
htmx:beforeRequest (click) si keydown (Enter/Space).
"""

from __future__ import annotations

import os
import re
import tempfile

import pytest
from starlette.testclient import TestClient


def _create_account_user(email: str, name: str = "Service", password: str = "parolasecreta10"):
    from app.accounts import create_account
    from app.users import create_user
    from app.db import get_connection

    conn = get_connection()
    try:
        acct_id = create_account(conn, name, active=True)
        create_user(conn, acct_id, email, password)
        return acct_id
    finally:
        conn.close()


def _login(client, email: str, password: str = "parolasecreta10") -> None:
    resp = client.get("/login")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
        re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
    assert m
    resp = client.post(
        "/login",
        data={"email": email, "parola": password, "csrf_token": m.group(1)},
    )
    assert resp.status_code == 303


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "modal_slim_test.db"))
    monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "true")
    from app.config import get_settings
    get_settings.cache_clear()
    from app.web import ratelimit
    ratelimit._hits.clear()
    from app.main import app
    with TestClient(app, follow_redirects=False) as c:
        yield c
    ratelimit._hits.clear()
    get_settings.cache_clear()


def test_handler_click_recunoaste_rand_slim(client):
    """htmx:beforeRequest deschide modalul si pentru clasa trimitere-slim."""
    _create_account_user("modal_click@test.com")
    _login(client, "modal_click@test.com")

    resp = client.get("/")
    assert resp.status_code == 200
    html = resp.text

    # Handler-ul de click (htmx:beforeRequest) trebuie sa trateze trimitere-slim.
    open_line = re.search(r"contains\('trimitere-slim'\)[^\n]*open\(elt\)", html)
    assert open_line, (
        "Handler-ul de click (htmx:beforeRequest -> open(elt)) nu recunoaste "
        "clasa 'trimitere-slim' -> modalul nu se deschide la click pe randul slim"
    )


def test_handler_keyboard_recunoaste_rand_slim(client):
    """keydown (Enter/Space) declanseaza click si pentru clasa trimitere-slim."""
    _create_account_user("modal_kbd@test.com")
    _login(client, "modal_kbd@test.com")

    resp = client.get("/")
    assert resp.status_code == 200
    html = resp.text

    # Handler-ul keydown verifica clasa inainte de a chema t.click().
    # Trebuie sa includa 'trimitere-slim' in conditia de garda.
    kbd = re.search(
        r"keydown[^\n]*\n(?:.*\n){0,6}?.*contains\('trimitere-slim'\)",
        html,
    )
    assert kbd, (
        "Handler-ul keydown (Enter/Space) nu recunoaste clasa 'trimitere-slim' "
        "-> tastatura nu deschide modalul pe randul slim"
    )
