import React, { useEffect, useState, useCallback } from 'react';
import { getMusicCredits } from '../../../api';

const CreditsBadge = () => {
    const [credits, setCredits] = useState(null);

    const fetchCredits = useCallback(async () => {
        try {
            const data = await getMusicCredits();
            setCredits(data);
        } catch {}
    }, []);

    useEffect(() => {
        fetchCredits();
        const interval = setInterval(fetchCredits, 30000);
        return () => clearInterval(interval);
    }, [fetchCredits]);

    if (!credits) return null;

    const remaining = credits.credits_left ?? credits.remaining ?? credits.data ?? null;
    if (remaining == null) return null;

    const isLow = remaining <= 10;

    return (
        <div className={`ms-credits-badge ${isLow ? 'is-low' : ''}`}>
            <span className="ms-credits-badge__icon">⚡</span>
            <span className="ms-credits-badge__value">{remaining}</span>
            <span className="ms-credits-badge__label">credits</span>
        </div>
    );
};

export default CreditsBadge;
