<script lang="ts">
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import { page } from '$app/stores';
  import { settings, loadSettings } from '$lib/stores/settings';
  import { searchLocalTracks } from '$lib/library/search';
  import { searchDeezerTracks } from '$lib/services/deezer/search';

  let query = $state('');
  let error = $state<string | null>(null);
  let isSearching = $state(false);

  onMount(async () => {
    await loadSettings();

    // Pre-fill query from URL parameter
    const urlQuery = $page.url.searchParams.get('q');
    if (urlQuery) {
      query = urlQuery;
    }
  });

  async function handleSearch(type: 'local' | 'online') {
    if (!query.trim()) {
      return;
    }

    if (type === 'local' && !$settings.musicFolder) {
      error = 'No music folder configured. Please set one in Settings.';
      return;
    }

    error = null;
    isSearching = true;

    try {
      // Perform search first
      const results = type === 'local'
        ? await searchLocalTracks(query)
        : await searchDeezerTracks(query);

      if (results.length === 0) {
        error = `No results found for "${query}"`;
        isSearching = false;
        return;
      }

      // Only navigate if we have results, pass results via state
      goto(`/search/results?q=${encodeURIComponent(query)}&type=${type}`, {
        state: { results }
      });
    } catch (e) {
      error = 'Error performing search: ' + (e as Error).message;
      isSearching = false;
    }
  }

  function handleKeyPress(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      // Default to local search on Enter
      handleSearch('local');
    }
  }
</script>

<div class="wrapper">
  <div class="search-container">
    <div class="search-logo">
      <h1>Shark! Search</h1>
    </div>

    <div class="search-box">
      <!-- svelte-ignore a11y_autofocus -->
      <!-- Autofocus is appropriate for the search tool, and is not an accessibility malfunction in this case -->
      <input
        type="text"
        bind:value={query}
        placeholder="Search for music..."
        onkeypress={handleKeyPress}
        autofocus
      />
    </div>

    <div class="search-buttons">
      <button onclick={() => handleSearch('local')} disabled={isSearching}>
        Search Local
      </button>
      <button onclick={() => handleSearch('online')} disabled={isSearching}>
        Search Online
      </button>
    </div>

    {#if isSearching}
      <p class="searching-message">Searching...</p>
    {/if}

    {#if error}
      <p class="error-message">{error}</p>
    {/if}
  </div>
</div>

<style>
  .wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .search-container {
    flex-shrink: 0;
    padding: 40px 20px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
  }

  .search-logo h1 {
    margin: 0;
    font-size: 2em;
    font-weight: normal;
    text-align: center;
  }

  .search-box {
    width: 100%;
    max-width: 600px;
  }

  .search-box input {
    width: 100%;
    padding: 8px 12px;
    box-sizing: border-box;
  }

  .search-buttons {
    display: flex;
    gap: 12px;
  }

  .search-buttons button {
    min-width: 140px;
  }

  .searching-message {
    margin: 0;
    opacity: 0.7;
  }

  .error-message {
    margin: 0;
    opacity: 0.7;
  }

</style>
