import React, { useState, useEffect, useCallback } from 'react';
import { SchoolData, PreMatriculaCampo, PreMatriculaConfig, PreMatriculaInscricao } from '../types';
import {
  Plus, Trash2, Save, Eye, EyeOff, Download, GripVertical, Link2,
  ClipboardPen, Copy, Check, ChevronDown, ChevronRight, Users, RefreshCw,
  FileText, X, Settings2, ArrowLeft, ExternalLink, AlertCircle, UserCheck, Edit, Upload,
  MessageSquare, Paperclip, Smile, Image
} from 'lucide-react';
import { useDialog } from '../DialogContext';

interface Props {
  data: SchoolData;
  updateData: (d: Partial<SchoolData>) => void;
  onConvert?: (preData: any) => void;
}

const FIELD_TYPES: Record<string, string> = {
  text: 'Texto', email: 'Email', phone: 'Telefone', cpf: 'CPF',
  date: 'Data', select: 'Seleção', textarea: 'Texto Longo', number: 'Número',
  file: 'Imagem / Documento (Upload)',
  banner: 'Folder / Panfleto de Promoção (Banner)'
};

const getFriendlyLabel = (key: string, value: any): string => {
  if (key === 'da80bac4-4018-4ee9-a9c4-a25551411269' || key === 'da80bac4-4018-4ee9-a9c4-a25551411269'.replace(/-/g, '')) return 'Sexo';
  if (key === '09e08119-02e1-49cf-8a48-eb7b51a35758' || key === '09e08119-02e1-49cf-8a48-eb7b51a35758'.replace(/-/g, '')) return 'Sexo';
  if (key === '82bcc4ce-8ece-4a1b-8131-e64585119cf4' || key === '82bcc4ce-8ece-4a1b-8131-e64585119cf4'.replace(/-/g, '')) return 'CPF';
  
  const valStr = String(value || '');
  if (valStr === 'Feminino' || valStr === 'Masculino' || valStr === 'Outro') {
    return 'Sexo';
  }
  if (/^\d{11}$/.test(valStr) || /^\d{3}\.\d{3}\.\d{3}-\d{2}$/.test(valStr)) {
    return 'CPF';
  }
  return 'Campo Excluído';
};

const DAY_NAMES = ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'];

