<?php

namespace MintyPHP\Tests\Architecture;

use PHPUnit\Framework\TestCase;

class FrontendComponentRuntimeContractTest extends TestCase
{
    use ProjectFileAssertionSupport;

    public function testEntrypointsUseRuntimeRegistrationWithoutSideeffectComponentImports(): void
    {
        $defaultEntry = $this->readProjectFile('web/js/app-init.js');
        $loginEntry = $this->readProjectFile('web/js/app-login-init.js');

        $this->assertStringContainsString("import { createComponentRuntime } from './core/app-component-runtime.js';", $defaultEntry);
        $this->assertStringContainsString("import { createComponentRuntime } from './core/app-component-runtime.js';", $loginEntry);
        $this->assertDoesNotMatchRegularExpression('/import\s+[\'"]\.\/components\//', $defaultEntry);
        $this->assertDoesNotMatchRegularExpression('/import\s+[\'"]\.\/components\//', $loginEntry);

        $this->assertStringContainsString("runtime.register('sidebar-toggle', initSidebarToggle", $defaultEntry);
        $this->assertStringContainsString("runtime.register('global-search', initGlobalSearch", $defaultEntry);
        $this->assertStringContainsString("await mountModuleComponentsByPhase('late');", $defaultEntry);
        $this->assertStringContainsString('moduleRuntimeComponents', $defaultEntry);
        $this->assertStringContainsString("selector: '[data-app-component=\"tabs\"]'", $defaultEntry);
        $this->assertStringContainsString('runtime.mountAll();', $defaultEntry);

        $this->assertStringContainsString("runtime.register('password-hints', initPasswordHints", $loginEntry);
        $this->assertStringContainsString("runtime.register('password-toggle', initPasswordToggles", $loginEntry);
        $this->assertStringContainsString("runtime.register('login-submit-lock', initLoginSubmitLock", $loginEntry);
        $this->assertStringContainsString('runtime.mountAll();', $loginEntry);
    }

    public function testRuntimeMigratedComponentsDoNotAutoInitialize(): void
    {
        $componentFiles = [
            'web/js/components/app-flash-auto-dismiss.js',
            'web/js/components/app-fslightbox-refresh.js',
            'web/js/components/app-password-hints.js',
            'web/js/components/app-copy-badge.js',
            'web/js/components/app-multiselect-init.js',
            'web/js/components/app-nav-history.js',
            'web/js/components/app-toggle-sidebar.js',
            'web/js/components/app-toggle-aside-panels.js',
            'web/js/components/app-toggle-details-aside.js',
            'web/js/components/app-global-search.js',
            'web/js/components/app-theme-toggle.js',
            'web/js/components/app-contrast-toggle.js',
            'web/js/components/app-confirm-actions.js',
            'web/js/components/app-details-state.js',
            'web/js/components/app-tenant-switcher.js',
            'web/js/components/app-color-default-toggle.js',
            'web/js/components/app-custom-field-options-toggle.js',
            'web/js/components/app-tenant-sso-toggle.js',
            'web/js/components/app-settings-telemetry.js',
            'web/js/components/app-standard-detail-page.js',
            'web/js/components/app-auto-submit.js',
            'modules/bookmarks/web/js/components/app-bookmark-save.js',
            'modules/bookmarks/web/js/components/app-bookmark-panel.js',
            'web/js/components/app-password-toggle.js',
            'web/js/components/app-page-editor.js',
        ];

        foreach ($componentFiles as $file) {
            $content = $this->readProjectFile($file);
            $this->assertStringNotContainsString('DOMContentLoaded', $content, $file);
            $this->assertStringNotContainsString("if (document.readyState === 'loading')", $content, $file);
        }
    }

