<?php

declare(strict_types=1);

namespace PpPhp\Core\Designer\Selection;

use PpPhp\Core\Designer\Inspector\DesignerInspectorBuilder;

final class DesignerSelectionRuntime
{
    public function tree(array $page): array
    {
        return (new DesignerSelectionTreeBuilder())->build($page);
    }

    public function inspect(array $page, array $target): array
    {
        return (new DesignerInspectorBuilder())->build($page, DesignerSelectionTarget::fromArray($target));
    }

    public function findTarget(array $tree, string $targetId): ?array
    {
        if (($tree['target']['targetId'] ?? '') === $targetId) {
            return (array) $tree['target'];
        }

        foreach ((array) ($tree['children'] ?? []) as $child) {
            if (!is_array($child)) {
                continue;
            }

            $target = $this->findTarget($child, $targetId);
            if ($target !== null) {
                return $target;
            }
        }

        return null;
    }

    public function firstSelectable(array $tree): ?array
    {
        foreach ((array) ($tree['children'] ?? []) as $child) {
            if (is_array($child) && isset($child['target'])) {
                return (array) $child['target'];
            }
        }

        return isset($tree['target']) ? (array) $tree['target'] : null;
    }
}