const PreMatricula: React.FC<Props> = ({ data, onConvert }) => {
  const { showAlert } = useDialog();
  const [config, setConfig] = useState<PreMatriculaConfig | null>(null);
  const [campos, setCampos] = useState<PreMatriculaCampo[]>([]);
  const [todosCampos, setTodosCampos] = useState<PreMatriculaCampo[]>([]);
  const [inscricoes, setInscricoes] = useState<PreMatriculaInscricao[]>([]);
  const [turmas, setTurmas] = useState<any[]>([]);
  const [activeTab, setActiveTab] = useState<'editor' | 'inscricoes'>('editor');
  const [isSaving, setIsSaving] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [copied, setCopied] = useState(false);
  const [selectedTurma, setSelectedTurma] = useState<string>('all');
  const [editingCampo, setEditingCampo] = useState<PreMatriculaCampo | null>(null);
  const [showNewField, setShowNewField] = useState(false);
  const [newField, setNewField] = useState({ label: '', tipo: 'text', placeholder: '', obrigatorio: false, opcoes: '' });
  const [uploadProgress, setUploadProgress] = useState<number | null>(null);

  const [showMassModal, setShowMassModal] = useState(false);
  const [targetType, setTargetType] = useState('todos');
  const [targetId, setTargetId] = useState('');
  const [messageText, setMessageText] = useState('');
  const [isSendingMass, setIsSendingMass] = useState(false);
  const [massDelay, setMassDelay] = useState('60');
  const [massAttachment, setMassAttachment] = useState<File | null>(null);
  const [showMassEmojis, setShowMassEmojis] = useState(false);
  const commonEmojis = ['😀', '😂', '🥰', '😎', '🎉', '👍', '🙏', '❤️', '🔥', '🚀', '✅', '❌', '⚠️', '💡', '🎓', '🏫', '📚', '📖', '✏️', '📝', '🎒', '💻', '🧠', '🤓', '🥇'];

  const normalizeLineBreaks = (text: string) => text.replace(/\r\n/g, '\n');

  const handleMassSend = async () => {
    if (!messageText.trim()) {
      return showAlert('Aviso', 'Digite uma mensagem para enviar.', 'warning');
    }

    let targetStudents = [];

    if (targetType === 'todos') {
      targetStudents = inscricoes;
    } else if (targetType === 'turma') {
      if (!targetId) return showAlert('Aviso', 'Selecione uma turma.', 'warning');
      targetStudents = inscricoes.filter(p => p.turmaId === targetId);
    } else if (targetType === 'aluno') {
      if (!targetId) return showAlert('Aviso', 'Selecione uma pré-matrícula.', 'warning');
      targetStudents = inscricoes.filter(p => p.id === targetId);
    }

    const validPre = targetStudents.filter(p => p.telefone);
    if (validPre.length === 0) {
      return showAlert('Erro', 'Nenhuma pré-matrícula com telefone válido foi selecionada.', 'error');
    }

    const payloadAlunos = validPre.map(p => ({
      nome: p.nome.split(' ')[0],
      telefone: p.telefone,
      matricula: 'Pré-Matrícula'
    }));

    setIsSendingMass(true);
    try {
      const formData = new FormData();
      formData.append('alunos', JSON.stringify(payloadAlunos));
      formData.append('mensagem', normalizeLineBreaks(messageText));
      formData.append('delay', String(parseInt(massDelay) || 60));
      if (massAttachment) {
        formData.append('attachment', massAttachment);
      }

      const resp = await fetch('/api/enviar-massa', {
        method: 'POST',
        body: formData
      });
      const resData = await resp.json();
      
      if (resp.ok) {
        setMessageText('');
        setTargetId('');
        setMassAttachment(null);
        setShowMassModal(false);
        showAlert('Sucesso', 'Disparo iniciado no servidor!', 'success');
      } else {
        showAlert('Erro', resData.error || 'Erro ao iniciar disparo.', 'error');
      }
    } catch (e) {
      showAlert('Erro', 'Erro de conexão.', 'error');
    } finally {
      setIsSendingMass(false);
    }
  };

  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const [cfgRes, camposRes, inscRes, turmasRes] = await Promise.all([
        fetch('/api/prematricula/config'),
        fetch('/api/prematricula/campos'),
        fetch('/api/prematricula/inscricoes'),
        fetch('/api/turmas')
      ]);
      if (cfgRes.ok) { const j = await cfgRes.json(); setConfig(j.config); }
      if (camposRes.ok) { const j = await camposRes.json(); setCampos(j.campos || []); setTodosCampos(j.todosCampos || j.campos || []); }
      if (inscRes.ok) { const j = await inscRes.json(); setInscricoes(j.inscricoes || []); }
      if (turmasRes.ok) { const j = await turmasRes.json(); setTurmas(j.turmas || []); }
    } catch (e) { console.error(e); }
    finally { setIsLoading(false); }
  }, []);

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

  const saveConfig = async () => {
    if (!config) return;
    setIsSaving(true);
    try {
      await fetch('/api/prematricula/config', {
        method: 'PUT', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config)
      });
    } catch (e) { console.error(e); }
    finally { setIsSaving(false); }
  };

  const togglePublish = async () => {
    if (!config) return;
    const newStatus = config.status === 'published' ? 'draft' : 'published';
    const updated = { ...config, status: newStatus as 'draft' | 'published' };
    setConfig(updated);
    await fetch('/api/prematricula/config', {
      method: 'PUT', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updated)
    });
  };

  const addField = async () => {
    let label = newField.label.trim();
    if (newField.tipo === 'banner' && !label) {
      label = 'Folder Promocional';
    }
    if (!label) return;
    const campo = {
      id: crypto.randomUUID(),
      label: label,
      tipo: newField.tipo,
      placeholder: newField.placeholder,
      obrigatorio: newField.obrigatorio,
      opcoes: newField.tipo === 'select' ? newField.opcoes.split(',').map(o => o.trim()).filter(Boolean) : [],
      ordem: campos.length,
      ativo: true
    };
    try {
      const res = await fetch('/api/prematricula/campos', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(campo)
      });
      if (res.ok) {
        setCampos(prev => [...prev, campo as PreMatriculaCampo]);
        setNewField({ label: '', tipo: 'text', placeholder: '', obrigatorio: false, opcoes: '' });
        setShowNewField(false);
      }
    } catch (e) { console.error(e); }
  };

  const deleteField = async (id: string) => {
    try {
      const res = await fetch(`/api/prematricula/campos/${id}`, { method: 'DELETE' });
      if (res.ok) setCampos(prev => prev.filter(c => c.id !== id));
    } catch (e) { console.error(e); }
  };

  const updateField = async (campo: PreMatriculaCampo) => {
    let label = campo.label.trim();
    if (campo.tipo === 'banner' && !label) {
      label = 'Folder Promocional';
    }
    const updatedCampo = { ...campo, label };
    try {
      await fetch(`/api/prematricula/campos/${campo.id}`, {
        method: 'PUT', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updatedCampo)
      });
      setCampos(prev => prev.map(c => c.id === campo.id ? updatedCampo : c));
      setEditingCampo(null);
    } catch (e) { console.error(e); }
  };

  const moveField = async (index: number, direction: 'up' | 'down') => {
    const targetIndex = direction === 'up' ? index - 1 : index + 1;
    if (targetIndex < 0 || targetIndex >= campos.length) return;
    
    const reordered = [...campos].sort((a, b) => a.ordem - b.ordem);
    const temp = reordered[index];
    reordered[index] = reordered[targetIndex];
    reordered[targetIndex] = temp;
    
    const updated = reordered.map((c, i) => ({ ...c, ordem: i }));
    setCampos(updated);
    
    try {
      await fetch('/api/prematricula/campos/reordenar', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ordem: updated.map(c => ({ id: c.id, ordem: c.ordem }))
        })
      });
    } catch (e) {
      console.error(e);
    }
  };

  const deleteInscricao = async (id: string) => {
    try {
      const res = await fetch(`/api/prematricula/inscricoes/${id}`, { method: 'DELETE' });
      if (res.ok) setInscricoes(prev => prev.filter(i => i.id !== id));
    } catch (e) { console.error(e); }
  };

  const exportCSV = (turmaId: string) => {
    const filtered = turmaId === 'all' ? inscricoes : inscricoes.filter(i => i.turmaId === turmaId);
    if (filtered.length === 0) return;
    const allKeys = new Set<string>();
    filtered.forEach(i => Object.keys(i.respostas || {}).forEach(k => allKeys.add(k)));
    const headers = ['Nome', 'Email', 'Telefone', 'Turma', 'Status', 'Data', ...Array.from(allKeys).map(k => {
      const field = todosCampos.find(c => c.id === k);
      return field ? field.label : getFriendlyLabel(k, null);
    })];
    const rows = filtered.map(i => [
      i.nome, i.email, i.telefone, i.turmaNome, i.status,
      new Date(i.createdAt).toLocaleDateString('pt-BR'),
      ...Array.from(allKeys).map(k => {
        const val = (i.respostas || {})[k] || '';
        return typeof val === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(val)
          ? val.split('-').reverse().join('/')
          : val;
      })
    ]);
    const csv = [headers.join(';'), ...rows.map(r => r.join(';'))].join('\n');
    const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url;
    const turmaName = turmaId === 'all' ? 'todas' : turmas.find(t => t.id === turmaId)?.nome || turmaId;
    a.download = `pre-matriculas-${turmaName}.csv`; a.click();
    URL.revokeObjectURL(url);
  };

  const copyLink = () => {
    if (!config) return;
    const url = `${window.location.origin}/${config.slug}`;
    navigator.clipboard.writeText(url);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const filteredInscricoes = selectedTurma === 'all'
    ? inscricoes : inscricoes.filter(i => i.turmaId === selectedTurma);

  const turmasComInscritos = turmas.map(t => ({
    ...t, count: inscricoes.filter(i => i.turmaId === t.id).length
  }));

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <RefreshCw size={32} className="text-indigo-600 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-in fade-in duration-500 pb-10">
      {/* Header */}
      <header className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-3xl font-extrabold text-slate-900 tracking-tight flex items-center gap-3">
            <ClipboardPen className="text-indigo-600" size={28} />
            Pré-Matrícula
          </h2>
          <p className="text-slate-500 font-medium">Gerencie o formulário público de pré-matrícula e visualize inscrições.</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={togglePublish}
            className={`flex items-center gap-2 px-4 py-2.5 rounded-xl font-bold text-sm transition-all active:scale-95 shadow-sm ${
              config?.status === 'published'
                ? 'bg-emerald-600 text-white hover:bg-emerald-700'
                : 'bg-amber-500 text-white hover:bg-amber-600'
            }`}
          >
            {config?.status === 'published' ? <><Eye size={18} /> Publicado</> : <><EyeOff size={18} /> Rascunho</>}
          </button>
          <button onClick={copyLink}
            className="flex items-center gap-2 px-4 py-2.5 bg-slate-100 text-slate-700 rounded-xl font-bold text-sm hover:bg-slate-200 transition-all active:scale-95"
          >
            {copied ? <><Check size={18} className="text-emerald-600" /> Copiado!</> : <><Link2 size={18} /> Copiar Link</>}
          </button>
        </div>
      </header>

      {/* Tab Switcher */}
      <div className="flex bg-slate-100 p-1 rounded-xl border border-slate-200 w-fit">
        <button onClick={() => setActiveTab('editor')}
          className={`px-5 py-2.5 rounded-lg text-sm font-bold transition-all ${activeTab === 'editor' ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
        >
          <Settings2 size={16} className="inline mr-2 -mt-0.5" />Editor do Formulário
        </button>
        <button onClick={() => setActiveTab('inscricoes')}
          className={`px-5 py-2.5 rounded-lg text-sm font-bold transition-all ${activeTab === 'inscricoes' ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
        >
          <Users size={16} className="inline mr-2 -mt-0.5" />Inscrições ({inscricoes.length})
        </button>
      </div>

      {activeTab === 'editor' ? (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Left: Config */}
          <div className="lg:col-span-1 space-y-6">
            <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm space-y-5">
              <h3 className="text-sm font-black text-slate-800 uppercase tracking-widest">Configurações</h3>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Título da Página</label>
                <input className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium"
                  value={config?.titulo || ''} onChange={e => setConfig(prev => prev ? { ...prev, titulo: e.target.value } : prev)} />
              </div>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Descrição</label>
                <textarea className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium resize-none" rows={3}
                  value={config?.descricao || ''} onChange={e => setConfig(prev => prev ? { ...prev, descricao: e.target.value } : prev)} />
              </div>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Slug do Link Personalizado</label>
                <div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg overflow-hidden">
                  <span className="px-3 text-xs text-slate-400 font-mono whitespace-nowrap">/</span>
                  <input className="flex-1 px-2 py-3 bg-transparent focus:outline-none text-sm font-mono font-bold text-indigo-700"
                    value={config?.slug || ''} 
                    onChange={e => setConfig(prev => prev ? { ...prev, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '') } : prev)} 
                  />
                </div>
              </div>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Cor Primária</label>
                <div className="flex items-center gap-3">
                  <input type="color" className="w-10 h-10 rounded-lg border border-slate-200 cursor-pointer"
                    value={config?.corPrimaria || '#4f46e5'} onChange={e => setConfig(prev => prev ? { ...prev, corPrimaria: e.target.value } : prev)} />
                  <span className="text-xs font-mono text-slate-500">{config?.corPrimaria}</span>
                </div>
              </div>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-2">Turmas Disponíveis no Formulário</label>
                
                {/* Selected Classes Chips with grey Tags/Chips UI */}
                <div className="flex flex-wrap gap-2 mb-3 p-2 bg-slate-100 border border-slate-200 rounded-xl min-h-[44px] items-center">
                  {(config?.turmasPermitidas || []).map(id => {
                    const turma = turmas.find(t => t.id === id);
                    if (!turma) return null;
                    return (
                      <span key={id} className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-slate-200 border border-slate-300 rounded-lg text-xs font-semibold text-slate-700 shadow-sm transition-all hover:bg-slate-300">
                        {turma.nome}
                        <button
                          type="button"
                          className="hover:bg-slate-400 p-0.5 rounded-full text-slate-400 hover:text-slate-600 transition-colors focus:outline-none"
                          onClick={() => {
                            const current = config?.turmasPermitidas || [];
                            const next = current.filter(x => x !== id);
                            setConfig(prev => prev ? { ...prev, turmasPermitidas: next } : prev);
                          }}
                        >
                          <X size={12} strokeWidth={2.5} />
                        </button>
                      </span>
                    );
                  })}
                  {(config?.turmasPermitidas || []).length === 0 && (
                    <span className="text-xs font-medium text-slate-400 italic px-2">Todas as turmas disponíveis (padrão)</span>
                  )}
                </div>

                {/* Dropdown to add a class */}
                <div className="relative">
                  <select
                    className="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none text-xs font-bold text-slate-700 appearance-none cursor-pointer"
                    value=""
                    onChange={(e) => {
                      const id = e.target.value;
                      if (!id) return;
                      const current = config?.turmasPermitidas || [];
                      if (!current.includes(id)) {
                        const next = [...current, id];
                        setConfig(prev => prev ? { ...prev, turmasPermitidas: next } : prev);
                      }
                      e.target.value = ""; // Reset select selection
                    }}
                  >
                    <option value="">+ Adicionar Turma...</option>
                    {turmas
                      .filter(t => !(config?.turmasPermitidas || []).includes(t.id))
                      .map(t => (
                        <option key={t.id} value={t.id}>
                          {t.nome}
                        </option>
                      ))}
                  </select>
                  <div className="absolute right-3.5 top-1/2 -translate-y-1/2 pointer-events-none text-slate-400">
                    <ChevronDown size={14} />
                  </div>
                </div>

                {/* Configurar Vagas e Horários por Turma */}
                {config?.turmasPermitidas && config.turmasPermitidas.length > 0 && (
                  <div className="mt-5 space-y-3">
                    <label className="block text-[10px] font-black text-slate-600 uppercase tracking-wider">Configurar Vagas e Horários</label>
                    <div className="space-y-2 max-h-64 overflow-y-auto pr-1">
                      {config.turmasPermitidas.map(id => {
                        const turma = turmas.find(t => t.id === id);
                        if (!turma) return null;
                        const horarioStr = turma.horario_inicio_padrao && turma.horario_fim_padrao 
                          ? `${turma.horario_inicio_padrao} às ${turma.horario_fim_padrao}` 
                          : 'Horário não definido';
                        return (
                          <div key={id} className="flex items-center justify-between p-3.5 bg-slate-50 border border-slate-100 rounded-2xl shadow-sm text-xs group hover:border-indigo-100 transition-colors">
                            <div className="flex-1 min-w-0 mr-3">
                              <p className="font-bold text-slate-800 truncate">{turma.nome}</p>
                              <p className="text-[10px] text-slate-400 font-bold mt-0.5 tracking-wide uppercase">
                                Horário: <span className="text-indigo-600 normal-case">{horarioStr}</span>
                              </p>
                            </div>
                            <div className="flex items-center gap-2 flex-shrink-0">
                              <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Vagas:</span>
                              <input
                                type="number"
                                min="0"
                                className="w-16 px-2 py-1.5 bg-white border border-slate-200 rounded-xl text-center font-bold text-slate-800 focus:ring-2 focus:ring-indigo-500 focus:outline-none shadow-sm"
                                value={turma.vagas_prematricula ?? ''}
                                placeholder="∞"
                                onChange={(e) => {
                                  const val = e.target.value === '' ? null : parseInt(e.target.value);
                                  setTurmas(prev => prev.map(t => t.id === id ? { ...t, vagas_prematricula: val } : t));
                                }}
                                onBlur={async (e) => {
                                  const val = e.target.value === '' ? null : parseInt(e.target.value);
                                  try {
                                    await fetch(`/api/turmas/${id}`, {
                                      method: 'PUT',
                                      headers: { 'Content-Type': 'application/json' },
                                      body: JSON.stringify({ vagas_prematricula: val })
                                    });
                                  } catch (err) {
                                    console.error('Erro ao atualizar vagas:', err);
                                  }
                                }}
                              />
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}
                
                <p className="text-[10px] text-slate-400 mt-2 font-medium leading-normal">
                  Se nenhuma turma for adicionada, todas as turmas ativas aparecerão para seleção do aluno. Defina o limite de vagas (deixe em branco para ilimitado).
                </p>
              </div>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Mensagem de Sucesso</label>
                <textarea className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium resize-none" rows={2}
                  value={config?.mensagemSucesso || ''} onChange={e => setConfig(prev => prev ? { ...prev, mensagemSucesso: e.target.value } : prev)} />
              </div>
              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Imagem de Pré-Visualização (WhatsApp/Social)</label>
                <div className="space-y-3">
                  {uploadProgress !== null ? (
                    <div className="border border-slate-200 rounded-xl p-5 bg-slate-50 flex flex-col items-center justify-center space-y-3 shadow-inner">
                      <RefreshCw size={24} className="animate-spin text-indigo-600" />
                      <div className="text-center">
                        <p className="text-xs font-bold text-slate-700">Enviando e compactando imagem...</p>
                        <p className="text-[10px] text-slate-400 font-bold mt-0.5">{uploadProgress}% concluído</p>
                      </div>
                      <div className="w-full bg-slate-200 rounded-full h-2 overflow-hidden shadow-inner">
                        <div
                          className="bg-indigo-600 h-full rounded-full transition-all duration-300 ease-out"
                          style={{ width: `${uploadProgress}%` }}
                        ></div>
                      </div>
                    </div>
                  ) : config?.logoUrl ? (
                    <div className="relative group border border-slate-200 rounded-xl overflow-hidden bg-slate-100 p-3 shadow-sm flex flex-col gap-3">
                      <div className="w-full h-44 bg-white border border-slate-200 rounded-lg overflow-hidden flex items-center justify-center relative">
                        <img src={config.logoUrl} alt="Preview" className="w-full h-full object-contain" />
                        <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                          <span className="text-white text-xs font-bold bg-black/60 px-3 py-1.5 rounded-lg backdrop-blur-sm">
                            Pré-visualização do Link
                          </span>
                        </div>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-[10px] text-slate-400 font-mono truncate max-w-[200px] font-bold" title={config.logoUrl}>
                          {config.logoUrl.split('/').pop()}
                        </span>
                        <button
                          type="button"
                          onClick={() => setConfig(prev => prev ? { ...prev, logoUrl: '' } : prev)}
                          className="px-3 py-2 bg-red-50 hover:bg-red-100 text-red-600 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95 shadow-sm"
                          title="Remover Imagem"
                        >
                          <Trash2 size={14} /> Remover
                        </button>
                      </div>
                    </div>
                  ) : (
                    <div className="flex items-center justify-center border-2 border-dashed border-slate-200 hover:border-indigo-400 rounded-xl p-5 bg-slate-50 hover:bg-indigo-50/20 transition-all cursor-pointer relative">
                      <input
                        type="file"
                        accept="image/*"
                        className="absolute inset-0 opacity-0 cursor-pointer"
                        onChange={async (e) => {
                          const file = e.target.files?.[0];
                          if (!file) return;
                          const formData = new FormData();
                          formData.append('file', file);
                          
                          setUploadProgress(0);
                          const xhr = new XMLHttpRequest();
                          
                          xhr.upload.addEventListener('progress', (event) => {
                            if (event.lengthComputable) {
                              const percent = Math.round((event.loaded / event.total) * 100);
                              setUploadProgress(percent);
                            }
                          });
                          
                          xhr.addEventListener('load', () => {
                            setUploadProgress(null);
                            if (xhr.status >= 200 && xhr.status < 300) {
                              try {
                                const resData = JSON.parse(xhr.responseText);
                                setConfig(prev => prev ? { ...prev, logoUrl: resData.url } : prev);
                                showAlert('Sucesso', 'Imagem de visualização carregada!', 'success');
                              } catch (err) {
                                showAlert('Erro', 'Falha ao processar resposta do servidor.', 'error');
                              }
                            } else {
                              showAlert('Erro', 'Falha ao carregar imagem.', 'error');
                            }
                          });
                          
                          xhr.addEventListener('error', () => {
                            setUploadProgress(null);
                            showAlert('Erro', 'Erro de conexão ao enviar imagem.', 'error');
                          });
                          
                          xhr.open('POST', '/api/prematricula/upload');
                          xhr.send(formData);
                        }}
                      />
                      <div className="text-center space-y-1">
                        <Image size={24} className="mx-auto text-slate-400 animate-pulse" />
                        <p className="text-xs font-bold text-slate-600">Fazer Upload da Imagem</p>
                        <p className="text-[9px] text-slate-400">JPG, PNG ou WebP até 5MB</p>
                      </div>
                    </div>
                  )}
                  {!config?.logoUrl && data.logo && (
                    <div className="flex items-center gap-2.5 p-2 bg-slate-50 border border-slate-200 rounded-xl mt-2">
                      <img src={data.logo} alt="Logo Escola" className="w-8 h-8 object-contain rounded border border-slate-200 bg-white" />
                      <span className="text-[10px] text-slate-500 font-bold">Logo padrão da escola ativa como imagem padrão do link.</span>
                    </div>
                  )}
                </div>
              </div>
              <button onClick={saveConfig} disabled={isSaving}
                className="w-full py-3 bg-indigo-600 text-white rounded-xl font-bold text-sm hover:bg-indigo-700 transition-all active:scale-95 flex items-center justify-center gap-2 disabled:opacity-50"
              >
                {isSaving ? <RefreshCw size={16} className="animate-spin" /> : <Save size={16} />} Salvar Configurações
              </button>
            </div>

            {/* Preview Link */}
            <div className="bg-gradient-to-br from-indigo-50 to-violet-50 p-5 rounded-2xl border border-indigo-100">
              <p className="text-[10px] font-black text-indigo-600 uppercase tracking-widest mb-2">Link Público</p>
              <p className="text-xs font-mono text-indigo-800 break-all mb-3">
                {window.location.origin}/{config?.slug}
              </p>
              <a href={`/${config?.slug}`} target="_blank" rel="noopener noreferrer"
                className="flex items-center gap-2 text-xs font-bold text-indigo-600 hover:text-indigo-700"
              >
                <ExternalLink size={14} /> Abrir Prévia
              </a>
            </div>
          </div>

          {/* Right: Fields Editor */}
          <div className="lg:col-span-2 space-y-6">
            <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-sm font-black text-slate-800 uppercase tracking-widest">Campos do Formulário</h3>
                <button onClick={() => setShowNewField(!showNewField)}
                  className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl font-bold text-xs hover:bg-indigo-700 transition-all active:scale-95"
                >
                  <Plus size={16} /> Novo Campo
                </button>
              </div>

              {/* New Field Form */}
              {showNewField && (
                <div className="bg-indigo-50 p-5 rounded-xl border border-indigo-100 mb-6 space-y-4 animate-in slide-in-from-top-2 duration-300">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Nome do Campo</label>
                      <input className="w-full px-4 py-3 bg-white border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium"
                        placeholder="Ex: Nome Completo" value={newField.label} onChange={e => setNewField({ ...newField, label: e.target.value })} />
                    </div>
                    <div>
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Tipo</label>
                      <select className="w-full px-4 py-3 bg-white border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium"
                        value={newField.tipo} onChange={e => setNewField({ ...newField, tipo: e.target.value })}>
                        {Object.entries(FIELD_TYPES).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                      </select>
                    </div>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {newField.tipo === 'banner' ? (
                      <div className="col-span-2">
                        <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Folder / Panfleto de Promoção (Banner)</label>
                        {newField.placeholder ? (
                          <div className="relative group border border-slate-200 rounded-xl overflow-hidden shadow-sm flex justify-center items-center bg-slate-50">
                            <img src={newField.placeholder} alt="Banner" className="w-full max-h-[350px] object-contain rounded-xl" />
                            <div className="absolute inset-0 bg-slate-900/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center rounded-xl">
                              <button 
                                type="button" 
                                onClick={() => setNewField(prev => ({ ...prev, placeholder: '' }))}
                                className="px-3 py-1 bg-red-600 hover:bg-red-700 text-white text-[10px] font-bold rounded-lg transition-all shadow-md"
                              >
                                Remover Folder
                              </button>
                            </div>
                          </div>
                        ) : (
                          <label className="flex flex-col items-center justify-center w-full h-32 border-2 border-slate-200 border-dashed rounded-xl cursor-pointer bg-white hover:bg-slate-50 border-slate-300 transition-all">
                            <div className="flex flex-col items-center justify-center pt-3 pb-3">
                              <Upload className="w-6 h-6 text-slate-400 mb-1 animate-bounce" />
                              <p className="text-[10px] text-slate-500 font-bold">Upload do Folder/Flyer</p>
                              <p className="text-[8px] text-slate-400 mt-0.5">PNG, JPG ou WEBP até 10MB</p>
                            </div>
                            <input 
                              type="file" 
                              accept="image/*" 
                              className="hidden" 
                              onChange={async (e) => {
                                const file = e.target.files?.[0];
                                if (!file) return;
                                const formData = new FormData();
                                formData.append('file', file);
                                try {
                                  const res = await fetch('/api/prematricula/upload', { method: 'POST', body: formData });
                                  if (res.ok) {
                                    const result = await res.json();
                                    setNewField(prev => ({ ...prev, placeholder: result.url }));
                                  }
                                } catch (err) { console.error(err); }
                              }}
                            />
                          </label>
                        )}
                      </div>
                    ) : (
                      <>
                        <div>
                          <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Placeholder</label>
                          <input className="w-full px-4 py-3 bg-white border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium"
                            placeholder="Texto de ajuda" value={newField.placeholder} onChange={e => setNewField({ ...newField, placeholder: e.target.value })} />
                        </div>
                        {newField.tipo === 'select' && (
                          <div>
                            <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Opções (separadas por vírgula)</label>
                            <input className="w-full px-4 py-3 bg-white border border-slate-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-medium"
                              placeholder="Opção 1, Opção 2, Opção 3" value={newField.opcoes} onChange={e => setNewField({ ...newField, opcoes: e.target.value })} />
                          </div>
                        )}
                      </>
                    )}
                  </div>
                  <div className="flex items-center justify-between">
                    <label className="flex items-center gap-2 text-sm font-bold text-slate-600 cursor-pointer">
                      <input type="checkbox" className="w-4 h-4 text-indigo-600 rounded"
                        checked={newField.obrigatorio} onChange={e => setNewField({ ...newField, obrigatorio: e.target.checked })} />
                      Campo Obrigatório
                    </label>
                    <div className="flex gap-2">
                      <button onClick={() => setShowNewField(false)} className="px-4 py-2 text-slate-600 font-bold text-xs rounded-lg hover:bg-slate-100">Cancelar</button>
                      <button onClick={addField} className="px-4 py-2 bg-indigo-600 text-white font-bold text-xs rounded-xl hover:bg-indigo-700 active:scale-95 transition-all">Adicionar</button>
                    </div>
                  </div>
                </div>
              )}

              {/* Fields List */}
              <div className="space-y-3">
                {campos.length === 0 && (
                  <div className="text-center py-12 text-slate-400">
                    <ClipboardPen size={48} className="mx-auto mb-3 opacity-30" />
                    <p className="font-bold">Nenhum campo criado</p>
                    <p className="text-xs mt-1">Clique em "Novo Campo" para começar a montar seu formulário.</p>
                  </div>
                )}
                {campos.sort((a, b) => a.ordem - b.ordem).map((campo, idx) => {
                  const isDefaultField = campo.id.startsWith('_');
                  return (
                    <div key={campo.id} className="flex items-center gap-3 p-4 bg-slate-50 rounded-xl border border-slate-200 group hover:border-indigo-200 transition-colors">
                      {/* Move Up/Down Controls for premium reordering */}
                      <div className="flex flex-col gap-0.5 flex-shrink-0">
                        <button 
                          disabled={idx === 0} 
                          onClick={() => moveField(idx, 'up')}
                          type="button"
                          className="p-1 text-slate-400 hover:text-indigo-600 disabled:opacity-30 disabled:hover:text-slate-400 rounded transition-colors"
                        >
                          <ChevronDown size={14} className="rotate-180" />
                        </button>
                        <button 
                          disabled={idx === campos.length - 1} 
                          onClick={() => moveField(idx, 'down')}
                          type="button"
                          className="p-1 text-slate-400 hover:text-indigo-600 disabled:opacity-30 disabled:hover:text-slate-400 rounded transition-colors"
                        >
                          <ChevronDown size={14} />
                        </button>
                      </div>
                      
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <p className="font-bold text-slate-800 text-sm truncate">{campo.label}</p>
                          {campo.obrigatorio && <span className="text-red-500 text-xs font-black">*</span>}
                          {isDefaultField && (
                            <span className="px-1.5 py-0.5 bg-slate-200 border border-slate-300 rounded text-[9px] font-black text-slate-600 uppercase tracking-wider">
                              Padrão
                            </span>
                          )}
                        </div>
                        <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wider">
                          {FIELD_TYPES[campo.tipo] || campo.tipo}
                          {campo.tipo === 'select' && campo.opcoes?.length ? ` · ${campo.opcoes.length} opções` : ''}
                        </p>
                      </div>
                      
                      <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button onClick={() => setEditingCampo(campo)}
                          type="button"
                          className="p-2 text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
                          title="Editar campo"
                        >
                          <Edit size={16} />
                        </button>
                        
                        {campo.id !== '_nome' && (
                          <button onClick={() => deleteField(campo.id)}
                            type="button"
                            className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                            title="Excluir campo"
                          >
                            <Trash2 size={16} />
                          </button>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Floating Edit Field Modal - Premium Floating Principle (Rule 11 & 17) */}
              {editingCampo && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-transparent animate-fade-in">
                  <div className="fixed inset-0 bg-slate-900/35 backdrop-blur-none" onClick={() => setEditingCampo(null)} />
                  <div className="relative bg-white w-full max-w-md p-6 rounded-3xl shadow-2xl border border-slate-100 animate-in zoom-in-95 duration-200">
                    <button onClick={() => setEditingCampo(null)} className="absolute right-4 top-4 p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-full transition-colors">
                      <X size={18} />
                    </button>
                    
                    <h3 className="text-base font-black text-slate-800 uppercase tracking-wider mb-5">Editar Campo</h3>
                    
                    <div className="space-y-4">
                      <div>
                        <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Nome do Campo</label>
                        <input 
                          className="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-semibold text-slate-800 shadow-sm"
                          value={editingCampo.label} 
                          onChange={e => setEditingCampo({ ...editingCampo, label: e.target.value })} 
                        />
                      </div>
                      
                      <div>
                        <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Tipo</label>
                        <select 
                          className="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-semibold text-slate-800 cursor-pointer shadow-sm"
                          value={editingCampo.tipo} 
                          onChange={e => setEditingCampo({ ...editingCampo, tipo: e.target.value })}
                        >
                          {Object.entries(FIELD_TYPES).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                        </select>
                      </div>
                      
                      {editingCampo.tipo === 'banner' ? (
                        <div>
                          <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Folder / Panfleto de Promoção (Banner)</label>
                          {editingCampo.placeholder ? (
                            <div className="relative group border border-slate-200 rounded-xl overflow-hidden shadow-sm flex justify-center items-center bg-slate-50">
                              <img src={editingCampo.placeholder} alt="Banner" className="w-full max-h-[350px] object-contain rounded-xl" />
                              <div className="absolute inset-0 bg-slate-900/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center rounded-xl">
                                <button 
                                  type="button" 
                                  onClick={() => setEditingCampo(prev => prev ? { ...prev, placeholder: '' } : null)}
                                  className="px-3 py-1 bg-red-600 hover:bg-red-700 text-white text-[10px] font-bold rounded-lg transition-all shadow-md"
                                >
                                  Remover Folder
                                </button>
                              </div>
                            </div>
                          ) : (
                            <label className="flex flex-col items-center justify-center w-full h-32 border-2 border-slate-200 border-dashed rounded-xl cursor-pointer bg-slate-50 hover:bg-slate-100 border-slate-300 transition-all">
                              <div className="flex flex-col items-center justify-center pt-3 pb-3">
                                <Upload className="w-6 h-6 text-slate-400 mb-1 animate-bounce" />
                                <p className="text-[10px] text-slate-500 font-bold">Upload do Folder/Flyer</p>
                              </div>
                              <input 
                                type="file" 
                                accept="image/*" 
                                className="hidden" 
                                onChange={async (e) => {
                                  const file = e.target.files?.[0];
                                  if (!file) return;
                                  const formData = new FormData();
                                  formData.append('file', file);
                                  try {
                                    const res = await fetch('/api/prematricula/upload', { method: 'POST', body: formData });
                                    if (res.ok) {
                                      const result = await res.json();
                                      setEditingCampo(prev => prev ? { ...prev, placeholder: result.url } : null);
                                    }
                                  } catch (err) { console.error(err); }
                                }}
                              />
                            </label>
                          )}
                        </div>
                      ) : (
                        <>
                          <div>
                            <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Placeholder</label>
                            <input 
                              className="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-semibold text-slate-800 shadow-sm"
                              value={editingCampo.placeholder || ''} 
                              onChange={e => setEditingCampo({ ...editingCampo, placeholder: e.target.value })} 
                            />
                          </div>
                          
                          {editingCampo.tipo === 'select' && (
                            <div>
                              <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Opções (separadas por vírgula)</label>
                              <input 
                                className="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:outline-none text-sm font-semibold text-slate-800 shadow-sm"
                                value={Array.isArray(editingCampo.opcoes) ? editingCampo.opcoes.join(', ') : editingCampo.opcoes || ''} 
                                onChange={e => setEditingCampo({ ...editingCampo, opcoes: e.target.value.split(',').map(x => x.trim()) })} 
                              />
                            </div>
                          )}
                        </>
                      )}
                      
                      <label className="flex items-center gap-2.5 text-sm font-bold text-slate-600 cursor-pointer py-1">
                        <input 
                          type="checkbox" 
                          className="w-4 h-4 text-indigo-600 rounded focus:ring-indigo-500"
                          checked={editingCampo.obrigatorio} 
                          onChange={e => setEditingCampo({ ...editingCampo, obrigatorio: e.target.checked })} 
                        />
                        Campo Obrigatório
                      </label>
                    </div>
                    
                    <div className="flex justify-end gap-2 mt-7">
                      <button 
                        onClick={() => setEditingCampo(null)} 
                        className="px-4 py-2.5 text-xs font-bold text-slate-500 rounded-xl hover:bg-slate-100 transition-colors"
                      >
                        Cancelar
                      </button>
                      <button 
                        onClick={() => updateField(editingCampo)} 
                        className="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-extrabold rounded-xl shadow-md transition-all active:scale-95"
                      >
                        Salvar Alterações
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      ) : (
        /* Inscricoes Tab */
        <div className="space-y-6">
          <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
            <div className="flex items-center gap-3 flex-wrap">
              <select className="px-4 py-2.5 bg-white border border-slate-200 rounded-xl text-sm font-bold text-slate-700 focus:ring-2 focus:ring-indigo-500 focus:outline-none"
                value={selectedTurma} onChange={e => setSelectedTurma(e.target.value)}>
                <option value="all">Todas as Turmas ({inscricoes.length})</option>
                {turmasComInscritos.map(t => (
                  <option key={t.id} value={t.id}>{t.nome} ({t.count})</option>
                ))}
              </select>
              <button onClick={() => loadData()} className="p-2.5 bg-slate-100 rounded-xl text-slate-600 hover:bg-slate-200 transition-all" title="Atualizar">
                <RefreshCw size={16} />
              </button>
            </div>
            <div className="flex items-center gap-3">
              <button onClick={() => setShowMassModal(true)}
                className="flex items-center gap-2 px-4 py-2.5 bg-indigo-600 text-white rounded-xl font-bold text-sm hover:bg-indigo-700 transition-all active:scale-95"
              >
                <MessageSquare size={16} /> Disparo em Massa
              </button>
              <button onClick={() => exportCSV(selectedTurma)}
                className="flex items-center gap-2 px-4 py-2.5 bg-emerald-600 text-white rounded-xl font-bold text-sm hover:bg-emerald-700 transition-all active:scale-95"
              >
                <Download size={16} /> Exportar CSV
              </button>
            </div>
          </div>

          {filteredInscricoes.length === 0 ? (
            <div className="bg-white p-12 rounded-2xl border border-slate-200 text-center">
              <Users size={48} className="mx-auto mb-3 text-slate-300" />
              <p className="font-bold text-slate-500">Nenhuma inscrição encontrada</p>
              <p className="text-xs text-slate-400 mt-1">As pré-matrículas aparecerão aqui quando forem preenchidas.</p>
            </div>
          ) : (
            <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="border-b border-slate-100 text-xs uppercase text-slate-500 font-bold tracking-wider">
                      <th className="p-4">Nome</th>
                      <th className="p-4">Contato</th>
                      <th className="p-4">Turma</th>
                      <th className="p-4">Status</th>
                      <th className="p-4">Data</th>
                      <th className="p-4 text-right">Ações</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-50 text-sm">
                    {filteredInscricoes.map(insc => (
                      <tr key={insc.id} className="hover:bg-slate-50 transition-colors">
                        <td className="p-4">
                          <p className="font-bold text-slate-800">{insc.nome}</p>
                           {insc.respostas && Object.keys(insc.respostas).length > 0 && (
                            <div className="mt-2 space-y-1 bg-slate-50 p-2.5 rounded-xl border border-slate-100 text-[11px] max-w-xs">
                              {Object.entries(insc.respostas).map(([key, value]) => {
                                const field = todosCampos.find(c => c.id === key);
                                const label = field ? field.label : getFriendlyLabel(key, value);
                                const isUrl = typeof value === 'string' && (value.startsWith('http') || value.startsWith('/storage/'));
                                return (
                                  <div key={key} className="flex flex-col sm:flex-row sm:items-center gap-1">
                                    <span className="font-bold text-slate-500">{label}:</span>
                                    {isUrl ? (
                                      <a href={value} target="_blank" rel="noopener noreferrer" className="text-indigo-600 hover:text-indigo-700 hover:underline font-extrabold flex items-center gap-1">
                                        📄 Ver Documento
                                      </a>
                                    ) : (
                                      <span className="text-slate-800 font-semibold truncate">
                                        {(() => {
                                          if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
                                            const dateFormatted = value.split('-').reverse().join('/');
                                            const isBirthDateField = label.toLowerCase().includes('nasc') || label.toLowerCase().includes('nascimento');
                                            if (isBirthDateField) {
                                              const parts = value.split('-');
                                              const birthYear = parseInt(parts[0], 10);
                                              const birthMonth = parseInt(parts[1], 10);
                                              const birthDay = parseInt(parts[2], 10);
                                              
                                              // Forçando fuso brasileiro para calcular a idade exata hoje (Regra 45)
                                              const todayStr = new Date().toLocaleString('en-US', { timeZone: 'America/Sao_Paulo' });
                                              const today = new Date(todayStr);
                                              
                                              let age = today.getFullYear() - birthYear;
                                              const monthDiff = (today.getMonth() + 1) - birthMonth;
                                              if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDay)) {
                                                age--;
                                              }
                                              return `${dateFormatted} (${age} anos)`;
                                            }
                                            return dateFormatted;
                                          }
                                          return String(value);
                                        })()}
                                      </span>
                                    )}
                                  </div>
                                );
                              })}
                            </div>
                          )}
                        </td>
                        <td className="p-4">
                          <p className="text-slate-600">{insc.email || '-'}</p>
                          <p className="text-xs text-slate-400">{insc.telefone || '-'}</p>
                        </td>
                        <td className="p-4 text-slate-600 font-medium">{insc.turmaNome || '-'}</td>
                        <td className="p-4">
                          <span className={`px-2.5 py-1 rounded-full text-[10px] font-bold uppercase ${
                            insc.status === 'pendente' ? 'bg-amber-100 text-amber-700' :
                            insc.status === 'aprovado' ? 'bg-emerald-100 text-emerald-700' :
                            insc.status === 'rejeitado' ? 'bg-red-100 text-red-700' :
                            'bg-indigo-100 text-indigo-700'
                          }`}>
                            {insc.status}
                          </span>
                        </td>
                        <td className="p-4 text-slate-500 text-xs">{new Date(insc.createdAt).toLocaleDateString('pt-BR')}</td>
                        <td className="p-4 text-right flex items-center justify-end gap-2">
                          <button
                            onClick={() => onConvert && onConvert(insc)}
                            className="flex items-center gap-1.5 px-3 py-1.5 bg-indigo-50 text-indigo-600 hover:bg-indigo-100 rounded-lg font-bold text-xs transition-colors"
                            title="Converter em Matrícula"
                          >
                            <UserCheck size={14} /> Matricular
                          </button>
                          <button onClick={() => deleteInscricao(insc.id)} className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors">
                            <Trash2 size={16} />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      {showMassModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-transparent animate-fade-in">
          <div className="fixed inset-0 bg-slate-900/35 backdrop-blur-none" onClick={() => !isSendingMass && setShowMassModal(false)} />
          <div className="relative bg-white w-full max-w-lg p-6 rounded-3xl shadow-2xl border border-slate-100 animate-in zoom-in-95 duration-200">
            <button onClick={() => !isSendingMass && setShowMassModal(false)} disabled={isSendingMass} className="absolute right-4 top-4 p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-full transition-colors disabled:opacity-50">
              <X size={18} />
            </button>
            
            <h3 className="text-base font-black text-slate-800 uppercase tracking-wider mb-5 flex items-center gap-2">
              <MessageSquare size={20} className="text-indigo-600" /> Disparo em Massa
            </h3>
            
            <div className="space-y-4">
              <select 
                className="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm bg-white font-bold text-slate-700 focus:ring-2 focus:ring-indigo-500 focus:outline-none"
                value={targetType}
                onChange={(e) => { setTargetType(e.target.value); setTargetId(''); }}
              >
                <option value="todos">Todas as Pré-Matrículas</option>
                <option value="turma">Por Turma</option>
                <option value="aluno">Individual</option>
              </select>

              {targetType !== 'todos' && (
                <select 
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm bg-white font-bold text-slate-700 focus:ring-2 focus:ring-indigo-500 focus:outline-none"
                  value={targetId}
                  onChange={(e) => setTargetId(e.target.value)}
                >
                  <option value="">-- Selecione --</option>
                  {targetType === 'turma'
                    ? turmas?.map(c => <option key={c.id} value={c.id}>{c.nome}</option>)
                    : inscricoes?.map(p => <option key={p.id} value={p.id}>{p.nome} ({p.telefone})</option>)
                  }
                </select>
              )}

              <div>
                <label className="block text-[10px] font-bold text-slate-500 uppercase mb-2 ml-1">Mensagem Personalizada</label>
                <div className="flex flex-wrap gap-1 mb-2 relative">
                  {['{nome}', '{matricula}'].map(v => (
                    <button 
                      key={v}
                      onClick={() => {
                        const textarea = document.getElementById('mass-editor') as HTMLTextAreaElement;
                        if (!textarea) return;
                        const start = textarea.selectionStart;
                        const end = textarea.selectionEnd;
                        const newText = messageText.substring(0, start) + v + messageText.substring(end);
                        setMessageText(newText);
                        setTimeout(() => { textarea.focus(); textarea.setSelectionRange(start + v.length, start + v.length); }, 10);
                      }}
                      className="text-[9px] bg-indigo-50 text-indigo-700 px-2 py-1 rounded-md border border-indigo-100 hover:bg-indigo-600 hover:text-white transition-all shadow-sm font-bold"
                    >
                      {v}
                    </button>
                  ))}
                  
                  <button
                    onClick={() => setShowMassEmojis(!showMassEmojis)}
                    className="flex items-center justify-center text-[9px] bg-indigo-50 text-indigo-700 px-2 py-1 rounded-md border border-indigo-100 hover:bg-indigo-600 hover:text-white transition-all shadow-sm ml-auto font-bold"
                    title="Inserir Emoji"
                  >
                    <Smile size={12} />
                  </button>

                  {showMassEmojis && (
                    <div className="absolute right-0 top-8 z-10 bg-white border border-slate-200 rounded-xl shadow-xl p-2 grid grid-cols-5 gap-1 w-48 animate-in fade-in zoom-in duration-200">
                      {commonEmojis.map(emoji => (
                        <button
                          key={emoji}
                          onClick={() => {
                            const textarea = document.getElementById('mass-editor') as HTMLTextAreaElement;
                            if (!textarea) return;
                            const start = textarea.selectionStart;
                            const end = textarea.selectionEnd;
                            const newText = messageText.substring(0, start) + emoji + messageText.substring(end);
                            setMessageText(newText);
                            setShowMassEmojis(false);
                            setTimeout(() => { textarea.focus(); textarea.setSelectionRange(start + emoji.length, start + emoji.length); }, 10);
                          }}
                          className="hover:bg-slate-50 text-lg rounded flex items-center justify-center p-1 transition-colors"
                        >
                          {emoji}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
                <textarea 
                  id="mass-editor"
                  rows={4}
                  className="w-full px-4 py-3 border border-slate-200 rounded-xl text-sm bg-white focus:ring-2 focus:ring-indigo-500 focus:outline-none font-medium shadow-sm resize-none text-slate-700"
                  placeholder="Escreva sua mensagem..."
                  value={messageText}
                  onChange={(e) => setMessageText(e.target.value)}
                />
                
                <div className="mt-2 flex items-center justify-between">
                  <div className="flex-1">
                    {massAttachment ? (
                      <div className="flex items-center gap-2 bg-indigo-50 text-indigo-700 text-[10px] font-bold px-2 py-1.5 rounded-lg border border-indigo-100 w-fit">
                        <span className="truncate max-w-[150px]">{massAttachment.name}</span>
                        <button onClick={() => setMassAttachment(null)} className="text-indigo-500 hover:text-red-500" title="Remover anexo"><X size={12} /></button>
                      </div>
                    ) : (
                      <div className="text-[9px] text-slate-400 font-medium">Nenhum anexo</div>
                    )}
                  </div>
                  
                  <label className="flex items-center gap-1.5 px-3 py-1.5 bg-slate-50 text-slate-600 rounded-lg border border-slate-200 text-[10px] font-black uppercase cursor-pointer hover:bg-slate-100 transition-all shadow-sm">
                    <Paperclip size={12} />
                    <span>Anexar Arquivo</span>
                    <input 
                      type="file" 
                      className="hidden" 
                      accept="image/*,application/pdf"
                      onChange={(e) => {
                        if (e.target.files && e.target.files[0]) {
                          setMassAttachment(e.target.files[0]);
                        }
                      }}
                    />
                  </label>
                </div>
              </div>

              <div className="bg-slate-50 p-3 rounded-xl border border-slate-100 mb-2">
                <label className="block text-[9px] font-black text-slate-500 uppercase tracking-widest mb-1.5 ml-1">Intervalo Mínimo (Segundos)</label>
                <div className="flex items-center gap-2">
                  <input 
                    type="number" 
                    min="10" max="600"
                    value={massDelay}
                    onChange={(e) => setMassDelay(e.target.value)}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm font-bold text-center text-slate-700 focus:ring-2 focus:ring-indigo-500 focus:outline-none"
                  />
                  <div className="text-[10px] text-slate-500 font-bold whitespace-nowrap">seg/msg</div>
                </div>
                <p className="text-[8px] text-slate-400 mt-1 font-medium leading-tight">Recomendado: 60s ou mais para evitar banimento.</p>
              </div>

              <button 
                onClick={handleMassSend}
                disabled={isSendingMass}
                className={`w-full flex items-center justify-center gap-2 py-3.5 px-4 rounded-xl font-black text-sm text-white transition-all shadow-lg active:scale-95 ${
                  isSendingMass ? 'bg-slate-400' : 'bg-indigo-600 hover:bg-indigo-700'
                }`}
              >
                {isSendingMass ? 'Iniciando...' : 'Iniciar Disparo'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default PreMatricula;
