<script lang="ts">
  import { onMount } from 'svelte';

  interface App {
    id: string;
    name: string;
    icon: string;
    route_prefix: string;
    connected: boolean;
  }

  let user = $state<{ username: string; display_name: string } | null>(null);
  let apps = $state<App[]>([]);
  let loading = $state(true);
  let darkMode = $state(false);

  // Fitness goals
  let goalCal = $state('');
  let goalProtein = $state('');
  let goalCarbs = $state('');
  let goalFat = $state('');
  let goalsLoaded = $state(false);
  let editingGoals = $state(false);
  let savingGoals = $state(false);

  // Connect form state
  let showConnectForm = $state('');
  let connectToken = $state('');
  let connectUser = $state('');
  let connectPass = $state('');
  let connectError = $state('');
  let connectingService = $state('');

  const iconMap: Record<string, string> = {
    'map': '🗺️', 'bar-chart': '📊', 'package': '📦', 'book': '📚',
    'music': '🎵', 'rss': '📰', 'wallet': '💰',
  };

  onMount(async () => {
    // Check theme
    darkMode = document.documentElement.classList.contains('dark');

    try {
      const [meRes, appsRes] = await Promise.all([
        fetch('/api/auth/me', { credentials: 'include' }),
        fetch('/api/apps', { credentials: 'include' }),
      ]);
      if (meRes.ok) {
        const data = await meRes.json();
        if (data.authenticated) user = data.user;
      }
      if (appsRes.ok) {
        const data = await appsRes.json();
        apps = data.apps || [];
      }
    } catch { /* silent */ }
    loading = false;

    // Load fitness goals
    try {
      const n = new Date();
      const today = `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`;
      const gRes = await fetch(`/api/fitness/goals/for-date?date=${today}`, { credentials: 'include' });
      if (gRes.ok) {
        const g = await gRes.json();
        goalCal = String(Math.round(g.calories || 2000));
        goalProtein = String(Math.round(g.protein || 150));
        goalCarbs = String(Math.round(g.carbs || 200));
        goalFat = String(Math.round(g.fat || 65));
        goalsLoaded = true;
      }
    } catch { /* silent */ }
  });

  async function connectService(serviceId: string) {
    connectError = '';
    connectingService = serviceId;

    let token = '';
    if (serviceId === 'fitness' && connectUser && connectPass) {
      try {
        const res = await fetch(`/api/${serviceId}/auth/login`, {
          method: 'POST', credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ username: connectUser, password: connectPass }),
        });
        const data = await res.json();
        if (data.token) { token = data.token; }
        else { connectError = data.error || 'Login failed'; connectingService = ''; return; }
      } catch { connectError = 'Connection failed'; connectingService = ''; return; }
    } else {
      token = connectToken;
    }

    if (!token) { connectError = 'Token required'; connectingService = ''; return; }

    try {
      const res = await fetch('/api/me/connections', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ service: serviceId, token, auth_type: 'bearer' }),
      });
      const data = await res.json();
      if (data.success) {
        apps = apps.map(a => a.id === serviceId ? { ...a, connected: true } : a);
        showConnectForm = ''; connectToken = ''; connectUser = ''; connectPass = '';
      } else { connectError = data.error || 'Failed to connect'; }
    } catch { connectError = 'Connection failed'; }
    connectingService = '';
  }

  async function disconnectService(serviceId: string) {
    const appName = apps.find(a => a.id === serviceId)?.name || serviceId;
    if (!confirm(`Disconnect ${appName}? You will need to reconnect it to use this service again.`)) return;
    await fetch('/api/me/connections', {
      method: 'POST', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ service: serviceId, action: 'disconnect' }),
    });
    apps = apps.map(a => a.id === serviceId ? { ...a, connected: false } : a);
  }

  function toggleTheme() {
    darkMode = !darkMode;
    document.documentElement.classList.toggle('dark', darkMode);
  }

  async function saveGoals() {
    savingGoals = true;
    try {
      const n = new Date();
      const today = `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`;
      const res = await fetch('/api/fitness/goals', {
        method: 'PUT', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          calories: parseFloat(goalCal) || 2000,
          protein: parseFloat(goalProtein) || 150,
          carbs: parseFloat(goalCarbs) || 200,
          fat: parseFloat(goalFat) || 65,
          start_date: today,
        }),
      });
      if (res.ok) editingGoals = false;
    } catch { /* silent */ }
    savingGoals = false;
  }

  async function logout() {
    await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
    window.location.href = '/login';
  }
