'use client';

import { useEffect, useRef } from 'react';
import { toast } from 'sonner';
import { hasGuestData } from '@/lib/guest-storage';
import { migrateGuestToProfile } from '@/lib/guest-migration';

export default function GuestMigration() {
  const migratedRef = useRef(false);

  useEffect(() => {
    if (typeof window === 'undefined') return;

    const token =
      localStorage.getItem('auth_token') ?? localStorage.getItem('access_token');
    if (!token || !hasGuestData() || migratedRef.current) return;

    migratedRef.current = true;

    migrateGuestToProfile(token)
      .then(({ migrated }) => {
        if (migrated > 0) {
          toast.success('Ваши чаты сохранены в профиль');
          window.dispatchEvent(new CustomEvent('gooseek:guest-migrated'));
        }
      })
      .catch(() => {
        migratedRef.current = false;
      });
  }, []);

  useEffect(() => {
    const onStorage = (e: StorageEvent) => {
      if (e.key === 'auth_token' || e.key === 'access_token') {
        const token =
          localStorage.getItem('auth_token') ??
          localStorage.getItem('access_token');
        if (token && hasGuestData()) {
          migratedRef.current = false;
        }
      }
    };
    window.addEventListener('storage', onStorage);
    return () => window.removeEventListener('storage', onStorage);
  }, []);

  return null;
}
