"use client";

import { useSyncExternalStore } from "react";
import { NO_UPDATE, type UpdateDecision, type UpdateOffer } from "./policy";

// What the update prompt shows, shared by the UI, the back button and the checker.

// "Later" hides an optional update this long, per build (a newer release shows at once).
const SNOOZE_MS = 24 * 60 * 60 * 1000;
const SNOOZE_KEY = "native-update-snoozed";

let state: UpdateDecision = NO_UPDATE;
const listeners = new Set<() => void>();

export function getNativeUpdateState(): UpdateDecision {
    return state;
}

export function subscribeNativeUpdateState(listener: () => void): () => void {
    listeners.add(listener);
    return () => { listeners.delete(listener); };
}

export function useNativeUpdateState(): UpdateDecision {
    return useSyncExternalStore(subscribeNativeUpdateState, getNativeUpdateState, () => NO_UPDATE);
}

/** Apply a fresh decision from the checker. Required updates ignore any snooze. */
export function applyDecision(decision: UpdateDecision): void {
    const next = decision.kind === "optional" && isSnoozed(decision.offer) ? NO_UPDATE : decision;
    if (sameDecision(state, next)) return;

    state = next;
    listeners.forEach((listener) => listener());
}

/** The user chose "later" on an optional update. */
export function snoozeOptionalUpdate(offer: UpdateOffer): void {
    try {
        localStorage.setItem(SNOOZE_KEY, JSON.stringify({ build: offer.latestBuild, until: Date.now() + SNOOZE_MS }));
    } catch { }

    if (state.kind === "optional") applyDecision(NO_UPDATE);
}

// localStorage is fine here: losing it only means the prompt shows once more.
function isSnoozed(offer: UpdateOffer): boolean {
    try {
        const raw = localStorage.getItem(SNOOZE_KEY);
        if (!raw) return false;
        const { build, until } = JSON.parse(raw);
        return build === offer.latestBuild && typeof until === "number" && Date.now() < until;
    } catch {
        return false;
    }
}

function sameDecision(a: UpdateDecision, b: UpdateDecision): boolean {
    if (a.kind !== b.kind) return false;
    if (a.kind === "none" || b.kind === "none") return true;
    return a.offer.latestBuild === b.offer.latestBuild && a.offer.link.url === b.offer.link.url;
}
