/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useEffect, useRef, useCallback } from "react";
import {
  LifeManagerProvider,
  useLifeManager,
} from "./context/LifeManagerContext";
import { db, auth, googleProvider } from "./firebase";
import { getDoc, doc } from "firebase/firestore";
import {
  linkWithPopup,
  signInWithCredential,
  GoogleAuthProvider,
} from "firebase/auth";

import { Dashboard } from "./components/Dashboard";

// Code Splitting using React.lazy for main pages to drastically reduce initial bundle size on mobile
const Finances = React.lazy(() =>
  import("./components/Finances").then((m) => ({ default: m.Finances })),
);
const Agenda = React.lazy(() =>
  import("./components/Agenda").then((m) => ({ default: m.Agenda })),
);
const Habits = React.lazy(() =>
  import("./components/Habits").then((m) => ({ default: m.Habits })),
);
const Goals = React.lazy(() =>
  import("./components/Goals").then((m) => ({ default: m.Goals })),
);
const AIChatCopilot = React.lazy(() =>
  import("./components/AIChatCopilot").then((m) => ({
    default: m.AIChatCopilot,
  })),
);
const Inventory = React.lazy(() =>
  import("./components/Inventory").then((m) => ({ default: m.Inventory })),
);
const SecondBrain = React.lazy(() =>
  import("./components/SecondBrain").then((m) => ({ default: m.SecondBrain })),
);
const SettingsPage = React.lazy(() =>
  import("./components/SettingsPage").then((m) => ({
    default: m.SettingsPage,
  })),
);


// Highly optimized preloading strategy: trigger the import of the essential screen chunks.
// By loading key chunks on module evaluation, we minimize the initial bundle but eliminate waterfall delay.
const preloadComponent = (tab: string) => {
  try {
    switch (tab) {
      case "finances":
        import("./components/Finances");
        break;
      case "agenda":
        import("./components/Agenda");
        break;
      case "habits":
        import("./components/Habits");
        break;
      case "goals":
        import("./components/Goals");
        break;
      case "inventory":
        import("./components/Inventory");
        break;
      case "second-brain":
        import("./components/SecondBrain");
        break;

      case "ai-copilot":
        import("./components/AIChatCopilot");
        break;
      case "settings":
        import("./components/SettingsPage");
        break;
    }
  } catch (e) {
    console.warn("Preload failed for tab:", tab, e);
  }
};

// Immediate preloading of the essential initial screen chunk (Dashboard)
// Now statically imported.
import {
  Brain,
  BarChart3,
  DollarSign,
  CalendarDays,
  Target,
  Share2,
  Copy,
  Check,
  Loader2,
  RefreshCw,
  Cloud,
  Menu,
  X,
  Sparkles,
  Settings,
  Compass,
  Bell,
  BellOff,
  LogIn,
  LogOut,
  Users,
  Shield,
  Clock,
  CheckCircle,
  AlertTriangle,
  AlertCircle,
  Lock,
  Plus,
  Trash2,
  Sliders,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  Flame,
  Package,
  Mail,
  UserPlus,
  ShieldAlert,
  Smartphone,
  Download,
  PanelLeftClose,
  PanelLeftOpen,
  Database,
  ScrollText,
  MapPin,
  Activity,
} from "lucide-react";
import { motion, AnimatePresence } from "motion/react";
import {
  ActiveTab,
  FamilyMember,
  NotificationSettings,
  DashboardSettings,
} from "./types";
import { Moving3DBackground } from "./components/Moving3DBackground";
import { logToServer } from "./utils/logger";
import { useErrorMonitor } from "./hooks/useErrorMonitor";
import { LogsPanelModal } from "./components/LogsPanelModal";
import { useHeartbeat } from "./hooks/useHeartbeat";
import {
  getReadAheadCache,
  saveReadAheadCache,
  getClientLogsFromDB,
  saveClientLogToDB,
  ClientLog,
  QueuedNotification,
  saveQueuedNotification,
  getQueuedNotifications,
  deleteQueuedNotification,
} from "./utils/indexedDB";

// Pre-populate user's Gemini API Key in localStorage synchronously at load-time
try {
  const existingKey = localStorage.getItem("life_manager_gemini_api_key");
  if (!existingKey || existingKey.trim() === "") {
    localStorage.setItem(
      "life_manager_gemini_api_key",
      "AQ.Ab8RN6JjApibBrSu-5_A88KGWddl2nsxdQQhbaRJowesUeXo5A",
    );
  }
} catch (e) {
  console.warn("Could not write to localStorage on initial module load:", e);
}

interface NotificationAlert {
  id: string;
  title: string;
  message: string;
  type: "appointment" | "bill" | "goal";
  meta?: string;
}

