<?php

namespace MintyPHP\Tests\Architecture;

use PHPUnit\Framework\TestCase;

class FilterDrawerContractTest extends TestCase
{
    use ProjectFileAssertionSupport;

    private function readTemplatePageModule(string $templateFile): string
    {
        $template = $this->readProjectFile($templateFile);
        $matched = preg_match("/assetVersion\\('js\\/pages\\/([^']+\\.js)'\\)/", $template, $captures);
        $this->assertSame(1, $matched, $templateFile . ' must reference a page module via assetVersion().');

        return $this->readProjectFile('web/js/pages/' . $captures[1]);
    }

    private function usesSharedListFiltersPartial(string $content): bool
    {
        return str_contains($content, "require templatePath('partials/app-list-filters.phtml');");
    }

    /**
     * @return list<string>
     */
    private function drawerTemplateFiles(): array
    {
        return [
            'pages/address-book/index(default).phtml',
            'pages/admin/users/index(default).phtml',
            'pages/admin/tenants/index(default).phtml',
            'pages/admin/departments/index(default).phtml',
            'pages/admin/roles/index(default).phtml',
            'pages/admin/permissions/index(default).phtml',
            'pages/admin/mail-log/index(default).phtml',
            'pages/admin/scheduled-jobs/index(default).phtml',
            'pages/admin/api-audit/index(default).phtml',
            'pages/admin/import-audit/index(default).phtml',
            'pages/admin/user-lifecycle-audit/index(default).phtml',
            'pages/admin/system-audit/index(default).phtml',
        ];
    }

    public function testDrawerTemplatesUseStandardListWrapperForFilterExperience(): void
    {
        foreach ($this->drawerTemplateFiles() as $file) {
            $content = $this->readProjectFile($file);
            $moduleContent = $this->readTemplatePageModule($file);
            $usesPartial = $this->usesSharedListFiltersPartial($content);
            $this->assertStringContainsString('initStandardListPage(', $moduleContent, $file);
            $this->assertStringContainsString("mode: 'drawer'", $moduleContent, $file);
            $this->assertStringNotContainsString('initListFilterExperience(', $moduleContent, $file);
            if (!$usesPartial) {
                $this->assertStringContainsString('role="dialog"', $content, $file);
                $this->assertStringContainsString('aria-modal="true"', $content, $file);
                $this->assertStringContainsString('aria-labelledby="', $content, $file);
                $this->assertStringContainsString('data-filter-live-region', $content, $file);
            }
            $this->assertStringNotContainsString('data-filter-drawer-draft-hint', $content, $file);
        }
    }

    public function testAddressBookSaveFilterReadsAppliedGridState(): void
    {
        $content = $this->readProjectFile('pages/address-book/index(default).phtml');
        $moduleContent = $this->readProjectFile('web/js/pages/address-book-index.js');

        $this->assertStringContainsString('new URL(gridConfig.baseUrl()).searchParams', $moduleContent);
        $this->assertStringNotContainsString('const state = collectFilterState();', $moduleContent);
        $this->assertStringContainsString('data-filter-chips-clear-all-label', $content);
        $this->assertStringContainsString('data-filter-chips-remove-label', $content);
        $this->assertStringContainsString('data-filter-live-applied-message', $content);
        $this->assertStringContainsString('data-filter-live-removed-message', $content);
        $this->assertStringContainsString('data-filter-live-cleared-message', $content);
    }

    public function testUsersResetKeepsTenantParam(): void
    {
        $moduleContent = $this->readProjectFile('web/js/pages/admin-users-index.js');
        $this->assertStringContainsString("preserveFilterParams: ['tenant']", $moduleContent);
    }

    public function testFilterDrawerAndExperienceImplementFocusTrapAndDirtyApplyUi(): void
    {
        $drawerJs = $this->readProjectFile('web/js/components/app-filter-drawer.js');
        $this->assertStringContainsString("drawer.setAttribute('role', 'dialog')", $drawerJs);
        $this->assertStringContainsString("drawer.setAttribute('aria-modal', 'true')", $drawerJs);
        $this->assertStringContainsString("if (event.key !== 'Tab') {return;}", $drawerJs);
        $this->assertStringContainsString('if (lastTrigger && typeof lastTrigger.focus === \'function\'', $drawerJs);

        $experienceJs = $this->readProjectFile('web/js/pages/app-list-filter-experience.js');
        $this->assertStringContainsString('countDraftChanges(', $experienceJs);
        $this->assertStringContainsString('countActiveDraftFilters(', $experienceJs);
        $this->assertStringContainsString('drawerController.setApplyEnabled(changedCount > 0);', $experienceJs);
        $this->assertStringContainsString('drawerController.setApplyCount(activeCount);', $experienceJs);
        $this->assertStringContainsString('announceLive(', $experienceJs);

        $stateJs = $this->readProjectFile('web/js/pages/app-list-filter-state.js');
        $this->assertStringContainsString('buildChipsFromMeta', $stateJs);
        $this->assertStringContainsString('removeChipFromMetaState', $stateJs);
        $this->assertStringContainsString('clearMetaState', $stateJs);
    }

    public function testSharedListFiltersPartialKeepsDrawerAccessibilityContract(): void
    {
        $content = $this->readProjectFile('templates/partials/app-list-filters.phtml');
        $this->assertStringContainsString('renderGridFilterToolbar(', $content);
        $this->assertStringContainsString('data-filter-drawer-open', $content);
        $this->assertStringContainsString('data-filter-drawer-apply', $content);
        $this->assertStringContainsString('data-active-filter-chips', $content);
        $this->assertStringContainsString('data-filter-chips-clear-all-label', $content);
        $this->assertStringContainsString('data-filter-chips-remove-label', $content);
        $this->assertStringContainsString('role="dialog"', $content);
        $this->assertStringContainsString('aria-modal="true"', $content);
        $this->assertStringContainsString('aria-labelledby=', $content);
        $this->assertStringContainsString('data-filter-live-region', $content);
        $this->assertStringContainsString('data-filter-live-applied-message', $content);
        $this->assertStringContainsString('data-filter-live-removed-message', $content);
        $this->assertStringContainsString('data-filter-live-cleared-message', $content);
    }
}
