'use client';
import React,{useEffect,useRef,useState} from 'react';
import type {LarpTemplate} from '@/lib/catalog';
import {ExternalLink,FileCode2,Lock,Loader2,RefreshCw} from 'lucide-react';
import {cn} from '@/lib/utils';

/**
 * The authenticated parent downloads the standalone app document and passes it
 * to a script-only, opaque-origin srcDoc frame. This prevents sandboxed scripts
 * from accessing the parent account, while preserving the original local UI.
 * The server bundles Cash App's own CSS/JS/fonts/images into that document.
 */
export function AppUiFrame({template,phone=true,ownerPreview=false,projectId,refreshKey=0,immersive=false,homepagePreview=false}: {
 template:LarpTemplate;phone?:boolean;ownerPreview?:boolean;projectId?:string;refreshKey?:number;immersive?:boolean;homepagePreview?:boolean;
}){
 const local=template.slug==='cash-app';
 const show=Boolean(template.uiReady&&(ownerPreview||['available','early'].includes(template.status)));
 const device=phone?'phone':'desktop';
 const base=`/api/app-ui/${encodeURIComponent(template.slug)}/${device}/index.html`;
 const url=base+(projectId?`?project=${encodeURIComponent(projectId)}&v=${refreshKey}`:homepagePreview?`?context=homepage&v=${refreshKey}`:refreshKey?`?v=${refreshKey}`:'');
 const frameRef=useRef<HTMLIFrameElement|null>(null);
 const [frameVersion,setFrameVersion]=useState(0);
 const [html,setHtml]=useState<string|null>(null),[error,setError]=useState(''),[loading,setLoading]=useState(false);
 useEffect(()=>{
  if(!show){setHtml(null);setError('');return;}
  const controller=new AbortController();
  setHtml(null);setError('');setLoading(true);
  void fetch(url,{credentials:'same-origin',cache:'no-store',signal:controller.signal})
   .then(async response=>{
    if(!response.ok){
     if(response.status===401||response.status===403)throw new Error('Sign in with an account that has paid access to view this LARP.');
     throw new Error(response.status===404?'The original LARP UI file was not found.':'Could not load the original LARP UI.');
    }
    return response.text();
   })
   .then(content=>{if(!controller.signal.aborted)setHtml(content);})
   .catch((reason:unknown)=>{if(!controller.signal.aborted)setError((reason as Error).message||'Preview unavailable');})
   .finally(()=>{if(!controller.signal.aborted)setLoading(false);});
  return()=>controller.abort();
 },[show,url]);
 useEffect(()=>{
  if(!projectId)return;
  const refresh=(event:Event)=>{
   const detail=(event as CustomEvent<{projectId?:string}>).detail;
   if(detail?.projectId!==projectId)return;
   void fetch(url,{credentials:'same-origin',cache:'no-store'}).then(r=>r.ok?r.text():Promise.reject()).then(content=>{setHtml(content);setFrameVersion(v=>v+1)}).catch(()=>{});
  };
  window.addEventListener('larpdevice:settings-saved',refresh);
  let channel:BroadcastChannel|undefined;
  try{channel=new BroadcastChannel('larpdevice-project-sync');channel.onmessage=e=>refresh(new CustomEvent('larpdevice:settings-saved',{detail:e.data}));}catch{}
  return()=>{window.removeEventListener('larpdevice:settings-saved',refresh);channel?.close()};
 },[projectId,url]);
 useEffect(()=>{
  if(!projectId)return;
  let inProgress=false;
  const onMessage=async(event:MessageEvent)=>{
   if(event.source!==frameRef.current?.contentWindow||inProgress)return;
   const message=event.data as {type?:string;requestId?:string;changes?:unknown;mode?:string;field?:string;selector?:string;value?:unknown;format?:string;symbol?:string}|null;
   if(!message||typeof message.requestId!=='string'||message.requestId.length>100)return;
   const isCashEdit=message.type==='larpdevice:edit-request'&&template.slug==='cash-app'&&phone;
   const isInline=message.type==='larpdevice:inline-edit';
   const isNative=message.type==='larpdevice:native-edit'&&template.slug!=='cash-app';
   if(!isCashEdit&&!isInline&&!isNative)return;
   if(isNative&&(!message.changes||typeof message.changes!=='object'||Array.isArray(message.changes)))return;
   if(isCashEdit&&(!message.changes||typeof message.changes!=='object'||Array.isArray(message.changes)))return;
   if(isInline&&(!['text','bind','field'].includes(String(message.mode))||typeof message.field!=='string'))return;
   inProgress=true;
   let ok=false,status=500,errorText='Could not save changes.';
   try{
    const endpoint=isCashEdit?'live-edit':isNative?'native-settings':'inline-edit';
    const changes=isCashEdit||isNative?message.changes:{mode:message.mode,field:message.field,selector:message.selector,value:message.value,format:message.format,symbol:message.symbol};
    const r=await fetch(`/api/projects/${encodeURIComponent(projectId)}/${endpoint}`,{method:'PATCH',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(changes)});
    const response=await r.json().catch(()=>({}));ok=r.ok;status=r.status;errorText=response.error||errorText;
   }catch{errorText='Connection failed. Please try again.'}
   frameRef.current?.contentWindow?.postMessage({type:isCashEdit?'larpdevice:edit-result':isNative?'larpdevice:native-result':'larpdevice:inline-result',requestId:message.requestId,ok,status,error:errorText},'*');
   if(ok){
    window.dispatchEvent(new CustomEvent('larpdevice:project-updated',{detail:{projectId}}));
    try{const channel=new BroadcastChannel('larpdevice-project-sync');channel.postMessage({projectId});channel.close()}catch{}
    // Pull the just-saved project from the server and regenerate a complete app
    // document. This updates other linked labels, including native Cash App UI.
    try{const r=await fetch(url,{credentials:'same-origin',cache:'no-store'});if(r.ok){setHtml(await r.text());setFrameVersion(v=>v+1)}}catch{}
   }
   inProgress=false;
  };
  window.addEventListener('message',onMessage);
  return()=>window.removeEventListener('message',onMessage);
 },[projectId,phone,template.slug,url]);
 return <div className={cn('w-full flex flex-col items-center min-w-0',immersive?'h-[100dvh] gap-0':'gap-3')}>
  <div className={cn('relative bg-[#0b0e1a] text-white',immersive?(phone?'flex-1 min-h-0 w-full max-w-[480px] overflow-hidden':'flex-1 min-h-0 w-full overflow-hidden'):'border border-white/15 shadow-[0_8px_35px_#0006]',!immersive&&(phone?'w-[390px] max-w-full h-[790px] rounded-2xl overflow-hidden':'w-full h-[790px] rounded-xl overflow-auto'))}>
   {html?<iframe ref={frameRef} key={url+'-'+frameVersion} title={`${template.name} fictional ${device} UI`} srcDoc={html} sandbox="allow-scripts" referrerPolicy="no-referrer" className={cn('border-0 bg-white h-full',immersive?'w-full':phone?'w-full':'w-full min-w-[1040px]')}/>:<div className="w-full h-full flex flex-col justify-center items-center gap-3 text-center px-8">
    {loading?<Loader2 size={28} className="animate-spin text-violet-300"/>:show?<Lock size={30} className="text-violet-300"/>:<FileCode2 size={30} className="text-violet-300"/>}
    <p className="font-bold text-sm">{loading?'Loading the original LARP UI...':error||(!show?'Coming Soon — preview not captured':'Preview unavailable')}</p>
    {!show&&<p className="text-xs text-white/70">This app does not yet have a complete local preview.</p>}
    {error&&<a className="text-xs underline text-violet-300" href={url} target="_blank" rel="noopener noreferrer">Open or troubleshoot the original file</a>}
   </div>}
  </div>
  {show&&!immersive&&<div className="flex gap-3 flex-wrap items-center justify-center text-xs"><span className="inline-flex items-center gap-1 text-muted-foreground"><Lock size={12}/> Fictional simulation</span><a href={`/preview/${encodeURIComponent(template.slug)}?device=${device}${projectId?'&project='+encodeURIComponent(projectId):''}`} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 rounded-xl px-5 py-3 bg-primary text-primary-foreground text-sm font-bold shadow-sm hover:opacity-90 focus-visible:ring-2 focus-visible:ring-primary/50"><ExternalLink size={16}/> Pop out {phone?'phone':'desktop'} preview</a><button type="button" onClick={()=>{setHtml(null);setError('');setLoading(true);void fetch(url,{credentials:'same-origin',cache:'no-store'}).then(r=>{if(!r.ok)throw Error('Cannot reload');return r.text()}).then(setHtml).catch(()=>setError('Could not reload the preview.')).finally(()=>setLoading(false));}} className="inline-flex items-center gap-1 text-muted-foreground hover:text-foreground"><RefreshCw size={12}/> Reload</button></div>}
 </div>;
}
