<script>
  // ProgressBar — Calories vs target with remaining (spec §4.6).
  // Renders server-computed values only (spec §8.2 rule 2).
  // The server returns raw totals + target; remaining computed here for display.

  import { formatKcal } from '../lib/format.js'
  import { navigateTo } from '../lib/stores.svelte.js'

  let { totals, target } = $props()

  let consumed = $derived(totals?.calories ?? 0)
  let goal = $derived(target?.calories ?? null)
  let pct = $derived(goal ? Math.min(100, Math.round((consumed / goal) * 100)) : 0)
  let remaining = $derived(goal ? goal - consumed : null)
  let barColor = $derived(pct > 100 ? 'over' : pct >= 90 ? 'warn' : 'ok')
</script>

<div class="progress-bar">
  {#if goal}
    <div class="bar-track">
      <div
        class="bar-fill {barColor}"
        style="width: {Math.min(100, pct)}%"
        role="progressbar"
        aria-valuenow={Math.round(consumed)}
        aria-valuemin="0"
        aria-valuemax={goal}
      ></div>
    </div>
    <div class="bar-labels">
      <span>{formatKcal(consumed)} consumed</span>
      <span>{formatKcal(goal)} target</span>
      {#if remaining !== null}
        <span class="remaining">
          {remaining <= 0 ? formatKcal(Math.abs(remaining)) + ' over' : formatKcal(remaining) + ' remaining'}
        </span>
      {/if}
    </div>
  {:else}
    <p class="no-target">
      {formatKcal(consumed)} consumed today.
      <button class="link" type="button" onclick={() => navigateTo('targetForm')}>
        Set a target
      </button>
    </p>
  {/if}
</div>

<style>
  .progress-bar {
    margin-bottom: 1.25rem;
  }
  .bar-track {
    height: 1.25rem;
    background: var(--bg-muted, #e5e7eb);
    border-radius: 0.5rem;
    overflow: hidden;
  }
  .bar-fill {
    height: 100%;
    border-radius: 0.5rem;
    transition: width 0.3s ease;
    min-width: 0;
  }
  .bar-fill.ok  { background: var(--color-ok, #22c55e); }
  .bar-fill.warn { background: var(--color-warn, #f59e0b); }
  .bar-fill.over { background: var(--color-over, #ef4444); }
  .bar-labels {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem 1rem;
    font-size: 0.85rem;
    margin-top: 0.4rem;
    color: var(--text-muted, #6b7280);
  }
  .remaining { font-weight: 600; }
  .no-target {
    font-size: 0.9rem;
    color: var(--text-muted, #6b7280);
  }
  button.link {
    background: none;
    border: none;
    color: var(--link, #2563eb);
    cursor: pointer;
    text-decoration: underline;
    font: inherit;
    padding: 0;
  }
</style>
