"""Parcours reels au clavier, sur le POS et une base Django de test isolee."""
import importlib.util
import os
from pathlib import Path
import re
import tempfile
from unittest import skipUnless
from unittest.mock import patch

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.core.cache import cache
from django.urls import reverse

from dgi.models import ItemType, TaxGroup
from .models import (
    Client, Commande, ConditionnementProduit, Configuration, LigneCommande, ModePaiement,
    MouvementStock, Paiement, PendingSale, PointDeVente, Produit, ProduitPointVentePrix, StockPointDeVente,
)


@skipUnless(importlib.util.find_spec("playwright"), "Installer requirements-dev.txt pour les tests clavier Chrome.")
class QuickBillingBrowserTests(StaticLiveServerTestCase):
    def setUp(self):
        cache.clear()
        self.pdv = PointDeVente.objects.create(nom="MAGASIN GOMBE")
        self.user = get_user_model().objects.create_user(username="keyboard", email="keyboard@example.com", role="ADMIN", is_staff=True, point_de_vente=self.pdv)
        Configuration.objects.create(nom_entreprise="FacControl", taux_change=1, type_dgi="FV", mode_dgi="ht", nif="A1234567Q", isf_dgi="CD01000000-1")
        group, _ = TaxGroup.objects.update_or_create(code="B", defaults={"name":"Taxable 16%", "tax":16})
        kind, _ = ItemType.objects.update_or_create(code="BIE", defaults={"name":"Bien"})
        self.product = Produit.objects.create(nom="PEMPASE", code_sku="GEDETEST01", prix_vente=1000, taxgroup=group, typeart=kind)
        self.piece = self.product.conditionnements.get()
        self.piece.libelle = "Pièce"
        self.piece.save()
        self.packet = ConditionnementProduit.objects.create(produit=self.product, code="PEM6", libelle="Paquet", facteur_conversion=6, prix_vente=5500)
        self.carton = ConditionnementProduit.objects.create(produit=self.product, code="PEM12", libelle="Carton", facteur_conversion=12, prix_vente=50000)
        ProduitPointVentePrix.objects.create(produit=self.product, conditionnement=self.carton, point_de_vente=self.pdv, prix_vente=46000)
        StockPointDeVente.objects.create(produit=self.product, point_de_vente=self.pdv, quantite=80)
        self.second = Produit.objects.create(nom="JUS MANGO", code_sku="GEDETEST02", prix_vente=23000, taxgroup=group, typeart=kind)
        StockPointDeVente.objects.create(produit=self.second, point_de_vente=self.pdv, quantite=100)
        self.customer = Client.objects.create(nom_complet="ADAM ALAME", nif="A1234567Q", telephone="0976187614")
        ModePaiement.objects.update_or_create(code="ESPECES", defaults={"designation":"Espèces"})
        ModePaiement.objects.update_or_create(code="CARD", defaults={"designation":"Carte"})
        self.client.force_login(self.user)
        self.session_value = self.client.cookies[settings.SESSION_COOKIE_NAME].value
        self.qa_dir = Path(os.environ.get("FACCONTROL_QA_DIR", Path(tempfile.gettempdir()) / "faccontrol-quick-billing-qa"))
        self.qa_dir.mkdir(parents=True, exist_ok=True)

    def browser(self, *, language="fr", viewport=None, init_script="", keyboard_scanner=False):
        """Session Chrome sur le POS.

        Playwright tape plus vite qu'une douchette : la detection G_Scan est
        donc coupee par defaut (`GScan.keyboardScanEnabled`) et reactivee par
        les tests du scan. `init_script` s'execute avant les scripts de la page.
        """
        from contextlib import contextmanager
        from playwright.sync_api import sync_playwright

        @contextmanager
        def session():
            with sync_playwright() as playwright:
                candidates = [os.environ.get("FACCONTROL_CHROME_PATH", ""), r"C:\Program Files\Google\Chrome\Application\chrome.exe"]
                executable = next((value for value in candidates if value and Path(value).is_file()), None)
                browser = playwright.chromium.launch(headless=True, **({"executable_path":executable} if executable else {}))
                context = browser.new_context(viewport=viewport or {"width":1366, "height":768}, locale=language, service_workers="block")
                context.add_cookies([
                    {"name":settings.SESSION_COOKIE_NAME, "value":self.session_value, "url":self.live_server_url},
                    {"name":settings.LANGUAGE_COOKIE_NAME, "value":language, "url":self.live_server_url},
                ])
                page = context.new_page()
                page.add_init_script(
                    f"window.GScan = Object.assign(window.GScan || {{}}, {{keyboardScanEnabled: {'true' if keyboard_scanner else 'false'}}});"
                    + init_script
                )
                page.route("**/*", lambda route: route.continue_() if route.request.url.startswith(self.live_server_url) else route.abort())
                page.goto(self.live_server_url + reverse("facturation:pos-view"), wait_until="load")
                page.wait_for_function("window.FacControlQuickBilling && window.FacControlQuickBilling.active")
                try:
                    yield page
                finally:
                    context.close()
                    browser.close()
        return session()

    def assert_focus(self, page, selector):
        from playwright.sync_api import expect
        expect(page.locator(selector)).to_be_focused()

    def test_pos_sidebar_stays_compact_in_quick_and_visual_modes_and_can_expand(self):
        """La navigation POS libere la largeur sans devenir inaccessible."""

        from playwright.sync_api import expect

        with self.browser(viewport={"width": 1366, "height": 768}) as page:
            sidebar = page.locator("#sidebar")
            main = page.locator("#main")
            rail_toggle = page.locator(".sidebar-rail-toggle")
            backdrop = page.locator(".sidebar-rail-backdrop")
            pos_label = page.locator('[data-menu-key="pos"] > span')
            current_section = page.locator(".sidebar-nav > .nav-item > .nav-link.is-current").first
            primary_fill = "rgb(65, 84, 241)"

            # Des l'ouverture du point de vente : icones seules, sans clic,
            # et la section du POS allumee dans la rampe.
            expect(page.locator("body")).to_have_class(re.compile(r"\bpos-compact-sidebar\b"))
            expect(sidebar).to_have_css("width", "64px")
            expect(main).to_have_css("margin-left", "64px")
            expect(rail_toggle).to_have_attribute("aria-expanded", "false")
            expect(pos_label).to_be_hidden()
            expect(current_section).to_have_css("background-color", primary_fill)
            page.screenshot(path=str(self.qa_dir / "pos-rail-quick.png"))

            # Le changement de presentation du POS ne doit pas rendre la
            # sidebar large : les deux modes partagent le meme espace utile.
            page.locator("#posVisualMode").click()
            expect(page.locator("#pos-app")).to_have_attribute("data-billing-mode", "visual")
            expect(sidebar).to_have_css("width", "64px")
            expect(main).to_have_css("margin-left", "64px")
            # Recherche produit pleine largeur comme en Billing rapide :
            # compteur et actions passent sur la ligne suivante.
            search_box = page.locator("#productSearchInput").bounding_box()
            panel_box = page.locator(".product-search-panel").bounding_box()
            actions_box = page.locator(".pos-quick-actions").bounding_box()
            self.assertAlmostEqual(search_box["width"], panel_box["width"], delta=1)
            self.assertGreaterEqual(actions_box["y"], search_box["y"] + search_box["height"])
            page.screenshot(path=str(self.qa_dir / "pos-rail-visual.png"))

            # Le chevron deplie le menu en superposition : le panier garde
            # exactement sa place, puis un clic a cote replie la rampe.
            rail_toggle.click()
            expect(sidebar).to_have_css("width", "300px")
            expect(main).to_have_css("margin-left", "64px")
            expect(rail_toggle).to_have_attribute("aria-expanded", "true")
            expect(backdrop).to_be_visible()
            expect(pos_label).to_be_visible()
            # Deplie, la section retrouve le style habituel du menu (teinte legere).
            expect(current_section).not_to_have_css("background-color", primary_fill)
            page.screenshot(path=str(self.qa_dir / "pos-rail-expanded.png"))
            backdrop.click()
            expect(sidebar).to_have_css("width", "64px")
            expect(backdrop).to_be_hidden()

            # Toucher l'icone d'une section ouvre directement cette section ;
            # Echap replie ensuite la navigation et rend le focus au chevron.
            section = page.locator(".sidebar-nav > .nav-item > .sidebar-section-toggle.collapsed").first
            submenu = page.locator("#" + section.get_attribute("aria-controls"))
            section.click()
            expect(sidebar).to_have_css("width", "300px")
            expect(submenu).to_have_class(re.compile(r"\bshow\b"))
            page.keyboard.press("Escape")
            expect(sidebar).to_have_css("width", "64px")
            expect(rail_toggle).to_be_focused()

            # Le bouton du header suit le meme comportement que le chevron.
            page.locator(".toggle-sidebar-btn").click()
            expect(sidebar).to_have_css("width", "300px")
            expect(rail_toggle).to_have_attribute("aria-expanded", "true")
            page.locator(".toggle-sidebar-btn").click()
            expect(sidebar).to_have_css("width", "64px")

            # Ecran de caisse 1024 px : la rampe reste en place ; en dessous de
            # 992 px, l'off-canvas historique reprend la main.
            page.set_viewport_size({"width": 1024, "height": 768})
            expect(sidebar).to_have_css("width", "64px")
            expect(main).to_have_css("margin-left", "64px")
            page.set_viewport_size({"width": 900, "height": 768})
            expect(rail_toggle).to_be_hidden()
            expect(main).to_have_css("margin-left", "0px")

    def test_billing_summary_panel_docks_detaches_moves_resizes_and_is_remembered(self):
        """Le resume de facture : epingle a droite ou a gauche, detache, deplace, redimensionne."""

        from playwright.sync_api import expect

        def drag(start, end, steps=8):
            page.mouse.move(*start)
            page.mouse.down()
            page.mouse.move(*end, steps=steps)
            page.mouse.up()

        with self.browser(viewport={"width": 1366, "height": 768}) as page:
            app = page.locator("#pos-app")
            column = page.locator("#pos-checkout-column")
            products = page.locator("#pos-products-column")
            products_card = page.locator("#pos-products-column > .card")
            head = page.locator("[data-pos-layout-handle]")
            action = lambda name: page.locator(f'[data-pos-layout-action="{name}"]')
            sized = re.compile(r"\bpos-dock-sized\b")
            collapsed = re.compile(r"\bpos-dock-collapsed\b")
            viewport_width = page.evaluate("document.documentElement.clientWidth")
            header_bottom = page.locator("#header").bounding_box()["height"]

            def assert_full_height(box):
                # Epingle : de la barre de navigation jusqu'en bas de l'ecran.
                self.assertAlmostEqual(box["y"], header_bottom + 12, delta=2)
                self.assertAlmostEqual(box["y"] + box["height"], 768 - 12, delta=2)

            # Par defaut : epingle a droite sur toute la hauteur, outils hors du parcours clavier.
            expect(app).to_have_attribute("data-pos-dock", "right")
            expect(action("reset")).to_be_hidden()
            self.assertEqual(column.evaluate("el => getComputedStyle(el).position"), "fixed")
            for selector in ('[data-pos-layout-action="pin"]', '[data-pos-layout-action="side"]', "[data-pos-layout-splitter]"):
                expect(page.locator(selector)).to_have_attribute("tabindex", "-1")
            panel = column.bounding_box()
            assert_full_height(panel)
            self.assertAlmostEqual(panel["x"] + panel["width"], viewport_width - 12, delta=2)
            # Le contenu (en-tete du POS compris) s'arrete avant le panneau.
            for content in (products_card, page.locator("#pos-switch-bar")):
                box = content.bounding_box()
                self.assertLessEqual(box["x"] + box["width"], panel["x"] - 8)
            # Valider reste a portee, en grand, meme panneau defile tout en haut.
            page.locator(".pos-dock-body").evaluate("el => { el.scrollTop = 0; }")
            self.assertEqual(page.locator(".pos-validate-bar").evaluate("el => getComputedStyle(el).position"), "sticky")
            validate = page.locator("#btnValidate").bounding_box()
            self.assertGreaterEqual(validate["height"], 50)
            self.assertLessEqual(validate["y"] + validate["height"], 768 - 12)
            page.screenshot(path=str(self.qa_dir / "pos-dock-right.png"))

            # A gauche, apres la barre laterale : les zones s'inversent, la recherche garde le focus.
            action("side").click()
            expect(app).to_have_attribute("data-pos-dock", "left")
            panel = column.bounding_box()
            assert_full_height(panel)
            self.assertAlmostEqual(panel["x"], page.locator("#main").bounding_box()["x"] + 12, delta=2)
            self.assertGreaterEqual(products_card.bounding_box()["x"], panel["x"] + panel["width"] + 8)
            self.assert_focus(page, "#productSearchInput")

            # Bord interieur : la largeur suit le pointeur et le contenu se decale, propre au Billing rapide.
            splitter = page.locator("[data-pos-layout-splitter]").bounding_box()
            grip = (splitter["x"] + splitter["width"] / 2, splitter["y"] + 120)
            drag(grip, (grip[0] + 120, grip[1]))
            self.assertAlmostEqual(column.bounding_box()["width"], panel["width"] + 120, delta=4)
            self.assertGreaterEqual(products_card.bounding_box()["x"], panel["x"] + panel["width"] + 120)
            expect(app).to_have_class(sized)
            page.screenshot(path=str(self.qa_dir / "pos-dock-left-wide.png"))
            page.locator("#posVisualMode").click()
            expect(app).not_to_have_class(sized)
            page.locator("#posQuickMode").click()
            expect(app).to_have_class(sized)

            # Detache : flottant a la meme place, le contenu reprend toute la largeur.
            action("pin").click()
            expect(app).to_have_attribute("data-pos-dock", "float")
            self.assertEqual(column.evaluate("el => getComputedStyle(el).position"), "fixed")
            self.assertAlmostEqual(products.bounding_box()["width"], app.bounding_box()["width"], delta=2)
            before = column.bounding_box()
            # Agrandi en largeur et raccourci par le coin, puis deplace par l'en-tete.
            corner = page.locator("[data-pos-layout-resize]").bounding_box()
            corner = (corner["x"] + 9, corner["y"] + 9)
            drag(corner, (corner[0] + 60, corner[1] - 200))
            sized_box = column.bounding_box()
            self.assertAlmostEqual(sized_box["width"], before["width"] + 60, delta=3)
            self.assertAlmostEqual(sized_box["height"], before["height"] - 200, delta=3)
            title = head.bounding_box()
            grab = (title["x"] + 70, title["y"] + title["height"] / 2)
            drag(grab, (grab[0] + 300, grab[1] + 40))
            resized = column.bounding_box()
            self.assertAlmostEqual(resized["x"], sized_box["x"] + 300, delta=3)
            self.assertAlmostEqual(resized["y"], sized_box["y"] + 40, delta=3)
            page.screenshot(path=str(self.qa_dir / "pos-dock-float.png"))

            # Reduit : l'en-tete seul affiche le net a payer ; F6 rouvre sur le paiement.
            action("collapse").click()
            expect(app).to_have_class(collapsed)
            expect(page.locator("[data-pos-layout-net]")).to_be_visible()
            self.assertLess(column.bounding_box()["height"], 80)
            page.keyboard.press("F6")
            expect(app).not_to_have_class(collapsed)
            self.assert_focus(page, ".payment-amount")

            # La disposition est memorisee par ce navigateur.
            page.reload()
            page.wait_for_function("window.FacControlQuickBilling && window.FacControlQuickBilling.active")
            expect(app).to_have_attribute("data-pos-dock", "float")
            self.assertAlmostEqual(column.bounding_box()["x"], resized["x"], delta=2)
            self.assertAlmostEqual(column.bounding_box()["width"], resized["width"], delta=2)

            # Glisse contre le bord droit : la zone de depot apparait, il s'y epingle.
            title = head.bounding_box()
            page.mouse.move(title["x"] + 70, title["y"] + 10)
            page.mouse.down()
            page.mouse.move(1366 - 12, title["y"] + 10, steps=10)
            expect(page.locator(".pos-dock-snap")).to_be_visible()
            page.screenshot(path=str(self.qa_dir / "pos-dock-snap.png"))
            page.mouse.up()
            expect(app).to_have_attribute("data-pos-dock", "right")
            expect(page.locator(".pos-dock-snap")).to_be_hidden()
            assert_full_height(column.bounding_box())

            action("reset").click()
            expect(app).not_to_have_class(sized)
            expect(action("reset")).to_be_hidden()

            # Telephone : empile, sans outils de disposition ni debordement.
            page.set_viewport_size({"width": 390, "height": 844})
            expect(page.locator(".pos-dock-tools")).to_be_hidden()
            self.assertEqual(column.evaluate("el => getComputedStyle(el).position"), "static")
            self.assertLessEqual(page.evaluate("document.documentElement.scrollWidth"), 390)
            page.screenshot(path=str(self.qa_dir / "pos-dock-mobile.png"), full_page=True)

    def test_client_list_shows_only_the_name_and_finds_customers_by_nif(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            page.keyboard.press("F4")
            page.keyboard.type("A1234567")
            option = page.locator("#clientSearchResults .client-search-option").first
            # Seul le nom (ou la raison sociale) s'affiche, meme trouve par son NIF.
            expect(option).to_have_text("ADAM ALAME")
            expect(option.locator(".faccontrol-search-column")).to_have_count(1)
            page.keyboard.press("Enter")
            expect(page.locator("#clientSelect")).to_have_value(str(self.customer.pk))
            expect(page.locator("#clientNIF")).to_have_value("A1234567Q")

    def test_sidebar_feature_search_filters_bilingually_and_opens_with_keyboard(self):
        """Ctrl+K deplie la rampe ; la recherche filtre des la premiere lettre."""

        from playwright.sync_api import expect

        with self.browser(viewport={"width": 1366, "height": 768}) as page:
            sidebar = page.locator("#sidebar")
            search = page.locator("#sidebarFeatureSearch")
            nav = page.locator("#sidebar-nav")
            options = page.locator("#sidebarFeatureResults .sidebar-feature-option")
            labels = page.locator("#sidebarFeatureResults .sidebar-feature-label")

            # Dans la rampe du POS, la recherche est une loupe ; Ctrl+K deplie.
            expect(search).to_be_hidden()
            expect(page.locator(".sidebar-rail-search")).to_be_visible()
            page.keyboard.press("Control+k")
            expect(sidebar).to_have_css("width", "300px")
            expect(search).to_be_focused()

            # Une seule lettre filtre deja (debuts de mots) et remplace le menu.
            page.keyboard.type("p")
            expect(nav).to_be_hidden()
            expect(labels.first).to_have_text("Point de Vente")
            expect(labels.first.locator("mark")).to_have_text("P")
            page.screenshot(path=str(self.qa_dir / "feature-search-letter.png"))

            # Anglais dans l'interface francaise, sans accent, faute, initiales.
            for query, expected in (
                ("customer", "Clients"),
                ("nouvelle categorie", "Nouvelle catégorie"),
                ("facure", "Ventes & Factures"),
                ("rca", "Rapport Chiffre d'Affaires"),
            ):
                search.fill(query)
                expect(labels.first).to_have_text(expected)

            search.fill("rapport")
            expect(options.first).to_have_attribute("aria-selected", "true")
            page.keyboard.press("ArrowDown")
            expect(options.nth(1)).to_have_attribute("aria-selected", "true")
            expect(search).to_have_attribute("aria-activedescendant", "sidebarFeatureOption-1")

            search.fill("zzzz")
            expect(options).to_have_count(0)
            expect(page.locator("#sidebarFeatureStatus")).to_contain_text("zzzz")

            # Echap efface d'abord la recherche, puis replie la rampe.
            page.keyboard.press("Escape")
            expect(search).to_have_value("")
            expect(nav).to_be_visible()
            page.keyboard.press("Escape")
            expect(sidebar).to_have_css("width", "64px")

            page.locator(".sidebar-rail-search").click()
            expect(search).to_be_focused()
            page.keyboard.type("stock actuel")
            expect(labels.first).to_have_text("Stock actuel")
            page.keyboard.press("Enter")
            page.wait_for_url(self.live_server_url + reverse("facturation:stock-list"))

            # Hors POS, la barre est directement visible en haut de la sidebar.
            expect(search).to_be_visible()
            expect(page.locator(".sidebar-rail-search")).to_have_count(0)
            search.fill("transfert")
            expect(labels.first).to_have_text("Transferts de stock")
            page.screenshot(path=str(self.qa_dir / "feature-search-sidebar.png"))

    def select_product(self, page, query="pem"):
        page.keyboard.press("F2")
        page.keyboard.press("Control+a")
        page.keyboard.type(query)
        page.locator('#quick-product-0').wait_for(state="visible")
        page.keyboard.press("ArrowDown")
        page.keyboard.press("Enter")

    def choose_carton(self, page):
        self.assert_focus(page, '[data-line-key="draft"] [data-quick-field="packaging"]')
        page.keyboard.press("ArrowDown")  # Pièce -> Paquet.
        page.keyboard.press("ArrowDown")  # Paquet -> Carton.
        self.assertEqual(page.locator('[data-line-key="draft"] select').input_value(), str(self.carton.pk))
        page.keyboard.press("Tab")
        self.assert_focus(page, '[data-packaging-id="%s"] [data-quick-field="quantity"]' % self.carton.pk)

    def enter_quantity_discount(self, page, quantity="2", *, enter=False):
        page.keyboard.press("Control+a")
        page.keyboard.type(quantity)
        page.keyboard.press("Enter" if enter else "Tab")
        self.assert_focus(page, '[data-quick-field="discount"]:focus')
        page.keyboard.press("Control+a")
        page.keyboard.type("0")
        page.keyboard.press("Enter" if enter else "Tab")
        self.assert_focus(page, '#productSearchInput')

    def test_required_workflow_finalizes_through_real_pos_without_mouse(self):
        from playwright.sync_api import expect

        with patch("facturation.views.FiscalOrchestrator.fiscalize_commande", return_value={"success":True, "channel":"MCF", "commande_id":1, "fiscal_transaction_id":"quick-browser-test"}) as fiscalize:
            with self.browser() as page:
                self.assert_focus(page, '#productSearchInput')
                self.select_product(page, "pem")
                self.choose_carton(page)
                self.enter_quantity_discount(page, "2")
                expect(page.locator('.quick-line-price')).to_contain_text("46 000,00")
                expect(page.locator('[data-quick-field="packaging"]').locator('..')).to_contain_text("24 Pièce")
                self.select_product(page, "GEDETEST02")
                self.assert_focus(page, '[data-product-id="%s"] [data-quick-field="quantity"]' % self.second.pk)
                self.enter_quantity_discount(page, "1", enter=True)
                page.keyboard.press("F4")
                self.assert_focus(page, '#clientSearchInput')
                page.keyboard.type("0976187614")
                page.keyboard.press("Enter")
                expect(page.locator('#clientSelect')).to_have_value(str(self.customer.pk))
                page.keyboard.press("Escape")
                page.keyboard.press("F2")
                self.assert_focus(page, '#productSearchInput')
                page.keyboard.press("F6")
                self.assert_focus(page, '.payment-amount')
                expect(page.locator('#netAPayer')).to_contain_text("133 400,00")
                page.keyboard.press("Enter")
                self.assert_focus(page, '.payment-currency')
                page.keyboard.press("Enter")
                self.assert_focus(page, '.payment-mode')
                page.screenshot(path=str(self.qa_dir / 'quick-billing-1366x768.png'))
                page.keyboard.press("Control+Enter")
                expect(page.locator('#printArea')).to_be_visible()
                self.assert_focus(page, '#newInvoiceButton')
                expect(page.locator('#newInvoiceButton')).to_have_text(' Nouvelle facture')
                expect(page.locator('iframe')).to_have_count(0)
                expect(page.locator('.pagetitle')).to_contain_text('Facture #FV-')
                expect(page.locator('#header')).to_be_visible()
                expect(page.get_by_role('button', name='Imprimer', exact=True)).to_be_visible()
                expect(page.get_by_role('link', name='Télécharger PDF', exact=True)).to_be_visible()
                page.screenshot(path=str(self.qa_dir / 'quick-billing-invoice-fr-1366.png'))
                page.keyboard.press('Enter')
                self.assert_focus(page, '#productSearchInput')
                expect(page.locator('.quick-cart-row')).to_have_count(0)
        fiscalize.assert_called_once()
        sale = Commande.objects.get()
        self.assertEqual(sale.montant_total, 133400)
        self.assertEqual(sale.tva_montant, 18400)
        self.assertEqual(LigneCommande.objects.count(), 2)
        self.assertEqual(sum(LigneCommande.objects.values_list("quantite_physique", flat=True)), 25)
        self.assertEqual(StockPointDeVente.objects.get(produit=self.product).quantite, 56)
        self.assertEqual(Paiement.objects.get().montant_verse, 133400)

    def test_same_product_different_packaging_and_repeat_keep_existing_lines(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            self.select_product(page, "GEDETEST01")
            page.keyboard.press("Tab")  # Accepter Pièce.
            self.enter_quantity_discount(page, "3")
            self.select_product(page, "pem")
            self.choose_carton(page)
            self.enter_quantity_discount(page, "2")
            expect(page.locator('.quick-cart-row')).to_have_count(2)
            expect(page.locator('[data-packaging-id="%s"] [data-quick-field="quantity"]' % self.piece.pk)).to_have_value("3,000")
            self.select_product(page, "pem")
            self.choose_carton(page)
            expect(page.locator('.quick-cart-row')).to_have_count(2)
            expect(page.locator('[data-packaging-id="%s"] [data-quick-field="quantity"]' % self.carton.pk)).to_have_value("3,000")
            expect(page.locator('[data-packaging-id="%s"] [data-quick-field="quantity"]' % self.piece.pk)).to_have_value("3,000")

    def test_draft_quantity_is_editable_before_confirming_packaging(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            self.select_product(page, "GEDETEST01")
            draft = page.locator('[data-line-key="draft"]')
            quantity = draft.locator('[data-quick-field="quantity"]')
            expect(quantity).to_be_visible()
            expect(quantity).to_have_value("1,000")

            draft.locator('[data-quick-field="packaging"]').select_option(str(self.carton.pk))
            quantity.fill("4")
            quantity.press("Tab")

            self.assert_focus(page, '[data-packaging-id="%s"] [data-quick-field="discount"]' % self.carton.pk)
            expect(page.locator('[data-packaging-id="%s"] [data-quick-field="quantity"]' % self.carton.pk)).to_have_value("4,000")
            expect(page.locator('[data-packaging-id="%s"] [data-quick-field="packaging"]' % self.carton.pk)).to_have_value(str(self.carton.pk))
            expect(page.locator('[data-packaging-id="%s"] [data-quick-field="packaging"]' % self.carton.pk).locator('..')).to_contain_text("48 Pièce")

    def test_quantity_uses_three_decimals_with_comma_in_quick_and_visual_modes(self):
        from playwright.sync_api import expect

        ConditionnementProduit.objects.filter(pk=self.piece.pk).update(fractionnable=True)
        with self.browser() as page:
            self.select_product(page, "GEDETEST01")
            expect(page.locator('[data-line-key="draft"] [data-quick-field="quantity"]')).to_have_value("1,000")
            page.keyboard.press("Tab")

            quick_quantity = page.locator('[data-packaging-id="%s"] [data-quick-field="quantity"]' % self.piece.pk)
            expect(quick_quantity).to_have_value("1,000")
            quick_quantity.fill("1,500")
            quick_quantity.press("Tab")
            expect(quick_quantity).to_have_value("1,500")
            self.assertEqual(page.evaluate("window.FacControlQuickBilling.engine.cart()[0].qty"), 1.5)

            page.locator('#posVisualMode').click()
            visual_quantity = page.locator('[data-visual-field="quantity"]')
            expect(visual_quantity).to_have_value("1,500")
            visual_quantity.fill("2,250")
            visual_quantity.press("Tab")
            expect(visual_quantity).to_have_value("2,250")
            self.assertEqual(page.evaluate("window.FacControlQuickBilling.engine.cart()[0].qty"), 2.25)

    def test_suggestions_escape_shortcuts_shift_tab_and_safe_line_deletion(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            page.keyboard.type("GEDETEST")
            page.locator('#quick-product-0').wait_for(state="visible")
            page.keyboard.press("ArrowDown")
            expect(page.locator('#quick-product-0')).to_have_attribute('aria-selected', 'true')
            page.keyboard.press("ArrowDown")
            expect(page.locator('#quick-product-1')).to_have_attribute('aria-selected', 'true')
            page.keyboard.press("ArrowUp")
            expect(page.locator('#quick-product-0')).to_have_attribute('aria-selected', 'true')
            page.keyboard.press("Escape")
            expect(page.locator('#quickProductSuggestions')).to_be_hidden()
            self.select_product(page)
            self.choose_carton(page)
            page.keyboard.press("Tab")
            self.assert_focus(page, '[data-quick-field="discount"]')
            page.keyboard.press("Shift+Tab")
            self.assert_focus(page, '[data-quick-field="quantity"]')
            page.keyboard.press("Delete")  # Efface une valeur, pas la ligne.
            expect(page.locator('.quick-cart-row')).to_have_count(1)
            page.keyboard.press("Control+Delete")
            expect(page.locator('.quick-cart-row')).to_have_count(0)
            self.assert_focus(page, '#productSearchInput')

    def test_tab_selects_highlighted_product_and_client(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            page.keyboard.type("GEDETEST")
            page.locator('#quick-product-0').wait_for(state="visible")
            page.keyboard.press("ArrowDown")
            page.keyboard.press("ArrowDown")
            expect(page.locator('#quick-product-1')).to_contain_text("PEMPASE")
            page.keyboard.press("Tab")
            self.assert_focus(page, '[data-line-key="draft"] [data-quick-field="packaging"]')
            page.keyboard.press("Tab")
            self.enter_quantity_discount(page, "3")
            page.keyboard.type("GEDETEST02")
            page.locator('#quick-product-0').wait_for(state="visible")
            page.keyboard.press("Tab")  # Sans fleche, accepter la premiere suggestion.
            self.assert_focus(page, '[data-product-id="%s"] [data-quick-field="quantity"]' % self.second.pk)
            self.enter_quantity_discount(page, "1")
            expect(page.locator('.quick-cart-row')).to_have_count(2)
            page.keyboard.press("F4")
            page.keyboard.type("A1234567Q")
            page.keyboard.press("Tab")
            expect(page.locator('#clientSelect')).to_have_value(str(self.customer.pk))
            self.assert_focus(page, '#clientNIF')
            page.keyboard.press("F4")
            self.assert_focus(page, '#clientSearchInput')
            page.keyboard.press("Escape")
            self.assert_focus(page, '#clientSearchInput')
            page.keyboard.press("F6")
            self.assert_focus(page, '.payment-amount')
            page.keyboard.press("F2")
            self.assert_focus(page, '#productSearchInput')

    def test_quantity_above_physical_stock_is_kept_with_negative_projection(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            self.select_product(page)
            self.choose_carton(page)
            page.keyboard.press("Control+a")
            page.keyboard.type("7")  # 84 U > 80 U.
            page.keyboard.press("Tab")
            expect(page.locator('.faccontrol-popup-root.is-open')).to_have_count(0)
            self.assert_focus(page, '[data-quick-field="discount"]')
            expect(page.locator('[data-quick-field="quantity"]')).to_have_value("7,000")
            expect(page.locator('[data-quick-field="packaging"]')).to_have_value(str(self.carton.pk))
            expect(page.locator('.quick-line-stock')).to_contain_text("-4")
            page.keyboard.press("F2")
            self.assert_focus(page, '#productSearchInput')

    def test_space_selects_after_arrow_navigation_and_preserves_spaces_in_search(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            page.keyboard.type("JUS MANGO")  # Espace dans un nom, aucune selection prematuree.
            expect(page.locator('#productSearchInput')).to_have_value("JUS MANGO")
            page.locator('#quick-product-0').wait_for(state="visible")
            page.keyboard.press("ArrowDown")
            expect(page.locator('#quick-product-0')).to_have_attribute('aria-selected', 'true')
            page.keyboard.press("Space")
            self.assert_focus(page, '[data-product-id="%s"] [data-quick-field="quantity"]' % self.second.pk)
            self.enter_quantity_discount(page, "2")
            expect(page.locator('.quick-cart-row')).to_have_count(1)
            page.keyboard.type("pem")
            page.locator('#quick-product-0').wait_for(state="visible")
            page.keyboard.press("ArrowDown")
            page.keyboard.press("Space")
            self.assert_focus(page, '[data-line-key="draft"] [data-quick-field="packaging"]')
            self.choose_carton(page)
            self.enter_quantity_discount(page, "2")
            expect(page.locator('.quick-cart-row')).to_have_count(2)

    def test_immediate_tab_fetches_and_selects_without_waiting_for_search_debounce(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            page.keyboard.type("GEDETEST02")
            page.keyboard.press("Tab")
            self.assert_focus(page, '[data-product-id="%s"] [data-quick-field="quantity"]' % self.second.pk)
            expect(page.locator('.quick-cart-row')).to_have_count(1)

    def test_rrr_still_finalizes_without_payment_or_stock_movement(self):
        from playwright.sync_api import expect

        StockPointDeVente.objects.filter(produit=self.product).update(quantite=0)
        with patch("facturation.views.FiscalOrchestrator.fiscalize_commande", return_value={"success":True, "channel":"MCF", "commande_id":1, "fiscal_transaction_id":"quick-rrr-test"}) as fiscalize:
            with self.browser() as page:
                page.locator('#documentMode').focus()
                page.keyboard.press("ArrowDown")
                expect(page.locator('#documentMode')).to_have_value("RRR")
                self.select_product(page)
                self.choose_carton(page)
                page.keyboard.press("Control+a")
                page.keyboard.type("2")
                page.keyboard.press("Tab")
                self.assert_focus(page, '[data-quick-field="discount"]')
                page.keyboard.press("Control+a")
                page.keyboard.type("1000")  # Montant unitaire de l'ajustement RRR existant.
                page.keyboard.press("Tab")
                page.keyboard.press("F4")
                page.keyboard.type("ADAM")
                page.keyboard.press("Enter")
                page.keyboard.press("Escape")
                page.keyboard.press("F6")
                self.assert_focus(page, '#btnValidate')
                page.keyboard.press("Control+Enter")
                expect(page.locator('#printArea')).to_be_visible()
                self.assert_focus(page, '#newInvoiceButton')
        fiscalize.assert_called_once()
        sale = Commande.objects.get()
        self.assertEqual((sale.type_facture, sale.nature_avoir), ("FA", "RRR"))
        self.assertEqual(sale.montant_total, 2320)
        self.assertFalse(Paiement.objects.exists())
        self.assertFalse(MouvementStock.objects.exists())
        self.assertEqual(StockPointDeVente.objects.get(produit=self.product).quantite, 0)

    def test_modes_share_cart_and_visual_grid_still_operates(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            self.select_product(page)
            self.choose_carton(page)
            self.enter_quantity_discount(page)
            page.locator('#posVisualMode').focus()
            page.keyboard.press("Enter")
            expect(page.locator('#productList .product-card')).to_have_count(2)
            expect(page.locator('#cartTableBody .cart-row')).to_have_count(1)
            expect(page.locator('#cartTableBody [data-visual-field="quantity"]')).to_have_value("2,000")
            self.assertIn("billing=visual", page.url)
            page.locator('#posQuickMode').focus()
            page.keyboard.press("Enter")
            self.assert_focus(page, '#productSearchInput')
            expect(page.locator('#productList .product-card')).to_have_count(0)
            expect(page.locator('[data-quick-field="quantity"]')).to_have_value("2,000")

    def test_visual_search_only_filters_grid_without_suggestion_list(self):
        """En POS visuel la recherche filtre la grille ; la liste reste au Billing rapide."""
        from playwright.sync_api import expect

        with self.browser() as page:
            cards = page.locator("#productList .product-card")
            suggestions = page.locator("#quickProductSuggestions")
            page.locator("#posVisualMode").click()
            expect(cards).to_have_count(2)

            page.locator("#productSearchInput").fill("pem")
            expect(cards).to_have_count(1)
            expect(cards).to_contain_text("PEMPASE")
            expect(suggestions).to_be_hidden()

            # Douchette : Entree ajoute le premier produit filtre, toujours sans liste.
            page.keyboard.press("Enter")
            expect(page.locator("#cartTableBody .cart-row")).to_have_count(1)
            expect(suggestions).to_be_hidden()

            page.locator("#posQuickMode").click()
            page.locator("#productSearchInput").fill("pem")
            expect(suggestions).to_be_visible()

    def test_default_mode_is_saved_without_changing_cart_and_used_on_next_opening(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            expect(page.locator('#posDefaultBillingMode')).to_have_value("quick")
            self.select_product(page)
            self.choose_carton(page)
            self.enter_quantity_discount(page, "2")
            page.locator('#posDefaultBillingMode').select_option("visual")
            expect(page.locator('#posDefaultBillingStatus')).to_contain_text("Enregistré")
            expect(page.locator('#pos-app')).to_have_attribute('data-billing-mode', 'quick')
            expect(page.locator('[data-quick-field="quantity"]')).to_have_value("2,000")
            page.goto(self.live_server_url + reverse("facturation:pos-view"), wait_until="load")
            expect(page.locator('#pos-app')).to_have_attribute('data-billing-mode', 'visual')
            expect(page.locator('#posDefaultBillingMode')).to_have_value("visual")
            expect(page.locator('#productList .product-card')).to_have_count(2)
            page.locator('#posQuickMode').click()
            page.reload(wait_until="load")
            expect(page.locator('#pos-app')).to_have_attribute('data-billing-mode', 'quick')
            expect(page.locator('#posDefaultBillingMode')).to_have_value("visual")
            page.locator('#posDefaultBillingMode').select_option("quick")
            expect(page.locator('#posDefaultBillingStatus')).to_contain_text("Enregistré")
            page.goto(self.live_server_url + reverse("facturation:pos-view"), wait_until="load")
            expect(page.locator('#pos-app')).to_have_attribute('data-billing-mode', 'quick')
            expect(page.locator('#posDefaultBillingMode')).to_have_value("quick")

    def test_failed_default_save_restores_previous_choice_and_keeps_cart(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            self.select_product(page, "GEDETEST02")
            self.enter_quantity_discount(page, "3")
            page.route("**/vente/mode-par-defaut/", lambda route: route.abort())
            page.locator('#posDefaultBillingMode').select_option("visual")
            expect(page.locator('#posDefaultBillingStatus')).to_contain_text("Impossible d'enregistrer")
            expect(page.locator('#posDefaultBillingMode')).to_have_value("quick")
            expect(page.locator('#posDefaultBillingMode')).to_be_enabled()
            expect(page.locator('[data-quick-field="quantity"]')).to_have_value("3,000")

    def test_existing_line_packaging_quantity_and_discount_are_editable_at_keyboard(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            self.select_product(page)
            self.choose_carton(page)
            self.enter_quantity_discount(page, "2")
            page.locator('[data-quick-field="packaging"]').focus()
            page.keyboard.press("ArrowUp")  # Carton -> Paquet.
            expect(page.locator('[data-quick-field="packaging"]')).to_have_value(str(self.packet.pk))
            expect(page.locator('.quick-line-price')).to_contain_text("5 500,00")
            expect(page.locator('.quick-line-stock')).to_contain_text("68")
            expect(page.locator('#netAPayer')).to_contain_text("12 760,00")
            page.keyboard.press("Tab")
            self.assert_focus(page, '[data-quick-field="quantity"]')
            page.keyboard.press("Control+a")
            page.keyboard.type("3")
            page.keyboard.press("Tab")
            self.assert_focus(page, '[data-quick-field="discount"]')
            page.keyboard.press("Control+a")
            page.keyboard.type("10%")
            page.keyboard.press("Tab")
            self.assert_focus(page, '#productSearchInput')
            expect(page.locator('.quick-line-stock')).to_contain_text("62")
            expect(page.locator('#netAPayer')).to_contain_text("17 226,00")
            expect(page.locator('.quick-line-active')).to_have_count(1)

    def test_pending_sale_restores_packaging_client_discounts_comments_and_payments(self):
        from playwright.sync_api import expect

        sale = PendingSale.objects.create(vendeur=self.user, point_de_vente=self.pdv, client=self.customer,
            panier_json=[{"id":self.product.pk, "conditionnement_id":self.carton.pk, "qty":2, "remise":100, "remise_input":"100"}],
            paiement_json=[{"raw_amount":"20000", "devise":"CDF", "mode":"ESPECES"}, {"raw_amount":"30000", "devise":"CDF", "mode":"CARD"}],
            commentaires_json=["Commande clavier"], payload_json={"document_mode":"FV", "remise_globale":50, "client_nif":"A1234567Q"})
        with self.browser() as page:
            page.keyboard.press("F7")
            page.locator('[data-bs-target="#pendingSalesModal"]').focus()
            page.keyboard.press("Enter")
            resume = page.locator('#pendingSalesList button.btn-outline-primary')
            resume.wait_for(state="visible")
            resume.focus()
            page.keyboard.press("Enter")
            expect(page.locator('.faccontrol-popup-root.is-open')).to_be_visible()
            page.keyboard.press("Enter")
            expect(page.locator('[data-quick-field="packaging"]')).to_have_value(str(self.carton.pk))
            expect(page.locator('[data-quick-field="quantity"]')).to_have_value("2,000")
            expect(page.locator('[data-quick-field="discount"]')).to_have_value("100")
            expect(page.locator('#clientSelect')).to_have_value(str(self.customer.pk))
            expect(page.locator('#remiseGlobale')).to_have_value("50")
            expect(page.locator('.comment-input')).to_have_value("Commande clavier")
            expect(page.locator('.payment-amount').nth(0)).to_have_value("20000")
            expect(page.locator('.payment-amount').nth(1)).to_have_value("30000")

    def test_english_interface_and_desktop_sizes(self):
        from playwright.sync_api import expect

        with self.browser(language="en") as page:
            expect(page.locator('#posQuickMode')).to_contain_text("Quick Billing")
            expect(page.locator('#productSearchInput')).to_have_attribute('placeholder', 'Scan a barcode or search for a product...')
            expect(page.locator('#posCartTable thead')).to_contain_text("Packaging")
            expect(page.locator('#posCartTable thead')).to_contain_text("Available stock")
            self.select_product(page, "GEDETEST02")
            self.enter_quantity_discount(page, "1")
            for width, height in ((1366, 768), (1440, 900), (1920, 1080), (800, 600)):
                page.set_viewport_size({"width":width, "height":height})
                self.assertLessEqual(page.evaluate('document.documentElement.scrollWidth'), width + 1)
                if width >= 1366:
                    page.wait_for_timeout(350)  # Existing responsive sidebar/margin transition.
                    page.keyboard.press("F6")
                    page.keyboard.press("Tab")
                    page.keyboard.press("Tab")
                    page.keyboard.press("Tab")
                    self.assert_focus(page, '#btnValidate')
                    box = page.locator('#btnValidate').bounding_box()
                    self.assertLessEqual(box['y'] + box['height'], height)
                    if height >= 900:
                        for selector in ('#clientSearchInput', '#netAPayer', '.payment-amount'):
                            box = page.locator(selector).bounding_box()
                            self.assertGreaterEqual(box['y'], 60)
                            self.assertLessEqual(box['y'] + box['height'], height)
                    page.screenshot(path=str(self.qa_dir / f'quick-billing-en-{width}x{height}.png'))

    def test_complete_invoice_with_tab_and_enter_only_and_next_sale_focus(self):
        from playwright.sync_api import expect

        with patch("facturation.views.FiscalOrchestrator.fiscalize_commande", return_value={"success":True, "channel":"MCF", "commande_id":1, "fiscal_transaction_id":"tab-only"}):
            with self.browser() as page:
                self.assert_focus(page, '#productSearchInput')
                page.keyboard.type("GEDETEST01")
                page.locator('#quick-product-0').wait_for(state="visible")
                page.keyboard.press("Enter")
                self.choose_carton(page)
                page.keyboard.type("2")  # Automatically selects the existing 1.
                page.keyboard.press("Tab")
                self.assert_focus(page, '[data-quick-field="discount"]:focus')
                page.keyboard.type("0")
                page.keyboard.press("Tab")
                self.assert_focus(page, '#productSearchInput')
                page.keyboard.type("GEDETEST02")
                page.locator('#quick-product-0').wait_for(state="visible")
                page.keyboard.press("Enter")
                page.keyboard.type("1")
                page.keyboard.press("Tab")
                page.keyboard.type("0")
                page.keyboard.press("Tab")
                page.keyboard.press("Tab")  # Empty search -> operation, skipping secondary buttons and rows.
                self.assert_focus(page, '#documentMode')
                page.keyboard.press("Tab")
                self.assert_focus(page, '#clientSearchInput')
                page.keyboard.type("ADAM")
                page.keyboard.press("Enter")
                expect(page.locator('#clientSelect')).to_have_value(str(self.customer.pk))
                page.keyboard.press("Tab")
                self.assert_focus(page, '#clientNIF')
                page.keyboard.press("Tab")
                self.assert_focus(page, '#remiseGlobale')
                page.keyboard.press("Tab")
                self.assert_focus(page, '.payment-amount')
                page.keyboard.type("133400")
                page.keyboard.press("Tab")
                self.assert_focus(page, '.payment-currency')
                page.keyboard.press("Tab")
                self.assert_focus(page, '.payment-mode')
                for _ in range(page.locator('.payment-mode option').count()):
                    if page.locator('.payment-mode').input_value() == 'CARD':
                        break
                    page.keyboard.press("ArrowDown")
                expect(page.locator('.payment-mode')).to_have_value('CARD')
                page.keyboard.press("Tab")
                self.assert_focus(page, '#btnValidate')
                page.screenshot(path=str(self.qa_dir / 'quick-billing-tab-before-validation.png'))
                page.keyboard.press("Enter")
                expect(page.locator('#printArea')).to_be_visible()
                self.assert_focus(page, '#newInvoiceButton')
                page.keyboard.press('Enter')  # Nouvelle facture returns to the existing cash register.
                self.assert_focus(page, '#productSearchInput')
                expect(page.locator('.quick-cart-row')).to_have_count(0)
                expect(page.locator('#clientSelect')).to_have_value("")
                expect(page.locator('#remiseGlobale')).to_have_value("0")
                expect(page.locator('#netAPayer')).to_contain_text("0,00")
                self.assertEqual(page.locator('#pos-app').get_attribute('data-active-pos'), str(self.pdv.pk))
                expect(page.locator('#pos-app')).to_have_attribute('data-billing-mode', 'quick')
                page.keyboard.type("GEDETEST01")
                page.locator('#quick-product-0').wait_for(state="visible")
                expect(page.locator('#quick-product-0 .quick-product-stock')).to_contain_text("56")
        sale = Commande.objects.get()
        self.assertEqual(sale.montant_total, 133400)
        self.assertEqual(LigneCommande.objects.count(), 2)
        self.assertEqual(Paiement.objects.get().mode_paiement_id, "CARD")
        invoice_url = reverse('facturation:facture-detail', args=[sale.pk])
        self.assertEqual(self.client.get(invoice_url)['X-Frame-Options'], 'DENY')
        self.assertEqual(self.client.get(invoice_url, {'billing': 'quick'})['X-Frame-Options'], 'DENY')
        self.assertEqual(StockPointDeVente.objects.get(produit=self.product).quantite, 56)

    def test_reverse_tab_skips_single_packaging_and_visits_summary_in_reverse(self):
        from playwright.sync_api import expect
        with self.browser() as page:
            self.select_product(page, "GEDETEST02")
            page.keyboard.press("Shift+Tab")
            self.assert_focus(page, '#productSearchInput')
            page.keyboard.press("Shift+Tab")
            self.assert_focus(page, '[data-quick-field="discount"]')
            page.keyboard.press("Shift+Tab")
            self.assert_focus(page, '[data-quick-field="quantity"]')
            page.keyboard.press("Shift+Tab")
            self.assert_focus(page, '#productSearchInput')
            page.keyboard.press("Tab")
            self.assert_focus(page, '#documentMode')
            page.keyboard.press("Tab")
            page.keyboard.press("Escape")  # Close client suggestions in place.
            self.assert_focus(page, '#clientSearchInput')
            page.keyboard.press("ArrowDown")
            expect(page.locator('#clientSearchResults .client-search-option.active')).to_be_visible()
            page.keyboard.press("Escape")
            self.assert_focus(page, '#clientSearchInput')
            for selector in ('#clientNIF', '#remiseGlobale', '.payment-amount', '.payment-currency', '.payment-mode', '#btnValidate'):
                page.keyboard.press("Tab")
                self.assert_focus(page, selector)
            for selector in ('.payment-mode', '.payment-currency', '.payment-amount', '#remiseGlobale', '#clientNIF', '#clientSearchInput', '#documentMode', '#productSearchInput'):
                page.keyboard.press("Shift+Tab")
                self.assert_focus(page, selector)

    def test_payment_error_returns_to_amount_and_shortcut_works_from_product_line(self):
        from playwright.sync_api import expect

        with patch("facturation.views.FiscalOrchestrator.fiscalize_commande", return_value={"success":True, "channel":"MCF", "commande_id":1, "fiscal_transaction_id":"payment-correction"}):
            with self.browser() as page:
                self.select_product(page, "GEDETEST02")
                self.enter_quantity_discount(page, "1")
                page.keyboard.press("F4")
                page.keyboard.type("ADAM")
                page.keyboard.press("Enter")
                page.keyboard.press("F6")
                page.keyboard.type("1")
                page.keyboard.press("Control+Enter")
                expect(page.locator('.faccontrol-popup-root.is-open')).to_be_visible()
                self.assert_focus(page, '.faccontrol-popup-root.is-open .faccontrol-popup-btn-primary')
                page.keyboard.press("Enter")
                expect(page.locator('.faccontrol-popup-root.is-open')).to_have_count(0)
                self.assert_focus(page, '.payment-amount')
                expect(page.locator('.quick-cart-row')).to_have_count(1)
                page.keyboard.type("41400")
                page.keyboard.press("F2")
                page.keyboard.press("ArrowUp")  # Edit an existing row without a mouse.
                self.assert_focus(page, '[data-quick-field="quantity"]')
                page.keyboard.press("Control+Enter")
                expect(page.locator('#printArea')).to_be_visible()
                self.assert_focus(page, '#newInvoiceButton')
        self.assertEqual(Paiement.objects.get().montant_verse, 41400)

    def test_existing_invoice_page_print_formats_and_new_invoice_in_english(self):
        from playwright.sync_api import expect

        with patch("facturation.views.FiscalOrchestrator.fiscalize_commande", return_value={"success":True, "channel":"MCF", "commande_id":1, "fiscal_transaction_id":"invoice-preview"}) as fiscalize:
            with self.browser(language='en') as page:
                errors = []
                page.on('pageerror', lambda error: errors.append(str(error)))
                page.add_init_script("window.print = () => document.documentElement.dataset.printCalled = '1'")
                self.select_product(page, 'GEDETEST02')
                self.enter_quantity_discount(page, '1')
                page.keyboard.press('F4')
                page.keyboard.type('ADAM')
                page.keyboard.press('Enter')
                expect(page.locator('#clientSelect')).to_have_value(str(self.customer.pk))
                page.keyboard.press('F6')
                page.keyboard.press('Control+Enter')
                expect(page.locator('#newInvoiceButton')).to_have_text(' New Invoice')
                self.assert_focus(page, '#newInvoiceButton')
                expect(page.locator('iframe')).to_have_count(0)
                expect(page.locator('#printArea')).to_contain_text('JUS MANGO')
                expect(page.locator('.pagetitle')).to_contain_text('Invoice #')
                expect(page.get_by_role('link', name='Download PDF', exact=True)).to_be_visible()
                self.assertEqual(page.locator('#main').evaluate('(el) => getComputedStyle(el).transitionDuration'), '0s')
                self.assertEqual(page.locator('html').evaluate('(el) => getComputedStyle(el).scrollBehavior'), 'auto')
                page.get_by_role('button', name='Print', exact=True).click()
                expect(page.locator('html')).to_have_attribute('data-print-called', '1')
                for width, height in ((1920, 1080), (390, 844)):
                    page.set_viewport_size({'width': width, 'height': height})
                    expect(page.locator('#newInvoiceButton')).to_be_visible()
                    expect(page.locator('#printArea')).to_be_visible()
                    self.assertLessEqual(page.evaluate('document.documentElement.scrollWidth'), width)
                    page.screenshot(path=str(self.qa_dir / f'quick-billing-invoice-en-{width}.png'))
                page.set_viewport_size({'width': 1366, 'height': 768})
                page.locator('#print-format-selector').select_option('TICKET_80MM')
                expect(page.locator('#t80-print-zone')).to_be_visible()
                expect(page.locator('#newInvoiceButton')).to_have_text(' New Invoice')
                self.assertIn('billing=quick', page.url)
                page.locator('#print-format-selector').select_option('A4')
                expect(page.locator('#printArea')).to_be_visible()
                expect(page.get_by_role('link', name='Download PDF', exact=True)).to_be_visible()
                page.locator('#newInvoiceButton').click()
                expect(page.locator('#pos-products-column')).to_be_visible()
                expect(page.locator('#pos-checkout-column')).to_be_visible()
                self.assert_focus(page, '#productSearchInput')
                expect(page.locator('#clientSelect')).to_have_value('')
                expect(page.locator('.payment-amount')).to_have_value('')
                page.keyboard.type('GEDETEST02')
                expect(page.locator('#quick-product-0 .quick-product-stock')).to_contain_text('99')
                self.assertFalse(errors)
        fiscalize.assert_called_once()
        self.assertEqual(Commande.objects.count(), 1)

    def test_secondary_actions_are_keyboard_accessible_and_multiple_payments_are_sequential(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            for selector in ('#posVisualMode', '#posDefaultBillingMode', '#productSearchClear', '#btnAddPayment', '#btnSuspendSale', '#btnValidateProforma'):
                expect(page.locator(selector)).to_have_attribute('tabindex', '-1')
            page.keyboard.press("F7")
            self.assert_focus(page, '#posVisualMode')
            self.assertTrue(page.locator('#quickSecondaryActions').evaluate('(el) => el.open'))
            # The secondary route preserves ordinary Tab, including add-payment and Pro-Forma.
            visited = set()
            for _ in range(35):
                visited.add(page.evaluate('document.activeElement.id'))
                if 'btnValidateProforma' in visited and 'btnAddPayment' in visited:
                    break
                page.keyboard.press("Tab")
            self.assertIn('btnAddPayment', visited)
            self.assertIn('btnValidateProforma', visited)
            page.keyboard.press("Escape")
            self.assert_focus(page, '#productSearchInput')
            page.keyboard.press("F7")
            # Test payment addition through the secondary keyboard route.
            for _ in range(35):
                if page.evaluate('document.activeElement.id') == 'btnAddPayment':
                    break
                page.keyboard.press("Tab")
            self.assert_focus(page, '#btnAddPayment')
            page.keyboard.press("Enter")
            expect(page.locator('.payment-row')).to_have_count(2)
            page.keyboard.press("F6")
            self.assert_focus(page, '.payment-row:first-child .payment-amount')
            for selector in ('.payment-currency', '.payment-mode'):
                page.keyboard.press("Tab")
                self.assert_focus(page, selector + ':focus')
            page.keyboard.press("Tab")
            self.assert_focus(page, '.payment-row:nth-child(2) .payment-amount')
            page.keyboard.press("Tab")
            page.keyboard.press("Tab")
            page.keyboard.press("Tab")
            self.assert_focus(page, '#btnValidate')

    def test_fiscal_confirmation_accepts_enter_and_cancels_with_escape_without_losing_cart(self):
        from playwright.sync_api import expect

        with self.browser() as page:
            self.select_product(page, "GEDETEST02")
            self.enter_quantity_discount(page, "1")
            page.keyboard.press("F4")
            page.keyboard.type("ADAM")
            page.keyboard.press("Enter")
            requests = []
            def fiscal_response(route):
                requests.append(route.request.post_data_json)
                if len(requests) <= 2:
                    route.fulfill(status=409, json={"success":False, "requires_fiscal_confirmation":True, "message":"Confirmer le canal MCF", "fiscal_transaction_id":"keyboard-confirm"})
                else:
                    route.fulfill(status=400, json={"success":False, "error":"Validation indisponible"})
            page.route("**/vente/", fiscal_response)
            page.keyboard.press("Control+Enter")
            expect(page.locator('.faccontrol-popup-root.is-open')).to_be_visible()
            self.assert_focus(page, '.faccontrol-popup-root.is-open .faccontrol-popup-btn-primary')
            page.keyboard.press("Shift+Tab")
            self.assert_focus(page, '.faccontrol-popup-root.is-open .faccontrol-popup-btn-secondary')
            page.keyboard.press("Tab")
            self.assert_focus(page, '.faccontrol-popup-root.is-open .faccontrol-popup-btn-primary')
            page.keyboard.press("Escape")
            expect(page.locator('.faccontrol-popup-message')).to_contain_text("enregistr")
            page.keyboard.press("Enter")
            expect(page.locator('.quick-cart-row')).to_have_count(1)
            page.keyboard.press("F6")
            page.keyboard.press("Control+Enter")
            expect(page.locator('.faccontrol-popup-root.is-open')).to_be_visible()
            self.assert_focus(page, '.faccontrol-popup-root.is-open .faccontrol-popup-btn-primary')
            page.keyboard.press("Enter")
            expect(page.locator('.faccontrol-popup-message')).to_contain_text("Validation indisponible")
            page.keyboard.press("Enter")
            self.assert_focus(page, '#documentMode')
            self.assertEqual(len(requests), 3)
            self.assertTrue(requests[-1]['allow_mcf_fallback'])
            self.assertEqual(requests[-1]['fiscal_transaction_id'], 'keyboard-confirm')
            expect(page.locator('.quick-cart-row')).to_have_count(1)

    def test_existing_rows_can_be_revisited_and_removed_without_mouse(self):
        from playwright.sync_api import expect
        with self.browser() as page:
            self.select_product(page, "GEDETEST01")
            self.choose_carton(page)
            self.enter_quantity_discount(page, "2")
            self.select_product(page, "GEDETEST02")
            self.enter_quantity_discount(page, "1")
            page.keyboard.press("ArrowUp")
            self.assert_focus(page, '[data-product-id="%s"] [data-quick-field="quantity"]' % self.second.pk)
            page.keyboard.press("Alt+ArrowUp")
            self.assert_focus(page, '[data-product-id="%s"] [data-quick-field="quantity"]' % self.product.pk)
            page.keyboard.type("3")
            page.keyboard.press("Tab")
            page.keyboard.press("Tab")
            expect(page.locator('[data-product-id="%s"] [data-quick-field="quantity"]' % self.product.pk)).to_have_value("3,000")
            page.keyboard.press("Control+Delete")  # Active line, even from the product search.
            expect(page.locator('.quick-cart-row')).to_have_count(1)
            self.assert_focus(page, '#productSearchInput')

    def test_f8_uses_existing_proforma_action_outside_primary_flow(self):
        from playwright.sync_api import expect
        from proforma.models import Proforma
        with self.browser() as page:
            self.select_product(page, "GEDETEST02")
            self.enter_quantity_discount(page, "1")
            page.keyboard.press("F4")
            page.keyboard.type("ADAM")
            page.keyboard.press("Enter")
            expect(page.locator('#clientSelect')).to_have_value(str(self.customer.pk))
            page.keyboard.press("F8")
            page.wait_for_url('**' + reverse('proforma:list') + '*/?created=1')
        self.assertEqual(Proforma.objects.count(), 1)
        self.assertFalse(Commande.objects.exists())
        self.assertFalse(MouvementStock.objects.exists())
