File size: 12,515 Bytes
5383ef0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// settings.js — Settings modal
import { send, on } from './ws.js';
import { openModal, closeModal, openDeviceSessionModal } from './modals.js';
import { isAuthenticated, currentUser, userProfile, userSettings } from './auth.js';
import { deleteAllSessions } from './sessions.js';
import { escHtml, showNotification } from './ui.js';

export function applyTheme(theme) {
  document.documentElement.setAttribute('data-theme', theme === 'light' ? 'light' : 'dark');
}

export function openSettings(tab = 'chat') {
  openModal(buildSettingsHtml(tab), {
    wide: true,
    onOpen(b) {
      setupSettingsTabs(b);
      setupChatSettings(b);
      if (isAuthenticated()) {
        setupAccountSettings(b);
      }
      // Disable memory buttons (placeholder)
      b.querySelectorAll('[data-disabled]').forEach(btn => {
        btn.disabled = true;
        btn.title = 'Coming soon';
        btn.style.opacity = '0.45';
      });
    }
  });
}

function buildSettingsHtml(activeTab) {
  const authed = isAuthenticated();
  const settings = userSettings || { theme: 'dark', webSearch: true, imageGen: true, videoGen: true, audioGen: true };
  const u = currentUser;

  return `
  <div class="modal-header">
    <span class="modal-title">Settings</span>
    <button class="modal-close" id="settings-close">×</button>
  </div>
  <div class="settings-tabs">
    <button class="settings-tab ${activeTab==='chat'?'active':''}" data-tab="chat">Chat</button>
    ${authed ? `<button class="settings-tab ${activeTab==='account'?'active':''}" data-tab="account">Account</button>` : ''}
  </div>

  <!-- Chat Settings -->
  <div class="settings-pane ${activeTab==='chat'?'active':''}" data-pane="chat" style="padding:0 24px 20px;">
    <div class="setting-row">
      <div>
        <div class="setting-label">Theme</div>
        <div class="setting-desc">Light or dark interface</div>
      </div>
      <div style="display:flex;gap:8px;">
        <button class="btn-ghost${settings.theme==='light'?' active-theme':''}" data-theme-btn="light" style="font-size:13px;padding:5px 12px;">☀ Light</button>
        <button class="btn-ghost${settings.theme!=='light'?' active-theme':''}" data-theme-btn="dark" style="font-size:13px;padding:5px 12px;">🌙 Dark</button>
      </div>
    </div>

    <div style="margin-top:16px;margin-bottom:8px;font-size:12px;text-transform:uppercase;letter-spacing:0.05em;color:var(--text-muted);">Available Tools</div>
    ${buildToolToggle('webSearch',  'Web Search',     'Search the web for current information', settings.webSearch)}
    ${buildToolToggle('imageGen',   'Image Generation','Generate images from prompts', settings.imageGen)}
    ${buildToolToggle('videoGen',   'Video Generation','Generate videos from prompts', settings.videoGen)}
    ${buildToolToggle('audioGen',   'Audio / SFX',    'Generate music and sound effects', settings.audioGen)}
  </div>

  ${authed ? buildAccountPane(activeTab) : ''}

  <div class="modal-footer" style="border-top:1px solid var(--border);padding-top:12px;">
    <button class="btn-ghost" id="settings-cancel">Cancel</button>
    <button class="btn-primary" id="settings-apply">Apply</button>
  </div>
  `;
}

function buildToolToggle(key, label, desc, enabled) {
  return `
  <div class="setting-row">
    <div>
      <div class="setting-label">${escHtml(label)}</div>
      <div class="setting-desc">${escHtml(desc)}</div>
    </div>
    <label class="toggle-switch" data-toggle="${key}">
      <input type="checkbox" ${enabled ? 'checked' : ''} />
      <div class="toggle-track"></div>
      <div class="toggle-thumb"></div>
    </label>
  </div>`;
}

