<script lang="ts">
  import { onMount } from 'svelte';

  interface FoodItem { id: string; name: string; info: string; calories: number; }

  let searchQuery = $state('');
  let foods = $state<FoodItem[]>([]);
  let loading = $state(true);

  function mapFood(f: any): FoodItem {
    const id = f.id || f.food_id || '';
    const name = f.name || f.snapshot_food_name || 'Unknown';
    const brand = f.brand ? `${f.brand} · ` : '';
    const unit = f.base_unit === '100g' ? '100g' : (f.servings?.[0]?.label || f.base_unit || 'serving');
    return { id, name, info: `${brand}${unit}`, calories: Math.round(f.calories_per_base || 0) };
  }

  async function loadFoods(query?: string) {
    loading = true;
    try {
      const url = query
        ? `/api/fitness/foods/search?q=${encodeURIComponent(query)}&limit=50`
        : `/api/fitness/foods?limit=50`;
      const res = await fetch(url, { credentials: 'include' });
      if (res.ok) {
        const raw = await res.json();
        foods = (Array.isArray(raw) ? raw : []).map(mapFood);
      }
    } catch { /* silent */ }
    loading = false;
  }

  let debounceTimer: ReturnType<typeof setTimeout>;
  $effect(() => {
    const q = searchQuery;
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => loadFoods(q || undefined), q ? 300 : 0);
  });

  const filteredFoods = $derived(foods);
</script>

<div class="page">
  <div class="app-surface">
    <div class="page-header">
      <div class="page-title">FITNESS</div>
      <div class="page-subtitle">Food Library</div>
    </div>

    <div class="search-bar">
      <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
      </svg>
      <input
        class="input search-input"
        type="text"
        placeholder="Search foods..."
        bind:value={searchQuery}
      />
    </div>

    <div class="food-list">
      {#each filteredFoods as food (food.name)}
        <div class="food-row">
          <div class="food-info">
            <div class="food-name">{food.name}</div>
            <div class="food-meta">{food.info}</div>
          </div>
          <div class="food-right">
            <span class="food-cal">{food.calories}</span>
            <button class="btn-icon add-btn">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
            </button>
          </div>
        </div>
      {/each}
    </div>
  </div>
</div>

<style>
  .page-subtitle {
    font-size: var(--text-2xl);
    font-weight: 300;
    color: var(--text-1);
    line-height: 1.2;
  }

  .search-bar {
    position: relative;
    margin-bottom: var(--section-gap);
  }
  .search-icon {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    width: 16px;
    height: 16px;
    color: var(--text-3);
    pointer-events: none;
  }
  .search-input {
    padding-left: 40px;
  }

  .food-list {
    display: flex;
    flex-direction: column;
    gap: 0;
  }
  .food-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 0;
    border-bottom: 1px solid var(--border);
  }
  .food-row:last-child { border-bottom: none; }
  .food-name {
    font-size: var(--text-base);
    font-weight: 500;
    color: var(--text-1);
  }
  .food-meta {
    font-size: var(--text-sm);
    color: var(--text-3);
    margin-top: var(--sp-0.5);
  }
  .food-right {
    display: flex;
    align-items: center;
    gap: var(--sp-3);
    flex-shrink: 0;
  }
  .food-cal {
    font-size: var(--text-base);
    font-family: var(--mono);
    color: var(--text-1);
  }
  .add-btn {
    width: 32px;
    height: 32px;
  }

  @media (max-width: 768px) {
    .page-subtitle { font-size: var(--text-xl); }
  }
</style>
