<?php

declare(strict_types=1);

namespace FleekDash\Admin;

use FleekDash\Admin\Iframe\IframeHelpers;

/**
 * WordPress admin "home" (index.php / bare admin.php) → FleekDash #/dashboard.
 *
 * Covers full-page loads (new tab with ?fleekdash-frame=1) and embedded iframe loads.
 * Keep embed-only query detection aligned with:
 * includes/js/iframe-navigation/wp-admin-home-to-fleekdash-dashboard.js
 */
final class AdminDashboardHomePolicy
{
    /** @var list<string> */
    private const EMBED_ONLY_QUERY_KEYS = [
        'fleekdash-frame',
        'protected',
        'fleek-compat',
        'adminbar',
        'wp_http_referer',
        '_wp_http_referer',
        'no-pop-state',
        'fleekdash',
    ];

    public static function getFleekdashDashboardShellUrl(): string
    {
        return \admin_url('admin.php?page=fleekdash#/dashboard');
    }

    /**
     * True when the current admin request is the WP dashboard root (no real screen).
     */
    public static function isDashboardHomeRequest(string $pagenow): bool
    {
        $isHome = !isset($_GET['rest_route'])
            && \in_array($pagenow, ['index.php', 'admin.php'], true);

        if ($isHome && $pagenow === 'admin.php') {
            $page = isset($_GET['page']) ? (string) $_GET['page'] : '';
            $isHome = $page === '' || $page === 'fleekdash';
        }

        if ($isHome) {
            $isHome = self::hasOnlyEmbedOrEmptyQuery();
        }

        return $isHome;
    }

    /**
     * Top-level redirect (new tab, direct visit, classic admin — not embedded).
     *
     * @return never
     */
    public static function redirectTopLevelToFleekdashDashboardOrExit(): void
    {
        \wp_safe_redirect(self::getFleekdashDashboardShellUrl());
        exit;
    }

    /**
     * Embedded iframe cannot wp_redirect to the shell — break out via parent navigation.
     */
    public static function registerEmbeddedParentDashboardRedirect(): void
    {
        static $registered = false;
        if ($registered) {
            return;
        }
        $registered = true;

        \add_action('admin_head', static function (): void {
            if (!IframeHelpers::requestRunsInNestedBrowsingContext()) {
                return;
            }
            $target = self::getFleekdashDashboardShellUrl();
            $jsonUrl = \wp_json_encode($target);
            if (!\is_string($jsonUrl) || $jsonUrl === '') {
                return;
            }
            echo '<script id="fleekdash-wp-admin-home-to-dashboard">';
            echo 'try{if(window.self!==window.top){window.top.location.replace(';
            echo $jsonUrl;
            echo ');}}catch(e){}</script>';
        }, -9999);
    }

    private static function hasOnlyEmbedOrEmptyQuery(): bool
    {
        $onlyEmbed = !\is_array($_GET) || $_GET === [];

        if (!$onlyEmbed) {
            foreach (\array_keys($_GET) as $key) {
                $onlyEmbed = \is_string($key)
                    && \in_array($key, self::EMBED_ONLY_QUERY_KEYS, true);
                if (!$onlyEmbed) {
                    break;
                }
            }
        }

        return $onlyEmbed;
    }
}
