import React, { createContext, useContext, useState, useEffect } from "react";
import {
  collection,
  query,
  where,
  onSnapshot,
  addDoc,
  updateDoc,
  deleteDoc,
  doc,
  setDoc,
  getDoc,
  getDocs,
} from "firebase/firestore";
import { db, auth, googleProvider } from "../firebase";
import {
  onAuthStateChanged,
  signInWithPopup,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  GoogleAuthProvider,
  OAuthProvider,
  linkWithPopup,
} from "firebase/auth";
import {
  Transaction,
  Appointment,
  Goal,
  Habit,
  Medication,
  WaterLog,
  FamilyMember,
  NotificationSettings,
  DashboardSettings,
  UserConfig,
  InventoryItem,
  SecondBrainNote,
  User,
} from "../types";
import {
  saveLocalBackup,
  getLocalBackup,
  saveReadAheadCache,
  getReadAheadCache,
  validateUserConfig,
  validateTransactions,
  validateBackupData,
} from "../utils/indexedDB";

export enum OperationType {
  CREATE = "create",
  UPDATE = "update",
  DELETE = "delete",
  LIST = "list",
  GET = "get",
  WRITE = "write",
}

export interface FirestoreErrorInfo {
  error: string;
  operationType: OperationType;
  path: string | null;
  authInfo: {
    userId?: string | null;
    email?: string | null;
    emailVerified?: boolean | null;
    isAnonymous?: boolean | null;
    tenantId?: string | null;
    providerInfo?: {
      providerId?: string | null;
      email?: string | null;
    }[];
  };
}

export function handleFirestoreError(
  error: unknown,
  operationType: OperationType,
  path: string | null,
  customUserId?: string | null,
) {
  const errInfo: FirestoreErrorInfo = {
    error: error instanceof Error ? error.message : String(error),
    authInfo: {
      userId: auth.currentUser?.uid || customUserId || null,
      email: auth.currentUser?.email || null,
      emailVerified: auth.currentUser?.emailVerified || null,
      isAnonymous: auth.currentUser?.isAnonymous || null,
      tenantId: auth.currentUser?.tenantId || null,
      providerInfo:
        auth.currentUser?.providerData?.map((provider) => ({
          providerId: provider.providerId,
          email: provider.email,
        })) || [],
    },
    operationType,
    path,
  };
  console.error("Firestore Error: ", JSON.stringify(errInfo));
  throw new Error(JSON.stringify(errInfo));
}

interface LifeManagerContextType {
  userId: string;
  changeUserId: (newId: string) => void;
  transactions: Transaction[];
  appointments: Appointment[];
  goals: Goal[];
  habits: Habit[];
  waterLogs: WaterLog[];
  medications: Medication[];
  inventoryItems: InventoryItem[];
  secondBrainNotes: SecondBrainNote[];
  loading: boolean;
  isSaving: boolean;
  lastSaved: Date | null;
  autoSaveStatus: "idle" | "saving" | "saved" | "idle_user";
  lastAutoSavedAt: Date | null;

  // Secure Authentication & Custom Profiles
  user: User | null;
  userConfig: UserConfig | null;
  activeMember: FamilyMember | null;
  isAuthLoading: boolean;
  loginWithGoogle: () => Promise<void>;
  loginWithEmail: (email: string, password: string) => Promise<void>;
  registerWithEmail: (email: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  setActiveMember: (member: FamilyMember | null) => void;
  addFamilyMember: (
    name: string,
    role: FamilyMember["role"] | string,
    pin?: string,
    email?: string,
  ) => Promise<void>;
  deleteFamilyMember: (id: string) => Promise<void>;
  updateFamilyMemberGPS: (
    memberId: string,
    updates: Partial<FamilyMember>,
  ) => Promise<void>;
  updateNotificationSettings: (
    settings: Partial<NotificationSettings>,
  ) => Promise<void>;
  updateDashboardSettings: (
    settings: Partial<DashboardSettings>,
  ) => Promise<void>;
  updateUserPhysicalData: (data: {
    weight?: number;
    height?: number;
    waterGoalType?: "auto" | "manual";
    manualWaterGoal?: number;
  }) => Promise<void>;

  // Transactions DB actions
  addTransaction: (tx: Omit<Transaction, "id" | "userId">) => Promise<void>;
  deleteTransaction: (id: string) => Promise<void>;
  updateTransaction: (
    id: string,
    updates: Partial<Transaction>,
  ) => Promise<void>;

  // Inventory DB actions
  addInventoryItem: (
    item: Omit<InventoryItem, "id" | "userId" | "lastUpdated">,
  ) => Promise<void>;
  updateInventoryItem: (
    id: string,
    updates: Partial<InventoryItem>,
  ) => Promise<void>;
  deleteInventoryItem: (id: string) => Promise<void>;

  // Appointments DB actions
  addAppointment: (apt: Omit<Appointment, "id" | "userId">) => Promise<void>;
  deleteAppointment: (id: string) => Promise<void>;
  toggleAppointmentCompleted: (
    id: string,
    currentStatus: boolean,
  ) => Promise<void>;

  // Goals DB actions
  addGoal: (goal: Omit<Goal, "id" | "userId">) => Promise<void>;
  deleteGoal: (id: string) => Promise<void>;
  updateGoalProgress: (id: string, newValue: number) => Promise<void>;
  updateGoalFields: (id: string, updates: Partial<Goal>) => Promise<void>;

  // Habits DB actions
  addHabit: (name: string, assignedTo?: string) => Promise<void>;
  deleteHabit: (id: string) => Promise<void>;
  toggleHabitForDate: (habitId: string, dateStr: string) => Promise<void>;

  // Medication DB actions
  addMedication: (
    name: string,
    dosage: string,
    scheduledTime: string,
    recheckIntervalMinutes: number,
    assignedTo?: string,
  ) => Promise<void>;
  deleteMedication: (id: string) => Promise<void>;
  toggleMedicationTaken: (id: string, dateStr: string) => Promise<void>;

  // Water logs actions
  addWaterLog: (
    amountMl: number,
    memberId?: string,
    dateStr?: string,
  ) => Promise<void>;
  deleteWaterLog: (id: string) => Promise<void>;

  // Second Brain / Obsidian Vault actions
  addSecondBrainNote: (
    note: Omit<SecondBrainNote, "id" | "userId" | "createdAt" | "updatedAt">,
  ) => Promise<void>;
  updateSecondBrainNote: (
    id: string,
    updates: Partial<SecondBrainNote>,
  ) => Promise<void>;
  deleteSecondBrainNote: (id: string) => Promise<void>;

  // Google Calendar Integration
  googleAccessToken: string | null;
  googleEvents: any[];
  googleCalendars: any[];
  selectedGoogleCalendarIds: string[];
  googleCalendarAlertIds: string[];
  defaultScheduleGoogleCalendarId: string;
  updateGoogleCalendarSelection: (
    selectedIds: string[],
    defaultScheduleId: string,
  ) => Promise<void>;
  updateGoogleCalendarAlertSelection: (alertIds: string[]) => Promise<void>;
  hiddenGoogleEventIds: string[];
  isGoogleAuthLoading: boolean;
  isGoogleAuthExpired: boolean;
  connectGoogleCalendar: () => Promise<string | null>;
  fetchGoogleEvents: () => Promise<void>;
  addGoogleEvent: (
    event: { title: string; date: string; time: string; description: string },
    calendarId?: string,
  ) => Promise<any>;
  deleteGoogleEvent: (eventId: string, calendarId?: string) => Promise<void>;
  hideGoogleEvent: (eventId: string) => Promise<void>;
  disconnectGoogleCalendar: () => Promise<void>;
  createSharedGoogleCalendar: () => Promise<string>;
  shareGoogleCalendarWithEmail: (email: string) => Promise<boolean>;

  // Outlook Calendar Integration
  outlookAccessToken: string | null;
  outlookEvents: any[];
  outlookCalendars: any[];
  selectedOutlookCalendarIds: string[];
  defaultScheduleOutlookCalendarId: string;
  updateOutlookCalendarSelection: (
    selectedIds: string[],
    defaultScheduleId: string,
  ) => Promise<void>;
  hiddenOutlookEventIds: string[];
  isOutlookAuthLoading: boolean;
  connectOutlookCalendar: () => Promise<string | null>;
  fetchOutlookEvents: () => Promise<void>;
  addOutlookEvent: (
    event: { title: string; date: string; time: string; description: string },
    calendarId?: string,
  ) => Promise<any>;
  deleteOutlookEvent: (eventId: string, calendarId?: string) => Promise<void>;
  hideOutlookEvent: (eventId: string) => Promise<void>;
  disconnectOutlookCalendar: () => Promise<void>;
  manualSync: () => Promise<void>;
  clearAllData: () => Promise<void>;
  failedSyncAttempts: number;
  restoreFromBackup: () => Promise<boolean>;
}

const LifeManagerContext = createContext<LifeManagerContextType | undefined>(
  undefined,
);

const generateSyncId = (): string => {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let result = "";
  for (let i = 0; i < 6; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return `GL-${result}`;
};

export const LifeManagerProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  // Active sync or user database identifier (Must be declared first so subsequent state initializers can reference it)
  const [userId, setUserId] = useState<string>(() => {
    const saved = localStorage.getItem("life_manager_user_id");
    if (saved) return saved;
    const newId = generateSyncId();
    localStorage.setItem("life_manager_user_id", newId);
    return newId;
  });

  // Authentication & Configuration States
  const [user, setUser] = useState<User | null>(null);
  const [userConfig, setUserConfig] = useState<UserConfig | null>(() => {
    try {
      const saved = localStorage.getItem(`life_manager_config_cache_${userId}`);
      if (saved) {
        const parsed = JSON.parse(saved);
        if (validateUserConfig(parsed)) {
          console.log(
            "⚡ [Fast-Path Cache]: Configurações carregadas de forma síncrona do cache local!",
          );
          return parsed;
        }
      }
    } catch (e) {
      console.warn("Falha ao analisar cache síncrono de configurações:", e);
    }
    return null;
  });
  const [activeMember, setActiveMemberState] = useState<FamilyMember | null>(
    null,
  );
  const [isAuthLoading, setIsAuthLoading] = useState<boolean>(true);

  const [transactions, setTransactions] = useState<Transaction[]>(() => {
    try {
      const saved = localStorage.getItem(
        `life_manager_transactions_cache_${userId}`,
      );
      if (saved) {
        const parsed = JSON.parse(saved);
        if (validateTransactions(parsed)) {
          console.log(
            "⚡ [Fast-Path Cache]: Transações carregadas de forma síncrona do cache local!",
          );
          return parsed;
        }
      }
    } catch (e) {
      console.warn("Falha ao analisar cache síncrono de transações:", e);
    }
    return [];
  });
  const [appointments, setAppointments] = useState<Appointment[]>([]);
  const [goals, setGoals] = useState<Goal[]>([]);
  const [habits, setHabits] = useState<Habit[]>([]);
  const [waterLogs, setWaterLogs] = useState<WaterLog[]>([]);
  const [medications, setMedications] = useState<Medication[]>([]);
  const [inventoryItems, setInventoryItems] = useState<InventoryItem[]>([]);
  const [secondBrainNotes, setSecondBrainNotes] = useState<SecondBrainNote[]>(
    [],
  );
  const [loading, setLoading] = useState<boolean>(true);
  const [isSaving, setIsSaving] = useState<boolean>(false);
  const [lastSaved, setLastSaved] = useState<Date | null>(() => new Date());
  const [autoSaveStatus, setAutoSaveStatus] = useState<
    "idle" | "saving" | "saved" | "idle_user"
  >("idle");
  const [lastAutoSavedAt, setLastAutoSavedAt] = useState<Date | null>(null);
  const [failedSyncAttempts, setFailedSyncAttempts] = useState<number>(0);

  const performWrite = async <T,>(operation: () => Promise<T>): Promise<T> => {
    setIsSaving(true);
    try {
      const result = await operation();
      setLastSaved(new Date());
      setFailedSyncAttempts(0);
      return result;
    } catch (err) {
      setFailedSyncAttempts((prev) => prev + 1);
      throw err;
    } finally {
      // Keep state true for at least 800ms so user can see save animation
      setTimeout(() => {
        setIsSaving(false);
      }, 800);
    }
  };

  // Google Calendar Integration states
  const [googleAccessToken, setGoogleAccessToken] = useState<string | null>(
    null,
  );
  const [googleEvents, setGoogleEvents] = useState<any[]>([]);
  const [googleCalendars, setGoogleCalendars] = useState<any[]>([]);
  const [selectedGoogleCalendarIds, setSelectedGoogleCalendarIds] = useState<
    string[]
  >([]);
  const [googleCalendarAlertIds, setGoogleCalendarAlertIds] = useState<
    string[]
  >([]);
  const [defaultScheduleGoogleCalendarId, setDefaultScheduleGoogleCalendarId] =
    useState<string>("primary");
  const [hiddenGoogleEventIds, setHiddenGoogleEventIds] = useState<string[]>(
    [],
  );
  const [isGoogleAuthLoading, setIsGoogleAuthLoading] =
    useState<boolean>(false);
  const [isGoogleAuthExpired, setIsGoogleAuthExpired] =
    useState<boolean>(false);

  // Outlook Calendar Integration states
  const [outlookAccessToken, setOutlookAccessToken] = useState<string | null>(
    null,
  );
  const [outlookEvents, setOutlookEvents] = useState<any[]>([]);
  const [outlookCalendars, setOutlookCalendars] = useState<any[]>([]);
  const [selectedOutlookCalendarIds, setSelectedOutlookCalendarIds] = useState<
    string[]
  >([]);
  const [
    defaultScheduleOutlookCalendarId,
    setDefaultScheduleOutlookCalendarId,
  ] = useState<string>("primary");
  const [hiddenOutlookEventIds, setHiddenOutlookEventIds] = useState<string[]>(
    [],
  );
  const [isOutlookAuthLoading, setIsOutlookAuthLoading] =
    useState<boolean>(false);

  // Set selected family profile locally
  const setActiveMember = (member: FamilyMember | null) => {
    setActiveMemberState(member);
    if (member) {
      localStorage.setItem(`life_member_active_${userId}`, member.id);
    } else {
      localStorage.removeItem(`life_member_active_${userId}`);
    }
  };

  const changeUserId = (newId: string) => {
    const cleanId = newId.trim().toUpperCase();
    if (cleanId) {
      setUserId(cleanId);
      localStorage.setItem("life_manager_user_id", cleanId);
    }
  };

  // 1. Listen for Authentication Changes securely via Firebase Auth
  useEffect(() => {
    setIsAuthLoading(true);

    // Helper to map Firebase user to our compatible User interface
    const mapFirebaseUser = (fbUser: any): User | null => {
      if (!fbUser) return null;
      return {
        uid: fbUser.uid,
        id: fbUser.uid,
        email: fbUser.email || null,
        displayName:
          fbUser.displayName || fbUser.email?.split("@")[0] || "Usuário",
        photoURL: fbUser.photoURL || null,
        providerData:
          fbUser.providerData?.map((p: any) => ({
            providerId: p.providerId,
          })) || [],
      };
    };

    const unsubscribe = onAuthStateChanged(
      auth,
      (fbUser) => {
        setIsAuthLoading(true);
        if (fbUser) {
          const mappedUser = mapFirebaseUser(fbUser);
          if (mappedUser) {
            setUser(mappedUser);
            setUserId(mappedUser.uid);
            localStorage.setItem("life_manager_user_id", mappedUser.uid);
            localStorage.removeItem("blocked_login_email");
          }
        } else {
          setUser(null);
          setUserConfig(null);
          setActiveMemberState(null);
          setGoogleAccessToken(null);
          setGoogleEvents([]);
          setOutlookAccessToken(null);
          setOutlookEvents([]);

          // Preserve existing anonymous user workspace ID if present, otherwise generate a fresh one
          const existingId = localStorage.getItem("life_manager_user_id");
          if (existingId) {
            setUserId(existingId);
          } else {
            const fallback = generateSyncId();
            setUserId(fallback);
            localStorage.setItem("life_manager_user_id", fallback);
          }
        }
        setIsAuthLoading(false);
      },
      (err) => {
        console.error("Error in Firebase auth state observer:", err);
        setIsAuthLoading(false);
      },
    );

    return () => {
      unsubscribe();
    };
  }, []);

  // 2. Load and Sync secure configs document '/users/{userId}' once authenticated
  useEffect(() => {
    if (!userId) return;

    if (!user) {
      // If we are anonymous, load config from localStorage or set default
      const saved = localStorage.getItem(`life_manager_config_cache_${userId}`);
      if (saved) {
        try {
          const parsed = JSON.parse(saved);
          if (validateUserConfig(parsed)) {
            setUserConfig(parsed);
            return;
          }
        } catch (e) {
          console.warn("Falha ao carregar configurações locais", e);
        }
      }

      const initialMembers: FamilyMember[] = [
        {
          id: "MEMBER-1",
          name: "Membro Principal",
          role: "lider",
          avatarColor: "bg-blue-600",
          pin: "",
        },
      ];
      const defaultConfig: UserConfig = {
        userId: userId,
        members: initialMembers,
        notificationSettings: {
          upcomingAppointments: true,
          appointmentAdvWarnMinutes: 30,
          billReminders: true,
          billAdvWarnDays: 3,
          goalReminders: true,
          pushAlertsEnabled: true,
          showOnScreenToasts: false,
          waterReminders: false,
          waterReminderIntervalMinutes: 120,
          quietHours: { enabled: false, start: "22:00", end: "08:00" },
          geolocationAlertsEnabled: false,
          homeLocation: {
            enabled: false,
            address: "",
            notifyGoals: true,
            notifyHabits: true,
          },
          workLocation: {
            enabled: false,
            address: "",
            notifyGoals: true,
            notifyHabits: true,
          },
          habitReminders: { enabled: false, reminderTimes: ["08:00", "20:00"] },
        },
        dashboardSettings: {
          layout: "grid",
          visibleWidgets: [
            "balance",
            "income",
            "expense",
            "inventory",
            "chart",
            "habits",
            "appointments",
            "goals",
          ],
          widgetOrder: [
            "balance",
            "income",
            "expense",
            "inventory",
            "chart",
            "habits",
            "appointments",
            "goals",
          ],
        },
        weight: 70,
        height: 175,
        waterGoalType: "auto",
        manualWaterGoal: 2000,
      };
      setUserConfig(defaultConfig);
      localStorage.setItem(
        `life_manager_config_cache_${userId}`,
        JSON.stringify(defaultConfig),
      );
      return;
    }

    // Since we are using Supabase config sync via performSyncCheck, we do not need the active Firestore subscription
    const saved = localStorage.getItem(`life_manager_config_cache_${userId}`);
    if (saved) {
      try {
        const parsed = JSON.parse(saved);
        if (validateUserConfig(parsed)) {
          setUserConfig(parsed);

          // Select previously chosen active member profile or auto-select first member
          const savedMemberId = localStorage.getItem(
            `life_member_active_${userId}`,
          );
          const savedMember = parsed.members.find(
            (m: any) => m.id === savedMemberId,
          );
          if (savedMember) {
            setActiveMemberState(savedMember);
          } else if (parsed.members.length > 0) {
            setActiveMemberState(parsed.members[0]);
            localStorage.setItem(
              `life_member_active_${userId}`,
              parsed.members[0].id,
            );
          }
        }
      } catch (e) {
        console.warn("Falha ao carregar configurações locais", e);
      }
    }
  }, [userId, user]);

  // login/logout trigger actions via Firebase Auth
  const loginWithGoogle = async () => {
    try {
      await signInWithPopup(auth, googleProvider);
    } catch (e) {
      console.error("Google authentication failed", e);
      throw e;
    }
  };

  const loginWithEmail = async (email: string, password: string) => {
    try {
      await signInWithEmailAndPassword(auth, email, password);
    } catch (e) {
      console.error("Email login failed", e);
      throw e;
    }
  };

  const registerWithEmail = async (email: string, password: string) => {
    try {
      await createUserWithEmailAndPassword(auth, email, password);
    } catch (e) {
      console.error("Email registration failed", e);
      throw e;
    }
  };

  const logout = async () => {
    try {
      localStorage.removeItem("life_manager_user_id");
      await auth.signOut();
    } catch (e) {
      console.error("Logout failed", e);
    }
  };

  // Google shared calendar helper
  const shareGoogleCalendarWithEmailInternal = async (
    calendarId: string,
    email: string,
  ): Promise<boolean> => {
    if (!googleAccessToken) {
      console.warn("Cannot share calendar: no google access token active.");
      return false;
    }
    const cleanEmail = email.toLowerCase().trim();
    try {
      console.log(`Sharing calendar ${calendarId} with ${cleanEmail}...`);
      const response = await fetch(
        `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/acl`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${googleAccessToken}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            role: "writer",
            scope: {
              type: "user",
              value: cleanEmail,
            },
          }),
        },
      );

