<script lang="ts">
  import { page } from '$app/stores';
  import { goto } from '$app/navigation';
  import type { SearchHit } from '$lib/server/recipes/search-local';

  let query = $state(($page.url.searchParams.get('q') ?? '').trim());
  let hits = $state<SearchHit[]>([]);
  let loading = $state(false);
  let searched = $state(false);
  let canWebSearch = $state(false);

  async function run(q: string) {
    loading = true;
    searched = true;
    canWebSearch = true;
    const res = await fetch(`/api/recipes/search?q=${encodeURIComponent(q)}`);
    const body = await res.json();
    hits = body.hits;
    loading = false;
  }

  $effect(() => {
    const q = ($page.url.searchParams.get('q') ?? '').trim();
    query = q;
    if (q) void run(q);
  });

  function submit(e: SubmitEvent) {
    e.preventDefault();
    goto(`/search?q=${encodeURIComponent(query.trim())}`);
  }
</script>

<form class="search-bar" onsubmit={submit}>
  <input
    type="search"
    bind:value={query}
    placeholder="Rezept suchen…"
    autocomplete="off"
    inputmode="search"
    aria-label="Suchbegriff"
  />
  <button type="submit">Suchen</button>
</form>

{#if loading}
  <p class="muted">Suche läuft …</p>
{:else if searched && hits.length === 0}
  <section class="empty">
    <p>Kein Rezept im Bestand für „{query}".</p>
    <a class="web-btn" href={`/search/web?q=${encodeURIComponent(query)}`}>
      🌐 Im Internet suchen
    </a>
  </section>
{:else if hits.length > 0}
  <ul class="hits">
    {#each hits as r (r.id)}
      <li>
        <a href={`/recipes/${r.id}`} class="hit">
          {#if r.image_path}
            <img src={`/images/${r.image_path}`} alt="" loading="lazy" />
          {:else}
            <div class="placeholder">🥘</div>
          {/if}
          <div class="hit-body">
            <div class="title">{r.title}</div>
            <div class="meta">
              {#if r.source_domain}<span>{r.source_domain}</span>{/if}
              {#if r.avg_stars !== null}
                <span>★ {r.avg_stars.toFixed(1)}</span>
              {/if}
              {#if r.last_cooked_at}
                <span>Zuletzt: {new Date(r.last_cooked_at).toLocaleDateString('de-DE')}</span>
              {/if}
            </div>
          </div>
        </a>
      </li>
    {/each}
  </ul>
  {#if canWebSearch}
    <div class="web-cta">
      <a class="web-btn" href={`/search/web?q=${encodeURIComponent(query)}`}>
        🌐 Im Internet weitersuchen
      </a>
    </div>
  {/if}
{/if}

<style>
  .search-bar {
    display: flex;
    gap: 0.5rem;
    padding: 1rem 0;
    position: sticky;
    top: 0;
    background: #f8faf8;
  }
  input[type='search'] {
    flex: 1;
    padding: 0.8rem 1rem;
    font-size: 1.05rem;
    border: 1px solid #cfd9d1;
    border-radius: 10px;
    min-height: 48px;
  }
  button {
    padding: 0.8rem 1.2rem;
    background: #2b6a3d;
    color: white;
    border: 0;
    border-radius: 10px;
    min-height: 48px;
    cursor: pointer;
  }
  .muted {
    color: #888;
    text-align: center;
    margin-top: 2rem;
  }
  .empty {
    text-align: center;
    margin-top: 2rem;
  }
  .hits {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
  }
  .hit {
    display: flex;
    gap: 0.75rem;
    background: white;
    border: 1px solid #e4eae7;
    border-radius: 14px;
    overflow: hidden;
    text-decoration: none;
    color: inherit;
    min-height: 96px;
  }
  .hit img,
  .placeholder {
    width: 104px;
    min-height: 96px;
    object-fit: cover;
    background: #eef3ef;
    display: grid;
    place-items: center;
    font-size: 2rem;
  }
  .hit-body {
    flex: 1;
    padding: 0.75rem 0.9rem;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .title {
    font-weight: 600;
    font-size: 1rem;
    line-height: 1.25;
  }
  .meta {
    display: flex;
    gap: 0.6rem;
    margin-top: 0.25rem;
    color: #888;
    font-size: 0.8rem;
    flex-wrap: wrap;
  }
  .web-cta {
    margin-top: 1.25rem;
    text-align: center;
  }
  .web-btn {
    display: inline-block;
    padding: 0.8rem 1.25rem;
    background: #2b6a3d;
    color: white;
    text-decoration: none;
    border-radius: 10px;
    font-size: 1rem;
    min-height: 48px;
  }
  .empty .web-btn {
    margin-top: 1rem;
  }
</style>
