<?php

declare(strict_types=1);

namespace FleekDash\Admin\Iframe;

/**
 * AUTO-GENERATED — do not edit by hand.
 *
 * Source: src/__window-system__/utils/iframe-classes.ts (iframeClassRules + compat + forced post types).
 * Regenerate: pnpm run generate:iframe-php-policy (also runs at end of pnpm run build).
 */
final class GeneratedIframeAdminUrlPolicy
{
    /** @var list<string> */
    private const FORCED_PROTECTED_POST_TYPES = ['acf-field-group', 'scf-field-group'];

    /** @var list<string> */
    private const EMBED_TRANSPORT_PARAMS = ['fleek-compat', 'protected', 'fleekdash-frame', 'adminbar', 'no-pop-state'];

    /**
     * One row per TS iframeClassRules entry, same order. Per rule: try string path, then regex (mirrors matchRuleMode).
     *
     * @var list<array{0:'str'|'regex', 1:string, 2:string, 3?:string}>
     */
    private const RULES = [
        ['regex', '(?:^|\\/)wp-admin\\/(?:index\\.php|dashboard\\.php|update-core\\.php|upgrade\\.php|update\\.php)(?:\\?|$)', '', 'trusted'],
        ['regex', '^(?:index\\.php|dashboard\\.php|update-core\\.php|upgrade\\.php|update\\.php)(?:\\?|$)', '', 'trusted'],
        ['regex', '(?:^|\\/)wp-admin\\/edit-comments\\.php(?:\\?|$)', '', 'trusted'],
        ['regex', '^edit-comments\\.php(?:\\?|$)', '', 'trusted'],
        ['regex', 'post_type=elementor_library', 'i', 'windowed-light'],
        ['regex', '(?:^|\\/)wp-admin\\/edit\\.php|user-edit\\.php|user-new\\.php|vx-templates-|edit-post-type(?:\\?|$)', '', 'windowed'],
        ['regex', '^(?:edit\\.php|user-new\\.php|erase-personal-data\\.php|export-personal-data\\.php|export\\.php|import\\.php|tools\\.php)(?:\\?|$)', '', 'windowed'],
        ['regex', 'post.php|post-new.php|post.php\\?post_type=', '', 'windowed-light'],
        ['regex', '[?&]page=elementor[-_a-z0-9]*(?:&|#|%23|\\/|$)', 'i', 'windowed-light'],
        ['regex', '(?:^|\\/)wp-admin\\/plugins\\.php(?:\\?(?!.*page=).*|$)', '', 'windowed'],
        ['regex', '^plugins\\.php(?:\\?(?!.*page=).*|$)', '', 'windowed'],
        ['regex', '(?:^|\\/)wp-admin\\/plugin-install\\.php', '', 'windowed'],
        ['regex', '^plugin-install\\.php', '', 'windowed'],
        ['regex', '(?:^|\\/)wp-admin\\/nav-menus\\.php', '', 'windowed'],
        ['regex', '^nav-menus\\.php', '', 'windowed'],
        ['regex', '(?:^|\\/)wp-admin\\/options-(?:general|writing|reading|discussion|media|permalink|privacy|connectors)\\.php(?:\\?|$)', '', 'windowed'],
        ['regex', '^options-(?:general|writing|reading|discussion|media|permalink|privacy|connectors)\\.php(?:\\?|$)', '', 'windowed'],
        ['regex', '(?:^|\\/)wp-admin\\/(?:users\\.php|tools\\.php)(?:\\?|$)', '', 'trusted'],
        ['regex', '^(?:users\\.php|tools\\.php)(?:\\?|$)', '', 'trusted'],
        ['regex', '(?:^|\\/)wp-admin\\/themes\\.php(?:\\?(?!.*page=).*|$)', '', 'windowed-light'],
        ['regex', '^themes\\.php(?:\\?(?!.*page=).*|$)', '', 'windowed-light'],
        ['regex', '(?:^|\\/)wp-admin\\/theme-install\\.php', '', 'windowed-light'],
        ['regex', '^theme-install\\.php', '', 'windowed-light'],
        ['regex', '[?&]page=custom-background(?:&|#|%23|\\/|$)', 'i', 'windowed'],
        ['regex', '(?:^|\\/)wp-admin\\/font-library\\.php(?:\\?|$)', '', 'windowed'],
        ['regex', '^font-library\\.php(?:\\?|$)', '', 'windowed'],
        ['regex', '(?:^|\\/)wp-admin\\/theme-editor\\.php(?:\\?|$)', '', 'windowed'],
        ['regex', '^theme-editor\\.php(?:\\?|$)', '', 'windowed'],
        ['regex', '(?:^|\\/)wp-admin\\/post\\.php\\?.*action=edit', '', 'windowed'],
        ['regex', '^(?:post\\.php\\?.*action=edit|site-health\\.php)', '', 'windowed'],
        ['regex', '(?:^|\\/)wp-admin\\/(?:upload\\.php|media-new\\.php)(?:\\?|$)', '', 'windowed'],
        ['regex', '^(?:upload\\.php|media-new\\.php)(?:\\?|$)', '', 'windowed'],
        ['regex', 'page=fleekdash', '', 'trusted'],
        ['regex', 'page=voxel-toolkit', '', 'protected'],
        ['regex', '[?&]page=(?:woocommerce|wc-[a-z0-9_-]+)(?:&|#|%23|\\/|$)', 'i', 'windowed-light'],
        ['regex', '[?&]page=product[-_](?:attributes|importer|exporter|reviews)(?:&|#|$)', 'i', 'windowed-light'],
        ['regex', '[?&]post_type=(?:product|product_variation|shop_order|shop_coupon|shop_order_refund)(?:&|#|$)', 'i', 'windowed-light'],
        ['regex', '[?&]taxonomy=(?:product_cat|product_tag|product_brand|pa_[a-z0-9_-]+)(?:&|#|$)', 'i', 'windowed-light'],
        ['regex', 'page=(voxel|plugin-install-php|classic-editor|gutenberg|classic-widgets|block-widgets|voxel-taxonomies|edit-post-type|etch(?:-[a-z0-9-]+)?)', 'i', 'windowed'],
    ];

