import React from 'react';
import CountUp from 'react-countup';
import { useInView } from 'react-intersection-observer';
import '../styles/CounterCard.css';

const CounterCard = ({ count, label, icon }) => {
  // Extract numeric part from count string (e.g. "200+" => 200)
  const numericCount = typeof count === 'string' ? parseInt(count, 10) : count;

  // Check if original count string ends with '+'
  const hasPlus = typeof count === 'string' && count.trim().endsWith('+');

  // Intersection Observer to detect when the card is visible
  const { ref, inView } = useInView({
    triggerOnce: true,  // animate only once
    threshold: 0.3      // 30% of the card visible triggers animation
  });

  return (
    <div className="counter-card" ref={ref}>
      {icon && (
        <div className="icon" style={{ fontSize: '3rem', marginBottom: '15px' }}>
          {icon}
        </div>
      )}
      <h3>
        {inView ? <CountUp end={numericCount} duration={2.5} /> : 0}
        {hasPlus && '+'}
      </h3>
      <p>{label}</p>
    </div>
  );
};

export default CounterCard;