    public function testMigratedComponentsExposeDestroyCleanupPaths(): void
    {
        $sidebar = $this->readProjectFile('web/js/components/app-toggle-sidebar.js');
        $aside = $this->readProjectFile('web/js/components/app-toggle-aside-panels.js');
        $search = $this->readProjectFile('web/js/components/app-global-search.js');
        $bookmarkSave = $this->readProjectFile('modules/bookmarks/web/js/components/app-bookmark-save.js');
        $bookmarkPanel = $this->readProjectFile('modules/bookmarks/web/js/components/app-bookmark-panel.js');
        $multiSelect = $this->readProjectFile('web/js/components/app-multiselect-init.js');

        $this->assertStringContainsString('destroy: () => {', $sidebar);
        $this->assertStringContainsString("cleanupFns.push(() => document.removeEventListener('keydown', onShortcut));", $sidebar);

        $this->assertStringContainsString('destroy: () => {', $aside);
        $this->assertStringContainsString("cleanupFns.push(() => document.removeEventListener('keydown', onKeyDown));", $aside);

        $this->assertStringContainsString('const destroy = () => {', $search);
        $this->assertStringContainsString("document.removeEventListener('keydown', onDocumentKeydown);", $search);

        $this->assertStringContainsString('const destroy = () => {', $bookmarkSave);
        $this->assertStringContainsString('abortController.abort();', $bookmarkSave);

        $this->assertStringContainsString('const destroy = () => {', $bookmarkPanel);
        $this->assertStringContainsString('abortController.abort();', $bookmarkPanel);
        $this->assertStringNotContainsString('export const init =', $bookmarkSave);
        $this->assertStringNotContainsString('export const init =', $bookmarkPanel);

        $this->assertStringContainsString('return {', $multiSelect);
        $this->assertStringContainsString('destroy: () => {', $multiSelect);
    }

    public function testBookmarkLegacyEntrypointFileIsRemoved(): void
    {
        $this->assertFileDoesNotExist($this->projectRootPath() . '/web/js/components/app-bookmark-init.js');
    }

    public function testRuntimeStorageContractUsesSharedUiStorageHelper(): void
    {
        $files = [
            'web/js/components/app-toggle-sidebar.js',
            'web/js/components/app-toggle-aside-panels.js',
            'web/js/components/app-toggle-details-aside.js',
            'web/js/components/app-contrast-toggle.js',
            'web/js/components/app-tabs.js',
            'web/js/core/app-details-open-state.js',
            'web/js/core/app-grid-factory.js',
        ];

        foreach ($files as $file) {
            $content = $this->readProjectFile($file);
            $this->assertStringNotContainsString('window.localStorage', $content, $file);
            $this->assertStringContainsString('createUiStorage', $content, $file);
        }
    }

    public function testHostBoundComponentsExposeDataAppComponentMarkupHosts(): void
    {
        $defaultTemplate = $this->readProjectFile('templates/default.phtml');
        $loginTemplate = $this->readProjectFile('templates/login.phtml');
        $flashPartial = $this->readProjectFile('templates/partials/app-flash.phtml');
        $topbarPartial = $this->readProjectFile('templates/partials/app-topbar.phtml');
        $asideIconBar = $this->readProjectFile('templates/partials/app-main-aside-icon-bar.phtml');
        $asidePartial = $this->readProjectFile('templates/partials/app-main-aside.phtml');
        $bookmarkDialog = $this->readProjectFile('modules/bookmarks/templates/bookmark-dialogs.phtml');
        $bookmarkPanelTemplate = $this->readProjectFile('modules/bookmarks/templates/aside-bookmarks-panel.phtml');
        $sessionWarningDialog = $this->readProjectFile('templates/partials/app-session-warning-dialog.phtml');

        $this->assertStringContainsString('id="page-config-app-components"', $defaultTemplate);
        $this->assertStringContainsString('id="page-config-login-components"', $loginTemplate);
        $this->assertStringNotContainsString("assetVersion('js/components/app-bookmark-init.js')", $defaultTemplate);

        $this->assertStringContainsString('data-app-component="flash-auto-dismiss"', $flashPartial);
        $this->assertStringContainsString('data-app-component="nav-history"', $topbarPartial);
        $this->assertStringContainsString('data-app-component="tenant-switcher"', $topbarPartial);
        $this->assertStringContainsString('data-app-component="theme-controls"', $topbarPartial);
        $this->assertStringContainsString('data-app-component="contrast-toggle"', $topbarPartial);
        $this->assertStringContainsString('data-app-component="details-aside-toggle"', $topbarPartial);
        $this->assertStringContainsString('data-app-component="aside-panels"', $asideIconBar);
        $this->assertStringContainsString('data-app-component="sidebar-toggle"', $asidePartial);
        $this->assertStringContainsString('data-app-component="global-search"', $asidePartial);
        $this->assertStringContainsString('data-app-component="bookmark-panel"', $bookmarkPanelTemplate);
        $this->assertStringContainsString('data-app-component="bookmark-save"', $bookmarkDialog);
        $this->assertStringContainsString('data-app-component="session-warning"', $sessionWarningDialog);
    }

