<script>
  import { getUsers, addUser, removeUser } from './api.js';

  let { selectedUserId = $bindable(null), onUsersChanged = () => {} } = $props();

  let users = $state([]);
  let newUserName = $state('');
  let showAddForm = $state(false);
  let error = $state('');
  let confirmDeleteId = $state(null);

  async function fetchUsers() {
    try {
      users = await getUsers();
      if (users.length > 0 && !selectedUserId) {
        selectedUserId = users[0].id;
      }
      // If selected user was deleted, select first available
      if (selectedUserId && !users.find(u => u.id === selectedUserId)) {
        selectedUserId = users.length > 0 ? users[0].id : null;
      }
      error = '';
    } catch (e) {
      error = e.message;
    }
  }

  async function handleAddUser() {
    if (!newUserName.trim()) return;
    try {
      const user = await addUser(newUserName.trim());
      newUserName = '';
      showAddForm = false;
      await fetchUsers();
      selectedUserId = user.id;
      onUsersChanged();
    } catch (e) {
      error = e.message;
    }
  }

  async function handleRemoveUser(id) {
    try {
      await removeUser(id);
      confirmDeleteId = null;
      await fetchUsers();
      onUsersChanged();
    } catch (e) {
      error = e.message;
    }
  }

  $effect(() => {
    fetchUsers();
  });
</script>

<div class="user-manager">
  <div class="user-bar">
    <div class="user-chips">
      {#each users as user}
        <!-- svelte-ignore node_invalid_placement_ssr -->
        <div
          class="user-chip {selectedUserId === user.id ? 'selected' : ''}"
          onclick={() => selectedUserId = user.id}
          role="button"
          tabindex="0"
          onkeydown={(e) => { if (e.key === 'Enter') selectedUserId = user.id; }}
        >
          <span class="user-name">{user.name}</span>
          {#if confirmDeleteId === user.id}
            <span class="confirm-delete">
              <button class="confirm-yes" onclick={(e) => { e.stopPropagation(); handleRemoveUser(user.id); }} title="Confirm delete">✓</button>
              <button class="confirm-no" onclick={(e) => { e.stopPropagation(); confirmDeleteId = null; }} title="Cancel">✕</button>
            </span>
          {:else}
            <button
              class="remove-btn"
              onclick={(e) => { e.stopPropagation(); confirmDeleteId = user.id; }}
              title="Remove user"
            >✕</button>
          {/if}
        </div>
      {/each}

      {#if showAddForm}
        <form class="add-user-form" onsubmit={(e) => { e.preventDefault(); handleAddUser(); }}>
          <!-- svelte-ignore a11y_autofocus -->
          <input
            type="text"
            bind:value={newUserName}
            placeholder="Name..."
            class="add-user-input"
            autofocus
          />
          <button type="submit" class="add-user-submit" disabled={!newUserName.trim()}>+</button>
          <button type="button" class="add-user-cancel" onclick={() => { showAddForm = false; newUserName = ''; }}>✕</button>
        </form>
      {:else}
        <button class="add-user-btn" onclick={() => showAddForm = true}>
          + User
        </button>
      {/if}
    </div>
  </div>

  {#if error}
    <div class="user-error">{error}</div>
  {/if}
</div>

<style>
  .user-manager {
    margin-bottom: 16px;
  }

  .user-bar {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .user-chips {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    align-items: center;
  }

  .user-chip {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    border-radius: 20px;
    border: 1px solid var(--color-border);
    background: var(--color-bg-card);
    color: var(--color-text-secondary);
    cursor: pointer;
    font-size: 12px;
    font-weight: 500;
    transition: all 0.15s;
  }

  .user-chip:hover {
    border-color: var(--color-accent);
    color: var(--color-text-primary);
  }

  .user-chip.selected {
    background: color-mix(in srgb, var(--color-accent) 15%, transparent);
    border-color: var(--color-accent);
    color: var(--color-accent);
  }

  .user-name {
    white-space: nowrap;
  }

  .remove-btn {
    background: none;
    border: none;
    color: var(--color-text-secondary);
    cursor: pointer;
    font-size: 10px;
    padding: 0 2px;
    opacity: 0.5;
    transition: opacity 0.15s, color 0.15s;
    line-height: 1;
  }

  .remove-btn:hover {
    opacity: 1;
    color: var(--color-danger);
  }

  .confirm-delete {
    display: flex;
    gap: 4px;
  }

  .confirm-yes, .confirm-no {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 11px;
    padding: 0 2px;
    line-height: 1;
  }

  .confirm-yes {
    color: var(--color-danger);
  }

  .confirm-no {
    color: var(--color-text-secondary);
  }

  .add-user-btn {
    padding: 6px 12px;
    border-radius: 20px;
    border: 1px dashed var(--color-border);
    background: transparent;
    color: var(--color-text-secondary);
    cursor: pointer;
    font-size: 12px;
    font-weight: 500;
    transition: all 0.15s;
  }

  .add-user-btn:hover {
    border-color: var(--color-accent);
    color: var(--color-accent);
  }

  .add-user-form {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .add-user-input {
    padding: 5px 10px;
    border-radius: 16px;
    border: 1px solid var(--color-border);
    background: var(--color-bg-primary);
    color: var(--color-text-primary);
    font-size: 12px;
    width: 100px;
    outline: none;
  }

  .add-user-input:focus {
    border-color: var(--color-accent);
  }

  .add-user-submit {
    background: var(--color-accent);
    color: white;
    border: none;
    border-radius: 50%;
    width: 24px;
    height: 24px;
    font-size: 14px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 1;
  }

  .add-user-submit:disabled {
    opacity: 0.4;
    cursor: not-allowed;
  }

  .add-user-cancel {
    background: none;
    border: none;
    color: var(--color-text-secondary);
    cursor: pointer;
    font-size: 12px;
  }

  .user-error {
    margin-top: 8px;
    padding: 6px 10px;
    border-radius: 6px;
    background: color-mix(in srgb, var(--color-danger) 10%, transparent);
    border: 1px solid color-mix(in srgb, var(--color-danger) 20%, transparent);
    color: var(--color-danger);
    font-size: 11px;
  }
</style>
