# Account

import { useState, useEffect } from 'react';


export const Account = () => {
  const [me, setMe] = useState(undefined); // undefined = loading, null = logged out, object = user
  const [cycle, setCycle] = useState('monthly');
  useEffect(() => {
    fetch('/api/v1/auth/me', { credentials: 'include' })
      .then((r) => (r.ok ? r.json() : null))
      .then(setMe)
      .catch(() => setMe(null));
  }, []);
  const checkout = async (tier) => {
    const r = await fetch('/api/v1/billing/checkout', {
      method: 'POST', credentials: 'include',
      headers: { 'content-type': 'application/json' }, body: JSON.stringify({ tier, cycle }),
    });
    const j = await r.json();
    if (j.url) window.location = j.url; else alert(j.error || 'Could not start checkout');
  };
  const portal = async () => {
    const r = await fetch('/api/v1/billing/portal', { method: 'POST', credentials: 'include' });
    const j = await r.json();
    if (j.url) window.location = j.url; else alert(j.error || 'No active subscription');
  };
  if (me === undefined) return <p>Loading…</p>;
  if (me === null) return (
    <p><a href="/api/v1/auth/login"><strong>Log in with GitHub</strong></a> to get a free Starter API key.</p>
  );
  const paid = me.tier === 'pro' || me.tier === 'business';
  const annual = cycle === 'annual';
  const proPrice = annual ? '$490/yr' : '$49/mo';
  const bizPrice = annual ? '$1,990/yr' : '$199/mo';
  return (
    <div>
      <p>Signed in as <strong>{me.login}</strong> — current tier: <strong>{me.tier}</strong></p>
      {me.usage && <p style={{ color: '#666' }}>Usage (last {me.usage.period}): <strong>{me.usage.used.toLocaleString()}</strong> requests.</p>}
      <p><strong>Your API key</strong> (send as the <code>X-API-Key</code> header):</p>
      <pre>{me.apiKey}</pre>
      <pre>{`curl -H "X-API-Key: ${me.apiKey}" "${me.baseUrl}/search?q=payments&limit=3"`}</pre>
      <p style={{ fontSize: '0.85rem' }}>
        Billing:{' '}
        <label><input type="radio" checked={!annual} onChange={() => setCycle('monthly')} /> Monthly</label>{' '}
        <label><input type="radio" checked={annual} onChange={() => setCycle('annual')} /> Annual (2 months free)</label>
      </p>
      <p style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
        {me.tier !== 'pro' && <button onClick={() => checkout('pro')}>Upgrade to Pro — {proPrice}</button>}
        {me.tier !== 'business' && <button onClick={() => checkout('business')}>Upgrade to Business — {bizPrice}</button>}
        {paid && <button onClick={portal}>Manage billing</button>}
        <a href="/api/v1/auth/logout">Log out</a>
      </p>
      <p style={{ fontSize: '0.85rem', color: '#666' }}>
        Pro &amp; Business unlock the <a href="/developer/api/industries">industries</a>,
        regions, and ratings endpoints. See <a href="./plans">Plans</a>.
      </p>
    </div>
  );
};

<Account />