</script>

<div class="page">
  <div class="app-surface">
    <div class="page-header">
      <div class="page-title">SETTINGS</div>
      <div class="page-subtitle">Preferences</div>
    </div>

    {#if loading}
      <div class="loading-state">Loading...</div>
    {:else}
      <!-- Account -->
      <section class="settings-section">
        <div class="section-title">Account</div>
        <div class="settings-card">
          <div class="setting-row">
            <div class="setting-label">Username</div>
            <div class="setting-value">{user?.username || '—'}</div>
          </div>
          <div class="setting-row">
            <div class="setting-label">Display Name</div>
            <div class="setting-value">{user?.display_name || '—'}</div>
          </div>
          <div class="setting-row">
            <div></div>
            <button class="btn-danger" onclick={logout}>Sign Out</button>
          </div>
        </div>
      </section>

      <!-- Appearance -->
      <section class="settings-section">
        <div class="section-title">Appearance</div>
        <div class="settings-card">
          <div class="setting-row">
            <div>
              <div class="setting-label">Theme</div>
              <div class="setting-hint">Switch between light and dark mode</div>
            </div>
            <button class="theme-toggle" class:dark={darkMode} onclick={toggleTheme} aria-label="Toggle theme">
              <div class="toggle-track">
                <div class="toggle-thumb">
                  {#if darkMode}
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
                  {:else}
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
                  {/if}
                </div>
              </div>
            </button>
          </div>
        </div>
      </section>

      <!-- Fitness Goals -->
      <section class="settings-section">
        <div class="section-title">Fitness Goals</div>
        <div class="settings-card">
          {#if editingGoals}
            <div class="setting-row">
              <div class="goal-edit-grid">
                <div class="goal-edit-field">
                  <label class="goal-edit-label">Calories</label>
                  <input class="goal-edit-input" type="number" bind:value={goalCal} />
                </div>
                <div class="goal-edit-field">
                  <label class="goal-edit-label">Protein (g)</label>
                  <input class="goal-edit-input" type="number" bind:value={goalProtein} />
                </div>
                <div class="goal-edit-field">
                  <label class="goal-edit-label">Carbs (g)</label>
                  <input class="goal-edit-input" type="number" bind:value={goalCarbs} />
                </div>
                <div class="goal-edit-field">
                  <label class="goal-edit-label">Fat (g)</label>
                  <input class="goal-edit-input" type="number" bind:value={goalFat} />
                </div>
              </div>
            </div>
            <div class="setting-row">
              <div></div>
              <div class="goal-actions">
                <button class="btn-text" onclick={() => editingGoals = false}>Cancel</button>
                <button class="btn-save-goals" onclick={saveGoals} disabled={savingGoals}>{savingGoals ? 'Saving...' : 'Save'}</button>
              </div>
            </div>
          {:else}
            <div class="setting-row">
              <div class="setting-label">Calories</div>
              <div class="setting-value">{goalsLoaded ? goalCal : '...'} kcal</div>
            </div>
            <div class="setting-row">
              <div class="setting-label">Protein</div>
              <div class="setting-value">{goalsLoaded ? goalProtein : '...'}g</div>
            </div>
            <div class="setting-row">
              <div class="setting-label">Carbs</div>
              <div class="setting-value">{goalsLoaded ? goalCarbs : '...'}g</div>
            </div>
            <div class="setting-row">
              <div class="setting-label">Fat</div>
              <div class="setting-value">{goalsLoaded ? goalFat : '...'}g</div>
            </div>
            <div class="setting-row">
              <div></div>
              <button class="btn-edit-goals" onclick={() => editingGoals = true}>Edit Goals</button>
            </div>
          {/if}
        </div>
      </section>

      <!-- Service Connections -->
      <section class="settings-section">
        <div class="section-title">Service Connections</div>
        <div class="settings-card">
          {#each apps as app}
            <div class="setting-row">
              <div class="service-info">
                <span class="service-icon">{iconMap[app.icon] || '📱'}</span>
                <div>
                  <div class="setting-label">{app.name}</div>
                  <div class="setting-hint">{app.route_prefix}</div>
                </div>
              </div>
              {#if app.connected}
                <div class="service-actions">
                  <span class="conn-badge connected">Connected</span>
                  <button class="btn-text-danger" onclick={() => disconnectService(app.id)}>Disconnect</button>
                </div>
              {:else}
                <button class="btn-connect" onclick={() => { showConnectForm = app.id; connectError = ''; }}>Connect</button>
              {/if}
            </div>

            {#if showConnectForm === app.id && !app.connected}
              <div class="connect-form">
                {#if connectError}
                  <div class="connect-error">{connectError}</div>
                {/if}

                {#if app.id === 'fitness'}
                  <input type="text" class="connect-input" placeholder="Fitness username" bind:value={connectUser} />
                  <input type="password" class="connect-input" placeholder="Fitness password" bind:value={connectPass} />
                {:else}
                  <input type="password" class="connect-input" placeholder="API Token" bind:value={connectToken} />
                {/if}

                <div class="connect-actions">
                  <button class="btn-connect" onclick={() => connectService(app.id)} disabled={connectingService === app.id}>
                    {connectingService === app.id ? 'Connecting...' : 'Connect'}
                  </button>
                  <button class="btn-cancel" onclick={() => showConnectForm = ''}>Cancel</button>
                </div>
              </div>
            {/if}
          {/each}

          {#if apps.length === 0}
            <div class="empty-state">No services configured</div>
          {/if}
        </div>
      </section>
    {/if}
  </div>
</div>

<style>
  .page-subtitle {
    font-size: var(--text-2xl);
    font-weight: 300;
    color: var(--text-1);
    line-height: 1.2;
  }

  .loading-state { padding: var(--sp-12); text-align: center; color: var(--text-3); }
  .settings-section { margin-bottom: var(--section-gap); }
  .section-title {
    font-size: var(--text-sm); font-weight: 600; color: var(--text-3);
    text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: var(--sp-3);
  }

  .settings-card {
    background: var(--card); border-radius: var(--radius);
    border: 1px solid var(--border); box-shadow: var(--shadow-sm); overflow: hidden;
  }

  .setting-row {
    display: flex; align-items: center; justify-content: space-between;
    padding: var(--sp-4) var(--sp-5); border-bottom: 1px solid var(--border);
  }
  .setting-row:last-child { border-bottom: none; }

  .setting-label { font-size: var(--text-base); font-weight: 500; color: var(--text-1); }
  .setting-value { font-size: var(--text-base); color: var(--text-2); }
  .setting-hint { font-size: var(--text-sm); color: var(--text-3); margin-top: var(--sp-0.5); }

  .service-info { display: flex; align-items: center; gap: var(--sp-3); }
  .service-icon { font-size: var(--text-xl); }
  .service-actions { display: flex; align-items: center; gap: var(--sp-2); }

  .conn-badge {
    font-size: var(--text-sm); font-weight: 600; padding: 3px var(--sp-3);
    border-radius: 10px; line-height: 1.5;
  }
  .conn-badge.connected { background: var(--success-bg); color: var(--success); }

  .btn-connect {
    padding: var(--sp-1.5) var(--sp-4); border-radius: var(--radius-md);
    background: var(--accent); color: white; border: none;
    font-size: var(--text-sm); font-weight: 600; cursor: pointer; font-family: var(--font);
    transition: opacity var(--transition);
  }
  .btn-connect:hover { opacity: 0.9; }
  .btn-connect:disabled { opacity: 0.5; }

  .btn-cancel {
    padding: var(--sp-1.5) var(--sp-4); border-radius: var(--radius-md);
    background: var(--card-secondary); color: var(--text-2); border: 1px solid var(--border);
    font-size: var(--text-sm); font-weight: 500; cursor: pointer; font-family: var(--font);
  }

  .btn-text-danger {
    background: none; border: none; color: var(--error); font-size: var(--text-sm);
    font-weight: 500; cursor: pointer; font-family: var(--font);
    transition: opacity var(--transition);
  }
  .btn-text-danger:hover { opacity: 0.7; }

  .btn-danger {
    padding: var(--sp-2) var(--sp-4); border-radius: var(--radius-md);
    background: none; border: 1px solid var(--error); color: var(--error);
    font-size: var(--text-sm); font-weight: 500; cursor: pointer; font-family: var(--font);
    transition: all var(--transition);
  }
  .btn-danger:hover { background: var(--error-dim); }

  .connect-form {
    padding: var(--sp-3) var(--sp-5) var(--sp-4);
    border-bottom: 1px solid var(--border);
    display: flex; flex-direction: column; gap: var(--sp-2);
  }
  .connect-input {
    width: 100%; padding: var(--sp-2) var(--sp-3); border-radius: var(--radius-md);
    border: 1px solid var(--border); background: var(--surface-secondary);
    color: var(--text-1); font-size: var(--text-sm); font-family: var(--font);
  }
  .connect-input:focus { outline: none; border-color: var(--accent); }
  .connect-input::placeholder { color: var(--text-4); }
  .connect-actions { display: flex; gap: var(--sp-2); }
  .connect-error {
    font-size: var(--text-sm); color: var(--error); background: var(--error-dim);
    padding: var(--sp-2) var(--sp-3); border-radius: var(--radius-sm);
  }

  .empty-state { padding: var(--sp-8); text-align: center; color: var(--text-3); font-size: var(--text-sm); }

  /* Theme Toggle */
  .theme-toggle { background: none; border: none; padding: 0; cursor: pointer; }
  .toggle-track {
    width: 48px; height: 28px; border-radius: 14px;
    background: var(--border-strong); position: relative; transition: background var(--transition);
  }
  .theme-toggle.dark .toggle-track { background: var(--accent); }
  .toggle-thumb {
    width: 22px; height: 22px; border-radius: 50%; background: white;
    position: absolute; top: 3px; left: 3px;
    transition: transform var(--transition);
    display: flex; align-items: center; justify-content: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.15);
  }
  .theme-toggle.dark .toggle-thumb { transform: translateX(20px); }
  .toggle-thumb svg { width: 14px; height: 14px; color: var(--text-3); }
  .theme-toggle.dark .toggle-thumb svg { color: var(--accent); }

  .goal-edit-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-3); width: 100%; }
  .goal-edit-field { display: flex; flex-direction: column; gap: var(--sp-1); }
  .goal-edit-label { font-size: var(--text-sm); color: var(--text-3); }
  .goal-edit-input { padding: var(--sp-2) var(--sp-3); border-radius: var(--radius-md); border: 1px solid var(--border); background: var(--surface-secondary); color: var(--text-1); font-size: var(--text-md); font-family: var(--mono); }
  .goal-edit-input:focus { outline: none; border-color: var(--accent); }
  .goal-actions { display: flex; gap: var(--sp-2); }
  .btn-text { background: none; border: none; color: var(--text-3); font-size: var(--text-sm); cursor: pointer; font-family: var(--font); }
  .btn-text:hover { color: var(--text-1); }
  .btn-save-goals { padding: var(--sp-2) var(--sp-4); border-radius: var(--radius-md); background: var(--accent); color: white; border: none; font-size: var(--text-sm); font-weight: 600; cursor: pointer; font-family: var(--font); }
  .btn-save-goals:disabled { opacity: 0.5; }
  .btn-edit-goals { padding: var(--sp-2) var(--sp-4); border-radius: var(--radius-md); background: var(--accent); color: white; border: none; font-size: var(--text-sm); font-weight: 600; cursor: pointer; font-family: var(--font); }

  @media (max-width: 768px) {
    .page-subtitle { font-size: var(--text-xl); }
    .setting-row { flex-wrap: wrap; gap: var(--sp-2); }
  }
</style>
