import type {Metadata} from 'next';
import {appTabBrand} from '@/lib/app-tab-brand';
import {PopoutTabIdentity} from '@/components/popout-tab-identity';
import Link from 'next/link';
import {headers} from 'next/headers';
import {NextRequest} from 'next/server';
import {lookupLiveLink} from '@/lib/live-links';
import {getProject,sessionUser} from '@/lib/server-store';
import {canUseApp} from '@/lib/billing-store';
import {isStudioAdmin,getStudioTemplate} from '@/lib/studio-store';
import {AppUiFrame} from '@/components/app-ui-frame';
export const dynamic='force-dynamic';
export async function generateMetadata({params}:{params:Promise<{code:string}>}):Promise<Metadata>{
 const {code}=await params;const link=lookupLiveLink(code);
 const h=await headers(),user=sessionUser(new NextRequest(process.env.APP_URL||'http://localhost:3000',{headers:h}));
 const project=link&&user?.id===link.userId&&!link.deletedAt?getProject(link.projectId):null;
 const app=project?getStudioTemplate(project.templateSlug):null;
 return appTabBrand(app,project?.name).metadata;
}

function Notice({title,message,links}:{title:string;message:string;links:Array<{href:string;text:string}>}){
 return <main className="min-h-screen flex items-center justify-center px-5"><div className="glass-panel max-w-xl w-full p-9 space-y-5"><div className="text-sm font-black tracking-widest text-primary">LARPDEVICE</div><h1 className="text-2xl font-black">{title}</h1><p className="text-muted-foreground">{message}</p><div className="flex flex-wrap gap-3">{links.map(l=><Link key={l.href} href={l.href} className="rounded-xl bg-primary text-white font-bold px-4 py-3 text-sm">{l.text}</Link>)}</div></div></main>
}
export default async function Page({params,searchParams}:{params:Promise<{code:string}>;searchParams:Promise<{device?:string}>}){
 const {code}=await params,{device}=await searchParams;const view=device==='desktop'?'desktop':'phone';const link=lookupLiveLink(code);
 const h=await headers();const req=new NextRequest(process.env.APP_URL||'http://localhost:3000',{headers:h});const user=sessionUser(req);
 if(!link)return <Notice title="This link is not available" message="Check that the link is correct. You can find your active LARPs in your dashboard." links={[{href:'/dashboard',text:'Go to dashboard'}]}/>;
 if(link.deletedAt||!getProject(link.projectId))return <Notice title="This LARP is no longer available" message={`The LARP was deleted. ${user?'You are signed in as '+user.email+'.':'You are not signed in.'}`} links={[{href:'/dashboard',text:'Go to dashboard'},{href:'/login',text:'Switch account'}]}/>;
 if(link.revokedAt)return <Notice title="This live link was replaced" message={`This link was deactivated. ${user?'Signed in as '+user.email+'.':''} Get the current link from your dashboard.`} links={[{href:'/dashboard',text:'Go to dashboard'}]}/>;
 if(!user||user.id!==link.userId)return <Notice title="Sign in to view your LARP" message={`${user?'You are signed in as '+user.email+', but this LARP belongs to another account.':'This is a private LARP belonging to another account.'} Sign in using its owner account, or create your own LARP.`} links={[{href:'/login?next='+encodeURIComponent('/l/'+code),text:'Sign in'},{href:'/signup',text:'Create account'}]}/>;
 const project=getProject(link.projectId),template=project&&getStudioTemplate(project.templateSlug);
 if(!project||!template)return <Notice title="This LARP is no longer available" message={`Signed in as ${user.email}. The original LARP has been removed.`} links={[{href:'/dashboard',text:'Go to dashboard'}]}/>;
 if(!isStudioAdmin(req)&&!canUseApp(user.id,project.templateSlug))return <Notice title="A paid plan is required" message={`Signed in as ${user.email}. Your plan does not include this LARP. Free accounts can only see labeled samples.`} links={[{href:'/pricing',text:'View packages'},{href:'/dashboard',text:'Dashboard'}]}/>;
 // A live link is already an authenticated, owner-bound app URL. Display the
 // saved interface full-tab instead of surrounding it with a second website UI.
 const brand=appTabBrand(template,project.name);
 return <main className="relative h-[100dvh] w-full overflow-hidden bg-[#080a13] text-white">
  <PopoutTabIdentity title={brand.title} icon={brand.icon}/>
  <AppUiFrame template={template} phone={view==='phone'} projectId={project.id} immersive/>
 </main>;
}
