
const DEFAULT_CONFIG={appName:'Your app name goes here',appDescription:'Add a short description of the app.',appLink:'',appImageData:'',brandLogoData:''};
const $=id=>document.getElementById(id);
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 renderConfig(c){c={...DEFAULT_CONFIG,...c};$('appName').textContent=c.appName||DEFAULT_CONFIG.appName;$('appDescription').textContent=c.appDescription||DEFAULT_CONFIG.appDescription;$('appLink').href=c.appLink||'#';$('appLink').classList.toggle('hidden',!c.appLink);$('appImageBox').innerHTML=c.appImageData?`<img src="${c.appImageData}" alt="App image">`:'App image / screenshot';if(c.brandLogoData){$('adminLogoTrigger').src=c.brandLogoData;$('adminLogoTrigger').alt='Page 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 failed');renderConfig(extractConfig(result.body));}catch(e){renderConfig(DEFAULT_CONFIG);}}
async function submitTesterForm(form){
  const data=new FormData(form);
  data.set('form-name','app-signup');
  data.set('submitted_at',new Date().toISOString());
  data.set('page_url',window.location.href);
  const body=new URLSearchParams(data).toString();
  const r=await fetch('/',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body});
  if(!r.ok){throw new Error('Form submit HTTP '+r.status);}
}
$('signupForm').addEventListener('submit',async e=>{
  e.preventDefault();
  const button=e.target.querySelector('button[type="submit"]');
  const original=button.textContent;
  try{
    button.disabled=true;button.textContent='Submitting...';
    await submitTesterForm(e.target);
    $('beforeBox').classList.add('hidden');$('successBox').classList.remove('hidden');
    e.target.reset();
  }catch(err){
    alert('Could not submit details. Please try again or contact the app owner. '+err.message);
  }finally{
    button.disabled=false;button.textContent=original;
  }
});

const adminLogo=$('adminLogoTrigger');
let adminPressTimer=null;
function clearAdminPress(){
  if(adminPressTimer){clearTimeout(adminPressTimer);adminPressTimer=null;}
  if(adminLogo)adminLogo.classList.remove('admin-pressing');
}
if(adminLogo){
  const start=()=>{
    clearAdminPress();
    adminLogo.classList.add('admin-pressing');
    adminPressTimer=setTimeout(()=>{window.location.href='admin.html';},4000);
  };
  adminLogo.addEventListener('pointerdown',start);
  ['pointerup','pointercancel','pointerleave','lostpointercapture'].forEach(evt=>adminLogo.addEventListener(evt,clearAdminPress));
  adminLogo.addEventListener('contextmenu',e=>e.preventDefault());
}

loadConfig();
