<?php
/**
 * Parses and composes Bricks setting keys with breakpoint/state suffixes.
 *
 * @package LolaCoreForBricks
 */

declare(strict_types=1);

namespace LolaCoreForBricks\Support;

/**
 * Supports modern colon grammar and legacy underscore grammar (pre-1.3.5).
 */
final class SettingsKeyGrammar
{
    /**
     * @return array{base: string, breakpoint: ?string, state: ?string, variant: ?string, legacy: bool}
     */
    public static function parse(string $key): array
    {
        if (str_contains($key, ':')) {
            $parts = explode(':', $key);
            $base  = array_shift($parts) ?? $key;

            return [
                'base'       => $base,
                'breakpoint' => $parts[0] ?? null,
                'state'      => $parts[1] ?? null,
                'variant'    => $parts[2] ?? null,
                'legacy'     => false,
            ];
        }

        if (preg_match('/^(.+)_(tablet|mobile|desktop)(?:_(portrait|landscape))?(?:_(hover|active|focus))?$/', $key, $matches) === 1) {
            return [
                'base'       => $matches[1],
                'breakpoint' => $matches[2] . (isset($matches[3]) && $matches[3] !== '' ? '_' . $matches[3] : ''),
                'state'      => $matches[4] ?? null,
                'variant'    => null,
                'legacy'     => true,
            ];
        }

        return [
            'base'       => $key,
            'breakpoint' => null,
            'state'      => null,
            'variant'    => null,
            'legacy'     => false,
        ];
    }

    public static function compose(
        string $base,
        ?string $breakpoint = null,
        ?string $state = null,
        ?string $variant = null
    ): string {
        $segments = array_filter([$base, $breakpoint, $state, $variant], static fn (?string $part): bool => $part !== null && $part !== '');

        return implode(':', $segments);
    }
}
