import { computed, toValue, type MaybeRefOrGetter } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const FALLBACK_RULES: Array<{ test: (path: string) => boolean; fallback: string }> = [
  { test: (p) => /^\/wallet\/transactions\//.test(p), fallback: '/wallet/detail' },
  { test: (p) => p.startsWith('/wallet/recharge/history'), fallback: '/wallet' },
  { test: (p) => p === '/wallet/recharge', fallback: '/wallet' },
  { test: (p) => p === '/wallet/detail', fallback: '/wallet' },
  { test: (p) => p === '/wallet/cashbacks' || p === '/profile/cashbacks', fallback: '/wallet' },
  { test: (p) => p === '/profile/edit', fallback: '/wallet' },
  { test: (p) => p.startsWith('/bets/'), fallback: '/bets' },
  { test: (p) => p.startsWith('/match/'), fallback: '/bet' },
  { test: (p) => p.startsWith('/outright/'), fallback: '/bet' },
  { test: (p) => p.startsWith('/announcements/'), fallback: '/announcements' },
  { test: (p) => p.startsWith('/messages/'), fallback: '/messages' },
  { test: (p) => p === '/wallet', fallback: '/' },
  { test: (p) => p === '/bets', fallback: '/' },
];

export function resolveSmartBackFallback(path: string): string {
  for (const rule of FALLBACK_RULES) {
    if (rule.test(path)) return rule.fallback;
  }
  return '/';
}

export function useSmartBack(fallback?: MaybeRefOrGetter<string | undefined>) {
  const router = useRouter();
  const route = useRoute();

  const resolvedFallback = computed(
    () => toValue(fallback) ?? resolveSmartBackFallback(route.path),
  );

  function goBack() {
    const state = window.history.state as { back?: string | null } | null;
    if (state?.back != null) {
      router.back();
      return;
    }
    void router.push(resolvedFallback.value);
  }

  return { goBack, fallback: resolvedFallback };
}
