<?php

declare(strict_types=1);

use Fisharebest\Webtrees\Census\CensusPlaceInterface;
use Fisharebest\Webtrees\Date;
use Fisharebest\Webtrees\I18N;

/**
 * @var array<CensusPlaceInterface> $census_places
 */

?>

<select class="form-select census-selector" aria-label="<?= I18N::translate('Census date and place') ?>" autocomplete="off">
    <option value="" disabled="disabled" selected="selected" hidden="hidden"><?= I18N::translate('Census date') ?></option>

    <?php foreach ($census_places as $census_place) : ?>
        <optgroup label="<?= $census_place->censusPlace() ?>">
          <?php foreach ($census_place->allCensusDates() as $census) : ?>
              <option data-wt-date="<?= $census->censusDate() ?>" data-wt-place="<?= $census->censusPlace() ?>" data-wt-census="<?= get_class($census) ?>">
                  <?= (new Date($census->censusDate()))->minimumDate()->format('%Y') ?>
                  —
                  <?= $census->censusPlace() ?>
              </option>
          <?php endforeach ?>
        </optgroup>
    <?php endforeach ?>
</select>

<script>
  document.querySelectorAll('.census-selector').forEach(function (el) {
    el.addEventListener('change', function (el) {
      const select = el.target;
      const option = select.options[select.selectedIndex];
      const form = select.closest('form');

      form.querySelector('[id$=CENS-DATE]').value = option.dataset.wtDate;
      // Don't set the place.  It's not always helpful.
    });
  });
</script>
