'use client';
import {useEffect,useState} from 'react';
import Link from 'next/link';
import {toast} from 'sonner';
import {ArrowLeft,Flag,Save,ExternalLink} from 'lucide-react';
import {WorkspaceShell} from '@/components/workspace-shell';
import {Button} from '@/components/ui/button';
import {api} from '@/components/providers';
import type {MilestoneStatus,ReleaseTask} from '@/lib/release-waves';
type Item={key:string;name:string;appSlug:string|null;uiStatus:string;task:ReleaseTask};type Wave={wave:number;items:Item[]};
const statuses:[MilestoneStatus,string][]=[['not-started','Not started'],['in-progress','In progress'],['needs-testing','Needs testing'],['beta-ready','Ready for beta'],['released','Released']];
export function ReleaseTracker(){const[waves,setWaves]=useState<Wave[]>([]),[draft,setDraft]=useState<Record<string,{status:MilestoneStatus;ownerNote:string}>>({}),[busy,setBusy]=useState(''),[error,setError]=useState('');
 async function reload(){try{const r=await api('/api/studio/release-tracker');setWaves(r.waves||[]);setDraft(Object.fromEntries((r.waves||[]).flatMap((w:Wave)=>w.items.map(i=>[i.key,{status:i.task.status,ownerNote:i.task.ownerNote}]))));setError('')}catch(e){setError((e as Error).message)}}
 useEffect(()=>{void reload()},[]);
 async function save(item:Item){setBusy(item.key);try{await api('/api/studio/release-tracker',{method:'PATCH',body:JSON.stringify({key:item.key,status:draft[item.key].status,note:draft[item.key].ownerNote})});toast.success('Release status saved to Owner Studio and activity log');await reload()}catch(e){toast.error((e as Error).message)}finally{setBusy('')}}
 return <WorkspaceShell title="Owner Studio · Release Waves" description="Based on the linked LARP DEVICE RELEASES document. Preview availability and beta readiness are tracked separately." actions={<Button asChild variant="outline"><Link href="/developer"><ArrowLeft size={15}/> Owner Studio</Link></Button>}>
 <p className="glass-panel p-4 text-sm text-muted-foreground mb-5">An app with a local HTML preview is not necessarily a working released product. Only mark a feature <b>Released</b> after you test editing, login, billing, mobile layout, and any backend behavior it requires.</p>{error&&<p className="text-destructive">{error}</p>}
 <div className="space-y-5">{waves.map(w=><section className="glass-panel p-5" key={w.wave}><h2 className="font-black text-xl flex gap-2 items-center"><Flag size={19}/> Wave {w.wave}</h2><div className="grid lg:grid-cols-2 gap-3 mt-4">{w.items.map(i=><article className="rounded-xl border border-border p-4" key={i.key}><div className="flex gap-3 justify-between items-center"><div><h3 className="font-bold text-sm">{i.name}</h3><p className="text-xs text-muted-foreground mt-1">Local preview: <b>{i.uiStatus==='available'?'Available UI':'Missing / Coming Soon'}</b></p></div>{i.appSlug&&<Link className="text-primary text-xs flex gap-1" href={'/larp/'+i.appSlug} target="_blank">See App <ExternalLink size={13}/></Link>}</div><label className="block text-xs mt-4">Development status<select className="block mt-1 h-9 w-full border rounded-lg bg-background px-2" value={draft[i.key]?.status||'not-started'} onChange={e=>setDraft(s=>({...s,[i.key]:{...s[i.key],status:e.target.value as MilestoneStatus}}))}>{statuses.map(([id,label])=><option key={id} value={id}>{label}</option>)}</select></label><label className="block text-xs mt-3">Owner notes / test requirements<textarea rows={2} maxLength={1200} value={draft[i.key]?.ownerNote||''} onChange={e=>setDraft(s=>({...s,[i.key]:{...s[i.key],ownerNote:e.target.value}}))} className="mt-1 block w-full rounded-lg bg-background border p-2 text-sm" placeholder="What remains? What did you test?"/></label><Button size="sm" variant="outline" className="mt-3" disabled={busy===i.key} onClick={()=>void save(i)}><Save size={14}/> Save status</Button></article>)}</div></section>)}</div>
 </WorkspaceShell>}
