// app/Professor/Estagios/index.tsx
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { useEffect, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  Modal,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { useTheme } from '../../../themecontext';
import { supabase } from '../../lib/supabase';

// --- Interfaces ---
interface Aluno { id: string; nome: string; turma_curso: string; ano: number; }
interface Empresa { id: string; nome: string; morada: string; tutor_nome: string; tutor_telefone: string; curso: string; }
interface Estagio {
  id: string;
  aluno_id: string;
  empresa_id: string;
  data_inicio: string;
  data_fim: string;
  horas_diarias?: string;
  alunos: { nome: string; turma_curso: string; ano: number };
  empresas: { id: string; nome: string; morada: string; tutor_nome: string; tutor_telefone: string; curso: string };
}

export default function Estagios() {
  const router = useRouter();
  const { isDarkMode } = useTheme();
  const insets = useSafeAreaInsets();
  
  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#FFFFFF',
    card: isDarkMode ? '#161618' : '#F8FAFC',
    texto: isDarkMode ? '#F8FAFC' : '#1A365D',
    secundario: isDarkMode ? '#94A3B8' : '#718096',
    azul: azulEPVC,
    laranja: laranjaEPVC,
    azulSuave: isDarkMode ? 'rgba(35, 144, 166, 0.12)' : '#F0F9FA',
    vermelho: '#EF4444',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    overlay: 'rgba(26, 54, 93, 0.8)',
  }), [isDarkMode]);

  // Estados
  const [estagios, setEstagios] = useState<Estagio[]>([]);
  const [alunos, setAlunos] = useState<Aluno[]>([]);
  const [empresas, setEmpresas] = useState<Empresa[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalVisible, setModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [estagioParaApagar, setEstagioParaApagar] = useState<{id: string, nome: string} | null>(null);
  const [passo, setPasso] = useState(1);
  const [alunoSelecionado, setAlunoSelecionado] = useState<Aluno | null>(null);
  const [empresaSelecionada, setEmpresaSelecionada] = useState<Empresa | null>(null);
  const [editandoEstagio, setEditandoEstagio] = useState<Estagio | null>(null);
  const [dataInicio, setDataInicio] = useState('');
  const [dataFim, setDataFim] = useState('');
  const [searchMain, setSearchMain] = useState('');
  
  const [hManhaIni, setHManhaIni] = useState('');
  const [hManhaFim, setHManhaFim] = useState('');
  const [hTardeIni, setHTardeIni] = useState('');
  const [hTardeFim, setHTardeFim] = useState('');

  useEffect(() => { fetchDados(); }, []);

  const fetchDados = async () => {
    try {
      setLoading(true);
      const [resEstagios, resAlunos, resEmpresas] = await Promise.all([
        supabase.from('estagios').select('*, alunos(nome, turma_curso, ano), empresas(*)'),
        supabase.from('alunos').select('id, nome, turma_curso, ano').order('nome'),
        supabase.from('empresas').select('*').order('nome')
      ]);
      if (resEstagios.data) setEstagios(resEstagios.data);
      if (resAlunos.data) setAlunos(resAlunos.data);
      if (resEmpresas.data) setEmpresas(resEmpresas.data);
    } catch (e) { console.error(e); } finally { setLoading(false); }
  };

  const carregarHorariosEdicao = async (estagioId: string) => {
    const { data } = await supabase.from('horarios_estagio').select('*').eq('estagio_id', estagioId);
    if (data) {
      setHManhaIni(''); setHManhaFim(''); setHTardeIni(''); setHTardeFim('');
      data.forEach(h => {
        if (h.periodo === 'Manhã') {
          setHManhaIni(h.hora_inicio?.slice(0, 5) || '');
          setHManhaFim(h.hora_fim?.slice(0, 5) || '');
        } else if (h.periodo === 'Tarde') {
          setHTardeIni(h.hora_inicio?.slice(0, 5) || '');
          setHTardeFim(h.hora_fim?.slice(0, 5) || '');
        }
      });
    }
  };

  const totalHorasDiarias = useMemo(() => {
    const calcularMinutos = (ini: string, fim: string) => {
      if (!ini || !fim || !ini.includes(':') || !fim.includes(':')) return 0;
      const [hI, mI] = ini.split(':').map(Number);
      const [hF, mF] = fim.split(':').map(Number);
      const totalI = (hI || 0) * 60 + (mI || 0);
      const totalF = (hF || 0) * 60 + (mF || 0);
      return totalF > totalI ? totalF - totalI : 0;
    };
    const totalMinutos = calcularMinutos(hManhaIni, hManhaFim) + calcularMinutos(hTardeIni, hTardeFim);
    const h = Math.floor(totalMinutos / 60);
    const m = totalMinutos % 60;
    return m > 0 ? `${h}h${m}m` : `${h}h`;
  }, [hManhaIni, hManhaFim, hTardeIni, hTardeFim]);

  const formatarHoraPostgres = (time: string) => {
    if (!time || !time.includes(':')) return null;
    const [h, m] = time.split(':');
    return `${h.padStart(2, '0')}:${m.padStart(2, '0')}`;
  };

  const salvarEstagio = async () => {
    setLoading(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (empresaSelecionada) {
        await supabase.from('empresas').update({
          tutor_nome: empresaSelecionada.tutor_nome,
          tutor_telefone: empresaSelecionada.tutor_telefone
        }).eq('id', empresaSelecionada.id);
      }

      const payload = {
        aluno_id: alunoSelecionado?.id,
        empresa_id: empresaSelecionada?.id,
        professor_id: user?.id,
        data_inicio: dataInicio || new Date().toISOString().split('T')[0],
        data_fim: dataFim || null,
        horas_diarias: totalHorasDiarias,
        estado: 'Ativo',
      };

      const { data: estData, error: errE } = editandoEstagio 
        ? await supabase.from('estagios').update(payload).eq('id', editandoEstagio.id).select().single()
        : await supabase.from('estagios').insert([payload]).select().single();

      if (errE) throw errE;
      const currentId = editandoEstagio?.id || estData.id;

      await supabase.from('horarios_estagio').delete().eq('estagio_id', currentId);
      const novosHorarios = [];
      if (hManhaIni && hManhaFim) {
        novosHorarios.push({ estagio_id: currentId, periodo: 'Manhã', hora_inicio: formatarHoraPostgres(hManhaIni), hora_fim: formatarHoraPostgres(hManhaFim) });
      }
      if (hTardeIni && hTardeFim) {
        novosHorarios.push({ estagio_id: currentId, periodo: 'Tarde', hora_inicio: formatarHoraPostgres(hTardeIni), hora_fim: formatarHoraPostgres(hTardeFim) });
      }
      if (novosHorarios.length > 0) await supabase.from('horarios_estagio').insert(novosHorarios);

      handleFecharModal();
      fetchDados();
    } catch (error: any) { Alert.alert("Erro", error.message); } finally { setLoading(false); }
  };

  const confirmarEliminacao = async () => {
    if (!estagioParaApagar) return;
    setLoading(true);
    const { error } = await supabase.from('estagios').delete().eq('id', estagioParaApagar.id);
    if (!error) { setDeleteModalVisible(false); fetchDados(); }
    setLoading(false);
  };

  const handleFecharModal = () => {
    setModalVisible(false); setEditandoEstagio(null); setAlunoSelecionado(null); setEmpresaSelecionada(null);
    setDataInicio(''); setDataFim(''); setHManhaIni(''); setHManhaFim(''); setHTardeIni(''); setHTardeFim('');
    setPasso(1);
  };

  const estagiosFiltrados = useMemo(() => {
    const groups: Record<string, Estagio[]> = {};
    estagios.filter(e => e.alunos?.nome?.toLowerCase().includes(searchMain.toLowerCase())).forEach(e => {
      const chave = e.alunos ? `${e.alunos.ano}º ${e.alunos.turma_curso}` : 'Geral';
      if (!groups[chave]) groups[chave] = [];
      groups[chave].push(e);
    });
    return Object.keys(groups).map(titulo => ({ titulo, dados: groups[titulo] })).sort((a, b) => b.titulo.localeCompare(a.titulo));
  }, [estagios, searchMain]);

  return (
    <View style={{ flex: 1, backgroundColor: cores.fundo }}>
      <StatusBar barStyle={isDarkMode ? "light-content" : "dark-content"} />
      <SafeAreaView style={{ flex: 1 }} edges={['top']}>
        
        {/* HEADER EPVC */}
        <View style={styles.header}>
          <TouchableOpacity style={[styles.btnAction, { borderColor: cores.borda }]} onPress={() => router.back()}>
            <Ionicons name="chevron-back" size={24} color={cores.azul}/>
          </TouchableOpacity>
          <View style={{alignItems: 'center'}}>
            <Text style={[styles.headerTitle, { color: cores.texto }]}>Plano de Estágios</Text>
            <Text style={[styles.headerSubtitle, { color: cores.laranja }]}>{estagios.length} Alunos Colocados</Text>
          </View>
          <TouchableOpacity style={[styles.btnAction, { borderColor: cores.borda }]} onPress={fetchDados}>
            <Ionicons name="reload-outline" size={20} color={cores.azul}/>
          </TouchableOpacity>
        </View>

        <ScrollView contentContainerStyle={[styles.scroll, { paddingBottom: 120 }]} showsVerticalScrollIndicator={false}>
          {/* SEARCH MODERNO */}
          <View style={[styles.searchBar, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <Ionicons name="search-outline" size={20} color={cores.azul} />
            <TextInput 
              placeholder="Pesquisar por aluno ou turma..." 
              placeholderTextColor={cores.secundario} 
              style={[styles.searchInput, { color: cores.texto }]} 
              onChangeText={setSearchMain} 
            />
          </View>

          {loading ? (
             <ActivityIndicator size="large" color={cores.azul} style={{marginTop: 50}} />
          ) : estagiosFiltrados.map(grupo => (
            <View key={grupo.titulo} style={{ marginBottom: 25 }}>
              <View style={styles.sectionHeader}>
                <View style={[styles.sectionDot, { backgroundColor: cores.laranja }]} />
                <Text style={[styles.sectionTitle, { color: cores.texto }]}>{grupo.titulo}</Text>
                <View style={[styles.sectionLine, { backgroundColor: cores.borda }]} />
              </View>
              
              {grupo.dados.map(e => (
                <TouchableOpacity 
                    key={e.id}
                    activeOpacity={0.8}
                    style={[styles.estagioCard, { backgroundColor: cores.card, borderColor: cores.borda }]}
                    onPress={() => {
                        setEditandoEstagio(e);
                        setAlunoSelecionado(alunos.find(a => a.id === e.aluno_id) || null);
                        setEmpresaSelecionada(empresas.find(emp => emp.id === e.empresa_id) || null);
                        setDataInicio(e.data_inicio || ''); setDataFim(e.data_fim || '');
                        carregarHorariosEdicao(e.id);
                        setPasso(2); setModalVisible(true);
                    }}
                    onLongPress={() => { 
                        setEstagioParaApagar({ id: e.id, nome: e.alunos?.nome }); 
                        setDeleteModalVisible(true); 
                    }}
                >
                    <View style={styles.cardHeader}>
                        <View style={[styles.avatar, { backgroundColor: cores.azulSuave }]}>
                            <Text style={[styles.avatarText, { color: cores.azul }]}>{e.alunos?.nome.charAt(0)}</Text>
                        </View>
                        <View style={{flex:1}}>
                            <Text style={[styles.alunoNome, { color: cores.texto }]}>{e.alunos?.nome}</Text>
                            <View style={styles.empresaRow}>
                                <Ionicons name="business-outline" size={13} color={cores.laranja} />
                                <Text style={[styles.empresaText, { color: cores.secundario }]} numberOfLines={1}>{e.empresas?.nome}</Text>
                            </View>
                        </View>
                        <View style={[styles.timeBadge, { backgroundColor: cores.fundo, borderColor: cores.borda }]}>
                            <Ionicons name="time-outline" size={12} color={cores.azul} />
                            <Text style={[styles.timeText, { color: cores.texto }]}>{e.horas_diarias}</Text>
                        </View>
                    </View>
                </TouchableOpacity>
              ))}
            </View>
          ))}
        </ScrollView>

        {/* FAB EPVC */}
        <TouchableOpacity 
          style={[styles.fab, { backgroundColor: cores.laranja, bottom: insets.bottom + 20 }]} 
          onPress={() => { setPasso(1); setModalVisible(true); }}
        >
          <Ionicons name="add" size={28} color="#fff" />
          <Text style={styles.fabText}>Novo Plano</Text>
        </TouchableOpacity>
      </SafeAreaView>

      {/* MODAL DE CRIAÇÃO/EDIÇÃO */}
      <Modal visible={modalVisible} animationType="slide" transparent>
        <View style={[styles.modalOverlay, { backgroundColor: cores.overlay }]}>
          <View style={[styles.modalContent, { backgroundColor: cores.card, paddingBottom: insets.bottom + 20 }]}>
            <View style={styles.modalIndicator} />
            <View style={styles.modalHeader}>
              <View>
                <Text style={[styles.modalTitle, { color: cores.texto }]}>{passo === 1 ? "Vinculação" : "Configuração"}</Text>
                <Text style={[styles.modalSub, { color: cores.laranja }]}>Passo {passo} de 2</Text>
              </View>
              <TouchableOpacity onPress={handleFecharModal} style={[styles.closeBtn, {backgroundColor: cores.fundo}]}>
                <Ionicons name="close" size={22} color={cores.texto} />
              </TouchableOpacity>
            </View>

            <ScrollView showsVerticalScrollIndicator={false} nestedScrollEnabled>
              {passo === 1 ? (
                <View style={{ gap: 20 }}>
                  <Text style={styles.inputLabel}>Selecionar Estagiário</Text>
                  <View style={[styles.pickerContainer, { borderColor: cores.borda, maxHeight: 220 }]}>
                    <ScrollView nestedScrollEnabled>
                      {Object.entries(alunos.reduce((acc, a) => {
                        const key = `${a.ano}º ${a.turma_curso}`.trim().toUpperCase();
                        if (!acc[key]) acc[key] = []; acc[key].push(a); return acc;
                      }, {} as Record<string, Aluno[]>))
                      .sort(([a], [b]) => a.localeCompare(b))
                      .map(([turma, lista]) => (
                        <View key={turma}>
                          <View style={[styles.groupHeader, { backgroundColor: cores.fundo }]}><Text style={[styles.groupHeaderText, { color: cores.secundario }]}>{turma}</Text></View>
                          {lista.map(a => (
                            <TouchableOpacity 
                                key={a.id} 
                                style={[styles.pickerItem, alunoSelecionado?.id === a.id && { backgroundColor: cores.azulSuave }]} 
                                onPress={() => setAlunoSelecionado(a)}
                            >
                              <Text style={[styles.pickerItemText, { color: cores.texto }]}>{a.nome}</Text>
                              {alunoSelecionado?.id === a.id && <Ionicons name="checkmark-circle" size={18} color={cores.azul} />}
                            </TouchableOpacity>
                          ))}
                        </View>
                      ))}
                    </ScrollView>
                  </View>

                  <Text style={styles.inputLabel}>Entidade de Acolhimento</Text>
                  <View style={[styles.pickerContainer, { borderColor: cores.borda, maxHeight: 220 }]}>
                    <ScrollView nestedScrollEnabled>
                      {Object.entries(empresas.reduce((acc, e) => {
                        const key = (e.curso || 'GERAL').trim().toUpperCase();
                        if (!acc[key]) acc[key] = []; acc[key].push(e); return acc;
                      }, {} as Record<string, Empresa[]>))
                      .sort(([a], [b]) => a.localeCompare(b))
                      .map(([curso, lista]) => (
                        <View key={curso}>
                          <View style={[styles.groupHeader, { backgroundColor: cores.fundo }]}><Text style={[styles.groupHeaderText, { color: cores.secundario }]}>{curso}</Text></View>
                          {lista.map(emp => (
                            <TouchableOpacity 
                                key={emp.id} 
                                style={[styles.pickerItem, empresaSelecionada?.id === emp.id && { backgroundColor: cores.azulSuave }]} 
                                onPress={() => setEmpresaSelecionada(emp)}
                            >
                              <Text style={[styles.pickerItemText, { color: cores.texto }]}>{emp.nome}</Text>
                              {empresaSelecionada?.id === emp.id && <Ionicons name="checkmark-circle" size={18} color={cores.azul} />}
                            </TouchableOpacity>
                          ))}
                        </View>
                      ))}
                    </ScrollView>
                  </View>
                </View>
              ) : (
                <View style={{ gap: 18 }}>
                  <View style={[styles.modernGroup, { backgroundColor: cores.fundo, borderColor: cores.borda }]}>
                    <Text style={[styles.groupTitle, { color: cores.azul }]}>Cronograma</Text>
                    <View style={styles.rowInputs}>
                        <View style={{flex:1}}><Text style={styles.miniLabel}>DATA INÍCIO</Text><TextInput style={[styles.modernInput, { color: cores.texto, backgroundColor: cores.card }]} value={dataInicio} onChangeText={setDataInicio} placeholder="AAAA-MM-DD"/></View>
                        <View style={{flex:1}}><Text style={styles.miniLabel}>DATA FIM (PREV.)</Text><TextInput style={[styles.modernInput, { color: cores.texto, backgroundColor: cores.card }]} value={dataFim} onChangeText={setDataFim} placeholder="AAAA-MM-DD"/></View>
                    </View>
                  </View>

                  <View style={[styles.modernGroup, { backgroundColor: cores.fundo, borderColor: cores.borda }]}>
                    <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                        <Text style={[styles.groupTitle, { color: cores.azul }]}>Horário de Trabalho</Text>
                        <View style={[styles.totalBadge, { backgroundColor: cores.laranja }]}><Text style={styles.totalText}>{totalHorasDiarias}/dia</Text></View>
                    </View>
                    <View style={styles.tabelaRow}>
                      <Text style={[styles.tabelaLabel, {color: cores.texto}]}>Manhã</Text>
                      <TextInput style={[styles.tabelaInput, {color: cores.texto, backgroundColor: cores.card}]} value={hManhaIni} onChangeText={setHManhaIni} placeholder="09:00" />
                      <TextInput style={[styles.tabelaInput, {color: cores.texto, backgroundColor: cores.card}]} value={hManhaFim} onChangeText={setHManhaFim} placeholder="13:00" />
                    </View>
                    <View style={styles.tabelaRow}>
                      <Text style={[styles.tabelaLabel, {color: cores.texto}]}>Tarde</Text>
                      <TextInput style={[styles.tabelaInput, {color: cores.texto, backgroundColor: cores.card}]} value={hTardeIni} onChangeText={setHTardeIni} placeholder="14:00" />
                      <TextInput style={[styles.tabelaInput, {color: cores.texto, backgroundColor: cores.card}]} value={hTardeFim} onChangeText={setHTardeFim} placeholder="18:00" />
                    </View>
                  </View>

                  <View style={[styles.modernGroup, { backgroundColor: cores.fundo, borderColor: cores.borda }]}>
                    <Text style={[styles.groupTitle, { color: cores.azul }]}>Responsável na Empresa</Text>
                    <TextInput style={[styles.modernInput, {color: cores.texto, backgroundColor: cores.card}]} value={empresaSelecionada?.tutor_nome} onChangeText={(t) => setEmpresaSelecionada(p => p ? {...p, tutor_nome: t} : p)} placeholder="Nome do Tutor"/>
                    <TextInput style={[styles.modernInput, {color: cores.texto, backgroundColor: cores.card, marginTop: 10}]} value={empresaSelecionada?.tutor_telefone} onChangeText={(t) => setEmpresaSelecionada(p => p ? {...p, tutor_telefone: t} : p)} keyboardType="phone-pad" placeholder="Telemóvel"/>
                  </View>
                </View>
              )}
            </ScrollView>

            <View style={styles.modalFooter}>
              {passo === 2 && (
                <TouchableOpacity onPress={() => setPasso(1)} style={[styles.btnModalSec, { borderColor: cores.borda }]}>
                    <Text style={{color: cores.texto, fontWeight: '800'}}>VOLTAR</Text>
                </TouchableOpacity>
              )}
              <TouchableOpacity 
                onPress={() => {
                  if(passo === 1) {
                    if(alunoSelecionado && empresaSelecionada) setPasso(2);
                    else Alert.alert("Atenção", "Selecione o aluno e a empresa.");
                  } else salvarEstagio();
                }} 
                style={[styles.btnModalPri, { backgroundColor: cores.azul }]}
              >
                {loading ? <ActivityIndicator color="#fff" /> : <Text style={{color:'#fff', fontWeight: '900'}}>{passo === 1 ? "CONTINUAR" : "FINALIZAR"}</Text>}
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>

      {/* DELETE MODAL */}
      <Modal visible={deleteModalVisible} transparent animationType="fade">
        <View style={[styles.modalOverlay, { backgroundColor: cores.overlay }]}>
          <View style={[styles.deleteCard, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <View style={[styles.deleteIconBg, { backgroundColor: isDarkMode ? '#2D1616' : '#FFF5F5' }]}>
                <Ionicons name="warning" size={35} color={cores.vermelho} />
            </View>
            <Text style={[styles.deleteTitle, { color: cores.texto }]}>Cancelar Estágio?</Text>
            <Text style={[styles.deleteSubtitle, { color: cores.secundario }]}>
                Irá remover o vínculo de <Text style={{fontWeight: '900', color: cores.texto}}>{estagioParaApagar?.nome}</Text>. Esta ação é irreversível.
            </Text>
            <View style={styles.deleteFooter}>
              <TouchableOpacity style={[styles.deleteBtnCancel, { backgroundColor: cores.fundo }]} onPress={() => setDeleteModalVisible(false)}>
                <Text style={[styles.deleteBtnText, { color: cores.texto }]}>FECHAR</Text>
              </TouchableOpacity>
              <TouchableOpacity style={[styles.deleteBtnConfirm, { backgroundColor: cores.vermelho }]} onPress={confirmarEliminacao}>
                <Text style={[styles.deleteBtnText, { color: '#fff' }]}>ELIMINAR</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 24, paddingVertical: 15 },
  headerTitle: { fontSize: 22, fontWeight: '900', letterSpacing: -0.5 },
  headerSubtitle: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5 },
  btnAction: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  scroll: { paddingHorizontal: 24, paddingTop: 10 },
  searchBar: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, height: 56, borderRadius: 20, borderWidth: 1.5, marginBottom: 25 },
  searchInput: { flex: 1, marginLeft: 12, fontSize: 14, fontWeight: '700' },
  sectionHeader: { flexDirection: 'row', alignItems: 'center', marginTop: 10, marginBottom: 18 },
  sectionDot: { width: 8, height: 8, borderRadius: 4, marginRight: 10 },
  sectionTitle: { fontSize: 13, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 0.8 },
  sectionLine: { flex: 1, height: 1, marginLeft: 15, opacity: 0.5 },
  estagioCard: { padding: 18, borderRadius: 28, borderWidth: 1, marginBottom: 14, elevation: 3, shadowColor: '#000', shadowOpacity: 0.04, shadowRadius: 10 },
  cardHeader: { flexDirection: 'row', alignItems: 'center', gap: 14 },
  avatar: { width: 48, height: 48, borderRadius: 16, justifyContent: 'center', alignItems: 'center' },
  avatarText: { fontSize: 20, fontWeight: '900' },
  alunoNome: { fontSize: 16, fontWeight: '800', letterSpacing: -0.3 },
  empresaRow: { flexDirection: 'row', alignItems: 'center', gap: 5, marginTop: 3 },
  empresaText: { fontSize: 13, fontWeight: '600' },
  timeBadge: { flexDirection: 'row', alignItems: 'center', gap: 5, paddingHorizontal: 10, paddingVertical: 6, borderRadius: 12, borderWidth: 1 },
  timeText: { fontSize: 11, fontWeight: '900' },
  fab: { position: 'absolute', right: 24, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 22, paddingVertical: 16, borderRadius: 22, elevation: 8, shadowColor: '#E38E00', shadowOpacity: 0.3, shadowRadius: 10 },
  fabText: { color: '#fff', fontSize: 15, fontWeight: '900', marginLeft: 10, textTransform: 'uppercase', letterSpacing: 0.5 },
  modalOverlay: { flex: 1, justifyContent: 'flex-end' },
  modalContent: { borderTopLeftRadius: 45, borderTopRightRadius: 45, padding: 28, height: '92%', width: '100%' },
  modalIndicator: { width: 45, height: 5, backgroundColor: 'rgba(0,0,0,0.1)', borderRadius: 10, alignSelf: 'center', marginBottom: 20 },
  modalHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 25 },
  modalTitle: { fontSize: 24, fontWeight: '900', letterSpacing: -0.5 },
  modalSub: { fontSize: 12, fontWeight: '800', textTransform: 'uppercase', marginTop: 2 },
  closeBtn: { width: 40, height: 40, borderRadius: 14, justifyContent: 'center', alignItems: 'center' },
  inputLabel: { fontSize: 11, fontWeight: '900', textTransform: 'uppercase', color: '#64748B', marginBottom: 10, marginLeft: 5, letterSpacing: 0.5 },
  pickerContainer: { borderWidth: 1.5, borderRadius: 24, overflow: 'hidden' },
  groupHeader: { paddingVertical: 10, paddingHorizontal: 18 },
  groupHeaderText: { fontSize: 10, fontWeight: '900', textTransform: 'uppercase' },
  pickerItem: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 18, borderBottomWidth: 1, borderColor: 'rgba(0,0,0,0.03)' },
  pickerItemText: { fontSize: 15, fontWeight: '700' },
  modernGroup: { padding: 20, borderRadius: 30, borderWidth: 1, marginBottom: 18 },
  groupTitle: { fontSize: 12, fontWeight: '900', textTransform: 'uppercase', marginBottom: 15, letterSpacing: 0.5 },
  rowInputs: { flexDirection: 'row', gap: 15 },
  miniLabel: { fontSize: 9, fontWeight: '900', color: '#94A3B8', marginBottom: 6, marginLeft: 2 },
  modernInput: { paddingVertical: 14, paddingHorizontal: 16, borderRadius: 16, fontSize: 14, fontWeight: '700', borderWidth: 1, borderColor: 'rgba(0,0,0,0.03)' },
  tabelaRow: { flexDirection: 'row', alignItems: 'center', gap: 12, marginBottom: 12 },
  tabelaLabel: { flex: 1, fontSize: 14, fontWeight: '800' },
  tabelaInput: { flex: 1, padding: 14, borderRadius: 16, textAlign: 'center', fontSize: 14, fontWeight: '800', borderWidth: 1, borderColor: 'rgba(0,0,0,0.03)' },
  totalBadge: { paddingHorizontal: 10, paddingVertical: 4, borderRadius: 8 },
  totalText: { color: '#fff', fontSize: 11, fontWeight: '900' },
  modalFooter: { flexDirection: 'row', gap: 15, marginTop: 15 },
  btnModalPri: { flex: 2, height: 62, borderRadius: 22, justifyContent: 'center', alignItems: 'center' },
  btnModalSec: { flex: 1, height: 62, borderRadius: 22, justifyContent: 'center', alignItems: 'center', borderWidth: 1.5 },
  deleteCard: { width: '85%', borderRadius: 40, padding: 30, alignItems: 'center', borderWidth: 1, alignSelf: 'center' },
  deleteIconBg: { width: 80, height: 80, borderRadius: 25, justifyContent: 'center', alignItems: 'center', marginBottom: 20 },
  deleteTitle: { fontSize: 22, fontWeight: '900', marginBottom: 12 },
  deleteSubtitle: { fontSize: 15, textAlign: 'center', lineHeight: 22, marginBottom: 30 },
  deleteFooter: { flexDirection: 'row', gap: 15, width: '100%' },
  deleteBtnCancel: { flex: 1, height: 55, borderRadius: 18, justifyContent: 'center', alignItems: 'center' },
  deleteBtnConfirm: { flex: 1, height: 55, borderRadius: 18, justifyContent: 'center', alignItems: 'center' },
  deleteBtnText: { fontSize: 14, fontWeight: '900' },
});