Files
0pt/app/portal/krediter/page.tsx
T

170 lines
6.6 KiB
TypeScript

'use client';
import { useCallback, useEffect, useState } from 'react';
import { useT } from '@/components/locale-provider';
import { PortalShell } from '@/components/portal-shell';
import { formatSEK } from '@/lib/data';
type Pack = { id: string; credits: number; amount_minor: number };
export default function CreditsPage() {
const t = useT();
const [balance, setBalance] = useState<{ available: number; reserved: number } | null>(null);
const [balanceNote, setBalanceNote] = useState<string | null>(null);
const [packs, setPacks] = useState<Pack[]>([]);
const [purchasesEnabled, setPurchasesEnabled] = useState(true);
const [currency, setCurrency] = useState('SEK');
const [packsNote, setPacksNote] = useState<string | null>(null);
const [buying, setBuying] = useState<string | null>(null);
const [status, setStatus] = useState<string | null>(null);
const load = useCallback(async () => {
try {
const r = await fetch('/api/0pt/credits/balance', { cache: 'no-store' });
const body = (await r.json()) as { available?: number; reserved?: number; message?: string };
if (r.ok) setBalance({ available: body.available ?? 0, reserved: body.reserved ?? 0 });
else
setBalanceNote(
body.message ?? t({ en: 'Credits are not available', sv: 'Krediter är inte tillgängliga' }),
);
} catch {
setBalanceNote(t({ en: 'Could not read the balance', sv: 'Kunde inte läsa saldot' }));
}
try {
const r = await fetch('/api/0pt/credits/packs', { cache: 'no-store' });
const body = (await r.json()) as {
packs?: Pack[];
currency?: string;
purchases_enabled?: boolean;
message?: string;
};
if (r.ok && body.packs) {
setPacks(body.packs);
setCurrency(body.currency ?? 'SEK');
setPurchasesEnabled(body.purchases_enabled !== false);
} else {
setPacksNote(
body.message ??
t({ en: 'Credit packs are not configured', sv: 'Kreditpaket är inte konfigurerade' }),
);
}
} catch {
setPacksNote(t({ en: 'Could not read credit packs', sv: 'Kunde inte läsa kreditpaket' }));
}
}, [t]);
useEffect(() => {
void load();
const params = new URLSearchParams(window.location.search);
const state = params.get('status');
if (state === 'success') {
setStatus(
t({
en: 'Payment received. Credits are added when Stripe confirms the payment.',
sv: 'Betalning mottagen. Krediter läggs till när Stripe bekräftar betalningen.',
}),
);
} else if (state === 'cancelled') {
setStatus(t({ en: 'Checkout cancelled.', sv: 'Betalningen avbröts.' }));
}
}, [load, t]);
const buy = useCallback(
async (packId: string) => {
setBuying(packId);
setStatus(null);
try {
const response = await fetch('/api/0pt/credits/checkout', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ pack_id: packId }),
});
const body = (await response.json().catch(() => ({}))) as { checkout_url?: string; message?: string };
if (response.ok && body.checkout_url) {
window.location.href = body.checkout_url;
return;
}
setStatus(
body.message ?? t({ en: 'Checkout is not available', sv: 'Betalning är inte tillgänglig' }),
);
} catch {
setStatus(t({ en: 'Checkout is not available', sv: 'Betalning är inte tillgänglig' }));
} finally {
setBuying(null);
}
},
[t],
);
const card = 'border border-border bg-background p-6';
return (
<PortalShell variant="customer" title={t({ en: 'Credits', sv: 'Krediter' })}>
<div className="mx-auto w-full max-w-3xl space-y-6">
<section className={card}>
<span className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground">
{t({ en: 'balance', sv: 'saldo' })}
</span>
{balance ? (
<p className="mt-3 font-mono text-3xl tracking-[-0.02em]">
{balance.available}
<span className="ml-2 text-[11px] uppercase tracking-[0.18em] text-muted-foreground">
{t({ en: 'available', sv: 'tillgängliga' })} · {balance.reserved}{' '}
{t({ en: 'reserved', sv: 'reserverade' })}
</span>
</p>
) : (
<p className="mt-3 text-[14px] text-muted-foreground">{balanceNote ?? '…'}</p>
)}
</section>
<section className={card}>
<h2 className="text-lg font-semibold tracking-[-0.02em]">
{t({ en: 'Buy credits', sv: 'Köp krediter' })}
</h2>
{packs.length === 0 ? (
<p className="mt-3 text-[14px] text-muted-foreground">{packsNote ?? '…'}</p>
) : (
<ul className="mt-4 divide-y divide-border border-y border-border">
{packs.map((pack) => (
<li key={pack.id} className="flex items-center justify-between gap-4 py-3">
<div>
<p className="font-mono text-[13px]">{pack.credits} credits</p>
<p className="font-mono text-[11px] text-muted-foreground">
{formatSEK(pack.amount_minor / 100)}
</p>
</div>
{purchasesEnabled ? (
<button
type="button"
onClick={() => buy(pack.id)}
disabled={buying !== null}
className="border border-foreground px-4 py-2 font-mono text-[11px] uppercase tracking-[0.18em] disabled:opacity-40"
>
{buying === pack.id
? t({ en: 'opening…', sv: 'öppnar…' })
: t({ en: 'buy', sv: 'köp' })}
</button>
) : null}
</li>
))}
</ul>
)}
{!purchasesEnabled ? (
<p className="mt-4 text-[14px] text-muted-foreground">
{t({
en: 'Billing is not active yet (pilot). No payment can be taken.',
sv: 'Betalning är inte aktiverad än (pilot). Ingen betalning kan tas.',
})}
</p>
) : null}
{status ? <p className="mt-4 text-[14px] text-muted-foreground">{status}</p> : null}
<p className="mt-4 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground">
{currency}
</p>
</section>
</div>
</PortalShell>
);
}