<script>
  import { onMount } from 'svelte';
  import { push } from 'svelte-spa-router';
  import { auth } from '../lib/stores/auth.js';
  import { getProfile, updateProfile, uploadAvatar } from '../lib/api/profile.js';

  let profile = null;
  let loading = true;
  let saving = false;
  let error = null;
  let success = null;
  let displayName = '';
  let avatarFile = null;
  let avatarPreview = null;

  $: userId = $auth.user?.id;

  $: if (userId && !profile && !loading) load();

  $: if (!$auth.loading && !userId) push('/');

  onMount(() => {
    if (userId) load();
    else if (!$auth.loading) loading = false;
  });

  async function load() {
    if (!userId) return;
    loading = true;
    error = null;
    try {
      profile = await getProfile(userId);
      displayName = profile?.display_name ?? '';
      avatarPreview = profile?.avatar_url ?? null;
    } catch (e) {
      error = e?.message ?? 'Failed to load profile';
    } finally {
      loading = false;
    }
  }

  function onAvatarChange(e) {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) {
      error = 'Please choose an image file (JPEG, PNG, GIF, or WebP).';
      return;
    }
    if (file.size > 2 * 1024 * 1024) {
      error = 'Image must be under 2 MB.';
      return;
    }
    error = null;
    avatarFile = file;
    avatarPreview = URL.createObjectURL(file);
  }

  function clearAvatar() {
    avatarFile = null;
    if (avatarPreview && avatarPreview.startsWith('blob:')) URL.revokeObjectURL(avatarPreview);
    avatarPreview = null;
  }

  async function save() {
    if (!userId) return;
    saving = true;
    error = null;
    success = null;
    try {
      let avatarUrl = profile?.avatar_url ?? null;
      if (avatarFile) {
        avatarUrl = await uploadAvatar(userId, avatarFile);
      } else if (avatarPreview === null && profile?.avatar_url) {
        avatarUrl = null;
      }
      await updateProfile(userId, {
        display_name: displayName.trim() || null,
        avatar_url: avatarUrl,
      });
      profile = await getProfile(userId);
      displayName = profile?.display_name ?? '';
      avatarPreview = profile?.avatar_url ?? null;
      avatarFile = null;
      success = 'Settings saved.';
      window.dispatchEvent(new CustomEvent('profile-updated', { detail: profile }));
    } catch (e) {
      error = e?.message ?? 'Failed to save';
    } finally {
      saving = false;
    }
  }

  function cancel(e) {
    if (e) e.preventDefault();
    push('/');
  }
</script>

