const STORAGE_KEY = 'eligibility_user_data';
const EXPIRY_DAYS = 7;

export interface StoredUserData {
  name: string;
  email: string;
  phone: string;
  storedAt: string;
}

export const eligibilityStorage = {
  // Store user data in localStorage
  setUserData: (userData: Omit<StoredUserData, 'storedAt'>): void => {
    if (typeof window === 'undefined') return;
    
    const dataToStore: StoredUserData = {
      ...userData,
      storedAt: new Date().toISOString()
    };
    
    localStorage.setItem(STORAGE_KEY, JSON.stringify(dataToStore));
  },

  // Get user data from localStorage if not expired
  getUserData: (): StoredUserData | null => {
    if (typeof window === 'undefined') return null;
    
    const stored = localStorage.getItem(STORAGE_KEY);
    if (!stored) return null;
    
    try {
      const userData: StoredUserData = JSON.parse(stored);
      const storedAt = new Date(userData.storedAt);
      const expiryDate = new Date(storedAt.getTime() + (EXPIRY_DAYS * 24 * 60 * 60 * 1000));
      
      if (new Date() > expiryDate) {
        localStorage.removeItem(STORAGE_KEY);
        return null;
      }
      
      return userData;
    } catch (error) {
      console.error('Error parsing stored user data:', error);
      localStorage.removeItem(STORAGE_KEY);
      return null;
    }
  },

  // Clear stored user data
  clearUserData: (): void => {
    if (typeof window === 'undefined') return;
    localStorage.removeItem(STORAGE_KEY);
  },

  // Check if user data exists and is valid - FIXED VERSION
  hasValidUserData: (): boolean => {
    return eligibilityStorage.getUserData() !== null;
  }
};