import type {DisplayData} from './models';

export const editableDemoFields=['displayName','cashtag','headline','accountLabel','balance','secondaryValue','imageUrl'] as const;
export type DemoField=typeof editableDemoFields[number];
export type DemoBinding={field:DemoField|'custom'|'customImage';value?:string;format?:'money';symbol?:'$'|'£'|'€'|'¥'};

/** A CSS path emitted by our viewer, not an arbitrary user-provided selector. */
export function validDemoSelector(selector:unknown):selector is string{
 return typeof selector==='string'&&selector.length<=650&&/^body:nth-of-type\(1\)(?:>[a-z][a-z0-9-]*:nth-of-type\([1-9][0-9]*\)){1,30}$/.test(selector);
}
export function validDemoValue(field:DemoField|'custom'|'customImage',value:unknown):boolean{
 if(field==='imageUrl'||field==='customImage')return typeof value==='string'&&value.length<=260000&&/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(value);
 if(field==='balance'||field==='secondaryValue')return typeof value==='number'&&Number.isFinite(value)&&value>=0&&value<=999999999;
 if(typeof value!=='string'||value.trim()!==value||value.length<1||value.length>120||/[\u0000-\u001f\u007f]/.test(value))return false;
 if(field==='cashtag')return /^\$?[A-Za-z0-9_]{1,30}$/.test(value);
 if(field==='displayName')return value.length<=70;
 if(field==='headline'||field==='accountLabel')return value.length<=90;
 return field==='custom';
}

