// Helper to initialize missing student fields function initializeStudentFields(student) { if (student.password === undefined) student.password = 'aluno123'; if (student.email === undefined) student.email = ''; if (student.whatsapp === undefined) student.whatsapp = ''; if (student.address === undefined) student.address = ''; if (student.age === undefined) student.age = 18; if (student.faceEmbedding === undefined) student.faceEmbedding = null; if (student.guardian === undefined) student.guardian = ''; if (student.objective === undefined) student.objective = ''; if (student.weeklyGoal === undefined) student.weeklyGoal = 3; if (student.profession === undefined) student.profession = ''; if (student.schoolName === undefined) student.schoolName = ''; if (student.hasLoan === undefined) student.hasLoan = false; if (student.kimonoBrand === undefined) student.kimonoBrand = ''; if (student.kimonoSize === undefined) student.kimonoSize = ''; if (student.kimonoDate === undefined) student.kimonoDate = ''; if (student.evaluationParents === undefined) student.evaluationParents = 'Pendente'; if (student.evaluationSchool === undefined) student.evaluationSchool = 'Pendente'; } const ADULT_BELTS = ['Branca', 'Azul', 'Roxa', 'Marrom', 'Preta']; const KIDS_BELTS = [ 'Branca', 'Cinza e Branca', 'Cinza', 'Cinza e Preta', 'Amarela e Branca', 'Amarela', 'Amarela e Preta', 'Laranja e Branca', 'Laranja', 'Laranja e Preta', 'Verde e Branca', 'Verde', 'Verde e Preta' ]; // State Management with LocalStorage persistence const DEFAULT_STUDENTS = [ { id: 'lucas', name: 'Lucas Souza', email: 'lucas@email.com', whatsapp: '(35) 99999-0001', belt: 'Branca', degrees: 2, attendanceCount: 24, selfie: null, streak: 80, address: 'Rua das Flores, 123 - Centro', age: 15, guardian: 'Ana Souza', objective: 'Aprender defesa pessoal e ganhar disciplina', weeklyGoal: 3, profession: 'Estudante', schoolName: 'E.E. Pandiá Calógeras', hasLoan: true, kimonoBrand: 'Koral', kimonoSize: 'M2', kimonoDate: '2026-05-15' }, { id: 'thiago', name: 'Thiago Behring', email: 'thiago@email.com', whatsapp: '(35) 99999-0002', belt: 'Azul', degrees: 1, attendanceCount: 52, selfie: 'preset_thiago', streak: 90, address: 'Av. Tiradentes, 45 - Alto', age: 22, guardian: '', objective: 'Focar em competição e condicionamento', weeklyGoal: 4, profession: 'Educador Físico', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' }, { id: 'felipe', name: 'Felipe Santana', email: 'felipe@email.com', whatsapp: '(35) 99999-0003', belt: 'Roxa', degrees: 3, attendanceCount: 112, selfie: 'preset_felipe', streak: 95, address: 'Rua São Bento, 987 - Vista Alegre', age: 28, guardian: '', objective: 'Estilo de vida e evolução na arte marcial', weeklyGoal: 3, profession: 'Desenvolvedor', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' }, { id: 'gabriela', name: 'Gabriela Lima', email: 'gabriela@email.com', whatsapp: '(35) 99999-0004', belt: 'Marrom', degrees: 0, attendanceCount: 198, selfie: null, streak: 65, address: 'Serrinha da Aliança, Km 4', age: 32, guardian: '', objective: 'Competir e um dia dar aulas', weeklyGoal: 2, profession: 'Veterinária', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' }, { id: 'roberto', name: 'Roberto Alencar', email: 'roberto@email.com', whatsapp: '(35) 99999-0005', belt: 'Preta', degrees: 2, attendanceCount: 342, selfie: 'preset_roberto', streak: 85, address: 'Rua do Cruzeiro, 50 - Centro', age: 45, guardian: '', objective: 'Manter a saúde e passar a tradição adiante', weeklyGoal: 5, profession: 'Empresário', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' }, { id: 'senpai_lucas', name: 'Senpai Lucas', email: 'senpai.lucas@email.com', whatsapp: '(35) 99999-0006', belt: 'Azul', degrees: 2, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 25, guardian: '', objective: 'Evolução técnica e auxílio nas aulas', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' }, { id: 'senpai_marcelo', name: 'Senpai Marcelo', email: 'senpai.marcelo@email.com', whatsapp: '(35) 99999-0007', belt: 'Roxa', degrees: 1, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 27, guardian: '', objective: 'Evolução técnica e competição', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' }, { id: 'senpai_maju', name: 'Senpai Maju', email: 'senpai.maju@email.com', whatsapp: '(35) 99999-0008', belt: 'Roxa', degrees: 2, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 23, guardian: '', objective: 'Evolução técnica e liderança feminina no tatame', weeklyGoal: 3, profession: 'Professora Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' }, { id: 'senpai_rogerio', name: 'Senpai Rogério', email: 'senpai.rogerio@email.com', whatsapp: '(35) 99999-0009', belt: 'Roxa', degrees: 3, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 29, guardian: '', objective: 'Evolução técnica e auxílio nas aulas', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' }, { id: 'senpai_felicio', name: 'Senpai Felício', email: 'senpai.felicio@email.com', whatsapp: '(35) 99999-0010', belt: 'Roxa', degrees: 2, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 26, guardian: '', objective: 'Evolução técnica e auxílio nas aulas', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' }, { id: 'senpai_isadora', name: 'Senpai Isadora', email: 'senpai.isadora@email.com', whatsapp: '(35) 99999-0011', belt: 'Azul', degrees: 4, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 24, guardian: '', objective: 'Evolução técnica e liderança feminina no tatame', weeklyGoal: 3, profession: 'Professora Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' } ]; const DEFAULT_EVENTS = [ { id: 1, title: 'Treino de Graduação e Defesa Pessoal', type: 'Treino', date: '2026-06-06', time: '10:00' }, { id: 2, title: 'Seminário de Passagem de Guarda', type: 'Seminário', date: '2026-06-15', time: '19:30' }, { id: 3, title: 'Exame Geral de Faixas', type: 'Graduação', date: '2026-07-04', time: '19:00' } ]; const DEFAULT_ANNOUNCEMENTS = [ { id: 1, title: 'Patches da Associação Behring', content: 'Atenção alunos: para o próximo exame geral de faixas em Julho, todos os kimonos devem estar devidamente equipados com o patch oficial da associação Behring. Disponíveis na secretaria.', date: '2026-06-04' }, { id: 2, title: 'Foco na Assiduidade', content: 'Lembramos a todos que a frequência é monitorada pelo app (check-in manual ou foto IA). A assiduidade é o critério principal para indicação aos graus nas faixas.', date: '2026-06-01' } ]; const DEFAULT_HISTORY = [ { date: '2026-06-03', time: '19:15', studentId: 'lucas', studentName: 'Lucas Souza', belt: 'Branca', method: 'manual' }, { date: '2026-06-03', time: '19:10', studentId: 'thiago', studentName: 'Thiago Behring', belt: 'Azul', method: 'ia' }, { date: '2026-06-03', time: '19:10', studentId: 'felipe', studentName: 'Felipe Santana', belt: 'Roxa', method: 'ia' }, { date: '2026-06-02', time: '19:05', studentId: 'lucas', studentName: 'Lucas Souza', belt: 'Branca', method: 'manual' }, { date: '2026-06-02', time: '19:05', studentId: 'gabriela', studentName: 'Gabriela Lima', belt: 'Marrom', method: 'manual' } ]; const DEFAULT_BJJ_HISTORY = { text: `A história do Jiu-Jitsu no Brasil começou no início do século XX. O mestre japonês Mitsuyo Maeda, conhecido como "Conde Koma", chegou ao Brasil em 1914. Ele viajou demonstrando o Kodokan Judo (então chamado de Jiu-Jitsu Kano ou simplesmente Jiu-Jitsu). Em Belém do Pará, Maeda conheceu Carlos Gracie. Carlos se interessou pelas demonstrações de Maeda e tornou-se seu aluno. Carlos ensinou a seus irmãos, incluindo Oswaldo, Gastão Jr., Jorge e Hélio Gracie. Hélio Gracie, sendo mais franzino, adaptou as técnicas para focar no uso da alavanca em vez da força bruta, dando origem ao Jiu-Jitsu Brasileiro (BJJ). O Jiu-Jitsu da linhagem Behring carrega as tradições técnicas e éticas estabelecidas pelo Grande Mestre Sylvio Behring, focando na defesa pessoal, respeito mútuo e disciplina dentro e fora dos tatames. A escola de São Bento do Sapucaí orgulha-se de manter este legado vivo.`, videos: [ { id: 1, title: 'A Origem do Jiu-Jitsu Brasileiro (BJJ)', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ' }, { id: 2, title: 'Defesa Pessoal Behring BJJ - Fundamentos', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ' } ] }; const DEFAULT_DOJO_SCHEDULES = { centro: [ { day: "Segunda", type: "Adulto", time: "10:00h e 18:30h" }, { day: "Terça", type: "Kids", time: "18h" }, { day: "Quarta", type: "Adulto", time: "10:00h e 18:30h" }, { day: "Quinta", type: "Kids", time: "18h" }, { day: "Sábado", type: "Misto", time: "10:00h" } ], quilombo: [ { day: "Segunda", type: "Misto", time: "18:30h" }, { day: "Quinta", type: "Misto", time: "18:30h" } ] }; // App State let db = { students: JSON.parse(localStorage.getItem('bjj_students')) || DEFAULT_STUDENTS, events: JSON.parse(localStorage.getItem('bjj_events')) || DEFAULT_EVENTS, announcements: JSON.parse(localStorage.getItem('bjj_announcements')) || DEFAULT_ANNOUNCEMENTS, history: JSON.parse(localStorage.getItem('bjj_history')) || DEFAULT_HISTORY, bjjHistory: JSON.parse(localStorage.getItem('bjj_history_content')) || DEFAULT_BJJ_HISTORY, dojoSchedules: JSON.parse(localStorage.getItem('bjj_dojo_schedules')) || DEFAULT_DOJO_SCHEDULES }; // Make sure all students have profile properties initialized db.students.forEach(initializeStudentFields); // Re-compute student attendance counts dynamically from history to ensure local database consistency on startup if (db.students && db.history) { db.students.forEach(student => { student.attendanceCount = db.history.filter(h => h.studentId === student.id).length; }); } let currentSession = { user: null, role: null, activeTab: null }; // Supabase Configuration const SUPABASE_URL = 'https://kvhcvuagncabwqtvrsnd.supabase.co'; const SUPABASE_KEY = 'sb_publishable_11I2BcMoKAoAr2uvSLuPwA_8PkDyBll'; const supabaseClient = (window.supabase) ? window.supabase.createClient(SUPABASE_URL, SUPABASE_KEY) : null; // Helper to map student record from Supabase schema to local database schema function mapSupabaseStudent(s) { return { id: s.id, name: s.name, email: s.email || '', whatsapp: s.whatsapp || '', password: s.senha || 'aluno123', belt: s.belt, degrees: s.degrees, attendanceCount: s.attendance_count, selfie: s.selfie, streak: s.streak, address: s.address, age: s.age, guardian: s.guardian, objective: s.objective, weeklyGoal: s.weekly_goal, profession: s.profession, schoolName: s.school_name, hasLoan: s.has_loan, kimonoBrand: s.kimono_brand, kimonoSize: s.kimono_size, kimonoDate: s.kimono_date, classTime: s.class_time || 'Qualquer Horário', evaluationParents: s.evaluation_parents || 'Pendente', evaluationSchool: s.evaluation_school || 'Pendente', faceEmbedding: s.face_embedding || null }; } // Ensure every logged-in professor has a corresponding student record (now and future) async function ensureStudentRecordForProfessor(profId, profName) { let student = db.students.find(s => s.id === profId); const isSensei = profId.startsWith('sensei_'); const isSenpai = profId.startsWith('senpai_'); if (student) { if (isSensei && student.belt !== 'Preta') { student.belt = 'Preta'; await syncStudentToCloud(student); saveDB(); } return; } student = { id: profId, name: profName, password: 'aluno123', email: '', whatsapp: '', belt: isSensei ? 'Preta' : (isSenpai ? 'Pendente' : 'Preta'), degrees: 0, attendanceCount: 0, selfie: null, streak: 100, address: '', age: null, guardian: '', objective: '', weeklyGoal: 3, profession: 'Professor', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '', classTime: 'Qualquer Horário' }; db.students.push(student); try { await syncStudentToCloud(student); } catch(e) { console.error("Failed to sync auto-created student profile for professor", e); } saveDB(); } let manualPresenceList = {}; // Temp store for today's check-ins let currentGroupPhoto = null; let lastRecognitionWasFallback = false; let currentIARecognitionResult = []; // Supabase Async Seeding Helpers async function seedSupabaseStudents() { for (let s of DEFAULT_STUDENTS) { await supabaseClient.from('students').insert({ id: s.id, name: s.name, email: s.email || '', senha: s.password || 'aluno123', belt: s.belt, degrees: s.degrees, attendance_count: s.attendanceCount, selfie: s.selfie, streak: s.streak, address: s.address, age: s.age, guardian: s.guardian, objective: s.objective, weekly_goal: s.weeklyGoal, profession: s.profession, school_name: s.schoolName, has_loan: s.hasLoan, kimono_brand: s.kimonoBrand, kimono_size: s.kimonoSize, kimono_date: s.kimonoDate }); } } async function seedSupabaseEvents() { for (let ev of DEFAULT_EVENTS) { await supabaseClient.from('events').insert({ id: ev.id, title: ev.title, type: ev.type, date: ev.date, time: ev.time }); } } async function seedSupabaseAnnouncements() { for (let ann of DEFAULT_ANNOUNCEMENTS) { await supabaseClient.from('announcements').insert({ id: ann.id, title: ann.title, content: ann.content, date: ann.date }); } } async function seedSupabaseBJJHistory() { await supabaseClient.from('bjj_history').insert({ id: 1, text: DEFAULT_BJJ_HISTORY.text, videos: DEFAULT_BJJ_HISTORY.videos }); } // Supabase Async Sync Operations async function loadDBFromSupabase() { if (!supabaseClient) { console.warn("Supabase client not loaded. Running in local fallback mode."); return; } try { // 1. Fetch Students const { data: studentsData, error: studentsError } = await supabaseClient.from('students').select('*'); if (studentsError) throw studentsError; if (studentsData && studentsData.length > 0) { db.students = studentsData.map(mapSupabaseStudent); localStorage.setItem('bjj_students_seeded', 'true'); } else { const seededStudents = localStorage.getItem('bjj_students_seeded'); if (!seededStudents) { await seedSupabaseStudents(); localStorage.setItem('bjj_students_seeded', 'true'); const { data: reloadedData } = await supabaseClient.from('students').select('*'); if (reloadedData) { db.students = reloadedData.map(mapSupabaseStudent); } } else { db.students = []; } } // 2. Fetch Events const { data: eventsData, error: eventsError } = await supabaseClient.from('events').select('*'); if (eventsError) throw eventsError; if (eventsData && eventsData.length > 0) { db.events = eventsData; localStorage.setItem('bjj_events_seeded', 'true'); } else { const seededEvents = localStorage.getItem('bjj_events_seeded'); if (!seededEvents) { await seedSupabaseEvents(); localStorage.setItem('bjj_events_seeded', 'true'); const { data: reloadedEvents } = await supabaseClient.from('events').select('*'); if (reloadedEvents) db.events = reloadedEvents; } else { db.events = []; } } // 3. Fetch Announcements const { data: announcementsData, error: announcementsError } = await supabaseClient.from('announcements').select('*'); if (announcementsError) throw announcementsError; if (announcementsData && announcementsData.length > 0) { db.announcements = announcementsData; localStorage.setItem('bjj_announcements_seeded', 'true'); } else { const seededAnnouncements = localStorage.getItem('bjj_announcements_seeded'); if (!seededAnnouncements) { await seedSupabaseAnnouncements(); localStorage.setItem('bjj_announcements_seeded', 'true'); const { data: reloadedAnnouncements } = await supabaseClient.from('announcements').select('*'); if (reloadedAnnouncements) db.announcements = reloadedAnnouncements; } else { db.announcements = []; } } // 4. Fetch History const { data: historyData, error: historyError } = await supabaseClient.from('attendance_history').select('*'); if (historyError) throw historyError; if (historyData) { db.history = historyData.map(h => { return { id: h.id, date: h.date, time: h.time, studentId: h.student_id, studentName: h.student_name, belt: h.belt, method: h.method, classTime: h.class_time || 'Qualquer Horário', teacherName: h.teacher_name || 'ADM' }; }); // Sort by descending (latest first) db.history.sort((a, b) => b.date.localeCompare(a.date) || b.time.localeCompare(a.time)); } // 5. Fetch BJJ History Content const { data: bjjHistoryData, error: bjjHistoryError } = await supabaseClient.from('bjj_history').select('*').eq('id', 1).single(); if (bjjHistoryError && bjjHistoryError.code !== 'PGRST116') throw bjjHistoryError; if (bjjHistoryData) { db.bjjHistory = bjjHistoryData; localStorage.setItem('bjj_history_seeded', 'true'); } else { const seededHistory = localStorage.getItem('bjj_history_seeded'); if (!seededHistory) { await seedSupabaseBJJHistory(); localStorage.setItem('bjj_history_seeded', 'true'); const { data: reloadedHistory } = await supabaseClient.from('bjj_history').select('*').eq('id', 1).single(); if (reloadedHistory) db.bjjHistory = reloadedHistory; } else { db.bjjHistory = { text: '', videos: [] }; } } // 6. Fetch Dojo Schedules if (supabaseClient) { try { const { data: schedData, error: schedError } = await supabaseClient.from('dojo_schedules').select('*').eq('id', 'schedule').single(); if (!schedError && schedData) { db.dojoSchedules = schedData.data; localStorage.setItem('bjj_schedules_seeded', 'true'); } else { const seededSchedules = localStorage.getItem('bjj_schedules_seeded'); if (!seededSchedules) { await supabaseClient.from('dojo_schedules').upsert({ id: 'schedule', data: db.dojoSchedules }); localStorage.setItem('bjj_schedules_seeded', 'true'); } } } catch(e) { console.warn("Could not load dojo schedules from Supabase", e); } } // 7. Fetch Face API Configuration (URL & Threshold) from Supabase dojo_schedules table if (supabaseClient) { try { const { data: configData, error: configError } = await supabaseClient.from('dojo_schedules').select('*').eq('id', 'config').single(); if (!configError && configData && configData.data) { if (configData.data.face_api_url) { localStorage.setItem('face_api_url', configData.data.face_api_url); const apiInput = document.getElementById('ia-api-url'); if (apiInput) apiInput.value = configData.data.face_api_url; const settingsApiInput = document.getElementById('settings-ia-api-url'); if (settingsApiInput) settingsApiInput.value = configData.data.face_api_url; } if (configData.data.face_api_threshold) { localStorage.setItem('face_api_threshold', configData.data.face_api_threshold); const thresholdInput = document.getElementById('ia-threshold'); if (thresholdInput) { thresholdInput.value = configData.data.face_api_threshold; const display = document.getElementById('ia-threshold-value'); if (display) display.textContent = parseFloat(configData.data.face_api_threshold).toFixed(2); } const settingsThresholdInput = document.getElementById('settings-ia-threshold'); if (settingsThresholdInput) { settingsThresholdInput.value = configData.data.face_api_threshold; const display = document.getElementById('settings-ia-threshold-value'); if (display) display.textContent = parseFloat(configData.data.face_api_threshold).toFixed(2); } } } } catch(e) { console.warn("Could not load face api config from Supabase", e); } } // Re-compute student attendance counts dynamically from history to ensure database consistency after cloud load if (db.students && db.history) { db.students.forEach(student => { student.attendanceCount = db.history.filter(h => h.studentId === student.id).length; }); } // Save local backup copy saveDBLocallyOnly(); populateClassTimeSelects(); } catch (e) { console.warn("Could not sync with Supabase tables. Running locally on LocalStorage.", e); } } function saveSessionToLocalStorage() { try { const sessionCopy = JSON.parse(JSON.stringify(currentSession)); if (sessionCopy.user && sessionCopy.user.selfie && sessionCopy.user.selfie.startsWith('data:')) { sessionCopy.user.selfie = 'placeholder'; } localStorage.setItem('bjj_session', JSON.stringify(sessionCopy)); } catch (err) { console.error("Failed to save session to localStorage:", err); } } function saveDBLocallyOnly() { try { const studentsClean = db.students.map(s => { const copy = { ...s }; // If the selfie is a large base64 string, do not write it to localStorage to prevent QuotaExceededError if (copy.selfie && copy.selfie.startsWith('data:')) { copy.selfie = 'placeholder'; } return copy; }); localStorage.setItem('bjj_students', JSON.stringify(studentsClean)); localStorage.setItem('bjj_events', JSON.stringify(db.events)); localStorage.setItem('bjj_announcements', JSON.stringify(db.announcements)); localStorage.setItem('bjj_history', JSON.stringify(db.history)); localStorage.setItem('bjj_history_content', JSON.stringify(db.bjjHistory)); localStorage.setItem('bjj_dojo_schedules', JSON.stringify(db.dojoSchedules)); } catch (err) { console.error("Failed to save database to localStorage:", err); } } // Central Cloud Sync Writer async function syncStudentToCloud(student) { if (!supabaseClient) { console.warn("Supabase client not loaded. Running in local fallback mode."); return; } try { const { error } = await supabaseClient.from('students').upsert({ id: student.id, name: student.name, email: student.email || '', whatsapp: student.whatsapp || '', senha: student.password || 'aluno123', belt: student.belt, degrees: student.degrees, attendance_count: student.attendanceCount, selfie: student.selfie, streak: student.streak, address: student.address, age: student.age, guardian: student.guardian, objective: student.objective, weekly_goal: student.weeklyGoal, profession: student.profession, school_name: student.schoolName, has_loan: student.hasLoan, kimono_brand: student.kimonoBrand, kimono_size: student.kimonoSize, kimono_date: student.kimonoDate, class_time: student.classTime || 'Qualquer Horário', evaluation_parents: student.evaluationParents || 'Pendente', evaluation_school: student.evaluationSchool || 'Pendente', face_embedding: student.faceEmbedding || null }); if (error) throw error; } catch(e) { console.error("Supabase Sync Failed (Student):", e); alert("Erro ao sincronizar dados do aluno com o Supabase (Verifique se a tabela 'students' possui todas as colunas do schema.sql e se o RLS está desabilitado):\n" + (e.message || JSON.stringify(e))); throw e; } } function setupSidebar() { const toggleBtn = document.getElementById('sidebar-toggle'); const sidebar = document.getElementById('app-sidebar'); const toggleIconPath = document.getElementById('toggle-icon-path'); if (toggleBtn && sidebar) { toggleBtn.addEventListener('click', () => { sidebar.classList.toggle('collapsed'); const isCollapsed = sidebar.classList.contains('collapsed'); localStorage.setItem('bjj_sidebar_collapsed', isCollapsed); if (toggleIconPath) { if (isCollapsed) { toggleIconPath.setAttribute('d', 'M9 5l7 7-7 7'); } else { toggleIconPath.setAttribute('d', 'M15 19l-7-7 7-7'); } } }); const wasCollapsed = localStorage.getItem('bjj_sidebar_collapsed') === 'true'; if (wasCollapsed) { sidebar.classList.add('collapsed'); if (toggleIconPath) { toggleIconPath.setAttribute('d', 'M9 5l7 7-7 7'); } } } } // Initialize application // Initialize application document.addEventListener('DOMContentLoaded', () => { setupSidebar(); // Check if session exists in localStorage immediately for instant rendering const savedSession = localStorage.getItem('bjj_session'); if (savedSession) { currentSession = JSON.parse(savedSession); setupUserInterface(); } else { showLoginScreen(); } // Set current date in Presence View const dateDisplay = document.getElementById('presence-current-date'); if (dateDisplay) { const today = new Date(); dateDisplay.textContent = today.toLocaleDateString('pt-BR'); } // Populate training time select dropdowns with cached data immediately populateClassTimeSelects(); // Load from Supabase asynchronously in the background to prevent blocking loadDBFromSupabase().then(() => { // Re-setup UI if a session was active, to sync live data if (currentSession.user) { setupUserInterface(); } populateClassTimeSelects(); // Sync again with live Supabase schedules data }).catch(err => { console.warn("Background database sync failed", err); }); }); // Database Save Helper function saveDB() { saveDBLocallyOnly(); } // Authentication handlers function toggleAuthForm(mode) { const loginForm = document.getElementById('login-form'); const registerForm = document.getElementById('register-form'); if (mode === 'register') { loginForm.style.display = 'none'; registerForm.style.display = 'block'; } else { loginForm.style.display = 'block'; registerForm.style.display = 'none'; } } async function handleLogin(event) { event.preventDefault(); const usernameInput = document.getElementById('username').value.trim(); const passwordInput = document.getElementById('password').value; const roleInput = document.getElementById('login-role').value; if (roleInput === 'professor') { const normalizedUser = usernameInput.toLowerCase().replace(/\s+/g, ' ').trim(); let professorName = ''; if (normalizedUser === 'sensei hugo') { professorName = 'Sensei Hugo'; } else if (normalizedUser === 'sensei leo') { professorName = 'Sensei Leo'; } else if (normalizedUser === 'adm') { professorName = 'ADM'; } else if (normalizedUser === 'professor') { professorName = 'Prof. Felipe'; } else if (normalizedUser === 'senpai lucas') { professorName = 'Senpai Lucas'; } else if (normalizedUser === 'sensei marcio' || normalizedUser === 'sensei márcio') { professorName = 'Sensei Márcio'; } else if (normalizedUser === 'senpai marcelo') { professorName = 'Senpai Marcelo'; } else if (normalizedUser === 'senpai maju') { professorName = 'Senpai Maju'; } else if (normalizedUser === 'senpai rogerio' || normalizedUser === 'senpai rogério') { professorName = 'Senpai Rogério'; } else if (normalizedUser === 'senpai felicio' || normalizedUser === 'senpai felício') { professorName = 'Senpai Felício'; } else if (normalizedUser === 'senpai isadora') { professorName = 'Senpai Isadora'; } if (professorName && passwordInput === 'bjj123') { currentSession.user = { id: normalizedUser.replace(/\s+/g, '_'), name: professorName }; currentSession.role = 'professor'; currentSession.activeTab = 'prof-presence'; saveSessionToLocalStorage(); if (currentSession.user.id !== 'adm') { await ensureStudentRecordForProfessor(currentSession.user.id, professorName); } setupUserInterface(); return; } else { alert('Credenciais de Professor incorretas! Verifique o nome do professor e a senha bjj123.'); return; } } else { // Student login const studentId = usernameInput.toLowerCase().replace(/\s+/g, '_'); let student = db.students.find(s => s.id === studentId); // Fast-path: check if student exists in local memory first for instant response if (student) { initializeStudentFields(student); if (student.password === passwordInput) { currentSession.user = student; currentSession.role = 'student'; currentSession.activeTab = 'stud-home'; saveSessionToLocalStorage(); setupUserInterface(); // Fetch latest update in background to refresh LocalStorage sync if (supabaseClient) { supabaseClient.from('students').select('*').eq('id', studentId).single().then(({ data }) => { if (data) { const updated = mapSupabaseStudent(data); const idx = db.students.findIndex(s => s.id === studentId); if (idx !== -1) { db.students[idx] = updated; } saveDB(); // Immediately update session user and profile views if currently active if (currentSession.user && currentSession.user.id === studentId) { currentSession.user = updated; saveSessionToLocalStorage(); renderStudentProfile(); renderStudentHome(); } } }).catch(e => console.warn("Background credentials refresh failed", e)); } return; } else { alert('Senha incorreta para este aluno!'); return; } } // Slow-path: Student not in local memory (e.g. fresh registration on another device) if (supabaseClient) { const btn = event.submitter || document.querySelector('#login-form button[type="submit"]'); const originalText = btn ? btn.textContent : "Entrar no App"; if (btn) { btn.textContent = "Verificando..."; btn.disabled = true; } try { const { data, error } = await supabaseClient.from('students').select('*').eq('id', studentId).single(); if (btn) { btn.textContent = originalText; btn.disabled = false; } if (data) { student = mapSupabaseStudent(data); db.students.push(student); saveDB(); initializeStudentFields(student); if (student.password === passwordInput) { currentSession.user = student; currentSession.role = 'student'; currentSession.activeTab = 'stud-home'; saveSessionToLocalStorage(); setupUserInterface(); return; } else { alert('Senha incorreta para este aluno!'); return; } } } catch (e) { console.warn("Supabase credentials fetch failed", e); if (btn) { btn.textContent = originalText; btn.disabled = false; } } } alert('Aluno não cadastrado! Por favor, use a opção de cadastro abaixo.'); } } async function handleRegister(event) { event.preventDefault(); const nameInput = document.getElementById('reg-name').value.trim(); const emailInput = document.getElementById('reg-email').value.trim(); const whatsappInput = document.getElementById('reg-whatsapp').value.trim(); const classTimeInput = 'Qualquer Horário'; const passwordInput = document.getElementById('reg-password').value; const confirmInput = document.getElementById('reg-confirm').value; if (passwordInput !== confirmInput) { alert('As senhas não coincidem!'); return; } const studentId = nameInput.toLowerCase().replace(/\s+/g, '_'); // Check if student ID already exists let exists = db.students.some(s => s.id === studentId); if (!exists) { try { const { data, error } = await supabaseClient.from('students').select('id').eq('id', studentId); if (data && data.length > 0) { exists = true; } } catch (e) { console.warn("Could not check duplicate username in Supabase", e); } } if (exists) { alert('Já existe um aluno cadastrado com este nome!'); return; } const newStudent = { id: studentId, name: nameInput, email: emailInput, whatsapp: whatsappInput, password: passwordInput, belt: 'Branca', degrees: 0, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 18, guardian: '', objective: '', weeklyGoal: 3, profession: '', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '', classTime: classTimeInput || 'Qualquer Horário' }; try { const { error } = await supabaseClient.from('students').insert({ id: newStudent.id, name: newStudent.name, email: newStudent.email, senha: newStudent.password, belt: newStudent.belt, degrees: newStudent.degrees, attendance_count: newStudent.attendanceCount, selfie: newStudent.selfie, streak: newStudent.streak, address: newStudent.address, age: newStudent.age, guardian: newStudent.guardian, objective: newStudent.objective, weekly_goal: newStudent.weeklyGoal, profession: newStudent.profession, school_name: newStudent.schoolName, has_loan: newStudent.hasLoan, kimono_brand: newStudent.kimonoBrand, kimono_size: newStudent.kimonoSize, kimono_date: newStudent.kimonoDate }); if (error) throw error; } catch (e) { console.error("Failed to sync new student to Supabase", e); alert("Erro ao salvar cadastro no banco de dados na nuvem:\n" + (e.message || JSON.stringify(e))); return; } db.students.push(newStudent); saveDB(); // Automatically log in currentSession.user = newStudent; currentSession.role = 'student'; currentSession.activeTab = 'stud-home'; saveSessionToLocalStorage(); // Reset inputs & toggle form back for next logouts document.getElementById('reg-name').value = ''; document.getElementById('reg-email').value = ''; document.getElementById('reg-password').value = ''; document.getElementById('reg-confirm').value = ''; toggleAuthForm('login'); setupUserInterface(); alert('Sua conta foi criada e você foi logado com sucesso!'); } function handleLogout() { currentSession = { user: null, role: null, activeTab: null }; localStorage.removeItem('bjj_session'); showLoginScreen(); } function showLoginScreen() { document.getElementById('auth-screen').style.display = 'flex'; document.getElementById('app-container').style.display = 'none'; } function setupUserInterface() { document.getElementById('auth-screen').style.display = 'none'; document.getElementById('app-container').style.display = 'flex'; // Set User Profile headers document.getElementById('nav-user-display').textContent = currentSession.user.name; document.getElementById('nav-user-role-display').textContent = currentSession.role === 'professor' ? 'Professor / Admin' : 'Aluno'; // Show/hide navigation tabs depending on role if (currentSession.role === 'professor') { document.getElementById('professor-tabs').style.display = 'flex'; document.getElementById('student-tabs').style.display = 'none'; // Initialize Face API configurations const apiInput = document.getElementById('ia-api-url'); if (apiInput) { apiInput.value = localStorage.getItem('face_api_url') || 'http://localhost:8000'; } const thresholdInput = document.getElementById('ia-threshold'); if (thresholdInput) { const val = localStorage.getItem('face_api_threshold') || '0.40'; thresholdInput.value = val; const display = document.getElementById('ia-threshold-value'); if (display) display.textContent = parseFloat(val).toFixed(2); } // Populate Professor views renderProfessorDashboard(); renderStudentsTable(); renderPresenceChecklist(); renderGeneralHistoryTable(); renderProfessorEventsAndAnnouncements(); // Asynchronously check and migrate any student selfies without vector embeddings backfillMissingEmbeddings(); // Check if professor onboarding is complete (selfie for Sensei/Senpai, belt for Senpai) if (currentSession.user.id !== 'adm') { const profRecord = db.students.find(s => s.id === currentSession.user.id); const isSenpai = currentSession.user.id.startsWith('senpai_'); const needsPhoto = !profRecord || !profRecord.selfie; const needsBelt = isSenpai && (!profRecord || profRecord.belt === 'Pendente' || !profRecord.belt); if (needsPhoto || needsBelt) { document.getElementById('prof-photo-modal-name').textContent = currentSession.user.name; // Show/hide Senpai belt selection const beltSelectionGroup = document.getElementById('prof-belt-selection-group'); if (beltSelectionGroup) { beltSelectionGroup.style.display = needsBelt ? 'block' : 'none'; if (profRecord && profRecord.belt && profRecord.belt !== 'Pendente') { document.getElementById('prof-photo-modal-belt').value = profRecord.belt; } else { document.getElementById('prof-photo-modal-belt').value = 'Branca'; } } const previewImg = document.getElementById('prof-photo-modal-preview'); if (profRecord && profRecord.selfie) { previewImg.src = profRecord.selfie; } else { previewImg.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%236f6f78'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z'/%3E%3C/svg%3E"; } const saveBtn = document.getElementById('btn-save-prof-photo'); if (saveBtn) { saveBtn.disabled = needsPhoto; // if they need a photo, they must capture it first. If they don't, they can save. } openModal('professor-photo-modal'); } } } else { document.getElementById('professor-tabs').style.display = 'none'; document.getElementById('student-tabs').style.display = 'flex'; // Sync student local info from DB (since details like degrees/selfie might change) const updatedStudent = db.students.find(s => s.id === currentSession.user.id); if (updatedStudent) { initializeStudentFields(updatedStudent); currentSession.user = updatedStudent; } // Populate Student views renderStudentHome(); renderStudentProfile(); renderStudentHistoryTable(); renderStudentEventsAndAnnouncements(); } // Switch to active tab switchTab(currentSession.activeTab); } // Tab Switching Routing function switchTab(tabId) { // Redirect deleted tabs to default if (currentSession.role === 'professor') { if (tabId === 'prof-ia-photo' || tabId === 'prof-bjj-history') { tabId = 'prof-presence'; } } else { if (tabId === 'stud-events') { tabId = 'stud-home'; } } currentSession.activeTab = tabId; saveSessionToLocalStorage(); // Remove active classes document.querySelectorAll('.nav-tab-item').forEach(item => item.classList.remove('active')); document.querySelectorAll('.view-section').forEach(item => item.classList.remove('active')); // Map tabId to navigation element and view section let navItem, sectionItem; if (currentSession.role === 'professor') { // Professor tabs const tabMap = { 'prof-presence': 1, 'prof-dashboard': 2, 'prof-students': 3, 'prof-history': 4, 'prof-events': 5, 'prof-settings': 6 }; const idx = tabMap[tabId]; navItem = document.querySelector(`#professor-tabs .nav-tab-item:nth-child(${idx})`); sectionItem = document.getElementById(`view-${tabId}`); } else { // Student tabs const tabMap = { 'stud-home': 1, 'stud-profile': 2, 'stud-history': 3 }; const idx = tabMap[tabId]; navItem = document.querySelector(`#student-tabs .nav-tab-item:nth-child(${idx})`); sectionItem = document.getElementById(`view-${tabId}`); } if (navItem) navItem.classList.add('active'); if (sectionItem) sectionItem.classList.add('active'); // Trigger re-renders for live lists if (tabId === 'prof-presence') setPresenceTab('ia'); if (tabId === 'prof-dashboard') renderProfessorDashboard(); if (tabId === 'prof-students') renderStudentsTable(); if (tabId === 'prof-history') renderGeneralHistoryTable(); if (tabId === 'prof-settings') renderProfessorSettings(); if (tabId === 'stud-home') renderStudentHome(); if (tabId === 'stud-profile') renderStudentProfile(); if (tabId === 'stud-history') renderStudentHistoryTable(); } function setPresenceTab(type) { const btnIA = document.getElementById('btn-presence-toggle-ia'); const btnManual = document.getElementById('btn-presence-toggle-manual'); const containerIA = document.getElementById('presence-ia-container'); const containerManual = document.getElementById('presence-manual-container'); if (type === 'ia') { if (containerIA) containerIA.style.display = 'block'; if (containerManual) containerManual.style.display = 'none'; if (btnIA) { btnIA.className = 'btn btn-primary btn-sm'; btnIA.style.background = 'var(--accent-color)'; btnIA.style.border = '1px solid var(--accent-color)'; btnIA.style.color = '#ffffff'; } if (btnManual) { btnManual.className = 'btn btn-secondary btn-sm'; btnManual.style.background = 'transparent'; btnManual.style.border = 'none'; btnManual.style.color = 'var(--text-muted)'; } // Update backfill count for IA view updateBackfillCount(); } else { if (containerIA) containerIA.style.display = 'none'; if (containerManual) containerManual.style.display = 'block'; if (btnIA) { btnIA.className = 'btn btn-secondary btn-sm'; btnIA.style.background = 'transparent'; btnIA.style.border = 'none'; btnIA.style.color = 'var(--text-muted)'; } if (btnManual) { btnManual.className = 'btn btn-primary btn-sm'; btnManual.style.background = 'var(--accent-color)'; btnManual.style.border = '1px solid var(--accent-color)'; btnManual.style.color = '#ffffff'; } // Render manual checklist renderPresenceChecklist(); } } // Helper to turn text URLs into clickable links function linkify(text) { if (!text) return ''; const urlPattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; return text.replace(urlPattern, '$1'); } // Helper to format date function formatDateStr(dateStr) { const parts = dateStr.split('-'); if (parts.length === 3) { return `${parts[2]}/${parts[1]}/${parts[0]}`; } return dateStr; } // Helper to get initials function getInitials(name) { const names = name.split(' '); if (names.length > 1) { return (names[0][0] + names[names.length - 1][0]).toUpperCase(); } return name[0].toUpperCase(); } // ==================== PROFESSOR VIEW CONTROLLERS ==================== function renderProfessorDashboard() { document.getElementById('dashboard-total-students').textContent = db.students.length; // Count today's presences in history const today = new Date().toISOString().split('T')[0]; const todayPresences = db.history.filter(h => h.date === today).length; document.getElementById('dashboard-today-presence').textContent = todayPresences; document.getElementById('dashboard-next-events').textContent = db.events.length; document.getElementById('dashboard-announcements-count').textContent = db.announcements.length; // Belt Distribution (Chart Builder) const beltCounts = { 'Branca': 0, 'Azul': 0, 'Roxa': 0, 'Marrom': 0, 'Preta': 0 }; db.students.forEach(s => { if (beltCounts[s.belt] !== undefined) beltCounts[s.belt]++; }); const chartContainer = document.getElementById('belt-chart-container'); chartContainer.innerHTML = ''; const maxCount = Math.max(...Object.values(beltCounts), 1); // Avoid division by zero const beltColors = { 'Branca': { bar: '#f0f0f5', text: '#111111' }, 'Azul': { bar: '#1e40af', text: '#ffffff' }, 'Roxa': { bar: '#6d28d9', text: '#ffffff' }, 'Marrom': { bar: '#78350f', text: '#ffffff' }, 'Preta': { bar: '#1f2937', text: '#ff0000', border: 'red' } }; Object.keys(beltCounts).forEach(belt => { const count = beltCounts[belt]; const pct = (count / maxCount) * 100; const row = document.createElement('div'); row.style.display = 'flex'; row.style.alignItems = 'center'; row.style.gap = '16px'; const borderStyle = belt === 'Preta' ? '1px solid red' : '1px solid rgba(255,255,255,0.1)'; row.innerHTML = `
Nenhum evento agendado.
'; } else { db.events.slice(0, 3).forEach(ev => { const dateObj = new Date(ev.date + 'T00:00:00'); const day = String(dateObj.getDate()).padStart(2, '0'); const month = dateObj.toLocaleDateString('pt-BR', { month: 'short' }).slice(0, 3).toUpperCase(); const item = document.createElement('div'); item.className = 'event-item'; item.innerHTML = `${ev.type} • ${ev.time}h
Nenhum aviso publicado.
'; } else { db.announcements.slice(0, 3).forEach(ann => { const item = document.createElement('div'); item.style.padding = '12px 0'; item.style.borderBottom = '1px solid var(--border-color)'; item.innerHTML = `${linkify(ann.content)}
`; dashboardAnnList.appendChild(item); }); } } // Dashboard Dojo Schedules List const dashCentroTbody = document.getElementById('dashboard-schedule-centro-tbody'); if (dashCentroTbody) { dashCentroTbody.innerHTML = ''; const centroList = db.dojoSchedules.centro || []; if (centroList.length === 0) { dashCentroTbody.innerHTML = 'Cadastre alunos para gerenciar presenças.
'; return; } const classFilter = document.getElementById('presence-class-filter').value; const searchQuery = document.getElementById('presence-search-input').value.toLowerCase().trim(); // Filter students: stop filtering by student's preferred class time. // The presence list shows all students, allowing easy name/belt search. let filteredStudents = db.students.filter(student => { if (searchQuery !== '') { return student.name.toLowerCase().includes(searchQuery) || student.belt.toLowerCase().includes(searchQuery); } return true; }); if (filteredStudents.length === 0) { grid.innerHTML = 'Nenhum aluno encontrado para os filtros selecionados.
'; return; } // Sort by name filteredStudents.sort((a, b) => a.name.localeCompare(b.name)); filteredStudents.forEach(student => { const isChecked = manualPresenceList[student.id] ? true : false; const card = document.createElement('div'); card.className = `card text-center ${isChecked ? 'match' : ''}`; card.style.padding = '16px'; card.style.cursor = 'pointer'; card.style.border = isChecked ? '1px solid var(--accent-color)' : '1px solid var(--border-color)'; card.onclick = () => { manualPresenceList[student.id] = !manualPresenceList[student.id]; renderPresenceChecklist(); }; const initials = getInitials(student.name); card.innerHTML = `Nenhum evento agendado.
'; } else { db.events.forEach(ev => { const dateObj = new Date(ev.date + 'T00:00:00'); const day = String(dateObj.getDate()).padStart(2, '0'); const month = dateObj.toLocaleDateString('pt-BR', { month: 'short' }).slice(0, 3).toUpperCase(); const div = document.createElement('div'); div.className = 'event-item'; div.innerHTML = `${ev.type} • Horário: ${ev.time}h
Mural de avisos vazio.
'; } else { db.announcements.forEach(ann => { const div = document.createElement('div'); div.style.padding = '16px 0'; div.style.borderBottom = '1px solid var(--border-color)'; div.innerHTML = `${ann.content}
`; annList.appendChild(div); }); } // Render dojo schedules editor renderProfessorSchedules(); } // Add/Delete Student Handlers async function handleAddStudent(event) { event.preventDefault(); const name = document.getElementById('new-student-name').value.trim(); const belt = document.getElementById('new-student-belt').value; const degrees = parseInt(document.getElementById('new-student-degrees').value); const id = name.toLowerCase().replace(/\s+/g, '_'); if (db.students.some(s => s.id === id)) { alert('Este aluno já está cadastrado!'); return; } const newStudent = { id, name, belt, degrees, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 18, guardian: '', objective: '', weeklyGoal: 3, profession: '', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '', evaluationParents: 'Pendente', evaluationSchool: 'Pendente' }; try { const { error } = await supabaseClient.from('students').insert({ id: newStudent.id, name: newStudent.name, senha: newStudent.password || 'aluno123', belt: newStudent.belt, degrees: newStudent.degrees, attendance_count: newStudent.attendanceCount, selfie: newStudent.selfie, streak: newStudent.streak, address: newStudent.address, age: newStudent.age, guardian: newStudent.guardian, objective: newStudent.objective, weekly_goal: newStudent.weeklyGoal, profession: newStudent.profession, school_name: newStudent.schoolName, has_loan: newStudent.hasLoan, kimono_brand: newStudent.kimonoBrand, kimono_size: newStudent.kimonoSize, kimono_date: newStudent.kimonoDate, evaluation_parents: newStudent.evaluationParents, evaluation_school: newStudent.evaluationSchool, face_embedding: null }); if (error) throw error; } catch (e) { console.error("Failed to sync new student creation to Supabase", e); alert("Erro ao salvar aluno no banco de dados na nuvem:\n" + (e.message || JSON.stringify(e))); return; } db.students.push(newStudent); saveDB(); closeModal('add-student-modal'); document.getElementById('new-student-name').value = ''; renderStudentsTable(); alert(`Aluno ${name} cadastrado com sucesso!`); } // Promot Graduation Modal // Promot Graduation Modal function openGraduationModal(studentId) { const student = db.students.find(s => s.id === studentId); if (student) { document.getElementById('grad-modal-student-id').value = student.id; document.getElementById('grad-modal-student-name').textContent = student.name; document.getElementById('grad-modal-student-info').textContent = `Faixa: ${student.belt} • ${student.degrees} Graus`; const avatar = document.getElementById('grad-modal-avatar'); if (student.selfie) { avatar.src = student.selfie.startsWith('data:') ? student.selfie : getPresetAvatar(student.id); } else { avatar.src = getPresetAvatar(student.id); } // Populate fields document.getElementById('grad-student-name').value = student.name || ''; document.getElementById('grad-student-email').value = student.email || ''; document.getElementById('grad-student-whatsapp').value = student.whatsapp || ''; document.getElementById('grad-student-password').value = student.password || 'aluno123'; document.getElementById('grad-student-age').value = (student.age !== null && student.age !== undefined) ? student.age : ''; document.getElementById('grad-student-guardian').value = student.guardian || ''; document.getElementById('grad-student-address').value = student.address || ''; document.getElementById('grad-student-profession').value = student.profession || ''; document.getElementById('grad-student-school-name').value = student.schoolName || ''; document.getElementById('grad-student-objective').value = student.objective || ''; document.getElementById('grad-student-weekly-goal').value = student.weeklyGoal || 3; const hasLoanChk = document.getElementById('grad-student-has-loan'); hasLoanChk.checked = student.hasLoan || false; document.getElementById('grad-student-kimono-brand').value = student.kimonoBrand || ''; document.getElementById('grad-student-kimono-size').value = student.kimonoSize || ''; document.getElementById('grad-student-kimono-date').value = student.kimonoDate || ''; // Dynamically configure inputs based on initial age handleGradAgeChange(); // Restore belt and degrees to the student's specific saved values document.getElementById('grad-student-belt').value = student.belt || 'Branca'; document.getElementById('grad-student-degrees').value = student.degrees || 0; toggleGradKimonoInputs(); openModal('grad-student-modal'); } } function toggleGradGuardianInput() { const ageVal = document.getElementById('grad-student-age').value; const age = ageVal !== '' ? parseInt(ageVal) : null; const guardianGroup = document.getElementById('grad-guardian-group'); if (age !== null && age < 18) { guardianGroup.style.display = 'block'; } else { guardianGroup.style.display = 'none'; } } function handleGradAgeChange() { toggleGradGuardianInput(); const studentId = document.getElementById('grad-modal-student-id').value; const ageVal = document.getElementById('grad-student-age').value; const isKid = ageVal !== '' && parseInt(ageVal) < 16; const student = db.students.find(s => s.id === studentId); if (student) { const beltSelect = document.getElementById('grad-student-belt'); const currentSelectedBelt = beltSelect.value; beltSelect.innerHTML = ''; const beltList = isKid ? KIDS_BELTS : ADULT_BELTS; beltList.forEach(belt => { const opt = document.createElement('option'); opt.value = belt; opt.textContent = belt; beltSelect.appendChild(opt); }); if (beltList.includes(currentSelectedBelt)) { beltSelect.value = currentSelectedBelt; } else { beltSelect.value = 'Branca'; } const kidsPanel = document.getElementById('kids-evaluation-panel'); if (kidsPanel) { if (isKid) { kidsPanel.style.display = 'block'; const dojoInput = document.getElementById('grad-pillar-dojo'); const isEligible = student.attendanceCount >= 100; dojoInput.value = isEligible ? 'Elegível' : `Pendente (${student.attendanceCount}/100)`; dojoInput.style.color = isEligible ? 'var(--success-color)' : 'var(--text-muted)'; const badgeContainer = document.getElementById('kids-eligibility-badge'); if (isEligible) { badgeContainer.innerHTML = `👑 Elegível para Avaliação de Faixa (100+ Treinos)`; } else { badgeContainer.innerHTML = `Abaixo de 100 Treinos (${student.attendanceCount}/100)`; } document.getElementById('grad-pillar-parents').value = student.evaluationParents || 'Pendente'; document.getElementById('grad-pillar-school').value = student.evaluationSchool || 'Pendente'; } else { kidsPanel.style.display = 'none'; } } } } function toggleGradKimonoInputs() { const hasLoan = document.getElementById('grad-student-has-loan').checked; const kimonoInputsDiv = document.getElementById('grad-kimono-loan-inputs'); if (hasLoan) { kimonoInputsDiv.style.display = 'block'; } else { kimonoInputsDiv.style.display = 'none'; } } async function handleSaveGraduation(event) { try { event.preventDefault(); const id = document.getElementById('grad-modal-student-id').value; const student = db.students.find(s => s.id === id); if (student) { const oldBelt = student.belt; student.belt = document.getElementById('grad-student-belt').value; student.degrees = parseInt(document.getElementById('grad-student-degrees').value); student.classTime = 'Qualquer Horário'; student.name = document.getElementById('grad-student-name').value.trim(); student.email = document.getElementById('grad-student-email').value.trim(); student.whatsapp = document.getElementById('grad-student-whatsapp').value.trim(); student.password = document.getElementById('grad-student-password').value.trim() || 'aluno123'; const ageVal = document.getElementById('grad-student-age').value; student.age = ageVal !== '' ? parseInt(ageVal) : null; const isKid = student.age !== null && student.age < 16; const isMinor = student.age !== null && student.age < 18; // Reset attendance count if belt changed if (oldBelt !== student.belt) { student.attendanceCount = 0; if (isKid) student.degrees = 0; } if (isKid) { student.evaluationParents = document.getElementById('grad-pillar-parents').value; student.evaluationSchool = document.getElementById('grad-pillar-school').value; } else { student.evaluationParents = 'Pendente'; student.evaluationSchool = 'Pendente'; } if (isMinor) { student.guardian = document.getElementById('grad-student-guardian').value.trim(); } else { student.guardian = ''; } student.address = document.getElementById('grad-student-address').value.trim(); student.profession = document.getElementById('grad-student-profession').value.trim(); student.schoolName = document.getElementById('grad-student-school-name').value.trim(); student.objective = document.getElementById('grad-student-objective').value.trim(); student.weeklyGoal = parseInt(document.getElementById('grad-student-weekly-goal').value) || 3; student.hasLoan = document.getElementById('grad-student-has-loan').checked; if (student.hasLoan) { student.kimonoBrand = document.getElementById('grad-student-kimono-brand').value.trim(); student.kimonoSize = document.getElementById('grad-student-kimono-size').value.trim(); student.kimonoDate = document.getElementById('grad-student-kimono-date').value; } else { student.kimonoBrand = ''; student.kimonoSize = ''; student.kimonoDate = ''; } let syncSuccess = true; try { await syncStudentToCloud(student); } catch (e) { console.error("Failed to save student details to Supabase", e); syncSuccess = false; } saveDB(); closeModal('grad-student-modal'); renderStudentsTable(); if (syncSuccess) { alert('Ficha do aluno atualizada com sucesso!'); } else { alert('Aviso: Os dados foram salvos temporariamente no navegador, mas falharam ao sincronizar com o Supabase. Por favor, verifique sua conexão ou a estrutura do banco de dados.'); } } } catch (err) { console.error("Critical error in handleSaveGraduation:", err); alert("Erro crítico ao salvar dados do aluno: " + err.message); closeModal('grad-student-modal'); } } async function handleDeleteStudent() { const id = document.getElementById('grad-modal-student-id').value; const student = db.students.find(s => s.id === id); if (!student) return; const confirmDelete = confirm(`Tem certeza que deseja excluir o aluno "${student.name}" definitivamente? Todos os dados dele serão apagados.`); if (!confirmDelete) return; // 1. Delete from Supabase if (supabaseClient) { try { // First check if the student exists in Supabase to know if it's an RLS issue or just missing from cloud const { data: existsData, error: existsError } = await supabaseClient.from('students').select('id').eq('id', student.id); if (existsError) throw existsError; const existedInCloud = existsData && existsData.length > 0; // Delete associated attendance logs from Supabase await supabaseClient.from('attendance_history').delete().eq('student_id', student.id); // Delete the student from Supabase const { data: deleteData, error: deleteError } = await supabaseClient.from('students').delete().eq('id', student.id).select(); if (deleteError) throw deleteError; // If it existed in the cloud but nothing was deleted, it is likely an RLS permission issue if (existedInCloud && (!deleteData || deleteData.length === 0)) { throw new Error("O registro existe no Supabase, mas não pôde ser excluído. Isso geralmente ocorre devido a políticas de Segurança de Nível de Linha (RLS) ativas. Certifique-se de que o RLS está desativado no Supabase para a tabela 'students' (execute ALTER TABLE public.students DISABLE ROW LEVEL SECURITY; no SQL Editor)."); } } catch (e) { console.error("Failed to delete student from Supabase", e); alert("Erro ao excluir aluno do banco de dados na nuvem:\n" + (e.message || e)); return; } } // 2. Delete from local db db.students = db.students.filter(s => s.id !== student.id); // Also clean up local history logs for this student db.history = db.history.filter(h => h.studentId !== student.id); saveDB(); // 3. Clear from manual attendance list if present if (manualPresenceList[student.id] !== undefined) { delete manualPresenceList[student.id]; } closeModal('grad-student-modal'); renderStudentsTable(); renderPresenceChecklist(); alert("Aluno excluído com sucesso!"); } // Add/Delete Events & Announcements Handlers async function handleAddEvent(event) { event.preventDefault(); const title = document.getElementById('event-title').value.trim(); const type = document.getElementById('event-type').value; const date = document.getElementById('event-date').value; const time = document.getElementById('event-time').value; const idVal = document.getElementById('edit-event-id').value; const isEdit = idVal !== ''; const publishApp = document.getElementById('event-publish-app') ? document.getElementById('event-publish-app').checked : true; const shareWhatsapp = document.getElementById('event-share-whatsapp') ? document.getElementById('event-share-whatsapp').checked : false; const newEvent = { id: isEdit ? parseInt(idVal) : Date.now(), title, type, date, time }; if (publishApp) { try { await supabaseClient.from('events').upsert(newEvent); } catch (e) { console.error("Failed to save event to Supabase", e); } if (isEdit) { const idx = db.events.findIndex(e => e.id === newEvent.id); if (idx !== -1) { db.events[idx] = newEvent; } } else { db.events.push(newEvent); } saveDB(); renderProfessorEventsAndAnnouncements(); } if (shareWhatsapp) { const formattedDate = formatDateStr(date); const msg = `*BEHRING JIU-JITSU - NOVO EVENTO* 🗓️\n\n*${title}*\nTipo: ${type}\nData: ${formattedDate} às ${time}h\n\nAcesse o aplicativo para confirmar presença:\nhttps://associacaobehring.netlify.app`; navigator.clipboard.writeText(msg).catch(err => console.error("Clipboard copy failed:", err)); alert("Notificação copiada para a área de transferência! Cole-a no grupo do WhatsApp a seguir."); window.open("https://chat.whatsapp.com/EAwwEG6l84XFLo5M0WChVo", "_blank"); } closeModal('add-event-modal'); document.getElementById('event-title').value = ''; document.getElementById('event-date').value = ''; document.getElementById('edit-event-id').value = ''; if (document.getElementById('event-share-whatsapp')) { document.getElementById('event-share-whatsapp').checked = false; } alert(isEdit ? 'Evento atualizado com sucesso!' : 'Novo evento agendado com sucesso!'); } async function deleteEvent(id) { if (confirm('Deseja realmente excluir este evento?')) { try { await supabaseClient.from('events').delete().eq('id', id); } catch (e) { console.error("Failed to delete event from Supabase", e); } db.events = db.events.filter(e => e.id !== id); saveDB(); renderProfessorEventsAndAnnouncements(); } } async function handleAddAnnouncement(event) { event.preventDefault(); const title = document.getElementById('ann-title').value.trim(); const content = document.getElementById('ann-content').value.trim(); const idVal = document.getElementById('edit-ann-id').value; const isEdit = idVal !== ''; const date = isEdit ? db.announcements.find(a => a.id === parseInt(idVal)).date : new Date().toISOString().split('T')[0]; const publishApp = document.getElementById('ann-publish-app') ? document.getElementById('ann-publish-app').checked : true; const shareWhatsapp = document.getElementById('ann-share-whatsapp') ? document.getElementById('ann-share-whatsapp').checked : false; const newAnn = { id: isEdit ? parseInt(idVal) : Date.now(), title, content, date }; if (publishApp) { try { await supabaseClient.from('announcements').upsert(newAnn); } catch (e) { console.error("Failed to save announcement to Supabase", e); } if (isEdit) { const idx = db.announcements.findIndex(a => a.id === newAnn.id); if (idx !== -1) { db.announcements[idx] = newAnn; } } else { db.announcements.push(newAnn); } saveDB(); renderProfessorEventsAndAnnouncements(); } if (shareWhatsapp) { const msg = `*BEHRING JIU-JITSU - COMUNICADO OFICIAL* 🥋\n\n*${title}*\n\n${content}\n\nLeia mais no aplicativo:\nhttps://associacaobehring.netlify.app`; navigator.clipboard.writeText(msg).catch(err => console.error("Clipboard copy failed:", err)); alert("Notificação copiada para a área de transferência! Cole-a no grupo do WhatsApp a seguir."); window.open("https://chat.whatsapp.com/EAwwEG6l84XFLo5M0WChVo", "_blank"); } closeModal('add-announcement-modal'); document.getElementById('ann-title').value = ''; document.getElementById('ann-content').value = ''; document.getElementById('edit-ann-id').value = ''; if (document.getElementById('ann-share-whatsapp')) { document.getElementById('ann-share-whatsapp').checked = false; } alert(isEdit ? 'Comunicado atualizado com sucesso!' : 'Aviso publicado com sucesso!'); } async function deleteAnnouncement(id) { if (confirm('Deseja realmente remover este aviso?')) { try { await supabaseClient.from('announcements').delete().eq('id', id); } catch (e) { console.error("Failed to delete announcement from Supabase", e); } db.announcements = db.announcements.filter(a => a.id !== id); saveDB(); renderProfessorEventsAndAnnouncements(); } } // ==================== STUDENT VIEW CONTROLLERS ==================== function renderStudentHome() { const student = currentSession.user; // Dynamically calculate attendance count from history const actualPresenceCount = db.history.filter(h => h.studentId === student.id).length; student.attendanceCount = actualPresenceCount; document.getElementById('student-welcome-title').textContent = `Olá, ${student.name.split(' ')[0]}!`; document.getElementById('student-total-classes').textContent = actualPresenceCount; document.getElementById('student-streak').textContent = `${student.streak}%`; const beltEl = document.getElementById('student-belt-name'); if (beltEl) { const sanitized = student.belt.toLowerCase().replace(/á/g, 'a').replace(/ê/g, 'e').replace(/\s+/g, '-'); beltEl.innerHTML = `${student.belt} ${student.degrees} ${student.degrees === 1 ? 'Grau' : 'Graus'}`; } // Warning Banner if selfie is missing const selfieAlert = document.getElementById('student-selfie-alert'); if (!student.selfie) { selfieAlert.style.display = 'flex'; } else { selfieAlert.style.display = 'none'; } // Latest Announcements on Student Home const annTimeline = document.getElementById('student-home-announcements'); annTimeline.innerHTML = ''; if (db.announcements.length === 0) { annTimeline.innerHTML = 'Nenhum aviso no mural.
'; } else { db.announcements.slice(0, 2).forEach(ann => { const div = document.createElement('div'); div.style.padding = '12px;'; div.style.borderLeft = '3px solid var(--accent-color)'; div.style.background = 'rgba(255, 255, 255, 0.01)'; div.style.marginBottom = '12px'; div.style.paddingLeft = '12px'; div.innerHTML = `${linkify(ann.content)}
`; annTimeline.appendChild(div); }); } // Upcoming Events on Student Home const evList = document.getElementById('student-home-events'); evList.innerHTML = ''; if (db.events.length === 0) { evList.innerHTML = 'Nenhum evento na agenda.
'; } else { db.events.slice(0, 2).forEach(ev => { const dateObj = new Date(ev.date + 'T00:00:00'); const day = String(dateObj.getDate()).padStart(2, '0'); const month = dateObj.toLocaleDateString('pt-BR', { month: 'short' }).slice(0, 3).toUpperCase(); const div = document.createElement('div'); div.className = 'event-item'; div.innerHTML = `${ev.type} • ${ev.time}h
Nenhum evento agendado.
'; } else { db.events.forEach(ev => { const dateObj = new Date(ev.date + 'T00:00:00'); const day = String(dateObj.getDate()).padStart(2, '0'); const month = dateObj.toLocaleDateString('pt-BR', { month: 'short' }).slice(0, 3).toUpperCase(); const div = document.createElement('div'); div.className = 'event-item'; div.innerHTML = `${ev.type} • Horário: ${ev.time}h
Nenhum aviso publicado no mural.
'; } else { db.announcements.forEach(ann => { const div = document.createElement('div'); div.style.padding = '16px 0'; div.style.borderBottom = '1px solid var(--border-color)'; div.innerHTML = `${linkify(ann.content)}
`; annContainer.appendChild(div); }); } } // Render schedules renderStudentSchedules(); } // ==================== MODAL CONTROLLERS ==================== function openModal(modalId) { document.getElementById(modalId).classList.add('active'); } function closeModal(modalId) { document.getElementById(modalId).classList.remove('active'); } function openCreateEventModal() { document.getElementById('edit-event-id').value = ''; document.getElementById('event-title').value = ''; document.getElementById('event-date').value = ''; document.getElementById('event-time').value = '19:00'; document.getElementById('event-type').value = 'Treino'; document.querySelector('#add-event-modal h3').textContent = 'Agendar Novo Evento'; document.querySelector('#add-event-modal button[type="submit"]').textContent = 'Publicar Evento'; openModal('add-event-modal'); } function openEditEventModal(id) { const ev = db.events.find(e => e.id === id); if (ev) { document.getElementById('edit-event-id').value = ev.id; document.getElementById('event-title').value = ev.title; document.getElementById('event-type').value = ev.type; document.getElementById('event-date').value = ev.date; document.getElementById('event-time').value = ev.time; document.querySelector('#add-event-modal h3').textContent = 'Editar Evento'; document.querySelector('#add-event-modal button[type="submit"]').textContent = 'Salvar Alterações'; openModal('add-event-modal'); } } function openCreateAnnouncementModal() { document.getElementById('edit-ann-id').value = ''; document.getElementById('ann-title').value = ''; document.getElementById('ann-content').value = ''; document.querySelector('#add-announcement-modal h3').textContent = 'Novo Aviso no Mural'; document.querySelector('#add-announcement-modal button[type="submit"]').textContent = 'Publicar Comunicado'; openModal('add-announcement-modal'); } function openEditAnnouncementModal(id) { const ann = db.announcements.find(a => a.id === id); if (ann) { document.getElementById('edit-ann-id').value = ann.id; document.getElementById('ann-title').value = ann.title; document.getElementById('ann-content').value = ann.content; document.querySelector('#add-announcement-modal h3').textContent = 'Editar Aviso'; document.querySelector('#add-announcement-modal button[type="submit"]').textContent = 'Salvar Alterações'; openModal('add-announcement-modal'); } } // Close modals clicking outside the content area window.onclick = function(event) { if (event.target.classList.contains('modal')) { event.target.classList.remove('active'); } }; // Help helper for graduation modal changes function updateGradModalBeltDisplay() { const belt = document.getElementById('grad-student-belt').value; const name = document.getElementById('grad-modal-student-name').textContent; const degrees = document.getElementById('grad-student-degrees').value; document.getElementById('grad-modal-student-info').textContent = `Faixa: ${belt} • ${degrees} Graus`; } // Student Profile Metadata View Controllers function renderStudentProfileDetails() { const student = currentSession.user; document.getElementById('profile-detail-email').textContent = student.email || 'Não informado'; document.getElementById('profile-detail-whatsapp').textContent = student.whatsapp || 'Não informado'; document.getElementById('profile-detail-address').textContent = student.address || 'Não informado'; document.getElementById('profile-detail-age').textContent = student.age ? `${student.age} anos` : 'Não informado'; const isMinor = student.age !== null && student.age < 18; document.getElementById('profile-detail-guardian').textContent = (isMinor && student.guardian) ? student.guardian : (isMinor ? 'Pendente' : 'Não aplicável (Maior de idade)'); let profText = 'Não informado'; if (student.profession) { profText = student.profession; if (student.profession.toLowerCase().includes('estudante') && student.schoolName) { profText += ` (${student.schoolName})`; } } document.getElementById('profile-detail-profession').textContent = profText; document.getElementById('profile-detail-objective').textContent = student.objective || 'Não informado'; document.getElementById('profile-detail-weekly-goal').textContent = student.weeklyGoal ? `${student.weeklyGoal}x por semana` : 'Não informado'; // Kimono Loan render const inactiveDiv = document.getElementById('kimono-loan-inactive'); const activeDiv = document.getElementById('kimono-loan-active'); if (student.hasLoan) { inactiveDiv.style.display = 'none'; activeDiv.style.display = 'flex'; document.getElementById('loan-kimono-brand').textContent = student.kimonoBrand || 'Não especificada'; document.getElementById('loan-kimono-size').textContent = student.kimonoSize || 'Não especificado'; document.getElementById('loan-kimono-date').textContent = student.kimonoDate ? formatDateStr(student.kimonoDate) : 'Não informada'; } else { inactiveDiv.style.display = 'block'; activeDiv.style.display = 'none'; } } // Edit Profile Form Handling function openEditProfileModal() { const student = currentSession.user; document.getElementById('edit-profile-name').value = student.name; document.getElementById('edit-profile-email').value = student.email || ''; document.getElementById('edit-profile-whatsapp').value = student.whatsapp || ''; document.getElementById('edit-profile-password').value = student.password || ''; document.getElementById('edit-profile-address').value = student.address || ''; document.getElementById('edit-profile-age').value = (student.age !== null && student.age !== undefined) ? student.age : ''; document.getElementById('edit-profile-guardian').value = student.guardian || ''; document.getElementById('edit-profile-profession').value = student.profession || ''; document.getElementById('edit-profile-school-name').value = student.schoolName || ''; document.getElementById('edit-profile-objective').value = student.objective || ''; document.getElementById('edit-profile-weekly-goal').value = student.weeklyGoal || 3; const hasLoanChk = document.getElementById('edit-profile-has-loan'); hasLoanChk.checked = student.hasLoan || false; document.getElementById('edit-profile-kimono-brand').value = student.kimonoBrand || ''; document.getElementById('edit-profile-kimono-size').value = student.kimonoSize || ''; document.getElementById('edit-profile-kimono-date').value = student.kimonoDate || ''; toggleGuardianInput(); toggleKimonoInputs(); openModal('edit-profile-modal'); } function toggleGuardianInput() { const age = parseInt(document.getElementById('edit-profile-age').value); const guardianGroup = document.getElementById('guardian-group'); if (age && age < 18) { guardianGroup.style.display = 'block'; } else { guardianGroup.style.display = 'none'; } } function toggleKimonoInputs() { const hasLoan = document.getElementById('edit-profile-has-loan').checked; const kimonoInputsDiv = document.getElementById('kimono-loan-inputs'); if (hasLoan) { kimonoInputsDiv.style.display = 'block'; } else { kimonoInputsDiv.style.display = 'none'; } } async function handleSaveProfile(event) { try { event.preventDefault(); const student = db.students.find(s => s.id === currentSession.user.id); if (student) { student.name = document.getElementById('edit-profile-name').value.trim(); student.email = document.getElementById('edit-profile-email').value.trim(); student.whatsapp = document.getElementById('edit-profile-whatsapp').value.trim(); student.password = document.getElementById('edit-profile-password').value.trim() || 'aluno123'; student.classTime = 'Qualquer Horário'; student.address = document.getElementById('edit-profile-address').value.trim(); const ageVal = document.getElementById('edit-profile-age').value; student.age = ageVal !== '' ? parseInt(ageVal) : null; const isMinor = student.age !== null && student.age < 18; if (isMinor) { student.guardian = document.getElementById('edit-profile-guardian').value.trim(); } else { student.guardian = ''; } student.profession = document.getElementById('edit-profile-profession').value.trim(); student.schoolName = document.getElementById('edit-profile-school-name').value.trim(); student.objective = document.getElementById('edit-profile-objective').value.trim(); student.weeklyGoal = parseInt(document.getElementById('edit-profile-weekly-goal').value) || 3; student.hasLoan = document.getElementById('edit-profile-has-loan').checked; if (student.hasLoan) { student.kimonoBrand = document.getElementById('edit-profile-kimono-brand').value.trim(); student.kimonoSize = document.getElementById('edit-profile-kimono-size').value.trim(); student.kimonoDate = document.getElementById('edit-profile-kimono-date').value; } else { student.kimonoBrand = ''; student.kimonoSize = ''; student.kimonoDate = ''; } let syncSuccess = true; try { await syncStudentToCloud(student); } catch (e) { console.error("Failed to sync profile updates to Supabase", e); syncSuccess = false; } saveDB(); // Update session currentSession.user = student; saveSessionToLocalStorage(); // Refresh views renderStudentProfile(); renderStudentHome(); setupUserInterface(); // Refresh headers closeModal('edit-profile-modal'); if (syncSuccess) { alert('Dados do seu perfil atualizados com sucesso!'); } else { alert('Aviso: Perfil atualizado localmente no navegador, mas falhou ao sincronizar com o Supabase.'); } } } catch (err) { console.error("Critical error in handleSaveProfile:", err); alert("Erro crítico ao salvar seu perfil: " + err.message); closeModal('edit-profile-modal'); } } // BJJ Study History View Controllers function renderStudentBJJHistory() { document.getElementById('student-bjj-history-text').textContent = db.bjjHistory.text; // Render video embeds const videosContainer = document.getElementById('student-bjj-history-videos'); videosContainer.innerHTML = ''; if (!db.bjjHistory.videos || db.bjjHistory.videos.length === 0) { videosContainer.innerHTML = 'Nenhum vídeo recomendado no momento.
'; } else { db.bjjHistory.videos.forEach(vid => { const card = document.createElement('div'); card.className = 'card'; card.style.padding = '12px'; card.style.background = 'var(--bg-secondary)'; const embedUrl = convertToEmbedUrl(vid.url); card.innerHTML = `