import * as Linking from 'expo-linking';
import { useEffect } from 'react';
import { useRouter } from 'expo-router';

/**
 * Build a deep link to a specific race that opens tip-builder.
 * @example tipsharks://race/abc123
 */
export function buildRaceLink(raceId: string): string {
  return Linking.createURL(`race/${raceId}`);
}

/**
 * Build a deep link to a specific tip that opens tip-result.
 * @example tipsharks://tip/abc123
 */
export function buildTipLink(tipId: string): string {
  return Linking.createURL(`tip/${tipId}`);
}

/**
 * Parse a deep link URL and route to the appropriate screen.
 *
 * Supported patterns:
 * - tipsharks://race/{raceId}    → /tip-builder?raceId={raceId}
 * - tipsharks://tip/{tipId}      → /tip-result?tipId={tipId}
 */
function handleDeepLink(url: string, router: ReturnType<typeof useRouter>) {
  const parsed = Linking.parse(url);

  if (!parsed.path) return;

  const segments = parsed.path.split('/');
  const [type, id] = segments;

  if (type === 'race' && id) {
    router.push(`/tip-builder?raceId=${id}`);
  } else if (type === 'tip' && id) {
    router.push(`/tip-result?tipId=${id}`);
  }
}

/**
 * Hook that listens for incoming deep links and navigates accordingly.
 * Must be called once in the root layout to cover the entire app.
 */
export function useDeepLinkHandler() {
  const router = useRouter();

  useEffect(() => {
    // Handle incoming URLs while the app is already open
    const subscription = Linking.addEventListener('url', (event) => {
      handleDeepLink(event.url, router);
    });

    // Handle initial URL when the app was cold-started via a deep link
    Linking.getInitialURL().then((url) => {
      if (url) {
        handleDeepLink(url, router);
      }
    });

    return () => {
      subscription.remove();
    };
  }, [router]);
}
