const TOKEN_KEY = 'itzaydin.token';
const LEGACY_TOKEN_KEY = 'aycore.token';
const buyDraftKey = 'itzaydin.buyDraft';
const legacyBuyDraftKey = 'aycore.buyDraft';

const memory = {
    user: null,
    settings: null,
};

export function getToken() {
    try {
        const current = sessionStorage.getItem(TOKEN_KEY) || '';
        if (current) return current;
        const legacy = sessionStorage.getItem(LEGACY_TOKEN_KEY) || '';
        if (legacy) { sessionStorage.setItem(TOKEN_KEY, legacy); sessionStorage.removeItem(LEGACY_TOKEN_KEY); }
        return legacy;
    } catch (_) { return ''; }
}
export function setToken(token) {
    try { sessionStorage.setItem(TOKEN_KEY, token); sessionStorage.removeItem(LEGACY_TOKEN_KEY); } catch (_) {}
}
export function clearToken() {
    try { sessionStorage.removeItem(TOKEN_KEY); sessionStorage.removeItem(LEGACY_TOKEN_KEY); } catch (_) {}
}

export function getUser() { return memory.user; }
export function setUser(u) { memory.user = u; }


export function getBuyDraft() {
    try {
        let raw = sessionStorage.getItem(buyDraftKey);
        if (!raw) {
            raw = sessionStorage.getItem(legacyBuyDraftKey);
            if (raw) { sessionStorage.setItem(buyDraftKey, raw); sessionStorage.removeItem(legacyBuyDraftKey); }
        }
        return raw ? JSON.parse(raw) : { step: 1 };
    } catch (_) { return { step: 1 }; }
}
export function setBuyDraft(draft) {
    try { sessionStorage.setItem(buyDraftKey, JSON.stringify(draft)); sessionStorage.removeItem(legacyBuyDraftKey); } catch (_) {}
}
export function clearBuyDraft() {
    try { sessionStorage.removeItem(buyDraftKey); sessionStorage.removeItem(legacyBuyDraftKey); } catch (_) {}
}

