<script>
  import { getUsers, addUser, removeUser, updateUser } from './api.js';
 
  let { 
    selectedUserId = $bindable(null), 
    onUsersChanged = () => {},
    mode = 'selector' // 'selector' | 'manager'
  } = $props();
 
  let users = $state([]);
  let newUserName = $state('');
  let showAddForm = $state(false);
  let error = $state('');
  let confirmDeleteId = $state(null);
  
  // Edit state
  let editingUserId = $state(null);
  let editName = $state('');
 
  async function fetchUsers() {
    try {
      users = await getUsers();
      if (users.length > 0 && !selectedUserId && mode === 'selector') {
        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();
      if (mode === 'selector') 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;
    }
  }
 
  function startEditing(user) {
    editingUserId = user.id;
    editName = user.name;
  }
 
  async function handleUpdateUser() {
    if (!editName.trim()) return;
    try {
      await updateUser(editingUserId, editName.trim());
      editingUserId = null;
      await fetchUsers();
      onUsersChanged();
    } catch (e) {
      error = e.message;
    }
  }
 
  // Load initial data on mount
  $effect(() => {
    fetchUsers();
  });
</script>
 
<div class="mb-4">
  {#if mode === 'selector'}
    <div class="flex items-center gap-2">
      <div class="flex flex-wrap gap-1.5 items-center">
        {#each users as user}
          <!-- svelte-ignore node_invalid_placement_ssr -->
          <div
            class="flex items-center gap-1.5 px-4 py-1.5 rounded-full border cursor-pointer text-[13px] font-semibold
              transition-all duration-200 hover:-translate-y-px hover:shadow-[0_4px_12px_rgba(0,0,0,0.1)]
              {selectedUserId === user.id
                ? 'bg-accent/20 border-accent text-accent ring-1 ring-accent'
                : 'border-border bg-bg-card text-text-secondary hover:border-accent hover:text-text-primary'}"
            onclick={() => selectedUserId = user.id}
            role="button"
            tabindex="0"
            onkeydown={(e) => { if (e.key === 'Enter') selectedUserId = user.id; }}
          >
            <span>{user.name}</span>
          </div>
        {/each}
      </div>
    </div>
  {:else}
    <!-- Manager Mode -->
    <header class="flex justify-between items-center mb-6">
      <h1 class="text-xl font-bold text-text-primary">User Management</h1>
      <button
        class="px-5 py-2.5 rounded-xl bg-accent text-white border-none font-semibold cursor-pointer transition-all
               shadow-accent/30 shadow-lg hover:brightness-110 hover:-translate-y-px"
        onclick={() => showAddForm = true}
      >
        + New User
      </button>
    </header>

    {#if showAddForm}
      <div class="fixed inset-0 bg-black/70 backdrop-blur flex items-center justify-center z-[100]">
        <form
          class="bg-bg-card p-6 rounded-[20px] border border-border w-full max-w-sm flex flex-col gap-5 shadow-[0_20px_40px_rgba(0,0,0,0.4)]"
          onsubmit={(e) => { e.preventDefault(); handleAddUser(); }}
        >
          <h3 class="text-lg font-semibold text-text-primary">Add User</h3>
          <!-- svelte-ignore a11y_autofocus -->
          <input
            type="text"
            bind:value={newUserName}
            placeholder="Name..."
            class="px-4 py-3 rounded-xl border border-border bg-bg-primary text-text-primary text-sm outline-none focus:border-accent"
            autofocus
          />
          <div class="flex gap-3 justify-end">
            <button
              type="button"
              class="px-4 py-2 rounded-lg bg-bg-primary text-text-secondary border border-border cursor-pointer transition-all hover:bg-bg-card-hover"
              onclick={() => { showAddForm = false; newUserName = ''; }}
            >Cancel</button>
            <button
              type="submit"
              class="px-4 py-2 rounded-lg bg-accent text-white border-none font-semibold cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
              disabled={!newUserName.trim()}
            >Add User</button>
          </div>
        </form>
      </div>
    {/if}

    <div class="grid gap-3">
      {#each users as user}
        <div class="flex justify-between items-center px-5 py-4 rounded-2xl bg-bg-card border border-border transition-all hover:border-accent hover:bg-bg-card-hover">
          {#if editingUserId === user.id}
            <form class="flex gap-3 w-full" onsubmit={(e) => { e.preventDefault(); handleUpdateUser(); }}>
              <!-- svelte-ignore a11y_autofocus -->
              <input
                type="text"
                bind:value={editName}
                class="flex-1 px-3 py-2 rounded-lg border border-accent bg-bg-primary text-text-primary outline-none"
                autofocus
              />
              <div class="flex gap-1.5">
                <button type="submit" class="px-3 py-1 rounded-md border-none bg-success text-white cursor-pointer transition-all" title="Save">✓</button>
                <button type="button" class="px-3 py-1 rounded-md border border-border bg-bg-primary text-text-secondary cursor-pointer transition-all" onclick={() => editingUserId = null} title="Cancel">✕</button>
              </div>
            </form>
          {:else}
            <div class="flex flex-col gap-1">
              <span class="text-base font-semibold text-text-primary">{user.name}</span>
              <span class="text-[11px] text-text-secondary font-mono uppercase tracking-[0.05em]">ID: {user.id}</span>
            </div>
            <div class="flex gap-2">
              <button
                class="bg-bg-primary border border-border text-text-secondary p-2 rounded-lg cursor-pointer text-sm transition-all hover:border-accent hover:text-accent hover:bg-bg-card"
                onclick={() => startEditing(user)}
                title="Rename"
              >✏️</button>
              {#if confirmDeleteId === user.id}
                <button
                  class="bg-danger/10 border border-danger/30 text-danger px-3 py-1 rounded-lg cursor-pointer text-sm transition-all"
                  onclick={() => handleRemoveUser(user.id)}
                >Delete!</button>
                <button
                  class="bg-bg-primary border border-border text-text-secondary p-2 rounded-lg cursor-pointer text-sm transition-all hover:bg-bg-card-hover"
                  onclick={() => confirmDeleteId = null}
                >Cancel</button>
              {:else}
                <button
                  class="bg-bg-primary border border-border text-text-secondary p-2 rounded-lg cursor-pointer text-sm transition-all hover:border-danger hover:text-danger hover:bg-danger/10"
                  onclick={() => confirmDeleteId = user.id}
                  title="Delete"
                >🗑️</button>
              {/if}
            </div>
          {/if}
        </div>
      {:else}
        <div class="text-center px-12 py-12 bg-bg-card border border-dashed border-border rounded-2xl text-text-secondary">
          No users found. Create one to get started!
        </div>
      {/each}
    </div>
  {/if}
 
  {#if error}
    <div class="mt-4 p-3 rounded-xl bg-danger/10 border border-danger/20 text-danger text-[13px] text-center">{error}</div>
  {/if}
</div>
