import React, { useState } from 'react'; import { Calendar, Link, CheckCircle2, AlertCircle, Loader2 } from 'lucide-react'; import { useToast } from '../contexts/ToastContext.tsx'; interface GoogleConnectButtonProps { ownerId: string; clinicaId?: string; isConnected: boolean; onStatusChange?: () => void; } export const GoogleConnectButton: React.FC = ({ ownerId, clinicaId, isConnected, onStatusChange }) => { const [isLoading, setIsLoading] = useState(false); const toast = useToast(); const handleConnect = async () => { setIsLoading(true); try { const params = new URLSearchParams({ ownerId }); if (clinicaId) params.set('clinicaId', clinicaId); const response = await fetch(`/api/auth/google/url?${params}`); const data = await response.json(); if (!response.ok || data.error) { toast.error((data.error || 'Falha ao obter URL de autenticação').toUpperCase()); setIsLoading(false); return; } const { url } = data; // Abrir em popup para manter o contexto const width = 600; const height = 700; const left = window.screen.width / 2 - width / 2; const top = window.screen.height / 2 - height / 2; const popup = window.open( url, 'google-auth', `width=${width},height=${height},left=${left},top=${top}` ); // Detecção robusta de fechamento. As páginas de login do Google enviam // Cross-Origin-Opener-Policy, o que BLOQUEIA ler popup.closed (enche o // console de warning e não detecta o fechamento). Por isso usamos o // retorno de FOCO à janela principal como sinal de que o popup foi fechado; // o polling de popup.closed fica só como fallback protegido por try/catch. let done = false; const finish = () => { if (done) return; done = true; window.removeEventListener('focus', onFocus); clearInterval(timer); setIsLoading(false); if (onStatusChange) onStatusChange(); }; const onFocus = () => { setTimeout(finish, 600); }; window.addEventListener('focus', onFocus); const timer = setInterval(() => { try { if (!popup || popup.closed) finish(); } catch { /* COOP bloqueia: ignora */ } }, 1000); } catch (error) { console.error('Erro ao conectar Google Agenda:', error); setIsLoading(false); } }; const handleDisconnect = async () => { if (!confirm('Deseja realmente desconectar esta agenda?')) return; setIsLoading(true); try { await fetch(`/api/auth/google/${ownerId}`, { method: 'DELETE' }); if (onStatusChange) onStatusChange(); } catch (error) { console.error('Erro ao desconectar:', error); } finally { setIsLoading(false); } }; if (isConnected) { return (

Google Agenda Conectada

Sincronização Ativa

); } return ( ); };