<script lang="ts">
  import { profileStore } from '$lib/client/profile.svelte';
  import { confirmAction, alertAction } from '$lib/client/confirm.svelte';

  let newName = $state('');
  let newEmoji = $state('🍳');
  let adding = $state(false);
  let errored = $state<string | null>(null);

  async function add() {
    errored = null;
    if (!newName.trim()) return;
    adding = true;
    try {
      await profileStore.create(newName.trim(), newEmoji || null);
      newName = '';
    } catch (e) {
      errored = (e as Error).message;
    } finally {
      adding = false;
    }
  }

  async function rename(id: number, currentName: string) {
    const next = prompt('Neuer Name:', currentName);
    if (!next || next === currentName) return;
    const res = await fetch(`/api/profiles/${id}`, {
      method: 'PATCH',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ name: next.trim() })
    });
    if (!res.ok) {
      const body = await res.json().catch(() => ({}));
      await alertAction({
        title: 'Umbenennen fehlgeschlagen',
        message: body.message ?? `HTTP ${res.status}`
      });
      return;
    }
    await profileStore.load();
  }

  async function remove(id: number, name: string) {
    const ok = await confirmAction({
      title: `Profil „${name}" löschen?`,
      message:
        'Bewertungen, Favoriten und Kochjournal-Einträge dieses Profils werden mit gelöscht. Rezepte und Kommentare bleiben erhalten.',
      confirmLabel: 'Löschen',
      destructive: true
    });
    if (!ok) return;
    await fetch(`/api/profiles/${id}`, { method: 'DELETE' });
    if (profileStore.activeId === id) profileStore.clear();
    await profileStore.load();
  }
</script>

<h1>Profile</h1>
<p class="intro">
  Profile werden ohne Passwort verwendet. Beim App-Start wählt man einfach aus.
</p>

<form
  class="row"
  onsubmit={(e) => {
    e.preventDefault();
    void add();
  }}
>
  <input type="text" bind:value={newEmoji} maxlength="8" class="emoji-in" />
  <input type="text" bind:value={newName} placeholder="Name" required />
  <button type="submit" class="btn primary" disabled={adding}>Anlegen</button>
</form>

{#if errored}
  <p class="error">{errored}</p>
{/if}

{#if !profileStore.loaded}
  <p class="muted">Lädt…</p>
{:else if profileStore.profiles.length === 0}
  <p class="muted">Noch keine Profile.</p>
{:else}
  <ul class="list">
    {#each profileStore.profiles as p (p.id)}
      <li>
        <div class="who">
          <span class="emoji">{p.avatar_emoji ?? '🙂'}</span>
          <span class="name">{p.name}</span>
          {#if profileStore.activeId === p.id}
            <span class="active-badge">aktiv</span>
          {/if}
        </div>
        <div class="actions">
          <button class="btn" onclick={() => rename(p.id, p.name)}>Umbenennen</button>
          <button class="btn danger" onclick={() => remove(p.id, p.name)}>Löschen</button>
        </div>
      </li>
    {/each}
  </ul>
{/if}

<style>
  h1 {
    font-size: 1.3rem;
    margin: 0 0 0.5rem;
  }
  .intro {
    color: #666;
    margin: 0 0 1rem;
    font-size: 0.95rem;
  }
  .row {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 1rem;
    flex-wrap: wrap;
  }
  .emoji-in {
    width: 3.2rem;
    text-align: center;
  }
  .row input {
    flex: 1;
    min-width: 140px;
    padding: 0.7rem 0.85rem;
    border: 1px solid #cfd9d1;
    border-radius: 10px;
    min-height: 44px;
    font-size: 1rem;
  }
  .btn {
    padding: 0.55rem 0.85rem;
    min-height: 40px;
    border-radius: 10px;
    border: 1px solid #cfd9d1;
    background: white;
    cursor: pointer;
    font-size: 0.9rem;
  }
  .btn.primary {
    background: #2b6a3d;
    color: white;
    border: 0;
    padding: 0.7rem 1rem;
    min-height: 44px;
  }
  .btn.danger {
    color: #c53030;
    border-color: #f1b4b4;
  }
  .list {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }
  .list li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: white;
    border: 1px solid #e4eae7;
    border-radius: 12px;
    padding: 0.6rem 0.9rem;
    gap: 0.75rem;
    flex-wrap: wrap;
  }
  .who {
    display: flex;
    align-items: center;
    gap: 0.6rem;
  }
  .emoji {
    font-size: 1.4rem;
  }
  .name {
    font-weight: 600;
  }
  .active-badge {
    padding: 0.15rem 0.5rem;
    background: #eaf4ed;
    color: #2b6a3d;
    border-radius: 999px;
    font-size: 0.75rem;
  }
  .actions {
    display: flex;
    gap: 0.5rem;
  }
  .error {
    color: #c53030;
    margin-bottom: 1rem;
  }
  .muted {
    color: #888;
    text-align: center;
    padding: 2rem 0;
  }
</style>