function buildAccountPane(activeTab) {
  const u = currentUser;
  const p = userProfile;
  const email = u?.email || '';
  const username = p?.username || '';

  return `
  <div class="settings-pane ${activeTab==='account'?'active':''}" data-pane="account" style="padding:0 24px 8px;">
    <!-- Username -->
    <div class="form-group" style="margin-top:4px;">
      <label class="form-label">Username</label>
      <div style="display:flex;gap:8px;">
        <input class="form-input" id="username-input" value="${escHtml(username)}" placeholder="Choose a username" style="flex:1;" />
        <button class="btn-ghost" id="username-save" style="font-size:13px;padding:6px 14px;white-space:nowrap;">Save</button>
      </div>
      <div id="username-msg" class="form-hint" style="display:none;"></div>
    </div>

    <!-- Plan info -->
    <div id="plan-section" style="padding:12px;border-radius:var(--radius-md);background:var(--bg-raised);border:1px solid var(--border);margin-bottom:16px;">
      <div style="font-size:12px;color:var(--text-muted);margin-bottom:4px;">Current Plan</div>
      <div id="plan-name-display" style="font-weight:600;font-size:15px;">Loading…</div>
      <button class="btn-ghost" id="billing-portal-btn" style="margin-top:8px;font-size:12px;padding:5px 12px;">Manage Billing ↗</button>
    </div>

    <!-- Data management -->
    <div style="margin-bottom:8px;font-size:12px;text-transform:uppercase;letter-spacing:0.05em;color:var(--text-muted);">Data</div>
    <div style="display:flex;flex-wrap:wrap;gap:8px;margin-bottom:16px;">
      <button class="btn-ghost" data-disabled style="font-size:13px;">Manage Memories</button>
      <button class="btn-ghost" data-disabled style="font-size:13px;">Delete All Memories</button>
      <button class="btn-danger" id="delete-sessions-btn" style="font-size:13px;">Delete All Chats</button>
    </div>

    <!-- Active sessions -->
    <div style="margin-bottom:8px;font-size:12px;text-transform:uppercase;letter-spacing:0.05em;color:var(--text-muted);">Devices &amp; Sessions</div>
    <div id="device-sessions-list" style="margin-bottom:10px;">
      <div style="font-size:13px;color:var(--text-muted);">Loading sessions…</div>
    </div>
    <button class="btn-danger" id="revoke-all-btn" style="font-size:13px;margin-bottom:16px;">Log Out All Other Devices</button>

    <!-- Delete account -->
    <div style="border-top:1px solid var(--border);padding-top:14px;">
      <button class="btn-danger" id="delete-account-btn" style="font-size:13px;">Delete Account</button>
    </div>
  </div>`;
}

function setupSettingsTabs(b) {
  b.querySelector('#settings-close')?.addEventListener('click', closeModal);
  b.querySelector('#settings-cancel')?.addEventListener('click', closeModal);

  b.querySelectorAll('.settings-tab').forEach(tab => {
    tab.addEventListener('click', () => {
      b.querySelectorAll('.settings-tab').forEach(t => t.classList.remove('active'));
      b.querySelectorAll('.settings-pane').forEach(p => p.classList.remove('active'));
      tab.classList.add('active');
      b.querySelector(`[data-pane="${tab.dataset.tab}"]`)?.classList.add('active');
    });
  });

  b.querySelector('#settings-apply')?.addEventListener('click', () => applySettings(b));
}

function setupChatSettings(b) {
  // Theme buttons
  b.querySelectorAll('[data-theme-btn]').forEach(btn => {
    btn.addEventListener('click', () => {
      b.querySelectorAll('[data-theme-btn]').forEach(t => t.classList.remove('active-theme'));
      btn.classList.add('active-theme');
      applyTheme(btn.dataset.themeBtn);
    });
  });
}

