File size: 5,647 Bytes
c024705
 
 
 
 
 
 
 
 
 
9d7601a
c024705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
(() => {
    'use strict';

    // Get API URL from configuration
    const getAPIBaseUrl = () => {
        if (window.AIMHSA && window.AIMHSA.Config) {
            return window.AIMHSA.Config.getApiBaseUrl();
        }
        
        // Fallback to auto-detection
        return `https://${window.location.hostname}`;
    };
    
    const API_BASE_URL = getAPIBaseUrl();

    // Elements
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');
    const authForm = document.getElementById('authForm');
    const signInBtn = document.getElementById('signInBtn');
    const registerBtn = document.getElementById('registerBtn');
    const anonBtn = document.getElementById('anonBtn');
    
    // Tab switching
    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const targetTab = btn.dataset.tab;
            
            // Update active tab
            tabBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            
            // Show target content
            tabContents.forEach(content => {
                if (content.id === targetTab) {
                    content.classList.remove('hidden');
                } else {
                    content.classList.add('hidden');
                }
            });
        });
    });
    
    // API helper
    async function api(path, opts) {
        const url = API_BASE_URL + path;
        const res = await fetch(url, opts);
        if (!res.ok) {
            const txt = await res.text();
            throw new Error(txt || res.statusText);
        }
        return res.json();
    }
    
    // Show message
    function showMessage(text, type = 'error') {
        const existing = document.querySelector('.error-message, .success-message');
        if (existing) existing.remove();
        
        const message = document.createElement('div');
        message.className = type === 'error' ? 'error-message' : 'success-message';
        message.textContent = text;
        
        authForm.insertBefore(message, authForm.firstChild);
        
        setTimeout(() => message.remove(), 5000);
    }
    
    // Redirect to main app
    function redirectToApp(account = null) {
        if (account) {
            localStorage.setItem('aimhsa_account', account);
        }
        window.location.href = 'index.html';
    }
    
    // Form submission
    authForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const activeTab = document.querySelector('.tab-content:not(.hidden)').id;
        
        if (activeTab === 'signin') {
            const username = document.getElementById('loginUsername').value.trim();
            const password = document.getElementById('loginPassword').value;
            
            if (!username || !password) {
                showMessage('Please enter both username and password');
                return;
            }
            
            signInBtn.disabled = true;
            signInBtn.textContent = 'Signing in...';
            
            try {
                const res = await api('/api/login', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, password })
                });
                
                showMessage('Successfully signed in!', 'success');
                setTimeout(() => redirectToApp(res.account || username), 1000);
            } catch (err) {
                showMessage('Invalid username or password');
            } finally {
                signInBtn.disabled = false;
                signInBtn.textContent = 'Sign In';
            }
        } else {
            const username = document.getElementById('regUsername').value.trim();
            const password = document.getElementById('regPassword').value;
            const confirmPassword = document.getElementById('regConfirmPassword').value;
            
            if (!username || !password || !confirmPassword) {
                showMessage('Please fill in all fields');
                return;
            }
            
            if (password !== confirmPassword) {
                showMessage('Passwords do not match');
                return;
            }
            
            if (password.length < 6) {
                showMessage('Password must be at least 6 characters');
                return;
            }
            
            registerBtn.disabled = true;
            registerBtn.textContent = 'Creating account...';
            
            try {
                await api('/api/register', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, password })
                });
                
                showMessage('Account created successfully!', 'success');
                setTimeout(() => redirectToApp(username), 1000);
            } catch (err) {
                showMessage('Username already exists or registration failed');
            } finally {
                registerBtn.disabled = false;
                registerBtn.textContent = 'Create Account';
            }
        }
    });
    
    // Anonymous access
    anonBtn.addEventListener('click', () => {
        localStorage.removeItem('aimhsa_account');
        redirectToApp();
    });
    
    // Check if already logged in
    const account = localStorage.getItem('aimhsa_account');
    if (account) {
        redirectToApp(account);
    }
})();