<script lang="ts">
  import { onMount } from 'svelte';
  import { PocketBaseAuth } from '$lib/auth/frontend';
  import type { AuthState } from '$lib/auth/types';
  
  let auth: PocketBaseAuth | undefined;
  let authState: AuthState = {
    isAuthenticated: false,
    user: null,
    token: null,
  };
  let graphToken = '';
  let pbTokenValid = false;
  let comparisonData: string | null = null;
  let loading = false;
  let error = '';
  
  onMount(async () => {
    try {
      const response = await fetch('/api/auth/config');
      if (!response.ok) throw new Error('Failed to get config');
      const config = await response.json();
      
      auth = new PocketBaseAuth(config, {
        onAuthSuccess: (state: AuthState) => {
          authState = state;
          console.log('Auth success:', state);
        },
        onAuthFailure: (err: unknown) => {
          error = 'Authentication failed: ' + (err instanceof Error ? err.message : 'Unknown error');
          console.error('Auth error:', err);
        },
        onTokenUpdate: (state: AuthState) => {
          authState = state;
        },
        onUiUpdate: (state: AuthState) => {
          authState = state;
        },
      });
    } catch (err) {
      error = err instanceof Error ? err.message : 'Unknown error';
      console.error(err);
    }
  });
  
  async function handleFetchGraphToken() {
    loading = true;
    error = '';
    try {
      const response = await fetch('/api/auth/graph/token');
      if (!response.ok) throw new Error('Failed to fetch Graph token');
      const data = await response.json();
      graphToken = JSON.stringify(data, null, 2);
    } catch (err) {
      error = err instanceof Error ? err.message : 'Unknown error';
    } finally {
      loading = false;
    }
  }
  
  async function handleRefreshGraphToken() {
    loading = true;
    error = '';
    try {
      const response = await fetch('/api/auth/refresh-graph', { method: 'POST' });
      if (!response.ok) throw new Error('Failed to refresh');
      const data = await response.json();
      graphToken = JSON.stringify(data, null, 2);
    } catch (err) {
      error = err instanceof Error ? err.message : 'Unknown error';
    } finally {
      loading = false;
    }
  }
  
  async function handleValidatePBToken() {
    loading = true;
    error = '';
    try {
      const pbToken = auth?.getPocketBase?.()?.authStore?.token;
      if (!pbToken) {
        error = 'No PocketBase token found. Please log in first.';
        pbTokenValid = false;
        return;
      }
      
      const response = await fetch('/api/auth/validate-pb-token', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ pbToken }),
      });
      if (!response.ok) throw new Error('Validation failed');
      const data = await response.json();
      pbTokenValid = data.valid;
      error = data.valid ? '' : 'Token validation failed';
    } catch (err) {
      error = err instanceof Error ? err.message : 'Unknown error';
      pbTokenValid = false;
    } finally {
      loading = false;
    }
  }
  
  async function handleCompareTokens() {
    loading = true;
    error = '';
    try {
      const pbToken = auth?.getPocketBase?.()?.authStore?.token;
      const response = await fetch('/api/auth/compare-tokens', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ pbToken }),
      });
      if (!response.ok) throw new Error('Comparison failed');
      const data = await response.json();
      comparisonData = JSON.stringify(data, null, 2);
    } catch (err) {
      error = err instanceof Error ? err.message : 'Unknown error';
    } finally {
      loading = false;
    }
  }
  
  function handleLogout() {
    if (auth) {
      auth.logout();
      authState = {
        isAuthenticated: false,
        user: null,
        token: null,
      };
      error = '';
    }
  }
</script>

