import type { LarpKind, LarpTemplate } from './catalog';

/** Declarative blocks: none of these values contain executable HTML or JavaScript. */
export type BlockType='hero'|'balance'|'stats'|'activity'|'actions'|'note'|'divider'|'banner'|'image'|'progress'|'spacer'|'navigation';
export type StudioBlock={id:string;type:BlockType;title:string;text:string;value:string;imageUrl:string;color:string;visible:boolean};
export type NodePosition={x:number;y:number};
export type NodeEdge={id:string;from:string;to:string};
export type StudioGraph={positions:Record<string,NodePosition>;edges:NodeEdge[]};
export type Blueprint={slug:string;name:string;description:string;kind:LarpKind;blocks:StudioBlock[];graph?:StudioGraph;builtIn?:boolean};
export type StudioLayout={blueprintSlug:string;blocks:StudioBlock[];graph?:StudioGraph;script?:string};
export type SiteConfig={eyebrow:string;heroTitle:string;heroEmphasis:string;heroDescription:string;primaryCta:string;announcement:string};
export type CatalogPatch=Partial<Pick<LarpTemplate,'name'|'category'|'color'|'icon'|'thumbnail'|'status'|'kind'|'publicVisible'|'uiFile'>> & {blueprintSlug?:string;description?:string};
export type PageTextEdit={path:string;selector:string;value:string};
export type StudioCatalog={overrides:Record<string,CatalogPatch>;customTemplates:LarpTemplate[];site:SiteConfig;pageEdits:PageTextEdit[];audit:{when:string;event:string}[]};
export const defaultSite:SiteConfig={
  eyebrow:'THE WORLD OF LARP EXPERIENCES',
  heroTitle:'Make it look like',
  heroEmphasis:'you made it.',
  heroDescription:'Browse LARP experiences. Each app opens its own assigned UI file; no premade phone interface is generated. More experiences are coming soon.',
  primaryCta:'Explore All LARPs',
  announcement:'Now featuring: File-driven UI previews · Draggable Blueprint node graph'
};
export const blockTypes:BlockType[]=['hero','balance','stats','activity','actions','note','divider','banner','image','progress','spacer','navigation'];
export const createBlock=(type:BlockType):StudioBlock=>({
  id:'b-'+Math.random().toString(36).slice(2,10),type,
  title:({hero:'Welcome back',balance:'My account',stats:'Insights',activity:'Activity',actions:'Quick actions',note:'A little note',divider:'',banner:'Discover more',image:'My image',progress:'Your progress',spacer:'',navigation:'Explore'} as Record<BlockType,string>)[type],
  text:({hero:'Create a story that feels like yours.',balance:'Demo credits only',stats:'Simulated statistics',activity:'Sample activity feed',actions:'Send, Save, History',note:'Double-click an item to edit it.',divider:'',banner:'Made for imagination.',image:'Image caption',progress:'65',spacer:'',navigation:'Home, Explore, Profile'} as Record<BlockType,string>)[type],
  value:type==='balance'?'24860.77':type==='progress'?'65':type==='stats'?'128': '',
  imageUrl:'',color:'#8a4aff',visible:true
});

export function validLayout(candidate:unknown):candidate is StudioLayout{
 if(!candidate||typeof candidate!=='object')return false;
 const v=candidate as Partial<StudioLayout>;
 return typeof v.blueprintSlug==='string'&&Array.isArray(v.blocks)&&v.blocks.length<=50&&
   v.blocks.every(b=>b&&typeof b.id==='string'&&b.id.length<80&&blockTypes.includes(b.type)&&
     ['title','text','value','imageUrl','color'].every(k=>typeof b[k as keyof StudioBlock]==='string'&&String(b[k as keyof StudioBlock]).length<=1200)&&typeof b.visible==='boolean')&&
   (v.script===undefined||(typeof v.script==='string'&&v.script.length<=5000)) && validGraph(v.graph, v.blocks);
}
export function validGraph(graph:unknown, blocks:StudioBlock[]):boolean{
 if(graph===undefined)return true;
 if(!graph||typeof graph!=='object')return false;
 const g=graph as Partial<StudioGraph>, ids=new Set(blocks.map(b=>b.id));
 if(!g.positions||typeof g.positions!=='object'||Array.isArray(g.positions)||!Array.isArray(g.edges)||g.edges.length>150)return false;
 if(Object.keys(g.positions).length>50)return false;
 return Object.entries(g.positions).every(([id,p])=>ids.has(id)&&p&&Number.isFinite(p.x)&&Number.isFinite(p.y)&&Math.abs(p.x)<5000&&Math.abs(p.y)<5000)&&
 g.edges.every(e=>e&&typeof e.id==='string'&&e.id.length<70&&ids.has(e.from)&&ids.has(e.to)&&e.from!==e.to);
}

/** Connected output-to-input links determine display order; unconnected blocks follow their original order. */
export function orderedBlocks(layout:StudioLayout):StudioBlock[]{
 const blocks=layout.blocks, edges=layout.graph?.edges||[];
 if(!edges.length)return blocks;
 const incoming=new Map(blocks.map(b=>[b.id,0]));
 for(const e of edges)if(incoming.has(e.to))incoming.set(e.to,(incoming.get(e.to)||0)+1);
 const visited=new Set<string>(), order:StudioBlock[]=[];
 const visit=(b:StudioBlock)=>{if(visited.has(b.id))return;visited.add(b.id);order.push(b);for(const e of edges.filter(x=>x.from===b.id)){const target=blocks.find(x=>x.id===e.to);if(target)visit(target)}};
 for(const b of blocks)if(!incoming.get(b.id))visit(b);
 for(const b of blocks)visit(b);
 return order;
}
