<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;
     }
   }
 
   $effect(() => {
     fetchUsers();
   });
 </script>
 
 <div class="user-manager mode-{mode}">
   {#if mode === 'selector'}
     <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>
           </div>
         {/each}
       </div>
     </div>
   {:else}
     <!-- Manager Mode -->
     <header class="manager-header">
       <h1 class="text-xl font-bold text-text-primary">User Management</h1>
       <button class="add-user-btn-large" onclick={() => showAddForm = true}>
         + New User
       </button>
     </header>
 
     {#if showAddForm}
       <div class="modal-overlay">
         <form class="add-user-modal" onsubmit={(e) => { e.preventDefault(); handleAddUser(); }}>
           <h3 class="text-lg font-semibold">Add User</h3>
           <!-- svelte-ignore a11y_autofocus -->
           <input
             type="text"
             bind:value={newUserName}
             placeholder="Name..."
             class="modal-input"
             autofocus
           />
           <div class="modal-actions">
             <button type="button" class="btn-secondary" onclick={() => { showAddForm = false; newUserName = ''; }}>Cancel</button>
             <button type="submit" class="btn-primary" disabled={!newUserName.trim()}>Add User</button>
           </div>
         </form>
       </div>
     {/if}
 
     <div class="user-list">
       {#each users as user}
         <div class="user-item">
           {#if editingUserId === user.id}
             <form class="edit-row" onsubmit={(e) => { e.preventDefault(); handleUpdateUser(); }}>
               <!-- svelte-ignore a11y_autofocus -->
               <input type="text" bind:value={editName} class="edit-input" autofocus />
               <div class="edit-actions">
                 <button type="submit" class="save-btn" title="Save">✓</button>
                 <button type="button" class="cancel-btn" onclick={() => editingUserId = null} title="Cancel">✕</button>
               </div>
             </form>
           {:else}
             <div class="user-info">
               <span class="user-name-large">{user.name}</span>
               <span class="user-id">ID: {user.id}</span>
             </div>
             <div class="user-actions">
               <button class="action-btn" onclick={() => startEditing(user)} title="Rename">✏️</button>
               {#if confirmDeleteId === user.id}
                 <button class="action-btn danger" onclick={() => handleRemoveUser(user.id)}>Delete!</button>
                 <button class="action-btn" onclick={() => confirmDeleteId = null}>Cancel</button>
               {:else}
                 <button class="action-btn" onclick={() => confirmDeleteId = user.id} title="Delete">🗑️</button>
               {/if}
             </div>
           {/if}
         </div>
       {:else}
         <div class="empty-state">No users found. Create one to get started!</div>
       {/each}
     </div>
   {/if}
 
   {#if error}
     <div class="user-error">{error}</div>
   {/if}
 </div>

 <style>
   .user-manager {
     margin-bottom: 16px;
   }
 
   /* Selector Mode Styles */
   .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 16px;
     border-radius: 20px;
     border: 1px solid var(--color-border);
     background: var(--color-bg-card);
     color: var(--color-text-secondary);
     cursor: pointer;
     font-size: 13px;
     font-weight: 600;
     transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
   }
 
   .user-chip:hover {
     border-color: var(--color-accent);
     color: var(--color-text-primary);
     transform: translateY(-1px);
     box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
   }
 
   .user-chip.selected {
     background: color-mix(in srgb, var(--color-accent) 20%, transparent);
     border-color: var(--color-accent);
     color: var(--color-accent);
     box-shadow: 0 0 0 1px var(--color-accent);
   }
 
   /* Manager Mode Styles */
   .manager-header {
     display: flex;
     justify-content: space-between;
     align-items: center;
     margin-bottom: 24px;
   }
 
   .add-user-btn-large {
     padding: 10px 20px;
     border-radius: 12px;
     background: var(--color-accent);
     color: white;
     border: none;
     font-weight: 600;
     cursor: pointer;
     transition: all 0.2s;
     box-shadow: 0 4px 14px color-mix(in srgb, var(--color-accent) 40%, transparent);
   }
 
   .add-user-btn-large:hover {
     filter: brightness(1.1);
     transform: translateY(-1px);
   }
 
   .user-list {
     display: grid;
     gap: 12px;
   }
 
   .user-item {
     display: flex;
     justify-content: space-between;
     align-items: center;
     padding: 16px 20px;
     border-radius: 16px;
     background: var(--color-bg-card);
     border: 1px solid var(--color-border);
     transition: all 0.2s;
   }
 
   .user-item:hover {
     border-color: var(--color-accent);
     background: var(--color-bg-card-hover);
   }
 
   .user-info {
     display: flex;
     flex-direction: column;
     gap: 4px;
   }
 
   .user-name-large {
     font-size: 16px;
     font-weight: 600;
     color: var(--color-text-primary);
   }
 
   .user-id {
     font-size: 11px;
     color: var(--color-text-secondary);
     font-family: var(--font-mono);
     text-transform: uppercase;
     letter-spacing: 0.05em;
   }
 
   .user-actions {
     display: flex;
     gap: 8px;
   }
 
   .action-btn {
     background: var(--color-bg-primary);
     border: 1px solid var(--color-border);
     color: var(--color-text-secondary);
     padding: 8px;
     border-radius: 8px;
     cursor: pointer;
     font-size: 14px;
     transition: all 0.2s;
   }
 
   .action-btn:hover {
     border-color: var(--color-accent);
     color: var(--color-accent);
     background: var(--color-bg-card);
   }
 
   .action-btn.danger:hover {
     border-color: var(--color-danger);
     color: var(--color-danger);
     background: color-mix(in srgb, var(--color-danger) 10%, transparent);
   }
 
   /* Modal Styles */
   .modal-overlay {
     position: fixed;
     inset: 0;
     background: rgba(0, 0, 0, 0.7);
     backdrop-filter: blur(4px);
     display: flex;
     align-items: center;
     justify-content: center;
     z-index: 100;
   }
 
   .add-user-modal {
     background: var(--color-bg-card);
     padding: 24px;
     border-radius: 20px;
     border: 1px solid var(--color-border);
     width: 100%;
     max-width: 400px;
     display: flex;
     flex-direction: column;
     gap: 20px;
     box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4);
   }
 
   .modal-input {
     padding: 12px 16px;
     border-radius: 12px;
     border: 1px solid var(--color-border);
     background: var(--color-bg-primary);
     color: var(--color-text-primary);
     font-size: 14px;
   }
 
   .modal-actions {
     display: flex;
     gap: 12px;
     justify-content: flex-end;
   }
 
   /* Edit Inline Row */
   .edit-row {
     display: flex;
     gap: 12px;
     width: 100%;
   }
 
   .edit-input {
     flex: 1;
     padding: 8px 12px;
     border-radius: 8px;
     border: 1px solid var(--color-accent);
     background: var(--color-bg-primary);
     color: var(--color-text-primary);
     outline: none;
   }
 
   .edit-actions {
     display: flex;
     gap: 6px;
   }
 
   .save-btn, .cancel-btn {
     padding: 4px 12px;
     border-radius: 6px;
     border: 1px solid var(--color-border);
     cursor: pointer;
     transition: all 0.2s;
   }
 
   .save-btn {
     background: var(--color-success);
     color: white;
     border-color: var(--color-success);
   }
 
   .cancel-btn {
     background: var(--color-bg-primary);
     color: var(--color-text-secondary);
   }
 
   /* Common UI items */
   .btn-primary {
     padding: 8px 16px;
     border-radius: 8px;
     background: var(--color-accent);
     color: white;
     border: none;
     font-weight: 600;
     cursor: pointer;
   }
 
   .btn-secondary {
     padding: 8px 16px;
     border-radius: 8px;
     background: var(--color-bg-primary);
     color: var(--color-text-secondary);
     border: 1px solid var(--color-border);
     cursor: pointer;
   }
 
   .btn-primary:disabled {
     opacity: 0.5;
     cursor: not-allowed;
   }
 
   .user-error {
     margin-top: 16px;
     padding: 12px;
     border-radius: 12px;
     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: 13px;
     text-align: center;
   }
 
   .empty-state {
     text-align: center;
     padding: 48px;
     background: var(--color-bg-card);
     border: 1px dashed var(--color-border);
     border-radius: 16px;
     color: var(--color-text-secondary);
   }
 </style>
