<script lang="ts">
  import { page } from '$app/stores';
  import { goto } from '$app/navigation';
  import { BookmarkPlus } from 'lucide-svelte';
  import RecipeView from '$lib/components/RecipeView.svelte';
  import { alertAction } from '$lib/client/confirm.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);
    } else {
      loading = false;
      errored = 'Kein ?url=-Parameter. Suche zuerst ein Rezept und klicke auf einen Treffer.';
    }
  });

  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(() => ({}));
      await alertAction({
        title: 'Speichern fehlgeschlagen',
        message: body.message ?? `HTTP ${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>Diese Seite enthält kein Rezept</h2>
    <p class="detail">{errored}</p>
    <p class="explain">
      Wahrscheinlich hast du eine Forum- oder Übersichtsseite erwischt, kein einzelnes
      Rezept. Geh zurück und wähle einen anderen Treffer.
    </p>
    <div class="actions">
      <button type="button" class="back-btn" onclick={() => history.back()}>
        ← Zurück zur Trefferliste
      </button>
      <a class="src-link" href={targetUrl} target="_blank" rel="noopener">
        Seite im Browser öffnen ↗
      </a>
    </div>
  </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}>
          {#if saving}
            <span>Speichern…</span>
          {:else}
            <BookmarkPlus size={18} strokeWidth={2} />
            <span>Rezept in Kochwas speichern</span>
          {/if}
        </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 {
    padding: 1.5rem 1.25rem;
    background: #fff6d7;
    border: 1px solid #e6d48a;
    border-radius: 12px;
    margin-top: 1rem;
  }
  .error-box h2 {
    color: #6d5400;
    margin: 0 0 0.5rem;
    font-size: 1.15rem;
  }
  .detail {
    color: #6d5400;
    font-family: monospace;
    font-size: 0.85rem;
    background: rgba(255, 255, 255, 0.55);
    padding: 0.5rem 0.75rem;
    border-radius: 6px;
    margin: 0 0 0.75rem;
  }
  .explain {
    color: #5c4800;
    line-height: 1.45;
    margin: 0 0 1rem;
  }
  .actions {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
  }
  .back-btn {
    padding: 0.7rem 1rem;
    min-height: 44px;
    background: #2b6a3d;
    color: white;
    border: 0;
    border-radius: 10px;
    cursor: pointer;
    font-size: 0.95rem;
  }
  .src-link {
    padding: 0.7rem 1rem;
    min-height: 44px;
    display: inline-flex;
    align-items: center;
    background: white;
    border: 1px solid #cfd9d1;
    border-radius: 10px;
    text-decoration: none;
    color: #444;
    font-size: 0.95rem;
  }
  .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>