      if (response.ok) {
        console.log(
          `Successfully shared calendar ${calendarId} with ${cleanEmail}`,
        );
        return true;
      } else {
        const errData = await response.json().catch(() => ({}));
        console.warn(`Failed to share calendar:`, errData);
        return false;
      }
    } catch (err) {
      console.error(`Error in shareGoogleCalendarWithEmailInternal:`, err);
      return false;
    }
  };

  const shareGoogleCalendarWithEmail = async (
    email: string,
  ): Promise<boolean> => {
    if (!googleAccessToken || !userConfig?.sharedGoogleCalendarId) return false;
    return shareGoogleCalendarWithEmailInternal(
      userConfig.sharedGoogleCalendarId,
      email,
    );
  };

  // Profile configuration updates
  const addFamilyMember = async (
    name: string,
    role: any,
    pin?: string,
    email?: string,
  ) => {
    if (!userConfig) return;
    const newMember: FamilyMember = {
      id: `MEMBER-${Date.now()}`,
      name,
      role,
      avatarColor: [
        "bg-blue-500",
        "bg-emerald-500",
        "bg-violet-500",
        "bg-rose-500",
        "bg-amber-500",
        "bg-cyan-500",
        "bg-pink-500",
      ][Math.floor(Math.random() * 7)],
      pin: pin || "",
      email: email || "",
    };
    const updatedMembers = [...userConfig.members, newMember];
    setUserConfig((prev) =>
      prev ? { ...prev, members: updatedMembers } : null,
    );
    await performWrite(async () => {
      await setDoc(
        doc(db, "users", userId),
        { members: updatedMembers },
        { merge: true },
      );

      if (email && email.trim()) {
        const cleanEmail = email.toLowerCase().trim();
        await setDoc(doc(db, "allowed_logins", cleanEmail), {
          email: cleanEmail,
          name,
          role,
          invitedAt: new Date().toISOString(),
          workspaceId: userId,
        });

        // Auto-invite if we have a shared/family collective calendar
        if (userConfig.sharedGoogleCalendarId && googleAccessToken) {
          try {
            await shareGoogleCalendarWithEmailInternal(
              userConfig.sharedGoogleCalendarId,
              cleanEmail,
            );
          } catch (calErr) {
            console.error(
              "Non-blocking auto-invite calendar exception:",
              calErr,
            );
          }
        }
      }
    });
  };

  const deleteFamilyMember = async (memberId: string) => {
    if (!userConfig) return;
    const updatedMembers = userConfig.members.filter((m) => m.id !== memberId);
    setUserConfig((prev) =>
      prev ? { ...prev, members: updatedMembers } : null,
    );
    await performWrite(() =>
      setDoc(
        doc(db, "users", userId),
        { members: updatedMembers },
        { merge: true },
      ),
    );
  };

  const updateFamilyMemberGPS = async (
    memberId: string,
    updates: Partial<FamilyMember>,
  ) => {
    if (!userConfig) return;
    const updatedMembers = userConfig.members.map((m) => {
      if (m.id === memberId) {
        return { ...m, ...updates };
      }
      return m;
    });
    setUserConfig((prev) =>
      prev ? { ...prev, members: updatedMembers } : null,
    );
    await performWrite(() =>
      setDoc(
        doc(db, "users", userId),
        { members: updatedMembers },
        { merge: true },
      ),
    );
  };

  const updateNotificationSettings = async (
    settings: Partial<NotificationSettings>,
  ) => {
    if (!userConfig) return;
    const updated = { ...userConfig.notificationSettings, ...settings };
    setUserConfig((prev) =>
      prev ? { ...prev, notificationSettings: updated } : null,
    );
    await performWrite(() =>
      setDoc(
        doc(db, "users", userId),
        { notificationSettings: updated },
        { merge: true },
      ),
    );
  };

  const updateDashboardSettings = async (
    settings: Partial<DashboardSettings>,
  ) => {
    if (!userConfig) return;
    const updated = { ...userConfig.dashboardSettings, ...settings };
    setUserConfig((prev) =>
      prev ? { ...prev, dashboardSettings: updated } : null,
    );
    await performWrite(() =>
      setDoc(
        doc(db, "users", userId),
        { dashboardSettings: updated },
        { merge: true },
      ),
    );
  };

  const updateUserPhysicalData = async (data: {
    weight?: number;
    height?: number;
    waterGoalType?: "auto" | "manual";
    manualWaterGoal?: number;
  }) => {
    if (!userConfig) return;
    setUserConfig((prev) => (prev ? { ...prev, ...data } : null));
    await performWrite(() =>
      setDoc(doc(db, "users", userId), data, { merge: true }),
    );
  };

  // Setup database listener and handles auto seeding for new accounts
  useEffect(() => {
    if (!userId) return;

    setLoading(true);

    let unsubBackup: (() => void) | null = null;
    let isMounted = true;

    const loadInitialCache = async () => {
      try {
        const [cache, backup] = await Promise.all([
          getReadAheadCache(userId),
          getLocalBackup(userId),
        ]);

        let hasLoadedConfig = false;
        let hasLoadedTxs = false;

        // 1. Validate and load read-ahead cache (configuration and finances)
        if (cache) {
          const isConfigValid =
            cache.userConfig && validateUserConfig(cache.userConfig);
          const isTxsValid =
            cache.transactions && validateTransactions(cache.transactions);

          if (isConfigValid && isTxsValid) {
            setUserConfig(cache.userConfig);
            setTransactions(cache.transactions);
            hasLoadedConfig = true;
            hasLoadedTxs = true;
            console.log(
              "⚡ [Read-Ahead Cache Integrity]: Válido! Configurações e Finanças carregadas instantaneamente.",
            );
          } else {
            console.warn(
              "⚠️ [Read-Ahead Cache Integrity]: Dados inválidos ou corrompidos detectados.",
            );
          }
        }

        // 2. Validate and load full backup if valid
        if (backup && validateBackupData(backup)) {
          if (!hasLoadedConfig && backup.userConfig) {
            setUserConfig(backup.userConfig);
            hasLoadedConfig = true;
          }
          if (!hasLoadedTxs) {
            setTransactions(backup.transactions || []);
          }
          setAppointments(backup.appointments || []);
          setGoals(backup.goals || []);
          setHabits(backup.habits || []);
          setMedications(backup.medications || []);
          setWaterLogs(backup.waterLogs || []);
          setInventoryItems(backup.inventoryItems || []);
          setSecondBrainNotes(backup.secondBrainNotes || []);

          if (isMounted) setLoading(false);
          console.log(
            "⚡ [Offline-First Integrity]: Todos os dados locais validados e carregados com sucesso!",
          );
        } else if (hasLoadedConfig) {
          if (isMounted) setLoading(false);
        } else {
          console.warn(
            "⚠️ [Offline-First Integrity]: Nenhum backup local válido encontrado.",
          );
        }

        if (!isMounted) return;

        // Firebase Native Sync: Listen to cloud_backups for cross-device real-time sync
        if (userId) {
          unsubBackup = onSnapshot(
            doc(db, "user_backups", userId),
            async (docSnap) => {
              if (docSnap.exists()) {
                const cloudData = docSnap.data();
                const cloudPayload = cloudData.payload
                  ? JSON.parse(cloudData.payload)
                  : null;
                if (cloudPayload) {
                  const localLastUpdatedStr = localStorage.getItem(`user_config_last_updated_${userId}`);
                  const localDate = localLastUpdatedStr ? new Date(localLastUpdatedStr).getTime() : 0;
                  const cloudDate = cloudPayload.lastUpdated
                    ? new Date(cloudPayload.lastUpdated).getTime()
                    : 0;

                  const lastPushed = localStorage.getItem(`firebase_last_pushed_sync_${userId}`);
                  
                  // Apply if cloud is newer than local mutations AND this is not an echo of our own sync
                  if (cloudDate > localDate && cloudPayload.lastUpdated !== lastPushed) {
                    console.log(
                      "☁️ [Firebase Sync]: Atualização mais recente encontrada na nuvem. Aplicando...",
                    );
                    localStorage.setItem(`__config_sync_in_progress_${userId}`, "true");
                    localStorage.setItem(`user_config_last_updated_${userId}`, cloudPayload.lastUpdated);
                    
                    if (cloudPayload.userConfig) {
                      setUserConfig(cloudPayload.userConfig);
                    }
                    setTransactions(cloudPayload.transactions || []);
                    setAppointments(cloudPayload.appointments || []);
                    setGoals(cloudPayload.goals || []);
                    setHabits(cloudPayload.habits || []);
                    setMedications(cloudPayload.medications || []);
                    setWaterLogs(cloudPayload.waterLogs || []);
                    setInventoryItems(cloudPayload.inventoryItems || []);
                    setSecondBrainNotes(cloudPayload.secondBrainNotes || []);
                    // Save to local cache as well
                    saveLocalBackup(userId, cloudPayload);
                  }
                }
              }
            },
            (err) => {
              console.warn(
                "⚠️ [Firebase Sync Warning]: Falha ao ouvir user_backups:",
                err.message,
              );
            },
          );
        }
      } catch (err) {
        console.error(
          "⚡ [Initialization Error]: Falha ao ler cache do IndexedDB:",
          err,
        );
      }
    };

    loadInitialCache();

    // Guard: Running in pure local-first / Supabase sync mode. Firestore direct collections bypassed.
    if (isMounted) setLoading(false);
    return () => {
      isMounted = false;
      if (unsubBackup) {
        unsubBackup();
      }
    };

    // Setup queries
    const qTransactions = query(
      collection(db, "transactions"),
      where("userId", "==", userId),
    );
    const qAppointments = query(
      collection(db, "appointments"),
      where("userId", "==", userId),
    );
    const qGoals = query(
      collection(db, "goals"),
      where("userId", "==", userId),
    );
    const qHabits = query(
      collection(db, "habits"),
      where("userId", "==", userId),
    );
    const qWater = query(
      collection(db, "water_logs"),
      where("userId", "==", userId),
    );
    const qInventory = query(
      collection(db, "inventory"),
      where("userId", "==", userId),
    );
    const qSecondBrain = query(
      collection(db, "second_brain_vault"),
      where("userId", "==", userId),
    );
    const qMedications = query(
      collection(db, "medications"),
      where("userId", "==", userId),
    );

    // Listeners state trackers to wait for initial snapshot
    let txLoaded = false;
    let aptLoaded = false;
    let goalLoaded = false;
    let habitLoaded = false;
    let waterLoaded = false;
    let inventoryLoaded = false;
    let secondBrainLoaded = false;
    let medicationLoaded = false;

    const checkAllLoaded = () => {
      if (
        txLoaded &&
        aptLoaded &&
        goalLoaded &&
        habitLoaded &&
        waterLoaded &&
        inventoryLoaded &&
        secondBrainLoaded &&
        medicationLoaded
      ) {
        setLoading(false);
      }
    };

    // Subscriptions
    const unsubTx = onSnapshot(
      qTransactions,
      (snapshot) => {
        const docs: Transaction[] = [];
        snapshot.forEach((docSnap) => {
          const data = docSnap.data();
          docs.push({
            id: docSnap.id,
            amount: data.amount,
            category: data.category,
            date: data.date,
            description: data.description,
            type: data.type,
            userId: data.userId,
            assignedTo: data.assignedTo || "all",
            dueDate: data.dueDate || "",
            status: data.status || "pago",
          });
        });
        // Sort transactions by date descending
        docs.sort((a, b) => b.date.localeCompare(a.date));
        setTransactions((prev) => {
          if (JSON.stringify(prev) !== JSON.stringify(docs)) {
            console.log(
              "⚡ [Firebase Finance Sync]: Transações alteradas no servidor. Atualizando estado...",
            );
            return docs;
          }
          return prev;
        });

        // Auto-seed removed to respect user request to start the app from 0 without mock data returning
        txLoaded = true;
        checkAllLoaded();
      },
      (err) => {
        console.error("Tx snapshot error", err);
        txLoaded = true;
        checkAllLoaded();
      },
    );

    const unsubApt = onSnapshot(
      qAppointments,
      (snapshot) => {
        const docs: Appointment[] = [];
        snapshot.forEach((docSnap) => {
          const data = docSnap.data();
          docs.push({
            id: docSnap.id,
            title: data.title,
            date: data.date,
            time: data.time,
            category: data.category,
            description: data.description,
            completed: data.completed,
            userId: data.userId,
            assignedTo: data.assignedTo || "all",
          });
        });
        // Sort appointments by date ascending then time
        docs.sort((a, b) => {
          const dateCompare = a.date.localeCompare(b.date);
          if (dateCompare !== 0) return dateCompare;
          return a.time.localeCompare(b.time);
        });
        setAppointments(docs);
        aptLoaded = true;
        checkAllLoaded();
      },
      (err) => {
        console.error("Apt snapshot error", err);
        aptLoaded = true;
        checkAllLoaded();
      },
    );

    const unsubGoal = onSnapshot(
      qGoals,
      (snapshot) => {
        const docs: Goal[] = [];
        snapshot.forEach((docSnap) => {
          const data = docSnap.data();
          docs.push({
            id: docSnap.id,
            title: data.title,
            targetValue: data.targetValue,
            currentValue: data.currentValue,
            category: data.category,
            deadline: data.deadline,
            userId: data.userId,
            assignedTo: data.assignedTo || "all",
            valueType: data.valueType || "number",
          });
        });
        setGoals(docs);
        goalLoaded = true;
        checkAllLoaded();
      },
      (err) => {
        console.error("Goals snapshot error", err);
        goalLoaded = true;
        checkAllLoaded();
      },
    );

    const unsubHabit = onSnapshot(
      qHabits,
      (snapshot) => {
        const docs: Habit[] = [];
        snapshot.forEach((docSnap) => {
          const data = docSnap.data();
          docs.push({
            id: docSnap.id,
            name: data.name,
            streak: data.streak || 0,
            history: data.history || {},
            userId: data.userId,
            createdAt: data.createdAt,
            assignedTo: data.assignedTo || "all",
          });
        });
        setHabits(docs);
        habitLoaded = true;
        checkAllLoaded();
      },
      (err) => {
        console.error("Habit snapshot error", err);
        habitLoaded = true;
        checkAllLoaded();
      },
    );

    const unsubWater = onSnapshot(
      qWater,
      (snapshot) => {
        const docs: WaterLog[] = [];
        snapshot.forEach((docSnap) => {
          const data = docSnap.data();
          docs.push({
            id: docSnap.id,
            userId: data.userId,
            memberId: data.memberId || "all",
            date: data.date,
            amountMl: data.amountMl,
            createdAt: data.createdAt,
          });
        });
        setWaterLogs(docs);
        waterLoaded = true;
        checkAllLoaded();
      },
      (err) => {
        console.error("Water snapshot error", err);
        waterLoaded = true;
        checkAllLoaded();
      },
    );

    const unsubInventory = onSnapshot(
      qInventory,
      (snapshot) => {
        const docs: InventoryItem[] = [];
        snapshot.forEach((docSnap) => {
          const data = docSnap.data();
          docs.push({
            id: docSnap.id,
            name: data.name,
            category: data.category || "Outros",
            quantity: Number(data.quantity) || 0,
            quantityInUse:
              data.quantityInUse !== undefined ? Number(data.quantityInUse) : 0,
            quantitySealed:
              data.quantitySealed !== undefined
                ? Number(data.quantitySealed)
                : Number(data.quantity) || 0,
            minQuantity: Number(data.minQuantity) || 0,
            unit: data.unit || "unid",
            averagePrice:
              data.averagePrice !== undefined ? Number(data.averagePrice) : 0,
            userId: data.userId,
            assignedTo: data.assignedTo || "all",
            lastUpdated: data.lastUpdated || new Date().toISOString(),
          });
        });
        // Sort items alphabetically by name
        docs.sort((a, b) => a.name.localeCompare(b.name, "pt-BR"));
        setInventoryItems(docs);
        inventoryLoaded = true;
        checkAllLoaded();
      },
      (err) => {
        console.error("Inventory snapshot error", err);
        inventoryLoaded = true;
        checkAllLoaded();
      },
    );

    const unsubSecondBrain = onSnapshot(
      qSecondBrain,
      (snapshot) => {
        const docs: SecondBrainNote[] = [];
        snapshot.forEach((docSnap) => {
          const data = docSnap.data();
          docs.push({
            id: docSnap.id,
            title: data.title || "",
            content: data.content || "",
            category: data.category || "Geral",
            tags: data.tags || [],
            createdAt: data.createdAt || new Date().toISOString(),
            updatedAt:
              data.updatedAt || data.createdAt || new Date().toISOString(),
            userId: data.userId,
            isEncrypted: !!data.isEncrypted,
            isSensitive: !!data.isSensitive,
            folder: data.folder || "",
          });
        });
        docs.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
        setSecondBrainNotes(docs);
        secondBrainLoaded = true;
        checkAllLoaded();
      },
      (err) => {
        console.error("Second brain snap error", err);
        secondBrainLoaded = true;
        checkAllLoaded();
      },
    );

    const unsubMedication = onSnapshot(
      qMedications,
      (snapshot) => {
        const docs: Medication[] = [];
        snapshot.forEach((docSnap) => {
          const data = docSnap.data();
          docs.push({
            id: docSnap.id,
            name: data.name || "",
            dosage: data.dosage || "",
            scheduledTime: data.scheduledTime || "08:00",
            recheckIntervalMinutes: Number(data.recheckIntervalMinutes) || 15,
            history: data.history || {},
            userId: data.userId,
            createdAt: data.createdAt || new Date().toISOString(),
            assignedTo: data.assignedTo || "all",
          });
        });
        setMedications(docs);
        medicationLoaded = true;
        checkAllLoaded();
      },
      (err) => {
        console.error("Medication snapshot error", err);
        medicationLoaded = true;
        checkAllLoaded();
      },
    );

    return () => {
      unsubTx();
      unsubApt();
      unsubGoal();
      unsubHabit();
      unsubWater();
      unsubInventory();
      unsubSecondBrain();
      unsubMedication();
    };
  }, [userId, user]);

  // Automatic background tracker to mark missed medications for past days (turned days)
  useEffect(() => {
    if (!medications || medications.length === 0) return;

    const checkAndMarkMissed = async () => {
      const todayStr = new Date().toLocaleDateString("en-CA"); // YYYY-MM-DD in local time

      for (const med of medications) {
        if (!med.createdAt) continue;

        // Start scanning from the medication's creation date (at local midnight)
        const createdDate = new Date(med.createdAt);
        createdDate.setHours(0, 0, 0, 0);

        const today = new Date();
        today.setHours(0, 0, 0, 0);

        let changed = false;
        const newHistory = { ...med.history };

        // Scan back up to 30 days to avoid infinite/huge operations
        const daysToScan = 30;
        for (let i = 1; i <= daysToScan; i++) {
          const checkDate = new Date();
          checkDate.setDate(today.getDate() - i);
          checkDate.setHours(0, 0, 0, 0);

          // Do not check days before the medication was created
          if (checkDate < createdDate) break;

          const dateStr = checkDate.toLocaleDateString("en-CA"); // YYYY-MM-DD

          // If a past day has no log (neither true nor false), explicitly mark it as not taken (false)
          if (newHistory[dateStr] === undefined) {
            newHistory[dateStr] = false;
            changed = true;
          }
        }

        if (changed) {
          try {
            await updateDoc(doc(db, "medications", med.id), {
              history: newHistory,
            });
          } catch (err) {
            console.error(
              `Erro ao auto-marcar medicação ${med.name} como não tomada para os dias anteriores:`,
              err,
            );
          }
        }
      }
    };

    // Run 2 seconds after medications are loaded/updated to avoid slamming Firestore during state transitions
    const timer = setTimeout(() => {
      checkAndMarkMissed();
    }, 2000);

    return () => clearTimeout(timer);
  }, [medications]);

  // Seeding realistic initial showcase data for brand new profiles
  const seedInitialData = async (uid: string) => {
    if (localStorage.getItem(`life_manager_cleared_${uid}`) === "true") return;

    const today = new Date().toISOString().split("T")[0];
    const yesterday = new Date(Date.now() - 86400000)
      .toISOString()
      .split("T")[0];
    const tomorrow = new Date(Date.now() + 86400000)
      .toISOString()
      .split("T")[0];
    const nextWeek = new Date(Date.now() + 86400000 * 5)
      .toISOString()
      .split("T")[0];

    try {
      // Seed Transactions
      const txs = [
        {
          amount: 5000,
          category: "Salário",
          date: today,
          description: "Salário Desenvolvimento Software",
          type: "income",
          userId: uid,
          assignedTo: "all",
          dueDate: "",
          status: "pago",
        },
        {
          amount: 80,
          category: "Alimentação",
          date: today,
          description: "Almoço Executivo",
          type: "expense",
          userId: uid,
          assignedTo: "MEMBER-1",
          dueDate: "",
          status: "pago",
        },
        {
          amount: 250,
          category: "Lazer",
          date: yesterday,
          description: "Ingressos de Show",
          type: "expense",
          userId: uid,
          assignedTo: "all",
          dueDate: "",
          status: "pago",
        },
        {
          amount: 450,
          category: "Freelance",
          date: yesterday,
          description: "Site Portfólio do Cliente",
          type: "income",
          userId: uid,
          assignedTo: "all",
          dueDate: "",
          status: "pago",
        },
        {
          amount: 1500,
          category: "Moradia",
          date: nextWeek,
          description: "Aluguel Mensal",
          type: "expense",
          userId: uid,
          assignedTo: "all",
          dueDate: nextWeek,
          status: "pendente",
        },
      ];
      for (const tx of txs) {
        await addDoc(collection(db, "transactions"), tx);
      }

      // Seed Appointments
      const apts = [
        {
          title: "Reunião de Kickoff",
          date: today,
          time: "10:00",
          category: "Trabalho",
          description: "Reunir com equipe para novos projetos.",
          completed: false,
          userId: uid,
          assignedTo: "MEMBER-1",
        },
        {
          title: "Treino em Família",
          date: today,
          time: "18:00",
          category: "Saúde",
          description: "Atividade física coletiva no parque.",
          completed: false,
          userId: uid,
          assignedTo: "all",
        },
        {
          title: "Consulta de Rotina",
          date: tomorrow,
          time: "14:30",
          category: "Saúde",
          description: "Levar exames médicos solicitados.",
          completed: false,
          userId: uid,
          assignedTo: "MEMBER-1",
        },
        {
          title: "Jantar com Amigos",
          date: nextWeek,
          time: "20:00",
          category: "Lazer",
          description: "Rodízio de pizza no centro.",
          completed: false,
          userId: uid,
          assignedTo: "all",
        },
      ];
      for (const apt of apts) {
        await addDoc(collection(db, "appointments"), apt);
      }

      // Seed Goals
      const gls = [
        {
          title: "Reserva de Emergência",
          targetValue: 10000,
          currentValue: 3500,
          category: "Financeira",
          deadline: "2026-12-31",
          userId: uid,
          assignedTo: "all",
          valueType: "money",
        },
        {
          title: "Estudar Programação",
          targetValue: 100,
          currentValue: 45,
          category: "Estudos",
          deadline: "2026-11-01",
          userId: uid,
          assignedTo: "MEMBER-1",
          valueType: "number",
        },
        {
          title: "Correr Meia Maratona",
          targetValue: 21,
          currentValue: 12,
          category: "Saúde/Fitness",
          deadline: "2026-09-15",
          userId: uid,
          assignedTo: "MEMBER-1",
          valueType: "number",
        },
      ];
      for (const gl of gls) {
        await addDoc(collection(db, "goals"), gl);
      }

      // Seed Habits
      const hbs = [
        {
          name: "Beber 2.5L de Água",
          streak: 3,
          history: { [yesterday]: true },
          userId: uid,
          createdAt: today,
          assignedTo: "all",
        },
        {
          name: "Ler 15 min por dia",
          streak: 2,
          history: { [yesterday]: true },
          userId: uid,
          createdAt: today,
          assignedTo: "MEMBER-1",
        },
        {
          name: "Exercitar 30 min",
          streak: 0,
          history: {},
          userId: uid,
          createdAt: today,
          assignedTo: "MEMBER-1",
        },
      ];
      for (const hb of hbs) {
        await addDoc(collection(db, "habits"), hb);
      }

      // Seed Inventory Items
      const invs = [
        {
          name: "Arroz Integral 5kg",
          category: "Alimentos",
          quantity: 2,
          quantityInUse: 1,
          quantitySealed: 1,
          minQuantity: 1,
          unit: "pacote",
          averagePrice: 24.9,
          userId: uid,
          lastUpdated: new Date().toISOString(),
        },
        {
          name: "Feijão Carioca 1kg",
          category: "Alimentos",
          quantity: 0,
          quantityInUse: 0,
          quantitySealed: 0,
          minQuantity: 2,
          unit: "pacote",
          averagePrice: 8.5,
          userId: uid,
          lastUpdated: new Date().toISOString(),
        },
        {
          name: "Detergente de Louça",
          category: "Limpeza",
          quantity: 1,
          quantityInUse: 1,
          quantitySealed: 0,
          minQuantity: 2,
          unit: "frasco",
          averagePrice: 2.2,
          userId: uid,
          lastUpdated: new Date().toISOString(),
        },
        {
          name: "Papel Higiênico Pct 12",
          category: "Higiene",
          quantity: 3,
          quantityInUse: 1,
          quantitySealed: 2,
          minQuantity: 1,
          unit: "pacote",
          averagePrice: 15.9,
          userId: uid,
          lastUpdated: new Date().toISOString(),
        },
        {
          name: "Sabonete Glicerina",
          category: "Higiene",
          quantity: 1,
          quantityInUse: 1,
          quantitySealed: 0,
          minQuantity: 3,
          unit: "barra",
          averagePrice: 3.5,
          userId: uid,
          lastUpdated: new Date().toISOString(),
        },
        {
          name: "Amaciante Concentrado 1.5L",
          category: "Limpeza",
          quantity: 0,
          quantityInUse: 0,
          quantitySealed: 0,
          minQuantity: 1,
          unit: "garrafa",
          averagePrice: 18.9,
          userId: uid,
          lastUpdated: new Date().toISOString(),
        },
      ];
      for (const inv of invs) {
        await addDoc(collection(db, "inventory"), inv);
      }
    } catch (e) {
      console.error("Error seeding details", e);
    }
  };

  // Race-safe verification to prevent cleared data from returning on load and session syncs
  const checkAndSeed = async (uid: string) => {
    try {
      const hasBeenClearedLocal =
        localStorage.getItem(`life_manager_cleared_${uid}`) === "true";
      if (hasBeenClearedLocal) return;

      // Force-check of Firestore user config to ensure they didn't clear the data previously
      const userDocRef = doc(db, "users", uid);
      const userDocSnap = await getDoc(userDocRef);
      if (userDocSnap.exists() && userDocSnap.data()?.isDataCleared === true) {
        localStorage.setItem(`life_manager_cleared_${uid}`, "true");
        return;
      }

      await seedInitialData(uid);
    } catch (err) {
      console.error("Error in checkAndSeed:", err);
    }
  };

  const getActiveMemberNameStr = () => {
    return activeMember
      ? `${activeMember.name} (Perfil ${activeMember.role})`
      : "Usuário Principal";
  };

  const sendProactiveFamilyPush = async (
    title: string,
    body: string,
    url: string = "/",
  ) => {
    try {
      const email = user?.email || "cnttdouglas@gmail.com";
      await fetch("/api/notifications/send", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email,
          userId,
          title,
          body,
          url,
        }),
      });
    } catch (e) {
      console.warn("Could not dispatch proactive push:", e);
    }
  };

  // Transactions Functions
  const addTransaction = async (tx: Omit<Transaction, "id" | "userId">) => {
    const newTx: Transaction = {
      ...tx,
      id: generateSyncId(),
      userId,
      assignedTo: tx.assignedTo || activeMember?.id || "all",
      dueDate: tx.dueDate || "",
      status: tx.status || "pago",
    };
    setTransactions((prev) => [newTx, ...prev]);
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );

    // Proactive family notification
    const name = getActiveMemberNameStr();
    const typeLabel = tx.type === "expense" ? "despesa" : "receita";
    sendProactiveFamilyPush(
      `💸 Nova transação por ${name}`,
      `Lançou ${typeLabel}: "${tx.description}" de R$ ${tx.amount.toLocaleString("pt-BR")}`,
    );
  };

  const deleteTransaction = async (id: string) => {
    setTransactions((prev) => prev.filter((t) => t.id !== id));
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  const updateTransaction = async (
    id: string,
    updates: Partial<Transaction>,
  ) => {
    setTransactions((prev) =>
      prev.map((t) => (t.id === id ? { ...t, ...updates } : t)),
    );
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  // Inventory Functions
  const addInventoryItem = async (
    item: Omit<InventoryItem, "id" | "userId" | "lastUpdated">,
  ) => {
    const newItem: InventoryItem = {
      ...item,
      id: generateSyncId(),
      userId,
      lastUpdated: new Date().toISOString(),
    };
    setInventoryItems((prev) => [...prev, newItem]);
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  const deleteInventoryItem = async (id: string) => {
    setInventoryItems((prev) => prev.filter((i) => i.id !== id));
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  const updateInventoryItem = async (
    id: string,
    updates: Partial<InventoryItem>,
  ) => {
    setInventoryItems((prev) =>
      prev.map((i) =>
        i.id === id
          ? { ...i, ...updates, lastUpdated: new Date().toISOString() }
          : i,
      ),
    );
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  // Appointments Functions
  const addAppointment = async (apt: Omit<Appointment, "id" | "userId">) => {
    let googleId = undefined;
    let outlookId = undefined;

    if (googleAccessToken) {
      try {
        const createdGoogle = await addGoogleEvent({
          title: apt.title,
          date: apt.date,
          time: apt.time,
          description: apt.description,
        });
        if (createdGoogle && createdGoogle.id) {
          googleId = createdGoogle.id;
        }
      } catch (err) {
        console.error(
          "Auto-syncing appointment to Google Calendar failed:",
          err,
        );
      }
    }

    if (outlookAccessToken) {
      try {
        const createdOutlook = await addOutlookEvent({
          title: apt.title,
          date: apt.date,
          time: apt.time,
          description: apt.description,
        });
        if (createdOutlook && createdOutlook.id) {
          outlookId = createdOutlook.id;
        }
      } catch (err) {
        console.error(
          "Auto-syncing appointment to Outlook Calendar failed:",
          err,
        );
      }
    }

    const newApt: Appointment = {
      ...apt,
      id: generateSyncId(),
      userId,
      assignedTo: apt.assignedTo || activeMember?.id || "all",
      googleEventId: googleId,
      outlookEventId: outlookId,
    };
    setAppointments((prev) => [...prev, newApt]);
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );

    // Proactive family notification
    const name = getActiveMemberNameStr();
    sendProactiveFamilyPush(
      `🗓️ Novo Compromisso por ${name}`,
      `Adicionou: "${apt.title}" para ${apt.date} às ${apt.time}`,
    );
  };

  const deleteAppointment = async (id: string) => {
    const apt = appointments.find((a) => a.id === id);
    if (apt) {
      if (apt.googleEventId && googleAccessToken) {
        await deleteGoogleEvent(apt.googleEventId).catch((err) =>
          console.warn(
            "Non-critical: Failed to auto-delete event from Google Calendar:",
            err,
          ),
        );
      }
      if (apt.outlookEventId && outlookAccessToken) {
        await deleteOutlookEvent(apt.outlookEventId).catch((err) =>
          console.warn(
            "Non-critical: Failed to auto-delete event from Outlook Calendar:",
            err,
          ),
        );
      }
    }

    setAppointments((prev) => prev.filter((a) => a.id !== id));
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  const toggleAppointmentCompleted = async (
    id: string,
    currentStatus: boolean,
  ) => {
    setAppointments((prev) =>
      prev.map((a) => (a.id === id ? { ...a, completed: !currentStatus } : a)),
    );
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );

    // Proactive family notification
    const name = getActiveMemberNameStr();
    const apt = appointments.find((a) => a.id === id);
    if (apt) {
      const statusLabel = !currentStatus ? "concluiu" : "reabriu";
      sendProactiveFamilyPush(
        `🗓️ Compromisso Atualizado por ${name}`,
        `${statusLabel} o compromisso: "${apt.title}" às ${apt.time}`,
      );
    }
  };

  // Goals Functions
  const addGoal = async (goal: Omit<Goal, "id" | "userId">) => {
    const newGoal: Goal = {
      ...goal,
      id: generateSyncId(),
      userId,
      assignedTo: goal.assignedTo || activeMember?.id || "all",
    };
    setGoals((prev) => [...prev, newGoal]);
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  const deleteGoal = async (id: string) => {
    setGoals((prev) => prev.filter((g) => g.id !== id));
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  const updateGoalProgress = async (id: string, newValue: number) => {
    setGoals((prev) =>
      prev.map((g) => (g.id === id ? { ...g, currentValue: newValue } : g)),
    );
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );

    // Proactive family notification
    const name = getActiveMemberNameStr();
    const goal = goals.find((g) => g.id === id);
    if (goal) {
      const progressPct = Math.round((newValue / goal.targetValue) * 100);
      const isCompleted = newValue >= goal.targetValue;
      const titleLabel = isCompleted
        ? `🎉 Meta Batida por ${name}!`
        : `📈 Progresso de Meta por ${name}`;
      const msgLabel = isCompleted
        ? `Bateu a meta coletiva: "${goal.title}"! Parabéns! 🥳`
        : `Atualizou a meta "${goal.title}" para R$ ${newValue.toLocaleString("pt-BR")} de R$ ${goal.targetValue.toLocaleString("pt-BR")} (${progressPct}%)`;

      sendProactiveFamilyPush(titleLabel, msgLabel);
    }
  };

  const updateGoalFields = async (id: string, updates: Partial<Goal>) => {
    setGoals((prev) =>
      prev.map((g) => (g.id === id ? { ...g, ...updates } : g)),
    );
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  // Habits Functions
  const addHabit = async (name: string, assignedTo?: string) => {
    const newHabit: Habit = {
      id: generateSyncId(),
      name,
      streak: 0,
      history: {},
      userId,
      createdAt: new Date().toISOString(),
      assignedTo: assignedTo || activeMember?.id || "all",
    };
    setHabits((prev) => [...prev, newHabit]);
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );

    // Proactive family notification
    const memberName = getActiveMemberNameStr();
    sendProactiveFamilyPush(
      `🌟 Novo Hábito Criado por ${memberName}`,
      `Iniciou o ritual: "${name}"`,
    );
  };

  const deleteHabit = async (id: string) => {
    setHabits((prev) => prev.filter((h) => h.id !== id));
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  const toggleHabitForDate = async (habitId: string, dateStr: string) => {
    const habit = habits.find((h) => h.id === habitId);
    if (!habit) return;

    const newHistory = { ...habit.history };
    const wasCompleted = !!newHistory[dateStr];

    if (wasCompleted) {
      delete newHistory[dateStr];
    } else {
      newHistory[dateStr] = true;
    }

    // Calculate dynamic habit streak
    let currentStreak = 0;
    const checkDate = new Date();

    // Check backwards from today to count consecutive days
    for (let i = 0; i < 30; i++) {
      const dStr = checkDate.toISOString().split("T")[0];
      if (newHistory[dStr]) {
        currentStreak++;
      } else {
        if (i > 0 || (i === 0 && dStr === dateStr && wasCompleted)) {
          break;
        }
      }
      checkDate.setDate(checkDate.getDate() - 1);
    }

    setHabits((prev) =>
      prev.map((h) =>
        h.id === habitId
          ? { ...h, history: newHistory, streak: currentStreak }
          : h,
      ),
    );
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );

    // Proactive family notification
    const name = getActiveMemberNameStr();
    if (habit) {
      const statusLabel = !wasCompleted ? "completou" : "desmarcou";
      sendProactiveFamilyPush(
        `🌟 Ritual Familiar por ${name}`,
        `${statusLabel} o hábito: "${habit.name}" hoje! Streak atual: ${currentStreak} dias`,
      );
    }
  };

  // Water Actions
  const addWaterLog = async (
    amountMl: number,
    memberId?: string,
    dateStr?: string,
  ) => {
    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 = dateStr || getLocalTodayStr();

    const newLog: WaterLog = {
      id: generateSyncId(),
      amountMl,
      memberId: memberId || activeMember?.id || "all",
      date: todayStr,
      userId,
      createdAt: new Date().toISOString(),
    };
    setWaterLogs((prev) => [...prev, newLog]);
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );

    // Proactive family notification
    const name = getActiveMemberNameStr();
    sendProactiveFamilyPush(
      `💧 Hidratação Coletiva`,
      `${name} registrou consumo de ${amountMl}ml de água! Vamos manter o foco na hidratação diária.`,
    );
  };

  const deleteWaterLog = async (id: string) => {
    setWaterLogs((prev) => prev.filter((w) => w.id !== id));
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  // Medication Actions
  const addMedication = async (
    name: string,
    dosage: string,
    scheduledTime: string,
    recheckIntervalMinutes: number,
    assignedTo?: string,
  ) => {
    const newMed: Medication = {
      id: generateSyncId(),
      name,
      dosage,
      scheduledTime,
      recheckIntervalMinutes: Number(recheckIntervalMinutes) || 15,
      history: {},
      userId,
      createdAt: new Date().toISOString(),
      assignedTo: assignedTo || activeMember?.id || "all",
    };
    setMedications((prev) => [...prev, newMed]);
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );

    const memberName = getActiveMemberNameStr();
    sendProactiveFamilyPush(
      `💊 Novo Controle de Medicação por ${memberName}`,
      `Remédio cadastrado: "${name}" (${dosage}) às ${scheduledTime}`,
    );
  };

  const deleteMedication = async (id: string) => {
    setMedications((prev) => prev.filter((m) => m.id !== id));
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  const toggleMedicationTaken = async (id: string, dateStr: string) => {
    const med = medications.find((m) => m.id === id);
    if (!med) return;

    const newHistory = { ...med.history };
    const wasTaken = !!newHistory[dateStr];

    if (wasTaken) {
      delete newHistory[dateStr];
    } else {
      newHistory[dateStr] = true;
    }

    setMedications((prev) =>
      prev.map((m) => (m.id === id ? { ...m, history: newHistory } : m)),
    );
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );

    const memberName = getActiveMemberNameStr();
    const actionStr = !wasTaken ? "tomou" : "desmarcou";
    sendProactiveFamilyPush(
      `💊 Medicação por ${memberName}`,
      `${actionStr} o remédio: "${med.name}" (${med.dosage}) programado para as ${med.scheduledTime}`,
    );
  };

  // Second Brain Vault Actions
  const addSecondBrainNote = async (
    note: Omit<SecondBrainNote, "id" | "userId" | "createdAt" | "updatedAt">,
  ) => {
    const now = new Date().toISOString();
    const newNote: SecondBrainNote = {
      ...note,
      id: generateSyncId(),
      userId,
      createdAt: now,
      updatedAt: now,
    };
    setSecondBrainNotes((prev) => [...prev, newNote]);
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  const updateSecondBrainNote = async (
    id: string,
    updates: Partial<SecondBrainNote>,
  ) => {
    const now = new Date().toISOString();
    setSecondBrainNotes((prev) =>
      prev.map((n) => (n.id === id ? { ...n, ...updates, updatedAt: now } : n)),
    );
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  const deleteSecondBrainNote = async (id: string) => {
    setSecondBrainNotes((prev) => prev.filter((n) => n.id !== id));
    localStorage.setItem(
      `user_config_last_updated_${userId}`,
      new Date().toISOString(),
    );
  };

  // Google Calendar API Integration Implementations
  const fetchGoogleCalendars = async (token: string) => {
    try {
      const response = await fetch(
        "https://www.googleapis.com/calendar/v3/users/me/calendarList",
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );
      if (response.ok) {
        const data = await response.json();
        if (data.items) {
          setGoogleCalendars(data.items);
          return data.items;
        }
      } else {
        console.warn(
          `Failed to fetch google calendar list. Status: ${response.status} ${response.statusText}`,
        );
        if (response.status === 401) {
          setIsGoogleAuthExpired(true);
          throw new Error("Expired");
        }
      }
    } catch (e: any) {
      if (e?.message !== "Expired") {
        console.error("Error fetching google calendar list:", e);
      }
      if (e?.message === "Expired") {
        setIsGoogleAuthExpired(true);
        throw e;
      }
    }
    return [];
  };

  const fetchGoogleEventsInternal = async (
    token: string,
    calendarIdsToFetch?: string[],
  ) => {
    try {
      // First, fetch list of calendars to ensure we have titles and metadata
      const calendars = (await fetchGoogleCalendars(token)) || [];

      let activeCalendarIds = calendarIdsToFetch || selectedGoogleCalendarIds;
      if (!activeCalendarIds || activeCalendarIds.length === 0) {
        const primaryCal = calendars.find((c: any) => c.primary);
        activeCalendarIds = [primaryCal ? primaryCal.id : "primary"];
      }

      const allEvents: any[] = [];
      const fetchPromises = activeCalendarIds.map(async (calendarId) => {
        try {
          const response = await fetch(
            `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/events?orderBy=startTime&singleEvents=true&maxResults=25&timeMin=${new Date().toISOString()}`,
            {
              headers: {
                Authorization: `Bearer ${token}`,
              },
            },
          );
          if (response.ok) {
            const data = await response.json();
            if (data.items) {
              const cal = calendars.find((c: any) => c.id === calendarId) || {
                summary:
                  calendarId === "primary" ? "Google Calendar" : calendarId,
              };
              return data.items.map((item: any) => ({
                ...item,
                calendarId: calendarId,
                calendarSummary: cal.summary,
              }));
            }
          } else {
            if (response.status === 401) {
              setIsGoogleAuthExpired(true);
              throw new Error("Expired");
            }
            console.warn(
              `Failed to fetch events for calendar ${calendarId}:`,
              response.statusText || response.status,
            );
          }
        } catch (err: any) {
          if (err?.message === "Expired") {
            setIsGoogleAuthExpired(true);
            throw err;
          }
          console.error(`Error fetching calendar ${calendarId} events:`, err);
        }
        return [];
      });

      try {
        const results = await Promise.all(fetchPromises);
        results.forEach((items) => {
          allEvents.push(...items);
        });

        // Sort consolidated events by startTime
        allEvents.sort((a, b) => {
          const startA = a.start?.dateTime || a.start?.date || "";
          const startB = b.start?.dateTime || b.start?.date || "";
          return startA.localeCompare(startB);
        });

        setGoogleEvents(allEvents.slice(0, 75)); // Allow more combined results
      } catch (err: any) {
        if (err?.message === "Expired") {
          console.log(
            "Cached Google Calendar token has expired, please re-authenticate.",
          );
          setIsGoogleAuthExpired(true);
          setGoogleEvents([]);
          setGoogleCalendars([]);
        }
      }
    } catch (e: any) {
      if (e?.message !== "Expired") {
        console.error("Error fetching google calendar events:", e);
      }
    }
  };

  const fetchGoogleEvents = async () => {
    if (!googleAccessToken) return;
    await fetchGoogleEventsInternal(googleAccessToken);
  };

  const updateGoogleCalendarSelection = async (
    selectedIds: string[],
    defaultScheduleId: string,
  ) => {
    setSelectedGoogleCalendarIds(selectedIds);
    setDefaultScheduleGoogleCalendarId(defaultScheduleId);
    if (userId) {
      try {
        await setDoc(
          doc(db, "users", userId),
          {
            selectedGoogleCalendarIds: selectedIds,
            defaultScheduleGoogleCalendarId: defaultScheduleId,
          },
          { merge: true },
        );

        if (googleAccessToken) {
          await fetchGoogleEventsInternal(googleAccessToken, selectedIds);
        }
      } catch (err) {
        console.error("Error saving Google Calendar settings:", err);
      }
    }
  };

  const updateGoogleCalendarAlertSelection = async (alertIds: string[]) => {
    setGoogleCalendarAlertIds(alertIds);
    if (userId) {
      try {
        await setDoc(
          doc(db, "users", userId),
          {
            googleCalendarAlertIds: alertIds,
          },
          { merge: true },
        );
      } catch (err) {
        console.error("Error saving Google Calendar alert settings:", err);
      }
    }
  };

  // Automatically fetch Google Events on token load/change
  useEffect(() => {
    if (googleAccessToken) {
      fetchGoogleEventsInternal(googleAccessToken);
    } else {
      setGoogleEvents([]);
      setGoogleCalendars([]);
    }
  }, [googleAccessToken]);

  const connectGoogleCalendar = async (): Promise<string | null> => {
    const provider = new GoogleAuthProvider();
    provider.addScope("https://www.googleapis.com/auth/calendar");
    provider.addScope("https://www.googleapis.com/auth/calendar.events");
    provider.addScope("https://www.googleapis.com/auth/calendar.readonly");
    provider.setCustomParameters({ prompt: "select_account" });

    try {
      let result;
      if (auth.currentUser) {
        try {
          // Tenta vincular o provider ao usuário atual para adicionar os escopos
          result = await linkWithPopup(auth.currentUser, provider);
        } catch (err: any) {
          // Se já estiver vinculado (provider-already-linked) ou o email já estiver em uso,
          // fazemos o signIn normal que vai reautenticar o usuário e atualizar o token.
          if (
            err.code === "auth/credential-already-in-use" ||
            err.code === "auth/provider-already-linked"
          ) {
            result = await signInWithPopup(auth, provider);
          } else {
            throw err;
          }
        }
      } else {
        result = await signInWithPopup(auth, provider);
      }

      setIsGoogleAuthLoading(true);
      setIsGoogleAuthExpired(false);

      const credential = GoogleAuthProvider.credentialFromResult(result);
      if (credential?.accessToken) {
        setGoogleAccessToken(credential.accessToken);
        // Persist the token to Firestore so it remains authorized on refresh
        try {
          await setDoc(
            doc(db, "users", userId),
            { googleAccessToken: credential.accessToken },
            { merge: true },
          );
        } catch (dbErr) {
          console.error("Failed to persist google token to Firestore:", dbErr);
        }
        setIsGoogleAuthLoading(false);
        await fetchGoogleEventsInternal(credential.accessToken);
        return credential.accessToken;
      }
      setIsGoogleAuthLoading(false);
      return null;
    } catch (e) {
      console.error("Failed to connect to Google Calendar:", e);
      setIsGoogleAuthLoading(false);
      throw e;
    }
  };

  const disconnectGoogleCalendar = async () => {
    setGoogleAccessToken(null);
    setGoogleEvents([]);
    setGoogleCalendars([]);
    setSelectedGoogleCalendarIds(["primary"]);
    setGoogleCalendarAlertIds(["primary"]);
    setDefaultScheduleGoogleCalendarId("primary");
    if (userId) {
      try {
        await setDoc(
          doc(db, "users", userId),
          {
            googleAccessToken: null,
            selectedGoogleCalendarIds: ["primary"],
            googleCalendarAlertIds: ["primary"],
            defaultScheduleGoogleCalendarId: "primary",
          },
          { merge: true },
        );
      } catch (e) {
        console.error("Failed to disconnect Google Calendar", e);
      }
    }
  };

  const addGoogleEvent = async (
    event: { title: string; date: string; time: string; description: string },
    calendarId?: string,
  ) => {
    if (!googleAccessToken) {
      throw new Error("Google Calendar is not connected. Connect first.");
    }

    const targetCalendarId =
      calendarId || defaultScheduleGoogleCalendarId || "primary";
    const startDateTime = `${event.date}T${event.time}:00`;
    const startTimeStamp = new Date(startDateTime).getTime();
    const endDateTime = new Date(startTimeStamp + 60 * 60 * 1000).toISOString();

    try {
      const response = await fetch(
        `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(targetCalendarId)}/events`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${googleAccessToken}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            summary: event.title,
            description:
              event.description + " (Importado via Gestor de Vida Coletivo)",
            start: {
              dateTime: new Date(startDateTime).toISOString(),
              timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            },
            end: {
              dateTime: endDateTime,
              timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            },
          }),
        },
      );

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText || "Failed to create Google Calendar event");
      }

      const created = await response.json();
      await fetchGoogleEventsInternal(googleAccessToken);
      return created;
    } catch (e) {
      console.error("Error creating Google Calendar event:", e);
      throw e;
    }
  };

  const deleteGoogleEvent = async (eventId: string, calendarId?: string) => {
    if (!googleAccessToken) return;
    const targetCalendarId = calendarId || "primary";
    try {
      const response = await fetch(
        `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(targetCalendarId)}/events/${eventId}`,
        {
          method: "DELETE",
          headers: {
            Authorization: `Bearer ${googleAccessToken}`,
          },
        },
      );
      if (response.ok) {
        await fetchGoogleEventsInternal(googleAccessToken);
      } else {
        let errorDetails = "";
        try {
          const errData = await response.json();
          errorDetails = errData?.error?.message || JSON.stringify(errData);
        } catch (_) {
          try {
            errorDetails = await response.text();
          } catch (_) {}
        }

        let customMsg = "Não foi possível excluir o evento do Google Agenda.";
        if (response.status === 403) {
          customMsg +=
            " Esse evento pode fazer parte de um calendário somente leitura (como Feriados, Aniversários ou Agendas compartilhadas sem permissão de escrita).";
        } else if (response.status === 404) {
          customMsg +=
            " O evento não foi encontrado ou já foi excluído no Google Agenda.";
        } else if (response.status === 401) {
          customMsg +=
            " Sua autenticação do Google expirou. Por favor, desconecte e reconecte.";
        }

        if (errorDetails) {
          customMsg += ` [Erro Google API: ${errorDetails}]`;
        } else {
          customMsg += ` [Status API: ${response.status}]`;
        }

        throw new Error(customMsg);
      }
    } catch (e) {
      console.warn("Google calendar event non-critical delete error:", e);
      throw e;
    }
  };

  const hideGoogleEvent = async (eventId: string) => {
    if (!userId) return;
    try {
      const updatedIds = [...hiddenGoogleEventIds, eventId];
      setHiddenGoogleEventIds(updatedIds);
      await setDoc(
        doc(db, "users", userId),
        { hiddenGoogleEventIds: updatedIds },
        { merge: true },
      );
    } catch (err) {
      console.error("Error hiding Google Calendar event locally:", err);
    }
  };

  const createSharedGoogleCalendar = async (): Promise<string> => {
    if (!googleAccessToken) {
      throw new Error(
        "Conecte ao Google primeiro para criar uma agenda coletiva.",
      );
    }
    try {
      const response = await fetch(
        "https://www.googleapis.com/calendar/v3/calendars",
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${googleAccessToken}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            summary: "Agenda Coletiva | Gestor de Vida",
          }),
        },
      );

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(
          `Erro do Google ao criar agenda: ${errorText || response.statusText}`,
        );
      }

      const calendarData = await response.json();
      const newCalendarId = calendarData.id;

      // Update local states and database
      if (userId) {
        await setDoc(
          doc(db, "users", userId),
          {
            sharedGoogleCalendarId: newCalendarId,
            selectedGoogleCalendarIds: [
              ...selectedGoogleCalendarIds,
              newCalendarId,
            ],
            defaultScheduleGoogleCalendarId: newCalendarId,
          },
          { merge: true },
        );

        setSelectedGoogleCalendarIds((prev) => [...prev, newCalendarId]);
        setDefaultScheduleGoogleCalendarId(newCalendarId);
      }

      // Share with existing family members that have emails
      if (userConfig?.members) {
        for (const m of userConfig.members) {
          if (m.email && m.email.trim()) {
            try {
              await shareGoogleCalendarWithEmailInternal(
                newCalendarId,
                m.email,
              );
            } catch (shareErr) {
              console.warn(
                `Failed auto-sharing with member ${m.name}:`,
                shareErr,
              );
            }
          }
        }
      }

      // Re-fetch calendars and events
      await fetchGoogleEventsInternal(googleAccessToken, [
        ...selectedGoogleCalendarIds,
        newCalendarId,
      ]);

      return newCalendarId;
    } catch (err: any) {
      console.error("Error creating shared Google Calendar:", err);
      throw err;
    }
  };

  // Outlook Calendar API Integration Implementations
  const fetchOutlookCalendars = async (token: string) => {
    try {
      const response = await fetch(
        "https://graph.microsoft.com/v1.0/me/calendars",
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );
      if (response.ok) {
        const data = await response.json();
        if (data.value) {
          const calendars = data.value.map((c: any) => ({
            id: c.id,
            name: c.name,
            summary: c.name,
            primary: c.isDefaultCalendar || false,
            colorId: c.color || "none",
          }));
          setOutlookCalendars(calendars);
          return calendars;
        }
      }
    } catch (e) {
      console.error("Error fetching outlook calendar list:", e);
    }
    return [];
  };

  const fetchOutlookEventsInternal = async (
    token: string,
    calendarIdsToFetch?: string[],
  ) => {
    try {
      const calendars = await fetchOutlookCalendars(token);

      let activeCalendarIds = calendarIdsToFetch || selectedOutlookCalendarIds;
      if (!activeCalendarIds || activeCalendarIds.length === 0) {
        const primaryCal = calendars.find((c: any) => c.primary);
        activeCalendarIds = [primaryCal ? primaryCal.id : "primary"];
      }

      const allEvents: any[] = [];
      const fetchPromises = activeCalendarIds.map(async (calendarId) => {
        try {
          const calIdEncoded =
            calendarId === "primary"
              ? "me/calendar"
              : `me/calendars/${encodeURIComponent(calendarId)}`;
          const response = await fetch(
            `https://graph.microsoft.com/v1.0/${calIdEncoded}/events?$top=50&$orderby=start/dateTime`,
            {
              headers: {
                Authorization: `Bearer ${token}`,
              },
            },
          );
          if (response.ok) {
            const data = await response.json();
            if (data.value) {
              const cal = calendars.find((c: any) => c.id === calendarId) || {
                name: calendarId === "primary" ? "Outlook Agenda" : calendarId,
              };
              return data.value.map((item: any) => ({
                id: item.id,
                summary: item.subject,
                description: item.bodyPreview || item.body?.content || "",
                start: {
                  dateTime: item.start?.dateTime,
                  timeZone: item.start?.timeZone,
                },
                end: {
                  dateTime: item.end?.dateTime,
                  timeZone: item.end?.timeZone,
                },
                calendarId: calendarId,
                calendarSummary: cal.name || "Outlook Agenda",
              }));
            }
          } else {
            if (response.status === 401) {
              throw new Error("Expired");
            }
            console.warn(
              `Failed to fetch Outlook events for ${calendarId}:`,
              response.statusText,
            );
          }
        } catch (err: any) {
          if (err?.message === "Expired") {
            throw err;
          }
          console.error(
            `Error fetching Outlook calendar ${calendarId} events:`,
            err,
          );
        }
        return [];
      });

      try {
        const results = await Promise.all(fetchPromises);
        results.forEach((items) => {
          allEvents.push(...items);
        });

        allEvents.sort((a, b) => {
          const startA = a.start?.dateTime || "";
          const startB = b.start?.dateTime || "";
          return startA.localeCompare(startB);
        });

        setOutlookEvents(allEvents.slice(0, 75));
      } catch (err: any) {
        if (err?.message === "Expired") {
          console.log(
            "Cached Outlook Calendar token has expired, please re-authenticate.",
          );
          setOutlookEvents([]);
          setOutlookCalendars([]);
        }
      }
    } catch (e) {
      console.error("Error fetching Outlook calendar events:", e);
    }
  };

  const fetchOutlookEvents = async () => {
    if (!outlookAccessToken) return;
    await fetchOutlookEventsInternal(outlookAccessToken);
  };

  const updateOutlookCalendarSelection = async (
    selectedIds: string[],
    defaultScheduleId: string,
  ) => {
    setSelectedOutlookCalendarIds(selectedIds);
    setDefaultScheduleOutlookCalendarId(defaultScheduleId);
    if (userId) {
      try {
        await setDoc(
          doc(db, "users", userId),
          {
            selectedOutlookCalendarIds: selectedIds,
            defaultScheduleOutlookCalendarId: defaultScheduleId,
          },
          { merge: true },
        );

        if (outlookAccessToken) {
          await fetchOutlookEventsInternal(outlookAccessToken, selectedIds);
        }
      } catch (err) {
        console.error("Error saving Outlook Calendar settings:", err);
      }
    }
  };

  useEffect(() => {
    if (outlookAccessToken) {
      fetchOutlookEventsInternal(outlookAccessToken);
    } else {
      setOutlookEvents([]);
      setOutlookCalendars([]);
    }
  }, [outlookAccessToken]);

  const connectOutlookCalendar = async (): Promise<string | null> => {
    const provider = new OAuthProvider("microsoft.com");
    provider.addScope("Calendars.ReadWrite");
    provider.addScope("offline_access");
    provider.setCustomParameters({ prompt: "select_account" });

    try {
      let result;
      if (auth.currentUser) {
        try {
          result = await linkWithPopup(auth.currentUser, provider);
        } catch (err: any) {
          if (
            err.code === "auth/credential-already-in-use" ||
            err.code === "auth/provider-already-linked"
          ) {
            result = await signInWithPopup(auth, provider);
          } else {
            throw err;
          }
        }
      } else {
        result = await signInWithPopup(auth, provider);
      }

      setIsOutlookAuthLoading(true);

      const credential = OAuthProvider.credentialFromResult(result);
      if (credential?.accessToken) {
        setOutlookAccessToken(credential.accessToken);
        try {
          await setDoc(
            doc(db, "users", userId),
            { outlookAccessToken: credential.accessToken },
            { merge: true },
          );
        } catch (dbErr) {
          console.error("Failed to persist outlook token to Firestore:", dbErr);
        }
        setIsOutlookAuthLoading(false);
        await fetchOutlookEventsInternal(credential.accessToken);
        return credential.accessToken;
      }
      setIsOutlookAuthLoading(false);
      return null;
    } catch (e) {
      console.error("Failed to connect to Outlook Calendar:", e);
      setIsOutlookAuthLoading(false);
      throw e;
    }
  };

  const disconnectOutlookCalendar = async () => {
    setOutlookAccessToken(null);
    setOutlookEvents([]);
    setOutlookCalendars([]);
    setSelectedOutlookCalendarIds(["primary"]);
    setDefaultScheduleOutlookCalendarId("primary");
    if (userId) {
      try {
        await setDoc(
          doc(db, "users", userId),
          {
            outlookAccessToken: null,
            selectedOutlookCalendarIds: ["primary"],
            defaultScheduleOutlookCalendarId: "primary",
          },
          { merge: true },
        );
      } catch (e) {
        console.error("Failed to disconnect Outlook Calendar", e);
      }
    }
  };

  const addOutlookEvent = async (
    event: { title: string; date: string; time: string; description: string },
    calendarId?: string,
  ) => {
    if (!outlookAccessToken) {
      throw new Error("Outlook Calendar is not connected. Connect first.");
    }

    const targetCalendarId =
      calendarId || defaultScheduleOutlookCalendarId || "primary";
    const calIdEncoded =
      targetCalendarId === "primary"
        ? "me/calendar"
        : `me/calendars/${encodeURIComponent(targetCalendarId)}`;
    const startDateTime = `${event.date}T${event.time}:00`;
    const startTimeStamp = new Date(startDateTime).getTime();
    const endDateTime = new Date(startTimeStamp + 60 * 60 * 1000).toISOString();

    try {
      const response = await fetch(
        `https://graph.microsoft.com/v1.0/${calIdEncoded}/events`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${outlookAccessToken}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            subject: event.title,
            body: {
              contentType: "text",
              content:
                event.description + " (Importado via Gestor de Vida Coletivo)",
            },
            start: {
              dateTime: startDateTime,
              timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            },
            end: {
              dateTime: endDateTime.substring(0, 19),
              timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            },
          }),
        },
      );

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText || "Failed to create Outlook Calendar event");
      }

      const created = await response.json();
      await fetchOutlookEventsInternal(outlookAccessToken);
      return created;
    } catch (e) {
      console.error("Error creating Outlook Calendar event:", e);
      throw e;
    }
  };

  const deleteOutlookEvent = async (eventId: string, calendarId?: string) => {
    if (!outlookAccessToken) return;
    try {
      const response = await fetch(
        `https://graph.microsoft.com/v1.0/me/events/${eventId}`,
        {
          method: "DELETE",
          headers: {
            Authorization: `Bearer ${outlookAccessToken}`,
          },
        },
      );
      if (response.ok) {
        await fetchOutlookEventsInternal(outlookAccessToken);
      } else {
        const errText = await response.text();
        console.error("Failed to delete Outlook event:", errText);
      }
    } catch (e) {
      console.error("Error deleting Outlook event:", e);
    }
  };

  const hideOutlookEvent = async (eventId: string) => {
    if (!userId) return;
    try {
      const updatedIds = [...hiddenOutlookEventIds, eventId];
      setHiddenOutlookEventIds(updatedIds);
      await setDoc(
        doc(db, "users", userId),
        { hiddenOutlookEventIds: updatedIds },
        { merge: true },
      );
    } catch (err) {
      console.error("Error hiding Outlook Calendar event locally:", err);
    }
  };

  const manualSync = async () => {
    setIsSaving(true);
    try {
      // Force refreshing google events if connected
      if (googleAccessToken) {
        await fetchGoogleEventsInternal(googleAccessToken);
      }

      // Perform a backup timestamp merge on firebase database
      if (userId) {
        await setDoc(
          doc(db, "users", userId),
          {
            lastSyncedAt: new Date().toISOString(),
          },
          { merge: true },
        );

        const nowIso = new Date().toISOString();
        // Save current active state directly from React memory for 100% up-to-date manual synchronization
        const payload = {
          userId,
          userConfig,
          transactions,
          appointments,
          goals,
          habits,
          medications,
          waterLogs,
          inventoryItems,
          secondBrainNotes,
          timestamp: nowIso,
          lastUpdated: nowIso,
        };
        
        localStorage.setItem(`firebase_last_pushed_sync_${userId}`, nowIso);
        localStorage.setItem(`user_config_last_updated_${userId}`, nowIso);

        try {
          const payloadStr = JSON.stringify(payload);
          await setDoc(doc(db, "user_backups", userId), {
            payload: payloadStr,
            lastUpdated: payload.lastUpdated,
          });
          console.log(
            "☁️ [Firebase Sync]: Backup manual salvo com sucesso no Firestore.",
          );
        } catch (err) {
          console.error("Erro ao salvar backup no Firestore:", err);
        }
      }

      // Provide an elegant satisfying loader feel
      await new Promise((resolve) => setTimeout(resolve, 800));
      setLastSaved(new Date());
      setFailedSyncAttempts(0);
    } catch (e) {
      console.error("Manual synchronization failed:", e);
      setFailedSyncAttempts((prev) => prev + 1);
      throw e;
    } finally {
      setIsSaving(false);
    }
  };

  // Autosave and inactivity detection system
  useEffect(() => {
    if (!userId) return;

    let lastInteraction = Date.now();
    const handleActivity = () => {
      lastInteraction = Date.now();
      setAutoSaveStatus((prev) => (prev === "idle_user" ? "idle" : prev));
    };

    window.addEventListener("mousemove", handleActivity);
    window.addEventListener("keydown", handleActivity);
    window.addEventListener("mousedown", handleActivity);
    window.addEventListener("scroll", handleActivity);
    window.addEventListener("touchstart", handleActivity);

    const triggerAutoSave = async (source: "periodic" | "inactivity") => {
      setAutoSaveStatus("saving");
      try {
        // 1. Update standard sync in Firestore
        try {
          await setDoc(
            doc(db, "users", userId),
            {
              lastSyncedAt: new Date().toISOString(),
              lastAutosavedAt: new Date().toISOString(),
              autosaveSource: source,
            },
            { merge: true },
          );

          const nowIso = new Date().toISOString();
          // Use current active state directly from React memory for robust real-time auto-synchronization
          const payload = {
            userId,
            userConfig,
            transactions,
            appointments,
            goals,
            habits,
            medications,
            waterLogs,
            inventoryItems,
            secondBrainNotes,
            timestamp: nowIso,
            lastUpdated: nowIso,
          };
          
          localStorage.setItem(`firebase_last_pushed_sync_${userId}`, nowIso);
          localStorage.setItem(`user_config_last_updated_${userId}`, nowIso);

          try {
            const payloadStr = JSON.stringify(payload);
            await setDoc(doc(db, "user_backups", userId), {
              payload: payloadStr,
              lastUpdated: payload.lastUpdated,
            });
            console.log(
              "☁️ [Firebase Sync]: Auto-sync salvo com sucesso no Firestore.",
            );
          } catch (err) {
            console.error("Erro ao salvar auto-sync no Firestore:", err);
          }
        } catch (setDocErr) {
          handleFirestoreError(
            setDocErr,
            OperationType.WRITE,
            `users/${userId}`,
            userId,
          );
        }

        // 2. Backup chat history to cloud if available in localStorage
        const chatHistory = localStorage.getItem("life_manager_chat_history");
        if (chatHistory) {
          try {
            const parsed = JSON.parse(chatHistory);
            try {
              await setDoc(
                doc(db, "users", userId),
                {
                  cloudChatBackup: parsed,
                  cloudChatBackupUpdatedAt: new Date().toISOString(),
                },
                { merge: true },
              );
            } catch (chatBackupErr) {
              handleFirestoreError(
                chatBackupErr,
                OperationType.WRITE,
                `users/${userId}`,
                userId,
              );
            }
          } catch (jsonErr) {
            console.error(
              "Failed to parse chat history during autosave",
              jsonErr,
            );
          }
        }

        const now = new Date();
        setLastSaved(now);
        setLastAutoSavedAt(now);
        setAutoSaveStatus("saved");
        setFailedSyncAttempts(0);

        setTimeout(() => {
          setAutoSaveStatus("idle");
        }, 3000);
      } catch (err) {
        console.error("Autosave to cloud failed:", err);
        setAutoSaveStatus("idle");
        setFailedSyncAttempts((prev) => prev + 1);
        throw err;
      }
    };

    // Every second, check if we need to trigger autosave.
    // Ensure we don't save too frequently if inactivity triggers.
    let lastPeriodicSave = Date.now();
    let lastInactivitySave = 0;

    const intervalId = setInterval(() => {
      const now = Date.now();

      // A. Periodic check (every 30 seconds since last periodic save)
      if (now - lastPeriodicSave >= 30000) {
        lastPeriodicSave = now;
        triggerAutoSave("periodic");
        return;
      }

      // B. Inactivity check (15 seconds of no user events)
      // Check if user is idle for 15s AND we haven't autosaved for inactivity in the last 30s
      if (now - lastInteraction >= 15000 && now - lastInactivitySave >= 30000) {
        lastInactivitySave = now;
        setAutoSaveStatus("idle_user");
        triggerAutoSave("inactivity");
      }
    }, 1000);

    return () => {
      window.removeEventListener("mousemove", handleActivity);
      window.removeEventListener("keydown", handleActivity);
      window.removeEventListener("mousedown", handleActivity);
      window.removeEventListener("scroll", handleActivity);
      window.removeEventListener("touchstart", handleActivity);
      clearInterval(intervalId);
    };
  }, [userId, user]);

  const clearAllData = async () => {
    await performWrite(async () => {
      const collectionsToClear = [
        "transactions",
        "appointments",
        "goals",
        "habits",
        "water_logs",
        "inventory",
        "second_brain_vault",
      ];

      // Persist the clear flag in Firestore
      await setDoc(
        doc(db, "users", userId),
        { isDataCleared: true },
        { merge: true },
      );
      localStorage.setItem(`life_manager_cleared_${userId}`, "true");

      const promises = collectionsToClear.map(async (colName) => {
        try {
          const q = query(
            collection(db, colName),
            where("userId", "==", userId),
          );
          const snapshot = await getDocs(q);
          const deletes = snapshot.docs.map((docSnap) =>
            deleteDoc(doc(db, colName, docSnap.id)),
          );
          await Promise.all(deletes);
        } catch (e) {
          console.error(`Error clearing collection ${colName}:`, e);
        }
      });

      await Promise.all(promises);
    });
  };

  // Local emergency backup to IndexedDB after items load or when state changes
  useEffect(() => {
    if (loading || !userId) return;

    saveLocalBackup(userId, {
      userConfig,
      transactions,
      appointments,
      goals,
      habits,
      medications,
      waterLogs,
      inventoryItems,
      secondBrainNotes,
    }).catch((err) => {
      console.error("Failed to write IndexedDB emergency backup:", err);
    });
  }, [
    loading,
    userId,
    userConfig,
    transactions,
    appointments,
    goals,
    habits,
    medications,
    waterLogs,
    inventoryItems,
    secondBrainNotes,
  ]);

  // Dedicated Read-Ahead Cache saver for configurations and finance data
  useEffect(() => {
    if (!userId) return;

    saveReadAheadCache(userId, userConfig, transactions)
      .then(() => {
        console.log(
          "⚡ [Read-Ahead Cache]: Configurações e Finanças atualizadas com sucesso no IndexedDB.",
        );
        // Synchronously save to localStorage for subsequent instantaneous app boots
        if (userConfig && validateUserConfig(userConfig)) {
          localStorage.setItem(
            `life_manager_config_cache_${userId}`,
            JSON.stringify(userConfig),
          );

          // Only update modification timestamp if it wasn't just set by a server sync (to prevent loop)
          const isFromSync =
            localStorage.getItem(`__config_sync_in_progress_${userId}`) ===
            "true";
          if (!isFromSync) {
            localStorage.setItem(
              `user_config_last_updated_${userId}`,
              new Date().toISOString(),
            );
          } else {
            localStorage.removeItem(`__config_sync_in_progress_${userId}`);
          }
        }
        if (transactions && validateTransactions(transactions)) {
          localStorage.setItem(
            `life_manager_transactions_cache_${userId}`,
            JSON.stringify(transactions),
          );
        }
      })
      .catch((err) => {
        console.error(
          "⚡ [Read-Ahead Cache]: Erro ao salvar configurações/finanças:",
          err,
        );
      });
  }, [userId, userConfig, transactions]);

  // Listen for background heartbeat synchronization updates
  useEffect(() => {
    if (!userId) return;

    const handleSyncUpdate = (e: Event) => {
      const customEvent = e as CustomEvent;
      if (customEvent.detail) {
        console.log(
          "⚡ [Context Sync Listener]: Recebida nova configuração vinda do servidor.",
        );
        // Set a flag so our save effect doesn't think this is a new local edit
        localStorage.setItem(`__config_sync_in_progress_${userId}`, "true");
        setUserConfig(customEvent.detail);
      }
    };

    const handleFullSyncUpdate = (e: Event) => {
      const customEvent = e as CustomEvent;
      if (customEvent.detail) {
        const d = customEvent.detail;
        console.log(
          "⚡ [Context Full Sync Listener]: Recebida sincronização completa vinda do servidor.",
        );
        localStorage.setItem(`__config_sync_in_progress_${userId}`, "true");
        if (d.userConfig) setUserConfig(d.userConfig);
        if (d.appointments) setAppointments(d.appointments);
        if (d.transactions) setTransactions(d.transactions);
        if (d.goals) setGoals(d.goals);
        if (d.waterLogs) setWaterLogs(d.waterLogs);
        if (d.medications) setMedications(d.medications);
        if (d.inventoryItems) setInventoryItems(d.inventoryItems);
        if (d.secondBrainNotes) setSecondBrainNotes(d.secondBrainNotes);
      }
    };

    window.addEventListener("user-config-synchronized", handleSyncUpdate);
    window.addEventListener("full-data-synchronized", handleFullSyncUpdate);
    return () => {
      window.removeEventListener("user-config-synchronized", handleSyncUpdate);
      window.removeEventListener(
        "full-data-synchronized",
        handleFullSyncUpdate,
      );
    };
  }, [userId]);

  const restoreFromBackup = async (): Promise<boolean> => {
    try {
      const backup = await getLocalBackup(userId);
      if (!backup) {
        console.warn("No local backup found for user ID:", userId);
        return false;
      }

      if (backup.userConfig) {
        setUserConfig(backup.userConfig);
      }
      setTransactions(backup.transactions || []);
      setAppointments(backup.appointments || []);
      setGoals(backup.goals || []);
      setHabits(backup.habits || []);
      setWaterLogs(backup.waterLogs || []);
      setInventoryItems(backup.inventoryItems || []);
      setSecondBrainNotes(backup.secondBrainNotes || []);

      setFailedSyncAttempts(0);
      return true;
    } catch (err) {
      console.error("Error restoring from backup:", err);
      return false;
    }
  };

  return (
    <LifeManagerContext.Provider
      value={{
        userId,
        changeUserId,
        transactions,
        appointments,
        goals,
        habits,
        loading,
        isSaving,
        lastSaved,
        autoSaveStatus,
        lastAutoSavedAt,

        // Auth & Family details
        user,
        userConfig,
        activeMember,
        isAuthLoading,
        loginWithGoogle,
        loginWithEmail,
        registerWithEmail,
        logout,
        setActiveMember,
        addFamilyMember,
        deleteFamilyMember,
        updateFamilyMemberGPS,
        updateNotificationSettings,
        updateDashboardSettings,
        updateUserPhysicalData,

        addTransaction,
        deleteTransaction,
        updateTransaction,
        addAppointment,
        deleteAppointment,
        toggleAppointmentCompleted,
        addGoal,
        deleteGoal,
        updateGoalProgress,
        updateGoalFields,
        addHabit,
        deleteHabit,
        toggleHabitForDate,

        medications,
        addMedication,
        deleteMedication,
        toggleMedicationTaken,

        waterLogs,
        addWaterLog,
        deleteWaterLog,

        inventoryItems,
        addInventoryItem,
        updateInventoryItem,
        deleteInventoryItem,

        secondBrainNotes,
        addSecondBrainNote,
        updateSecondBrainNote,
        deleteSecondBrainNote,

        // Google Calendar Integration
        googleAccessToken,
        googleEvents: googleEvents.filter(
          (gev) => !hiddenGoogleEventIds.includes(gev.id),
        ),
        googleCalendars,
        selectedGoogleCalendarIds,
        googleCalendarAlertIds,
        defaultScheduleGoogleCalendarId,
        updateGoogleCalendarSelection,
        updateGoogleCalendarAlertSelection,
        hiddenGoogleEventIds,
        isGoogleAuthLoading,
        isGoogleAuthExpired,
        connectGoogleCalendar,
        fetchGoogleEvents,
        addGoogleEvent,
        deleteGoogleEvent,
        hideGoogleEvent,
        disconnectGoogleCalendar,
        createSharedGoogleCalendar,
        shareGoogleCalendarWithEmail,

        // Outlook Calendar Integration
        outlookAccessToken,
        outlookEvents: outlookEvents.filter(
          (oev) => !hiddenOutlookEventIds.includes(oev.id),
        ),
        outlookCalendars,
        selectedOutlookCalendarIds,
        defaultScheduleOutlookCalendarId,
        updateOutlookCalendarSelection,
        hiddenOutlookEventIds,
        isOutlookAuthLoading,
        connectOutlookCalendar,
        fetchOutlookEvents,
        addOutlookEvent,
        deleteOutlookEvent,
        hideOutlookEvent,
        disconnectOutlookCalendar,

        manualSync,
        clearAllData,
        failedSyncAttempts,
        restoreFromBackup,
      }}
    >
      {children}
    </LifeManagerContext.Provider>
  );
};

export const useLifeManager = () => {
  const context = useContext(LifeManagerContext);
  if (context === undefined) {
    throw new Error("useLifeManager must be used within a LifeManagerProvider");
  }
  return context;
};