<div style="min-height: 100vh; background: linear-gradient(to bottom, #0f172a, #1e293b); color: white; padding: 16px; padding-bottom: 100px;">
  <div style="max-width: 800px; margin: 0 auto;">
    <!-- Header -->
    <div style="margin-bottom: 32px;">
      <h1 style="font-size: 28px; font-weight: bold; margin: 0 0 8px 0; color: #60a5fa;">Mode2Svelte</h1>
      <p style="font-size: 14px; color: #94a3b8; margin: 0;">Advanced Auth Testing Dashboard</p>
    </div>

    <!-- Error Display -->
    {#if error}
      <div style="background: rgba(127, 29, 29, 0.2); border: 1px solid #dc2626; color: #fca5a5; padding: 12px; border-radius: 8px; margin-bottom: 16px; font-size: 14px;">
        {error}
      </div>
    {/if}

    <!-- Auth Status -->
    <div style="background: rgba(71, 85, 105, 0.3); border: 1px solid #475569; padding: 16px; border-radius: 8px; margin-bottom: 16px;">
      <h2 style="font-size: 20px; font-weight: bold; margin: 0 0 12px 0;">Authentication Status</h2>
      
      {#if authState.isAuthenticated && authState.user !== null}
        <div style="display: flex; flex-direction: column; gap: 12px;">
          <div style="font-size: 14px;">
            <span style="color: #cbd5e1;">Status:</span>
            <span style="margin-left: 8px; color: #4ade80; font-weight: bold;">✓ Authenticated</span>
          </div>
          <div style="font-size: 14px; word-break: break-all;">
            <span style="color: #cbd5e1;">User:</span>
            <span style="margin-left: 8px; color: #93c5fd;" id="userDisplayName">{authState.user?.name}</span>
          </div>
          <div style="font-size: 14px; word-break: break-all;">
            <span style="color: #cbd5e1;">Email:</span>
            <span style="margin-left: 8px; color: #93c5fd;" id="userEmailValue">{authState.user?.email}</span>
          </div>
          <button
            on:click={handleLogout}
            style="background: #dc2626; color: white; border: none; padding: 12px 16px; border-radius: 6px; font-weight: bold; font-size: 14px; cursor: pointer; margin-top: 8px; width: 100%;"
          >
            Logout
          </button>
        </div>
      {:else}
        <div id="loginContainer" style="display: flex; flex-direction: column; gap: 12px;">
          <p style="font-size: 14px; color: #cbd5e1; margin: 0;">Not authenticated. Log in to begin testing.</p>
          <button
            id="loginBtn"
            style="background: #2563eb; color: white; border: none; padding: 16px; border-radius: 6px; font-weight: bold; font-size: 16px; cursor: pointer; width: 100%;"
          >
            Login with Microsoft
          </button>
          <div id="loginError" style="color: #f87171; font-size: 12px; display: none;"></div>
        </div>
      {/if}
    </div>

    <!-- API Testing -->
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 16px;">
      <!-- Graph Token -->
      <div style="background: rgba(71, 85, 105, 0.3); border: 1px solid #475569; padding: 12px; border-radius: 8px;">
        <h3 style="font-size: 16px; font-weight: bold; margin: 0 0 12px 0;">Graph Token</h3>
        <div style="display: flex; flex-direction: column; gap: 8px;">
          <button
            on:click={handleFetchGraphToken}
            disabled={loading}
            style="background: #4f46e5; color: white; border: none; padding: 10px; border-radius: 6px; font-weight: bold; font-size: 14px; cursor: pointer; opacity: {loading ? 0.6 : 1}; width: 100%;"
          >
            {loading ? 'Loading...' : 'Fetch Token'}
          </button>
          <button
            on:click={handleRefreshGraphToken}
            disabled={loading}
            style="background: #4f46e5; color: white; border: none; padding: 10px; border-radius: 6px; font-weight: bold; font-size: 14px; cursor: pointer; opacity: {loading ? 0.6 : 1}; width: 100%;"
          >
            {loading ? 'Loading...' : 'Refresh'}
          </button>
        </div>
      </div>

      <!-- PocketBase Token -->
      <div style="background: rgba(71, 85, 105, 0.3); border: 1px solid #475569; padding: 12px; border-radius: 8px;">
        <h3 style="font-size: 16px; font-weight: bold; margin: 0 0 12px 0;">PocketBase Token</h3>
        <div style="display: flex; flex-direction: column; gap: 8px;">
          <button
            on:click={handleValidatePBToken}
            disabled={loading}
            style="background: #059669; color: white; border: none; padding: 10px; border-radius: 6px; font-weight: bold; font-size: 14px; cursor: pointer; opacity: {loading ? 0.6 : 1}; width: 100%;"
          >
            {loading ? 'Loading...' : 'Validate'}
          </button>
          {#if pbTokenValid}
            <p style="color: #4ade80; font-size: 12px; margin: 0;">✓ Token is valid</p>
          {/if}
        </div>
      </div>
    </div>

    <!-- Compare Tokens -->
    <div style="background: rgba(71, 85, 105, 0.3); border: 1px solid #475569; padding: 12px; border-radius: 8px; margin-bottom: 16px;">
      <button
        on:click={handleCompareTokens}
        disabled={loading}
        style="background: #9333ea; color: white; border: none; padding: 12px; border-radius: 6px; font-weight: bold; font-size: 14px; cursor: pointer; opacity: {loading ? 0.6 : 1}; width: 100%;"
      >
        {loading ? 'Loading...' : 'Compare Tokens'}
      </button>
    </div>

    <!-- Output -->
    {#if graphToken}
      <div style="background: rgba(71, 85, 105, 0.3); border: 1px solid #475569; padding: 12px; border-radius: 8px; margin-bottom: 16px;">
        <h3 style="font-size: 16px; font-weight: bold; margin: 0 0 12px 0;">Graph Token Response</h3>
        <pre style="background: #0f172a; padding: 12px; border-radius: 6px; overflow-x: auto; font-size: 11px; color: #cbd5e1; max-height: 200px; white-space: pre-wrap; word-wrap: break-word; margin: 0;">{graphToken}</pre>
      </div>
    {/if}

    {#if comparisonData}
      <div style="background: rgba(71, 85, 105, 0.3); border: 1px solid #475569; padding: 12px; border-radius: 8px;">
        <h3 style="font-size: 16px; font-weight: bold; margin: 0 0 12px 0;">Token Comparison</h3>
        <pre style="background: #0f172a; padding: 12px; border-radius: 6px; overflow-x: auto; font-size: 11px; color: #cbd5e1; max-height: 200px; white-space: pre-wrap; word-wrap: break-word; margin: 0;">{comparisonData}</pre>
      </div>
    {/if}
  </div>
</div>

