File size: 11,686 Bytes
ea9ca44
 
 
 
fdd5c82
ea9ca44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdd5c82
ea9ca44
 
 
 
 
 
 
 
4b3a33f
ea9ca44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b3a33f
ea9ca44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b3a33f
ea9ca44
 
 
 
 
 
 
4b3a33f
ea9ca44
 
 
 
 
 
 
 
 
 
 
4b3a33f
ea9ca44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b3a33f
 
 
 
 
 
 
 
 
 
 
ea9ca44
 
 
 
 
4b3a33f
ea9ca44
 
 
 
 
 
 
 
fdd5c82
 
 
 
 
 
 
 
 
 
 
 
ea9ca44
 
 
 
 
 
 
 
 
 
 
fdd5c82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9ca44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState, useEffect } from 'react';
import { supabase } from '../supabaseClient';
import ApplicantLayout from '../components/ApplicantLayout'; // The Navigation Wrapper
import ProfilePage from '../components/ProfilePage'; // The UI Component
import { motion, AnimatePresence } from 'framer-motion';

export default function ApplicantProfile({ onNavigate }) {
    // --- 1. STATE VARIABLES ---
    const [formData, setFormData] = useState({});
    const [originalFormData, setOriginalFormData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [resumeFile, setResumeFile] = useState(null);
    const [avatarFile, setAvatarFile] = useState(null);
    const [avatarUrl, setAvatarUrl] = useState(null);
    const [photoPreviewUrl, setPhotoPreviewUrl] = useState(null);
    const [showFullProfile, setShowFullProfile] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [saveSuccess, setSaveSuccess] = useState(false);
    const [isExtracting, setIsExtracting] = useState(false);
    const [showRefreshNotification, setShowRefreshNotification] = useState(false);

    // --- 2. FETCH DATA ---
    useEffect(() => {
        const fetchInitialData = async () => {
            setLoading(true);
            try {
                // Get current user
                const { data: { user } } = await supabase.auth.getUser();

                if (user) {
                    // Fetch Profile using maybeSingle() to avoid errors if empty
                    const { data: profile, error } = await supabase
                        .from('profiles')
                        .select('*')
                        .eq('id', user.id)
                        .maybeSingle();

                    if (error) {
                        console.error("Error fetching profile:", error.message);
                    }

                    if (profile) {
                        // Profile exists - Load it
                        const combinedData = { ...profile, email: user.email };
                        setFormData(combinedData);
                        setOriginalFormData(combinedData);
                        if (profile.avatar_url) {
                            setAvatarUrl(profile.avatar_url);
                        }
                    } else {
                        // New user - Initialize with just email
                        setFormData({ email: user.email });
                    }
                }
            } catch (error) {
                console.error("Unexpected error:", error);
            } finally {
                // ✅ CRITICAL FIX: This ensures loading ALWAYS stops
                setLoading(false);
            }
        };
        fetchInitialData();
    }, []);

    // --- 3. HANDLERS ---
    const handleEditClick = () => {
        setFormData(currentData => {
            const hasExperience = currentData.work_experience && currentData.work_experience.length > 0;
            if (!hasExperience) {
                return {
                    ...currentData,
                    work_experience: [{ id: Date.now(), company: '', role: '', years: '' }]
                };
            }
            return currentData;
        });
        setShowFullProfile(true);
        setIsEditing(true);
    };

    const handleCancelClick = () => {
        if (originalFormData) setFormData(originalFormData);
        setAvatarFile(null);
        setResumeFile(null);
        setPhotoPreviewUrl(null);
        setIsEditing(false);
    };

    const handleProfileChange = (e) => {
        const { name, value, type, checked } = e.target;
        const newValue = type === 'checkbox' ? checked : value;
        setFormData(prev => ({ ...prev, [name]: newValue }));
    };

    const handleAddExperience = () => {
        const newExperience = { id: Date.now(), company: '', role: '', years: '' };
        setFormData(prev => ({
            ...prev,
            work_experience: [...(prev.work_experience || []), newExperience]
        }));
    };

    const handleExperienceChange = (index, e) => {
        const { name, value } = e.target;
        const updatedExperience = [...(formData.work_experience || [])];
        updatedExperience[index] = { ...updatedExperience[index], [name]: value };
        setFormData(prev => ({ ...prev, work_experience: updatedExperience }));
    };

    const handleResumeFileChange = (e) => {
        if (!isEditing || !e.target.files || e.target.files.length === 0) return;
        setResumeFile(e.target.files[0]);
    };

    const handleAvatarFileChange = (e) => {
        if (!isEditing || !e.target.files || e.target.files.length === 0) return;
        const file = e.target.files[0];
        setAvatarFile(file);
        setPhotoPreviewUrl(URL.createObjectURL(file));
    };

    const handleSaveProfile = async () => {
        setIsSaving(true);
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) return;

        try {
            const updates = { ...formData, id: user.id, updated_at: new Date() };
            delete updates.email; // Don't try to update email in profiles table

            if (avatarFile) {
                const filePath = `${user.id}/${Date.now()}_${avatarFile.name}`;
                await supabase.storage.from('avatars').upload(filePath, avatarFile, { upsert: true });
                const { data: urlData } = supabase.storage.from('avatars').getPublicUrl(filePath);
                updates.avatar_url = urlData.publicUrl;
            }

            if (resumeFile) {
                // Delete old resume if it exists to prevent duplication
                if (originalFormData?.resume_url) {
                    try {
                        const oldPath = originalFormData.resume_url;
                        const { error: removeError } = await supabase.storage.from('resume').remove([oldPath]);
                        if (removeError) console.warn("Could not delete old resume:", removeError.message);
                    } catch (e) {
                         console.warn("Exception during old resume removal:", e);
                    }
                }

                const filePath = `${user.id}/${Date.now()}_${resumeFile.name}`;
                // Make sure your bucket is named 'resumes' (plural) or 'resume' (singular) to match your Supabase Storage
                await supabase.storage.from('resume').upload(filePath, resumeFile, { upsert: true });
                updates.resume_url = filePath;
            }

            const { error } = await supabase.from('profiles').upsert(updates);
            if (error) throw error;

            setSaveSuccess(true);
            if (updates.avatar_url) setAvatarUrl(updates.avatar_url);
            setOriginalFormData(formData);
            setPhotoPreviewUrl(null);
            setIsEditing(false);

            // ✅ Show refresh notification 10 seconds after uploading a new resume
            if (resumeFile) {
                setTimeout(() => {
                    setShowRefreshNotification(true);
                    
                    // Auto-hide after 15 seconds
                    setTimeout(() => {
                        setShowRefreshNotification(false);
                    }, 15000);
                }, 10000); // 10 seconds delay
            }
        } catch (error) {
            alert(`Error saving profile: ${error.message}`);
        } finally {
            setIsSaving(false);
            setTimeout(() => setSaveSuccess(false), 3000);
        }
    };

    // --- 4. RENDER ---
    return (
        <ApplicantLayout activePage="applicant-profile" onNavigate={onNavigate}>
            <AnimatePresence>
                {showRefreshNotification && (
                    <motion.div
                        initial={{ opacity: 0, y: -50, x: '-50%' }}
                        animate={{ opacity: 1, y: 0, x: '-50%' }}
                        exit={{ opacity: 0, y: -50, x: '-50%' }}
                        style={{
                            position: 'fixed',
                            top: '30px',
                            left: '50%',
                            backgroundColor: '#10b981', // Emerald green
                            color: 'white',
                            padding: '1rem 1.5rem',
                            borderRadius: '0.75rem',
                            boxShadow: '0 10px 25px rgba(0,0,0,0.2)',
                            zIndex: 9999,
                            fontWeight: '500',
                            display: 'flex',
                            alignItems: 'center',
                            gap: '1rem',
                            border: '1px solid rgba(255,255,255,0.2)'
                        }}
                    >
                        <span>✨ We've analyzed your newly uploaded resume! Please refresh the page to view your auto-filled profile fields.</span>
                        <button 
                            onClick={() => window.location.reload()} 
                            style={{
                                background: 'white',
                                color: '#10b981',
                                border: 'none',
                                padding: '0.5rem 1rem',
                                borderRadius: '0.5rem',
                                cursor: 'pointer',
                                fontWeight: 'bold',
                                whiteSpace: 'nowrap',
                                transition: 'all 0.2s',
                                outline: 'none'
                            }}
                            onMouseEnter={(e) => e.target.style.transform = 'scale(1.05)'}
                            onMouseLeave={(e) => e.target.style.transform = 'scale(1)'}
                        >
                            Refresh Now
                        </button>
                        <button 
                            onClick={() => setShowRefreshNotification(false)}
                            style={{
                                background: 'transparent',
                                border: 'none',
                                color: 'white',
                                fontSize: '1.2rem',
                                cursor: 'pointer',
                                padding: '0',
                                marginLeft: '0.5rem'
                            }}
                        >
                            ×
                        </button>
                    </motion.div>
                )}
            </AnimatePresence>
            <ProfilePage
                profileData={formData}
                loading={loading}
                avatarUrl={avatarUrl}
                photoPreviewUrl={photoPreviewUrl}
                resumeFile={resumeFile}
                isSaving={isSaving}
                saveSuccess={saveSuccess}
                isEditing={isEditing}
                isExtracting={isExtracting}
                showFullProfile={showFullProfile}
                setShowFullProfile={setShowFullProfile}
                // Pass Handlers
                handleEditClick={handleEditClick}
                handleCancelClick={handleCancelClick}
                handleProfileChange={handleProfileChange}
                handleExperienceChange={handleExperienceChange}
                handleAddExperience={handleAddExperience}
                handleSaveProfile={handleSaveProfile}
                handleFileChange={handleResumeFileChange}
                handlePhotoChange={handleAvatarFileChange}
            />
        </ApplicantLayout>
    );
}