import { useEffect } from 'react';
import { Alert, Linking } from 'react-native';
import { checkForUpdates, wasPromptedFor, markPrompted } from '@/services/updates';

export function UpdateNotifier() {
  useEffect(() => {
    const run = async () => {
      const update = await checkForUpdates();
      if (!update || (await wasPromptedFor(update.tagName))) return;
      await markPrompted(update.tagName);
      const url = update.apkUrl ?? update.releaseUrl;
      Alert.alert(
        'Update available',
        `A new version (${update.version}) is available for download.`,
        [
          { text: 'Later', style: 'cancel' },
          {
            text: 'Download',
            onPress: () => {
              if (url) Linking.openURL(url).catch(() => {});
            },
          },
        ],
      );
    };
    run();
  }, []);

  return null;
}