    public function testTabsHostsUseDataAppComponentContract(): void
    {
        $files = [
            'modules/addressbook/pages/address-book/view(default).phtml',
            'pages/admin/departments/_form.phtml',
            'pages/admin/permissions/_form.phtml',
            'pages/admin/roles/_form.phtml',
            'pages/admin/settings/index(default).phtml',
            'pages/admin/stats/index(default).phtml',
            'pages/admin/tenants/_form.phtml',
            'pages/admin/users/_form.phtml',
        ];

        foreach ($files as $file) {
            $content = $this->readProjectFile($file);
            $this->assertStringContainsString('data-tabs', $content, $file);
            $this->assertStringContainsString('data-app-component="tabs"', $content, $file);
        }
    }

    public function testPageEditorUsesPageModuleEntrypointWithPageConfig(): void
    {
        $pageEditor = $this->readProjectFile('web/js/components/app-page-editor.js');
        $pageEditorEntry = $this->readProjectFile('web/js/pages/app-page-editor-entry.js');
        $adminPage = $this->readProjectFile('pages/page/index(default).phtml');
        $publicPage = $this->readProjectFile('pages/public-page/index(page).phtml');

        $this->assertStringContainsString('export function initPageEditor(root = document, config = {})', $pageEditor);
        $this->assertStringNotContainsString('const form = document.querySelector', $pageEditor);
        $this->assertStringContainsString("readPageConfig('page-editor')", $pageEditorEntry);
        $this->assertStringContainsString("assetVersion('js/pages/app-page-editor-entry.js')", $adminPage);
        $this->assertStringContainsString("assetVersion('js/pages/app-page-editor-entry.js')", $publicPage);
        $this->assertStringNotContainsString("assetVersion('js/components/app-page-editor.js')", $adminPage);
        $this->assertStringNotContainsString("assetVersion('js/components/app-page-editor.js')", $publicPage);
        $this->assertStringContainsString('id="page-config-page-editor"', $adminPage);
        $this->assertStringContainsString('id="page-config-page-editor"', $publicPage);
    }

    public function testNoCustomWindowGlobalsRemainInWebJs(): void
    {
        $violations = $this->findPatternMatchesInFiles(
            'web/js',
            '/window\.(AppSidebar|AppAsidePanels|requestFsLightboxRefresh|__fsLightboxRefreshPending|APP_ASSET_BASE|APP_BASE)\b/',
            ['js']
        );

        $this->assertSame([], $violations, 'Custom window globals found in web/js: ' . implode(', ', $violations));
    }

    public function testHostBoundRuntimeComponentsAreRootStrictWithoutDocumentFallbackQuery(): void
    {
        $files = [
            'web/js/components/app-global-search.js',
            'modules/bookmarks/web/js/components/app-bookmark-panel.js',
            'web/js/components/app-tabs.js',
        ];

        foreach ($files as $file) {
            $content = $this->readProjectFile($file);
            $this->assertDoesNotMatchRegularExpression('/\|\|\s*document\.querySelector/', $content, $file);
        }
    }

    public function testDomBindingUtilitiesExposeDestroyLifecycle(): void
    {
        $activeFilterChips = $this->readProjectFile('web/js/components/app-active-filter-chips.js');
        $multiselectCascade = $this->readProjectFile('web/js/components/app-multiselect-cascade.js');

        $this->assertStringContainsString('return { render, destroy };', $activeFilterChips);
        $this->assertStringContainsString('return {', $multiselectCascade);
        $this->assertStringContainsString('destroy: () => {', $multiselectCascade);
    }
}
