<?php

declare(strict_types=1);

class LocalizedTags
{
    public static function dedupe(array $tags): array
    {
        if (count($tags) < 2) {
            return $tags;
        }

        $out = [];
        $seen = [];

        foreach ($tags as $tag) {
            if (!is_array($tag)) {
                $out[] = $tag;
                continue;
            }

            $key = self::key((string) ($tag['name'] ?? ''));
            if ($key === '') {
                $out[] = $tag;
                continue;
            }

            if (!isset($seen[$key])) {
                $seen[$key] = count($out);
                $out[] = $tag;
                continue;
            }

            $position = $seen[$key];
            if (self::preferred($tag, $out[$position])) {
                $out[$position] = $tag;
            }
        }

        return $out;
    }

    public static function dedupeGroups(array $groups): array
    {
        foreach ($groups as $groupKey => $rows) {
            if (is_array($rows)) {
                $groups[$groupKey] = self::dedupe($rows);
            }
        }

        return $groups;
    }

    private static function key(string $name): string
    {
        $collapsed = preg_replace('/\s+/u', ' ', $name);
        if (!is_string($collapsed)) {
            $collapsed = $name;
        }

        $collapsed = trim($collapsed);
        if ($collapsed === '') {
            return '';
        }

        return function_exists('mb_strtolower') ? mb_strtolower($collapsed, 'UTF-8') : strtolower($collapsed);
    }

    private static function preferred(array $candidate, array $current): bool
    {
        $candidateCount = (int) ($candidate['video_count'] ?? 0);
        $currentCount = (int) ($current['video_count'] ?? 0);
        if ($candidateCount !== $currentCount) {
            return $candidateCount > $currentCount;
        }

        return (int) ($candidate['id'] ?? 0) < (int) ($current['id'] ?? 0);
    }
}
