<script lang="ts">
  import {
    meetsToolRequirement,
    DEFAULT_ADMIN_RANK_FALLBACK,
    PLEB_BEATLEADER_ID,
    type BeatLeaderPlayerProfile,
    type ToolRequirement
  } from '$lib/utils/plebsaber-utils';
  import PlayerCard from '$lib/components/PlayerCard.svelte';

  const BL_PATREON_URL = 'https://www.patreon.com/BeatLeader';

  export let player: BeatLeaderPlayerProfile | null = null;
  export let requirement: ToolRequirement | null = null;
  export let showCurrentRank = true;
  export let adminRank: number | null = null;
  export let adminPlayer: BeatLeaderPlayerProfile | null = null;

  $: requirementContext = { adminRank };
  $: hasAccess = meetsToolRequirement(player, requirement, requirementContext);
  $: fallbackBaseline = DEFAULT_ADMIN_RANK_FALLBACK;
  $: resolvedBaseline =
    typeof adminRank === 'number' && Number.isFinite(adminRank) && adminRank > 0 ? adminRank : fallbackBaseline;
  $: plebProfile = adminPlayer;
  $: plebName = plebProfile?.name;
  $: baselineCopy = resolvedBaseline
    ? `players ranked better than ${plebName} (#${resolvedBaseline.toLocaleString()})`
    : `players ranked better than ${plebName}`;
  $: playerRank = typeof player?.rank === 'number' ? player?.rank ?? null : null;
  $: playerRankDisplay = playerRank !== null ? `#${playerRank.toLocaleString()}` : null;
</script>

{#if hasAccess}
  <slot />
{:else}
  <div class="mt-6 rounded-md border border-amber-500/40 bg-amber-500/10 p-4 text-sm text-amber-100 leading-relaxed">
    <p class="font-semibold text-amber-200">
      Auth Required: Tools are restricted to <a class="underline hover:text-white" href={BL_PATREON_URL} target="_blank" rel="noreferrer noopener">BeatLeader supporters</a> (and {baselineCopy}).
    </p>
    {#if plebProfile}
      <div class="pleb-card">
        <PlayerCard
          name={plebProfile.name ?? plebName}
          country={plebProfile.country ?? null}
          rank={plebProfile.rank ?? resolvedBaseline}
          showRank={Boolean(plebProfile.rank ?? resolvedBaseline)}
          avatar={plebProfile.avatar ?? null}
          avatarSize={48}
          techPp={plebProfile?.techPp}
          accPp={plebProfile?.accPp}
          passPp={plebProfile?.passPp}
          playerId={plebProfile?.id ?? PLEB_BEATLEADER_ID}
          gradientId="pleb-baseline"
        />
      </div>
    {/if}
    {#if showCurrentRank}
      <p class="mt-2 text-xs text-amber-200/80">
        {#if playerRankDisplay}
          Current global rank: {playerRankDisplay}
        {:else}
          We couldn't determine your current BeatLeader rank. Try logging in.
        {/if}
      </p>
    {/if}
  </div>
{/if}

<style>
  .pleb-card {
    margin-top: 1rem;
    display: flex;
  }

  .pleb-card :global(.summary-header) {
    width: 100% !important;
    max-width: 100% !important;
  }
</style>