function MainApp() {
  const {
    userId,
    changeUserId,
    loading,
    isSaving,
    lastSaved,
    autoSaveStatus,
    lastAutoSavedAt,
    manualSync,
    user,
    isAuthLoading,
    userConfig,
    activeMember,
    setActiveMember,
    loginWithGoogle,
    loginWithEmail,
    registerWithEmail,
    logout,
    addFamilyMember,
    deleteFamilyMember,
    updateFamilyMemberGPS,
    updateNotificationSettings,
    updateDashboardSettings,
    appointments,
    transactions,
    goals,
    waterLogs,
    medications,
    inventoryItems,
    secondBrainNotes,
    failedSyncAttempts,
    restoreFromBackup,
    googleEvents,
    googleCalendarAlertIds,
    habits,
  } = useLifeManager();

  const { activeError, dismissError, openLogsPanel } = useErrorMonitor();
  const [activeTab, setActiveTab] = useState<ActiveTab>("dashboard");
  const [sidebarCollapsed, setSidebarCollapsed] = useState(
    () => localStorage.getItem("sidebar_collapsed") === "true",
  );

  // Real-time mouse coordinate tracker for interactive premium 3D spotlight glows
  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      document.documentElement.style.setProperty("--mouse-x", `${e.clientX}px`);
      document.documentElement.style.setProperty("--mouse-y", `${e.clientY}px`);
    };
    window.addEventListener("mousemove", handleMouseMove);
    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
    };
  }, []);

  // Idle Preloader effect to cache other page components when the network/browser is idle (1.5s after load)
  useEffect(() => {
    const idleTimer = setTimeout(() => {
      preloadComponent("finances");
      preloadComponent("agenda");
      preloadComponent("habits");
      preloadComponent("settings");
      preloadComponent("goals");
      preloadComponent("inventory");
      preloadComponent("second-brain");
      preloadComponent("ai-copilot");
    }, 1500);
    return () => clearTimeout(idleTimer);
  }, []);

  // Modal trigger states
  const [showSyncPanel, setShowSyncPanel] = useState(false);
  const [syncInput, setSyncInput] = useState("");
  const [copied, setCopied] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  // Family configuration states
  const [showFamilyModal, setShowFamilyModal] = useState(false);
  const [newMemberName, setNewMemberName] = useState("");
  const [newMemberRole, setNewMemberRole] = useState<
    "lider" | "filho" | "filha" | "parente" | "outro"
  >("lider");
  const [newMemberPin, setNewMemberPin] = useState("");
  const [newMemberEmail, setNewMemberEmail] = useState("");
  const [memberInviteSuccess, setMemberInviteSuccess] = useState<string | null>(
    null,
  );

  // Profile PIN switching states
  const [switchingMember, setSwitchingMember] = useState<FamilyMember | null>(
    null,
  );
  const [pinInput, setPinInput] = useState("");
  const [pinError, setPinError] = useState(false);

  // Settings Panel state
  const [showSettingsModal, setShowSettingsModal] = useState(false);
  const [newHabitReminderTime, setNewHabitReminderTime] = useState("08:00");

  const [bypassGoogle, setBypassGoogle] = useState(false);
  useEffect(() => {
    if (user) {
      setBypassGoogle(
        localStorage.getItem(`bypass_google_${user.uid}`) === "true",
      );
    } else {
      setBypassGoogle(false);
    }
  }, [user]);

  // Notifications Popover State
  const [showNotifications, setShowNotifications] = useState(false);
  const [activeAlerts, setActiveAlerts] = useState<NotificationAlert[]>([]);
  const [rewrittenAlerts, setRewrittenAlerts] = useState<
    Record<string, { title: string; message: string }>
  >({});

  // PWA & Push Notification States
  const [deferredPrompt, setDeferredPrompt] = useState<any>(null);
  const [isInstallable, setIsInstallable] = useState(false);
  const [pushPermissionState, setPushPermissionState] = useState<string>(() => {
    return "Notification" in window ? Notification.permission : "unsupported";
  });
  const [isSubscribingPush, setIsSubscribingPush] = useState(false);
  const [pushStatusMessage, setPushStatusMessage] = useState<string>("");
  const [isTestMode, setIsTestMode] = useState<boolean>(false);
  const testModeErrorsRef = useRef<number>(0);

  // Client-Side Custom Toast Notifications (fully reliable on Mobile, PC, & inside Preview iframes)
  const [toasts, setToasts] = useState<
    { id: string; title: string; body: string }[]
  >([]);
  const showToast = useCallback((title: string, body: string) => {
    const id = Math.random().toString();
    setToasts((prev) => [...prev, { id, title, body }]);
    setTimeout(() => {
      setToasts((prev) => prev.filter((t) => t.id !== id));
    }, 6000);
  }, []);

  const handleManualSync = useCallback(async () => {
    try {
      await manualSync();
      showToast("☁️ Sincronização Concluída", "Seus dados foram salvos com sucesso na nuvem!");
    } catch (err: any) {
      console.error("Manual sync failed:", err);
      showToast("❌ Falha na Sincronização", "Ocorreu um erro ao salvar na nuvem. Verifique sua conexão.");
    }
  }, [manualSync, showToast]);

  const { serverOnline, lastChecked } = useHeartbeat();

  // Automated Heartbeat & Synchronization service in App.tsx
  useEffect(() => {
    if (!serverOnline) return;

    const performSyncCheck = async () => {
      const userId = localStorage.getItem("life_manager_user_id");
      if (!userId) return;

      try {
        // Compare timestamp between IndexedDB & server
        const cache = await getReadAheadCache(userId);
        const lastLocalTimestamp =
          cache?.updatedAt || new Date(0).toISOString();

        const response = await fetch("/api/config/sync", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            userId,
            userConfig: cache?.userConfig || userConfig || null,
            appointments,
            transactions,
            goals,
            waterLogs,
            medications,
            inventoryItems,
            secondBrainNotes,
            activeMember: activeMember || null,
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            timezoneOffset: new Date().getTimezoneOffset(),
            lastUpdated: lastLocalTimestamp,
          }),
        });

        if (response.ok) {
          const contentType = response.headers.get("content-type") || "";
          if (!contentType.includes("application/json")) {
            console.log(
              "⚡ [App Heartbeat Sync]: Servidor retornou HTML/estático em vez de JSON (SPA fallback ativo). Ignorando sincronização.",
            );
            return;
          }
          const data = await response.json();
          if (data.status === "loaded" && data.userConfig && data.lastUpdated) {
            console.log(
              "⚡ [App Heartbeat Sync]: Divergência de timestamp detectada (Servidor mais recente). Atualizando cache local...",
            );

            // Update IndexedDB cache
            await saveReadAheadCache(
              userId,
              data.userConfig,
              data.transactions || [],
            );

            // Update localstorage
            localStorage.setItem(
              `life_manager_config_cache_${userId}`,
              JSON.stringify(data.userConfig),
            );
            localStorage.setItem(
              `user_config_last_updated_${userId}`,
              data.lastUpdated,
            );

            // Set flag and notify context
            localStorage.setItem(`__config_sync_in_progress_${userId}`, "true");
            window.dispatchEvent(
              new CustomEvent("full-data-synchronized", { detail: data }),
            );

            console.log(
              "⚡ [App Heartbeat Sync]: Configurações sincronizadas silenciosamente em segundo plano.",
            );
          } else if (data.status === "saved") {
            console.log(
              "⚡ [App Heartbeat Sync]: Configurações locais sincronizadas e salvas na nuvem.",
            );
          }
        }
      } catch (err: any) {
        if (err?.message === "Failed to fetch" || err?.name === "TypeError") {
          console.log(
            "⚡ [App Heartbeat Sync]: Servidor temporariamente indisponível ou offline (Failed to fetch).",
          );
        } else {
          console.error("❌ [App Heartbeat Sync Error]:", err);
        }
      }
    };

    performSyncCheck();
  }, [
    serverOnline,
    lastChecked,
    showToast,
    userConfig,
    appointments,
    transactions,
    goals,
    waterLogs,
    medications,
    activeMember,
  ]);

  // Active/Background Tab Keep-Alive Service using Web Worker
  // This bypasses browser tab background throttling and keeps the Cloud Run container warm
  useEffect(() => {
    try {
      const workerCode = `
        let intervalId = null;
        self.onmessage = function(e) {
          if (e.data === 'start') {
            if (intervalId) clearInterval(intervalId);
            intervalId = setInterval(() => {
              fetch('/api/health')
                .then(r => r.json())
                .then(data => {
                  self.postMessage({ type: 'pong', status: 'ok' });
                })
                .catch(err => {
                  self.postMessage({ type: 'pong', status: 'error', error: err.message });
                });
            }, 60000); // Ping every 60 seconds to keep container alive and warm
          } else if (e.data === 'stop') {
            if (intervalId) {
              clearInterval(intervalId);
              intervalId = null;
            }
          }
        };
      `;
      const blob = new Blob([workerCode], { type: "application/javascript" });
      const workerUrl = URL.createObjectURL(blob);
      const worker = new Worker(workerUrl);

      worker.onmessage = (e) => {
        if (e.data.type === "pong" && e.data.status === "ok") {
          console.log(
            "⚡ [Background Keep-Alive Worker]: Ping /api/health completed. Server warmed.",
          );
        }
      };

      worker.postMessage("start");

      return () => {
        worker.postMessage("stop");
        worker.terminate();
        URL.revokeObjectURL(workerUrl);
      };
    } catch (err) {
      console.warn("Could not start background keep-alive Web Worker:", err);
    }
  }, []);

  useEffect(() => {
    const handleBeforeInstall = (e: any) => {
      e.preventDefault();
      setDeferredPrompt(e);
      setIsInstallable(true);
    };
    window.addEventListener("beforeinstallprompt", handleBeforeInstall);

    // Check if running in standalone/installed mode
    const isStandalone =
      window.matchMedia("(display-mode: standalone)").matches ||
      (window.navigator as any).standalone === true;
    if (isStandalone) {
      setIsInstallable(false);
    }

    return () =>
      window.removeEventListener("beforeinstallprompt", handleBeforeInstall);
  }, []);

  useEffect(() => {
    console.log("PushPermissionState changed to:", pushPermissionState);
  }, [pushPermissionState]);

  const urlB64ToUint8Array = (base64String: string) => {
    if (!base64String) {
      throw new Error("Chave VAPID vazia ou inválida.");
    }
    // Remover todos os espaços em branco, quebras de linha e quebras de carro
    const cleanString = base64String.replace(/\s/g, "");

    // Remover padding existente para recalcular corretamente de forma precisa
    const base64WithoutPadding = cleanString.replace(/=/g, "");

    const padding = "=".repeat((4 - (base64WithoutPadding.length % 4)) % 4);
    const base64 = (base64WithoutPadding + padding)
      .replace(/-/g, "+")
      .replace(/_/g, "/");

    try {
      const rawData = window.atob(base64);
      const outputArray = new Uint8Array(rawData.length);

      for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
      }

      // Web Push requer que a chave tenha exatamente 65 bytes de tamanho
      return outputArray;
    } catch (e: any) {
      console.error("Erro ao decodificar Base64 VAPID:", e);
      throw new Error(
        `Erro de decodificação da chave de segurança: ${e.message || e}`,
      );
    }
  };

  const subscribeUserToPush = async () => {
    if (!("Notification" in window)) {
      alert("Seu dispositivo ou navegador não suporta notificações nativas.");
      return;
    }

    if (Notification.permission === "denied") {
      alert(
        "⚠️ Permissão de Notificação Bloqueada pelo Navegador!\n\n" +
          "O seu navegador está configurado para bloquear notificações deste site.\n\n" +
          "Para reativar e receber alertas:\n" +
          "1. Clique no ícone de cadeado (🔒) ou de configurações à esquerda do endereço do site (URL).\n" +
          '2. Mude a permissão de "Notificações" (Notification) para "Permitir" (Allow).\n' +
          "3. Recarregue a página (F5) e clique novamente para Habilitar Alertas!",
      );
      setPushPermissionState("denied");
      return;
    }

    try {
      setIsSubscribingPush(true);
      setPushStatusMessage("Solicitando permissão...");

      const permission = await Notification.requestPermission();
      setPushPermissionState(permission);

      if (permission !== "granted") {
        throw new Error("Permissão de notificação rejeitada!");
      }

      // If serviceWorker or PushManager is missing but we've got normal Notification permissions, activate local
      if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
        setPushPermissionState("granted");
        setPushStatusMessage("Pronto! Ativado local.");
        showToast(
          "🔔 Notificações Locais Ativas",
          "Notificações locais foram habilitadas com sucesso neste dispositivo!",
        );
        triggerNativeOSNotification(
          "🔔 Notificações Ativadas!",
          "Os alertas funcionarão enquanto o aplicativo estiver aberto.",
        );
        return;
      }

      setPushStatusMessage("Sincronizando com satélite...");

      // Attempt Web Push registration in a separate nested try-catch block so it never crashes the local fallback
      try {
        const registration = await Promise.race([
          navigator.serviceWorker.ready,
          new Promise<ServiceWorkerRegistration>((_, reject) =>
            setTimeout(
              () =>
                reject(
                  new Error(
                    "Timeout ao conectar com Service Worker (Limite de 5 segundos)",
                  ),
                ),
              5000,
            ),
          ),
        ]);

        if (!registration || !registration.pushManager) {
          throw new Error(
            "PushManager não é suportado neste dispositivo ou navegador.",
          );
        }

        // Obter chave pública VAPID do servidor primeiro para poder validar e auto-renovar se necessário
        setPushStatusMessage("Autenticando criptografia...");
        const res = await fetch("/api/notifications/vapid-key");

        const contentType = res.headers.get("content-type");
        if (!contentType || !contentType.includes("application/json")) {
          const text = await res.text();
          console.error("Non-JSON VAPID response:", text.substring(0, 200));
          throw new Error(
            "O servidor de notificações em nuvem retornou uma resposta inesperada. Ativando modo local.",
          );
        }

        const data = await res.json();
        if (!res.ok) {
          throw new Error(
            data?.error || "Não foi possível obter a chave do servidor.",
          );
        }
        if (!data || !data.publicKey) {
          throw new Error("Chave pública VAPID não configurada no servidor.");
        }
        console.log("VAPID Key received:", data.publicKey);

        const convertedVapidKey = urlB64ToUint8Array(data.publicKey);

        let subscription = await registration.pushManager.getSubscription();

        if (subscription) {
          // Comparar a chave do servidor com a chave da inscrição atual para auto-renovação
          const appServerKey = subscription.options.applicationServerKey;
          let keysMatch = false;
          if (appServerKey) {
            const keyArray = new Uint8Array(appServerKey);
            if (keyArray.length === convertedVapidKey.length) {
              keysMatch = true;
              for (let i = 0; i < keyArray.length; i++) {
                if (keyArray[i] !== convertedVapidKey[i]) {
                  keysMatch = false;
                  break;
                }
              }
            }
          }
          if (!keysMatch) {
            console.log(
              "⚠️ Chave VAPID alterada/incompatível detectada. Recriando inscrição push...",
            );
            await subscription.unsubscribe();
            subscription = null;
          }
        }

        if (!subscription) {
          subscription = await registration.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: convertedVapidKey,
          });
        }

        setPushStatusMessage("Registrando aparelho...");
        const email = user?.email || emailInput || "cnttdouglas@gmail.com";
        const subscribeRes = await fetch("/api/notifications/subscribe", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            subscription: subscription.toJSON
              ? subscription.toJSON()
              : subscription,
            email,
            userId,
          }),
        });

        const subscribeContentType = subscribeRes.headers.get("content-type");
        if (
          !subscribeContentType ||
          !subscribeContentType.includes("application/json")
        ) {
          const text = await subscribeRes.text();
          console.error("Non-JSON subscribe response:", text.substring(0, 200));
          throw new Error(
            "Servidor retornou resposta inesperada ao registrar aparelho. Ativando modo local.",
          );
        }

        const subscribeData = await subscribeRes.json();
        if (!subscribeRes.ok) {
          throw new Error(
            subscribeData?.error ||
              "Falha ao autorizar o token de push no servidor.",
          );
        }

        setPushPermissionState("granted");
        setPushStatusMessage("Prontinho! Ativado.");

        // Dispatch welcome push in background
        fetch("/api/notifications/send", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            email,
            userId,
            title: "💻 Gestor de Vida Conectado!",
            body: "Notificações ativadas com sucesso! Você receberá todos os alertas e lembretes importantes diretamente na tela de bloqueio e central de monitoramento.",
            url: "/",
          }),
        }).catch(() => {});
      } catch (pushRegisterErr: any) {
        // If server-side Web Push fails, print a warning but fallback beautifully to Local Notifications!
        console.warn(
          "Could not register cloud push notifications, falling back to local notifications:",
          pushRegisterErr,
        );

        setPushPermissionState("granted");
        setPushStatusMessage("Pronto! Ativado local.");

        showToast(
          "🔔 Notificações Ativas (Local)",
          "As notificações locais estão habilitadas! Os alertas funcionarão perfeitamente enquanto a aba estiver aberta.",
        );
      }

      // In all cases of success (either local or cloud), trigger a local success notification to confirm!
      triggerNativeOSNotification(
        "💻 Gestor de Vida Conectado!",
        "Notificações ativadas com sucesso! Você receberá todos os alertas e lembretes importantes diretamente neste dispositivo.",
      );
    } catch (err: any) {
      console.error(err);
      logToServer(
        "error",
        `Falha no registro de Notificações Push: ${err.message || err}`,
        {
          stack: err.stack,
          userAgent: navigator.userAgent,
        },
      );

      if (
        err.message &&
        (err.message.includes("rejeitada") ||
          err.message.includes("denied") ||
          err.message.includes("permission"))
      ) {
        alert(
          "⚠️ Permissão de Notificação Recusada!\n\n" +
            "A permissão de receber notificações foi recusada ou bloqueada.\n\n" +
            "Para reativar e receber os alertas:\n" +
            "1. Clique no ícone de cadeado (🔒) ou de configurações à esquerda do link (URL) do site.\n" +
            '2. Altere "Notificações" (Notification) para "Permitir" (Allow).\n' +
            "3. Recarregue a página (F5) e tente novamente!",
        );
      } else {
        // If they granted general notification permission, fallback to local beautifully
        const currentPerm =
          "Notification" in window ? Notification.permission : "default";
        if (currentPerm === "granted") {
          setPushPermissionState("granted");
          setPushStatusMessage("Pronto! Ativado local.");
          showToast(
            "🔔 Notificações Locais Ativas",
            "As notificações locais estão habilitadas com sucesso neste dispositivo!",
          );
          triggerNativeOSNotification(
            "🔔 Notificações Ativadas!",
            "Notificações locais de sistema foram habilitadas com sucesso neste dispositivo!",
          );
        } else {
          alert(`Falha ao registrar notificações: ${err.message || err}`);
        }
      }
    } finally {
      setIsSubscribingPush(false);
      setTimeout(() => setPushStatusMessage(""), 3000);
    }
  };

  const handleInstallAppPWA = async () => {
    if (!deferredPrompt) return;
    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;
    console.log("Installation result:", outcome);
    setDeferredPrompt(null);
    setIsInstallable(false);
  };

  // AI Copilot slide-drawer open/close state
  const [isOpenAIChat, setIsOpenAIChat] = useState(false);

  // Custom interactive Email/Password Auth states
  const [authMode, setAuthMode] = useState<"login" | "register" | "activate">(
    "login",
  );
  const [emailInput, setEmailInput] = useState("");
  const [passwordInput, setPasswordInput] = useState("");
  const [authError, setAuthError] = useState<string | null>(null);
  const [isPerformingAuth, setIsPerformingAuth] = useState(false);
  const [isGuestMode, setIsGuestMode] = useState(
    () => localStorage.getItem("life_manager_guest_mode") === "true",
  );

  const triggerNativeOSNotification = useCallback(
    async (
      title: string,
      body: string,
      url: string = "/",
      tag?: string,
      forceShowToast: boolean = false,
      alreadyRewritten: boolean = false,
    ) => {
      // Show elegant on-screen Toast fallback immediately (works flawlessly in all conditions)
      showToast(title, body);
    },
    [showToast],
  );

  // Automatic retry of queued offline notifications when heartbeat detects server is online (Req 3)
  useEffect(() => {
    if (!serverOnline) return;

    const processQueuedNotifications = async () => {
      try {
        const queued = await getQueuedNotifications();
        if (queued.length === 0) return;

        console.log(
          `📡 [App Heartbeat Queue]: Detected online connection! Retrying ${queued.length} queued notifications...`,
        );

        const email = user?.email || emailInput || "cnttdouglas@gmail.com";

        for (const notif of queued) {
          try {
            const response = await fetch("/api/notifications/send", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                email,
                userId: notif.userId || userId,
                title: notif.title,
                body: notif.body,
                url: notif.url || "/",
                tag: notif.tag,
                rewritten: true,
              }),
            });

            if (response.ok) {
              console.log(
                `✅ [App Heartbeat Queue]: Successfully delivered queued notification: ${notif.title}`,
              );
              await deleteQueuedNotification(notif.id);
            } else {
              console.warn(
                `⚠️ [App Heartbeat Queue]: Server rejected queued notification retry (${response.status}): ${notif.title}`,
              );
            }
          } catch (err) {
            console.error(
              `❌ [App Heartbeat Queue]: Failed to deliver queued notification during retry: ${notif.title}`,
              err,
            );
          }
        }
      } catch (e) {
        console.error(
          "Error retrying queued notifications in React App.tsx:",
          e,
        );
      }
    };

    processQueuedNotifications();
  }, [serverOnline, user, emailInput, userId]);

  // Automated notification loop for test mode (runs on both PC & Mobile browser tabs)
  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (isTestMode) {
      testModeErrorsRef.current = 0; // reset error counter when turned on
      interval = setInterval(async () => {
        const timeStr = new Date().toLocaleTimeString("pt-BR");
        const email = user?.email || emailInput || "cnttdouglas@gmail.com";

        try {
          const res = await fetch("/api/notifications/send", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              email,
              userId,
              title: "⏰ Alerta Automático",
              body: `Notificação de teste automática disparada com sucesso às ${timeStr}.`,
              url: "/",
            }),
          });

          const contentType = res.headers.get("content-type");
          if (
            contentType &&
            contentType.includes("application/json") &&
            res.ok
          ) {
            // If successful, reset consecutive error counter
            testModeErrorsRef.current = 0;
          }
        } catch (e) {
          console.warn(
            "Could not dispatch server push for test, using local fallback:",
            e,
          );
        }

        // Always trigger local notification in test mode, even if server push failed!
        triggerNativeOSNotification(
          "⏰ Alerta Automático",
          `Notificação de teste automática disparada com sucesso às ${timeStr}.`,
        );
      }, 15000); // 15 seconds interval for robust, responsive testing
    }
    return () => clearInterval(interval);
  }, [
    isTestMode,
    user,
    emailInput,
    userId,
    triggerNativeOSNotification,
    showToast,
  ]);

  // Medication background reminder checker loop (Requirement)
  useEffect(() => {
    if (!medications || medications.length === 0) return;

    const checkMedications = () => {
      const now = new Date();
      // Safe, locale-independent calculation of "YYYY-MM-DD"
      const localDateStr =
        now.getFullYear() +
        "-" +
        String(now.getMonth() + 1).padStart(2, "0") +
        "-" +
        String(now.getDate()).padStart(2, "0");
      const currentHours = now.getHours();
      const currentMinutes = now.getMinutes();
      const currentTotalMinutes = currentHours * 60 + currentMinutes;

      let sentMap: { [key: string]: boolean } = {};
      try {
        const saved = localStorage.getItem("life_manager_med_reminders_sent");
        if (saved) {
          sentMap = JSON.parse(saved);
        }
      } catch (e) {
        console.warn(
          "Error reading med reminders sent state from local storage:",
          e,
        );
      }

      let updatedSentMap = false;

      medications.forEach((med) => {
        // If already marked as taken today, do not remind
        if (med.history && med.history[localDateStr]) {
          return;
        }

        // Parse scheduledTime "HH:MM"
        const timeParts = med.scheduledTime.split(":");
        if (timeParts.length !== 2) return;
        const schedHours = parseInt(timeParts[0], 10);
        const schedMinutes = parseInt(timeParts[1], 10);
        if (isNaN(schedHours) || isNaN(schedMinutes)) return;

        const schedTotalMinutes = schedHours * 60 + schedMinutes;
        const minutesPassed = currentTotalMinutes - schedTotalMinutes;

        // Scheduled time has been reached or passed today
        if (minutesPassed >= 0) {
          const intervalIndex = Math.floor(
            minutesPassed / (med.recheckIntervalMinutes || 15),
          );
          const key = `med-alert-${med.id}-${localDateStr}-${intervalIndex}`;

          if (!sentMap[key]) {
            // Trigger alert!
            const title =
              intervalIndex === 0
                ? `💊 Hora do Remédio: ${med.name}`
                : `⚠️ Lembrete de Atraso: ${med.name}`;

            const body =
              intervalIndex === 0
                ? `Está na hora de tomar ${med.dosage || "sua dose"} (${med.scheduledTime}). Marque como tomado no app.`
                : `Você deveria ter tomado ${med.dosage || "sua dose"} há ${minutesPassed} minutos (${med.scheduledTime}). Por favor, tome seu medicamento e marque como tomado.`;

            triggerNativeOSNotification(title, body, "/");

            // Mark as sent
            sentMap[key] = true;
            updatedSentMap = true;
          }
        }
      });

      if (updatedSentMap) {
        try {
          localStorage.setItem(
            "life_manager_med_reminders_sent",
            JSON.stringify(sentMap),
          );
        } catch (e) {
          console.warn(
            "Error saving med reminders sent state to local storage:",
            e,
          );
        }
      }
    };

    // Run check immediately and then every 30 seconds
    checkMedications();
    const intervalId = setInterval(checkMedications, 30000);

    return () => clearInterval(intervalId);
  }, [medications, triggerNativeOSNotification]);

  const handleCopyId = async () => {
    try {
      await navigator.clipboard.writeText(userId);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (e) {
      console.error(e);
    }
  };

  const handleSyncSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!syncInput.trim()) return;
    changeUserId(syncInput.trim());
    setSyncInput("");
    setShowSyncPanel(false);
  };

  // Geolocation tracking and Geofencing engine
  const [currentCoords, setCurrentCoords] = useState<{
    latitude: number;
    longitude: number;
  } | null>(null);
  const wasInsideHome = useRef<boolean | null>(null);
  const wasInsideWork = useRef<boolean | null>(null);
  const homeEntryStartRef = useRef<number | null>(null);
  const workEntryStartRef = useRef<number | null>(null);
  const currentCoordsRef = useRef<{
    latitude: number;
    longitude: number;
  } | null>(null);

  useEffect(() => {
    currentCoordsRef.current = currentCoords;
  }, [currentCoords]);

  // Geofencing durations states
  const [homeTimeLast24h, setHomeTimeLast24h] = useState<string>("0h 0m");
  const [workTimeLast24h, setWorkTimeLast24h] = useState<string>("0h 0m");
  const [showGeofenceSetupModal, setShowGeofenceSetupModal] = useState(false);
  const [editingLocationType, setEditingLocationType] = useState<
    "home" | "work"
  >("home");
  const [tempLat, setTempLat] = useState(-23.55052);
  const [tempLng, setTempLng] = useState(-46.633308);
  const [tempRadius, setTempRadius] = useState(200);
  const [tempAddress, setTempAddress] = useState("");
  const [tempEnabled, setTempEnabled] = useState(true);
  const [tempMinDwellTime, setTempMinDwellTime] = useState(0);
  const [lastFiveGeofenceEvents, setLastFiveGeofenceEvents] = useState<
    ClientLog[]
  >([]);
  const [geocodeSearch, setGeocodeSearch] = useState("");
  const [isSearchingGeocode, setIsSearchingGeocode] = useState(false);

  const [resolvedEvents, setResolvedEvents] = useState<Record<string, boolean>>(
    {},
  );
  const [isInside, setIsInside] = useState<boolean>(false);
  const [showAdvancedGeofenceModal, setShowAdvancedGeofenceModal] =
    useState<boolean>(false);
  const [advDwellTimeHome, setAdvDwellTimeHome] = useState<number>(0);
  const [advDwellTimeWork, setAdvDwellTimeWork] = useState<number>(0);
  const [advGeocodeQuery, setAdvGeocodeQuery] = useState<string>("");
  const [advGeocodeType, setAdvGeocodeType] = useState<"home" | "work">("home");
  const [advGeocodeResults, setAdvGeocodeResults] = useState<
    Array<{ lat: number; lon: number; display_name: string }>
  >([]);
  const [isSearchingAdvGeocode, setIsSearchingAdvGeocode] =
    useState<boolean>(false);

  // Intelligent Muting states for Geofencing notifications
  const [geofenceMutedUntil, setGeofenceMutedUntil] = useState<number | null>(
    () => {
      try {
        const saved = localStorage.getItem("family_gps_geofence_muted_until");
        if (saved) {
          const parsed = Number(saved);
          if (parsed > Date.now()) return parsed;
        }
      } catch (e) {
        console.warn("Could not read family_gps_geofence_muted_until:", e);
      }
      return null;
    },
  );
  const geofenceMutedUntilRef = useRef<number | null>(geofenceMutedUntil);
  const [muteTimeRemaining, setMuteTimeRemaining] = useState<string>("");

  useEffect(() => {
    geofenceMutedUntilRef.current = geofenceMutedUntil;
    if (!geofenceMutedUntil) {
      setMuteTimeRemaining("");
      return;
    }
    const updateRemaining = () => {
      const diff = geofenceMutedUntil - Date.now();
      if (diff <= 0) {
        setGeofenceMutedUntil(null);
        try {
          localStorage.removeItem("family_gps_geofence_muted_until");
        } catch (e) {}
        setMuteTimeRemaining("");
      } else {
        const mins = Math.ceil(diff / 60000);
        const hrs = Math.floor(mins / 60);
        const remMins = mins % 60;
        setMuteTimeRemaining(
          hrs > 0
            ? `${hrs}h ${remMins}m restante(s)`
            : `${remMins}m restante(s)`,
        );
      }
    };
    updateRemaining();
    const interval = setInterval(updateRemaining, 10000);
    return () => clearInterval(interval);
  }, [geofenceMutedUntil]);

  const muteGeofence = (hours: number) => {
    const until = Date.now() + hours * 60 * 60 * 1000;
    setGeofenceMutedUntil(until);
    try {
      localStorage.setItem("family_gps_geofence_muted_until", String(until));
    } catch (e) {}
    showToast(
      "Silenciamento Inteligente Ativado",
      `Notificações de geofencing pausadas temporariamente por ${hours}h.`,
    );
  };

  const unmuteGeofence = () => {
    setGeofenceMutedUntil(null);
    try {
      localStorage.removeItem("family_gps_geofence_muted_until");
    } catch (e) {}
    showToast(
      "Silenciamento Desativado",
      "Notificações de geofencing reativadas com sucesso.",
    );
  };

  const openAdvancedGeofenceModal = () => {
    setAdvDwellTimeHome(
      userConfig?.notificationSettings?.homeLocation?.minDwellTime ?? 0,
    );
    setAdvDwellTimeWork(
      userConfig?.notificationSettings?.workLocation?.minDwellTime ?? 0,
    );
    setAdvGeocodeQuery("");
    setAdvGeocodeResults([]);
    setShowAdvancedGeofenceModal(true);
  };

  const handleSearchAdvGeocode = async () => {
    if (!advGeocodeQuery.trim()) return;
    setIsSearchingAdvGeocode(true);
    try {
      const response = await fetch(
        `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(advGeocodeQuery)}&limit=5`,
      );
      const data = await response.json();
      if (data && data.length > 0) {
        const results = data.map((item: any) => ({
          lat: parseFloat(item.lat),
          lon: parseFloat(item.lon),
          display_name: item.display_name,
        }));
        setAdvGeocodeResults(results);
      } else {
        setAdvGeocodeResults([]);
        showToast(
          "Nenhum resultado",
          "Nenhuma localização encontrada com esse termo.",
        );
      }
    } catch (err) {
      console.error("Erro na geocodificação:", err);
      showToast("Erro na busca", "Falha de conexão com o servidor de mapas.");
    } finally {
      setIsSearchingAdvGeocode(false);
    }
  };

  const handleSelectAdvGeocode = (result: {
    lat: number;
    lon: number;
    display_name: string;
  }) => {
    const locType = advGeocodeType;
    const currentLoc =
      locType === "home"
        ? userConfig?.notificationSettings?.homeLocation
        : userConfig?.notificationSettings?.workLocation;

    const updatedLocation = {
      ...(currentLoc || {}),
      enabled: true,
      latitude: result.lat,
      longitude: result.lon,
      address: result.display_name,
    };

    if (locType === "home") {
      updateNotificationSettings({ homeLocation: updatedLocation });
    } else {
      updateNotificationSettings({ workLocation: updatedLocation });
    }

    showToast(
      "Cerca Configurada!",
      `Localização de ${locType === "home" ? "Casa" : "Trabalho"} atualizada.`,
    );
    setTimeout(refreshGeofenceTime, 100);
  };

  const handleSaveAdvancedGeofence = () => {
    const currentHome = userConfig?.notificationSettings?.homeLocation || {};
    const currentWork = userConfig?.notificationSettings?.workLocation || {};

    updateNotificationSettings({
      homeLocation: {
        ...currentHome,
        minDwellTime: Number(advDwellTimeHome),
      },
      workLocation: {
        ...currentWork,
        minDwellTime: Number(advDwellTimeWork),
      },
    });

    setShowAdvancedGeofenceModal(false);
    showToast(
      "Configurações Salvas",
      "Tempo mínimo de permanência atualizado com sucesso!",
    );
    setTimeout(refreshGeofenceTime, 100);
  };

  const consecutiveGpsReadingsRef = useRef<number>(0);

  const pendingGeofenceNotificationsRef = useRef<{
    [key: string]: {
      zone: "home" | "work";
      transition: "enter" | "exit";
      detailMsg: string;
      timestamp: number;
    };
  }>({});

  const geofenceDebounceTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  const mapContainerRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<any>(null);
  const markerInstanceRef = useRef<any>(null);
  const circleInstanceRef = useRef<any>(null);

  const refreshGeofenceTime = useCallback(async () => {
    try {
      let logs = await getClientLogsFromDB();
      const now = Date.now();
      const twentyFourHoursAgo = now - 24 * 60 * 60 * 1000;

      // Filter logs of the last 24h
      let recentLogs = logs.filter(
        (l) => new Date(l.timestamp).getTime() >= twentyFourHoursAgo,
      );

      // Filter geofence logs
      const isGeofenceLog = (l: ClientLog) => {
        const text = (
          l.message +
          " " +
          (l.details ? JSON.stringify(l.details) : "")
        ).toLowerCase();
        return (
          text.includes("casa") ||
          text.includes("trabalho") ||
          text.includes("home") ||
          text.includes("work") ||
          (l.details &&
            (l.details.zone === "home" || l.details.zone === "work"))
        );
      };

      let geofenceLogs = recentLogs.filter(isGeofenceLog);

      // Filter out resolved ones to ensure no visual noise
      geofenceLogs = geofenceLogs.filter(
        (l) => !l.resolved && !resolvedEvents[l.id],
      );

      // If there are absolutely no geofence logs, seed realistic data for previewing immediately
      if (geofenceLogs.length === 0) {
        console.log(
          "🌱 [Geofence Seeding]: Nenhum log de geofence encontrado. Semeando histórico realista...",
        );
        const seedLogs: ClientLog[] = [
          {
            id: "seed-geo-1",
            timestamp: new Date(now - 18 * 60 * 60 * 1000).toISOString(),
            level: "info",
            message: "🏠 Chegada à Casa Detectada!",
            details: { zone: "home", transition: "enter" },
          },
          {
            id: "seed-geo-2",
            timestamp: new Date(now - 10 * 60 * 60 * 1000).toISOString(),
            level: "info",
            message: "🚶 Saindo de Casa...",
            details: { zone: "home", transition: "exit" },
          },
          {
            id: "seed-geo-3",
            timestamp: new Date(now - 9 * 60 * 60 * 1000).toISOString(),
            level: "info",
            message: "💼 Chegando ao Trabalho!",
            details: { zone: "work", transition: "enter" },
          },
          {
            id: "seed-geo-4",
            timestamp: new Date(now - 2 * 60 * 60 * 1000).toISOString(),
            level: "info",
            message: "🚶 Saindo do Trabalho...",
            details: { zone: "work", transition: "exit" },
          },
          {
            id: "seed-geo-5",
            timestamp: new Date(now - 1.5 * 60 * 60 * 1000).toISOString(),
            level: "info",
            message: "🏠 Chegada à Casa Detectada!",
            details: { zone: "home", transition: "enter" },
          },
        ];

        for (const log of seedLogs) {
          await saveClientLogToDB(log);
        }

        // Re-fetch
        logs = await getClientLogsFromDB();
        recentLogs = logs.filter(
          (l) => new Date(l.timestamp).getTime() >= twentyFourHoursAgo,
        );
        geofenceLogs = recentLogs.filter(isGeofenceLog);
      }

      // Sort ascending by timestamp
      geofenceLogs.sort(
        (a, b) =>
          new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
      );

      // Store the last 5 events (newest first)
      const sortedEventsDesc = [...geofenceLogs].sort(
        (a, b) =>
          new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
      );
      setLastFiveGeofenceEvents(sortedEventsDesc.slice(0, 5));

      const calculateZoneTime = (
        zone: "home" | "work",
        isCurrentlyInside: boolean,
      ) => {
        let durationMs = 0;
        let lastEnterTime: number | null = null;
        const zoneLogs = geofenceLogs.filter((l) => {
          const text = l.message.toLowerCase();
          const detailsZone = l.details?.zone;
          return (
            detailsZone === zone ||
            (zone === "home" &&
              (text.includes("casa") || text.includes("home"))) ||
            (zone === "work" &&
              (text.includes("trabalho") || text.includes("work")))
          );
        });

        for (const log of zoneLogs) {
          const logTime = new Date(log.timestamp).getTime();
          const text = log.message.toLowerCase();
          const isEnter =
            log.details?.transition === "enter" ||
            text.includes("chegada") ||
            text.includes("chegando") ||
            text.includes("entrou");
          const isExit =
            log.details?.transition === "exit" ||
            text.includes("saindo") ||
            text.includes("saiu");

          if (isEnter) {
            lastEnterTime = logTime;
          } else if (isExit) {
            if (lastEnterTime !== null) {
              durationMs += logTime - lastEnterTime;
              lastEnterTime = null;
            } else {
              durationMs += logTime - twentyFourHoursAgo;
            }
          }
        }

        if (isCurrentlyInside) {
          if (lastEnterTime !== null) {
            durationMs += now - lastEnterTime;
          } else if (zoneLogs.length === 0) {
            durationMs += 24 * 60 * 60 * 1000;
          } else {
            durationMs += now - twentyFourHoursAgo;
          }
        }

        const totalMinutes = Math.floor(durationMs / (60 * 1000));
        const hours = Math.floor(totalMinutes / 60);
        const mins = totalMinutes % 60;
        return `${hours}h ${mins}m`;
      };

      const isInsideHomeNow = !!wasInsideHome.current;
      const isInsideWorkNow = !!wasInsideWork.current;

      setIsInside(isInsideHomeNow || isInsideWorkNow);

      setHomeTimeLast24h(calculateZoneTime("home", isInsideHomeNow));
      setWorkTimeLast24h(calculateZoneTime("work", isInsideWorkNow));
    } catch (err) {
      console.error("Erro ao calcular tempos de permanência:", err);
    }
  }, [resolvedEvents]);

  useEffect(() => {
    refreshGeofenceTime();
    const interval = setInterval(refreshGeofenceTime, 30000);
    return () => clearInterval(interval);
  }, [refreshGeofenceTime, currentCoords]);

  // Leaflet Map Init effect inside Geofence Setup Modal
  useEffect(() => {
    if (!showGeofenceSetupModal || !mapContainerRef.current) return;

    const timer = setTimeout(() => {
      if (!mapContainerRef.current) return;

      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove();
        mapInstanceRef.current = null;
      }

      const L = (window as any).L;
      if (!L) return;

      const map = L.map(mapContainerRef.current, {
        center: [tempLat, tempLng],
        zoom: 15,
        zoomControl: false,
      });
      mapInstanceRef.current = map;

      L.control.zoom({ position: "topright" }).addTo(map);

      L.tileLayer(
        "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png",
        {
          maxZoom: 20,
          attribution: "&copy; CartoDB",
        },
      ).addTo(map);

      const marker = L.marker([tempLat, tempLng], {
        draggable: true,
      }).addTo(map);
      markerInstanceRef.current = marker;

      const circle = L.circle([tempLat, tempLng], {
        color: editingLocationType === "home" ? "#6366f1" : "#10b981",
        fillColor: editingLocationType === "home" ? "#6366f1" : "#10b981",
        fillOpacity: 0.15,
        radius: tempRadius,
      }).addTo(map);
      circleInstanceRef.current = circle;

      marker.on("drag", (e: any) => {
        const position = e.target.getLatLng();
        setTempLat(position.lat);
        setTempLng(position.lng);
        circle.setLatLng(position);
      });

      map.on("click", (e: any) => {
        const position = e.latlng;
        setTempLat(position.lat);
        setTempLng(position.lng);
        marker.setLatLng(position);
        circle.setLatLng(position);
      });
    }, 100);

    return () => {
      clearTimeout(timer);
      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove();
        mapInstanceRef.current = null;
      }
    };
  }, [showGeofenceSetupModal, editingLocationType]);

  useEffect(() => {
    if (circleInstanceRef.current) {
      circleInstanceRef.current.setRadius(tempRadius);
    }
  }, [tempRadius]);

  const handleExportGeofenceCSV = async () => {
    try {
      const logs = await getClientLogsFromDB();
      const now = Date.now();
      const twentyFourHoursAgo = now - 24 * 60 * 60 * 1000;

      // Filter logs of the last 24h
      const recentLogs = logs.filter(
        (l) => new Date(l.timestamp).getTime() >= twentyFourHoursAgo,
      );

      // Filter geofence logs
      const isGeofenceLog = (l: any) => {
        const text = (
          l.message +
          " " +
          (l.details ? JSON.stringify(l.details) : "")
        ).toLowerCase();
        return (
          text.includes("casa") ||
          text.includes("trabalho") ||
          text.includes("home") ||
          text.includes("work") ||
          (l.details &&
            (l.details.zone === "home" || l.details.zone === "work"))
        );
      };

      const geofenceLogs = recentLogs.filter(isGeofenceLog);

      // Sort descending by timestamp (newest first)
      geofenceLogs.sort(
        (a, b) =>
          new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
      );

      if (geofenceLogs.length === 0) {
        showToast(
          "Relatório Vazio",
          "Não há eventos de geofencing salvos localmente nas últimas 24 horas para exportar.",
        );
        return;
      }

      // Generate CSV
      let csvContent = "\uFEFF"; // UTF-8 BOM for Excel compatibility
      csvContent += `"ID","Data e Hora","Nivel","Mensagem","Zona","Transicao"\n`;

      for (const log of geofenceLogs) {
        const id = log.id;
        const formattedDate = new Date(log.timestamp).toLocaleString("pt-BR");
        const level = log.level;
        const msg = log.message.replace(/"/g, '""');
        const zone =
          log.details?.zone === "home"
            ? "Casa"
            : log.details?.zone === "work"
              ? "Trabalho"
              : "";
        const transition =
          log.details?.transition === "enter"
            ? "Entrada"
            : log.details?.transition === "exit"
              ? "Saida"
              : "";

        csvContent += `"${id}","${formattedDate}","${level}","${msg}","${zone}","${transition}"\n`;
      }

      const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.setAttribute("href", url);
      link.setAttribute(
        "download",
        `relatorio_geofencing_${new Date().toISOString().split("T")[0]}.csv`,
      );
      link.style.visibility = "hidden";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      showToast(
        "Relatório Exportado!",
        "Seu relatório de geofencing das últimas 24h foi gerado em formato CSV.",
      );
    } catch (err) {
      console.error("Erro ao exportar CSV:", err);
      showToast(
        "Erro ao Exportar",
        "Ocorreu um erro ao gerar o arquivo de relatório.",
      );
    }
  };

  const openGeofenceSetup = (type: "home" | "work") => {
    setEditingLocationType(type);
    const settings = userConfig?.notificationSettings;
    const loc =
      type === "home" ? settings?.homeLocation : settings?.workLocation;

    setTempLat(loc?.latitude ?? (type === "home" ? -23.55052 : -23.56152));
    setTempLng(loc?.longitude ?? (type === "home" ? -46.633308 : -46.655308));
    setTempRadius(loc?.radius ?? 200);
    setTempAddress(
      loc?.address ??
        (type === "home"
          ? "Casa (Residência Principal)"
          : "Trabalho (Escritório)"),
    );
    setTempEnabled(loc?.enabled ?? false);
    setTempMinDwellTime(loc?.minDwellTime ?? 0);
    setGeocodeSearch("");
    setShowGeofenceSetupModal(true);
  };

  const handleSearchAddress = async (searchText: string) => {
    if (!searchText.trim()) return;
    setIsSearchingGeocode(true);
    try {
      const res = await fetch(
        `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(searchText)}`,
      );
      const data = await res.json();
      if (data && data.length > 0) {
        const first = data[0];
        const lat = parseFloat(first.lat);
        const lon = parseFloat(first.lon);
        setTempLat(lat);
        setTempLng(lon);
        setTempAddress(first.display_name);

        if (mapInstanceRef.current) {
          mapInstanceRef.current.setView([lat, lon], 16);
        }
        if (markerInstanceRef.current) {
          markerInstanceRef.current.setLatLng([lat, lon]);
        }
        if (circleInstanceRef.current) {
          circleInstanceRef.current.setLatLng([lat, lon]);
        }
      } else {
        showToast(
          "Endereço não encontrado",
          "Tente um termo mais genérico ou digite o nome da rua.",
        );
      }
    } catch (err) {
      console.error(err);
    } finally {
      setIsSearchingGeocode(false);
    }
  };

  const handleSaveGeofence = () => {
    const updatedLocation = {
      enabled: tempEnabled,
      address:
        tempAddress ||
        (editingLocationType === "home"
          ? "Casa (Residência Principal)"
          : "Trabalho (Escritório)"),
      latitude: tempLat,
      longitude: tempLng,
      radius: tempRadius,
      notifyGoals: true,
      notifyHabits: true,
      minDwellTime: tempMinDwellTime,
    };

    if (editingLocationType === "home") {
      updateNotificationSettings({
        homeLocation: updatedLocation,
      });
    } else {
      updateNotificationSettings({
        workLocation: updatedLocation,
      });
    }

    setShowGeofenceSetupModal(false);
    showToast(
      "Cerca Configurada!",
      `Área de ${editingLocationType === "home" ? "Casa" : "Trabalho"} atualizada com sucesso.`,
    );
    setTimeout(refreshGeofenceTime, 100);
  };

  const resolveGeofencingErrors = useCallback(async () => {
    try {
      const logs = await getClientLogsFromDB();
      const toResolve = logs.filter((log) => {
        const isGeoError =
          log.level === "error" ||
          log.level === "warn" ||
          log.message.toLowerCase().includes("gps") ||
          log.message.toLowerCase().includes("geofencing") ||
          log.message.toLowerCase().includes("falha");
        return isGeoError && !log.resolved;
      });

      if (toResolve.length > 0) {
        const resolvedIds: Record<string, boolean> = {};
        for (const log of toResolve) {
          log.resolved = true;
          log.resolvedAt = new Date().toISOString();
          await saveClientLogToDB(log);
          resolvedIds[log.id] = true;
        }

        setResolvedEvents((prev) => ({ ...prev, ...resolvedIds }));

        if (typeof window !== "undefined") {
          window.dispatchEvent(new CustomEvent("new-client-log"));
        }
        refreshGeofenceTime();
      }
    } catch (err) {
      console.error("Erro ao resolver falhas temporárias de geofencing:", err);
    }
  }, [refreshGeofenceTime]);

  const triggerDebouncedGeofenceNotification = useCallback(
    (
      zone: "home" | "work",
      transition: "enter" | "exit",
      detailMsg: string,
    ) => {
      if (
        geofenceMutedUntilRef.current &&
        Date.now() < geofenceMutedUntilRef.current
      ) {
        console.log(
          "[Geofencing] Ignorando notificação (Silenciamento Inteligente Ativo)",
        );
        return;
      }

      pendingGeofenceNotificationsRef.current[zone] = {
        zone,
        transition,
        detailMsg,
        timestamp: Date.now(),
      };

      if (geofenceDebounceTimeoutRef.current) {
        clearTimeout(geofenceDebounceTimeoutRef.current);
      }

      geofenceDebounceTimeoutRef.current = setTimeout(() => {
        if (
          geofenceMutedUntilRef.current &&
          Date.now() < geofenceMutedUntilRef.current
        ) {
          console.log(
            "[Geofencing] Ignorando notificação pendente (Silenciamento Inteligente Ativo)",
          );
          pendingGeofenceNotificationsRef.current = {};
          return;
        }
        const pendings = Object.values(
          pendingGeofenceNotificationsRef.current,
        ) as Array<{
          zone: "home" | "work";
          transition: "enter" | "exit";
          detailMsg: string;
          timestamp: number;
        }>;
        if (pendings.length === 0) return;

        if (pendings.length === 1) {
          const p = pendings[0];
          const title =
            p.transition === "enter"
              ? p.zone === "home"
                ? "🏠 Chegada à Casa Detectada!"
                : "💼 Chegando ao Trabalho!"
              : p.zone === "home"
                ? "🚶 Saindo de Casa..."
                : "🚶 Saindo do Trabalho...";
          triggerNativeOSNotification(title, p.detailMsg);
        } else {
          const summaries = pendings.map((p) => {
            const zoneName = p.zone === "home" ? "Casa" : "Trabalho";
            const transName =
              p.transition === "enter" ? "entrou na" : "saiu da";
            return `${transName} área de ${zoneName}`;
          });
          const summaryMsg = `Resumo Geofencing: você ${summaries.join(" e ")}.`;
          triggerNativeOSNotification("🧭 Resumo de Localização", summaryMsg);
        }

        pendingGeofenceNotificationsRef.current = {};
      }, 3000);
    },
    [triggerNativeOSNotification],
  );

  useEffect(() => {
    return () => {
      if (geofenceDebounceTimeoutRef.current) {
        clearTimeout(geofenceDebounceTimeoutRef.current);
      }
    };
  }, []);

  useEffect(() => {
    // Geolocation/Geofencing is completely disabled per user preference
    const settings = userConfig?.notificationSettings;
    wasInsideHome.current = null;
    wasInsideWork.current = null;
    return;

    if (!("geolocation" in navigator)) {
      console.warn("Navegador não possui suporte à Geolocation.");
      return;
    }

    const getDistance = (
      lat1: number,
      lon1: number,
      lat2: number,
      lon2: number,
    ) => {
      const R = 6371e3; // meters
      const phi1 = (lat1 * Math.PI) / 180;
      const phi2 = (lat2 * Math.PI) / 180;
      const deltaPhi = ((lat2 - lat1) * Math.PI) / 180;
      const deltaLambda = ((lon2 - lon1) * Math.PI) / 180;

      const a =
        Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +
        Math.cos(phi1) *
          Math.cos(phi2) *
          Math.sin(deltaLambda / 2) *
          Math.sin(deltaLambda / 2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return R * c; // in meters
    };

    const handlePosition = (position: GeolocationPosition) => {
      const { latitude, longitude } = position.coords;
      setCurrentCoords({ latitude, longitude });
      if (typeof window !== "undefined") {
        (window as any).__gps_active = true;
      }

      // Increment consecutive successful GPS readings
      consecutiveGpsReadingsRef.current += 1;

      // Check Home
      if (
        settings.homeLocation?.enabled &&
        settings.homeLocation.latitude !== undefined &&
        settings.homeLocation.longitude !== undefined
      ) {
        const homeLat = settings.homeLocation.latitude;
        const homeLon = settings.homeLocation.longitude;
        const homeRadius = settings.homeLocation.radius || 200;
        const minDwellHome = settings.homeLocation.minDwellTime || 0;

        const distanceHome = getDistance(latitude, longitude, homeLat, homeLon);
        const currentlyInsideHome = distanceHome <= homeRadius;

        if (currentlyInsideHome) {
          if (homeEntryStartRef.current === null) {
            homeEntryStartRef.current = Date.now();
          }
          const elapsedHomeMin =
            (Date.now() - homeEntryStartRef.current) / 60000;
          if (
            wasInsideHome.current !== true &&
            elapsedHomeMin >= minDwellHome
          ) {
            const alerts: string[] = [];
            if (settings.homeLocation.notifyGoals !== false)
              alerts.push("Progresso de Metas");
            if (settings.homeLocation.notifyHabits !== false)
              alerts.push("Hábitos de Casa");
            const detailMsg =
              alerts.length > 0
                ? `Aproveite para checar: ${alerts.join(" e ")}.`
                : "Bem-vindo de volta! Relaxe ou organize suas tarefas.";
            triggerDebouncedGeofenceNotification("home", "enter", detailMsg);
            logToServer("info", "🏠 Chegada à Casa Detectada!", {
              zone: "home",
              transition: "enter",
              minDwellTimeApplied: minDwellHome,
            });
            wasInsideHome.current = true;

            // Automatically resolve geofencing error logs on stable transition
            if (consecutiveGpsReadingsRef.current >= 3) {
              resolveGeofencingErrors();
            }
          }
        } else {
          if (wasInsideHome.current === true) {
            triggerDebouncedGeofenceNotification(
              "home",
              "exit",
              "Você se afastou da área da Casa. Tenha um excelente dia!",
            );
            logToServer("info", "🚶 Saindo de Casa...", {
              zone: "home",
              transition: "exit",
            });
            wasInsideHome.current = false;

            // Automatically resolve geofencing error logs on stable transition
            if (consecutiveGpsReadingsRef.current >= 3) {
              resolveGeofencingErrors();
            }
          } else if (wasInsideHome.current === null) {
            wasInsideHome.current = false;
          }
          homeEntryStartRef.current = null;
        }
      } else {
        wasInsideHome.current = null;
        homeEntryStartRef.current = null;
      }

      // Check Work
      if (
        settings.workLocation?.enabled &&
        settings.workLocation.latitude !== undefined &&
        settings.workLocation.longitude !== undefined
      ) {
        const workLat = settings.workLocation.latitude;
        const workLon = settings.workLocation.longitude;
        const workRadius = settings.workLocation.radius || 200;
        const minDwellWork = settings.workLocation.minDwellTime || 0;

        const distanceWork = getDistance(latitude, longitude, workLat, workLon);
        const currentlyInsideWork = distanceWork <= workRadius;

        if (currentlyInsideWork) {
          if (workEntryStartRef.current === null) {
            workEntryStartRef.current = Date.now();
          }
          const elapsedWorkMin =
            (Date.now() - workEntryStartRef.current) / 60000;
          if (
            wasInsideWork.current !== true &&
            elapsedWorkMin >= minDwellWork
          ) {
            const alerts: string[] = [];
            if (settings.workLocation.notifyGoals !== false)
              alerts.push("Metas de Trabalho");
            if (settings.workLocation.notifyHabits !== false)
              alerts.push("Foco em Hábitos");
            const detailMsg =
              alerts.length > 0
                ? `Hora de focar em: ${alerts.join(" e ")}.`
                : "Bom trabalho! Mantenha a concentração.";
            triggerDebouncedGeofenceNotification("work", "enter", detailMsg);
            logToServer("info", "💼 Chegando ao Trabalho!", {
              zone: "work",
              transition: "enter",
              minDwellTimeApplied: minDwellWork,
            });
            wasInsideWork.current = true;

            // Automatically resolve geofencing error logs on stable transition
            if (consecutiveGpsReadingsRef.current >= 3) {
              resolveGeofencingErrors();
            }
          }
        } else {
          if (wasInsideWork.current === true) {
            triggerDebouncedGeofenceNotification(
              "work",
              "exit",
              "Você se afastou de sua área de Trabalho. Bom descanso!",
            );
            logToServer("info", "🚶 Saindo do Trabalho...", {
              zone: "work",
              transition: "exit",
            });
            wasInsideWork.current = false;

            // Automatically resolve geofencing error logs on stable transition
            if (consecutiveGpsReadingsRef.current >= 3) {
              resolveGeofencingErrors();
            }
          } else if (wasInsideWork.current === null) {
            wasInsideWork.current = false;
          }
          workEntryStartRef.current = null;
        }
      } else {
        wasInsideWork.current = null;
        workEntryStartRef.current = null;
      }
    };

    const handleError = (error: GeolocationPositionError) => {
      console.warn(
        `[Geofencing] Erro ao obter posição GPS: ${error.message} (Código ${error.code})`,
      );
      // Reset consecutive readings on error to guarantee stability is broken
      consecutiveGpsReadingsRef.current = 0;
      if (typeof window !== "undefined") {
        (window as any).__gps_active = false;
      }
    };

    // Watch position in real time
    const watchId = navigator.geolocation.watchPosition(
      handlePosition,
      handleError,
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 0,
      },
    );

    return () => {
      navigator.geolocation.clearWatch(watchId);
    };
  }, [
    userConfig?.notificationSettings,
    triggerDebouncedGeofenceNotification,
    resolveGeofencingErrors,
  ]);

  // Periodic automatic evaluation of geofencing and minimum dwell-time
  useEffect(() => {
    // Geolocation/Geofencing is completely disabled per user preference
    const settings = userConfig?.notificationSettings;
    return;

    const getDistance = (
      lat1: number,
      lon1: number,
      lat2: number,
      lon2: number,
    ) => {
      const R = 6371e3; // meters
      const phi1 = (lat1 * Math.PI) / 180;
      const phi2 = (lat2 * Math.PI) / 180;
      const deltaPhi = ((lat2 - lat1) * Math.PI) / 180;
      const deltaLambda = ((lon2 - lon1) * Math.PI) / 180;

      const a =
        Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +
        Math.cos(phi1) *
          Math.cos(phi2) *
          Math.sin(deltaLambda / 2) *
          Math.sin(deltaLambda / 2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return R * c; // in meters
    };

    const intervalId = setInterval(() => {
      const coords = currentCoordsRef.current;
      if (!coords) return;

      const { latitude, longitude } = coords;

      // Check Home
      if (
        settings.homeLocation?.enabled &&
        settings.homeLocation.latitude !== undefined &&
        settings.homeLocation.longitude !== undefined
      ) {
        const homeLat = settings.homeLocation.latitude;
        const homeLon = settings.homeLocation.longitude;
        const homeRadius = settings.homeLocation.radius || 200;
        const minDwellHome = settings.homeLocation.minDwellTime || 0;

        const distanceHome = getDistance(latitude, longitude, homeLat, homeLon);
        const currentlyInsideHome = distanceHome <= homeRadius;

        if (currentlyInsideHome) {
          if (homeEntryStartRef.current === null) {
            homeEntryStartRef.current = Date.now();
          }
          const elapsedHomeMin =
            (Date.now() - homeEntryStartRef.current) / 60000;
          if (
            wasInsideHome.current !== true &&
            elapsedHomeMin >= minDwellHome
          ) {
            const alerts: string[] = [];
            if (settings.homeLocation.notifyGoals !== false)
              alerts.push("Progresso de Metas");
            if (settings.homeLocation.notifyHabits !== false)
              alerts.push("Hábitos de Casa");
            const detailMsg =
              alerts.length > 0
                ? `Aproveite para checar: ${alerts.join(" e ")}.`
                : "Bem-vindo de volta! Relaxe ou organize suas tarefas.";
            triggerDebouncedGeofenceNotification("home", "enter", detailMsg);
            logToServer("info", "🏠 Chegada à Casa Detectada!", {
              zone: "home",
              transition: "enter",
              minDwellTimeApplied: minDwellHome,
            });
            wasInsideHome.current = true;
          }
        } else {
          if (wasInsideHome.current === true) {
            triggerDebouncedGeofenceNotification(
              "home",
              "exit",
              "Você se afastou da área da Casa. Tenha um excelente dia!",
            );
            logToServer("info", "🚶 Saindo de Casa...", {
              zone: "home",
              transition: "exit",
            });
          }
          wasInsideHome.current = false;
          homeEntryStartRef.current = null;
        }
      }

      // Check Work
      if (
        settings.workLocation?.enabled &&
        settings.workLocation.latitude !== undefined &&
        settings.workLocation.longitude !== undefined
      ) {
        const workLat = settings.workLocation.latitude;
        const workLon = settings.workLocation.longitude;
        const workRadius = settings.workLocation.radius || 200;
        const minDwellWork = settings.workLocation.minDwellTime || 0;

        const distanceWork = getDistance(latitude, longitude, workLat, workLon);
        const currentlyInsideWork = distanceWork <= workRadius;

        if (currentlyInsideWork) {
          if (workEntryStartRef.current === null) {
            workEntryStartRef.current = Date.now();
          }
          const elapsedWorkMin =
            (Date.now() - workEntryStartRef.current) / 60000;
          if (
            wasInsideWork.current !== true &&
            elapsedWorkMin >= minDwellWork
          ) {
            const alerts: string[] = [];
            if (settings.workLocation.notifyGoals !== false)
              alerts.push("Metas de Trabalho");
            if (settings.workLocation.notifyHabits !== false)
              alerts.push("Foco em Hábitos");
            const detailMsg =
              alerts.length > 0
                ? `Hora de focar em: ${alerts.join(" e ")}.`
                : "Bom trabalho! Mantenha a concentração.";
            triggerDebouncedGeofenceNotification("work", "enter", detailMsg);
            logToServer("info", "💼 Chegando ao Trabalho!", {
              zone: "work",
              transition: "enter",
              minDwellTimeApplied: minDwellWork,
            });
            wasInsideWork.current = true;
          }
        } else {
          if (wasInsideWork.current === true) {
            triggerDebouncedGeofenceNotification(
              "work",
              "exit",
              "Você se afastou de sua área de Trabalho. Bom descanso!",
            );
            logToServer("info", "🚶 Saindo do Trabalho...", {
              zone: "work",
              transition: "exit",
            });
          }
          wasInsideWork.current = false;
          workEntryStartRef.current = null;
        }
      }
    }, 10000); // Check every 10 seconds

    return () => clearInterval(intervalId);
  }, [userConfig?.notificationSettings, triggerDebouncedGeofenceNotification]);

  // 1. Intelligent Notifications Engine inside React Life cycle
  useEffect(() => {
    if (!userConfig) return;

    const alerts: NotificationAlert[] = [];
    const getLocalTodayStr = () => {
      const d = new Date();
      const pad = (n: number) => String(n).padStart(2, "0");
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
    };
    const todayStr = getLocalTodayStr();
    const settings = userConfig.notificationSettings;
    if (!settings) return;

    // Filter by selected family member if one is active, otherwise evaluate all
    const curMemberId = activeMember?.id || "all";

    // A. APPOINTMENTS REMINDERS
    if (settings.upcomingAppointments) {
      const advMinutes = settings.appointmentAdvWarnMinutes;
      const filteredApts = appointments.filter((apt) => {
        if (apt.completed) return false;
        // if assigned to this specific member or shared
        if (
          curMemberId !== "all" &&
          apt.assignedTo !== "all" &&
          apt.assignedTo !== curMemberId
        ) {
          return false;
        }
        return true;
      });

      filteredApts.forEach((apt) => {
        // Evaluate close appointments (scheduled for today or nearby dates)
        if (apt.date === todayStr) {
          alerts.push({
            id: `apt-${apt.id}`,
            title: `Compromisso Hoje!`,
            message: `"${apt.title}" às ${apt.time}. (Aviso prévio de ${advMinutes} min ativado)`,
            type: "appointment",
            meta: apt.id,
          });
        } else {
          // If due soon (tomorrow)
          const getLocalTomorrowStr = () => {
            const d = new Date();
            d.setDate(d.getDate() + 1);
            const pad = (n: number) => String(n).padStart(2, "0");
            return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
          };
          const tomStr = getLocalTomorrowStr();
          if (apt.date === tomStr) {
            alerts.push({
              id: `apt-tom-${apt.id}`,
              title: `Compromisso Amanhã`,
              message: `"${apt.title}" está agendado às ${apt.time} de amanhã.`,
              type: "appointment",
            });
          }
        }
      });
    }

    // A2. GOOGLE CALENDAR REMINDERS
    if (
      settings.upcomingAppointments &&
      googleEvents &&
      googleEvents.length > 0
    ) {
      googleEvents.forEach((gev) => {
        // Only trigger warnings for selected notification agendas!
        if (
          !googleCalendarAlertIds ||
          !googleCalendarAlertIds.includes(gev.calendarId)
        ) {
          return;
        }

        if (!gev.start || (!gev.start.dateTime && !gev.start.date)) {
          return;
        }

        const startDateTimeStr = gev.start.dateTime;
        const startDateStr = gev.start.date;

        let eventDate = "";
        let eventTime = "";

        if (startDateTimeStr) {
          const d = new Date(startDateTimeStr);
          const pad = (n: number) => String(n).padStart(2, "0");
          eventDate = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
          eventTime = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
        } else if (startDateStr) {
          eventDate = startDateStr;
          eventTime = "Dia todo";
        }

        if (eventDate === todayStr) {
          alerts.push({
            id: `google-apt-${gev.id}-${eventDate}`,
            title: `Compromisso Hoje! 🗓️`,
            message: `"${gev.summary || "Sem Título"}" às ${eventTime}.`,
            type: "appointment",
            meta: gev.id,
          });
        } else {
          const getLocalTomorrowStr = () => {
            const d = new Date();
            d.setDate(d.getDate() + 1);
            const pad = (n: number) => String(n).padStart(2, "0");
            return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
          };
          const tomStr = getLocalTomorrowStr();
          if (eventDate === tomStr) {
            alerts.push({
              id: `google-apt-tom-${gev.id}-${eventDate}`,
              title: `Compromisso Amanhã 🗓️`,
              message: `"${gev.summary || "Sem Título"}" às ${eventTime} de amanhã.`,
              type: "appointment",
            });
          }
        }
      });
    }

    // B. BILLS DUE REMINDERS ("Vencimento de Contas")
    if (settings.billReminders) {
      const advDays = settings.billAdvWarnDays;
      const today = new Date();

      const billTransactions = transactions.filter((t) => {
        // Bills are categorized as expenses with a dueDate and pending status
        if (t.type !== "expense" || !t.dueDate || t.status !== "pendente")
          return false;
        if (
          curMemberId !== "all" &&
          t.assignedTo !== "all" &&
          t.assignedTo !== curMemberId
        ) {
          return false;
        }
        if (settings.billCategoriesConfig && t.category) {
          const isEnabled = settings.billCategoriesConfig[t.category];
          if (isEnabled === false) {
            return false;
          }
        }
        return true;
      });

      billTransactions.forEach((bill) => {
        const dueDate = new Date(bill.dueDate + "T00:00:00");
        const diffTime = dueDate.getTime() - today.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        if (diffDays <= advDays && diffDays >= 0) {
          alerts.push({
            id: `bill-${bill.id}`,
            title:
              diffDays === 0
                ? `Conta Vence Hoje!`
                : `Conta Vence em ${diffDays}d`,
            message: `"${bill.description}" de R$ ${bill.amount.toLocaleString("pt-BR")} expira em ${bill.dueDate}.`,
            type: "bill",
            meta: bill.id,
          });
        } else if (diffDays < 0) {
          alerts.push({
            id: `bill-late-${bill.id}`,
            title: `Conta Atrasada!`,
            message: `"${bill.description}" de R$ ${bill.amount.toLocaleString("pt-BR")} venceu em ${bill.dueDate}.`,
            type: "bill",
            meta: bill.id,
          });
        }
      });
    }

    // C. GOALS STATUS PROMPTS
    if (settings?.quietHours?.enabled) {
      const now = new Date();
      const currentHourStr = now.toTimeString().substring(0, 5); // e.g. "18:05"
      if (
        settings.quietHours.start &&
        settings.quietHours.end &&
        (currentHourStr >= settings.quietHours.start ||
          currentHourStr <= settings.quietHours.end)
      ) {
        // Skip goal status prompts during quiet hours
        setActiveAlerts(alerts);
        return;
      }
    }

    if (settings.goalReminders) {
      goals.forEach((goal) => {
        if (
          curMemberId !== "all" &&
          goal.assignedTo !== "all" &&
          goal.assignedTo !== curMemberId
        ) {
          return;
        }
        const progressPct = Math.round(
          (goal.currentValue / goal.targetValue) * 100,
        );
        // Prompt users if goal is running behind or has 0 progress
        if (progressPct < 30) {
          alerts.push({
            id: `goal-prompt-${goal.id}`,
            title: `Atualizar Metas?`,
            message: `Sua meta "${goal.title}" está com ${progressPct}% concluído. Pronto para lançar novos avanços?`,
            type: "goal",
            meta: goal.id,
          });
        }
      });
    }

    // D. HOURLY WATER REMINDERS (Meta Dinâmica de Água)
    const todayWaterLogs = waterLogs.filter(
      (w) =>
        w.date === todayStr &&
        (curMemberId === "all" ||
          w.memberId === curMemberId ||
          w.memberId === "all"),
    );
    const totalWaterMl = todayWaterLogs.reduce(
      (sum, item) => sum + item.amountMl,
      0,
    );

    const getWaterGoal = () => {
      if (!userConfig) return 4000;
      if (userConfig.waterGoalType === "manual") {
        return userConfig.manualWaterGoal ?? 2000;
      }
      const weight = userConfig.weight ?? 70;
      return Math.round(weight * 35);
    };
    const waterGoal = getWaterGoal();
    const remainingMl = Math.max(0, waterGoal - totalWaterMl);

    if (settings.waterReminders) {
      const interval = settings.waterReminderIntervalMinutes || 120;
      const now = new Date();
      const currentHour = now.getHours();
      const currentMinute = now.getMinutes();
      const currentTotalMinutes = currentHour * 60 + currentMinute;

      const startMinutes = 8 * 60; // 08:00
      const endMinutes = 22 * 60; // 22:00

      for (let m = startMinutes; m <= endMinutes; m += interval) {
        const itemHour = Math.floor(m / 60);
        const itemMinute = m % 60;
        const itemTotalMinutes = itemHour * 60 + itemMinute;

        // Show the checkpoint if the current time has passed it but is within 3 hours (180 minutes)
        if (
          currentTotalMinutes >= itemTotalMinutes &&
          currentTotalMinutes < itemTotalMinutes + 180
        ) {
          if (remainingMl > 0) {
            const timeFormatted = `${String(itemHour).padStart(2, "0")}:${String(itemMinute).padStart(2, "0")}`;
            alerts.push({
              id: `water-interval-${itemTotalMinutes}-${todayStr}`,
              title: `Se hidrata! 💧`,
              message: `Bora dar aquele gole? Você consumiu ${totalWaterMl}ml de ${waterGoal}ml. Faltam só ${remainingMl}ml pra meta de ${(waterGoal / 1000).toFixed(1)}L!`,
              type: "appointment",
            });
          }
        }
      }
    }

    if (totalWaterMl >= waterGoal) {
      alerts.push({
        id: `water-success-${todayStr}`,
        title: `Meta de água batida! 🎉💧`,
        message: `Limpou o rim! Mandou bem demais se hidratando hoje com ${totalWaterMl}ml consumidos.`,
        type: "goal",
      });
    }

    // E. HABIT REMINDERS (Lembretes de Hábitos)
    if (settings.habitReminders?.enabled && habits && habits.length > 0) {
      const reminderTimes = settings.habitReminders.reminderTimes || [];
      habits.forEach((habit) => {
        // Filtro de membro da família atribuído
        if (
          curMemberId !== "all" &&
          habit.assignedTo !== "all" &&
          habit.assignedTo !== curMemberId
        ) {
          return;
        }

        // Verificar se já foi concluído hoje
        const completedToday =
          habit.history && habit.history[todayStr] === true;
        if (completedToday) {
          return;
        }

        // Avaliar para cada horário definido se o alerta deve ser exibido
        reminderTimes.forEach((timeStr) => {
          try {
            const [h, m] = timeStr.split(":").map(Number);
            if (isNaN(h) || isNaN(m)) return;

            const now = new Date();
            const currentHour = now.getHours();
            const currentMinute = now.getMinutes();
            const currentTotalMinutes = currentHour * 60 + currentMinute;
            const reminderTotalMinutes = h * 60 + m;

            // Mostra o alerta se o horário atual passou do horário do lembrete, mas em até 120 minutos (2 horas)
            if (
              currentTotalMinutes >= reminderTotalMinutes &&
              currentTotalMinutes < reminderTotalMinutes + 120
            ) {
              alerts.push({
                id: `habit-${habit.id}-${timeStr}-${todayStr}`,
                title: `Se liga no ritual! ⚡`,
                message: `Bora concluir o hábito "${habit.name}"? Não vai quebrar a sequência linda de ${habit.streak || 0} dias, hein! 🔥`,
                type: "goal",
                meta: habit.id,
              });
            }
          } catch (err) {
            console.error("Erro ao avaliar hora do lembrete de hábito:", err);
          }
        });
      });
    }

    setActiveAlerts(alerts);
  }, [
    userConfig,
    activeMember,
    appointments,
    transactions,
    goals,
    waterLogs,
    googleEvents,
    googleCalendarAlertIds,
    habits,
  ]);

  const notifiedAlertsRef = useRef<Set<string>>(new Set());

  // Carrega histórico de alertas já notificados por push
  useEffect(() => {
    try {
      const saved = localStorage.getItem("life_manager_pushed_alerts");
      if (saved) {
        const parsed = JSON.parse(saved);
        if (Array.isArray(parsed)) {
          notifiedAlertsRef.current = new Set(parsed);
        }
      }
    } catch (e) {
      console.warn("Falha ao recuperar histórico de alertas por push", e);
    }
  }, []);

  // Efeito secundário para reescrever dinamicamente com IA os alertas da central em segundo plano
  useEffect(() => {
    if (activeAlerts.length === 0) return;

    const rewriteNewAlerts = async () => {
      let changed = false;
      const updatedDict = { ...rewrittenAlerts };

      for (const alert of activeAlerts) {
        if (!updatedDict[alert.id]) {
          try {
            const rewriteRes = await fetch("/api/notifications/rewrite", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ title: alert.title, body: alert.message }),
            });
            if (rewriteRes.ok) {
              const data = await rewriteRes.json();
              if (data.title && data.body) {
                updatedDict[alert.id] = {
                  title: data.title,
                  message: data.body,
                };
                changed = true;
              }
            }
          } catch (err) {
            console.warn(
              `⚠️ Falha ao reescrever alerta ${alert.id} via Gemini:`,
              err,
            );
          }
        }
      }

      if (changed) {
        setRewrittenAlerts(updatedDict);
      }
    };

    rewriteNewAlerts();
  }, [activeAlerts]);

  useEffect(() => {
    if (activeAlerts.length === 0) return;

    let updated = false;
    const pushEnabled =
      userConfig?.notificationSettings?.pushAlertsEnabled !== false;

    activeAlerts.forEach((alert) => {
      if (!notifiedAlertsRef.current.has(alert.id)) {
        notifiedAlertsRef.current.add(alert.id);
        updated = true;

        if (pushEnabled) {
          const cachedRewrite = rewrittenAlerts[alert.id];
          const titleToUse = cachedRewrite?.title || alert.title;
          const bodyToUse = cachedRewrite?.message || alert.message;
          const isAlreadyRewritten = !!cachedRewrite;
          triggerNativeOSNotification(
            titleToUse,
            bodyToUse,
            "/",
            undefined,
            false,
            isAlreadyRewritten,
          );
        }
      }
    });

    if (updated) {
      try {
        const list = Array.from(notifiedAlertsRef.current).slice(-200);
        localStorage.setItem(
          "life_manager_pushed_alerts",
          JSON.stringify(list),
        );
      } catch (e) {
        console.warn("Falha ao persistir histórico de alertas por push", e);
      }
    }
  }, [
    activeAlerts,
    userConfig?.notificationSettings?.pushAlertsEnabled,
    triggerNativeOSNotification,
    rewrittenAlerts,
  ]);

  // Family profile switching PIN processor
  const handleProfileSwitchConfirm = (e: React.FormEvent) => {
    e.preventDefault();
    if (!switchingMember) return;

    if (switchingMember.pin === pinInput.trim()) {
      setActiveMember(switchingMember);
      setSwitchingMember(null);
      setPinInput("");
      setPinError(false);
    } else {
      setPinError(true);
      setPinInput("");
    }
  };

  const selectProfileTrigger = (member: FamilyMember) => {
    if (member.pin) {
      setSwitchingMember(member);
      setPinInput("");
      setPinError(false);
    } else {
      setActiveMember(member);
    }
  };

  const handleAddMemberSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newMemberName.trim()) return;
    await addFamilyMember(
      newMemberName.trim(),
      newMemberRole,
      newMemberPin.trim(),
      newMemberEmail.trim(),
    );

    if (newMemberEmail.trim()) {
      setMemberInviteSuccess(
        `E-mail com instruções de primeiro acesso e criação de senha enviado para: ${newMemberEmail.trim()}`,
      );
    } else {
      setMemberInviteSuccess(
        `Perfil de ${newMemberName.trim()} foi criado com sucesso.`,
      );
    }

    setNewMemberName("");
    setNewMemberPin("");
    setNewMemberEmail("");
    setNewMemberRole("lider");

    setTimeout(() => {
      setMemberInviteSuccess(null);
    }, 6000);
  };

  const currentFormattedDate = new Date().toLocaleDateString("pt-BR", {
    weekday: "short",
    day: "numeric",
    month: "short",
  });

  const renderTabContent = () => {
    switch (activeTab) {
      case "dashboard":
        return <Dashboard onNavigate={(tab) => setActiveTab(tab)} />;
      case "finances":
        return <Finances />;
      case "agenda":
        return <Agenda />;
      case "habits":
        return <Habits />;
      case "goals":
        return <Goals />;
      case "inventory":
        return <Inventory />;
      case "second-brain":
        return <SecondBrain />;

      case "ai-copilot":
        return (
          <AIChatCopilot
            activeTab={activeTab}
            setActiveTab={setActiveTab}
            isFullPage={true}
          />
        );
      case "settings":
        return (
          <SettingsPage
            onNavigate={(tab) => setActiveTab(tab)}
            pushPermissionState={pushPermissionState}
            isSubscribingPush={isSubscribingPush}
            pushStatusMessage={pushStatusMessage}
            subscribeUserToPush={subscribeUserToPush}
            triggerNativeOSNotification={triggerNativeOSNotification}
            isTestMode={isTestMode}
            setIsTestMode={setIsTestMode}
          />
        );
      default:
        return <Dashboard onNavigate={(tab) => setActiveTab(tab)} />;
    }
  };

  if (isAuthLoading) {
    return (
      <div
        className="h-screen w-screen bg-[#020617] flex items-center justify-center font-sans"
        id="loading-screen"
      >
        <Loader2 className="w-6 h-6 text-indigo-500/80 animate-spin stroke-[1.5]" />
      </div>
    );
  }

  const isGoogleConnected =
    user && user.providerData.some((p) => p.providerId === "google.com");

  if (!user) {
    const blockedEmail = localStorage.getItem("blocked_login_email");

    const handleEmailAuth = async (e: React.FormEvent) => {
      e.preventDefault();
      setAuthError(null);
      setIsPerformingAuth(true);

      if (!emailInput || !passwordInput) {
        setAuthError("Por favor, preencha todos os campos!");
        setIsPerformingAuth(false);
        return;
      }

      try {
        if (authMode === "login") {
          localStorage.removeItem("blocked_login_email");
          await loginWithEmail(emailInput, passwordInput);
        } else if (authMode === "activate") {
          const cleanEmail = emailInput.toLowerCase().trim();
          const superUsers = [
            "cnttdouglas@gmail.com",
            "admin@agenda.com",
            "demo@agenda.com",
            "guest@agenda.com",
          ];
          const isSuperUser = superUsers.includes(cleanEmail);

          let canRegister = isSuperUser;
          if (!canRegister) {
            const docSnap = await getDoc(doc(db, "allowed_logins", cleanEmail));
            if (docSnap.exists()) {
              canRegister = true;
            }
          }

          if (canRegister) {
            await registerWithEmail(cleanEmail, passwordInput);
            setAuthMode("login");
            localStorage.removeItem("blocked_login_email");
          } else {
            setAuthError(
              "Desculpe, este e-mail não recebeu convite ou pré-autorização do Gestor Principal.",
            );
          }
        }
      } catch (err: any) {
        console.error("Auth error details:", err);
        let errorDesc =
          "Ocorreu um erro ao autenticar. Verifique sua conexão ou tente novamente.";
        if (
          err.code === "auth/wrong-password" ||
          err.code === "auth/invalid-credential"
        ) {
          errorDesc = "Credenciais incorretas. Verifique a senha ou e-mail.";
        } else if (err.code === "auth/user-not-found") {
          errorDesc = "Nenhum usuário correspondente a este e-mail.";
        } else if (err.code === "auth/email-already-in-use") {
          errorDesc =
            "Este e-mail de convite já registrou uma senha. Por favor, acesse pelo login.";
        } else if (err.code === "auth/weak-password") {
          errorDesc = "A senha deve conter pelo menos 6 caracteres.";
        } else if (err.code === "auth/invalid-email") {
          errorDesc = "O formato de e-mail inserido é inválido.";
        } else {
          // Expor o erro original para facilitar o diagnóstico
          const detailedMsg = err.message || String(err);
          const detailedCode = err.code ? ` (${err.code})` : "";
          errorDesc = `Erro de autenticação: ${detailedMsg}${detailedCode}`;
        }
        setAuthError(errorDesc);
      } finally {
        setIsPerformingAuth(false);
      }
    };

    const handleGoogleAuth = async () => {
      setAuthError(null);
      setIsPerformingAuth(true);
      try {
        await loginWithGoogle();
      } catch (err: any) {
        console.error("Google auth error details:", err);
        const code = err?.code || "";
        const message = err?.message || String(err);
        if (
          code === "auth/unauthorized-domain" ||
          message.includes("unauthorized-domain") ||
          message.includes("unauthorized domain")
        ) {
          const domain = window.location.hostname;
          const projectId =
            auth.app?.options?.projectId || "caramel-virtue-vr6z7";
          setAuthError(
            `Domínio Não Autorizado!\n\nSeu domínio real "${domain}" precisa ser adicionado aos domínios autorizados do Firebase:\n\n` +
              `1. Acesse diretamente a página de configurações:\nhttps://console.firebase.google.com/project/${projectId}/authentication/settings\n\n` +
              `2. No menu lateral esquerdo da página, clique em "Domínios autorizados" (Authorized domains).\n\n` +
              `3. Clique no botão "Adicionar domínio" (Add domain) à direita.\n\n` +
              `4. Digite exatamente:\n${domain}\n\n5. Clique em salvar e tente logar novamente!`,
          );
        } else {
          setAuthError("Falha no login com Google. Tente novamente.");
        }
      } finally {
        setIsPerformingAuth(false);
      }
    };

    return (
      <div
        className="h-screen w-screen bg-slate-950 flex items-center justify-center font-sans relative overflow-y-auto py-8"
        id="login-screen"
      >
        <Moving3DBackground />

        {/* Ambient background blur circles */}
        <div className="absolute top-[-10%] left-[-10%] w-[50%] h-[50%] rounded-full bg-indigo-500/10 blur-[120px] pointer-events-none" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[50%] h-[50%] rounded-full bg-blue-500/10 blur-[120px] pointer-events-none" />

        <div
          className="max-w-md w-full mx-4 relative z-10"
          id="login-card-container"
        >
          <motion.div
            initial={{ opacity: 0, scale: 0.98, y: 15 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            transition={{ duration: 0.4 }}
            className="bg-slate-900/60 backdrop-blur-xl border border-slate-800 rounded-2xl p-6 md:p-8 shadow-2xl space-y-6"
          >
            {/* Header / Brand */}
            <div className="text-center space-y-2">
              <div className="inline-flex items-center justify-center p-2.5 bg-rose-500/10 text-rose-450 rounded-xl border border-rose-500/15 mb-1">
                <Lock className="w-6 h-6 animate-pulse text-rose-400" />
              </div>
              <h1 className="text-xl md:text-2xl font-black text-white tracking-tight">
                Acesso Restrito
              </h1>
              <p className="text-slate-400 text-xs font-medium leading-relaxed">
                Insira seus dados de login para entrar no sistema
              </p>
            </div>

            {/* Selector: Join existing workspace portal */}
            {authMode === "activate" && (
              <div className="p-3 bg-indigo-500/10 border border-indigo-500/20 rounded-xl space-y-1">
                <span className="text-[10px] uppercase font-black tracking-wider text-indigo-450 block">
                  Ativação de Primeiro Acesso
                </span>
                <p className="text-[10px] text-slate-300 leading-normal">
                  Insira o e-mail pré-autorizado pelo seu gestor e a senha de
                  sua preferência para registrar.
                </p>
              </div>
            )}

            {/* Custom Email Auth Form */}
            <form onSubmit={handleEmailAuth} className="space-y-4">
              <div className="space-y-1">
                <label className="text-[10px] font-black uppercase text-slate-400 tracking-wider">
                  E-mail
                </label>
                <div className="relative">
                  <Mail className="w-3.5 h-3.5 text-slate-500 absolute left-3.5 top-1/2 -translate-y-1/2" />
                  <input
                    type="email"
                    required
                    value={emailInput}
                    onChange={(e) => setEmailInput(e.target.value)}
                    placeholder="seu@email.com"
                    className="w-full bg-slate-950/70 border border-slate-800 focus:border-indigo-500/50 rounded-xl pl-10 pr-4 py-2.5 text-xs text-white placeholder-slate-600 outline-none transition input-with-icon-left"
                  />
                </div>
              </div>

              <div className="space-y-1">
                <label className="text-[10px] font-black uppercase text-slate-400 tracking-wider">
                  Senha
                </label>
                <div className="relative">
                  <Lock className="w-3.5 h-3.5 text-slate-500 absolute left-3.5 top-1/2 -translate-y-1/2" />
                  <input
                    type="password"
                    required
                    value={passwordInput}
                    onChange={(e) => setPasswordInput(e.target.value)}
                    placeholder={
                      authMode === "login"
                        ? "Sua senha segura"
                        : "Crie sua senha segura (mínimo 6 chars)"
                    }
                    className="w-full bg-slate-950/70 border border-slate-800 focus:border-indigo-500/50 rounded-xl pl-10 pr-4 py-2.5 text-xs text-white placeholder-slate-600 outline-none transition input-with-icon-left"
                  />
                </div>
              </div>

              {authError && (
                <div className="p-3.5 bg-rose-500/10 border border-rose-500/15 rounded-xl text-[11px] text-rose-300 font-semibold flex items-start gap-2.5 whitespace-pre-line text-left leading-relaxed select-text">
                  <ShieldAlert className="w-4 h-4 text-rose-405 shrink-0 mt-0.5" />
                  <span className="flex-1 overflow-x-auto break-words">
                    {authError}
                  </span>
                </div>
              )}

              {blockedEmail && !authError && (
                <div className="p-3 bg-rose-500/10 border border-rose-500/15 rounded-xl text-xs text-rose-300 font-semibold flex flex-col gap-1">
                  <div className="flex items-center gap-2">
                    <ShieldAlert className="w-4 h-4 text-rose-450 shrink-0" />
                    <span>Acesso Negado!</span>
                  </div>
                  <span className="text-[10.5px] font-medium text-slate-300">
                    O e-mail{" "}
                    <code className="text-rose-400 font-mono text-[10px] bg-rose-950/40 px-1 rounded">
                      {blockedEmail}
                    </code>{" "}
                    não está pré-autorizado. Solicite acesso ao Gestor
                    Principal.
                  </span>
                </div>
              )}

              <button
                type="submit"
                disabled={isPerformingAuth}
                className="w-full flex items-center justify-center gap-2 bg-indigo-600 hover:bg-indigo-500 active:scale-[0.99] text-white font-bold py-2.5 px-4 rounded-xl shadow-lg transition duration-150 cursor-pointer text-xs"
              >
                {isPerformingAuth ? (
                  <Loader2 className="w-3.5 h-3.5 animate-spin" />
                ) : authMode === "login" ? (
                  <LogIn className="w-3.5 h-3.5" />
                ) : (
                  <UserPlus className="w-3.5 h-3.5" />
                )}
                {authMode === "login"
                  ? "Entrar com E-mail"
                  : "Ativar Conta e Definir Senha"}
              </button>
            </form>

            <div className="relative flex py-1 items-center">
              <div className="flex-grow border-t border-slate-800"></div>
              <span className="flex-shrink mx-4 text-[10px] text-slate-500 uppercase font-black tracking-wider">
                ou
              </span>
              <div className="flex-grow border-t border-slate-800"></div>
            </div>

            {/* Social Google Trigger */}
            <div className="space-y-3.5">
              <button
                type="button"
                onClick={handleGoogleAuth}
                disabled={isPerformingAuth}
                className="w-full flex items-center justify-center gap-2.5 bg-slate-950/80 hover:bg-slate-950 border border-slate-850 hover:border-slate-850 text-slate-200 hover:text-white font-bold py-2.5 px-4 rounded-xl transition cursor-pointer text-xs"
              >
                <svg
                  className="w-3.5 h-3.5"
                  viewBox="0 0 24 24"
                  width="24"
                  height="24"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <g transform="matrix(1, 0, 0, 1, 0, 0)">
                    <path
                      d="M21.35,11.1H12v2.7h5.38C16.88,15.22,14.77,16.5,12,16.5c-3.03,0-5.6-2.05-6.51-4.82C5.22,10.87,5.08,10.15,5.08,9.4c0-0.75,0.14-1.47,0.41-2.28C6.4,4.35,8.97,2.3,12,2.3c1.98,0,3.77,0.73,5.17,1.93l2.03-2.03C17.06,0.34,14.7,0,12,0C7.3,0,3.31,2.83,1.52,6.93C0.84,8.47,0.47,10.18,0.47,12c0,1.82,0.37,3.53,1.05,5.07c1.79,4.1,5.78,6.93,10.48,6.93c4.7,0,8.71-3.13,10.02-7.51c0.41-1.37,0.61-2.82,0.61-4.29C22.63,11.95,22.18,11.39,21.35,11.1z"
                      fill="#4285F4"
                    />
                  </g>
                </svg>
                Logar com Google Autorizado
              </button>

              {authMode === "login" ? (
                <button
                  type="button"
                  onClick={() => {
                    setAuthMode("activate");
                    setAuthError(null);
                  }}
                  className="w-full text-center text-xs text-indigo-400 hover:text-indigo-300 font-bold transition underline cursor-pointer"
                >
                  Recebeu convite de um gestor? Crie sua senha
                </button>
              ) : (
                <button
                  type="button"
                  onClick={() => {
                    setAuthMode("login");
                    setAuthError(null);
                  }}
                  className="w-full text-center text-xs text-indigo-400 hover:text-indigo-300 font-bold transition underline cursor-pointer"
                >
                  Voltar para tela de Login
                </button>
              )}
            </div>

            <p className="text-center text-[10px] text-slate-500 leading-normal font-medium">
              Apenas contas pré-autorizadas pelo Gestor Principal possuem
              permissão de acesso.
            </p>
          </motion.div>
        </div>
      </div>
    );
  }

  if (user && !isGoogleConnected && !bypassGoogle) {
    const handleLinkGoogle = async () => {
      let linked = false;
      try {
        if (!auth.currentUser) throw new Error("Nenhum usuário autenticado.");

        try {
          const result = await linkWithPopup(auth.currentUser, googleProvider);
          linked = true;
        } catch (linkErr: any) {
          if (
            linkErr.code === "auth/credential-already-in-use" ||
            (linkErr.message &&
              linkErr.message.includes("credential-already-in-use"))
          ) {
            const credential = GoogleAuthProvider.credentialFromError(linkErr);
            if (credential) {
              console.log(
                "Credential already in use. Signing in directly with Google credential instead...",
              );
              await signInWithCredential(auth, credential);
              linked = true;
              return;
            }
          }
          throw linkErr;
        }
      } catch (err: any) {
        setAuthError(null);
        setIsPerformingAuth(true);
        console.warn(
          "Linking with Google failed, attempting fallback handling:",
          err,
        );
        if (
          err.code === "auth/credential-already-in-use" ||
          (err.message && err.message.includes("credential-already-in-use"))
        ) {
          setAuthError(
            "Esta conta do Google já está associada a outro usuário no sistema. Por favor, clique no botão 'Continuar sem Vincular Google' abaixo para acessar o sistema normalmente, ou use o botão do Google para entrar diretamente.",
          );
        } else {
          setAuthError(
            "Falha na associação: " + (err.message || "Tente novamente"),
          );
        }
        setIsPerformingAuth(false);
      }

      if (linked) {
        setIsPerformingAuth(true);
        setAuthError(null);
        // it will navigate away naturally
      }
    };

    return (
      <div
        className="h-screen w-screen bg-slate-950 flex items-center justify-center font-sans relative overflow-hidden"
        id="google-enforce-screen"
      >
        <Moving3DBackground />

        {/* Ambient background blur circles */}
        <div className="absolute top-[-10%] left-[-10%] w-[50%] h-[50%] rounded-full bg-indigo-500/10 blur-[120px] pointer-events-none" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[50%] h-[50%] rounded-full bg-blue-500/10 blur-[120px] pointer-events-none" />

        <div className="max-w-md w-full mx-4 relative z-10">
          <motion.div
            initial={{ opacity: 0, scale: 0.98, y: 15 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            className="bg-slate-900/60 backdrop-blur-xl border border-slate-800 rounded-2xl p-6 md:p-8 shadow-2xl space-y-6 text-center"
          >
            <div className="inline-flex items-center justify-center p-3.5 bg-indigo-500/10 border border-indigo-500/20 text-indigo-400 rounded-xl mb-1 shrink-0">
              <svg
                className="w-7 h-7 animate-pulse text-indigo-400"
                viewBox="0 0 24 24"
                fill="currentColor"
              >
                <path d="M12.24 10.285V13.4h6.887C18.2 15.614 15.645 18 12.24 18c-3.86 0-7-3.14-7-7s3.14-7 7-7c1.7 0 3.3.65 4.5 1.8l2.42-2.42C17.21 1.63 14.84 1 12.24 1 6.58 1 2 5.58 2 11.24s4.58 10.24 10.24 10.24c5.79 0 10.24-4.06 10.24-10.24 0-.69-.06-1.35-.19-1.95H12.24z" />
              </svg>
            </div>

            <h1 className="text-xl md:text-2xl font-black text-white tracking-tight font-display">
              Conexão Google Obrigatória
            </h1>
            <p className="text-slate-300 text-xs leading-relaxed max-w-sm mx-auto font-medium">
              Sua conta de e-mail está autenticada. No entanto, para fins de
              segurança e integração total do ecossistema, você pode conectar
              seu perfil ao Google ou continuar diretamente.
            </p>

            {authError && (
              <div className="p-3 bg-rose-500/10 border border-rose-500/15 rounded-xl text-xs text-rose-300 font-semibold text-left flex items-center gap-2">
                <ShieldAlert className="w-4 h-4 text-rose-400 shrink-0" />
                <span>{authError}</span>
              </div>
            )}

            <div className="space-y-3 pt-1">
              <button
                type="button"
                onClick={handleLinkGoogle}
                disabled={isPerformingAuth}
                className="w-full flex items-center justify-center gap-2.5 bg-indigo-600 hover:bg-indigo-550 active:scale-[0.98] text-white font-bold py-3 px-4 rounded-xl shadow-lg cursor-pointer text-xs"
              >
                {isPerformingAuth ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <span>Conectar Conta Google</span>
                )}
              </button>

              <button
                type="button"
                onClick={() => {
                  if (user) {
                    localStorage.setItem(`bypass_google_${user.uid}`, "true");
                    setBypassGoogle(true);
                  }
                }}
                className="w-full py-2.5 px-4 bg-slate-800/40 hover:bg-slate-800/60 active:scale-[0.98] text-slate-300 hover:text-white text-xs font-bold rounded-xl border border-slate-700/50 transition cursor-pointer"
              >
                Continuar sem Vincular Google
              </button>

              <button
                type="button"
                onClick={logout}
                className="w-full py-2.5 px-4 bg-slate-950/80 hover:bg-slate-950 text-slate-400 hover:text-white text-xs font-bold rounded-xl border border-slate-800 transition cursor-pointer"
              >
                Sair / Desconectar Sessão
              </button>
            </div>
          </motion.div>
        </div>
      </div>
    );
  }

  return (
    <div
      className="h-screen w-screen bg-transparent text-slate-100 flex overflow-hidden font-sans relative"
      id="main-app-root"
    >
      {/* Premium Exclusive Interactive Background elements */}
      <div className="cosmic-spotlight"></div>
      <div className="absolute top-1/4 left-1/4 w-[500px] h-[500px] floating-orb-1 opacity-10 pointer-events-none z-0"></div>
      <div className="absolute bottom-1/4 right-1/4 w-[600px] h-[600px] floating-orb-2 opacity-10 pointer-events-none z-0"></div>

      {/* Sidebar - Desktop Layout */}
      <aside
        className={`hidden md:flex ${sidebarCollapsed ? "w-20 px-2.5" : "w-64 px-4"} border-r border-slate-850 bg-slate-900/80 backdrop-blur-md flex-col justify-between py-6 shrink-0 relative z-10 transition-all duration-300`}
        id="sidebar-panel"
      >
        <div className="space-y-5">
          {/* Brand Logo & Collapse Toggle */}
          <div
            className={`flex items-center ${sidebarCollapsed ? "justify-center border-b border-slate-800/40 pb-3.5" : "justify-between px-1 border-b border-slate-800/40 pb-3.5"} transition-all duration-300`}
          >
            {!sidebarCollapsed ? (
              <>
                <div className="flex items-center gap-2">
                  <div className="p-1.5 bg-blue-500/10 border border-blue-500/20 text-blue-400 rounded-lg shrink-0">
                    <BarChart3 className="w-4 h-4" />
                  </div>
                  <div>
                    <h2 className="text-[11px] font-black text-white tracking-wider uppercase">
                      Gestor de Vida
                    </h2>
                    <span className="text-[8px] text-blue-400 font-bold font-mono uppercase tracking-wider block -mt-0.5">
                      Centro Gestor
                    </span>
                  </div>
                </div>
                <button
                  onClick={() => {
                    setSidebarCollapsed(true);
                    localStorage.setItem("sidebar_collapsed", "true");
                  }}
                  className="p-1.5 rounded-lg text-slate-400 hover:text-slate-100 hover:bg-slate-800/60 transition cursor-pointer"
                  title="Recolher Menu"
                >
                  <PanelLeftClose className="w-4.5 h-4.5" />
                </button>
              </>
            ) : (
              <button
                onClick={() => {
                  setSidebarCollapsed(false);
                  localStorage.setItem("sidebar_collapsed", "false");
                }}
                className="p-2 rounded-lg text-slate-400 hover:text-slate-100 hover:bg-slate-800/60 transition cursor-pointer flex items-center justify-center"
                title="Expandir Menu"
              >
                <PanelLeftOpen className="w-5 h-5" />
              </button>
            )}
          </div>

          {/* Premium User Profile Header */}
          <div
            className={`${sidebarCollapsed ? "p-1.5" : "p-4"} bg-gradient-to-b from-slate-900 via-slate-850 to-slate-900 border border-slate-800 rounded-2xl relative overflow-hidden shadow-2xl transition-all duration-300`}
          >
            {/* Elegant accent strip */}
            <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-blue-500 via-indigo-500 to-violet-500" />

            {user ? (
              <div className="flex flex-col items-center text-center">
                <div className="relative mt-2">
                  {user.photoURL ? (
                    <img
                      src={user.photoURL}
                      alt={user.displayName || "Usuário"}
                      referrerPolicy="no-referrer"
                      loading="lazy"
                      className={`${sidebarCollapsed ? "w-10 h-10" : "w-14 h-14"} rounded-full border-2 border-slate-800 shadow-md object-cover relative z-10 transition-all duration-300`}
                    />
                  ) : (
                    <div
                      className={`${sidebarCollapsed ? "w-10 h-10 text-sm" : "w-14 h-14 text-lg"} rounded-full bg-gradient-to-tr from-blue-600 to-indigo-600 border-2 border-slate-800 shadow-md flex items-center justify-center text-white font-bold font-sans relative z-10 transition-all duration-300`}
                    >
                      {(user.displayName || user.email || "U")
                        .charAt(0)
                        .toUpperCase()}
                    </div>
                  )}
                  {/* Active online green pulse */}
                  <span className="absolute bottom-0 right-0 w-3 h-3 bg-emerald-500 border-2 border-slate-900 rounded-full shadow-sm z-20 animate-pulse" />
                </div>

                {!sidebarCollapsed && (
                  <div className="mt-2.5 space-y-0.5 max-w-full">
                    <span className="inline-flex items-center px-2 py-0.5 rounded-full text-[8px] font-bold bg-blue-500/10 text-blue-300 border border-blue-500/15 tracking-wide uppercase">
                      Gestor Principal
                    </span>
                    <h3
                      className="text-xs font-bold text-slate-100 truncate px-1 max-w-[180px]"
                      title={user.displayName || ""}
                    >
                      {user.displayName || "Usuário"}
                    </h3>
                    <p
                      className="text-[10px] text-slate-400 truncate px-1 max-w-[180px]"
                      title={user.email || ""}
                    >
                      {user.email}
                    </p>
                  </div>
                )}
              </div>
            ) : sidebarCollapsed ? (
              <div
                className="flex flex-col items-center py-2 text-amber-500"
                title="Modo Local Sandbox"
              >
                <Shield className="w-5 h-5" />
              </div>
            ) : (
              <div className="space-y-2.5">
                <div className="flex items-center gap-1.5 text-amber-500">
                  <Shield className="w-3.5 h-3.5" />
                  <span className="text-[10px] font-bold uppercase tracking-wider">
                    Modo Local Sandbox
                  </span>
                </div>
                <p className="text-[10px] text-slate-400 leading-normal">
                  Seus dados estão temporários. Faça login com Google para
                  garantir criptografia e sincronização segura!
                </p>
                <button
                  onClick={loginWithGoogle}
                  className="w-full py-1.5 bg-blue-650 hover:bg-blue-600 text-white rounded-lg text-[10px] font-bold flex items-center justify-center gap-1.5 transition cursor-pointer"
                >
                  <LogIn className="w-3.5 h-3.5" /> Login com Google
                </button>
              </div>
            )}
          </div>

          {/* Nav Menu */}
          <nav className="space-y-1.5">
            <button
              onClick={() => setActiveTab("dashboard")}
              onMouseEnter={() => preloadComponent("dashboard")}
              onTouchStart={() => preloadComponent("dashboard")}
              title={sidebarCollapsed ? "Painel Geral" : undefined}
              className={`w-full flex items-center ${sidebarCollapsed ? "justify-center py-3 px-0" : "justify-between px-3.5 py-2.5"} rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                activeTab === "dashboard"
                  ? "bg-gradient-to-r from-blue-600 to-indigo-650 text-white shadow-lg shadow-blue-950/50 border border-blue-500/10"
                  : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
              }`}
            >
              <span
                className={`flex items-center ${sidebarCollapsed ? "justify-center" : "gap-3"}`}
              >
                <BarChart3 className="w-4 h-4 shrink-0" />
                {!sidebarCollapsed && <span>Painel Geral</span>}
              </span>
            </button>

            <button
              onClick={() => setActiveTab("finances")}
              onMouseEnter={() => preloadComponent("finances")}
              onTouchStart={() => preloadComponent("finances")}
              title={sidebarCollapsed ? "Finanças" : undefined}
              className={`w-full flex items-center ${sidebarCollapsed ? "justify-center py-3 px-0" : "justify-between px-3.5 py-2.5"} rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                activeTab === "finances"
                  ? "bg-gradient-to-r from-blue-600 to-indigo-650 text-white shadow-lg shadow-blue-950/50 border border-blue-500/10"
                  : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
              }`}
            >
              <span
                className={`flex items-center ${sidebarCollapsed ? "justify-center" : "gap-3"}`}
              >
                <DollarSign className="w-4 h-4 shrink-0" />
                {!sidebarCollapsed && <span>Finanças</span>}
              </span>
            </button>

            <button
              onClick={() => setActiveTab("agenda")}
              onMouseEnter={() => preloadComponent("agenda")}
              onTouchStart={() => preloadComponent("agenda")}
              title={sidebarCollapsed ? "Compromissos" : undefined}
              className={`w-full flex items-center ${sidebarCollapsed ? "justify-center py-3 px-0" : "justify-between px-3.5 py-2.5"} rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                activeTab === "agenda"
                  ? "bg-gradient-to-r from-blue-600 to-indigo-650 text-white shadow-lg shadow-blue-950/50 border border-blue-500/10"
                  : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
              }`}
            >
              <span
                className={`flex items-center ${sidebarCollapsed ? "justify-center" : "gap-3"}`}
              >
                <CalendarDays className="w-4 h-4 shrink-0" />
                {!sidebarCollapsed && <span>Compromissos</span>}
              </span>
            </button>

            <button
              onClick={() => setActiveTab("habits")}
              onMouseEnter={() => preloadComponent("habits")}
              onTouchStart={() => preloadComponent("habits")}
              title={sidebarCollapsed ? "Hábitos e Rotinas" : undefined}
              className={`w-full flex items-center ${sidebarCollapsed ? "justify-center py-3 px-0" : "justify-between px-3.5 py-2.5"} rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                activeTab === "habits"
                  ? "bg-gradient-to-r from-blue-600 to-indigo-650 text-white shadow-lg shadow-blue-950/50 border border-blue-500/10"
                  : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
              }`}
            >
              <span
                className={`flex items-center ${sidebarCollapsed ? "justify-center" : "gap-3"}`}
              >
                <Flame
                  className={`w-4 h-4 shrink-0 transition-colors ${activeTab === "habits" ? "text-indigo-400" : "text-slate-400"}`}
                />
                {!sidebarCollapsed && <span>Hábitos e Rotinas</span>}
              </span>
            </button>

            <button
              onClick={() => setActiveTab("goals")}
              onMouseEnter={() => preloadComponent("goals")}
              onTouchStart={() => preloadComponent("goals")}
              title={sidebarCollapsed ? "Metas de Vida" : undefined}
              className={`w-full flex items-center ${sidebarCollapsed ? "justify-center py-3 px-0" : "justify-between px-3.5 py-2.5"} rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                activeTab === "goals"
                  ? "bg-gradient-to-r from-blue-600 to-indigo-650 text-white shadow-lg shadow-blue-950/50 border border-blue-500/10"
                  : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
              }`}
            >
              <span
                className={`flex items-center ${sidebarCollapsed ? "justify-center" : "gap-3"}`}
              >
                <Target className="w-4 h-4 shrink-0" />
                {!sidebarCollapsed && <span>Metas de Vida</span>}
              </span>
            </button>

            <button
              onClick={() => setActiveTab("inventory")}
              onMouseEnter={() => preloadComponent("inventory")}
              onTouchStart={() => preloadComponent("inventory")}
              title={sidebarCollapsed ? "Controle de Estoque" : undefined}
              className={`w-full flex items-center ${sidebarCollapsed ? "justify-center py-3 px-0" : "justify-between px-3.5 py-2.5"} rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                activeTab === "inventory"
                  ? "bg-gradient-to-r from-blue-600 to-indigo-650 text-white shadow-lg shadow-blue-950/50 border border-blue-500/10"
                  : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
              }`}
            >
              <span
                className={`flex items-center ${sidebarCollapsed ? "justify-center" : "gap-3"}`}
              >
                <Package
                  className={`w-4 h-4 shrink-0 transition-colors ${activeTab === "inventory" ? "text-indigo-400" : "text-slate-400"}`}
                />
                {!sidebarCollapsed && <span>Controle de Estoque</span>}
              </span>
            </button>

            <button
              onClick={() => setActiveTab("second-brain")}
              onMouseEnter={() => preloadComponent("second-brain")}
              onTouchStart={() => preloadComponent("second-brain")}
              title={sidebarCollapsed ? "Segundo Cérebro" : undefined}
              className={`w-full flex items-center ${sidebarCollapsed ? "justify-center py-3 px-0" : "justify-between px-3.5 py-2.5"} rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                activeTab === "second-brain"
                  ? "bg-gradient-to-r from-blue-600 to-indigo-650 text-white shadow-lg shadow-blue-950/50 border border-blue-500/10"
                  : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
              }`}
            >
              <span
                className={`flex items-center ${sidebarCollapsed ? "justify-center" : "gap-3"}`}
              >
                <Brain
                  className={`w-4 h-4 shrink-0 ${activeTab === "second-brain" ? "text-indigo-400" : "text-slate-400"}`}
                />
                {!sidebarCollapsed && <span>Segundo Cérebro</span>}
              </span>
            </button>



            <button
              onClick={() => {
                setActiveTab("ai-copilot");
                if (typeof setIsOpenAIChat === "function") {
                  setIsOpenAIChat(false);
                }
              }}
              onMouseEnter={() => preloadComponent("ai-copilot")}
              onTouchStart={() => preloadComponent("ai-copilot")}
              title={sidebarCollapsed ? "Leandrinha (IA)" : undefined}
              className={`w-full flex items-center ${sidebarCollapsed ? "justify-center py-3 px-0" : "justify-between px-3.5 py-2.5"} rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                activeTab === "ai-copilot"
                  ? "bg-gradient-to-r from-indigo-600 to-violet-650 text-white shadow-lg shadow-indigo-950/50 border border-indigo-505/10"
                  : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
              }`}
            >
              <span
                className={`flex items-center ${sidebarCollapsed ? "justify-center" : "gap-3"}`}
              >
                <Sparkles
                  className={`w-4 h-4 shrink-0 ${activeTab === "ai-copilot" ? "text-indigo-400" : "text-indigo-500"}`}
                />
                {!sidebarCollapsed && <span>Leandrinha (IA)</span>}
              </span>
              {!sidebarCollapsed && (
                <span className="relative flex h-2 w-2">
                  <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
                  <span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500"></span>
                </span>
              )}
            </button>

            <button
              onClick={() => setActiveTab("settings")}
              onMouseEnter={() => preloadComponent("settings")}
              onTouchStart={() => preloadComponent("settings")}
              title={sidebarCollapsed ? "Configurações" : undefined}
              className={`w-full flex items-center ${sidebarCollapsed ? "justify-center py-3 px-0" : "justify-between px-3.5 py-2.5"} rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                activeTab === "settings"
                  ? "bg-gradient-to-r from-blue-600 to-indigo-650 text-white shadow-lg shadow-blue-950/50 border border-blue-500/10"
                  : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
              }`}
            >
              <span
                className={`flex items-center ${sidebarCollapsed ? "justify-center" : "gap-3"}`}
              >
                <Settings
                  className={`w-4 h-4 shrink-0 transition-colors ${activeTab === "settings" ? "text-indigo-400" : "text-slate-400"}`}
                />
                {!sidebarCollapsed && <span>Configurações</span>}
              </span>
            </button>

            {/* Sincronizar Nuvem and Membros da Família action buttons relocated inside Settings module */}
          </nav>
        </div>
      </aside>

      {/* Main Viewport panel */}
      <main className="flex-1 flex flex-col bg-transparent overflow-hidden relative z-10">
        {/* Top Header Bar */}
        <header
          className="relative z-40 h-[calc(4rem+env(safe-area-inset-top,0px))] pt-[env(safe-area-inset-top,0px)] md:h-16 md:pt-0 border-b border-indigo-500/10 bg-slate-900/60 backdrop-blur-xl px-4 sm:px-6 md:px-8 flex items-center justify-between shrink-0 shadow-lg shadow-indigo-950/20"
          id="main-header"
        >
          <div className="flex items-center gap-2 sm:gap-4_">
            {/* Mobile hamburger menu button */}
            <button
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              className="md:hidden p-2 text-slate-400 hover:text-white hover:bg-slate-800/60 rounded-xl cursor-pointer transition-all duration-200"
            >
              {mobileMenuOpen ? (
                <X className="w-5 h-5" />
              ) : (
                <Menu className="w-5 h-5 text-slate-400" />
              )}
            </button>

            <div className="flex flex-col justify-center">
              <h2 className="text-sm font-extrabold tracking-wide uppercase text-white capitalize flex items-center gap-1.5 font-sans md:text-base">
                <span>
                  {activeTab === "dashboard"
                    ? "Overview Geral"
                    : activeTab === "finances"
                      ? "Finanças"
                      : activeTab === "agenda"
                        ? "Agenda de Compromissos"
                        : activeTab === "habits"
                          ? "Hábitos e Rotinas"
                          : activeTab === "goals"
                            ? "Metas de Vida"
                            : activeTab === "inventory"
                              ? "Controle de Estoque"
                              : activeTab === "settings"
                                ? "Configurações Compartilhadas"
                                : activeTab === "ai-copilot"
                                  ? "Leandrinha"
                                  : activeTab}
                </span>
              </h2>
              {/* Date under title on Mobile */}
              <span className="text-[9px] text-blue-400 font-bold font-mono tracking-wider md:hidden leading-none mt-0.5">
                {currentFormattedDate}
              </span>
            </div>

            {/* Date as pill on Desktop */}
            <span className="hidden md:inline-flex items-center gap-1.5 text-[10px] bg-blue-500/10 border border-blue-500/25 text-blue-300 px-3.5 py-1.5 rounded-full font-bold font-mono tracking-wider shadow-sm shadow-blue-950/10">
              <span className="w-1.5 h-1.5 rounded-full bg-blue-400 animate-pulse"></span>
              {currentFormattedDate}
            </span>
          </div>

          <div className="flex items-center gap-1.5 sm:gap-3">
            {/* Assistente Copiloto IA (Sparkles tool trigger) */}
            <button
              onClick={() => setIsOpenAIChat(!isOpenAIChat)}
              className={`p-2 rounded-full hover:bg-slate-800 text-slate-350 hover:text-white transition relative cursor-pointer ${isOpenAIChat ? "bg-slate-800 text-indigo-400" : ""}`}
              title="Falar com a Leandrinha (Copiloto de IA)"
              id="ai-copilot-trigger"
            >
              <Sparkles className="w-4.5 h-4.5 animate-pulse" />
              <span className="absolute -top-0.5 -right-0.5 bg-indigo-505 w-2 h-2 rounded-full animate-ping"></span>
              <span className="absolute -top-0.5 -right-0.5 bg-indigo-500 w-2 h-2 rounded-full"></span>
            </button>

            {/* General Gear Configuration Settings Button */}
            <button
              onClick={() => setActiveTab("settings")}
              className={`p-2 rounded-full hover:bg-slate-800 transition cursor-pointer ${
                activeTab === "settings"
                  ? "bg-slate-850 text-indigo-400 border border-slate-750"
                  : "text-slate-350 hover:text-white"
              }`}
              title="Personalizar Painel e Notificações"
            >
              <Settings className="w-4.5 h-4.5" />
            </button>

            {/* Quick action backup status & manual sync button */}
            <div className="flex items-center gap-2">
              {/* Emergency Restore Button when sync fails repeatedly */}
              {failedSyncAttempts >= 3 && (
                <button
                  onClick={async () => {
                    const ok = await restoreFromBackup();
                    if (ok) {
                      alert(
                        "Dados restaurados do cache offline IndexedDB com sucesso!",
                      );
                    } else {
                      alert(
                        "Nenhum cache de emergência encontrado neste dispositivo.",
                      );
                    }
                  }}
                  className="px-2.5 py-1.5 rounded-xl bg-amber-500/20 hover:bg-amber-500/30 text-amber-350 hover:text-white text-[10px] font-extrabold flex items-center gap-1.5 border border-amber-500/40 transition-all duration-200 cursor-pointer shadow-[0_0_12px_rgba(245,158,11,0.2)] shrink-0 animate-pulse"
                  title="Sincronização com a nuvem indisponível. Clique aqui para restaurar seu histórico e dados do backup offline completo."
                >
                  <Database className="w-3.5 h-3.5 text-amber-400 shrink-0" />
                  <span className="hidden sm:inline">Restaurar do Cache</span>
                  <span className="sm:hidden">Restaurar</span>
                </button>
              )}

              {/* Manual Backup Trigger Button */}
              <button
                onClick={handleManualSync}
                disabled={isSaving}
                className={`relative p-2 rounded-xl cursor-pointer flex items-center justify-center border transition-all duration-200 group ${
                  isSaving
                    ? "bg-indigo-500/10 border-indigo-500/25 text-indigo-400 cursor-not-allowed"
                    : "bg-slate-900/80 border-slate-800 text-slate-300 hover:text-white hover:border-blue-500/40 hover:bg-slate-850"
                }`}
                title="Sincronizar dados manualmente com a nuvem"
              >
                <RefreshCw
                  className={`w-4 h-4 ${isSaving ? "animate-spin text-blue-400" : "group-hover:rotate-180 transition-transform duration-500 text-slate-400 group-hover:text-blue-300"}`}
                />
                {!isSaving && (
                  <span className="absolute -top-0.5 -right-0.5 flex h-2 w-2">
                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"></span>
                    <span className="relative inline-flex rounded-full h-2 w-2 bg-blue-500"></span>
                  </span>
                )}
              </button>

              {isSaving || autoSaveStatus === "saving" ? (
                <div className="p-1 sm:px-3 py-1.5 rounded-xl bg-blue-500/10 text-blue-400 text-[10px] font-extrabold flex items-center gap-1.5 border border-blue-500/25 animate-pulse shadow-[0_0_12px_rgba(59,130,246,0.15)]">
                  <Loader2 className="w-3.5 h-3.5 animate-spin text-blue-400" />
                  <span className="hidden sm:inline">
                    {autoSaveStatus === "saving"
                      ? "Autosalvando..."
                      : "Sincronizando..."}
                  </span>
                </div>
              ) : autoSaveStatus === "saved" ? (
                <div className="p-1 sm:px-3 py-1.5 rounded-xl bg-emerald-500/10 text-emerald-400 text-[10px] font-extrabold flex items-center gap-1.5 border border-emerald-500/30 transition-all duration-300 animate-pulse shadow-[0_0_12px_rgba(16,185,129,0.25)]">
                  <Check className="w-3.5 h-3.5 text-emerald-400 shrink-0 animate-bounce" />
                  <span className="hidden sm:inline">Autosave realizado!</span>
                </div>
              ) : autoSaveStatus === "idle_user" ? (
                <div className="p-1 sm:px-3 py-1.5 rounded-xl bg-indigo-500/10 text-indigo-400 text-[10px] font-extrabold flex items-center gap-1.5 border border-indigo-500/20 transition-all duration-300 shadow-[0_0_10px_rgba(99,102,241,0.15)] animate-pulse">
                  <span className="relative flex h-2 w-2">
                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
                    <span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500"></span>
                  </span>
                  <span className="hidden sm:inline">
                    Inatividade detectada
                  </span>
                </div>
              ) : (
                <div
                  className="p-1 sm:px-3 py-1.5 rounded-xl bg-emerald-500/5 text-emerald-400 text-[10px] font-bold flex items-center gap-1.5 border border-emerald-500/15 transition-all duration-300 shadow-[0_0_10px_rgba(16,185,129,0.03)] hover:border-emerald-500/25 cursor-help"
                  title={
                    lastSaved
                      ? `Último backup: ${lastSaved.toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit", second: "2-digit" })}`
                      : "Sincronizado na nuvem"
                  }
                  id="autosave-indicator"
                  onClick={handleManualSync}
                >
                  <Cloud className="w-3.5 h-3.5 text-emerald-500 shrink-0 animate-pulse" />
                  <span className="hidden sm:inline text-slate-350">
                    Nuvem ativa
                  </span>
                  {lastAutoSavedAt && (
                    <span className="text-[9px] text-slate-500 ml-1">
                      (
                      {lastAutoSavedAt.toLocaleTimeString("pt-BR", {
                        hour: "2-digit",
                        minute: "2-digit",
                        second: "2-digit",
                      })}
                      )
                    </span>
                  )}
                </div>
              )}
            </div>
          </div>
        </header>

        {/* Sticky Mobile navigation view */}
        <AnimatePresence>
          {mobileMenuOpen && (
            <>
              {/* Mobile Menu Backdrop */}
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                onClick={() => setMobileMenuOpen(false)}
                className="md:hidden fixed inset-0 bg-slate-950/80 backdrop-blur-xs z-50 cursor-pointer"
              />

              {/* Mobile Side Drawer Menu */}
              <motion.div
                initial={{ x: "-100%" }}
                animate={{ x: 0 }}
                exit={{ x: "-100%" }}
                transition={{ type: "spring", damping: 25, stiffness: 200 }}
                className="md:hidden fixed top-0 bottom-0 left-0 w-72 h-full bg-slate-900 border-r border-slate-800 z-50 shadow-2xl flex flex-col overflow-y-auto"
              >
                {/* Header with Title and Close Button */}
                <div className="pt-[calc(1.25rem+env(safe-area-inset-top,0px))] pb-5 px-5 border-b border-slate-800/60 flex items-center justify-between">
                  <div className="flex items-center gap-2.5">
                    <div className="p-1.5 bg-blue-500/10 border border-blue-500/20 text-blue-400 rounded-lg shrink-0">
                      <BarChart3 className="w-4.5 h-4.5" />
                    </div>
                    <div>
                      <h2 className="text-xs font-black text-white tracking-widest uppercase">
                        Gestor de Vida
                      </h2>
                      <span className="text-[8px] text-blue-400 font-bold font-mono uppercase tracking-wider">
                        Centro Gestor
                      </span>
                    </div>
                  </div>
                  <button
                    onClick={() => setMobileMenuOpen(false)}
                    className="p-1.5 rounded-lg bg-slate-850 hover:bg-slate-800 text-slate-400 hover:text-white transition cursor-pointer"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>

                {/* Profile Display */}
                <div className="p-5 border-b border-slate-850 bg-slate-950/30">
                  {user ? (
                    <div className="flex items-center gap-3">
                      <div className="relative shrink-0">
                        {user.photoURL ? (
                          <img
                            src={user.photoURL}
                            referrerPolicy="no-referrer"
                            loading="lazy"
                            className="w-10 h-10 rounded-full border border-slate-850 object-cover shadow-xs"
                          />
                        ) : (
                          <div className="w-10 h-10 rounded-full bg-gradient-to-tr from-blue-600 to-indigo-650 flex items-center justify-center text-white text-xs font-bold">
                            {(user.displayName || user.email || "U")
                              .charAt(0)
                              .toUpperCase()}
                          </div>
                        )}
                        <span className="absolute bottom-0 right-0 w-2.5 h-2.5 bg-emerald-500 border border-slate-900 rounded-full shadow-xs animate-pulse" />
                      </div>
                      <div className="min-w-0 flex-1">
                        <span className="text-[8px] font-black uppercase text-indigo-400 tracking-wider bg-indigo-500/10 border border-indigo-500/20 px-1.5 py-0.5 rounded">
                          Gestor
                        </span>
                        <h4 className="text-xs font-bold text-slate-200 truncate mt-1">
                          {user.displayName || "Usuário"}
                        </h4>
                        <p className="text-[10px] text-slate-455 truncate">
                          {user.email}
                        </p>
                      </div>
                    </div>
                  ) : (
                    <div className="space-y-2">
                      <div className="flex items-center gap-1 text-amber-500">
                        <Shield className="w-3 h-3" />
                        <span className="text-[9px] font-bold uppercase tracking-wider">
                          Modo Sandbox
                        </span>
                      </div>
                      <button
                        onClick={() => {
                          setMobileMenuOpen(false);
                          loginWithGoogle();
                        }}
                        className="w-full py-1.5 bg-blue-650 hover:bg-blue-600 text-white rounded-lg text-[10px] font-black flex items-center justify-center gap-1 cursor-pointer transition"
                      >
                        <LogIn className="w-3 h-3" /> Conectar Conta
                      </button>
                    </div>
                  )}
                </div>

                {/* Navigation Items */}
                <div className="flex-1 p-4 space-y-1">
                  <button
                    onClick={() => {
                      setActiveTab("dashboard");
                      setMobileMenuOpen(false);
                    }}
                    onMouseEnter={() => preloadComponent("dashboard")}
                    onTouchStart={() => preloadComponent("dashboard")}
                    className={`w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                      activeTab === "dashboard"
                        ? "bg-gradient-to-r from-blue-600 to-indigo-655 text-white shadow-lg border border-blue-500/10"
                        : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
                    }`}
                  >
                    <BarChart3 className="w-4 h-4" />
                    Painel Geral
                  </button>
                  <button
                    onClick={() => {
                      setActiveTab("finances");
                      setMobileMenuOpen(false);
                    }}
                    onMouseEnter={() => preloadComponent("finances")}
                    onTouchStart={() => preloadComponent("finances")}
                    className={`w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                      activeTab === "finances"
                        ? "bg-gradient-to-r from-blue-600 to-indigo-655 text-white shadow-lg border border-blue-500/10"
                        : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
                    }`}
                  >
                    <DollarSign className="w-4 h-4" />
                    Finanças
                  </button>
                  <button
                    onClick={() => {
                      setActiveTab("agenda");
                      setMobileMenuOpen(false);
                    }}
                    onMouseEnter={() => preloadComponent("agenda")}
                    onTouchStart={() => preloadComponent("agenda")}
                    className={`w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                      activeTab === "agenda"
                        ? "bg-gradient-to-r from-blue-600 to-indigo-655 text-white shadow-lg border border-blue-500/10"
                        : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
                    }`}
                  >
                    <CalendarDays className="w-4 h-4" />
                    Compromissos
                  </button>
                  <button
                    onClick={() => {
                      setActiveTab("habits");
                      setMobileMenuOpen(false);
                    }}
                    onMouseEnter={() => preloadComponent("habits")}
                    onTouchStart={() => preloadComponent("habits")}
                    className={`w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                      activeTab === "habits"
                        ? "bg-gradient-to-r from-blue-600 to-indigo-655 text-white shadow-lg border border-blue-500/10"
                        : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
                    }`}
                  >
                    <Flame className="w-4 h-4" />
                    Hábitos e Rotinas
                  </button>
                  <button
                    onClick={() => {
                      setActiveTab("goals");
                      setMobileMenuOpen(false);
                    }}
                    onMouseEnter={() => preloadComponent("goals")}
                    onTouchStart={() => preloadComponent("goals")}
                    className={`w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                      activeTab === "goals"
                        ? "bg-gradient-to-r from-blue-600 to-indigo-655 text-white shadow-lg border border-blue-500/10"
                        : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
                    }`}
                  >
                    <Target className="w-4 h-4" />
                    Metas de Vida
                  </button>
                  <button
                    onClick={() => {
                      setActiveTab("inventory");
                      setMobileMenuOpen(false);
                    }}
                    onMouseEnter={() => preloadComponent("inventory")}
                    onTouchStart={() => preloadComponent("inventory")}
                    className={`w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                      activeTab === "inventory"
                        ? "bg-gradient-to-r from-blue-600 to-indigo-655 text-white shadow-lg border border-blue-500/10"
                        : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
                    }`}
                  >
                    <Package className="w-4 h-4" />
                    Controle de Estoque
                  </button>
                  <button
                    onClick={() => {
                      setActiveTab("second-brain");
                      setMobileMenuOpen(false);
                    }}
                    onMouseEnter={() => preloadComponent("second-brain")}
                    onTouchStart={() => preloadComponent("second-brain")}
                    className={`w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                      activeTab === "second-brain"
                        ? "bg-gradient-to-r from-blue-600 to-indigo-655 text-white shadow-lg border border-blue-500/10"
                        : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
                    }`}
                  >
                    <Brain className="w-4 h-4 shrink-0" />
                    Segundo Cérebro
                  </button>

                  <button
                    onClick={() => {
                      setActiveTab("ai-copilot");
                      setMobileMenuOpen(false);
                    }}
                    onMouseEnter={() => preloadComponent("ai-copilot")}
                    onTouchStart={() => preloadComponent("ai-copilot")}
                    className={`w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                      activeTab === "ai-copilot"
                        ? "bg-gradient-to-r from-indigo-600 to-purple-655 text-white shadow-lg border border-indigo-500/10"
                        : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
                    }`}
                  >
                    <Sparkles className="w-4 h-4 text-indigo-400" />
                    Leandrinha (IA)
                  </button>
                  <button
                    onClick={() => {
                      setActiveTab("settings");
                      setMobileMenuOpen(false);
                    }}
                    onMouseEnter={() => preloadComponent("settings")}
                    onTouchStart={() => preloadComponent("settings")}
                    className={`w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold transition duration-150 cursor-pointer ${
                      activeTab === "settings"
                        ? "bg-gradient-to-r from-blue-600 to-indigo-655 text-white shadow-lg border border-blue-500/10"
                        : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"
                    }`}
                  >
                    <Settings className="w-4 h-4 text-slate-400" />
                    Configurações
                  </button>

                  <div className="border-t border-slate-800 my-2 pt-2 space-y-1">
                    <button
                      onClick={() => {
                        setIsOpenAIChat(true);
                        setMobileMenuOpen(false);
                      }}
                      className="w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold text-slate-400 hover:text-slate-200 hover:bg-slate-800/40 transition duration-150 cursor-pointer"
                    >
                      <Sparkles className="w-4 h-4 text-indigo-400" />
                      Leandrinha (Copiloto)
                    </button>
                    <button
                      onClick={handleManualSync}
                      disabled={isSaving}
                      className="w-full flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-xs font-bold text-slate-400 hover:text-slate-200 hover:bg-slate-800/40 transition duration-150 cursor-pointer"
                    >
                      <Cloud
                        className={`w-4 h-4 ${isSaving ? "animate-spin text-blue-400" : "text-emerald-500"}`}
                      />
                      Sincronizar Nuvem
                    </button>
                  </div>
                </div>

                {/* Footer Brand Info */}
                <div className="p-4 border-t border-slate-850 text-center text-[9px] text-slate-550 font-medium font-mono">
                  v3.4.0 • Gestor de Vida Cloud
                </div>
              </motion.div>
            </>
          )}
        </AnimatePresence>

        {/* Scrollable primary workspace context container */}
        <div
          className={`flex-1 ${activeTab === "ai-copilot" ? "overflow-hidden p-0" : "overflow-y-auto p-4 md:p-6"} scroll-hide`}
        >
          <AnimatePresence mode="wait">
            <motion.div
              key={activeTab}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -10 }}
              transition={{ duration: 0.15 }}
              id="tab-content-container"
              className={activeTab === "ai-copilot" ? "h-full" : ""}
            >
              <React.Suspense
                fallback={
                  <div
                    className="flex flex-col items-center justify-center py-20 min-h-[400px] w-full"
                    id="page-suspense-loading"
                  >
                    <Loader2 className="w-8 h-8 text-indigo-500 animate-spin stroke-[1.5] mb-3" />
                    <p className="text-slate-400 text-xs font-mono">
                      Carregando módulo inteligente...
                    </p>
                  </div>
                }
              >
                {renderTabContent()}
              </React.Suspense>
            </motion.div>
          </AnimatePresence>
        </div>
      </main>

      {/* Copiloto de Inteligência Artificial */}
      {activeTab !== "ai-copilot" && (
        <React.Suspense fallback={null}>
          <AIChatCopilot
            activeTab={activeTab}
            setActiveTab={setActiveTab}
            isOpen={isOpenAIChat}
            setIsOpen={setIsOpenAIChat}
          />
        </React.Suspense>
      )}

      {/* 1. Family Members Management Modal */}
      <AnimatePresence>
        {showFamilyModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/60 backdrop-blur-xs px-4"
          >
            <motion.div
              initial={{ scale: 0.95 }}
              animate={{ scale: 1 }}
              exit={{ scale: 0.95 }}
              className="bg-slate-900 max-w-md w-full rounded-2xl p-5 shadow-2xl border border-slate-800 relative space-y-4 text-white"
            >
              <button
                onClick={() => setShowFamilyModal(false)}
                className="absolute top-4 right-4 p-1.5 text-slate-400 hover:text-white rounded-full hover:bg-slate-800 cursor-pointer transition"
              >
                <X className="w-4.5 h-4.5" />
              </button>

              <div className="space-y-1">
                <h3 className="font-bold text-white text-sm flex items-center gap-1.5 font-display">
                  <span className="p-1.5 bg-indigo-550/10 border border-indigo-505/20 text-indigo-455 rounded-lg inline-block">
                    <Users className="w-4 h-4 text-indigo-400" />
                  </span>
                  Membros da Família
                </h3>
                <p className="text-[11px] text-slate-400">
                  Gerencie quem compartilha este painel. Cada membro pode usar
                  PINs para restringir acessos a faturas financeiras.
                </p>
              </div>

              {/* Form to create member */}
              <form
                onSubmit={handleAddMemberSubmit}
                className="bg-slate-950 border border-slate-850 p-4 rounded-xl space-y-2.5 shadow-inner"
              >
                <span className="text-[9px] uppercase font-bold text-indigo-400 block tracking-wider">
                  Adicionar Novo Perfil
                </span>

                {memberInviteSuccess && (
                  <div className="p-2.5 bg-emerald-500/10 border border-emerald-500/20 rounded-lg text-[10.5px] text-emerald-400 font-semibold leading-relaxed">
                    {memberInviteSuccess}
                  </div>
                )}

                <div className="grid grid-cols-2 gap-2">
                  <input
                    type="text"
                    required
                    placeholder="Nome do membro..."
                    className="col-span-2 bg-slate-900 border border-slate-800 rounded px-2.5 py-1.5 text-xs text-white outline-none focus:ring-1 focus:ring-indigo-500 font-medium"
                    value={newMemberName}
                    onChange={(e) => setNewMemberName(e.target.value)}
                  />

                  <input
                    type="email"
                    placeholder="E-mail de login (gera convite)"
                    className="col-span-2 bg-slate-900 border border-slate-800 rounded px-2.5 py-1.5 text-xs text-white outline-none focus:ring-1 focus:ring-indigo-500 font-medium text-slate-200"
                    value={newMemberEmail}
                    onChange={(e) => setNewMemberEmail(e.target.value)}
                  />

                  <select
                    className="bg-slate-900 border border-slate-800 text-slate-200 rounded px-2 py-1.5 text-xs font-semibold outline-none cursor-pointer"
                    value={newMemberRole}
                    onChange={(e: any) => setNewMemberRole(e.target.value)}
                  >
                    <option value="lider">Líder da Família (Admin)</option>
                    <option value="filho">Filho</option>
                    <option value="filha">Filha</option>
                    <option value="outro">Outro</option>
                  </select>

                  <input
                    type="text"
                    maxLength={4}
                    pattern="\d*"
                    placeholder="PIN opcional (4 dgt)"
                    className="bg-slate-900 border border-slate-800 rounded px-2 py-1.5 text-xs text-white outline-none focus:ring-1 focus:ring-indigo-500 font-medium font-mono"
                    value={newMemberPin}
                    onChange={(e) =>
                      setNewMemberPin(e.target.value.replace(/\D/g, ""))
                    }
                  />
                </div>
                <button
                  type="submit"
                  className="w-full bg-indigo-600 hover:bg-indigo-705 py-2 text-white font-bold text-xs rounded-lg transition flex items-center justify-center gap-1 cursor-pointer"
                >
                  <Plus className="w-3.5 h-3.5" /> Adicionar Perfil
                </button>
              </form>

              {/* Roster of active members */}
              <div className="space-y-1.5 max-h-[180px] overflow-y-auto pr-1 customize-scrollbar">
                <span className="text-[9px] uppercase font-bold text-slate-400 block tracking-wider mb-1">
                  Perfis Registrados
                </span>
                {userConfig && userConfig.members.length > 0 ? (
                  userConfig.members.map((m) => {
                    const isActive = activeMember?.id === m.id;
                    return (
                      <div
                        key={m.id}
                        onClick={() => {
                          if (!isActive) {
                            selectProfileTrigger(m);
                            setShowFamilyModal(false);
                          }
                        }}
                        className={`p-2.5 border rounded-xl flex justify-between items-center transition select-none ${
                          isActive
                            ? "border-indigo-500 bg-indigo-650/10"
                            : "border-slate-800 hover:bg-slate-850 cursor-pointer"
                        }`}
                      >
                        <div className="flex items-center gap-2">
                          <div
                            className={`w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold ${m.avatarColor}`}
                          >
                            {m.name.charAt(0).toUpperCase()}
                          </div>
                          <div className="text-left">
                            <div className="flex items-center gap-1.5">
                              <p className="text-xs font-bold text-slate-100">
                                {m.name}
                              </p>
                              {isActive && (
                                <span className="inline-flex items-center text-[7px] bg-emerald-500/10 text-emerald-400 font-black px-1 rounded border border-emerald-500/20 uppercase shrink-0">
                                  Ativo
                                </span>
                              )}
                            </div>
                            <p className="text-[10px] text-slate-400 capitalize flex items-center gap-1">
                              <span>{m.role}</span>
                              {m.pin && (
                                <span className="text-indigo-400 text-[8px] bg-indigo-550/10 px-1 rounded flex items-center">
                                  <Lock className="w-2.5 h-2.5 mr-0.5" /> PIN
                                </span>
                              )}
                            </p>
                          </div>
                        </div>

                        {/* Safety: Don't let users delete the last member profile */}
                        {userConfig.members.length > 1 && (
                          <button
                            onClick={(e) => {
                              e.stopPropagation(); // Avoid triggering profile switch
                              deleteFamilyMember(m.id);
                            }}
                            className="text-slate-500 hover:text-rose-400 hover:bg-rose-950/20 p-1.5 rounded-lg transition cursor-pointer"
                            title="Remover Perfil"
                          >
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        )}
                      </div>
                    );
                  })
                ) : (
                  <div className="text-center py-4 text-slate-500 text-xs italic">
                    Nenhum membro configurado
                  </div>
                )}
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 2. Profile Swapping PIN lock modal */}
      <AnimatePresence>
        {switchingMember && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/70 backdrop-blur-xs px-4"
          >
            <motion.div
              initial={{ scale: 0.95 }}
              animate={{ scale: 1 }}
              exit={{ scale: 0.95 }}
              className="bg-slate-900 max-w-sm w-full rounded-2xl p-6 shadow-2xl border border-slate-800 relative text-center space-y-4 text-white"
            >
              <div className="w-12 h-12 rounded-full bg-indigo-550/10 border border-indigo-505/20 text-indigo-400 flex items-center justify-center mx-auto shadow-inner">
                <Lock className="w-5 h-5" />
              </div>

              <div className="space-y-1">
                <h3 className="font-bold text-white text-sm font-display">
                  Perfil Bloqueado
                </h3>
                <p className="text-[11px] text-slate-400 leading-relaxed">
                  Digite o PIN de 4 dígitos para acessar o painel de{" "}
                  <span className="font-bold text-slate-200">
                    "{switchingMember.name}"
                  </span>
                  .
                </p>
              </div>

              <form onSubmit={handleProfileSwitchConfirm} className="space-y-3">
                <input
                  type="password"
                  maxLength={4}
                  required
                  autoFocus
                  placeholder="••••"
                  className="w-32 bg-slate-950 border border-slate-800 text-white rounded-xl px-3 py-2 text-center text-lg font-bold tracking-widest outline-none focus:ring-2 focus:ring-indigo-550"
                  value={pinInput}
                  onChange={(e) =>
                    setPinInput(e.target.value.replace(/\D/g, ""))
                  }
                />

                {pinError && (
                  <p className="text-[10px] text-rose-455 font-bold flex items-center justify-center gap-1">
                    <AlertTriangle className="w-3.5 h-3.5" /> PIN informado
                    incorreto. Tente novamente!
                  </p>
                )}

                <div className="flex gap-2 justify-center pt-2">
                  <button
                    type="button"
                    onClick={() => setSwitchingMember(null)}
                    className="px-3.5 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg text-xs font-bold transition cursor-pointer"
                  >
                    Cancelar
                  </button>
                  <button
                    type="submit"
                    className="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold transition cursor-pointer"
                  >
                    Confirmar
                  </button>
                </div>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 3. Global Configuration settings Modal */}
      <AnimatePresence>
        {showSettingsModal && userConfig && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/60 backdrop-blur-xs px-4"
          >
            <motion.div
              initial={{ scale: 0.95 }}
              animate={{ scale: 1 }}
              exit={{ scale: 0.95 }}
              className="bg-slate-900 max-w-lg w-full rounded-2xl p-5 shadow-2xl border border-slate-800 relative space-y-5 text-white"
            >
              <button
                onClick={() => setShowSettingsModal(false)}
                className="absolute top-4 right-4 p-1.5 text-slate-400 hover:text-white rounded-full hover:bg-slate-850 cursor-pointer transition"
              >
                <X className="w-4.5 h-4.5" />
              </button>

              <div className="space-y-1">
                <h3 className="font-bold text-white text-sm flex items-center gap-1.5 font-display">
                  <span className="p-1.5 bg-indigo-550/10 border border-indigo-505/20 text-indigo-455 rounded-lg inline-block">
                    <Settings className="w-4.5 h-4.5 text-indigo-400" />
                  </span>
                  Configurações Personalizadas do Gestor
                </h3>
                <p className="text-[11px] text-slate-400">
                  Defina regras de organização e visualizações do painel principal.
                </p>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-h-[365px] overflow-y-auto pr-1 customize-scrollbar">
                {/* 3B: INTERACTIVE PANEL CUSTOMIZER */}
                <div className="space-y-3 bg-slate-950/80 border border-slate-850 p-4 rounded-xl md:col-span-2">
                  <h4 className="text-xs font-bold text-indigo-400 flex items-center gap-1.5 uppercase tracking-wide">
                    <Sliders className="w-3.5 h-3.5 text-indigo-400" /> Layout e
                    Organização
                  </h4>

                  <div className="space-y-2.5 text-xs">
                    <div>
                      <span className="text-[10px] text-slate-400 font-bold block mb-1 uppercase">
                        Estrutura do Painel
                      </span>
                      <select
                        className="w-full bg-slate-950 border border-slate-800 text-slate-100 rounded px-2.5 py-1.5 text-xs font-bold outline-none cursor-pointer focus:ring-1 focus:ring-indigo-500"
                        value={userConfig.dashboardSettings.layout}
                        onChange={(e) =>
                          updateDashboardSettings({
                            layout: e.target.value as any,
                          })
                        }
                      >
                        <option value="grid">Bento Grid (Recomendado)</option>
                        <option value="compact">
                          Modo Compacto de Alta Densidade
                        </option>
                        <option value="dense">Modo Denso Conectado</option>
                        <option value="classic">
                          Layout Clássico Vertical de Cartões
                        </option>
                      </select>
                    </div>

                    <div>
                      <span className="text-[10px] text-slate-400 font-bold block mb-1 uppercase">
                        Widgets Habilitados
                      </span>
                      <div className="space-y-1.5 pl-1 max-h-[120px] overflow-y-auto pr-1 customize-scrollbar">
                        {[
                          { id: "balance", name: "Saldo Geral" },
                          { id: "income", name: "Histórico Receitas" },
                          { id: "expense", name: "Histórico Despesas" },
                          { id: "chart", name: "Gráfico de Fluxo" },
                          { id: "inventory", name: "Controle de Estoque" },
                          { id: "habits", name: "Checklist de Hábitos" },
                          { id: "appointments", name: "Próximos Compromissos" },
                          { id: "goals", name: "Metas Ativas" },
                          { id: "medications", name: "Status de Medicação" },
                        ].map((w) => {
                          const isChecked =
                            userConfig.dashboardSettings.visibleWidgets.includes(
                              w.id,
                            );
                          return (
                            <label
                              key={w.id}
                              className="flex items-center gap-2 text-slate-300 cursor-pointer hover:text-white transition"
                            >
                              <input
                                type="checkbox"
                                className="rounded accent-indigo-600 border-slate-700 bg-slate-900 w-3.5 h-3.5 cursor-pointer"
                                checked={isChecked}
                                onChange={(e) => {
                                  const current =
                                    userConfig.dashboardSettings.visibleWidgets;
                                  const updated = e.target.checked
                                    ? [...current, w.id]
                                    : current.filter((id) => id !== w.id);
                                  updateDashboardSettings({
                                    visibleWidgets: updated,
                                  });
                                }}
                              />
                              {w.name}
                            </label>
                          );
                        })}
                      </div>
                    </div>
                  </div>
                </div>

                {/* 3D: INSTALAÇÃO & TELEFONE INTELIGENTE */}
                <div
                  className="col-span-1 md:col-span-2 space-y-4 bg-gradient-to-br from-indigo-950/40 to-slate-950 border border-indigo-500/15 p-4 rounded-xl shadow-[0_0_15px_rgba(99,102,241,0.05)] animate-fade-in transition-all duration-500"
                >
                  <div className="flex justify-between items-start">
                    <h4 className="text-xs font-bold text-indigo-400 flex items-center gap-1.5 uppercase tracking-wide">
                      <Smartphone className="w-3.5 h-3.5" /> Instalação do Aplicativo (PWA)
                    </h4>
                    <span className="text-[9px] bg-indigo-500/10 text-indigo-300 font-bold px-2 py-0.5 rounded-full border border-indigo-500/20">
                      Suporte iOS & Android
                    </span>
                  </div>

                  <div className="grid grid-cols-1 gap-4 text-xs font-sans">
                    {/* Column 1: Install Home Screen */}
                    <div className="space-y-2 bg-slate-900/40 p-3 rounded-lg border border-slate-850">
                      <span className="text-[10px] text-slate-400 font-bold block uppercase tracking-wider mb-1 flex items-center gap-1 font-mono">
                        <Download className="w-3 h-3" /> Instalar na Tela de Início
                      </span>
                      <p className="text-[10.5px] text-slate-350 leading-relaxed">
                        Transforme o Gestor de Vida em um aplicativo exclusivo do celular para carregamento super rápido e tela inteira (PWA).
                      </p>

                      {isInstallable ? (
                        <button
                          type="button"
                          onClick={handleInstallAppPWA}
                          className="w-full mt-2 py-2 px-3 bg-indigo-650 hover:bg-indigo-600 text-white font-bold rounded-lg transition-all flex items-center justify-center gap-1.5 cursor-pointer shadow-sm shadow-indigo-950/40"
                        >
                          <Download className="w-3.5 h-3.5" /> Adicionar à Tela de Início
                        </button>
                      ) : (
                        <div className="p-2 sm:p-2.5 rounded bg-slate-950/60 border border-slate-800 text-[10px] text-slate-450 space-y-1 mt-1 leading-normal">
                          <span className="font-bold text-indigo-400 uppercase font-mono tracking-wider block">
                            📲 Como instalar no iPhone (iOS):
                          </span>
                          <span>
                            Abra o site no navegador <strong>Safari</strong>,
                            toque no ícone de <strong>Compartilhar</strong>{" "}
                            (ícone de seta pra cima no menu do navegador{" "}
                            <Share2 className="w-2.5 h-2.5 inline" />) e
                            selecione{" "}
                            <strong>"Adicionar à Tela de Início"</strong>.
                            Pronto! Ele abrirá em tela cheia como App nativo.
                          </span>
                        </div>
                      )}
                    </div>
                  </div>
                </div>

                    {/* Geofencing Quick Settings & Location Tracking Duration - Desativado conforme solicitado */}
                    {false && (
                    <div className="col-span-1 lg:col-span-2 mt-1 p-3.5 bg-slate-950/40 border border-slate-850/60 rounded-xl space-y-3">
                      <div className="flex items-center justify-between pb-1.5 border-b border-slate-900">
                        <span className="text-[10px] text-slate-350 font-bold block uppercase tracking-wider flex items-center gap-1.5 font-mono">
                          <Compass className="w-3.5 h-3.5 text-indigo-400" />{" "}
                          Monitoramento Geográfico (Geofencing)
                        </span>

                        <div className="flex items-center gap-2">
                          <span
                            className={`flex h-2 w-2 relative ${!!userConfig?.notificationSettings?.geolocationAlertsEnabled ? "block" : "hidden"}`}
                          >
                            <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
                            <span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500"></span>
                          </span>
                          <span
                            className={`text-[9px] font-mono font-black ${!!userConfig?.notificationSettings?.geolocationAlertsEnabled ? "text-indigo-400" : "text-slate-500"}`}
                          >
                            {!!userConfig?.notificationSettings
                              ?.geolocationAlertsEnabled
                              ? "RASTREAMENTO ATIVO"
                              : "RASTREAMENTO INATIVO"}
                          </span>
                        </div>
                      </div>

                      <p className="text-[10.5px] text-slate-400 leading-normal">
                        Defina coordenadas precisas de geofencing de{" "}
                        <strong>Casa</strong> e <strong>Trabalho</strong> no
                        mapa para receber alertas contextuais inteligentes e
                        relatórios de permanência.
                      </p>

                      {/* Home / Work Settings with 24h counters */}
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3 pt-1">
                        {/* Casa */}
                        <div className="bg-slate-900/40 border border-slate-850/50 rounded-xl p-3 space-y-2.5 transition hover:border-indigo-500/20">
                          <div className="flex justify-between items-start">
                            <div className="flex items-center gap-2">
                              <div className="p-1.5 rounded-lg bg-indigo-500/10 text-indigo-400 border border-indigo-500/15">
                                <MapPin className="w-3.5 h-3.5" />
                              </div>
                              <div>
                                <span className="font-extrabold text-[11px] text-slate-200 block">
                                  🏠 Casa (Padrão)
                                </span>
                                <span
                                  className="text-[9px] text-slate-500 block max-w-[110px] truncate"
                                  title={
                                    userConfig?.notificationSettings
                                      ?.homeLocation?.address || "Sem endereço"
                                  }
                                >
                                  {userConfig?.notificationSettings
                                    ?.homeLocation?.address || "Sem endereço"}
                                </span>
                              </div>
                            </div>

                            <div className="flex flex-col items-end gap-1">
                              <span className="text-[10px] font-mono font-bold text-slate-400 bg-slate-950 px-2 py-0.5 border border-slate-850 rounded-md">
                                R:{" "}
                                {userConfig?.notificationSettings?.homeLocation
                                  ?.radius ?? 200}
                                m
                              </span>
                              {userConfig?.notificationSettings?.homeLocation
                                ?.minDwellTime !== undefined &&
                                userConfig.notificationSettings.homeLocation
                                  .minDwellTime > 0 && (
                                  <span
                                    className="text-[9px] font-mono font-semibold text-amber-400 bg-amber-500/10 px-1.5 py-0.5 border border-amber-500/20 rounded"
                                    title="Tempo de permanência mínimo"
                                  >
                                    ⏱️{" "}
                                    {
                                      userConfig.notificationSettings
                                        .homeLocation.minDwellTime
                                    }{" "}
                                    min
                                  </span>
                                )}
                            </div>
                          </div>

                          <div className="flex items-center justify-between pt-1.5 border-t border-slate-900/60">
                            <div>
                              <span className="text-[8.5px] uppercase tracking-wider text-slate-500 block font-bold">
                                Permanência (24h)
                              </span>
                              <span className="text-xs font-mono font-black text-indigo-400 flex items-center gap-1">
                                <Clock className="w-3 h-3 text-indigo-400/70" />
                                {homeTimeLast24h}
                              </span>
                            </div>

                            <button
                              type="button"
                              onClick={() => openGeofenceSetup("home")}
                              className="px-2.5 py-1 text-[9px] font-bold text-white bg-indigo-650 hover:bg-indigo-600 rounded border border-indigo-600/30 transition cursor-pointer"
                            >
                              Configurar Cerca
                            </button>
                          </div>
                        </div>

                        {/* Trabalho */}
                        <div className="bg-slate-900/40 border border-slate-850/50 rounded-xl p-3 space-y-2.5 transition hover:border-emerald-500/20">
                          <div className="flex justify-between items-start">
                            <div className="flex items-center gap-2">
                              <div className="p-1.5 rounded-lg bg-emerald-500/10 text-emerald-400 border border-emerald-500/15">
                                <MapPin className="w-3.5 h-3.5" />
                              </div>
                              <div>
                                <span className="font-extrabold text-[11px] text-slate-200 block">
                                  💼 Trabalho (Padrão)
                                </span>
                                <span
                                  className="text-[9px] text-slate-500 block max-w-[110px] truncate"
                                  title={
                                    userConfig?.notificationSettings
                                      ?.workLocation?.address || "Sem endereço"
                                  }
                                >
                                  {userConfig?.notificationSettings
                                    ?.workLocation?.address || "Sem endereço"}
                                </span>
                              </div>
                            </div>

                            <div className="flex flex-col items-end gap-1">
                              <span className="text-[10px] font-mono font-bold text-slate-400 bg-slate-950 px-2 py-0.5 border border-slate-850 rounded-md">
                                R:{" "}
                                {userConfig?.notificationSettings?.workLocation
                                  ?.radius ?? 200}
                                m
                              </span>
                              {userConfig?.notificationSettings?.workLocation
                                ?.minDwellTime !== undefined &&
                                userConfig.notificationSettings.workLocation
                                  .minDwellTime > 0 && (
                                  <span
                                    className="text-[9px] font-mono font-semibold text-amber-400 bg-amber-500/10 px-1.5 py-0.5 border border-amber-500/20 rounded"
                                    title="Tempo de permanência mínimo"
                                  >
                                    ⏱️{" "}
                                    {
                                      userConfig.notificationSettings
                                        .workLocation.minDwellTime
                                    }{" "}
                                    min
                                  </span>
                                )}
                            </div>
                          </div>

                          <div className="flex items-center justify-between pt-1.5 border-t border-slate-900/60">
                            <div>
                              <span className="text-[8.5px] uppercase tracking-wider text-slate-500 block font-bold">
                                Permanência (24h)
                              </span>
                              <span className="text-xs font-mono font-black text-emerald-400 flex items-center gap-1">
                                <Clock className="w-3 h-3 text-emerald-400/70" />
                                {workTimeLast24h}
                              </span>
                            </div>

                            <button
                              type="button"
                              onClick={() => openGeofenceSetup("work")}
                              className="px-2.5 py-1 text-[9px] font-bold text-white bg-indigo-650 hover:bg-indigo-600 rounded border border-indigo-600/30 transition cursor-pointer"
                            >
                              Configurar Cerca
                            </button>
                          </div>
                        </div>
                      </div>

                      {/* Botão de Configurações Avançadas e Busca */}
                      <div className="flex justify-end pt-1">
                        <button
                          type="button"
                          onClick={openAdvancedGeofenceModal}
                          className="w-full sm:w-auto py-1.5 px-3 text-[10px] font-bold text-indigo-300 hover:text-white bg-indigo-500/10 hover:bg-indigo-600/30 border border-indigo-500/20 hover:border-indigo-500/40 rounded-lg transition-all duration-300 flex items-center justify-center gap-1.5 cursor-pointer shadow-sm"
                        >
                          <Sliders className="w-3.5 h-3.5 text-indigo-400" />
                          Configurações Avançadas (Tempo de Permanência & Busca)
                        </button>
                      </div>

                      {/* Silenciamento Inteligente */}
                      <div className="p-3 bg-slate-900/60 rounded-xl border border-slate-850/60 space-y-2 font-sans animate-fade-in transition-all">
                        <div className="flex items-center justify-between">
                          <span className="text-[10px] text-slate-400 font-bold uppercase tracking-wider font-mono flex items-center gap-1.5">
                            <BellOff className="w-3.5 h-3.5 text-indigo-400" />{" "}
                            Silenciamento Inteligente de Geofencing
                          </span>
                          {geofenceMutedUntil &&
                          Date.now() < geofenceMutedUntil ? (
                            <span className="inline-flex items-center gap-1 text-[9px] font-mono font-extrabold text-amber-400 bg-amber-500/10 border border-amber-500/20 px-2 py-0.5 rounded-full animate-pulse">
                              PAUSADO
                            </span>
                          ) : (
                            <span className="inline-flex items-center gap-1 text-[9px] font-mono font-semibold text-slate-400 bg-slate-950 border border-slate-850 px-2 py-0.5 rounded-full">
                              ATIVO
                            </span>
                          )}
                        </div>
                        <p className="text-[10px] text-slate-400 leading-normal">
                          Pausa temporariamente alertas de geofencing de entrada
                          e saída por um período definido, sem afetar outras
                          notificações globais.
                        </p>
                        <div className="flex flex-wrap items-center gap-2 pt-1">
                          <button
                            type="button"
                            onClick={() => muteGeofence(1)}
                            className={`px-2.5 py-1 text-[9.5px] font-bold rounded-md border transition cursor-pointer ${
                              geofenceMutedUntil &&
                              Math.abs(
                                geofenceMutedUntil -
                                  Date.now() -
                                  1 * 60 * 60 * 1000,
                              ) < 60000
                                ? "bg-indigo-600 border-indigo-500 text-white shadow-md shadow-indigo-950/20"
                                : "bg-slate-950 border-slate-850 text-slate-300 hover:text-white hover:bg-slate-900"
                            }`}
                          >
                            1 Hora
                          </button>
                          <button
                            type="button"
                            onClick={() => muteGeofence(2)}
                            className={`px-2.5 py-1 text-[9.5px] font-bold rounded-md border transition cursor-pointer ${
                              geofenceMutedUntil &&
                              Math.abs(
                                geofenceMutedUntil -
                                  Date.now() -
                                  2 * 60 * 60 * 1000,
                              ) < 60000
                                ? "bg-indigo-600 border-indigo-500 text-white shadow-md shadow-indigo-950/20"
                                : "bg-slate-950 border-slate-850 text-slate-300 hover:text-white hover:bg-slate-900"
                            }`}
                          >
                            2 Horas
                          </button>
                          <button
                            type="button"
                            onClick={() => muteGeofence(4)}
                            className={`px-2.5 py-1 text-[9.5px] font-bold rounded-md border transition cursor-pointer ${
                              geofenceMutedUntil &&
                              Math.abs(
                                geofenceMutedUntil -
                                  Date.now() -
                                  4 * 60 * 60 * 1000,
                              ) < 60000
                                ? "bg-indigo-600 border-indigo-500 text-white shadow-md shadow-indigo-950/20"
                                : "bg-slate-950 border-slate-850 text-slate-300 hover:text-white hover:bg-slate-900"
                            }`}
                          >
                            4 Horas
                          </button>
                          {geofenceMutedUntil &&
                            Date.now() < geofenceMutedUntil && (
                              <button
                                type="button"
                                onClick={unmuteGeofence}
                                className="px-2.5 py-1 text-[9.5px] font-bold rounded-md border border-red-500/30 bg-red-500/10 hover:bg-red-500/20 text-red-400 transition cursor-pointer ml-auto"
                              >
                                Reativar Alertas
                              </button>
                            )}
                        </div>
                        {muteTimeRemaining && (
                          <div className="text-[9.5px] font-mono text-amber-400 flex items-center gap-1 pt-1">
                            <span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping" />
                            Silenciado: {muteTimeRemaining}
                          </div>
                        )}
                      </div>

                      {/* Contador Dinâmico de Tempo Real */}
                      <div className="p-3 bg-slate-900/60 rounded-xl border border-slate-850 space-y-2 font-sans">
                        <div className="flex items-center justify-between">
                          <span className="text-[10px] text-slate-400 font-bold uppercase tracking-wider font-mono">
                            🕒 Tempo Real de Permanência (Últimas 24h)
                          </span>
                          {isInside ? (
                            <span className="inline-flex items-center gap-1 text-[9px] font-mono font-extrabold text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-2 py-0.5 rounded-full animate-pulse">
                              <span className="w-1.5 h-1.5 rounded-full bg-emerald-400" />
                              DENTRO DA ZONA
                            </span>
                          ) : (
                            <span className="inline-flex items-center gap-1 text-[9px] font-mono font-semibold text-slate-400 bg-slate-950 border border-slate-850 px-2 py-0.5 rounded-full">
                              <span className="w-1.5 h-1.5 rounded-full bg-slate-500" />
                              FORA DAS ÁREAS BASE
                            </span>
                          )}
                        </div>

                        {isInside ? (
                          <div className="flex items-center justify-between p-2 rounded-lg bg-indigo-950/20 border border-indigo-500/10">
                            <div>
                              <span className="text-[10px] text-slate-400 block uppercase tracking-wider font-semibold">
                                Zona Atual Ativa
                              </span>
                              <span className="text-xs font-bold text-indigo-300">
                                {!!wasInsideHome.current
                                  ? "🏠 Casa (Principal)"
                                  : "💼 Trabalho (Escritório)"}
                              </span>
                            </div>
                            <div className="text-right">
                              <span className="text-[9px] text-slate-450 block uppercase tracking-wider font-semibold">
                                Total Acumulado (24h)
                              </span>
                              <span className="text-lg font-black font-mono text-indigo-400">
                                {!!wasInsideHome.current
                                  ? homeTimeLast24h
                                  : workTimeLast24h}
                              </span>
                            </div>
                          </div>
                        ) : (
                          <div className="grid grid-cols-2 gap-2 text-center font-sans">
                            <div className="p-2 rounded-lg bg-slate-950/40 border border-slate-900">
                              <span className="text-[9px] text-slate-500 block uppercase tracking-wider font-semibold">
                                Total Casa (24h)
                              </span>
                              <span className="text-sm font-bold font-mono text-slate-300">
                                {homeTimeLast24h}
                              </span>
                            </div>
                            <div className="p-2 rounded-lg bg-slate-950/40 border border-slate-900">
                              <span className="text-[9px] text-slate-500 block uppercase tracking-wider font-semibold">
                                Total Trabalho (24h)
                              </span>
                              <span className="text-sm font-bold font-mono text-slate-300">
                                {workTimeLast24h}
                              </span>
                            </div>
                          </div>
                        )}
                      </div>

                      {/* Mini Tabela de Transições de Geofencing (Últimos 3 Horários) */}
                      <div className="p-3 bg-slate-900/60 rounded-xl border border-slate-850 space-y-2 font-sans">
                        <span className="text-[10px] text-slate-400 font-bold uppercase tracking-wider font-mono block">
                          📊 Últimas 3 Transições Registradas (IndexedDB)
                        </span>
                        {lastFiveGeofenceEvents.length > 0 ? (
                          <div className="overflow-x-auto rounded-lg border border-slate-950 bg-slate-950/20">
                            <table className="w-full text-left border-collapse min-w-[300px]">
                              <thead>
                                <tr className="border-b border-slate-950 bg-slate-950/60 text-[8px] font-bold text-slate-500 uppercase tracking-wider font-mono">
                                  <th className="p-1.5 pl-2 font-semibold">
                                    Data / Hora
                                  </th>
                                  <th className="p-1.5 font-semibold">Zona</th>
                                  <th className="p-1.5 text-right pr-2 font-semibold">
                                    Ação
                                  </th>
                                </tr>
                              </thead>
                              <tbody className="divide-y divide-slate-950/30 text-[9.5px]">
                                {lastFiveGeofenceEvents
                                  .slice(0, 3)
                                  .map((event) => {
                                    const textLower =
                                      event.message.toLowerCase();
                                    const isHome =
                                      textLower.includes("casa") ||
                                      textLower.includes("home") ||
                                      event.details?.zone === "home";
                                    const isEnter =
                                      textLower.includes("chegada") ||
                                      textLower.includes("chegando") ||
                                      event.details?.transition === "enter";
                                    return (
                                      <tr
                                        key={event.id}
                                        className="hover:bg-slate-950/40 transition-colors"
                                      >
                                        <td className="p-1.5 pl-2 font-mono text-slate-400">
                                          {new Date(
                                            event.timestamp,
                                          ).toLocaleString("pt-BR", {
                                            hour: "2-digit",
                                            minute: "2-digit",
                                            second: "2-digit",
                                          })}
                                        </td>
                                        <td className="p-1.5 font-semibold text-slate-300">
                                          {isHome ? "🏠 Casa" : "💼 Trabalho"}
                                        </td>
                                        <td className="p-1.5 text-right pr-2">
                                          <span
                                            className={`inline-flex items-center gap-1 text-[8px] font-bold px-1 rounded-sm ${
                                              isEnter
                                                ? "bg-indigo-500/10 text-indigo-400"
                                                : "bg-amber-500/10 text-amber-400"
                                            }`}
                                          >
                                            {isEnter ? "Entrada" : "Saída"}
                                          </span>
                                        </td>
                                      </tr>
                                    );
                                  })}
                              </tbody>
                            </table>
                          </div>
                        ) : (
                          <p className="text-[10px] text-slate-500 italic text-center py-2 bg-slate-950/10 rounded">
                            Nenhuma transição recente encontrada nos registros.
                          </p>
                        )}
                      </div>

                      {/* Linha do Tempo / Últimos Eventos de Geofencing & Exportar Relatório */}
                      <div className="pt-3 border-t border-slate-900/80 space-y-2.5">
                        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                          <span className="text-[10px] text-indigo-400 font-extrabold uppercase tracking-wider flex items-center gap-1.5 font-mono">
                            <Activity className="w-3.5 h-3.5 text-indigo-400 animate-pulse" />{" "}
                            Últimos 5 Eventos Detectados
                          </span>

                          <button
                            type="button"
                            onClick={handleExportGeofenceCSV}
                            className="px-2.5 py-1 text-[9.5px] font-bold text-indigo-400 hover:text-white bg-indigo-500/10 hover:bg-indigo-650 border border-indigo-500/20 hover:border-indigo-600 rounded-lg transition-all duration-300 flex items-center gap-1.5 cursor-pointer self-start sm:self-auto"
                          >
                            <Download className="w-3.5 h-3.5" /> Exportar
                            Relatório (CSV)
                          </button>
                        </div>

                        {lastFiveGeofenceEvents.length > 0 ? (
                          <div className="overflow-x-auto rounded-lg border border-slate-900 bg-slate-950/40">
                            <table className="w-full text-left border-collapse min-w-[340px]">
                              <thead>
                                <tr className="border-b border-slate-900 bg-slate-950/80 text-[8.5px] font-bold text-slate-400 uppercase tracking-wider font-mono">
                                  <th className="p-2 font-semibold">Hora</th>
                                  <th className="p-2 font-semibold">Cerca</th>
                                  <th className="p-2 font-semibold">
                                    Transição
                                  </th>
                                  <th className="p-2 font-semibold text-right">
                                    Status
                                  </th>
                                </tr>
                              </thead>
                              <tbody className="divide-y divide-slate-900/40 text-[10px]">
                                {lastFiveGeofenceEvents.map((event) => {
                                  const textLower = event.message.toLowerCase();
                                  const isHome =
                                    textLower.includes("casa") ||
                                    textLower.includes("home") ||
                                    event.details?.zone === "home";
                                  const isEnter =
                                    textLower.includes("chegada") ||
                                    textLower.includes("chegando") ||
                                    event.details?.transition === "enter";

                                  return (
                                    <tr
                                      key={event.id}
                                      className="hover:bg-slate-900/20 transition-colors"
                                    >
                                      <td className="p-2 font-mono text-slate-400">
                                        {new Date(
                                          event.timestamp,
                                        ).toLocaleTimeString("pt-BR", {
                                          hour: "2-digit",
                                          minute: "2-digit",
                                          second: "2-digit",
                                        })}
                                      </td>
                                      <td className="p-2 font-semibold text-slate-200">
                                        {isHome ? "🏠 Casa" : "💼 Trabalho"}
                                      </td>
                                      <td className="p-2 text-slate-350">
                                        {isEnter
                                          ? "Entrada na área"
                                          : "Saída da área"}
                                      </td>
                                      <td className="p-2 text-right">
                                        <span
                                          className={`inline-flex items-center gap-1 text-[8.5px] font-bold px-1.5 py-0.5 rounded ${
                                            isEnter
                                              ? "bg-emerald-500/10 text-emerald-400 border border-emerald-500/10"
                                              : "bg-amber-500/10 text-amber-400 border border-amber-500/10"
                                          }`}
                                        >
                                          <span
                                            className={`w-1 h-1 rounded-full ${isEnter ? "bg-emerald-400" : "bg-amber-400"}`}
                                          />
                                          {isEnter ? "Dentro" : "Fora"}
                                        </span>
                                      </td>
                                    </tr>
                                  );
                                })}
                              </tbody>
                            </table>
                          </div>
                        ) : (
                          <div className="py-4 text-center text-[10px] text-slate-500 bg-slate-950/20 border border-slate-900/60 rounded-xl italic">
                            Nenhum evento registrado nas últimas 24 horas.
                          </div>
                        )}
                      </div>
                    </div>
                    )}

                {/* 3C: CONEXÃO E SEGURANÇA */}
                <div className="col-span-1 md:col-span-2 space-y-3 bg-slate-950/80 border border-slate-850 p-4 rounded-xl">
                  <h4 className="text-xs font-bold text-white flex items-center justify-between">
                    <span className="flex items-center gap-1.5 text-indigo-400 uppercase tracking-wide">
                      <Shield className="w-3.5 h-3.5 text-indigo-400" /> Conta &
                      Conectividade
                    </span>
                    {user ? (
                      <span className="inline-flex items-center gap-1.5 text-[9px] bg-emerald-500/10 text-emerald-400 font-bold px-2 py-0.5 rounded-full border border-emerald-500/20">
                        <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />{" "}
                        Sincronizado na Nuvem
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1.5 text-[9px] bg-amber-500/10 text-amber-400 font-bold px-2 py-0.5 rounded-full border border-amber-500/20">
                        <span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse" />{" "}
                        Sandbox Local
                      </span>
                    )}
                  </h4>

                  {/* Relocated Family Management & Cloud Synchronization buttons */}
                  <div className="p-3 bg-indigo-505/5 border border-indigo-505/10 rounded-xl space-y-2">
                    <h5 className="text-[11px] font-bold text-indigo-300 flex items-center gap-1.5 uppercase tracking-wide">
                      <Users className="w-3.5 h-3.5 text-indigo-450" /> Membros
                      Compartilhados
                    </h5>
                    <p className="text-[10px] text-slate-400 leading-normal">
                      Gerencie as pessoas cadastradas para acompanhamento mútuo
                      de despesas, boletos, metas e hábitos ou ative a
                      sincronização multi-dispositivo segura.
                    </p>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 pt-1">
                      <button
                        type="button"
                        onClick={() => {
                          setShowSettingsModal(false);
                          setShowFamilyModal(true);
                        }}
                        className="py-1.5 px-3 bg-indigo-650 hover:bg-indigo-600 text-white text-[11px] font-bold rounded-lg transition-all flex items-center justify-center gap-1.5 cursor-pointer shadow-sm shadow-indigo-950/40"
                      >
                        <Users className="w-3.5 h-3.5" /> Gerenciar Membros
                      </button>
                      <button
                        type="button"
                        onClick={() => {
                          setShowSettingsModal(false);
                          setShowSyncPanel(true);
                        }}
                        className="py-1.5 px-3 bg-slate-800 hover:bg-slate-700 text-slate-205 text-[11px] font-bold rounded-lg transition-all flex items-center justify-center gap-1.5 cursor-pointer border border-slate-750"
                      >
                        <Share2 className="w-3.5 h-3.5" /> Sincronizar Nuvem
                      </button>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-1">
                    <div className="space-y-1 bg-slate-900 border border-slate-800 p-3 rounded-xl flex flex-col justify-center">
                      <span className="text-[9px] font-bold text-slate-400 block uppercase tracking-wider">
                        Conta Conectada
                      </span>
                      {user ? (
                        <div className="flex items-center gap-2 mt-1">
                          {user.photoURL ? (
                            <img
                              src={user.photoURL}
                              referrerPolicy="no-referrer"
                              loading="lazy"
                              className="w-8 h-8 rounded-full border border-slate-800 shadow-3xs"
                            />
                          ) : (
                            <div className="w-8 h-8 rounded-full bg-indigo-500/10 border border-indigo-500/20 text-indigo-400 flex items-center justify-center text-xs font-bold">
                              {user.displayName?.charAt(0) || "U"}
                            </div>
                          )}
                          <div className="min-w-0 flex-1">
                            <p className="text-xs font-bold text-white truncate">
                              {user.displayName || "Usuário"}
                            </p>
                            <p className="text-[9.5px] text-slate-400 truncate">
                              {user.email}
                            </p>
                          </div>
                        </div>
                      ) : (
                        <p className="text-xs text-amber-400 font-medium mt-1">
                          Não conectado à nuvem
                        </p>
                      )}
                    </div>

                    <div className="space-y-1 bg-slate-900 border border-slate-800 p-3 rounded-xl flex flex-col justify-between">
                      <div>
                        <span className="text-[9px] font-bold text-slate-400 block uppercase tracking-wider">
                          Código de Nuvem Ativo
                        </span>
                        <p className="text-[10px] text-slate-400 font-medium">
                          Use para ligar outros aparelhos:
                        </p>
                        <p className="font-mono text-xs font-bold text-indigo-400 tracking-wider mt-0.5">
                          {userId}
                        </p>
                      </div>
                    </div>
                  </div>

                  <div className="flex flex-col sm:flex-row gap-2 pt-2.5 border-t border-slate-800">
                    <button
                      type="button"
                      onClick={() => {
                        setShowSettingsModal(false);
                        setShowSyncPanel(true);
                      }}
                      className="flex-grow py-2 px-3 bg-indigo-650/10 hover:bg-indigo-650/20 text-indigo-300 hover:text-white text-xs font-bold rounded-lg transition-all flex items-center justify-center gap-1.5 border border-indigo-500/20 cursor-pointer"
                    >
                      <Share2 className="w-3.5 h-3.5" /> Configurar
                      Sincronização
                    </button>

                    {user || isGuestMode ? (
                      <button
                        type="button"
                        onClick={() => {
                          logout();
                          setIsGuestMode(false);
                          localStorage.removeItem("life_manager_guest_mode");
                          setShowSettingsModal(false);
                        }}
                        className="py-2 px-4 bg-rose-500/10 hover:bg-rose-500/20 text-rose-450 hover:text-rose-400 text-xs font-bold rounded-lg transition-all flex items-center justify-center gap-1.5 border border-rose-500/20 cursor-pointer text-center"
                        title="Sair de todas as sessões e ir para tela de login"
                      >
                        <LogOut className="w-3.5 h-3.5" /> Sair
                      </button>
                    ) : (
                      <button
                        type="button"
                        onClick={() => {
                          loginWithGoogle();
                          setShowSettingsModal(false);
                        }}
                        className="py-2 px-4 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold rounded-lg transition-all flex items-center justify-center gap-1.5 cursor-pointer shadow-sm"
                      >
                        <LogIn className="w-3.5 h-3.5" /> Conectar com Google
                      </button>
                    )}
                  </div>
                </div>
              </div>

              <div className="pt-2 flex justify-end">
                <button
                  onClick={() => setShowSettingsModal(false)}
                  className="px-5 py-2 bg-indigo-600 hover:bg-indigo-705 text-white rounded-lg text-xs font-bold transition shadow-md"
                >
                  Concluir Ajustes
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Sync configuration Modal panel overlay */}
      <AnimatePresence>
        {showSyncPanel && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/60 backdrop-blur-xs px-4"
          >
            <motion.div
              initial={{ scale: 0.95 }}
              animate={{ scale: 1 }}
              exit={{ scale: 0.95 }}
              className="bg-slate-900 max-w-sm w-full rounded-2xl p-6 shadow-2xl border border-slate-800 relative space-y-4 text-white"
            >
              <button
                onClick={() => setShowSyncPanel(false)}
                className="absolute top-4 right-4 p-1.5 text-slate-400 hover:text-white rounded-full hover:bg-slate-800 cursor-pointer transition"
              >
                <X className="w-4.5 h-4.5" />
              </button>

              <div className="space-y-1.5 pr-6">
                <h3 className="font-semibold text-white text-sm flex items-center gap-2 font-display">
                  <span className="p-1.5 bg-indigo-550/10 border border-indigo-505/20 text-indigo-455 rounded-lg inline-block">
                    <Share2 className="w-4 h-4 text-indigo-400" />
                  </span>
                  Sincronização em Tempo Real
                </h3>
                <p className="text-[11px] text-slate-400 leading-relaxed">
                  Conecte múltiplos dispositivos à mesma base de dados copiando
                  o código abaixo ou inserindo um novo.
                </p>
              </div>

              {/* Unique Sync ID Card */}
              <div className="bg-slate-950 border border-slate-850 rounded-xl p-3 flex justify-between items-center shadow-inner">
                <div>
                  <span className="text-[9px] text-slate-450 font-bold block uppercase tracking-wider">
                    Seu Código Ativo
                  </span>
                  <span className="font-mono text-sm font-bold text-indigo-400 tracking-widest">
                    {userId}
                  </span>
                </div>
                <button
                  type="button"
                  onClick={handleCopyId}
                  className="p-1 px-2.5 bg-slate-900 hover:bg-slate-800 rounded-lg text-slate-300 border border-slate-800 transition text-[10px] font-bold cursor-pointer flex items-center gap-1.5"
                  title="Copiar ID"
                >
                  {copied ? (
                    <>
                      <Check className="w-3 h-3 text-emerald-400" /> Copiado!
                    </>
                  ) : (
                    <>
                      <Copy className="w-3 h-3" /> Copiar
                    </>
                  )}
                </button>
              </div>

              {/* Load database input sync */}
              <form onSubmit={handleSyncSubmit} className="space-y-3 pt-1">
                <div>
                  <label className="text-[10px] uppercase font-bold text-slate-400 block mb-1">
                    Conectar e Carregar outro ID
                  </label>
                  <input
                    type="text"
                    required
                    placeholder="Ex: GL-J7H49D"
                    className="w-full bg-slate-950 border border-slate-850 rounded-lg px-3 py-2 text-xs text-white font-mono font-bold uppercase tracking-widest outline-none focus:ring-1 focus:ring-indigo-500"
                    value={syncInput}
                    onChange={(e) => setSyncInput(e.target.value)}
                  />
                </div>
                <button
                  type="submit"
                  className="w-full py-2 bg-indigo-600 hover:bg-indigo-705 text-white font-bold rounded-lg text-xs transition cursor-pointer"
                >
                  Conectar Código
                </button>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Floating On-Screen Toast Notifications Fallback for PC & Mobile */}
      <div className="fixed top-4 right-4 z-50 flex flex-col gap-2.5 max-w-sm w-full pointer-events-none px-4">
        {toasts.length > 1 && (
          <button
            onClick={() => setToasts([])}
            className="self-end pointer-events-auto bg-slate-800/80 hover:bg-slate-700 border border-slate-700/50 text-slate-300 hover:text-white px-2.5 py-1 rounded-lg text-[10px] font-bold flex items-center gap-1 transition cursor-pointer backdrop-blur shadow-md"
          >
            <X className="w-3 h-3" />
            <span>Limpar Todos</span>
          </button>
        )}
        <AnimatePresence>
          {toasts.map((t) => (
            <motion.div
              key={t.id}
              initial={{ opacity: 0, y: -20, scale: 0.95 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, scale: 0.9, transition: { duration: 0.15 } }}
              className="bg-slate-900/95 border border-slate-800 text-white p-3.5 rounded-xl shadow-2xl flex flex-col gap-1 pointer-events-auto backdrop-blur-md relative pr-8"
            >
              <button
                onClick={() =>
                  setToasts((prev) => prev.filter((item) => item.id !== t.id))
                }
                className="absolute top-3 right-3 text-slate-400 hover:text-white p-1 rounded-md hover:bg-slate-800 transition cursor-pointer"
                title="Fechar"
              >
                <X className="w-3 h-3" />
              </button>
              <div className="flex items-center gap-2 text-indigo-400">
                <Bell className="w-4 h-4 animate-bounce" />
                <span className="font-bold text-xs tracking-tight uppercase">
                  {t.title}
                </span>
              </div>
              <p className="text-[11.5px] text-slate-300 leading-normal font-medium">
                {t.body}
              </p>
            </motion.div>
          ))}
        </AnimatePresence>
      </div>

      {/* Persistent Diagnostic Error Toast Monitor */}
      <AnimatePresence>
        {activeError && (
          <motion.div
            initial={{ opacity: 0, y: 50, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 20, scale: 0.95 }}
            className="fixed bottom-6 right-6 z-[60] max-w-sm w-full bg-slate-900 border border-rose-900/40 hover:border-rose-900/70 p-4 rounded-2xl shadow-2xl flex flex-col gap-3 backdrop-blur-md text-left"
          >
            <div className="flex items-start gap-3">
              <div className="p-2 bg-rose-500/10 border border-rose-500/20 text-rose-400 rounded-xl shrink-0">
                <AlertCircle className="w-5 h-5 text-rose-400" />
              </div>
              <div className="flex-1 min-w-0">
                <span className="text-[10px] font-bold text-rose-400 uppercase tracking-wider font-mono block">
                  Erro Crítico Detectado
                </span>
                <p className="text-xs text-slate-200 font-medium leading-normal mt-0.5 break-all line-clamp-3">
                  {activeError.message}
                </p>
                <span className="text-[9px] text-slate-500 mt-1 font-mono block">
                  {new Date(activeError.timestamp).toLocaleTimeString()}
                </span>
              </div>
              <button
                onClick={dismissError}
                className="text-slate-500 hover:text-slate-300 p-1 rounded-lg transition"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            <div className="flex justify-end gap-2.5 border-t border-slate-800/80 pt-2.5">
              <button
                onClick={dismissError}
                className="px-2.5 py-1.5 text-[10px] font-bold text-slate-400 hover:text-white hover:bg-slate-850 rounded-lg transition"
              >
                Dispensar
              </button>
              <button
                onClick={openLogsPanel}
                className="px-3 py-1.5 bg-rose-950/40 hover:bg-rose-900/40 border border-rose-900/40 hover:border-rose-900/60 text-rose-300 hover:text-rose-200 rounded-lg text-[10px] font-bold flex items-center gap-1.5 transition"
              >
                <ScrollText className="w-3.5 h-3.5" />
                Analisar Logs
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Floating Log Panel Modal */}
      <LogsPanelModal />

      {/* Geofence Setup Modal */}
      <AnimatePresence>
        {showGeofenceSetupModal && (
          <div className="fixed inset-0 z-[9999] flex items-center justify-center p-4">
            {/* Backdrop */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setShowGeofenceSetupModal(false)}
              className="absolute inset-0 bg-slate-950/80 backdrop-blur-sm"
            />

            {/* Modal Body */}
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 15 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 15 }}
              className="relative w-full max-w-lg bg-slate-900 border border-slate-800 rounded-2xl shadow-2xl shadow-indigo-950/40 overflow-hidden flex flex-col max-h-[90vh]"
            >
              {/* Header */}
              <div className="p-4 border-b border-slate-800 flex items-center justify-between">
                <div>
                  <h3 className="text-sm font-black text-white flex items-center gap-2">
                    <MapPin
                      className={`w-4 h-4 ${editingLocationType === "home" ? "text-indigo-400" : "text-emerald-400"}`}
                    />
                    Configurar Cerca:{" "}
                    {editingLocationType === "home"
                      ? "🏠 Casa (Residência)"
                      : "💼 Trabalho (Escritório)"}
                  </h3>
                  <p className="text-[10px] text-slate-400 mt-0.5">
                    Selecione as coordenadas no mapa, ajuste o raio e o
                    endereço.
                  </p>
                </div>
                <button
                  type="button"
                  onClick={() => setShowGeofenceSetupModal(false)}
                  className="p-1.5 hover:bg-slate-850 rounded-lg text-slate-400 hover:text-white transition"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>

              {/* Body */}
              <div className="p-4 space-y-4 overflow-y-auto flex-1">
                {/* Search Address bar */}
                <div className="space-y-1.5">
                  <label className="text-[10px] font-bold text-slate-300 block uppercase tracking-wider font-mono">
                    Buscar Endereço / Local
                  </label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={geocodeSearch}
                      onChange={(e) => setGeocodeSearch(e.target.value)}
                      placeholder="Ex: Av. Paulista, 1000, São Paulo..."
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          e.preventDefault();
                          handleSearchAddress(geocodeSearch);
                        }
                      }}
                      className="flex-1 bg-slate-950 border border-slate-850 focus:border-indigo-500 rounded-lg px-3 py-1.5 text-xs text-white placeholder-slate-600 focus:outline-none transition"
                    />
                    <button
                      type="button"
                      disabled={isSearchingGeocode}
                      onClick={() => handleSearchAddress(geocodeSearch)}
                      className="px-3 py-1.5 bg-indigo-650 hover:bg-indigo-600 text-white font-bold text-xs rounded-lg transition disabled:opacity-50 cursor-pointer"
                    >
                      {isSearchingGeocode ? "Buscando..." : "Buscar"}
                    </button>
                  </div>
                </div>

                {/* Leaflet Embedded Map Container */}
                <div className="space-y-1.5">
                  <div className="flex justify-between items-center">
                    <label className="text-[10px] font-bold text-slate-300 block uppercase tracking-wider font-mono">
                      Mapa Interativo (Arraste ou clique)
                    </label>
                    <span className="text-[9px] text-slate-500 font-mono">
                      Lat: {tempLat.toFixed(5)}, Lng: {tempLng.toFixed(5)}
                    </span>
                  </div>

                  {/* Map Element */}
                  <div
                    ref={mapContainerRef}
                    id="quick-geofence-map"
                    className="h-[220px] w-full rounded-xl border border-slate-800 bg-slate-950 overflow-hidden relative z-10"
                  />
                  <p className="text-[9.5px] text-slate-500 text-right italic">
                    *Arraste o pin ou clique em qualquer ponto do mapa para
                    definir o centro.
                  </p>
                </div>

                {/* Radius Selector */}
                <div className="space-y-1.5">
                  <div className="flex justify-between items-center text-xs">
                    <label className="text-[10px] font-bold text-slate-300 block uppercase tracking-wider font-mono">
                      Raio de Detecção
                    </label>
                    <span className="font-mono font-bold text-indigo-400">
                      {tempRadius} metros
                    </span>
                  </div>
                  <input
                    type="range"
                    min="50"
                    max="1000"
                    step="50"
                    value={tempRadius}
                    onChange={(e) => setTempRadius(parseInt(e.target.value))}
                    className="w-full h-1.5 bg-slate-950 rounded-lg appearance-none cursor-pointer accent-indigo-500"
                  />
                  <div className="flex justify-between text-[9px] text-slate-500 font-mono">
                    <span>50m</span>
                    <span>500m (Padrão)</span>
                    <span>1000m</span>
                  </div>
                </div>

                {/* Minimum Dwell Time Selector */}
                <div className="space-y-1.5">
                  <div className="flex justify-between items-center text-xs">
                    <label className="text-[10px] font-bold text-slate-300 block uppercase tracking-wider font-mono">
                      Tempo Mínimo de Permanência
                    </label>
                    <span className="font-mono font-bold text-indigo-400">
                      {tempMinDwellTime === 0
                        ? "Sem atraso (Imediato)"
                        : `${tempMinDwellTime} minutos`}
                    </span>
                  </div>
                  <input
                    type="range"
                    min="0"
                    max="15"
                    step="1"
                    value={tempMinDwellTime}
                    onChange={(e) =>
                      setTempMinDwellTime(parseInt(e.target.value))
                    }
                    className="w-full h-1.5 bg-slate-950 rounded-lg appearance-none cursor-pointer accent-indigo-500"
                  />
                  <div className="flex justify-between text-[9px] text-slate-500 font-mono">
                    <span>Imediato</span>
                    <span>5 min</span>
                    <span>10 min</span>
                    <span>15 min</span>
                  </div>
                  <p className="text-[9.5px] text-slate-500 leading-normal">
                    Evita alertas falsos se você apenas passar de carro ou
                    caminhar rapidamente pela área sem parar.
                  </p>
                </div>

                {/* Address Input */}
                <div className="space-y-1.5">
                  <label className="text-[10px] font-bold text-slate-300 block uppercase tracking-wider font-mono">
                    Identificador de Endereço (Nome Curto)
                  </label>
                  <input
                    type="text"
                    value={tempAddress}
                    onChange={(e) => setTempAddress(e.target.value)}
                    placeholder="Ex: Meu Prédio, Casa de Praia..."
                    className="w-full bg-slate-950 border border-slate-850 focus:border-indigo-500 rounded-lg px-3 py-1.5 text-xs text-white placeholder-slate-600 focus:outline-none transition"
                  />
                </div>

                {/* Toggle Enabled */}
                <div className="flex items-center justify-between p-3 bg-slate-950/60 rounded-xl border border-slate-850/50">
                  <div>
                    <span className="text-[11px] font-bold text-slate-200 block">
                      Ativar esta Cerca Geográfica
                    </span>
                    <span className="text-[9px] text-slate-500 block">
                      Disparar lembretes automáticos ao cruzar este limite.
                    </span>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={tempEnabled}
                      onChange={(e) => setTempEnabled(e.target.checked)}
                      className="sr-only peer"
                    />
                    <div className="w-9 h-5 bg-slate-800 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-slate-300 after:border-slate-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-indigo-600 peer-checked:after:bg-white peer-checked:after:border-white"></div>
                  </label>
                </div>
              </div>

              {/* Footer */}
              <div className="p-4 border-t border-slate-800 bg-slate-900 flex justify-end gap-2.5">
                <button
                  type="button"
                  onClick={() => setShowGeofenceSetupModal(false)}
                  className="px-3.5 py-2 text-xs font-bold text-slate-300 hover:text-white bg-slate-800 hover:bg-slate-750 rounded-lg transition cursor-pointer"
                >
                  Cancelar
                </button>
                <button
                  type="button"
                  onClick={handleSaveGeofence}
                  className="px-4 py-2 text-xs font-bold text-white bg-indigo-650 hover:bg-indigo-600 rounded-lg transition shadow-md shadow-indigo-950/20 cursor-pointer"
                >
                  Salvar Alterações
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Advanced Geofence Settings & Geocoding Modal */}
      <AnimatePresence>
        {showAdvancedGeofenceModal && (
          <div className="fixed inset-0 z-[9999] flex items-center justify-center p-4">
            {/* Backdrop */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setShowAdvancedGeofenceModal(false)}
              className="absolute inset-0 bg-slate-950/80 backdrop-blur-sm"
            />

            {/* Modal Body */}
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 15 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 15 }}
              className="relative w-full max-w-lg bg-slate-900 border border-slate-800 rounded-2xl shadow-2xl shadow-indigo-950/40 overflow-hidden flex flex-col max-h-[90vh]"
            >
              {/* Header */}
              <div className="p-4 border-b border-slate-800 flex items-center justify-between">
                <div>
                  <h3 className="text-sm font-black text-white flex items-center gap-2">
                    <Sliders className="w-4 h-4 text-indigo-400" />
                    Configuração Avançada de Geofencing
                  </h3>
                  <p className="text-[10px] text-slate-400 mt-0.5">
                    Ajuste os tempos mínimos de permanência e faça
                    geocodificação direta de endereços.
                  </p>
                </div>
                <button
                  type="button"
                  onClick={() => setShowAdvancedGeofenceModal(false)}
                  className="p-1.5 hover:bg-slate-850 rounded-lg text-slate-400 hover:text-white transition"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>

              {/* Body */}
              <div className="p-4 space-y-4 overflow-y-auto flex-1 text-xs">
                {/* 1. minDwellTime Editing */}
                <div className="space-y-3 bg-slate-950/40 p-3 rounded-xl border border-slate-850/60 font-sans">
                  <span className="text-[10px] font-bold text-slate-300 block uppercase tracking-wider font-mono">
                    ⏱️ Tempo Mínimo de Permanência (Dwell Time)
                  </span>

                  <div className="grid grid-cols-2 gap-3">
                    <div className="space-y-1.5 font-sans">
                      <label className="text-[10px] text-slate-400 block font-semibold">
                        🏠 Casa (Minutos)
                      </label>
                      <input
                        type="number"
                        min="0"
                        max="120"
                        value={advDwellTimeHome}
                        onChange={(e) =>
                          setAdvDwellTimeHome(
                            Math.max(0, parseInt(e.target.value) || 0),
                          )
                        }
                        className="w-full bg-slate-950 border border-slate-850 focus:border-indigo-500 rounded-lg px-3 py-1.5 text-xs text-white focus:outline-none transition font-mono"
                      />
                    </div>

                    <div className="space-y-1.5 font-sans">
                      <label className="text-[10px] text-slate-400 block font-semibold">
                        💼 Trabalho (Minutos)
                      </label>
                      <input
                        type="number"
                        min="0"
                        max="120"
                        value={advDwellTimeWork}
                        onChange={(e) =>
                          setAdvDwellTimeWork(
                            Math.max(0, parseInt(e.target.value) || 0),
                          )
                        }
                        className="w-full bg-slate-950 border border-slate-850 focus:border-indigo-500 rounded-lg px-3 py-1.5 text-xs text-white focus:outline-none transition font-mono"
                      />
                    </div>
                  </div>
                  <p className="text-[9.5px] text-slate-500 leading-normal">
                    * Define quantos minutos você precisa ficar dentro da área
                    delimitada para disparar alertas de entrada.
                  </p>
                </div>

                {/* Silenciamento Inteligente */}
                <div className="space-y-3 bg-slate-950/40 p-3 rounded-xl border border-slate-850/60 font-sans">
                  <div className="flex items-center justify-between">
                    <span className="text-[10px] font-bold text-slate-300 block uppercase tracking-wider font-mono flex items-center gap-1.5">
                      <BellOff className="w-3.5 h-3.5 text-indigo-400" />{" "}
                      Silenciamento Inteligente
                    </span>
                    {geofenceMutedUntil && Date.now() < geofenceMutedUntil ? (
                      <span className="inline-flex items-center gap-1 text-[9px] font-mono font-extrabold text-amber-400 bg-amber-500/10 border border-amber-500/20 px-2 py-0.5 rounded-full animate-pulse">
                        PAUSADO
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1 text-[9px] font-mono font-semibold text-slate-400 bg-slate-950 border border-slate-850 px-2 py-0.5 rounded-full">
                        ATIVO
                      </span>
                    )}
                  </div>
                  <p className="text-[9.5px] text-slate-500 leading-normal">
                    Pausa temporariamente notificações de geofencing por 1, 2 ou
                    4 horas sem alterar a configuração global de notificações.
                  </p>
                  <div className="flex flex-wrap items-center gap-2 pt-1">
                    <button
                      type="button"
                      onClick={() => muteGeofence(1)}
                      className={`px-2.5 py-1.5 text-[9.5px] font-bold rounded-md border transition cursor-pointer ${
                        geofenceMutedUntil &&
                        Math.abs(
                          geofenceMutedUntil - Date.now() - 1 * 60 * 60 * 1000,
                        ) < 60000
                          ? "bg-indigo-600 border-indigo-500 text-white shadow-md shadow-indigo-950/20"
                          : "bg-slate-950 border-slate-850 text-slate-300 hover:text-white hover:bg-slate-900"
                      }`}
                    >
                      1 Hora
                    </button>
                    <button
                      type="button"
                      onClick={() => muteGeofence(2)}
                      className={`px-2.5 py-1.5 text-[9.5px] font-bold rounded-md border transition cursor-pointer ${
                        geofenceMutedUntil &&
                        Math.abs(
                          geofenceMutedUntil - Date.now() - 2 * 60 * 60 * 1000,
                        ) < 60000
                          ? "bg-indigo-600 border-indigo-500 text-white shadow-md shadow-indigo-950/20"
                          : "bg-slate-950 border-slate-850 text-slate-300 hover:text-white hover:bg-slate-900"
                      }`}
                    >
                      2 Horas
                    </button>
                    <button
                      type="button"
                      onClick={() => muteGeofence(4)}
                      className={`px-2.5 py-1.5 text-[9.5px] font-bold rounded-md border transition cursor-pointer ${
                        geofenceMutedUntil &&
                        Math.abs(
                          geofenceMutedUntil - Date.now() - 4 * 60 * 60 * 1000,
                        ) < 60000
                          ? "bg-indigo-600 border-indigo-500 text-white shadow-md shadow-indigo-950/20"
                          : "bg-slate-950 border-slate-850 text-slate-300 hover:text-white hover:bg-slate-900"
                      }`}
                    >
                      4 Horas
                    </button>
                    {geofenceMutedUntil && Date.now() < geofenceMutedUntil && (
                      <button
                        type="button"
                        onClick={unmuteGeofence}
                        className="px-2.5 py-1.5 text-[9.5px] font-bold rounded-md border border-red-500/30 bg-red-500/10 hover:bg-red-500/20 text-red-400 transition cursor-pointer ml-auto"
                      >
                        Reativar
                      </button>
                    )}
                  </div>
                  {muteTimeRemaining && (
                    <div className="text-[9.5px] font-mono text-amber-400 flex items-center gap-1 pt-1">
                      <span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping" />
                      Silenciado: {muteTimeRemaining}
                    </div>
                  )}
                </div>

                {/* 2. Geocoding Search & Type selection */}
                <div className="space-y-3 bg-slate-950/40 p-3 rounded-xl border border-slate-850/60 font-sans">
                  <span className="text-[10px] font-bold text-slate-300 block uppercase tracking-wider font-mono">
                    🔍 Geocodificação Direta de Coordenadas
                  </span>

                  <div className="space-y-1.5 font-sans">
                    <label className="text-[10px] text-slate-400 block font-semibold">
                      Destino para Atualização
                    </label>
                    <div className="flex gap-4">
                      <label className="flex items-center gap-1.5 text-slate-300 cursor-pointer">
                        <input
                          type="radio"
                          name="advGeocodeType"
                          checked={advGeocodeType === "home"}
                          onChange={() => setAdvGeocodeType("home")}
                          className="accent-indigo-500"
                        />
                        🏠 Casa
                      </label>
                      <label className="flex items-center gap-1.5 text-slate-300 cursor-pointer">
                        <input
                          type="radio"
                          name="advGeocodeType"
                          checked={advGeocodeType === "work"}
                          onChange={() => setAdvGeocodeType("work")}
                          className="accent-indigo-500"
                        />
                        💼 Trabalho
                      </label>
                    </div>
                  </div>

                  <div className="space-y-1.5 font-sans">
                    <label className="text-[10px] text-slate-400 block font-semibold">
                      Pesquisar Endereço / Cidade
                    </label>
                    <div className="flex gap-2">
                      <input
                        type="text"
                        value={advGeocodeQuery}
                        onChange={(e) => setAdvGeocodeQuery(e.target.value)}
                        placeholder="Ex: Av. Paulista 1000, São Paulo..."
                        onKeyDown={(e) => {
                          if (e.key === "Enter") {
                            e.preventDefault();
                            handleSearchAdvGeocode();
                          }
                        }}
                        className="flex-1 bg-slate-950 border border-slate-850 focus:border-indigo-500 rounded-lg px-3 py-1.5 text-xs text-white placeholder-slate-600 focus:outline-none transition"
                      />
                      <button
                        type="button"
                        disabled={isSearchingAdvGeocode}
                        onClick={handleSearchAdvGeocode}
                        className="px-3 py-1.5 bg-indigo-650 hover:bg-indigo-600 text-white font-bold text-xs rounded-lg transition disabled:opacity-50 cursor-pointer"
                      >
                        {isSearchingAdvGeocode ? "Buscando..." : "Buscar"}
                      </button>
                    </div>
                  </div>

                  {/* Results List */}
                  {advGeocodeResults.length > 0 && (
                    <div className="space-y-1.5 pt-1.5 max-h-[150px] overflow-y-auto divide-y divide-slate-900/60 border-t border-slate-900/80 font-sans">
                      <span className="text-[9px] font-bold text-slate-500 uppercase font-mono block">
                        Resultados Encontrados (Clique para selecionar):
                      </span>
                      {advGeocodeResults.map((res, idx) => (
                        <button
                          key={idx}
                          type="button"
                          onClick={() => handleSelectAdvGeocode(res)}
                          className="w-full text-left p-2 hover:bg-slate-950 rounded-lg transition text-[10.5px] text-slate-300 hover:text-white flex items-start gap-1.5 cursor-pointer leading-tight font-sans"
                        >
                          <MapPin className="w-3.5 h-3.5 text-indigo-400 shrink-0 mt-0.5" />
                          <div>
                            <span className="block font-semibold">
                              {res.display_name}
                            </span>
                            <span className="text-[9px] text-slate-500 font-mono">
                              Lat: {res.lat.toFixed(5)}, Lng:{" "}
                              {res.lon.toFixed(5)}
                            </span>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>

              {/* Footer */}
              <div className="p-4 border-t border-slate-800 bg-slate-900 flex justify-end gap-2.5">
                <button
                  type="button"
                  onClick={() => setShowAdvancedGeofenceModal(false)}
                  className="px-3.5 py-2 text-xs font-bold text-slate-300 hover:text-white bg-slate-800 hover:bg-slate-750 rounded-lg transition cursor-pointer"
                >
                  Cancelar
                </button>
                <button
                  type="button"
                  onClick={handleSaveAdvancedGeofence}
                  className="px-4 py-2 text-xs font-bold text-white bg-indigo-650 hover:bg-indigo-600 rounded-lg transition shadow-md shadow-indigo-950/20 cursor-pointer"
                >
                  Salvar Parâmetros
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
}

export default function App() {
  return (
    <LifeManagerProvider>
      <MainApp />
    </LifeManagerProvider>
  );
}
