'use client';
import {useEffect,useState} from 'react';
import Link from 'next/link';
import {Gift,ArrowRight} from 'lucide-react';
import {Button} from '@/components/ui/button';
import {useAccount,api} from '@/components/providers';
export function TrialOffer(){const {user}=useAccount();const [config,setConfig]=useState<{enabled:boolean;days:number}|null>(null),[used,setUsed]=useState(false),[active,setActive]=useState(false),[busy,setBusy]=useState(false),[error,setError]=useState(''),[granted,setGranted]=useState(false);
 useEffect(()=>{void api('/api/billing/trial').then(x=>{setConfig(x.config);setUsed(!!x.used);setActive(!!x.active)}).catch(()=>{})},[user]);
 async function start(){setBusy(true);setError('');try{await api('/api/billing/trial',{method:'POST',body:'{}'});setGranted(true);setUsed(true);setActive(true);window.dispatchEvent(new Event('billing:updated'))}catch(e){setError((e as Error).message)}finally{setBusy(false)}}
 if(!config?.enabled||used&&!active&&!granted)return null;
 return <section className="glass-panel p-5 mt-6 flex flex-wrap gap-4 items-center justify-between"><div className="max-w-2xl"><h2 className="font-black text-lg flex items-center gap-2"><Gift size={20} className="text-primary"/> Owner-offered {config.days}-day trial</h2><p className="text-sm text-muted-foreground mt-2">Try eligible fictional apps without a purchase. One trial per account; no automatic charge or renewal. You still need a separate paid plan after the trial ends.</p>{error&&<p className="text-sm text-destructive mt-2">{error}</p>}{granted&&<p className="text-sm text-primary mt-2">Trial activated. Your available LARPs are unlocked until it expires.</p>}</div>{active?<Button asChild variant="gradient"><Link href="/my-larps">Open My LARPs <ArrowRight size={15}/></Link></Button>:user?<Button onClick={()=>void start()} disabled={busy}>{busy?'Activating…':'Start free trial'}</Button>:<Button asChild><Link href="/signup?next=/pricing">Create account to start</Link></Button>}</section>
}
