<profile-page>
  <div class="profile-overlay" onclick={handleOverlayClick}>
    <div class="profile-card">
      <div class="profile-header">
        <h2>Profile</h2>
        <button class="btn btn-ghost btn-icon" onclick={props.cbClose} title="Close">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>
      </div>

      <div class="avatar-section">
        <div class="avatar-wrapper">
          <img src={currentAvatar()} alt="Avatar" class="avatar-preview" width="96" height="96" />
          <label class="avatar-edit-btn" title="Upload avatar">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
              <circle cx="12" cy="13" r="4"/>
            </svg>
            <input type="file" accept="image/png,image/jpeg,image/gif,image/webp" onchange={handleAvatarUpload} class="hidden-input" />
          </label>
        </div>
        <p if={state.avatarUploading} class="upload-status">Uploading...</p>
        <button if={props.user?.avatar_url} class="btn btn-ghost btn-sm remove-avatar" onclick={handleRemoveAvatar}>
          Remove custom avatar
        </button>
      </div>

      <form onsubmit={handleSave}>
        <div class="form-group">
          <label for="displayName">Display Name</label>
          <input
            type="text"
            id="displayName"
            value={state.displayName}
            oninput={e => update({ displayName: e.target.value })}
            required
          />
        </div>

        <div class="form-group" if={!props.user?.nostr_pubkey}>
          <label>Email</label>
          <input type="email" value={props.user?.email} disabled class="input-disabled" />
          <span class="form-hint">Email cannot be changed</span>
        </div>

        <div class="form-group" if={props.user?.nostr_pubkey}>
          <label>Nostr Public Key</label>
          <input type="text" value={npubDisplay()} disabled class="input-disabled input-mono" />
          <span class="form-hint">Logged in via Nostr</span>
        </div>

        <p if={state.error} class="error-text">{state.error}</p>
        <p if={state.success} class="success-text">{state.success}</p>

        <div class="profile-actions">
          <button type="button" class="btn btn-ghost" onclick={props.cbClose}>Cancel</button>
          <button type="submit" class="btn btn-primary" disabled={state.saving}>
            {state.saving ? 'Saving...' : 'Save Changes'}
          </button>
        </div>
      </form>
    </div>
  </div>

  <style>
    .profile-overlay {
      position: fixed;
      inset: 0;
      background: rgba(0, 0, 0, 0.6);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 100;
      animation: fadeIn 0.15s ease-out;
    }

    .profile-card {
      width: 100%;
      max-width: 440px;
      background: var(--bg-secondary);
      border: 1px solid var(--border);
      border-radius: var(--radius-lg);
      padding: var(--space-xl);
      animation: slideUp 0.2s ease-out;
    }

    @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
    @keyframes slideUp { from { transform: translateY(16px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }

    .profile-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: var(--space-lg);
    }

    .profile-header h2 {
      font-size: var(--text-lg);
      font-weight: 600;
    }

    .avatar-section {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: var(--space-xl);
    }

    .avatar-wrapper {
      position: relative;
      width: 96px;
      height: 96px;
    }

    .avatar-preview {
      width: 96px;
      height: 96px;
      border-radius: var(--radius-full);
      object-fit: cover;
      border: 3px solid var(--border);
    }

    .avatar-edit-btn {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 32px;
      height: 32px;
      border-radius: var(--radius-full);
      background: var(--accent);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: background var(--transition-fast);
      border: 2px solid var(--bg-secondary);
    }

    .avatar-edit-btn:hover {
      background: var(--accent-hover);
    }

    .hidden-input {
      display: none;
    }

    .upload-status {
      margin-top: var(--space-sm);
      font-size: var(--text-sm);
      color: var(--text-secondary);
    }

    .remove-avatar {
      margin-top: var(--space-sm);
      font-size: var(--text-xs);
      color: var(--text-muted);
    }

    .form-group {
      margin-bottom: var(--space-md);
    }

    .form-group label {
      display: block;
      margin-bottom: var(--space-xs);
      font-size: var(--text-sm);
      color: var(--text-secondary);
    }

    .input-disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }

    .input-mono {
      font-family: var(--font-mono);
      font-size: var(--text-xs);
    }

    .form-hint {
      display: block;
      margin-top: 4px;
      font-size: var(--text-xs);
      color: var(--text-muted);
    }

    .error-text {
      color: var(--error);
      font-size: var(--text-sm);
      margin-bottom: var(--space-sm);
    }

    .success-text {
      color: var(--success);
      font-size: var(--text-sm);
      margin-bottom: var(--space-sm);
    }

    .profile-actions {
      display: flex;
      justify-content: flex-end;
      gap: var(--space-sm);
      margin-top: var(--space-lg);
    }

    .btn-icon {
      width: 36px;
      height: 36px;
      padding: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: var(--radius-md);
    }

    .btn-sm {
      padding: var(--space-xs) var(--space-md);
      font-size: var(--text-sm);
    }
  </style>

  <script>
    import { api, saveAuth } from '../services/api.js'
    import { getAvatarUrl } from '../services/avatar.js'

    export default {
      state: {
        displayName: '',
        saving: false,
        avatarUploading: false,
        error: null,
        success: null,
      },

      onMounted() {
        // Copy the current profile value into local form state so edits stay cancelable.
        this.update({
          displayName: this.props.user?.display_name || '',
        })
      },

      npubDisplay() {
        const hex = this.props.user?.nostr_pubkey
        if (!hex) return ''
        // Show truncated hex with npub prefix hint
        return 'npub...' + hex.slice(-12)
      },

      currentAvatar() {
        return getAvatarUrl(this.props.user, 96)
      },

      handleOverlayClick(e) {
        if (e.target.classList.contains('profile-overlay')) {
          this.props.cbClose()
        }
      },

      async handleSave(e) {
        e.preventDefault()
        this.update({ saving: true, error: null, success: null })

        try {
          const data = await api.updateProfile({ display_name: this.state.displayName })
          // Server returns a refreshed token/user pair, so persist both together.
          saveAuth(data.token, data.user)
          this.props.cbProfileUpdate(data.user)
          this.update({ saving: false, success: 'Profile updated!' })
        } catch (err) {
          this.update({ saving: false, error: err.message })
        }
      },

      async handleAvatarUpload(e) {
        const file = e.target.files[0]
        if (!file) return

        // Keep avatar uploads small because they are stored and served by the app itself.
        if (file.size > 2 * 1024 * 1024) {
          this.update({ error: 'Avatar must be under 2MB' })
          return
        }

        this.update({ avatarUploading: true, error: null, success: null })

        try {
          const data = await api.uploadAvatar(file)
          saveAuth(data.token, data.user)
          this.props.cbProfileUpdate(data.user)
          this.update({ avatarUploading: false, success: 'Avatar updated!' })
        } catch (err) {
          this.update({ avatarUploading: false, error: err.message })
        }
      },

      async handleRemoveAvatar() {
        this.update({ error: null, success: null })

        try {
          const data = await api.deleteAvatar()
          saveAuth(data.token, data.user)
          this.props.cbProfileUpdate(data.user)
          this.update({ success: 'Avatar removed' })
        } catch (err) {
          this.update({ error: err.message })
        }
      },
    }
  </script>
</profile-page>
