File size: 11,642 Bytes
d70361b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Login / create-account page. Two sign-in modes:
//   * "password" — email + password → session cookie
//   * "otp"      — mobile number → SMS OTP → session cookie
// Reuses ddaApi(), showDdaError(), showDdaSuccess() from shared.js.
(function () {
  let mode = 'login';        // 'login' | 'register'
  let loginMethod = 'password'; // 'password' | 'otp'
  let pendingOtp = null;

  const form = document.getElementById('auth-form');
  const otpForm = document.getElementById('otp-form');
  const title = document.getElementById('auth-title');
  const submitBtn = document.getElementById('auth-submit');
  const tabsEl = document.getElementById('auth-tabs');
  const toggleToRegister = document.getElementById('toggle-to-register');
  const toggleToLogin = document.getElementById('toggle-to-login');
  const countrySelect = document.getElementById('country_code');
  const phoneInput = document.getElementById('phone');

  const fields = {
    full_name: document.getElementById('full_name'),
    email: document.getElementById('email'),
    password: document.getElementById('password'),
    confirm_password: document.getElementById('confirm_password'),
    phone: phoneInput,
  };

  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  if (typeof window.populateCountrySelect === 'function') {
    window.populateCountrySelect(countrySelect, '+91');
  }

  function setFieldError(name, message) {
    const el = document.getElementById('err-' + name);
    const input = fields[name];
    if (message) {
      if (el) { el.textContent = message; el.classList.remove('hidden'); }
      if (input) input.classList.add('invalid');
    } else {
      if (el) { el.textContent = ''; el.classList.add('hidden'); }
      if (input) input.classList.remove('invalid');
    }
  }

  function clearFieldErrors() {
    Object.keys(fields).forEach((name) => setFieldError(name, null));
  }

  function digitsOnly(value) {
    return String(value || '').replace(/\D/g, '');
  }

  // Client-side validity check for the local part of the mobile number.
  // The full E.164 validation still happens on the server.
  function isPhoneValid(dial, local) {
    const digits = digitsOnly(local);
    if (dial === '+91') return digits.length === 10 && /^[6-9]/.test(digits);
    return digits.length >= 6 && digits.length <= 15;
  }

  function showFields() {
    const showByField = (name, on) => {
      document.querySelectorAll(`[data-field="${name}"]`).forEach((el) => {
        el.classList.toggle('hidden', !on);
      });
    };
    const isRegister = mode === 'register';
    const isLogin = mode === 'login';
    const passwordMode = isLogin && loginMethod === 'password';
    const otpMode = isLogin && loginMethod === 'otp';

    showByField('full_name', isRegister);
    showByField('email', true);
    showByField('password', isRegister || passwordMode);
    showByField('confirm_password', isRegister);
    showByField('phone', isRegister);
    showByField('remember', isLogin);
    showByField('forgot', passwordMode);
    document.getElementById('hint-password').classList.toggle('hidden', !isRegister);

    fields.email.required = true;
    fields.password.required = isRegister || passwordMode;
    fields.full_name.required = isRegister;
    fields.confirm_password.required = isRegister;
    fields.phone.required = false;

    tabsEl.classList.toggle('hidden', isRegister);

    if (isRegister) {
      title.textContent = 'Create account';
      submitBtn.textContent = 'Create account';
    } else if (otpMode) {
      title.textContent = 'Sign in with OTP';
      submitBtn.textContent = 'Send OTP to email';
    } else {
      title.textContent = 'Sign in';
      submitBtn.textContent = 'Sign in';
    }
  }

  function setMode(next) {
    mode = next;
    const isRegister = mode === 'register';
    toggleToRegister.classList.toggle('hidden', isRegister);
    toggleToLogin.classList.toggle('hidden', !isRegister);
    fields.password.autocomplete = isRegister ? 'new-password' : 'current-password';
    hideDdaError();
    clearFieldErrors();
    showFields();
  }

  function setLoginMethod(next) {
    loginMethod = next;
    tabsEl.querySelectorAll('.dda-auth-tab').forEach((btn) => {
      const active = btn.dataset.tab === next;
      btn.classList.toggle('is-active', active);
      btn.setAttribute('aria-selected', active ? 'true' : 'false');
    });
    hideDdaError();
    clearFieldErrors();
    showFields();
  }

  tabsEl?.querySelectorAll('.dda-auth-tab').forEach((btn) => {
    btn.addEventListener('click', () => setLoginMethod(btn.dataset.tab));
  });

  function showOtpStep(on, masked) {
    form.classList.toggle('hidden', on);
    otpForm.classList.toggle('hidden', !on);
    tabsEl.classList.toggle('hidden', on);
    document.querySelector('.auth-toggle')?.classList.toggle('hidden', on);
    if (on) {
      title.textContent = 'Enter email code';
      const help = document.getElementById('otp-help');
      if (help) {
        help.textContent = masked
          ? `We sent a 6-digit code to ${masked}. It expires in 10 minutes.`
          : 'Enter the 6-digit code sent to your email.';
      }
      document.getElementById('otp_code').value = '';
      document.getElementById('otp_code').focus();
    } else {
      pendingOtp = null;
      showFields();
    }
    hideDdaError();
  }

  otpForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    hideDdaError();
    const code = digitsOnly(document.getElementById('otp_code')?.value);
    if (!/^\d{6}$/.test(code)) {
      showDdaError('Enter the 6-digit code from your email.');
      return;
    }
    const btn = document.getElementById('otp-submit');
    if (btn) btn.disabled = true;
    try {
      await ddaApi('POST', '/api/auth/login/verify-otp', {
        body: JSON.stringify({ otpToken: pendingOtp?.token, code }),
      });
      window.location.href = '/';
    } catch (err) {
      showDdaError(err.message || 'Invalid sign-in code.');
    } finally {
      if (btn) btn.disabled = false;
    }
  });

  document.getElementById('otp-resend')?.addEventListener('click', async () => {
    hideDdaError();
    const btn = document.getElementById('otp-resend');
    if (btn) btn.disabled = true;
    try {
      const data = await ddaApi('POST', '/api/auth/login/resend-otp', {
        body: JSON.stringify({ otpToken: pendingOtp?.token }),
      });
      if (data?.otpToken) pendingOtp = { ...pendingOtp, token: data.otpToken };
      showDdaSuccess('A new code was sent to your email.');
      showOtpStep(true, data?.emailMasked || pendingOtp?.emailMasked);
    } catch (err) {
      showDdaError(err.message || 'Could not resend the code.');
    } finally {
      if (btn) btn.disabled = false;
    }
  });

  document.getElementById('otp-back')?.addEventListener('click', () => showOtpStep(false));

  document.getElementById('show-register').addEventListener('click', () => setMode('register'));
  document.getElementById('show-login').addEventListener('click', () => setMode('login'));

  function validate() {
    clearFieldErrors();
    let ok = true;
    const isRegister = mode === 'register';
    const passwordMode = !isRegister && loginMethod === 'password';
    const otpMode = !isRegister && loginMethod === 'otp';

    if (isRegister && !fields.full_name.value.trim()) {
      setFieldError('full_name', 'Full name is required.');
      ok = false;
    }

    const email = fields.email.value.trim();
    if (!email) {
      setFieldError('email', 'Email is required.');
      ok = false;
    } else if (!EMAIL_RE.test(email)) {
      setFieldError('email', 'Enter a valid email address.');
      ok = false;
    }

    if (isRegister || passwordMode) {
      const password = fields.password.value;
      if (!password) {
        setFieldError('password', 'Password is required.');
        ok = false;
      } else if (isRegister && password.length < 8) {
        setFieldError('password', 'Password must be at least 8 characters.');
        ok = false;
      }
      if (isRegister) {
        const confirm = fields.confirm_password.value;
        if (!confirm) {
          setFieldError('confirm_password', 'Please confirm your password.');
          ok = false;
        } else if (confirm !== password) {
          setFieldError('confirm_password', 'Passwords do not match.');
          ok = false;
        }
      }
    }

    if (isRegister) {
      const local = digitsOnly(fields.phone.value);
      if (local) {
        const dial = countrySelect.value || '+91';
        if (!isPhoneValid(dial, local)) {
          setFieldError('phone', dial === '+91'
            ? 'Enter a valid 10-digit Indian mobile number.'
            : 'Enter a valid mobile number.');
          ok = false;
        }
      }
    }

    return ok;
  }

  fields.confirm_password.addEventListener('input', () => {
    if (mode !== 'register') return;
    const confirm = fields.confirm_password.value;
    if (!confirm) return;
    setFieldError('confirm_password', confirm === fields.password.value ? null : 'Passwords do not match.');
  });

  phoneInput.addEventListener('input', () => {
    phoneInput.value = digitsOnly(phoneInput.value);
  });

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    hideDdaError();
    document.getElementById('dda-success')?.classList.add('hidden');
    if (!validate()) return;

    submitBtn.disabled = true;
    try {
      if (mode === 'register') {
        await ddaApi('POST', '/api/auth/register', {
          body: JSON.stringify({
            email: fields.email.value.trim(),
            password: fields.password.value,
            full_name: fields.full_name.value.trim(),
            phone: digitsOnly(fields.phone.value),
            country_code: countrySelect.value || '+91',
          }),
        });
        window.location.href = '/login?registered=1';
        return;
      }

      const remember_me = document.getElementById('remember_me').checked;

      if (loginMethod === 'password') {
        await ddaApi('POST', '/api/auth/login', {
          body: JSON.stringify({
            email: fields.email.value.trim(),
            password: fields.password.value,
            remember_me,
          }),
        });
        window.location.href = '/';
        return;
      }

      const data = await ddaApi('POST', '/api/auth/login/request-otp', {
        body: JSON.stringify({
          email: fields.email.value.trim(),
          remember_me,
        }),
      });
      pendingOtp = {
        token: data.otpToken,
        emailMasked: data.emailMasked,
      };
      showOtpStep(true, data.emailMasked);
    } catch (err) {
      const msg = err.message || 'Sign-in failed.';
      if (/already registered/i.test(msg) && /mobile/i.test(msg)) {
        setFieldError('phone', 'This mobile number is already registered.');
      } else if (/already registered/i.test(msg)) {
        setFieldError('email', 'This email is already registered.');
      } else if (/no account/i.test(msg) || /unknown email/i.test(msg)) {
        setFieldError('email', 'No account is registered with this email.');
        showDdaError('No account is registered with this email. Try Password sign-in or create an account.');
      } else if (/mobile number/i.test(msg)) {
        setFieldError('phone', msg);
      } else {
        showDdaError(msg);
      }
    } finally {
      submitBtn.disabled = false;
    }
  });

  showFields();

  if (new URLSearchParams(window.location.search).get('registered') === '1') {
    showDdaSuccess('Account created. Please sign in.');
    window.history.replaceState({}, '', '/login');
  }
})();