<?php
/**
 * Locates Bricks elements by class, name, id, or position.
 *
 * @package LolaCoreForBricks
 */

declare(strict_types=1);

namespace LolaCoreForBricks\Support;

/**
 * Shared selector for bulk content and class writes.
 */
final class ElementSelector
{
    /**
     * @param array<int, array<string, mixed>> $elements
     * @param array<string, mixed>             $selector
     * @return string[]
     */
    public function select(array $elements, array $selector, ?string $classId = null): array
    {
        $elementId = (string) ($selector['element_id'] ?? '');
        $name      = sanitize_key((string) ($selector['name'] ?? $selector['element'] ?? ''));
        $matches   = [];

        foreach ($elements as $element) {
            if (!is_array($element)) {
                continue;
            }

            $id = (string) ($element['id'] ?? '');
            if ($id === '') {
                continue;
            }

            if ($elementId !== '' && $id !== $elementId) {
                continue;
            }

            if ($name !== '' && sanitize_key((string) ($element['name'] ?? '')) !== $name) {
                continue;
            }

            if ($classId !== null) {
                $classes = $element['settings']['_cssGlobalClasses'] ?? [];
                if (!is_array($classes) || !in_array($classId, $classes, true)) {
                    continue;
                }
            }

            $matches[] = $id;
        }

        if (!array_key_exists('position', $selector) && !array_key_exists('nth', $selector)) {
            return $matches;
        }

        $position = $selector['position'] ?? $selector['nth'];
        if (!is_numeric($position)) {
            return [];
        }

        $index = (int) $position;

        return isset($matches[$index]) ? [$matches[$index]] : [];
    }

    /**
     * @param array<string, mixed> $selector
     */
    public function isEmpty(array $selector): bool
    {
        return (string) ($selector['element_id'] ?? '') === ''
            && sanitize_key((string) ($selector['name'] ?? $selector['element'] ?? '')) === ''
            && (string) ($selector['class'] ?? '') === ''
            && !array_key_exists('position', $selector)
            && !array_key_exists('nth', $selector);
    }
}
