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

  let calories = $state(2000);
  let protein = $state(150);
  let carbs = $state(200);
  let fat = $state(65);
  let sugar = $state(0);
  let fiber = $state(0);
  let startDate = $state('');
  let loading = $state(true);
  let editing = $state(false);
  let saving = $state(false);
  let hasGoal = $state(false);

  // Edit state
  let editCal = $state('2000');
  let editProtein = $state('150');
  let editCarbs = $state('200');
  let editFat = $state('65');
  let editSugar = $state('0');
  let editFiber = $state('0');

  function today(): string {
    const n = new Date();
    return `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`;
  }

  async function loadGoals() {
    try {
      const res = await fetch(`/api/fitness/goals/for-date?date=${today()}`, { credentials: 'include' });
      if (res.ok) {
        const g = await res.json();
        calories = g.calories || 2000;
        protein = g.protein || 150;
        carbs = g.carbs || 200;
        fat = g.fat || 65;
        sugar = g.sugar || 0;
        fiber = g.fiber || 0;
        hasGoal = true;
        if (g.start_date) {
          const d = new Date(g.start_date + 'T00:00:00');
          startDate = d.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
        }
      }
    } catch { /* silent */ }
    loading = false;
  }

  function startEdit() {
    editCal = String(Math.round(calories));
    editProtein = String(Math.round(protein));
    editCarbs = String(Math.round(carbs));
    editFat = String(Math.round(fat));
    editSugar = String(Math.round(sugar));
    editFiber = String(Math.round(fiber));
    editing = true;
  }

  function cancelEdit() {
    editing = false;
  }

  async function saveGoals() {
    saving = true;
    try {
      const res = await fetch('/api/fitness/goals', {
        method: 'PUT',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          calories: parseFloat(editCal) || 2000,
          protein: parseFloat(editProtein) || 150,
          carbs: parseFloat(editCarbs) || 200,
          fat: parseFloat(editFat) || 65,
          sugar: parseFloat(editSugar) || 0,
          fiber: parseFloat(editFiber) || 0,
          start_date: today(),
        }),
      });
      if (res.ok) {
        editing = false;
        await loadGoals();
      }
    } catch { /* silent */ }
    saving = false;
  }

  onMount(loadGoals);
</script>