function setupAccountSettings(b) {
  // Username
  b.querySelector('#username-save')?.addEventListener('click', async () => {
    const val = b.querySelector('#username-input')?.value;
    const msgEl = b.querySelector('#username-msg');
    send({ type: 'account:setUsername', username: val });
    on('account:usernameResult', function handler(msg) {
      import('./ws.js').then(({ off }) => off('account:usernameResult', handler));
      msgEl.style.display = '';
      if (msg.success) {
        msgEl.textContent = `Username set to @${msg.username}`;
        msgEl.style.color = 'var(--plan-core)';
      } else {
        msgEl.textContent = msg.error || 'Failed';
        msgEl.style.color = '#f87171';
      }
    });
  });

  // Billing portal
  b.querySelector('#billing-portal-btn')?.addEventListener('click', () => {
    window.open('https://sharktide-lightning.hf.space/portal', '_blank');
  });

  // Delete all sessions
  b.querySelector('#delete-sessions-btn')?.addEventListener('click', () => {
    if (confirm('Delete all chats? This cannot be undone.')) {
      deleteAllSessions();
      closeModal();
    }
  });

  // Revoke all devices
  b.querySelector('#revoke-all-btn')?.addEventListener('click', () => {
    if (confirm('Log out all other devices?')) {
      send({ type: 'account:revokeAllOthers' });
      showNotification({ type: 'success', message: 'Other sessions logged out', duration: 2500 });
    }
  });

  // Delete account
  b.querySelector('#delete-account-btn')?.addEventListener('click', async () => {
    if (!confirm('Delete your account permanently? This cannot be undone.')) return;
    const auth = JSON.parse(localStorage.getItem('ipai_auth_v1') || '{}');
    if (!auth.access_token) return;
    const res = await fetch('https://dpixehhdbtzsbckfektd.supabase.co/functions/v1/delete_account', {
      method: 'POST', headers: { Authorization: `Bearer ${auth.access_token}` },
    });
    if (res.ok) {
      closeModal();
      import('./auth.js').then(a => a.logout());
    } else {
      const d = await res.json().catch(() => ({}));
      showNotification({ type: 'error', message: d.error || 'Delete failed', duration: 4000 });
    }
  });

  // Load subscription + device sessions
  send({ type: 'account:getSubscription' });
  send({ type: 'account:getSessions' });

  on('account:subscription', function handler(msg) {
    import('./ws.js').then(({ off }) => off('account:subscription', handler));
    const planEl = b.querySelector('#plan-name-display');
    if (planEl && msg.info) {
      const pKey = msg.info.planKey || 'free';
      const pName = msg.info.planName || 'Free Tier';
      planEl.innerHTML = `<span style="color:var(--plan-${pKey})">${escHtml(pName)}</span>`;
    }
  });

  on('account:deviceSessions', function handler(msg) {
    import('./ws.js').then(({ off }) => off('account:deviceSessions', handler));
    const listEl = b.querySelector('#device-sessions-list');
    if (!listEl) return;
    const sessions = msg.sessions || [];
    const currentToken = msg.currentToken;
    if (sessions.length === 0) { listEl.innerHTML = '<div style="font-size:13px;color:var(--text-muted);">No sessions found.</div>'; return; }

    listEl.innerHTML = sessions.map(s => `
      <div class="device-session-item" data-token="${escHtml(s.token)}">
        <div class="device-badge">💻</div>
        <div class="device-info">
          <div class="device-name">${escHtml(s.userAgent?.slice(0,50) || 'Unknown device')}</div>
          <div class="device-meta">${escHtml(s.ip || '—')} · Last seen ${escHtml(s.lastSeen ? new Date(s.lastSeen).toLocaleDateString() : '—')}</div>
          ${s.token === currentToken ? '<div class="device-current">Current session</div>' : ''}
        </div>
      </div>`).join('');

    listEl.querySelectorAll('.device-session-item').forEach(el => {
      el.addEventListener('click', () => {
        const token = el.dataset.token;
        const session = sessions.find(s => s.token === token);
        if (session) openDeviceSessionModal(session, token === currentToken);
      });
    });
  });
}

function applySettings(b) {
  const theme = b.querySelector('[data-theme-btn].active-theme')?.dataset.themeBtn
    || (document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark');

  const tools = {};
  b.querySelectorAll('[data-toggle]').forEach(label => {
    const key = label.dataset.toggle;
    const checked = label.querySelector('input[type="checkbox"]').checked;
    tools[key] = checked;
  });

  const newSettings = { theme, ...tools };
  applyTheme(theme);

  // Sync tool buttons in chat UI
  document.querySelectorAll('[data-tool]').forEach(btn => {
    const t = btn.dataset.tool;
    if (t in tools) {
      btn.classList.toggle('active', !!tools[t]);
      btn.style.display = '';
    }
  });

  if (isAuthenticated()) {
    send({ type: 'settings:save', settings: newSettings });
  }

  closeModal();
}

// Init theme on load from stored settings
on('auth:ok', (msg) => {
  if (msg.settings?.theme) applyTheme(msg.settings.theme);
});
on('auth:guestOk', () => {
  const stored = (() => {
    try { return JSON.parse(localStorage.getItem('ipai_settings') || '{}'); } catch { return {}; }
  })();
  applyTheme(stored.theme || 'dark');
});