---
import { Icon } from 'astro-icon/components';

interface Props {
  today?: number;
  total?: number;
}

const { today = 0, total = 0 } = Astro.props;
---

<div class="visitor-counters">
  <div class="counter-item">
    <Icon name="users-group" />
    <span class="counter-value">{today} сегодня</span>
  </div>
  <div class="counter-item">
    <Icon name="users-total" />
    <span class="counter-value">{total} всего</span>
  </div>
</div>

<script>
  (function() {
    const root = document.querySelector('.visitor-counters');
    if (!root) return;

    const valueEls = root.querySelectorAll('.counter-value');
    if (valueEls.length < 2) return;

    const todayStr = new Date().toDateString();
    const lastVisit = localStorage.getItem('site_visited');

    // Если уже посещали сегодня - помечаем как повторный визит
    const isRepeat = lastVisit === todayStr;
    const apiUrl = isRepeat ? '/api/visitors?repeat=true' : '/api/visitors';

    fetch(apiUrl).then(r => r.json()).then(d => {
      if (typeof d.todayVisitors === 'number') {
        if (d.isNewVisitor) {
          localStorage.setItem('site_visited', todayStr);
        }
        if (valueEls[0]) valueEls[0].textContent = d.todayVisitors + ' сегодня';
        if (valueEls[1]) valueEls[1].textContent = d.totalVisitors + ' всего';
      }
    }).catch(() => {});
  })();
</script>

<style>
  .visitor-counters {
    display: flex;
    gap: 1rem;
    align-items: center;
  }

  .counter-item {
    display: flex;
    align-items: center;
    gap: 0.4rem;
    color: #8c9bb0;
    font-size: 0.75rem;
  }

  .counter-item :global(svg) {
    width: 14px;
    height: 14px;
    flex-shrink: 0;
  }

  .counter-value {
    font-variant-numeric: tabular-nums;
  }
</style>