import { useState, useEffect } from 'react';
import { getStats, type SiteStats } from '../api';
import { ensurePageViewOnce } from '../pageView';

export default function Stats() {
  const [stats, setStats] = useState<SiteStats | null>(null);

  const load = () => {
    getStats().then(setStats).catch(() => { /* ignore */ });
  };

  useEffect(() => {
    let cancelled = false;
    (async () => {
      let ok = await ensurePageViewOnce();
      if (!ok && !cancelled) {
        await new Promise(r => setTimeout(r, 400));
        ok = await ensurePageViewOnce();
      }
      if (cancelled) return;
      load();
    })();
    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    const onVis = () => { if (document.visibilityState === 'visible') load(); };
    document.addEventListener('visibilitychange', onVis);
    return () => document.removeEventListener('visibilitychange', onVis);
  }, []);

  if (!stats) {
    return (
      <div className="stats-bar" aria-hidden>
        <div className="stat-card">
          <div className="stat-value">—</div>
          <div className="stat-label">短链</div>
        </div>
        <div className="stat-card">
          <div className="stat-value">—</div>
          <div className="stat-label">点击</div>
        </div>
        <div className="stat-card">
          <div className="stat-value">—</div>
          <div className="stat-label">浏览</div>
        </div>
      </div>
    );
  }

  const pv = typeof stats.page_views === 'number' ? stats.page_views : 0;

  return (
    <div className="stats-bar">
      <div className="stat-card">
        <div className="stat-value">{stats.total_links.toLocaleString()}</div>
        <div className="stat-label">短链</div>
      </div>
      <div className="stat-card">
        <div className="stat-value">{stats.total_clicks.toLocaleString()}</div>
        <div className="stat-label">点击</div>
      </div>
      <div className="stat-card">
        <div className="stat-value">{pv.toLocaleString()}</div>
        <div className="stat-label">浏览</div>
      </div>
    </div>
  );
}
