// eveai-token-manager.js
class EveAITokenManager extends EventTarget {
    constructor() {
        super();
        this.token = null;
        this.checkInterval = null;
        this.isRefreshing = false;
        this.refreshThreshold = 60; // Refresh token if less than 60s remaining
    }

    // Initialize with a token
    async initialize(token) {
        this.token = token;
        this.startTokenCheck();
        this.dispatchEvent(new CustomEvent('tokenChanged', { detail: { token } }));
    }

    // Start periodic token verification
    startTokenCheck() {
        if (this.checkInterval) {
            clearInterval(this.checkInterval);
        }

        this.checkInterval = setInterval(async () => {
            await this.verifyAndRefreshToken();
        }, 5000); // Check every 5 seconds
    }

    // Verify token and refresh if needed
    async verifyAndRefreshToken() {
        if (!this.token || this.isRefreshing) return;

        try {
            const response = await fetch(`${this.proxyUrl}/verify`, {
                headers: {
                    'Authorization': `Bearer ${this.token}`
                }
            });

            if (!response.ok) {
                throw new Error('Token verification failed');
            }

            const data = await response.json();
            if (data.expires_in < this.refreshThreshold) {
                await this.refreshToken();
            }
        } catch (error) {
            this.handleTokenError(error);
        }
    }

    // Handle any token errors
    handleTokenError(error) {
        this.dispatchEvent(new CustomEvent('tokenError', { detail: { error } }));
        this.token = null;
        if (this.checkInterval) {
            clearInterval(this.checkInterval);
        }
    }

    // Clean up
    destroy() {
        if (this.checkInterval) {
            clearInterval(this.checkInterval);
        }
        this.token = null;
    }
}