<script lang="ts">
  import { onMount } from 'svelte';
  import { browser } from '$app/environment';

  let name = '';
  let clientId = '';
  let origin = '';
  let redirectUrls = '';
  let scopes: string[] = ['scp:profile', 'scp:offline_access'];
  let iconFile: File | null = null;
  let message: string | null = null;
  let created: any = null;
  let existing: { client_id: string; client_secret: string } | null = null;
  let manualClientId = '';
  let manualClientSecret = '';
  let recommendedClientId = generateDefaultClientId();
  let copying: string | null = null;
  let returnTo: string | null = null;
  let blCredsStatus: 'unknown' | 'configured' | 'missing' = 'unknown';
  let blManageUrl: string | null = null;

  onMount(async () => {
    if (browser) {
      try { origin = location.origin; } catch {}
      try { redirectUrls = origin + '/auth/beatleader/callback'; } catch {}
    }
    try {
      const sp = new URLSearchParams(location.search);
      const ret = sp.get('return');
      if (ret) returnTo = ret;
    } catch {}
    try {
      const redirect = location.pathname + (location.search || '');
      blManageUrl = `/tools/beatleader-oauth?return=${encodeURIComponent(redirect)}`;
      const statusRes = await fetch('/api/beatleader/oauth/status');
      if (statusRes.ok) {
        const st: any = await statusRes.json();
        blCredsStatus = st?.hasCreds ? 'configured' : 'missing';
      } else {
        blCredsStatus = 'unknown';
      }
    } catch {
      blCredsStatus = 'unknown';
    }
    try {
      const res = await fetch('/api/beatleader/oauth/creds');
      if (res.ok) {
        const data: any = await res.json();
        const hasId = typeof data?.client_id === 'string' && data.client_id.length > 0;
        const hasSecret = typeof data?.client_secret === 'string' && data.client_secret.length > 0;
        existing = hasId && hasSecret ? { client_id: data.client_id, client_secret: data.client_secret } : null;
      } else {
        existing = null;
      }
    } catch {}
  });

  function onIconChange(ev: Event) {
    const input = ev.target as HTMLInputElement;
    const f = input.files?.[0] ?? null;
    if (!f) {
      iconFile = null;
      return;
    }
    const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
    if (!validTypes.includes(f.type)) {
      message = 'Icon must be JPG, PNG, or GIF';
      iconFile = null;
      return;
    }
    if (f.size > 5 * 1024 * 1024) {
      message = 'Icon must be under 5MB';
      iconFile = null;
      return;
    }
    message = null;
    iconFile = f;
  }

  async function saveManual(ev: SubmitEvent) {
    ev.preventDefault();
    message = null;
    try {
      const res = await fetch('/api/beatleader/oauth/creds', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ client_id: manualClientId, client_secret: manualClientSecret })
      });
      if (!res.ok) throw new Error(await res.text());
      existing = { client_id: manualClientId, client_secret: manualClientSecret };
      manualClientId = '';
      manualClientSecret = '';
      message = 'Saved credentials.';
    } catch (err) {
      message = err instanceof Error ? err.message : 'Failed to save credentials';
    }
  }

  async function register(ev: SubmitEvent) {
    ev.preventDefault();
    message = null;
    created = null;
    try {
      // Perform registration directly against BeatLeader using browser cookies (must be logged in on beatleader.com)
      const url = new URL('https://api.beatleader.com/developer/app');
      url.searchParams.set('name', name);
      url.searchParams.set('clientId', clientId || generateClientId());
      url.searchParams.set('scopes', scopes.join(','));
      url.searchParams.set('redirectUrls', redirectUrls);

      let blRes: Response;
      if (iconFile) {
        const buf = await iconFile.arrayBuffer();
        blRes = await fetch(url.toString(), {
          method: 'POST',
          body: buf,
          credentials: 'include'
        });
      } else {
        blRes = await fetch(url.toString(), {
          method: 'POST',
          credentials: 'include'
        });
      }

      if (!blRes.ok) throw new Error(await blRes.text());
      const data = await blRes.json();
      created = data;

      const savedClientId = data?.clientId ?? data?.client_id;
      const savedClientSecret = data?.clientSecret ?? data?.client_secret;
      if (!savedClientId || !savedClientSecret) throw new Error('BeatLeader response missing credentials');

      // Persist credentials locally
      const saveRes = await fetch('/api/beatleader/oauth/creds', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ client_id: savedClientId, client_secret: savedClientSecret })
      });
      if (!saveRes.ok) throw new Error(await saveRes.text());

      existing = { client_id: savedClientId, client_secret: savedClientSecret };
      message = 'Registered successfully. Credentials saved.';
    } catch (err) {
      const base = err instanceof Error ? err.message : 'Registration failed';
      message = base || 'Registration failed. Ensure you are logged into BeatLeader in this browser.';
    }
  }

  function generateClientId(): string {
    return 'bl_' + Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
  }

  function generateDefaultClientId(): string {
    try {
      // Prefer uuid for readability; strip dashes
      const uuid = (crypto?.randomUUID?.() ?? '') as string;
      if (uuid) return 'bl_' + uuid.replace(/-/g, '');
    } catch {}
    return generateClientId();
  }

  async function copy(text: string, kind: string) {
    try {
      copying = kind;
      await navigator.clipboard.writeText(text);
    } catch {
      // ignore
    } finally {
      setTimeout(() => (copying = null), 800);
    }
  }
