<script lang="ts">
  import { onMount, onDestroy } from 'svelte';
  import { goto } from '$app/navigation';
  import RecipeView from '$lib/components/RecipeView.svelte';
  import StarRating from '$lib/components/StarRating.svelte';
  import { profileStore } from '$lib/client/profile.svelte';
  import { confirmAction } from '$lib/client/confirm.svelte';
  import type { CommentRow } from '$lib/server/recipes/actions';

  let { data } = $props();

  // local reactive copies we can mutate after actions
  let ratings = $state<typeof data.ratings>([]);
  let comments = $state<CommentRow[]>([]);
  let cookingLog = $state<typeof data.cooking_log>([]);
  let isFav = $state(false);
  let onWishlist = $state(false);
  let newComment = $state('');

  $effect(() => {
    ratings = [...data.ratings];
    comments = [...data.comments];
    cookingLog = [...data.cooking_log];
  });

  const myRating = $derived(
    profileStore.active
      ? (ratings.find((r) => r.profile_id === profileStore.active!.id)?.stars ?? null)
      : null
  );

  async function checkFavorite() {
    if (!profileStore.active) {
      isFav = false;
      return;
    }
    // Fetch favorite status via list endpoint (quick hack: GET not implemented, infer from no-op)
    // Not critical for MVP — we mutate state on toggle.
  }

  async function setRating(stars: number) {
    if (!profileStore.active) {
      alert('Bitte erst Profil wählen.');
      return;
    }
    await fetch(`/api/recipes/${data.recipe.id}/rating`, {
      method: 'PUT',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ profile_id: profileStore.active.id, stars })
    });
    const existing = ratings.find((r) => r.profile_id === profileStore.active!.id);
    if (existing) existing.stars = stars;
    else ratings = [...ratings, { profile_id: profileStore.active.id, stars }];
  }

  async function toggleFavorite() {
    if (!profileStore.active) {
      alert('Bitte erst Profil wählen.');
      return;
    }
    const method = isFav ? 'DELETE' : 'PUT';
    await fetch(`/api/recipes/${data.recipe.id}/favorite`, {
      method,
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ profile_id: profileStore.active.id })
    });
    isFav = !isFav;
  }

  async function logCooked() {
    if (!profileStore.active) {
      alert('Bitte erst Profil wählen.');
      return;
    }
    const res = await fetch(`/api/recipes/${data.recipe.id}/cooked`, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ profile_id: profileStore.active.id })
    });
    const entry = await res.json();
    cookingLog = [entry, ...cookingLog];
  }

  async function addComment() {
    if (!profileStore.active) {
      alert('Bitte erst Profil wählen.');
      return;
    }
    const text = newComment.trim();
    if (!text) return;
    const res = await fetch(`/api/recipes/${data.recipe.id}/comments`, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ profile_id: profileStore.active.id, text })
    });
    if (res.ok) {
      const body = await res.json();
      comments = [
        ...comments,
        {
          id: body.id,
          profile_id: profileStore.active.id,
          text,
          created_at: new Date().toISOString(),
          author: profileStore.active.name
        }
      ];
      newComment = '';
    }
  }

  async function deleteRecipe() {
    const ok = await confirmAction({
      title: 'Rezept löschen?',
      message: `„${data.recipe.title}" wird endgültig entfernt — mit Bewertungen, Kommentaren und Kochjournal-Einträgen.`,
      confirmLabel: 'Löschen',
      destructive: true
    });
    if (!ok) return;
    await fetch(`/api/recipes/${data.recipe.id}`, { method: 'DELETE' });
    goto('/');
  }

  async function renameRecipe() {
    const newTitle = prompt('Neuer Titel:', data.recipe.title);
    if (!newTitle || newTitle === data.recipe.title) return;
    await fetch(`/api/recipes/${data.recipe.id}`, {
      method: 'PATCH',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ title: newTitle })
    });
    location.reload();
  }

  async function toggleWishlist() {
    if (onWishlist) {
      await fetch(`/api/wishlist/${data.recipe.id}`, { method: 'DELETE' });
      onWishlist = false;
    } else {
      await fetch('/api/wishlist', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          recipe_id: data.recipe.id,
          profile_id: profileStore.active?.id ?? null
        })
      });
      onWishlist = true;
    }
  }

  async function refreshWishlistState() {
    // No dedicated GET for a single entry; scan the list and check.
    const res = await fetch('/api/wishlist?sort=newest');
    if (!res.ok) return;
    const body = await res.json();
    onWishlist = body.entries.some((e: { recipe_id: number }) => e.recipe_id === data.recipe.id);
  }

  // Wake-Lock
  let wakeLock: WakeLockSentinel | null = null;
  async function requestWakeLock() {
    try {
      if ('wakeLock' in navigator) {
        wakeLock = await navigator.wakeLock.request('screen');
      }
    } catch {
      // silently ignore
    }
  }

  onMount(() => {
    void requestWakeLock();
    void checkFavorite();
    void refreshWishlistState();
    const onVisibility = () => {
      if (document.visibilityState === 'visible' && !wakeLock) void requestWakeLock();
    };
    document.addEventListener('visibilitychange', onVisibility);
    return () => document.removeEventListener('visibilitychange', onVisibility);
  });

  onDestroy(() => {
    if (wakeLock) void wakeLock.release();
  });
