
const DEFAULT_CONFIG={appName:'',appDescription:'',appLink:'',appImageData:'',brandLogoData:''};
const $=id=>document.getElementById(id);let imageData='';let brandLogoData='';
function setStatus(text,type='warn'){$('status').className=type;$('status').textContent=text;}
async function readResponse(response){
  const text=await response.text();
  let body=text;
  try{body=JSON.parse(text);}catch(e){}
  return {body};
}
function extractConfig(payload){return payload && payload.config ? payload.config : (payload || {});}
function render(){const n=$('appName').value.trim()||'App name';const d=$('appDescription').value.trim()||'Description preview';const l=$('appLink').value.trim();$('namePreview').textContent=n;$('descPreview').textContent=d;$('linkPreview').textContent=l;$('imgPreview').innerHTML=imageData?`<img src="${imageData}" alt="App image preview">`:'App image / screenshot';$('brandLogoPreview').innerHTML=brandLogoData?`<img src="${brandLogoData}" alt="Page logo preview">`:'Current logo';}
async function loadConfig(){
  try{
    const r=await fetch('/.netlify/functions/get-config?ts='+Date.now(),{cache:'no-store'});
    const result=await readResponse(r);
    if(!r.ok)throw new Error('get-config HTTP '+r.status);
    const c={...DEFAULT_CONFIG,...extractConfig(result.body)};
    $('appName').value=c.appName||'';$('appDescription').value=c.appDescription||'';$('appLink').value=c.appLink||'';imageData=c.appImageData||'';brandLogoData=c.brandLogoData||'';render();
    setStatus('Current app details loaded.','notice');
  }catch(e){setStatus('Admin storage/load failed: '+e.message,'warn');render();}
}
['appName','appDescription','appLink'].forEach(id=>$(id).addEventListener('input',render));
async function fileToDataUrl(file,maxW,maxH,quality){return new Promise((resolve,reject)=>{const reader=new FileReader();reader.onerror=()=>reject(new Error('Could not read image'));reader.onload=()=>{const img=new Image();img.onerror=()=>reject(new Error('Could not load image'));img.onload=()=>{let w=img.width,h=img.height;const scale=Math.min(1,maxW/w,maxH/h);w=Math.max(1,Math.round(w*scale));h=Math.max(1,Math.round(h*scale));const canvas=document.createElement('canvas');canvas.width=w;canvas.height=h;const ctx=canvas.getContext('2d');ctx.drawImage(img,0,0,w,h);resolve(canvas.toDataURL('image/jpeg',quality));};img.src=reader.result;};reader.readAsDataURL(file);});}
$('appImage').addEventListener('change',async()=>{const file=$('appImage').files&&$('appImage').files[0];if(!file)return;try{imageData=await fileToDataUrl(file,1200,900,.82);render();setStatus('App image ready. Press Publish to save.','notice');}catch(e){setStatus(e.message,'warn');}});
$('brandLogo').addEventListener('change',async()=>{const file=$('brandLogo').files&&$('brandLogo').files[0];if(!file)return;try{brandLogoData=await fileToDataUrl(file,700,700,.86);render();setStatus('Logo ready. Press Publish to save.','notice');}catch(e){setStatus(e.message,'warn');}});
$('publish').addEventListener('click',async()=>{
  const btn=$('publish');btn.disabled=true;btn.textContent='Publishing...';
  try{
    const outgoing={pin:$('pin').value,appName:$('appName').value,appDescription:$('appDescription').value,appLink:$('appLink').value,appImageData:imageData,brandLogoData:brandLogoData};
    const r=await fetch('/.netlify/functions/save-config',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(outgoing)});
    const saveResult=await readResponse(r);
    if(!r.ok){throw new Error('save-config HTTP '+r.status);}
    const verify=await fetch('/.netlify/functions/get-config?verify='+Date.now(),{cache:'no-store'});
    const verifyResult=await readResponse(verify);
    if(!verify.ok)throw new Error('get-config verification HTTP '+verify.status);
    const c={...DEFAULT_CONFIG,...extractConfig(verifyResult.body)};
    $('appName').value=c.appName||'';$('appDescription').value=c.appDescription||'';$('appLink').value=c.appLink||'';imageData=c.appImageData||'';brandLogoData=c.brandLogoData||'';render();
    if((c.appName||'')!==(outgoing.appName||'')){throw new Error('Verification mismatch: saved name and loaded name differ');}
    setStatus('Published. The public page has been updated.','notice');
  }catch(e){setStatus('Could not publish: '+e.message,'warn');}
  finally{btn.disabled=false;btn.textContent='Publish app details';}
});
loadConfig();
