<script lang="ts">
  import { onMount } from 'svelte';
  import beatleaderLogo from '$lib/assets/beatleader-logo.png';
  import { DEFAULT_ADMIN_RANK_FALLBACK, PLEB_BEATLEADER_ID } from '$lib/utils/plebsaber-utils';
  const links = [
    { href: '/', label: 'Home' },
    { href: '/tools', label: 'Tools' },
    { href: '/guides', label: 'Guides' }
  ];
  let open = false;
  const toggle = () => (open = !open);
  const close = () => (open = false);

  type BeatLeaderIdentity = {
    id?: string;
    name?: string;
  };

  type BeatLeaderPlayer = {
    id?: string;
    name?: string;
    avatar?: string | null;
    rank?: number | null;
    countryRank?: number | null;
  };

  type BeatLeaderProfile = {
    id?: string;
    name?: string;
    avatar?: string;
    rank?: number | null;
    countryRank?: number | null;
  };

  let user: BeatLeaderProfile | null = null;
  let loginHref = '/auth/beatleader/login';
  let checkingSession = true;
  let menuOpen = false;
  let adminRank: number | null = null;
  let adminFallbackRank = DEFAULT_ADMIN_RANK_FALLBACK;

  const getProfileUrl = (id?: string) => (id ? `https://beatleader.com/u/${encodeURIComponent(id)}` : 'https://beatleader.com');

  function extractPlayer(payload: unknown): BeatLeaderProfile | null {
    if (!payload || typeof payload !== 'object') return null;
    const { identity, player } = payload as { identity?: BeatLeaderIdentity | null; player?: BeatLeaderPlayer | null };

    const sourcePlayer = player ?? null;
    const sourceIdentity = identity ?? null;

    const id = sourcePlayer?.id ?? sourceIdentity?.id;
    const name = sourcePlayer?.name ?? sourceIdentity?.name;
    const avatar = sourcePlayer?.avatar ?? null;
    const rank = sourcePlayer?.rank ?? null;
    const countryRank = sourcePlayer?.countryRank ?? null;

    if (!id && !name) return null;

    return {
      id: typeof id === 'string' ? id : undefined,
      name: typeof name === 'string' ? name : undefined,
      avatar: typeof avatar === 'string' ? avatar : undefined,
      rank: typeof rank === 'number' ? rank : null,
      countryRank: typeof countryRank === 'number' ? countryRank : null
    };
  }

  function extractAdminBaseline(payload: unknown): { rank: number | null; fallback: number } | null {
    if (!payload || typeof payload !== 'object') return null;
    const baseline = (payload as { adminBaseline?: { rank?: unknown; fallback?: unknown } }).adminBaseline;
    if (!baseline || typeof baseline !== 'object') return null;
    const rank = (baseline as { rank?: unknown }).rank;
    const fallback = (baseline as { fallback?: unknown }).fallback;
    return {
      rank: typeof rank === 'number' && Number.isFinite(rank) && rank > 0 ? rank : null,
      fallback: typeof fallback === 'number' && Number.isFinite(fallback) && fallback > 0 ? fallback : DEFAULT_ADMIN_RANK_FALLBACK
    };
  }

  onMount(() => {
    const redirectTarget = `${window.location.pathname}${window.location.search}${window.location.hash}` || '/';
    loginHref = `/auth/beatleader/login?redirect_uri=${encodeURIComponent(redirectTarget)}`;

    (async () => {
      try {
        const res = await fetch('/api/beatleader/me');
        if (res.ok) {
          const json = (await res.json()) as unknown;
          const profile = extractPlayer(json);
          if (profile) {
            user = profile;
          }
          const baseline = extractAdminBaseline(json);
          if (baseline) {
            adminRank = baseline.rank;
            adminFallbackRank = baseline.fallback;
          }
        } else if (res.status === 401) {
          try {
            const body = (await res.json()) as Record<string, unknown>;
            const suggested = body?.login;
            if (typeof suggested === 'string') {
              loginHref = suggested;
            }
          } catch {
            // ignore JSON parsing errors for 401 responses
          }
        }
      } catch (err) {
        console.error('Failed to determine BeatLeader session state', err);
      } finally {
        checkingSession = false;
      }
    })();
  });

  function toggleMenu() {
    menuOpen = !menuOpen;
  }

  function closeMenu() {
    menuOpen = false;
  }

  $: baselineRank = (adminRank ?? adminFallbackRank ?? DEFAULT_ADMIN_RANK_FALLBACK);
  $: requiresWarning = typeof user?.rank === 'number' && Number.isFinite(user.rank)
    ? (user.rank as number) > baselineRank
    : false;
  $: baselineCopy = baselineRank ? `pleb (#${baselineRank.toLocaleString()})` : 'pleb';
