<script lang="ts">
  import { onDestroy, onMount } from 'svelte';
  import PlayerCard from '$lib/components/PlayerCard.svelte';
  import type { PageData } from './$types';

  export let data: PageData;

  const formatter = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
  const ranges: Array<{ unit: Intl.RelativeTimeFormatUnit; ms: number }> = [
    { unit: 'year', ms: 1000 * 60 * 60 * 24 * 365 },
    { unit: 'month', ms: 1000 * 60 * 60 * 24 * 30 },
    { unit: 'week', ms: 1000 * 60 * 60 * 24 * 7 },
    { unit: 'day', ms: 1000 * 60 * 60 * 24 },
    { unit: 'hour', ms: 1000 * 60 * 60 },
    { unit: 'minute', ms: 1000 * 60 },
    { unit: 'second', ms: 1000 }
  ];

  let now = Date.now();
  let timer: ReturnType<typeof setInterval> | null = null;

  const formatTimeSince = (timestamp: number): string => {
    const diff = timestamp - now;
    for (const { unit, ms } of ranges) {
      const value = diff / ms;
      if (Math.abs(value) >= 1 || unit === 'second') {
        return formatter.format(Math.round(value), unit);
      }
    }
    return formatter.format(0, 'second');
  };

  onMount(() => {
    timer = setInterval(() => {
      now = Date.now();
    }, 60_000);
  });

  onDestroy(() => {
    if (timer) {
      clearInterval(timer);
    }
  });
</script>

<svelte:head>
  <title>plebsaber · Stats</title>
</svelte:head>

<section class="page-wrapper">
  <header class="page-header">
    <h1>Historical BeatLeader Logins</h1>
    <p class="page-subtitle">Tracking everyone who has authenticated with plebsaber tools.</p>
    <p class="page-meta">Total users: {data.users.length}</p>
  </header>

  {#if data.users.length === 0}
    <div class="empty-state">
      <p>No BeatLeader sessions have been recorded yet.</p>
    </div>
  {:else}
    <ul class="user-grid" aria-live="polite">
      {#each data.users as user, index}
        <li class="user-card">
          <div class="card-header">
            <PlayerCard
              name={user.name ?? 'Unknown BeatLeader user'}
              avatar={user.avatar ?? null}
              country={user.country ?? null}
              rank={user.rank ?? null}
              showRank={typeof user.rank === 'number'}
              width="100%"
              avatarSize={64}
              techPp={user.techPp}
              accPp={user.accPp}
              passPp={user.passPp}
              playerId={user.beatleaderId}
              gradientId={`stats-player-${index}`}
            />
          </div>
          <div class="user-meta">
            <div class="meta-item">
              <span class="meta-label">ID</span>
              <span class="meta-value">{user.beatleaderId}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">Last Session</span>
              <time class="meta-value" datetime={user.lastSeenIso}>
                {formatTimeSince(user.lastSeenAt)}
              </time>
            </div>
          </div>
        </li>
      {/each}
    </ul>
  {/if}
</section>

<style>
  .page-wrapper {
    display: grid;
    gap: 2rem;
    padding: 2.5rem 0;
  }

  .page-header {
    display: grid;
    gap: 0.75rem;
  }

  .page-header h1 {
    font-size: clamp(1.75rem, 3vw, 2.5rem);
    font-weight: 700;
    letter-spacing: 0.05em;
  }

  .page-subtitle {
    color: rgba(226, 232, 240, 0.7);
  }

  .page-meta {
    font-size: 0.9rem;
    color: rgba(226, 232, 240, 0.55);
    text-transform: uppercase;
    letter-spacing: 0.15em;
  }

  .empty-state {
    padding: 3rem;
    border: 1px dashed rgba(148, 163, 184, 0.35);
    border-radius: 0.75rem;
    text-align: center;
    color: rgba(148, 163, 184, 0.85);
    background: rgba(15, 23, 42, 0.35);
  }

  .user-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
    gap: 1.5rem;
    padding: 0;
    margin: 0;
    list-style: none;
  }

  .user-card {
    display: flex;
    flex-direction: column;
    gap: 1rem;
    padding: 1.25rem;
    border-radius: 0.85rem;
    border: 1px solid rgba(148, 163, 184, 0.18);
    background: linear-gradient(160deg, rgba(15, 23, 42, 0.6), rgba(8, 12, 24, 0.85));
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25), inset 0 0 0 1px rgba(34, 211, 238, 0.05);
    transition: border-color 0.2s ease, box-shadow 0.2s ease;
  }

  .user-card:hover,
  .user-card:focus-within {
    border-color: rgba(34, 211, 238, 0.35);
    box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35), inset 0 0 0 1px rgba(34, 211, 238, 0.15);
  }

  .card-header {
    display: flex;
    width: 100%;
  }

  .user-meta {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0.75rem;
    padding-top: 0.75rem;
    border-top: 1px solid rgba(148, 163, 184, 0.15);
  }

  .meta-item {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
  }

  .meta-label {
    font-size: 0.7rem;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: rgba(148, 163, 184, 0.6);
    font-weight: 600;
  }

  .meta-value {
    font-size: 0.85rem;
    color: rgba(226, 232, 240, 0.9);
    word-break: break-all;
  }

  @media (max-width: 640px) {
    .user-grid {
      grid-template-columns: 1fr;
    }

    .user-meta {
      grid-template-columns: 1fr;
    }
  }
</style>

