[CmdletBinding()]
param(
    [string]$BaseUrl = 'http://127.0.0.1/CCW',
    [string]$Username = 'admin',
    [string]$Password = 'admin123',
    [string]$ArtifactDirectory = '',
    [string]$BrowserPath = ''
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

. (Join-Path $PSScriptRoot 'browser_automation_helpers.ps1')

function Assert-BrowserTrue {
    param(
        [object]$Condition,
        [string]$Message
    )

    if (-not [bool]$Condition) {
        throw $Message
    }
}

$resolvedBaseUrl = Resolve-BrowserBaseUrl -BaseUrl $BaseUrl
$session = $null
$results = [ordered]@{
    browser_engine = 'winforms-webbrowser'
}

try {
    $session = Start-BrowserAutomationSession -StartUrl "$resolvedBaseUrl/pages/login.php" -ArtifactDirectory $ArtifactDirectory
    $results['artifact_dir'] = [string]$session.ArtifactDirectory

    $loginTitle = Get-BrowserPageTitle -Session $session
    $loginCsrfToken = Get-BrowserFormCsrfToken -Session $session -FormActionSuffix '../process/login.php'
    Assert-BrowserTrue -Condition ($loginTitle -match 'CCW') -Message "Login page title was unexpected: $loginTitle"
    Assert-BrowserTrue -Condition (-not [string]::IsNullOrWhiteSpace($loginCsrfToken)) -Message 'Login form CSRF token was not found in browser automation.'
    $results['login_url'] = Get-BrowserCurrentUrl -Session $session
    $results['login_title'] = $loginTitle
    $results['login_screenshot'] = Save-BrowserScreenshot -Session $session -OutputPath (Join-Path $session.ArtifactDirectory '01-login.png')

    Submit-BrowserLogin -Session $session -BaseUrl $resolvedBaseUrl -Username $Username -Password $Password -DisplayMode 'web'
    Wait-BrowserUrlContains -Session $session -ExpectedFragment '/pages/dashboard.php' -TimeoutSeconds 20

    $dashboardUrl = Get-BrowserCurrentUrl -Session $session
    $dashboardTitle = Get-BrowserPageTitle -Session $session
    Assert-BrowserTrue -Condition ($dashboardUrl -match 'dashboard\.php') -Message "Unexpected post-login URL: $dashboardUrl"
    Assert-BrowserTrue -Condition ($dashboardTitle -match 'CCW') -Message "Dashboard title was unexpected: $dashboardTitle"
    Assert-BrowserTrue -Condition (Test-BrowserHasClassName -Session $session -ClassName 'dashboard-console') -Message 'Dashboard shell was not rendered as expected.'
    Assert-BrowserTrue -Condition (Test-BrowserHasClassName -Session $session -ClassName 'dashboard-kpi-grid') -Message 'Dashboard KPI grid was not rendered as expected.'
    $results['dashboard_url'] = $dashboardUrl
    $results['dashboard_title'] = $dashboardTitle
    $results['dashboard_screenshot'] = Save-BrowserScreenshot -Session $session -OutputPath (Join-Path $session.ArtifactDirectory '02-dashboard.png')

    Navigate-BrowserPage -Session $session -Url "$resolvedBaseUrl/pages/queue.php" -TimeoutSeconds 20
    $queueUrl = Get-BrowserCurrentUrl -Session $session
    $queueTitle = Get-BrowserPageTitle -Session $session
    $queueHasGrid = Test-BrowserHasClassName -Session $session -ClassName 'queue-grid'
    $queueHasEmptyState = Test-BrowserHasClassName -Session $session -ClassName 'empty-state'
    Assert-BrowserTrue -Condition ($queueUrl -match 'queue\.php') -Message "Queue URL was unexpected: $queueUrl"
    Assert-BrowserTrue -Condition ($queueTitle -match 'CCW') -Message "Queue title was unexpected: $queueTitle"
    Assert-BrowserTrue -Condition (Test-BrowserHasClassName -Session $session -ClassName 'page-hero') -Message 'Queue hero panel was not rendered as expected.'
    Assert-BrowserTrue -Condition ($queueHasGrid -or $queueHasEmptyState) -Message 'Queue page did not render either queue cards or the empty state.'
    $results['queue_url'] = $queueUrl
    $results['queue_title'] = $queueTitle
    $results['queue_state'] = if ($queueHasGrid) { 'queue-grid' } else { 'empty-state' }
    $results['queue_screenshot'] = Save-BrowserScreenshot -Session $session -OutputPath (Join-Path $session.ArtifactDirectory '03-queue.png')

    $jobDetailsHref = Get-BrowserFirstLinkHrefContaining -Session $session -Fragment 'job_details.php?id='
    if ([string]::IsNullOrWhiteSpace($jobDetailsHref)) {
        $results['job_details_browser_probe'] = 'skipped:no-queue-item'
    } else {
        Navigate-BrowserPage -Session $session -Url $jobDetailsHref -TimeoutSeconds 20
        $jobDetailsUrl = Get-BrowserCurrentUrl -Session $session
        $jobDetailsTitle = Get-BrowserPageTitle -Session $session
        Assert-BrowserTrue -Condition ($jobDetailsUrl -match 'job_details\.php\?id=\d+') -Message "Job details URL was unexpected: $jobDetailsUrl"
        Assert-BrowserTrue -Condition ($jobDetailsTitle -match 'CCW') -Message "Job details title was unexpected: $jobDetailsTitle"
        Assert-BrowserTrue -Condition (Test-BrowserHasClassName -Session $session -ClassName 'job-summary-stats') -Message 'Job details summary stats were not rendered as expected.'
        Assert-BrowserTrue -Condition (Test-BrowserHasClassName -Session $session -ClassName 'job-meta-grid') -Message 'Job details meta grid was not rendered as expected.'
        $results['job_details_url'] = $jobDetailsUrl
        $results['job_details_title'] = $jobDetailsTitle
        $results['job_details_screenshot'] = Save-BrowserScreenshot -Session $session -OutputPath (Join-Path $session.ArtifactDirectory '04-job-details.png')
        $results['job_details_browser_probe'] = 'passed'
    }

    $results.GetEnumerator() | ForEach-Object {
        '{0}: {1}' -f $_.Key, $_.Value
    }
} finally {
    if ($null -ne $session) {
        Stop-BrowserAutomationSession -Session $session
    }
}