</script>

<header class="sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-surface/50 border-b border-white/10">
  <div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
    <div class="flex h-14 items-center justify-between">
      <a href="/" class="flex items-center gap-2">
        <span class="font-display text-lg tracking-widest">
          <span class="neon-text">plebsaber</span><span class="text-muted">.stream</span>
        </span>
        <span class="h-2 w-2 rounded-full bg-neon-fuchsia" style="box-shadow: 0 0 12px rgba(255,0,229,0.60);"></span>
        <span class="h-2 w-2 rounded-full bg-neon" style="box-shadow: 0 0 12px rgba(34,211,238,0.60);"></span>
      </a>

      <nav class="hidden md:flex items-center gap-6">
        {#each links as link}
          <a href={link.href} class="text-muted hover:text-white transition">{link.label}</a>
        {/each}
        {#if checkingSession}
          <span class="text-sm text-muted">Connecting…</span>
        {:else if user}
          <div class="relative">
            <button
              class="flex items-center gap-3 rounded-md border border-white/10 px-3 py-1.5 text-sm transition hover:bg-white/10"
              on:click={toggleMenu}
              aria-haspopup="true"
              aria-expanded={menuOpen}
            >
              <img
                src={user.avatar ?? beatleaderLogo}
                alt="BeatLeader avatar"
                class="h-8 w-8 rounded-full object-cover shadow-sm"
                loading="lazy"
              />
              <span class="font-medium text-white">{user.name ?? 'BeatLeader user'}</span>
              <svg class={`h-4 w-4 transition-transform ${menuOpen ? 'rotate-180' : ''}`} viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.292l3.71-4.06a.75.75 0 111.08 1.04l-4.25 4.65a.75.75 0 01-1.08 0l-4.25-4.65a.75.75 0 01.02-1.06z" clip-rule="evenodd" />
              </svg>
            </button>
            {#if menuOpen}
              <div class="dropdown" role="menu">
                {#if requiresWarning}
                  <div class="dropdown-warning">
                    <strong>Heads up:</strong>
                    <span>Tools are limited to <a class="underline" href="https://www.patreon.com/BeatLeader" target="_blank" rel="noreferrer noopener">BeatLeader supporters</a> or players ranked better than {baselineCopy}.</span>
                  </div>
                {/if}
                {#if user?.id === PLEB_BEATLEADER_ID}
                  <a href="/tools/stats" class="dropdown-item" on:click={closeMenu}>Stats</a>
                {/if}
                <a href="/player-info" class="dropdown-item" on:click={closeMenu}>Player Info</a>
                <a href={getProfileUrl(user.id)} class="dropdown-item dropdown-item--with-icon" target="_blank" rel="noreferrer noopener" on:click={closeMenu}>
                  <span>Profile</span>
                  <img src={beatleaderLogo} alt="BeatLeader" class="dropdown-icon" />
                </a>
                <form action="/auth/beatleader/logout?redirect_uri=%2F" method="POST" class="dropdown-item-form">
                  <button type="submit" class="dropdown-item-button">Logout</button>
                </form>
              </div>
            {/if}
          </div>
        {:else}
          <a href={loginHref} class="btn-neon inline-flex items-center gap-2 px-3 py-1.5">
            <img src={beatleaderLogo} alt="BeatLeader" class="h-6 w-6" />
            <span>Login</span>
          </a>
        {/if}
      </nav>

      <button class="md:hidden btn-neon px-3 py-1.5" on:click={toggle} aria-expanded={open} aria-controls="mobile-nav">
        Menu
      </button>
    </div>
  </div>

  {#if open}
    <div id="mobile-nav" class="md:hidden border-t border-white/10 bg-surface/80">
      <div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-3 grid gap-3">
        {#each links as link}
          <a href={link.href} on:click={close} class="text-muted hover:text-white transition">{link.label}</a>
        {/each}
        {#if checkingSession}
          <span class="text-sm text-muted">Connecting…</span>
        {:else if user}
          <div class="border border-white/10 rounded-md overflow-hidden">
            {#if requiresWarning}
              <div class="dropdown-warning mobile">
                <strong>Heads up:</strong>
                <span>Tools are limited to <a class="underline" href="https://www.patreon.com/BeatLeader" target="_blank" rel="noreferrer noopener">BeatLeader supporters</a> or players ranked better than {baselineCopy}.</span>
              </div>
            {/if}
            {#if user?.id === PLEB_BEATLEADER_ID}
              <a href="/tools/stats" class="dropdown-item" on:click={close}>Stats</a>
            {/if}
            <a href="/player-info" class="dropdown-item" on:click={close}>Player Info</a>
            <a href={getProfileUrl(user.id)} class="dropdown-item dropdown-item--with-icon" target="_blank" rel="noreferrer noopener" on:click={close}>
              <span>Profile</span>
              <img src={beatleaderLogo} alt="BeatLeader" class="dropdown-icon" />
            </a>
            <form action="/auth/beatleader/logout?redirect_uri=%2F" method="POST">
              <button type="submit" class="dropdown-item-button w-full text-left">Logout</button>
            </form>
          </div>
        {:else}
          <a href={loginHref} on:click={close} class="btn-neon inline-flex items-center gap-2 w-max px-3 py-2">
            <img src={beatleaderLogo} alt="BeatLeader" class="h-6 w-6" />
            <span>Login</span>
          </a>
        {/if}
      </div>
    </div>
  {/if}
</header>

<style>
  .dropdown {
    position: absolute;
    right: 0;
    top: calc(100% + 0.5rem);
    min-width: 14rem;
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: linear-gradient(160deg, rgba(15, 23, 42, 0.95), rgba(8, 12, 24, 0.98));
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45), 0 0 20px rgba(34, 211, 238, 0.35);
    border-radius: 0.6rem;
    padding: 0.35rem;
    display: grid;
    gap: 0.25rem;
    z-index: 50;
    backdrop-filter: blur(12px);
  }

  .dropdown::before {
    content: '';
    position: absolute;
    top: -0.5rem;
    right: 1.2rem;
    width: 0.75rem;
    height: 0.75rem;
    background: inherit;
    transform: rotate(45deg);
    border-left: 1px solid rgba(255, 255, 255, 0.1);
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    z-index: -1;
  }

  .dropdown-item,
  .dropdown-item-button {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.6rem 0.75rem;
    border-radius: 0.45rem;
    font-size: 0.85rem;
    color: rgba(226, 232, 240, 0.8);
    transition: background 0.2s ease, color 0.2s ease, transform 0.2s ease;
    text-decoration: none;
  }

  .dropdown-item--with-icon {
    justify-content: flex-start;
  }

  .dropdown-icon {
    width: 1.25rem;
    height: 1.25rem;
  }

  .dropdown-item:hover,
  .dropdown-item-button:hover {
    background: rgba(34, 211, 238, 0.15);
    color: rgba(255, 255, 255, 0.95);
    transform: translateX(2px);
  }

  .dropdown-item-button {
    width: 100%;
    background: none;
    border: none;
    text-align: left;
    cursor: pointer;
    font-family: inherit;
  }

  .dropdown-item-form {
    margin: 0;
  }

  .dropdown-warning {
    display: flex;
    flex-direction: column;
    gap: 0.35rem;
    padding: 0.6rem 0.75rem;
    border-radius: 0.45rem;
    background: rgba(255, 152, 0, 0.18);
    color: rgba(255, 220, 186, 0.95);
    font-size: 0.8rem;
    box-shadow: inset 0 0 15px rgba(255, 152, 0, 0.15);
  }

  .dropdown-warning strong {
    font-weight: 700;
    font-size: 0.78rem;
    text-transform: uppercase;
    letter-spacing: 0.08em;
  }

  .dropdown-warning.mobile {
    border-radius: 0;
  }

  @media (max-width: 768px) {
    .dropdown {
      position: static;
      box-shadow: none;
      backdrop-filter: none;
    }

    .dropdown::before {
      display: none;
    }
  }
</style>


