<script lang="ts">
  import { page } from '$app/stores';
  import { goto } from '$app/navigation';
  import RecipeView from '$lib/components/RecipeView.svelte';
  import type { Recipe } from '$lib/types';

  let targetUrl = $state(($page.url.searchParams.get('url') ?? '').trim());
  let recipe = $state<Recipe | null>(null);
  let loading = $state(true);
  let errored = $state<string | null>(null);
  let saving = $state(false);

  async function load(url: string) {
    loading = true;
    errored = null;
    try {
      const res = await fetch(`/api/recipes/preview?url=${encodeURIComponent(url)}`);
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        errored = body.message ?? `HTTP ${res.status}`;
        return;
      }
      recipe = await res.json();
    } catch (e) {
      errored = (e as Error).message;
    } finally {
      loading = false;
    }
  }

  $effect(() => {
    const u = ($page.url.searchParams.get('url') ?? '').trim();
    targetUrl = u;
    if (u) void load(u);
  });

  async function save() {
    if (!targetUrl) return;
    saving = true;
    const res = await fetch('/api/recipes/import', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ url: targetUrl })
    });
    saving = false;
    if (!res.ok) {
      const body = await res.json().catch(() => ({}));
      alert(`Speichern fehlgeschlagen: ${body.message ?? res.status}`);
      return;
    }
    const body = await res.json();
    goto(`/recipes/${body.id}`);
  }
</script>

{#if loading}
  <p class="muted">Vorschau wird geladen…</p>
{:else if errored}
  <section class="error-box">
    <h2>Vorschau nicht möglich</h2>
    <p>{errored}</p>
    <p class="hint">
      <button type="button" class="link" onclick={() => history.back()}>← Zurück</button>
    </p>
  </section>
{:else if recipe}
  <div class="banner">
    <span class="pulse"></span>
    <span>Vorschau — noch nicht gespeichert</span>
  </div>
  <RecipeView {recipe}>
    {#snippet showActions()}
      <div class="save-bar">
        <button class="btn primary" onclick={save} disabled={saving}>
          {saving ? 'Speichern…' : '💾 In meine Sammlung speichern'}
        </button>
        <button type="button" class="btn ghost" onclick={() => history.back()}>Zurück</button>
      </div>
    {/snippet}
  </RecipeView>
{/if}

<style>
  .muted {
    color: #888;
    text-align: center;
    margin: 3rem 0;
  }
  .error-box {
    text-align: center;
    padding: 2rem 1rem;
    background: #fdf3f3;
    border: 1px solid #f1b4b4;
    border-radius: 12px;
    margin-top: 1rem;
  }
  .error-box h2 {
    color: #c53030;
    margin: 0 0 0.5rem;
  }
  .link {
    background: none;
    border: 0;
    color: #666;
    cursor: pointer;
    padding: 0;
    font: inherit;
    text-decoration: underline;
  }
  .banner {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.7rem 1rem;
    background: #fff6d7;
    border: 1px solid #e6d48a;
    border-radius: 10px;
    margin: 0.75rem 0 1rem;
    font-size: 0.9rem;
    color: #6d5400;
  }
  .pulse {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #e6a800;
    animation: pulse 1.8s infinite ease-in-out;
  }
  @keyframes pulse {
    0%, 100% { opacity: 0.35; }
    50% { opacity: 1; }
  }
  .save-bar {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
  }
  .btn {
    padding: 0.8rem 1.1rem;
    min-height: 48px;
    border-radius: 10px;
    cursor: pointer;
    font-size: 1rem;
    border: 0;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
  }
  .btn.primary {
    background: #2b6a3d;
    color: white;
    flex: 1;
    justify-content: center;
  }
  .btn.primary:disabled {
    opacity: 0.6;
    cursor: wait;
  }
  .btn.ghost {
    background: white;
    color: #444;
    border: 1px solid #cfd9d1;
  }
</style>
