import { nextTick, ref } from 'vue';

export interface BetLocateTarget {
  matchId: string;
  selectionId: string;
  marketId?: string;
  marketType: string;
}

const pendingLocate = ref<BetLocateTarget | null>(null);

export function useDesktopBetLocate() {
  function requestLocate(target: BetLocateTarget) {
    pendingLocate.value = { ...target };
  }

  function clearLocate() {
    pendingLocate.value = null;
  }

  return {
    pendingLocate,
    requestLocate,
    clearLocate,
  };
}

export async function scrollToBetSelection(selectionId: string) {
  await nextTick();
  await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));

  const escaped = typeof CSS !== 'undefined' && CSS.escape
    ? CSS.escape(selectionId)
    : selectionId.replace(/"/g, '\\"');
  const el = document.querySelector(`[data-bet-selection-id="${escaped}"]`) as HTMLElement | null;
  if (!el) return false;

  el.scrollIntoView({ behavior: 'smooth', block: 'center' });
  el.classList.add('bet-locate-flash');
  window.setTimeout(() => el.classList.remove('bet-locate-flash'), 2200);
  return true;
}
