'use client';

import { useEffect, useRef } from 'react';
import { useFinanzasStore } from '@/lib/store';

export function DataSync() {
  const initialized = useRef(false);

  useEffect(() => {
    async function init() {
      // Prevent double init in StrictMode
      if (initialized.current) return;
      
      try {
        const res = await fetch('/api/sync');
        // If 401 (unauthorized), stop here. User needs to login.
        if (res.status === 401) return;
        if (!res.ok) return;

        const serverData = await res.json();
        
        // Comprehensive check if server has ANY data
        const hasServerData = 
            (serverData.fixedDebts?.length ?? 0) > 0 || 
            (serverData.variableDebts?.length ?? 0) > 0 ||
            (serverData.creditCards?.length ?? 0) > 0 ||
            (serverData.incomes?.length ?? 0) > 0 ||
            (serverData.serviceBills?.length ?? 0) > 0;
        
        if (hasServerData) {
          console.log("Sync: Hydrating from Server");
          useFinanzasStore.setState(serverData);
        } else {
            // Server is empty. If we have local data, push it.
            // But verify we actually have local data worth pushing to avoid overwriting with empty defaults unnecessarily
            const localState = useFinanzasStore.getState();
            const hasLocalData = 
                localState.fixedDebts.length > 0 || 
                localState.variableDebts.length > 0 ||
                localState.creditCards.length > 0 ||
                localState.incomes.length > 0;

            if (hasLocalData) {
                console.log("Sync: Server empty, pushing Local Data");
                syncToServer(localState);
            }
        }
      } catch (e) {
        console.error("Sync init error", e);
      } finally {
        // Mark as initialized so subsequent changes trigger sync
        initialized.current = true;
      }
    }

    init();
  }, []);

  // Sync on change
  useEffect(() => {
    const unsub = useFinanzasStore.subscribe((state) => {
       // Only sync to server if we have finished initialization/hydration
       if (initialized.current) {
          syncToServer(state);
       }
    });
    return () => unsub();
  }, []);

  return null;
}

let timeout: NodeJS.Timeout;
function syncToServer(state: any) {
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    fetch('/api/sync', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(state)
    }).catch(e => console.error("Sync error", e));
  }, 2000); // Debounce 2s
}
