<?php

declare(strict_types=1);

use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Individual;
use Fisharebest\Webtrees\Module\IndividualListModule;
use Fisharebest\Webtrees\Module\ModuleListInterface;
use Fisharebest\Webtrees\Tree;

/**
 * @var IndividualListModule|null   $module
 * @var array<string,string>        $params
 * @var array<non-empty-array<int>> $surnames
 * @var bool                        $totals
 * @var Tree                        $tree
 */

$maximum = $surnames === [] ? 0 : max(array_map(static fn (array $x): int => max($x), $surnames));
$minimum = $surnames === [] ? 0 : min(array_map(static fn (array $x): int => min($x), $surnames));

?>

<div class="wt-surnames-tag-cloud">
    <?php foreach ($surnames as $surn => $surns) : ?>
        <?php foreach ($surns as $surname => $count) : ?>
            <?php
            $size = $maximum === $minimum ? 1.0 : 1.0 + 1.5 * ($count - $minimum) / ($maximum - $minimum);

            if ($surname === Individual::NOMEN_NESCIO) {
                $label = I18N::translateContext('Unknown surname', '…');
            } elseif ($surname === '') {
                $label = e($surn);
            } else {
                $label = e($surname);
            }

            if ($totals) {
                $label = I18N::translate('%1$s (%2$s)', $label, I18N::number($count));
            }

            ?>
            <?php if ($module instanceof ModuleListInterface) : ?>
                <a class="ut" style="font-size:<?= $size ?>rem" href="<?= e($module->listUrl($tree, ['surname' => $surname] + $params)) ?>">
                    <?= $label ?>
                </a>
            <?php else : ?>
                <span class="text-nowrap ut" style="font-size:<?= $size ?>rem" dir="auto">
                    <?= $label ?>
                </span>
            <?php endif ?>
        <?php endforeach ?>
    <?php endforeach ?>
</div>
