// WaitlistCounter — bottom-left live count badge, fetched from Supabase.

const SUPABASE_URL      = window.TIDES_CONFIG?.SUPABASE_URL;
const SUPABASE_ANON_KEY = window.TIDES_CONFIG?.SUPABASE_ANON_KEY;

const WaitlistCounter = () => {
  const [count, setCount]               = React.useState(null);
  const [displayCount, setDisplayCount] = React.useState(0);
  const isMobile = window.innerWidth < 600 || window.matchMedia('(pointer: coarse)').matches;

  const fetchCount = async () => {
    try {
      const res = await fetch(`${SUPABASE_URL}/rest/v1/rpc/get_waitlist_count`, {
        method: 'POST',
        headers: {
          'apikey': SUPABASE_ANON_KEY,
          'Authorization': `Bearer ${SUPABASE_ANON_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({}),
      });
      const total = await res.json();
      if (typeof total === 'number' && !isNaN(total)) setCount(total + 50);
    } catch {}
  };

  React.useEffect(() => {
    fetchCount();
    const id = setInterval(fetchCount, 30000);
    return () => clearInterval(id);
  }, []);

  // animate count up on first load / change
  const prevCount = React.useRef(0);
  React.useEffect(() => {
    if (count === null) return;
    const start = prevCount.current;
    const end   = count;
    prevCount.current = end;
    if (start === end) return;
    const duration  = 1400;
    const startTime = performance.now();
    const step = (now) => {
      const p     = Math.min((now - startTime) / duration, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      setDisplayCount(Math.round(start + (end - start) * eased));
      if (p < 1) requestAnimationFrame(step);
    };
    requestAnimationFrame(step);
  }, [count]);

  if (count === null || count === 0) return null;

  return (
    <div style={{
      position: 'fixed',
      bottom: isMobile ? 14 : 28,
      left: isMobile ? 14 : 36,
      zIndex: 50,
      pointerEvents: 'none',
      animation: 'counterFadeIn 0.6s ease both',
    }}>
      <div style={{
        background: 'rgba(255,255,255,0.55)',
        backdropFilter: 'blur(14px)',
        WebkitBackdropFilter: 'blur(14px)',
        border: '1px solid rgba(26,58,74,0.12)',
        borderRadius: 999,
        padding: isMobile ? '7px 13px' : '9px 18px',
        boxShadow: '0 8px 24px -8px rgba(26,58,74,0.16), inset 0 1px 0 rgba(255,255,255,0.65)',
        display: 'flex',
        alignItems: 'center',
        gap: isMobile ? 6 : 8,
      }}>
        {/* pulsing live dot */}
        <span style={{
          width: isMobile ? 5 : 6,
          height: isMobile ? 5 : 6,
          borderRadius: '50%',
          background: 'var(--deep)',
          flexShrink: 0,
          animation: 'counterDot 2.2s ease-out infinite',
        }} />
        <span style={{
          fontSize: isMobile ? 12 : 14,
          color: 'var(--ink)',
          letterSpacing: '0.01em',
          lineHeight: 1,
          whiteSpace: 'nowrap',
        }}>
          <span style={{
            fontFamily: "'Fraunces', serif",
            fontStyle: 'italic',
            fontSize: isMobile ? 14 : 17,
            fontWeight: 400,
            marginRight: 3,
          }}>
            {displayCount.toLocaleString()}
          </span>
          <span style={{
            fontFamily: "'Instrument Sans', sans-serif",
            opacity: 0.65,
            fontSize: isMobile ? 10 : 12,
            letterSpacing: '0.04em',
          }}>
            on the waitlist
          </span>
        </span>
      </div>

      <style>{`
        @keyframes counterFadeIn {
          from { opacity: 0; transform: translateY(6px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes counterDot {
          0%   { box-shadow: 0 0 0 0 rgba(61,122,149,0.55); }
          70%  { box-shadow: 0 0 0 5px rgba(61,122,149,0); }
          100% { box-shadow: 0 0 0 0 rgba(61,122,149,0); }
        }
      `}</style>
    </div>
  );
};

window.WaitlistCounter = WaitlistCounter;