/** No external requests: an opaque-origin viewer can only ask its authenticated parent to save. */
const EDIT_SCRIPT=String.raw`(function(){
'use strict';
var root=document.getElementById('ld-inline-config');if(!root)return;
var cfg;try{cfg=JSON.parse(root.textContent||'{}')}catch(e){return}
var core=['displayName','cashtag','balance','secondaryValue','headline','accountLabel'];
var names=['Display name','Cashtag / handle','Demo balance','Demo savings','Heading','Account label'];
var bindings=cfg.bindings||{},fields=cfg.fields||{};
var selected=null,stamp=0,pending={},timer=null,downX=0,downY=0,panel=null,modeSelect=null,valueInput=null,status=null;
function pathFor(el){var parts=[];while(el&&el.nodeType===1&&el!==document.body){var tag=el.tagName.toLowerCase(),n=1,sib=el.previousElementSibling;while(sib){if(sib.tagName===el.tagName)n++;sib=sib.previousElementSibling}parts.unshift(tag+':nth-of-type('+n+')');el=el.parentElement;if(parts.length>30)return null}return el===document.body?'body:nth-of-type(1)>'+parts.join('>'):null}
function candidate(node){var el=node&&node.nodeType===1?node:node&&node.parentElement;
 while(el&&el!==document.body){if(el.tagName==='IMG'&&el.getClientRects().length&&pathFor(el))return el;if(el.closest('#ld-inline-ui,#ld-inline-config,#larpdevice-simulation-notice,[aria-label*="SIMULATION"]'))return null;
 if(/^(SPAN|DIV|P|H1|H2|H3|H4|H5|H6|STRONG|EM|SMALL|B|TD)$/.test(el.tagName)&&el.children.length===0&&!el.isContentEditable){
   var value=(el.textContent||'').trim();if(value.length>0&&value.length<=120&&el.getClientRects().length&&pathFor(el))return el;
 }el=el.parentElement}return null}
function renderSaved(){for(var selector in bindings){if(!Object.prototype.hasOwnProperty.call(bindings,selector))continue;var item=bindings[selector],el;
 try{el=document.querySelector(selector)}catch(e){continue}if(!el||el.children.length>0||el.closest('#ld-inline-ui,#larpdevice-simulation-notice,[aria-label*=\"SIMULATION\"]'))continue;
 var value=item.field==='custom'||item.field==='customImage'?item.value:fields[item.field];
 if(el.tagName==='IMG'){if(typeof value==='string'&&/^data:image\/(png|jpeg|webp);base64,/.test(value)&&el.getAttribute('src')!==value)el.setAttribute('src',value);continue}
 if(value===undefined||value===null)continue;if(item.format==='money'&&typeof value==='number'){value=(item.symbol||'$')+value.toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2})}else{value=String(value)}if(el.textContent!==value)el.textContent=value;
 }}
function build(){if(document.getElementById('ld-inline-ui'))return;
 var ui=document.createElement('div');ui.id='ld-inline-ui';ui.innerHTML='<div id="ld-inline-cover" hidden></div><section id="ld-inline-panel" role="dialog" aria-label="Edit this LARP demo" hidden><div class="ld-handle"></div><div class="ld-head"><b>Demo settings</b><button type="button" id="ld-inline-close" aria-label="Close">&times;</button></div><p class="ld-tip">Hold a label, number or profile photo to edit it. On desktop, double-click. Values are fictional and saved to this LARP.</p><label class="ld-label">What would you like to edit?<select id="ld-inline-mode"></select></label><label class="ld-label" id="ld-inline-value-wrap">Value<input id="ld-inline-value" autocomplete="off" maxlength="120"/></label><p id="ld-inline-status" role="status" aria-live="polite"></p><div class="ld-actions"><button id="ld-inline-cancel" type="button">Cancel</button><button id="ld-inline-save" type="button">Save changes</button></div></section>';
 document.body.appendChild(ui);panel=ui.querySelector('#ld-inline-panel');modeSelect=ui.querySelector('#ld-inline-mode');valueInput=ui.querySelector('#ld-inline-value');status=ui.querySelector('#ld-inline-status');
 for(var i=0;i<core.length;i++){var opt=document.createElement('option');opt.value=core[i];opt.textContent=names[i];modeSelect.appendChild(opt)}
 var custom=document.createElement('option');custom.value='custom';custom.textContent='Only this text';modeSelect.appendChild(custom);var photo=document.createElement('option');photo.value='customImage';photo.textContent='Replace selected image';modeSelect.appendChild(photo);
 ui.querySelector('#ld-inline-close').addEventListener('click',close);ui.querySelector('#ld-inline-cancel').addEventListener('click',close);ui.querySelector('#ld-inline-cover').addEventListener('click',close);
 modeSelect.addEventListener('change',refreshInput);ui.querySelector('#ld-inline-save').addEventListener('click',save);
 window.addEventListener('message',function(e){if(e.source!==window.parent||!e.data||e.data.type!=='larpdevice:inline-result')return;var resolve=pending[e.data.requestId];if(!resolve)return;delete pending[e.data.requestId];resolve(e.data)});
 renderSaved();
 if(window.MutationObserver){var t=null;new MutationObserver(function(){clearTimeout(t);t=setTimeout(renderSaved,120)}).observe(document.body,{subtree:true,childList:true,characterData:true})}
 // Cash App phone already has its own long-press editor. Do not intercept it.
 if(!cfg.existingHoldEditor){document.addEventListener('pointerdown',function(e){if(e.target.closest('#ld-inline-ui'))return;downX=e.clientX;downY=e.clientY;clearTimeout(timer);var target=candidate(e.target);if(target)timer=setTimeout(function(){open(target)},570)},true);
 document.addEventListener('pointermove',function(e){if(Math.abs(e.clientX-downX)>12||Math.abs(e.clientY-downY)>12)clearTimeout(timer)},true);
 ['pointerup','pointercancel','scroll'].forEach(function(k){document.addEventListener(k,function(){clearTimeout(timer)},true)});
 document.addEventListener('dblclick',function(e){var target=candidate(e.target);if(target){e.preventDefault();open(target)}},true)}
 }
function open(el){selected=el&&pathFor(el)?{selector:pathFor(el),text:(el.textContent||'').trim(),image:el.tagName==='IMG'}:null;panel.hidden=false;document.getElementById('ld-inline-cover').hidden=false;
 modeSelect.querySelector('option[value="custom"]').disabled=!selected||selected.image;modeSelect.querySelector('option[value="customImage"]').disabled=!selected||!selected.image;
 var old=selected&&bindings[selected.selector];modeSelect.value=old?old.field:(selected?(selected.image?'customImage':'custom'):'displayName');refreshInput();status.textContent=selected?'Editing selected text':'Edit the saved values for this LARP';}
function refreshInput(){var key=modeSelect.value,existing=selected&&bindings[selected.selector];valueInput.type=key==='customImage'?'file':(key==='balance'||key==='secondaryValue')?'number':'text';if(key==='customImage')valueInput.accept='image/png,image/jpeg,image/webp';valueInput.inputMode=valueInput.type==='number'?'decimal':'text';valueInput.maxLength=key==='custom'?120:90;
 var value=key==='custom'?(existing&&existing.field==='custom'?existing.value:selected?selected.text:''):fields[key];valueInput.value=key==='customImage'?'':value==null?'':String(value)}
function close(){panel.hidden=true;document.getElementById('ld-inline-cover').hidden=true;selected=null}
function save(){var field=modeSelect.value;
 if(field==='customImage'){
  var f=valueInput.files&&valueInput.files[0];if(!f||!/^image\/(png|jpeg|webp)$/.test(f.type)||f.size>8000000){status.textContent='Choose a PNG, JPEG, or WebP under 8 MB.';return}
  var url=URL.createObjectURL(f),img=new Image();status.textContent='Preparing image…';
  img.onload=function(){var c=document.createElement('canvas');c.width=256;c.height=256;var x=c.getContext('2d');if(!x){URL.revokeObjectURL(url);status.textContent='Image error';return}
   var side=Math.min(img.naturalWidth,img.naturalHeight);x.drawImage(img,(img.naturalWidth-side)/2,(img.naturalHeight-side)/2,side,side,0,0,256,256);
   URL.revokeObjectURL(url);var value=c.toDataURL('image/jpeg',0.8);if(value.length>260000){status.textContent='Image too large.';return}savePrepared(field,value,value)};
  img.onerror=function(){URL.revokeObjectURL(url);status.textContent='Image could not be opened.'};img.src=url;return
 }
 var raw=valueInput.value.trim(),value=field==='balance'||field==='secondaryValue'?Number(raw):raw;
 savePrepared(field,raw,value)}
function savePrepared(field,raw,value){
 if(!raw||(field!=='customImage'&&raw.length>120)||!core.includes(field)&&field!=='custom'&&field!=='customImage'||!selected&&(field==='custom'||field==='customImage')){status.textContent='Enter a valid value.';return}
 if(field==='cashtag'&&!/^\$?[a-zA-Z0-9_]{1,30}$/.test(raw)){status.textContent='Use letters, numbers or underscore for the cashtag.';return}
 if(typeof value==='number'&&(!Number.isFinite(value)||value<0||value>999999999)){status.textContent='Enter a nonnegative demo amount.';return}
 var symbol=selected&&selected.text.match(/^\s*([$£€¥])/);
 var message={type:'larpdevice:inline-edit',requestId:'inline-'+(++stamp),mode:selected?(field==='custom'||field==='customImage'?'text':'bind'):'field',selector:selected&&selected.selector,field:field,value:value};
 if(selected&&(field==='balance'||field==='secondaryValue')&&symbol){message.format='money';message.symbol=symbol[1]}
 status.textContent='Saving…';var button=document.getElementById('ld-inline-save');button.disabled=true;
 new Promise(function(resolve){pending[message.requestId]=resolve;window.parent.postMessage(message,'*');setTimeout(function(){if(pending[message.requestId]){delete pending[message.requestId];resolve({ok:false,error:'Save timed out. Open this LARP through the website.'})}},12000)})
 .then(function(r){button.disabled=false;status.textContent=r.ok?'Saved. Refreshing…':(r.error||'Could not save.');if(r.ok){fields[field]=value;if(selected)bindings[selected.selector]={field:field,value:field==='custom'||field==='customImage'?raw:undefined,format:message.format,symbol:message.symbol};renderSaved();setTimeout(close,450)}});
}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',build);else build();
})();`;
const EDIT_CSS=String.raw`<style id="ld-inline-css">
#ld-inline-ui{font-family:system-ui,-apple-system,sans-serif!important;z-index:2147483644!important;color:#fff!important}
#ld-inline-cover:not([hidden]){position:fixed!important;inset:0!important;background:#0008!important;z-index:2147483645!important}
#ld-inline-panel:not([hidden]){box-sizing:border-box!important;position:fixed!important;left:50%!important;bottom:0!important;transform:translateX(-50%)!important;width:min(100%,500px)!important;max-height:min(80vh,610px)!important;overflow-y:auto!important;background:#191a25!important;color:#fff!important;z-index:2147483646!important;padding:18px 20px 26px!important;border-radius:20px 20px 0 0!important;box-shadow:0 -8px 45px #0009!important;line-height:1.4!important;text-align:left!important}
#ld-inline-panel *{box-sizing:border-box!important;font-family:inherit!important}
#ld-inline-panel .ld-handle{height:4px!important;width:36px!important;border-radius:50px!important;background:#888!important;margin:-8px auto 18px!important}
#ld-inline-panel .ld-head{display:flex!important;align-items:center!important;justify-content:space-between!important;font-size:18px!important;margin-bottom:8px!important}
#ld-inline-panel .ld-head button{color:white!important;background:none!important;border:none!important;font-size:28px!important;cursor:pointer!important}
#ld-inline-panel .ld-tip{font-size:12px!important;color:#b9b9cc!important;margin:8px 0 18px!important}
#ld-inline-panel .ld-label{display:block!important;font-size:13px!important;font-weight:600!important;margin:14px 0!important;color:#fff!important}
#ld-inline-panel select,#ld-inline-panel input{display:block!important;width:100%!important;min-height:43px!important;background:#292a38!important;color:#fff!important;border:1px solid #717183!important;border-radius:10px!important;padding:10px!important;font-size:15px!important;margin-top:7px!important;outline-offset:2px!important}
#ld-inline-panel #ld-inline-status{font-size:12px!important;color:#c9c8dc!important;min-height:18px!important}
#ld-inline-panel .ld-actions{display:flex!important;gap:10px!important;margin-top:14px!important}
#ld-inline-panel .ld-actions button{min-height:44px!important;flex:1!important;border-radius:9px!important;border:1px solid #888!important;color:white!important;background:#323243!important;font-weight:700!important;cursor:pointer!important}
#ld-inline-panel #ld-inline-save{background:#8059fa!important;border-color:#8059fa!important}
#ld-inline-panel #ld-inline-save:disabled{opacity:.55!important}
</style>`;

export function injectInlineDemoEditor(html:string,data:DisplayData,options:{existingHoldEditor?:boolean}={}):string{
 const config=JSON.stringify({fields:Object.fromEntries(editableDemoFields.map(k=>[k,data[k]])),bindings:data.uiBindings||{},existingHoldEditor:!!options.existingHoldEditor})
  .replace(/</g,'\\u003c').replace(/>/g,'\\u003e').replace(/&/g,'\\u0026');
 const widget=EDIT_CSS+'<script type="application/json" id="ld-inline-config">'+config+'</script><script id="ld-inline-script">'+EDIT_SCRIPT+'</script>';
 return /<\/body>/i.test(html)?html.replace(/<\/body>/i,()=>widget+'</body>'):html+widget;
}
