<?php

declare(strict_types=1);

namespace FleekDash\Admin\Iframe;

/**
 * Resolves iframe mode for edit-tags.php from WordPress taxonomy / post_type registration (_builtin),
 * not per-plugin URL allowlists.
 */
final class EditTagsIframeModeResolver
{
    /**
     * @return 'trusted'|'windowed-light'|null null when the URL is not an edit-tags.php screen
     */
    public static function tryResolveMode(string $url): ?string
    {
        if (preg_match('/edit-tags\.php/i', $url) !== 1) {
            return null;
        }

        $params = self::extractEditTagsQueryParams($url);
        $mode = 'windowed-light';
        if (
            $params['taxonomy'] !== null
            && $params['taxonomy'] !== ''
            && self::isBuiltinTaxonomyScreen($params['taxonomy'], $params['post_type'])
        ) {
            $mode = 'trusted';
        }

        return $mode;
    }

    /**
     * @return array{taxonomy: ?string, post_type: ?string}
     */
    private static function extractEditTagsQueryParams(string $url): array
    {
        if (preg_match('/edit-tags\.php/i', $url, $match, PREG_OFFSET_CAPTURE) !== 1) {
            return ['taxonomy' => null, 'post_type' => null];
        }

        $suffix = substr($url, (int) $match[0][1]);
        $qPos = strpos($suffix, '?');
        if ($qPos === false) {
            return ['taxonomy' => null, 'post_type' => null];
        }

        $query = substr($suffix, $qPos + 1);
        $hashPos = strpos($query, '#');
        if ($hashPos !== false) {
            $query = substr($query, 0, $hashPos);
        }

        parse_str($query, $params);
        $taxonomy = isset($params['taxonomy']) && is_string($params['taxonomy'])
            ? $params['taxonomy']
            : null;
        $postType = isset($params['post_type']) && is_string($params['post_type'])
            ? $params['post_type']
            : null;

        return ['taxonomy' => $taxonomy, 'post_type' => $postType];
    }

    private static function isBuiltinTaxonomyScreen(string $taxonomy, ?string $postType): bool
    {
        $isBuiltin = false;

        if (function_exists('get_taxonomy')) {
            $taxObj = get_taxonomy($taxonomy);
            $hasBuiltinTaxonomy = $taxObj instanceof \WP_Taxonomy && $taxObj->_builtin;
            $postTypeIsEmpty = $postType === null || $postType === '';
            $hasBuiltinPostType = false;

            if ($hasBuiltinTaxonomy && !$postTypeIsEmpty && function_exists('get_post_type_object')) {
                $ptObj = get_post_type_object($postType);
                $hasBuiltinPostType = $ptObj instanceof \WP_Post_Type && $ptObj->_builtin;
            }

            $isBuiltin = $hasBuiltinTaxonomy && ($postTypeIsEmpty || $hasBuiltinPostType);
        }

        return $isBuiltin;
    }
}
