'use client';

import { useState, useTransition } from 'react';

export default function BillingPage() {
  const [error, setError] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();

  function onClick() {
    setError(null);
    startTransition(async () => {
      const res = await fetch('/api/billing/checkout', { method: 'POST' });
      if (!res.ok) {
        setError(`Checkout failed (${res.status})`);
        return;
      }
      const body = (await res.json()) as { url?: string };
      if (!body.url) {
        setError('No checkout URL returned');
        return;
      }
      window.location.href = body.url;
    });
  }

  return (
    <div>
      <h1>Billing</h1>
      <div className="card">
        <h2>Upgrade</h2>
        <p className="muted">
          v1 MVP uses a Stripe stub — clicking Upgrade simulates a successful
          checkout and unlocks unlimited bandwidth.
        </p>
        {error && <p className="error">{error}</p>}
        <button onClick={onClick} disabled={isPending}>
          {isPending ? 'Redirecting…' : 'Upgrade'}
        </button>
      </div>
    </div>
  );
}