<div class="page">
  <div class="app-surface">
    <div class="page-header">
      <div class="page-title">FITNESS</div>
      <div class="page-subtitle">Daily Goals</div>
    </div>

    <div class="module">
      <div class="module-header">
        <div class="module-title">CURRENT GOALS</div>
        {#if !editing}
          <button class="module-action" onclick={startEdit}>Edit Goals</button>
        {/if}
      </div>

      {#if editing}
        <div class="edit-grid">
          <div class="edit-field">
            <label class="edit-label">Calories (kcal/day)</label>
            <input class="edit-input" type="number" bind:value={editCal} />
          </div>
          <div class="edit-field">
            <label class="edit-label">Protein (g/day)</label>
            <input class="edit-input" type="number" bind:value={editProtein} />
          </div>
          <div class="edit-field">
            <label class="edit-label">Carbs (g/day)</label>
            <input class="edit-input" type="number" bind:value={editCarbs} />
          </div>
          <div class="edit-field">
            <label class="edit-label">Fat (g/day)</label>
            <input class="edit-input" type="number" bind:value={editFat} />
          </div>
          <div class="edit-field">
            <label class="edit-label">Sugar (g/day)</label>
            <input class="edit-input" type="number" bind:value={editSugar} />
          </div>
          <div class="edit-field">
            <label class="edit-label">Fiber (g/day)</label>
            <input class="edit-input" type="number" bind:value={editFiber} />
          </div>
        </div>
        <div class="edit-actions">
          <button class="btn-cancel" onclick={cancelEdit}>Cancel</button>
          <button class="btn-save" onclick={saveGoals} disabled={saving}>
            {saving ? 'Saving...' : 'Save Goals'}
          </button>
        </div>
      {:else}
        <div class="goals-grid">
          <div class="goal-card">
            <div class="goal-label">Calories</div>
            <div class="goal-value">{loading ? '...' : Math.round(calories).toLocaleString()}</div>
            <div class="goal-unit">kcal/day</div>
          </div>
          <div class="goal-card">
            <div class="goal-label">Protein</div>
            <div class="goal-value">{loading ? '...' : Math.round(protein)}</div>
            <div class="goal-unit">grams/day</div>
          </div>
          <div class="goal-card">
            <div class="goal-label">Carbs</div>
            <div class="goal-value">{loading ? '...' : Math.round(carbs)}</div>
            <div class="goal-unit">grams/day</div>
          </div>
          <div class="goal-card">
            <div class="goal-label">Fat</div>
            <div class="goal-value">{loading ? '...' : Math.round(fat)}</div>
            <div class="goal-unit">grams/day</div>
          </div>
          <div class="goal-card">
            <div class="goal-label">Sugar</div>
            <div class="goal-value">{loading ? '...' : Math.round(sugar)}</div>
            <div class="goal-unit">grams/day</div>
          </div>
          <div class="goal-card">
            <div class="goal-label">Fiber</div>
            <div class="goal-value">{loading ? '...' : Math.round(fiber)}</div>
            <div class="goal-unit">grams/day</div>
          </div>
        </div>

        {#if startDate}
          <div class="start-date">
            <span class="start-date-label">Active since</span>
            <span class="start-date-value">{startDate}</span>
          </div>
        {:else if !loading && !hasGoal}
          <div class="no-goal">No goals set yet. Tap "Edit Goals" to get started.</div>
        {/if}
      {/if}
    </div>
  </div>
</div>

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

  .module { background: var(--card); border-radius: var(--radius); padding: var(--card-pad-primary); box-shadow: var(--card-shadow); border: 1px solid var(--border); }
  .module-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: var(--sp-5); }
  .module-title { font-size: var(--text-sm); font-weight: 600; color: var(--text-3); text-transform: uppercase; letter-spacing: 0.04em; }
  .module-action { font-size: var(--text-sm); color: var(--accent); font-weight: 500; cursor: pointer; background: none; border: none; padding: 0; }
  .module-action:hover { text-decoration: underline; }

  .goals-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--row-gap); margin-bottom: var(--sp-5); }
  .goal-card { background: var(--surface-secondary); border-radius: var(--radius-sm); padding: var(--sp-4); border: 1px solid var(--border); }
  .goal-label { font-size: var(--text-sm); font-weight: 500; color: var(--text-3); text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: var(--sp-2); }
  .goal-value { font-size: var(--text-xl); font-weight: 500; font-family: var(--mono); color: var(--text-1); line-height: 1; }
  .goal-unit { font-size: var(--text-sm); color: var(--text-3); margin-top: var(--sp-1); }

  .start-date { display: flex; align-items: center; justify-content: space-between; padding-top: var(--sp-4); border-top: 1px solid var(--border); }
  .start-date-label { font-size: var(--text-sm); color: var(--text-3); }
  .start-date-value { font-size: var(--text-sm); color: var(--text-2); font-weight: 500; }
  .no-goal { font-size: var(--text-sm); color: var(--text-3); text-align: center; padding: var(--sp-4) 0; }

  .edit-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-3); margin-bottom: var(--sp-5); }
  .edit-field { display: flex; flex-direction: column; gap: var(--sp-1); }
  .edit-label { font-size: var(--text-sm); font-weight: 500; color: var(--text-3); }
  .edit-input {
    padding: var(--sp-2) var(--sp-3); border-radius: var(--radius-md); border: 1px solid var(--border);
    background: var(--surface-secondary); color: var(--text-1); font-size: var(--text-lg); font-family: var(--mono);
  }
  .edit-input:focus { outline: none; border-color: var(--accent); }
  .edit-actions { display: flex; gap: var(--sp-2); justify-content: flex-end; }
  .btn-cancel {
    padding: var(--sp-2) var(--sp-4); border-radius: var(--radius-md);
    background: var(--card-secondary); color: var(--text-2); border: 1px solid var(--border);
    font-size: var(--text-sm); font-weight: 500; cursor: pointer; font-family: var(--font);
  }
  .btn-save {
    padding: var(--sp-2) var(--sp-4); border-radius: var(--radius-md);
    background: var(--accent); color: white; border: none;
    font-size: var(--text-sm); font-weight: 600; cursor: pointer; font-family: var(--font);
  }
  .btn-save:disabled { opacity: 0.5; }

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