<script lang="ts">
  import { onMount } from 'svelte';
  let hasSession = false;
  let steamTicket = '';
  let busy = false;
  let message: string | null = null;
  let helperConfigured = false;
  async function refresh() {
    try {
      const res = await fetch('/api/beatleader/oauth/status');
      const data = res.ok ? await res.json() : {};
      hasSession = Boolean(data?.hasSession);
    } catch { hasSession = false; }
  }
  async function getTicketFromHelper() {
    message = null; busy = true;
    try {
      const res = await fetch('/api/steam/ticket');
      const data = await res.json();
      if (res.ok && data?.ticket) {
        steamTicket = data.ticket;
        message = 'Ticket fetched from Steam';
      } else {
        message = data?.error || 'Failed to fetch Steam ticket';
      }
    } catch {
      message = 'Failed to fetch Steam ticket';
    } finally {
      busy = false;
    }
  }
  async function submitTicket() {
    message = null; busy = true;
    try {
      const res = await fetch('/auth/beatleader/steam-ticket', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ ticket: steamTicket.trim() })
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data?.ok) {
        message = data?.error || 'Failed to create session';
      } else {
        message = 'Session captured!';
        await refresh();
      }
    } catch (e) {
      message = 'Network error';
    } finally {
      busy = false;
    }
  }
  async function clearSession() {
    busy = true; message = null;
    await fetch('/auth/beatleader/session/logout', { method: 'POST' });
    await refresh(); busy = false;
  }
  onMount(async () => {
    await refresh();
    // Detect helper availability (501 => not configured)
    try {
      const res = await fetch('/api/steam/ticket');
      const data = await res.json();
      helperConfigured = Boolean(res.ok && data?.ticket) || res.status !== 501;
    } catch {
      helperConfigured = false;
    }
  });
</script>

<section class="py-8 prose prose-invert max-w-none">
  <h1 class="font-display tracking-widest">BeatLeader Authentication</h1>
  <p>Establish a BeatLeader website session using your Steam session ticket. This mimics how the BeatLeader mod logs in.</p>

  <div class="not-prose my-4 grid gap-3 md:grid-cols-2">
    <div class="rounded border border-white/10 p-4">
      <div class="text-sm text-muted">Website Session</div>
      <div class="mt-1">{hasSession ? 'Active (captured via Steam)' : 'Not active'}</div>
      <div class="mt-3 flex gap-2">
        <button class="btn-neon" on:click={refresh} disabled={busy}>Refresh</button>
        {#if hasSession}
          <button class="rounded bg-white/10 px-3 py-1 hover:bg-white/20" on:click={clearSession} disabled={busy}>Clear Session</button>
        {/if}
      </div>
    </div>

    <div class="rounded border border-white/10 p-4">
      <div class="text-sm text-muted">Steam Session Ticket</div>
      <p class="text-xs text-muted mt-1">We can obtain your Steam session ticket using a local helper (bundled in Tauri). If unavailable, you can paste a ticket from a compatible client.</p>
      <div class="mt-2 flex gap-2 items-center">
        <button class="rounded bg-white/10 px-3 py-1 hover:bg-white/20" on:click={getTicketFromHelper} disabled={busy}>
          Get Ticket from Steam {#if !helperConfigured}<span class="text-[10px] text-muted">(helper unavailable)</span>{/if}
        </button>
        {#if steamTicket}
          <span class="text-xs text-muted">Ticket fetched</span>
        {/if}
      </div>
      <textarea class="mt-2 w-full rounded bg-white/5 p-2 text-sm" rows="5" bind:value={steamTicket} placeholder="Paste steam session ticket..."></textarea>
      <div class="mt-3 flex items-center gap-3">
        <button class="btn-neon" on:click={submitTicket} disabled={busy || !steamTicket.trim()}>Create Session</button>
        {#if message}
          <span class="text-xs text-muted">{message}</span>
        {/if}
      </div>
    </div>
  </div>

  <h2>How it works</h2>
  <ul>
    <li>We POST your ticket to BeatLeader <code>/signin</code> with <code>provider=steamTicket</code>.</li>
    <li>BeatLeader sets website cookies; we store those server‑side and attach them to API calls that require a website session.</li>
    <li>Use <code>?auth=session</code> on our API where OAuth is ignored by BL (e.g., scores/leaderboards that show unranked stars).</li>
  </ul>
</section>


