import { test as base, expect, type Page } from "@playwright/test"
import { attachConsoleMonitor } from "../fixtures/console-monitor"

const API_BASE = "/api"

export const test = base.extend({
    page: async ({ page }, use) => {
        const monitor = attachConsoleMonitor(page)

        const origGoto = page.goto.bind(page)
        const origReload = page.reload.bind(page)
        const origGoBack = page.goBack.bind(page)
        const origGoForward = page.goForward.bind(page)

        page.goto = ((url: string, opts?: any) =>
            origGoto(url, { waitUntil: "domcontentloaded", ...opts })) as typeof page.goto
        page.reload = ((opts?: any) => origReload({ waitUntil: "domcontentloaded", ...opts })) as typeof page.reload
        page.goBack = ((opts?: any) => origGoBack({ waitUntil: "domcontentloaded", ...opts })) as typeof page.goBack
        page.goForward = ((opts?: any) =>
            origGoForward({ waitUntil: "domcontentloaded", ...opts })) as typeof page.goForward

        await use(page)
        monitor.assertNoErrors()
    },
})

export async function waitForSpaReady(page: Page): Promise<string> {
    await page.waitForLoadState("domcontentloaded")
    await expect(page.locator("#appContainer")).not.toBeEmpty({ timeout: 15000 })
    const url = page.url()
    const match = url.match(/\/([a-z]{2})(\/|$)/)
    return match?.[1] || "de"
}

export async function navigateToRoute(page: Page, routePath: string): Promise<void> {
    const url = page.url()
    const match = url.match(/\/([a-z]{2})(\/|$)/)
    const lang = match?.[1] || "de"
    const fullPath = routePath === "/" ? `/${lang}` : `/${lang}${routePath}`
    await page.goto(fullPath)
    await page.waitForLoadState("domcontentloaded")
    await expect(page.locator("#appContainer")).not.toBeEmpty({ timeout: 15000 })
}

export async function clickSpaLink(page: Page, linkSelector: string): Promise<void> {
    await page.evaluate(() => {
        ;(window as any).__spa_navigation_marker = true
    })
    await page.locator(linkSelector).first().click()
    await page.waitForLoadState("domcontentloaded")
    const markerExists = await page.evaluate(() => {
        return (window as any).__spa_navigation_marker === true
    })
    if (!markerExists) {
        throw new Error(`SPA navigation failed: full page reload detected when clicking "${linkSelector}"`)
    }
}

export { expect, API_BASE, type Page }
