'use client';

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

export function DataSync() {
  // const isHydrated = useFinanzasStore(state => state._hasHydrated); 
  const store = useFinanzasStore();
  const initialized = useRef(false);

  useEffect(() => {
    async function init() {
      if (initialized.current) return;
      initialized.current = true;

      try {
        const res = await fetch('/api/sync');
        if (!res.ok) return;
        const serverData = await res.json();
        
        // Simple logic: if server has data (debts or cards or something), trust server.
        const hasServerData = serverData.fixedDebts?.length > 0 || serverData.creditCards?.length > 0;
        
        if (hasServerData) {
          console.log("Sync: Hydrating from Server");
          useFinanzasStore.setState(serverData);
        } else {
            // Server is empty, but we might have local data.
            // Push local data to server to initialize it.
            console.log("Sync: Initializing Server with Local Data");
            syncToServer(useFinanzasStore.getState());
        }
      } catch (e) {
        console.error("Sync init error", e);
      }
    }

    init();
  }, []);

  // Sync on change
  useEffect(() => {
    if (!initialized.current) return;

    const unsub = useFinanzasStore.subscribe((state) => {
       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
}