</script>

<section class="py-8">
  <h1 class="font-display text-3xl sm:text-4xl">BeatLeader OAuth Setup</h1>
  <p class="mt-2 text-muted">Register an OAuth application and store credentials for this site.</p>

  <div class="mt-2 text-xs text-muted flex flex-wrap items-center gap-2">
    {#if blCredsStatus === 'unknown'}
      <span class="rounded bg-white/10 px-2 py-1">Checking BeatLeader access…</span>
    {:else if blCredsStatus === 'configured'}
      <span class="rounded bg-emerald-500/20 text-emerald-300 px-2 py-1">BeatLeader access: Connected</span>
      {#if blManageUrl}
        <a class="underline hover:text-white" href={blManageUrl}>Manage</a>
      {/if}
    {:else}
      <span class="rounded bg-rose-500/20 text-rose-300 px-2 py-1">BeatLeader access: Not connected</span>
      {#if blManageUrl}
        <a class="underline hover:text-white" href={blManageUrl}>Configure</a>
      {/if}
    {/if}
  </div>

  {#if returnTo}
    <div class="mt-4">
      <a class="rounded-md border border-white/10 px-3 py-1.5 text-sm hover:border-white/20" href={returnTo}>Return to previous page</a>
    </div>
  {/if}

  <div class="mt-6 grid gap-3 max-w-xl text-sm">
    <div class="text-muted">Manual setup (recommended):</div>
    <ol class="list-decimal pl-5 grid gap-2">
      <li>
        Open the BeatLeader developer portal: 
        <a class="underline" href="https://beatleader.com/developer" target="_blank" rel="noreferrer">beatleader.com/developer</a>
      </li>
      <li>
        Create a new application using the following values:
        <div class="mt-2 grid gap-2">
          <div>
            <div class="text-muted">Suggested Client ID</div>
            <div class="flex items-center gap-2">
              <code>{recommendedClientId}</code>
              <button type="button" class="rounded-md border border-white/10 px-2 py-1 text-xs hover:border-white/20" on:click={() => copy(recommendedClientId, 'clientId')}>
                {copying === 'clientId' ? 'Copied' : 'Copy'}
              </button>
            </div>
          </div>
          <div>
            <div class="text-muted">Redirect URL</div>
            <div class="flex items-center gap-2">
              <code>{origin}/auth/beatleader/callback</code>
              <button type="button" class="rounded-md border border-white/10 px-2 py-1 text-xs hover:border-white/20" on:click={() => copy(`${origin}/auth/beatleader/callback`, 'redirect')}>
                {copying === 'redirect' ? 'Copied' : 'Copy'}
              </button>
            </div>
          </div>
          <div>
            <div class="text-muted">Scopes</div>
            <code>scp:profile{scopes.includes('scp:offline_access') ? ',scp:offline_access' : ''}</code>
          </div>
        </div>
      </li>
      <li>
        After creation, copy the shown client secret and paste both values below to save locally.
      </li>
    </ol>
  </div>

  {#if existing}
    <div class="mt-4 text-sm">
      <div class="text-muted">Existing credentials found.</div>
      <div class="mt-1">Client ID: <code>{existing.client_id}</code></div>
      <div>Client Secret: <code>{existing.client_secret}</code></div>
    </div>
  {/if}

  <details class="mt-4">
    <summary class="cursor-pointer text-sm text-muted">Enter credentials manually</summary>
    <form class="mt-3 grid gap-3 max-w-xl" on:submit|preventDefault={saveManual}>
      <div>
        <label class="block text-sm text-muted" for="mClientId">Client ID</label>
        <input id="mClientId" class="w-full rounded-md border border-white/10 bg-transparent px-3 py-2 text-sm outline-none" bind:value={manualClientId} required />
      </div>
      <div>
        <label class="block text-sm text-muted" for="mClientSecret">Client Secret</label>
        <input id="mClientSecret" class="w-full rounded-md border border-white/10 bg-transparent px-3 py-2 text-sm outline-none" bind:value={manualClientSecret} required />
      </div>
      <div>
        <button class="btn-neon">Save</button>
      </div>
    </form>
  </details>

  

  {#if message}
    <div class="mt-4 text-sm">{message}</div>
  {/if}

  {#if created}
    <div class="mt-6 text-sm">
      <div><strong>Client ID:</strong> <code>{created.clientId}</code></div>
      <div><strong>Client Secret:</strong> <code>{created.clientSecret}</code></div>
      <div class="mt-2">
          <a class="rounded-md border border-white/10 px-3 py-1.5 text-sm hover:border-white/20" href="/auth/beatleader/login">Proceed to Login</a>
      </div>
    </div>
  {/if}
</section>


