<script>
  import '../app.css';
  import { Home, Settings, History, Github, Menu } from 'lucide-svelte';
  import { onMount } from 'svelte';
  
  let currentPage = 'tts';
  let sidebarOpen = true;
  let isLoggedIn = false;
  let username = '';
  let showTokenInput = false;
  let tokenInput = '';
  let tokenError = '';
  let isLocalEnvironment = false;
  let isCheckingAuth = true;
  
  onMount(() => {
    console.log('onMount called - starting auth check');
    // First check if we can use local token (for local development)
    // This should happen before checking localStorage to prioritize local tokens
    checkLocalTokenAvailability();
    
    // Then check if user is logged in (from localStorage)
    checkLoginStatus();
    
    // Re-check login status when page becomes visible (e.g., after OAuth redirect)
    document.addEventListener('visibilitychange', () => {
      if (!document.hidden) {
        checkLoginStatus();
      }
    });
    
    // Listen for storage changes (e.g., when token is set from OAuth callback)
    window.addEventListener('storage', checkLoginStatus);
    
    // Also check periodically to catch cases where localStorage changes in same tab
    const interval = setInterval(checkLoginStatus, 1000);
    
    return () => {
      window.removeEventListener('storage', checkLoginStatus);
      clearInterval(interval);
    };
  });
  
  async function checkLocalTokenAvailability() {
    try {
      console.log('Checking local token availability...');
      const response = await fetch('/api/auth/local-token');
      const data = await response.json();
      console.log('Local token response:', data);
      
      if (data.available) {
        isLocalEnvironment = true;
        // Always use the local token if available (it's more reliable than localStorage)
        localStorage.setItem('hf_access_token', data.token);
        console.log('Set local token in localStorage');
        
        // If we have user info from the API, use it directly
        if (data.user_info && data.user_info.name !== "Local User") {
          isLoggedIn = true;
          username = data.user_info.name.split(' ')[0];
          console.log('Logged in with user info:', username);
        } else {
          // For local tokens, even if we can't validate due to rate limiting,
          // we should still consider the user logged in
          isLoggedIn = true;
          username = "Local User";
          console.log('Logged in with local token (validation skipped due to rate limiting)');
          console.log('isLoggedIn set to:', isLoggedIn, 'username set to:', username);
        }
      } else {
        isLocalEnvironment = false;
        console.log('No local token available');
      }
    } catch (error) {
      console.log('Could not check local token availability:', error);
      isLocalEnvironment = false;
    } finally {
      isCheckingAuth = false;
      console.log('Finished checking auth, isLoggedIn:', isLoggedIn);
    }
  }

  function checkLoginStatus() {
    const token = localStorage.getItem('hf_access_token');
    if (token && !isLoggedIn) {
      // Only fetch user info if we're not already logged in
      // (to avoid overriding the local token login state)
      fetchUserInfo(token);
    } else if (!token) {
      isLoggedIn = false;
      username = '';
    }
  }
  
  async function fetchUserInfo(token) {
    try {
      console.log('Fetching user info for token:', token.substring(0, 10) + '...');
      // Validate token using the correct whoami-v2 endpoint
      const response = await fetch('https://huggingface.co/api/whoami-v2', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (response.ok) {
        const userData = await response.json();
        isLoggedIn = true;
        const fullName = userData.name || userData.fullname || userData.login || userData.username || 'User';
        username = fullName.split(' ')[0];
        console.log('Successfully fetched user info:', username);
      } else {
        // Token might be invalid, remove it
        localStorage.removeItem('hf_access_token');
        isLoggedIn = false;
        username = '';
        console.log('Token validation failed:', response.status);
      }
    } catch (error) {
      // Token might be invalid, remove it
      localStorage.removeItem('hf_access_token');
      isLoggedIn = false;
      username = '';
      console.log('Error fetching user info:', error);
    }
  }
  
  async function handleAuthAction() {
    if (isLoggedIn) {
      // Logout
      localStorage.removeItem('hf_access_token');
      sessionStorage.removeItem('oauth_state');
      isLoggedIn = false;
      username = '';
    } else {
      // If we're on Spaces, redirect to OAuth
      if (window.location.hostname.includes('hf.space') || window.location.hostname.includes('huggingface.co')) {
        // On Spaces, we need to get the OAuth client ID from the backend
        try {
          const response = await fetch('/api/auth/oauth-config');
          const config = await response.json();
          const scopes = config.scopes || 'read-repos write-repos manage-repos inference-api';
          const oauthUrl = `https://huggingface.co/oauth/authorize?client_id=${config.client_id}&redirect_uri=${encodeURIComponent(window.location.origin + '/auth/callback')}&scope=${encodeURIComponent(scopes)}&response_type=code&state=${Date.now()}`;
          window.location.href = oauthUrl;
        } catch (error) {
          console.error('Failed to get OAuth config:', error);
          // Fallback to manual token input
          showTokenInput = true;
          tokenInput = '';
          tokenError = '';
        }
      } else {
        // Local development fallback: show token input
        showTokenInput = true;
        tokenInput = '';
        tokenError = '';
      }
    }
  }

  function closeTokenInput() {
    showTokenInput = false;
    tokenInput = '';
    tokenError = '';
  }

  async function submitToken() {
    if (!tokenInput.trim()) {
      tokenError = 'Please enter a token';
      return;
    }

    if (!tokenInput.startsWith('hf_')) {
      tokenError = 'Token should start with "hf_"';
      return;
    }

    try {
      // Validate token using the correct whoami-v2 endpoint
      const response = await fetch('https://huggingface.co/api/whoami-v2', {
        headers: {
          'Authorization': `Bearer ${tokenInput.trim()}`
        }
      });

      if (response.ok) {
        const userData = await response.json();
        localStorage.setItem('hf_access_token', tokenInput.trim());
        isLoggedIn = true;
        const fullName = userData.name || userData.fullname || userData.login || userData.username || 'User';
        username = fullName.split(' ')[0];
        closeTokenInput();
      } else {
        const errorText = await response.text();
        console.log('Token validation error:', response.status, errorText);
        tokenError = `Invalid token (${response.status}). Please check your token and try again.`;
      }
    } catch (error) {
      console.error('Token validation error:', error);
      tokenError = 'Error validating token. Please try again.';
    }
  }
</script>

<div class="flex h-screen bg-white">
  <!-- Sidebar -->
  <aside class="w-56 border-r border-gray-200 bg-white flex-shrink-0 {sidebarOpen ? '' : 'hidden'}">
    <div class="p-4 border-b border-gray-200">
      <div class="flex items-center gap-3">
        <img src="/assets/hf-studio-logo.png" alt="HF Logo" class="w-8 h-8" />
        <h1 class="text-xl font-semibold">HFStudio<sup class="text-xs text-gray-500 ml-1">BETA</sup></h1>
      </div>
    </div>
    
    <nav class="p-2 text-sm">      
      <div class="mt-2 mb-1 px-2 text-xs font-medium text-gray-500 uppercase">
        Tasks
      </div>
      
      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-gray-100 transition-colors text-left
               {currentPage === 'tts' ? 'bg-gray-100' : ''}"
        on:click={() => currentPage = 'tts'}
      >
        <span>🎙️</span>
        <span>Text to Speech</span>
      </button>
      
      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎵</span>
        <span>Voice Cloning</span>
      </button>
      
      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎧</span>
        <span>Speech to Text</span>
      </button>
      
      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎼</span>
        <span>Sound Effects</span>
      </button>
      
      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎸</span>
        <span>Music Generation</span>
      </button>
      
      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🔊</span>
        <span>Audio Enhancement</span>
      </button>
      
    </nav>
    
    <!-- Sign in with Hugging Face at bottom -->
    <div class="absolute bottom-4 left-2 right-2 w-52">
      <button
        on:click={handleAuthAction}
        disabled={isCheckingAuth}
        class="w-full px-6 py-3 bg-black text-white rounded-lg font-medium hover:bg-gray-800 transition-colors shadow-sm flex items-center justify-center gap-2 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
      >
        <img src="/assets/hf-logo.png" alt="HF Logo" class="w-5 h-5" />
        {#if isCheckingAuth}
          <span>Checking... ({isLoggedIn ? 'logged in' : 'not logged in'})</span>
        {:else if isLoggedIn}
          <span>Sign Out, {username}</span>
        {:else}
          <span>Sign In</span>
        {/if}
      </button>
    </div>
  </aside>
  
  <!-- Main content -->
  <main class="flex-1 overflow-auto">
    <slot />
  </main>

  <!-- Token Input Modal -->
  {#if showTokenInput}
    <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 max-w-md w-full mx-4 shadow-xl">
        <h2 class="text-xl font-semibold mb-4">Sign In with HuggingFace Token</h2>
        
        <div class="mb-4 p-3 bg-blue-50 rounded-md text-sm">
          <p class="text-blue-800 mb-2">
            <strong>Manual Token Entry:</strong> Please enter your HuggingFace token.
          </p>
          <p class="text-blue-700">
            1. Go to <a href="https://huggingface.co/settings/tokens" target="_blank" class="underline text-blue-600">HuggingFace Settings</a><br>
            2. Create a new token with "Inference API" permissions<br>
            3. Copy and paste it below
          </p>
          {#if isLocalEnvironment}
            <p class="text-blue-600 mt-2">
              <strong>Tip:</strong> You can also run <code>huggingface-cli login</code> in your terminal to automatically use your local token.
            </p>
          {/if}
        </div>

        <div class="mb-4">
          <label for="token" class="block text-sm font-medium text-gray-700 mb-2">
            HuggingFace Token
          </label>
          <input
            id="token"
            type="password"
            bind:value={tokenInput}
            placeholder="hf_..."
            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent"
            on:keydown={(e) => e.key === 'Enter' && submitToken()}
          />
          {#if tokenError}
            <p class="text-red-600 text-sm mt-1">{tokenError}</p>
          {/if}
        </div>

        <div class="flex justify-end gap-3">
          <button
            on:click={closeTokenInput}
            class="px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors"
          >
            Cancel
          </button>
          <button
            on:click={submitToken}
            class="px-4 py-2 bg-orange-500 text-white rounded-md hover:bg-orange-600 transition-colors"
          >
            Sign In
          </button>
        </div>
      </div>
    </div>
  {/if}
</div>