</script>

<RecipeView recipe={data.recipe}>
  {#snippet showActions()}
    <div class="action-bar">
      <div class="rating-row">
        <span class="label">Deine Bewertung:</span>
        <StarRating value={myRating} onChange={setRating} size="lg" />
        {#if data.avg_stars !== null}
          <span class="avg">⌀ {data.avg_stars.toFixed(1)} ({ratings.length})</span>
        {/if}
      </div>
      <div class="btn-row">
        <button class="btn" onclick={logCooked}>
          🍳 Heute gekocht
          {#if cookingLog.length > 0}
            <span class="count">({cookingLog.length})</span>
          {/if}
        </button>
        <button class="btn" class:heart={isFav} onclick={toggleFavorite}>
          {isFav ? '♥' : '♡'} Favorit
        </button>
        <button class="btn" class:wish={onWishlist} onclick={toggleWishlist}>
          {onWishlist ? '✓' : '🍽️'} {onWishlist ? 'Auf Wunschliste' : 'Auf Wunschliste setzen'}
        </button>
        <button class="btn" onclick={() => window.print()}>🖨 Drucken</button>
        <button class="btn" onclick={renameRecipe}>✎ Umbenennen</button>
        <button class="btn danger" onclick={deleteRecipe}>🗑 Löschen</button>
      </div>
    </div>
  {/snippet}
</RecipeView>

<section class="comments">
  <h2>Kommentare</h2>
  {#if comments.length === 0}
    <p class="muted">Noch keine Kommentare.</p>
  {/if}
  <ul>
    {#each comments as c (c.id)}
      <li>
        <div class="author">{c.author}</div>
        <div class="text">{c.text}</div>
        <div class="date">{new Date(c.created_at).toLocaleString('de-DE')}</div>
      </li>
    {/each}
  </ul>
  <div class="new-comment">
    <textarea
      bind:value={newComment}
      placeholder={profileStore.active
        ? 'z.B. Salz durch Zucker ersetzen'
        : 'Erst Profil wählen, um Kommentare zu schreiben.'}
      rows="3"
      disabled={!profileStore.active}
    ></textarea>
    <button class="btn primary" onclick={addComment} disabled={!profileStore.active}>
      Kommentar speichern
    </button>
  </div>
</section>

{#if cookingLog.length > 0}
  <section class="cooking-log">
    <h2>Kochjournal</h2>
    <ul>
      {#each cookingLog.slice(0, 20) as entry (entry.id)}
        <li>
          {new Date(entry.cooked_at).toLocaleString('de-DE')}
        </li>
      {/each}
    </ul>
  </section>
{/if}

<style>
  .action-bar {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    padding: 0.9rem;
    background: white;
    border: 1px solid #e4eae7;
    border-radius: 14px;
  }
  .rating-row {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    flex-wrap: wrap;
  }
  .label {
    font-size: 0.95rem;
    color: #555;
  }
  .avg {
    color: #888;
    font-size: 0.9rem;
  }
  .btn-row {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
  }
  .btn {
    padding: 0.6rem 0.85rem;
    min-height: 44px;
    border: 1px solid #cfd9d1;
    background: white;
    border-radius: 10px;
    cursor: pointer;
    font-size: 0.95rem;
  }
  .btn:hover {
    background: #f4f8f5;
  }
  .btn.heart {
    color: #c53030;
    border-color: #f1b4b4;
    background: #fdf3f3;
  }
  .btn.wish {
    color: #2b6a3d;
    border-color: #b7d6c2;
    background: #eaf4ed;
  }
  .btn.primary {
    background: #2b6a3d;
    color: white;
    border: 0;
  }
  .btn.danger {
    color: #c53030;
    border-color: #f1b4b4;
  }
  .count {
    color: #888;
    font-size: 0.85em;
  }
  .comments {
    margin-top: 2rem;
  }
  .comments h2 {
    font-size: 1.15rem;
    margin: 0 0 0.75rem;
  }
  .comments ul {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-direction: column;
    gap: 0.6rem;
  }
  .comments li {
    background: white;
    border: 1px solid #e4eae7;
    border-radius: 12px;
    padding: 0.75rem 0.9rem;
  }
  .comments .author {
    font-weight: 600;
    font-size: 0.9rem;
  }
  .comments .text {
    margin-top: 0.25rem;
    line-height: 1.4;
  }
  .comments .date {
    font-size: 0.8rem;
    color: #888;
    margin-top: 0.3rem;
  }
  .new-comment {
    margin-top: 1rem;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }
  .new-comment textarea {
    width: 100%;
    padding: 0.75rem;
    border: 1px solid #cfd9d1;
    border-radius: 10px;
    font: inherit;
    resize: vertical;
  }
  .muted {
    color: #888;
  }
  .cooking-log {
    margin-top: 2rem;
  }
  .cooking-log h2 {
    font-size: 1.1rem;
    margin: 0 0 0.5rem;
  }
  .cooking-log ul {
    list-style: none;
    padding: 0;
    margin: 0;
    color: #555;
  }
  .cooking-log li {
    padding: 0.35rem 0;
    border-bottom: 1px solid #edf1ee;
    font-size: 0.9rem;
  }
</style>
