"use client"

import { getAuthValue, setAuthValue } from "@/lib/services/auth.service"

// A coach's invite (technical-plan 4.7): rangook.ir/marjan → /c/?slug=marjan, or any page
// opened with ?ref=marjan / ?ref=MARJAN. The slug or code is kept until the next login and sent
// as `ref` on /auth/verify, which makes the learner that coach's learner for 12 months.
// Stored like the auth values: a cookie on the website, native storage in the apps.

const REF_KEY = "ref"

/** An invite older than this is dropped. */
const MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000

/** Slugs (marjan, marjan-k) and codes (MARJAN); anything else is ignored. */
const REF_PATTERN = /^[A-Za-z0-9-]{3,64}$/

/**
 * Keeps the invite from this URL, if it has one: ?ref= on any page, or ?slug= on the /c/
 * landing only (other pages, like /coach/view?slug=, use slug for something else).
 */
export function captureReferral(
    search: string = typeof window !== "undefined" ? window.location.search : "",
    pathname: string = typeof window !== "undefined" ? window.location.pathname : "",
): void {
    const params = new URLSearchParams(search)
    const onLanding = /^\/c\/?$/.test(pathname)
    const ref = (params.get("ref") ?? (onLanding ? params.get("slug") : null) ?? "").trim()

    if (!REF_PATTERN.test(ref)) return

    // The latest invite wins until login.
    setAuthValue(REF_KEY, `${ref}|${Date.now()}`)
}

/** The kept invite for the login request, or undefined when there is none or it is too old. */
export function pendingReferral(): string | undefined {
    const stored = getAuthValue(REF_KEY)
    if (!stored) return undefined

    const [ref, at] = stored.split("|")
    if (!REF_PATTERN.test(ref ?? "") || !(Date.now() - Number(at) < MAX_AGE_MS)) {
        clearReferral()
        return undefined
    }

    return ref
}

/** After a successful login: the server has recorded it. */
export function clearReferral(): void {
    setAuthValue(REF_KEY, null)
}
