'use client';
import {useEffect,useState} from 'react';
import Link from 'next/link';
import {useRouter} from 'next/navigation';
import {toast} from 'sonner';
import {Plus,Copy,ExternalLink,Pencil,RotateCcw,Trash2,ShieldCheck,ArrowLeft,Crown,Settings2,Images} from 'lucide-react';
import {useAccount,api} from '@/components/providers';
import {WorkspaceShell} from '@/components/workspace-shell';
import {Button} from '@/components/ui/button';
import {BrandIcon} from '@/components/common';
import {isFreeDemoApp} from '@/lib/free-demo';
import type{LarpTemplate} from '@/lib/catalog';
export function LarpHub({template}:{template:LarpTemplate}){
 const router=useRouter();const {user,projects,loading,createFrom,refreshData}=useAccount();
 const [owner,setOwner]=useState(false),[access,setAccess]=useState(false),[busy,setBusy]=useState(false),[links,setLinks]=useState<Record<string,string>>({});
 const own=projects.filter(p=>p.templateSlug===template.slug);
 useEffect(()=>{if(!user)return;let active=true;Promise.all([api('/api/billing/status'),api('/api/studio/access')]).then(([billing,role])=>{if(!active)return;setOwner(!!role.owner);const level=billing.currentPlan?.plan;const activePlan=!!billing.currentPlan?.active&&level!=='free';const purchase=(billing.purchases||[]).filter((p:{active:boolean;expiresAt:number|null})=>p.active&&(!p.expiresAt||p.expiresAt>Date.now())).sort((a:{updatedAt:string},b:{updatedAt:string})=>b.updatedAt.localeCompare(a.updatedAt));const current=purchase[0];const include=current?(billing.config.packages.find((p:{id:string})=>p.id===current.packageId)?.includedApps??billing.config.plans[current.plan]?.includedApps):billing.config.plans[level]?.includedApps;const allowed=include==='all'||Array.isArray(include)&&include.includes(template.slug);
 setAccess(Boolean(role.owner||(activePlan&&allowed)||isFreeDemoApp(template.slug)));}).catch(()=>{});return()=>{active=false}},[user]);
 useEffect(()=>{if(!user||!own.length)return;let alive=true;Promise.all(own.map(p=>api('/api/projects/'+p.id+'/link').then(x=>({id:p.id,url:x.link?.url||''})).catch(()=>({id:p.id,url:''})))).then(rows=>{if(alive)setLinks(Object.fromEntries(rows.map(x=>[x.id,x.url])))});return()=>{alive=false}},[user,projects.length,template.slug]);
 async function create(){if(!user){router.push('/login?next='+encodeURIComponent('/larp/'+template.slug));return}if(!access){router.push('/pricing');return}setBusy(true);try{const p=await createFrom(template.slug);if(p){await refreshData();router.push('/editor/'+template.slug+'?project='+p.id)}}finally{setBusy(false)}}
 async function rotate(id:string){if(!window.confirm('Replace this live link? The old one will stop working.'))return;try{const x=await api('/api/projects/'+id+'/link',{method:'POST'});setLinks(v=>({...v,[id]:x.link.url}));toast.success('A new private link was created and documented')}catch(e){toast.error((e as Error).message)}}
 async function remove(id:string){if(!window.confirm('Delete this LARP permanently? Its old live links will show an unavailable message.'))return;try{await api('/api/projects/'+id,{method:'DELETE'});await refreshData();toast.success('LARP deleted. Links remain in the audit history.')}catch(e){toast.error((e as Error).message)}}
 const copy=(url:string)=>void navigator.clipboard.writeText(location.origin+url).then(()=>toast.success('Link copied')).catch(()=>toast.error('Cannot copy link'));
 return <WorkspaceShell title={template.name+' · My LARPs'} description="Create a LARP, open its private link, or adjust its settings. All screens are simulations." actions={<Button asChild variant="outline"><Link href="/library"><ArrowLeft size={16}/> All apps</Link></Button>}>
 <section className="glass-panel p-6 mb-6"><div className="flex flex-wrap gap-5 items-center"><BrandIcon template={template} size={80}/><div className="flex-1 min-w-56"><h2 className="text-xl font-black">{template.name} creative workspace</h2><p className="text-sm text-muted-foreground mt-1">Every LARP has its own link tied to the account that created it. A different account cannot open it.</p>{isFreeDemoApp(template.slug)&&<p className="text-xs font-semibold text-amber-500 mt-2">Free roleplay demo: the saved app carries a visible @larpdevice simulation mark.</p>}</div><Button size="lg" variant="gradient" onClick={()=>void create()} disabled={busy||loading||!['available','early'].includes(template.status)}><Plus size={17}/> Create new LARP</Button></div></section>
 {!user?<section className="glass-panel p-8"><h2 className="font-bold text-lg">Sign in to create a LARP</h2><p className="text-muted-foreground text-sm mt-2">You need an account and active paid access to create a private LARP.</p><div className="flex gap-3 mt-5"><Button asChild><Link href={'/login?next='+encodeURIComponent('/larp/'+template.slug)}>Sign in</Link></Button><Button variant="outline" asChild><Link href="/signup">Create account</Link></Button></div></section>:!access?<section className="glass-panel p-7 mb-6"><h2 className="font-bold flex gap-2"><Crown size={20}/> Paid access required</h2><p className="text-sm mt-2 text-muted-foreground">Cash App, Shopify, and YouTube Studio have free marked demos. Other private LARPs require an active plan or approved promotional upgrade.</p><div className="flex gap-3 mt-4 flex-wrap"><Button asChild variant="gradient"><Link href="/pricing">Choose a package</Link></Button><Button asChild variant="outline"><Link href="/free-upgrade">Get free upgrade</Link></Button></div></section>:null}
 <section className="space-y-3"><h2 className="text-lg font-bold">Your {template.name} LARPs ({own.length})</h2>{own.length===0?<div className="glass-panel p-10 text-center"><Images className="mx-auto text-primary"/><h3 className="mt-4 font-bold">No LARPs created yet</h3><p className="text-sm text-muted-foreground mt-2">Click Create new LARP above to get started.</p></div>:own.map(p=><article key={p.id} className="glass-panel p-5 space-y-3"><div className="flex flex-wrap items-start justify-between gap-2"><div><div className="font-bold">{p.name}</div><p className="text-xs text-muted-foreground">Created {new Date(p.createdAt).toLocaleDateString()} · {p.published?'Published sample':'Private draft'}</p></div><span className="text-[10px] uppercase tracking-wider bg-amber-500/15 text-amber-500 rounded-lg px-2 py-1 font-black">SIMULATION ONLY</span></div><div className="rounded-lg bg-muted/30 border px-3 py-2 flex flex-wrap gap-3 justify-between items-center"><span className="text-xs text-muted-foreground break-all">{links[p.id]?locationSafe(links[p.id]):'Private link unavailable'}</span>{links[p.id]&&<Button size="sm" variant="outline" onClick={()=>copy(links[p.id])}><Copy size={14}/> Copy</Button>}</div><div className="flex flex-wrap gap-2"><Button size="sm" asChild disabled={!links[p.id]}><Link href={'/open/'+p.id} target="_blank" rel="noopener noreferrer"><ExternalLink size={15}/> Open live LARP</Link></Button><Button size="sm" asChild variant="outline"><Link href={'/editor/'+p.templateSlug+'?project='+p.id}><Settings2 size={15}/> Edit settings</Link></Button><Button size="sm" asChild variant="outline"><Link href={'/studio/'+p.templateSlug+'?project='+p.id}><Pencil size={15}/> Advanced blueprint</Link></Button><Button size="sm" variant="outline" onClick={()=>void rotate(p.id)}><RotateCcw size={14}/> New live code</Button><Button size="sm" variant="outline" onClick={()=>void remove(p.id)}><Trash2 size={14}/> Delete</Button></div></article>)}</section>
 <p className="flex gap-2 items-center text-xs text-muted-foreground mt-6"><ShieldCheck size={15}/> Live links are private and recorded on the server. Any view is fictional and visibly labeled.</p>
 </WorkspaceShell>;
}
function locationSafe(url:string){return url.startsWith('/l/')?'Private code: '+url.split('/').pop()?.slice(0,8)+'…':'Private link'}
