'use client';

import { useEffect, useState } from 'react';
import SectionHead from '@/components/vyndr/SectionHead';

interface FounderCount {
  available: boolean;
  claimed?: number;
  total?: number;
}

/**
 * Founder-seat scarcity meter (§12 ClaimMeter).
 *
 * TRUTH LAW (Truth-Everywhere Part 2, item 2): this used to render a hardcoded
 * "47 / 100 CLAIMED". It now fetches the REAL count of active paying founders
 * from /api/founders/count (Stripe-synced, cached). If the source is
 * unavailable — or the fetch fails — the counter and progress bar HIDE
 * entirely. We never fall back to a number. A low real count is fine; the
 * truth is the feature.
 */
export default function ClaimMeter() {
  const [data, setData] = useState<FounderCount | null>(null);

  useEffect(() => {
    let active = true;
    fetch('/api/founders/count', { cache: 'no-store' })
      .then((r) => r.json())
      .then((d) => { if (active) setData(d); })
      .catch(() => { if (active) setData({ available: false }); });
    return () => { active = false; };
  }, []);

  // Hide until we have a REAL number. Unavailable source → render nothing.
  if (!data || !data.available || typeof data.claimed !== 'number') return null;

  const total = data.total || 100;
  const claimed = Math.max(0, Math.min(total, data.claimed));
  const pct = Math.min(100, Math.round((claimed / total) * 100));
  // Item B — at capacity the meter flips to sold-out (checkout has already
  // flipped to standard pricing via the same countFounderSeats truth).
  const soldOut = claimed >= total;

  return (
    <div style={{ maxWidth: 420, margin: '0 auto', width: '100%' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
        <SectionHead accent="var(--amber)">FOUNDER SEATS</SectionHead>
        <span className="mono amber-glow" style={{ fontSize: 13, fontWeight: 700, color: 'var(--amber)' }}>
          {soldOut ? 'SOLD OUT' : `${claimed} / ${total} CLAIMED`}
        </span>
      </div>
      <div style={{ height: 6, background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 4, overflow: 'hidden' }}>
        <div
          style={{
            width: `${pct}%`,
            height: '100%',
            background: 'linear-gradient(90deg, #b8761f, var(--amber))',
            boxShadow: '0 0 12px rgba(255,179,71,.6)',
            borderRadius: 4,
            transition: 'width .4s ease-out',
          }}
        />
      </div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--text-1)', marginTop: 8, letterSpacing: '0.02em' }}>
        {soldOut
          ? 'Founder seats are gone — standard pricing now applies.'
          : 'Founder pricing locks for life. When the seats are gone, the rate is gone.'}
      </div>
    </div>
  );
}