<div class="page">
  <header class="page-header">
    <h1>Settings</h1>
    <div class="header-actions">
      <button type="button" class="btn btn-secondary" onclick={cancel} disabled={saving}>Cancel</button>
      <button type="button" class="btn btn-primary" onclick={save} disabled={saving}>
        {saving ? 'Saving…' : 'Save'}
      </button>
    </div>
  </header>

  {#if $auth.loading || (userId && loading)}
    <p class="muted">Loading…</p>
  {:else if !userId}
    <p class="auth-required">Sign in to manage your settings.</p>
  {:else}
    <form class="settings-form" onsubmit={(e) => { e.preventDefault(); save(); }}>
      <div class="form-group">
        <label for="display-name">Username</label>
        <input
          id="display-name"
          type="text"
          class="input"
          bind:value={displayName}
          placeholder="Display name"
          maxlength="100"
        />
      </div>

      <div class="form-group">
        <span class="form-label">Avatar</span>
        <div class="avatar-row">
          <div class="avatar-wrap">
            <label for="avatar-input" class="avatar-clickable" title="Choose image">
              <div class="avatar-preview-wrap">
                {#if avatarPreview}
                  <img src={avatarPreview} alt="Avatar" class="avatar-preview" />
                {:else}
                  <div class="avatar-placeholder">
                    <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                      <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
                      <circle cx="12" cy="7" r="4" />
                    </svg>
                  </div>
                {/if}
              </div>
            </label>
            <input
              id="avatar-input"
              type="file"
              accept="image/jpeg,image/png,image/gif,image/webp"
              onchange={onAvatarChange}
              class="sr-only"
            />
            <div class="avatar-edge-actions">
              <button type="button" class="avatar-edge-btn" title="Remove" onclick={clearAvatar} disabled={!avatarPreview && !avatarFile}>
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <polyline points="3 6 5 6 21 6" />
                  <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
                  <line x1="10" y1="11" x2="10" y2="17" />
                  <line x1="14" y1="11" x2="14" y2="17" />
                </svg>
              </button>
            </div>
          </div>
        </div>
        <p class="form-hint">JPEG, PNG, GIF or WebP. Max 2 MB.</p>
      </div>

      {#if error}
        <p class="error">{error}</p>
      {/if}
      {#if success}
        <p class="success">{success}</p>
      {/if}
    </form>
  {/if}
</div>

<style>
  .page {
    padding: 1.5rem;
    max-width: 560px;
    margin: 0 auto;
  }

  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 1rem;
    margin-bottom: 1.5rem;
  }

  .page-header h1 {
    margin: 0;
    font-size: 1.5rem;
    font-weight: 600;
    color: var(--text-primary, #f0f0f0);
  }

  .header-actions {
    display: flex;
    gap: 0.5rem;
  }

  .auth-required,
  .muted {
    margin: 0;
    color: var(--text-muted, #a0a0a0);
  }

  .settings-form {
    display: flex;
    flex-direction: column;
    gap: 1.25rem;
  }

  .form-group label {
    display: block;
    font-size: 0.9rem;
    font-weight: 500;
    color: var(--text-muted, #a0a0a0);
    margin-bottom: 0.35rem;
  }

  .input {
    width: 100%;
    padding: 0.6rem 0.75rem;
    font-size: 0.95rem;
    border: 1px solid var(--border, #333);
    border-radius: 6px;
    background: var(--card-bg, #1e1e1e);
    color: var(--text-primary, #f0f0f0);
  }

  .avatar-row {
    display: flex;
    align-items: center;
  }

  .avatar-wrap {
    position: relative;
    flex-shrink: 0;
  }

  .avatar-clickable {
    display: block;
    cursor: pointer;
  }

  .avatar-preview-wrap {
    display: block;
  }

  .avatar-preview {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid var(--border, #333);
  }

  .avatar-placeholder {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: var(--card-bg, #1e1e1e);
    border: 2px solid var(--border, #333);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--text-muted, #a0a0a0);
  }

  .avatar-edge-actions {
    position: absolute;
    bottom: -2px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    gap: 4px;
    z-index: 1;
  }

  .avatar-edge-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    padding: 0;
    border: 1px solid var(--border, #333);
    border-radius: 50%;
    background: var(--card-bg, #1a1a1a);
    color: var(--text-muted, #a0a0a0);
    cursor: pointer;
    transition: color 0.2s, background 0.2s, border-color 0.2s;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
  }

  .avatar-edge-btn:hover:not(:disabled) {
    color: var(--text-primary, #f0f0f0);
    background: var(--hover-bg, #2a2a2a);
    border-color: var(--border-hover, #444);
  }

  .avatar-edge-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .avatar-edge-btn svg {
    display: block;
  }

  .form-hint {
    margin: 0.35rem 0 0 0;
    font-size: 0.85rem;
    color: var(--text-muted, #888);
  }

  .sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    border: 0;
  }

  .btn {
    padding: 0.5rem 1rem;
    font-size: 0.9rem;
    font-weight: 500;
    border: 1px solid var(--border, #333);
    border-radius: 6px;
    background: var(--card-bg, #1e1e1e);
    color: var(--text-primary, #f0f0f0);
    cursor: pointer;
  }

  .btn:hover:not(:disabled) {
    background: var(--hover-bg, #2a2a2a);
  }

  .btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  .btn-primary {
    background: var(--accent, #3b82f6);
    border-color: var(--accent, #3b82f6);
  }

  .btn-primary:hover:not(:disabled) {
    background: #2563eb;
  }

  .btn-secondary {
    background: transparent;
  }

  .form-group .form-label {
    display: block;
    font-size: 0.9rem;
    font-weight: 500;
    color: var(--text-muted, #a0a0a0);
    margin-bottom: 0.35rem;
  }

  .error {
    margin: 0;
    font-size: 0.9rem;
    color: #ef4444;
  }

  .success {
    margin: 0;
    font-size: 0.9rem;
    color: #22c55e;
  }
</style>
