<script lang="ts">
  import { goto } from '$app/navigation';

  let query = $state('');

  function handleSubmit(e: Event) {
    e.preventDefault();
    if (query.trim()) {
      goto(`/search?q=${encodeURIComponent(query.trim())}`);
    }
  }

  function handleKeydown(e: KeyboardEvent) {
    if (e.key === 'Escape') {
      query = '';
    }
  }
</script>

<form class="search-bar" onsubmit={handleSubmit}>
  <input
    type="text"
    bind:value={query}
    placeholder="Search videos..."
    onkeydown={handleKeydown}
  />
  <button type="submit" aria-label="Search">
    <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
      <path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
    </svg>
  </button>
</form>

<style>
  .search-bar {
    display: flex;
    max-width: 600px;
    width: 100%;
  }

  input {
    flex: 1;
    padding: 0.75rem 1rem;
    font-size: 1rem;
    border: 1px solid var(--border-color);
    border-right: none;
    border-radius: 4px 0 0 4px;
    background: var(--bg-secondary);
    color: var(--text-primary);
    outline: none;
  }

  input:focus {
    border-color: var(--accent-color);
  }

  input::placeholder {
    color: var(--text-muted);
  }

  button {
    padding: 0.75rem 1.25rem;
    border: 1px solid var(--border-color);
    border-radius: 0 4px 4px 0;
    background: var(--bg-secondary);
    color: var(--text-primary);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  button:hover {
    background: var(--bg-hover);
  }
</style>