    public static function shouldOmitProtectedQueryParam(string $url): bool
    {
        return !self::modeSkipsMainAdminCss(self::resolveMode($url));
    }

    public static function resolveModeForAdminUrl(string $url): string
    {
        return self::resolveMode($url);
    }

    public static function modeRequiresProtectedQueryParam(string $mode): bool
    {
        return self::modeSkipsMainAdminCss($mode);
    }

    private static function modeSkipsMainAdminCss(string $mode): bool
    {
        return $mode === 'protected' || $mode === 'protected-dark';
    }

    /**
     * Strip embed transport params — policy resolves from canonical wp-admin path/query only.
     */
    private static function stripTransportParamsFromUrl(string $url): string
    {
        $parts = parse_url($url);
        if ($parts === false) {
            return $url;
        }

        $query = [];
        if (isset($parts['query'])) {
            parse_str((string) $parts['query'], $query);
            foreach (self::EMBED_TRANSPORT_PARAMS as $key) {
                unset($query[$key]);
            }
        }

        $fragment = isset($parts['fragment']) ? (string) $parts['fragment'] : '';
        if ($fragment !== '' && str_contains($fragment, '?')) {
            [$fragPath, $fragQuery] = explode('?', $fragment, 2);
            $fragParams = [];
            parse_str($fragQuery, $fragParams);
            foreach (self::EMBED_TRANSPORT_PARAMS as $key) {
                unset($fragParams[$key]);
            }
            $fragment = $fragPath;
            if ($fragParams !== []) {
                $fragment .= '?' . http_build_query($fragParams);
            }
        }

        $result = (string) ($parts['path'] ?? '');
        if ($query !== []) {
            $result .= '?' . http_build_query($query);
        }
        if ($fragment !== '') {
            $result .= '#' . $fragment;
        }

        return $result;
    }

    private static function resolveMode(string $url): string
    {
        $policyUrl = self::stripTransportParamsFromUrl($url);
        $mode = 'protected';

        if (self::shouldForceProtectedForEditor($policyUrl)) {
            $mode = 'protected';
        } else {
            $editTagsMode = EditTagsIframeModeResolver::tryResolveMode($policyUrl);
            if ($editTagsMode !== null) {
                $mode = $editTagsMode;
            } else {
                $ruleMode = self::matchIframeRuleMode($policyUrl);
                if ($ruleMode !== null) {
                    $mode = $ruleMode;
                }
            }
        }

        return $mode;
    }

    private static function matchIframeRuleMode(string $url): ?string
    {
        $matched = null;
        $normalizedUrl = explode('?', $url, 2)[0] ?? $url;

        foreach (self::RULES as $rule) {
            if ($rule[0] === 'str') {
                $needle = $rule[1];
                if (str_contains($normalizedUrl, $needle) || str_contains($url, $needle)) {
                    $matched = $rule[2];
                    break;
                }
                continue;
            }
            $source = $rule[1];
            $flags = $rule[2] ?? '';
            $ruleMode = $rule[3] ?? 'protected';
            $delim = '#';
            $pattern = $delim . addcslashes($source, $delim) . $delim . $flags;
            if (@preg_match($pattern, $url) === 1) {
                $matched = $ruleMode;
                break;
            }
        }

        return $matched;
    }

    private static function shouldForceProtectedForEditor(string $url): bool
    {
        $forced = false;
        $parts = parse_url($url);

        if ($parts !== false && isset($parts['path'])) {
            $path = (string) $parts['path'];
            $isPostNew = str_ends_with($path, '/post-new.php') || str_ends_with($path, 'post-new.php');
            if ($isPostNew && isset($parts['query'])) {
                parse_str((string) $parts['query'], $q);
                $postType = $q['post_type'] ?? null;
                if (is_string($postType)) {
                    $forced = in_array($postType, self::FORCED_PROTECTED_POST_TYPES, true);
                }
            }
        }

        return $forced;
    }
}
