import { useEffect, useState } from 'react';
import client from '../api/client';

const cacheMap = new Map();
const CACHE_TTL = 60 * 1000;

function getCacheKey(phrase) {
  return phrase ? `w_${phrase.slice(0, 16)}` : '_global_';
}

export default function useStakingRates(phrase) {
  const cacheKey = getCacheKey(phrase);
  const cached = cacheMap.get(cacheKey);
  const [rates, setRates] = useState(cached?.data || null);
  const [loading, setLoading] = useState(!cached?.data);
  const [error, setError] = useState(null);

  useEffect(() => {
    let ignore = false;
    const entry = cacheMap.get(cacheKey);

    const loadRates = async () => {
      setLoading(true);
      try {
        const params = phrase ? { phrase } : {};
        const response = await client.get('/api/staking/rates', { params });
        const data = response.data?.data || {};
        cacheMap.set(cacheKey, { data, timestamp: Date.now() });
        if (!ignore) {
          setRates(data);
          setError(null);
        }
      } catch (err) {
        if (!ignore) {
          setError(err);
        }
      } finally {
        if (!ignore) {
          setLoading(false);
        }
      }
    };

    if (!entry?.data || Date.now() - entry.timestamp > CACHE_TTL) {
      loadRates();
    } else {
      setRates(entry.data);
      setLoading(false);
    }

    return () => {
      ignore = true;
    };
  }, [phrase, cacheKey]);

  return { rates: rates || {}, loading, error };
}

