import { useState, useEffect, useCallback } from 'react';

const API_BASE = import.meta.env.VITE_API_URL || '';

function fmtPrice(n, symbol) {
  if (n == null) return '—';
  // VIX and TNX are usually shown raw without $
  if (symbol === '^VIX' || symbol === '^TNX' || symbol === 'DX-Y.NYB') {
    return n.toFixed(2);
  }
  return `$${n.toFixed(2)}`;
}

export default function MacroIndicatorsPanel() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

  const fetchData = useCallback(async () => {
    try {
      const res = await fetch(`${API_BASE}/api/market/macro`);
      const json = await res.json();
      if (json.success) {
        setData(json.data);
      }
    } catch (err) {
      console.error('[MacroIndicatorsPanel] Error fetching macro data:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 90000); // 90 seconds
    return () => clearInterval(interval);
  }, [fetchData]);

  if (loading && data.length === 0) {
    return (
      <div className="flex gap-4 overflow-x-hidden p-1 opacity-50 mb-6">
        {Array.from({ length: 6 }).map((_, i) => (
          <div key={i} className="animate-pulse bg-slate-900 border border-slate-800 rounded-xl min-w-[140px] h-[72px]" />
        ))}
      </div>
    );
  }

  if (data.length === 0) return null;

  function fmtPct(n) {
    if (n == null) return '—';
    return (n >= 0 ? '+' : '') + n.toFixed(2) + '%';
  }

  function getColor(n) {
    if (n == null) return 'text-slate-500';
    return n >= 0 ? 'text-emerald-400' : 'text-red-400';
  }

  return (
    <div className="mb-6">
      <div className="text-xs font-bold text-slate-500 mb-3 uppercase tracking-wider pl-1">Global Macro Context</div>
      <div className="flex gap-3 overflow-x-auto pb-4 scrollbar-thin scrollbar-thumb-slate-700 scrollbar-track-transparent">
        {data.map((item) => (
          <div 
            key={item.symbol} 
            className="bg-slate-900 border border-slate-700/50 rounded-xl p-3 min-w-[200px] flex-shrink-0 flex flex-col justify-between hover:bg-slate-800 transition-colors shadow-sm"
          >
            <div className="flex justify-between items-start mb-2">
              <div className="text-xs font-semibold text-slate-400">{item.name}</div>
              <span className="text-white font-mono font-bold text-sm">
                {fmtPrice(item.price, item.symbol)}
              </span>
            </div>
            <div className="grid grid-cols-4 gap-1 text-[10px] text-center">
              <div className="flex flex-col bg-slate-800/50 rounded p-1">
                <span className="text-slate-500 mb-0.5">1D</span>
                <span className={`font-semibold tabular-nums ${getColor(item.change_pct)}`}>{fmtPct(item.change_pct)}</span>
              </div>
              <div className="flex flex-col bg-slate-800/50 rounded p-1">
                <span className="text-slate-500 mb-0.5">1W</span>
                <span className={`font-semibold tabular-nums ${getColor(item.change_1w)}`}>{fmtPct(item.change_1w)}</span>
              </div>
              <div className="flex flex-col bg-slate-800/50 rounded p-1">
                <span className="text-slate-500 mb-0.5">1M</span>
                <span className={`font-semibold tabular-nums ${getColor(item.change_1m)}`}>{fmtPct(item.change_1m)}</span>
              </div>
              <div className="flex flex-col bg-slate-800/50 rounded p-1">
                <span className="text-slate-500 mb-0.5">1Y</span>
                <span className={`font-semibold tabular-nums ${getColor(item.change_1y)}`}>{fmtPct(item.change_1y)}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
