import { getTodayISOString } from './dateUtils';

const DAILY_PLAYED_PREFIX = 'hoerdle_daily_played_';
const EXTRA_POPOVER_PREFIX = 'hoerdle_extra_puzzles_shown_';

function getTodayKey(prefix: string): string | null {
    if (typeof window === 'undefined') return null;
    const today = getTodayISOString();
    return `${prefix}${today}`;
}

export function markDailyPuzzlePlayedToday(genreKey: string) {
    const storageKey = getTodayKey(DAILY_PLAYED_PREFIX);
    if (!storageKey) return;

    try {
        const raw = window.localStorage.getItem(storageKey);
        const list: string[] = raw ? JSON.parse(raw) : [];
        if (!list.includes(genreKey)) {
            list.push(genreKey);
            window.localStorage.setItem(storageKey, JSON.stringify(list));
        }
    } catch (e) {
        console.warn('[extraPuzzles] Failed to mark daily puzzle as played', e);
    }
}

export function hasPlayedAllDailyPuzzlesForToday(requiredGenreKeys: string[]): boolean {
    const storageKey = getTodayKey(DAILY_PLAYED_PREFIX);
    if (!storageKey) return false;

    try {
        const raw = window.localStorage.getItem(storageKey);
        const played: string[] = raw ? JSON.parse(raw) : [];
        if (!Array.isArray(played) || played.length === 0) {
            return false;
        }
        return requiredGenreKeys.every(key => played.includes(key));
    } catch (e) {
        console.warn('[extraPuzzles] Failed to read played puzzles', e);
        return false;
    }
}

export function hasSeenExtraPuzzlesPopoverToday(): boolean {
    const storageKey = getTodayKey(EXTRA_POPOVER_PREFIX);
    if (!storageKey) return false;

    try {
        return window.localStorage.getItem(storageKey) === 'true';
    } catch (e) {
        console.warn('[extraPuzzles] Failed to read popover state', e);
        return false;
    }
}

export function markExtraPuzzlesPopoverShownToday() {
    const storageKey = getTodayKey(EXTRA_POPOVER_PREFIX);
    if (!storageKey) return;

    try {
        window.localStorage.setItem(storageKey, 'true');
    } catch (e) {
        console.warn('[extraPuzzles] Failed to persist popover state', e);
    }
}


