import {COUNTRY_OPTIONS,normalizePhone,validateRegistration,validateContact} from './shared.mjs';
const C=window.TC_CONFIG;
const $=(s,r=document)=>r.querySelector(s), $$=(s,r=document)=>Array.from(r.querySelectorAll(s));
const storage={get(k,session=false){try{return (session?sessionStorage:localStorage).getItem(k)}catch{return null}},set(k,v,session=false){try{(session?sessionStorage:localStorage).setItem(k,v)}catch{}}};
const CONSENT_KEY='tc_consent_v1',CONSENT_AGE=180*864e5;
let consent={analytics:false,advertising:false}, consentSaved=false, currentModal=null,returnFocus=null,loadedTag=false,sessionToken=null;
window.dataLayer=window.dataLayer||[];
window.gtag=window.gtag||function(){window.dataLayer.push(arguments)};
const consentValues=()=>({ad_storage:consent.advertising?'granted':'denied',analytics_storage:consent.analytics?'granted':'denied',ad_user_data:consent.advertising?'granted':'denied',ad_personalization:consent.advertising?'granted':'denied',functionality_storage:'granted',security_storage:'granted'});
gtag('consent','default',{ad_storage:'denied',analytics_storage:'denied',ad_user_data:'denied',ad_personalization:'denied',functionality_storage:'granted',security_storage:'granted'});
try{const s=JSON.parse(storage.get(CONSENT_KEY));if(s&&s.version===1&&Date.now()-s.timestamp>=0&&Date.now()-s.timestamp<CONSENT_AGE){consent={analytics:s.analytics===true,advertising:s.advertising===true};consentSaved=true}}catch{}
function deleteOptionalCookies(){
 for(const entry of document.cookie.split(';')){
  const n=entry.split('=')[0].trim();if(!/^(_ga|_gid|_gat|_gcl)/.test(n))continue;
  document.cookie=n+'=; Max-Age=0; path=/; SameSite=Lax';
  const host=location.hostname.split('.');for(let i=0;i<host.length-1;i++)document.cookie=n+'=; Max-Age=0; path=/; domain=.'+host.slice(i).join('.')+'; SameSite=Lax';
 }
}
function applyConsent(){
 window['ga-disable-'+C.googleAnalyticsId]=!consent.analytics;
 gtag('consent','update',consentValues());
 if(!consent.analytics&&!consent.advertising)deleteOptionalCookies();
 const ga=/^G-[A-Z0-9]+$/.test(C.googleAnalyticsId)?C.googleAnalyticsId:null;
 const ads=/^AW-\d+$/.test(C.googleAdsId)?C.googleAdsId:null;
 const ids=[...(consent.analytics&&ga?[ga]:[]),...(consent.advertising&&ads?[ads]:[])];
 if(ids.length&&!loadedTag){
  loadedTag=true;gtag('js',new Date());
  const tag=document.createElement('script');tag.async=true;tag.src='https://www.googletagmanager.com/gtag/js?id='+encodeURIComponent(ids[0]);document.head.append(tag);
 }
 for(const id of ids)gtag('config',id,{send_page_view:false,allow_google_signals:consent.advertising,allow_ad_personalization_signals:consent.advertising,page_location:location.origin+location.pathname,page_referrer:document.referrer?new URL(document.referrer).origin:''});
}
applyConsent();
const sentEvents=new Set();
function track(name,dedupe=''){
 if(dedupe&&sentEvents.has(dedupe))return;
 if(dedupe)sentEvents.add(dedupe);
 const payload={event:name,brand:'tradingcourtyard',page_path:location.pathname};
 if(consent.analytics){window.dataLayer.push(payload);if(C.googleAnalyticsId)gtag('event',name,{brand:'tradingcourtyard',page_path:location.pathname,page_location:location.origin+location.pathname});}
 if(name==='registration_success'&&consent.advertising&&/^AW-\d+$/.test(C.googleAdsId)&&C.googleAdsConversionLabel)gtag('event','conversion',{send_to:C.googleAdsId+'/'+C.googleAdsConversionLabel,transaction_id:dedupe});
}
const banner=$('#cookie-banner');
function updateBanner(){if(banner)banner.hidden=consentSaved||!!currentModal;}
updateBanner();
function saveConsent(a,b){consent={analytics:a,advertising:b};consentSaved=true;storage.set(CONSENT_KEY,JSON.stringify({...consent,version:1,timestamp:Date.now()}));applyConsent();if(currentModal?.id==='cookie-modal')closeModal();updateBanner();}
$$('[data-consent-action]').forEach(b=>b.addEventListener('click',()=>{const action=b.dataset.consentAction;if(action==='accept')saveConsent(true,true);else if(action==='reject')saveConsent(false,false);else openCookieSettings(b)}));
function focusable(el){return $$('a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex="0"]',el).filter(x=>!x.closest('[hidden]')&&x.getClientRects().length)}
function openModal(modal,trigger){
 if(currentModal)closeModal(false);
 returnFocus=trigger||document.activeElement;if(returnFocus&&!returnFocus.getClientRects().length)returnFocus=$('.menu-toggle');currentModal=modal;modal.hidden=false;document.body.classList.add('locked');
 for(const el of document.body.children)if(el!==modal&&!['SCRIPT','LINK'].includes(el.tagName))el.inert=true;
 updateBanner();requestAnimationFrame(()=>{$('.modal-panel',modal).scrollTop=0;($('.modal-close',modal)||focusable(modal)[0])?.focus()});
}
function closeModal(restore=true){if(!currentModal)return;currentModal.hidden=true;currentModal=null;document.body.classList.remove('locked');for(const el of document.body.children)el.inert=false;updateBanner();if(restore&&returnFocus?.isConnected)returnFocus.focus();}
$$('.modal').forEach(m=>{m.addEventListener('click',e=>{if(e.target===m||e.target.closest('[data-close-modal]'))closeModal()})});
document.addEventListener('keydown',e=>{
 if(!currentModal)return;
 if(e.key==='Escape'){e.preventDefault();closeModal();return}
 if(e.key==='Tab'){const f=focusable(currentModal);if(!f.length){e.preventDefault();return}const first=f[0],last=f.at(-1);if(e.shiftKey&&(document.activeElement===first||!currentModal.contains(document.activeElement))){e.preventDefault();last.focus()}else if(!e.shiftKey&&(document.activeElement===last||!currentModal.contains(document.activeElement))){e.preventDefault();first.focus()}}
});
function openCookieSettings(trigger){$('#consent-analytics').checked=consent.analytics;$('#consent-advertising').checked=consent.advertising;openModal($('#cookie-modal'),trigger)}
$$('[data-cookie-settings]').forEach(b=>b.addEventListener('click',()=>openCookieSettings(b)));
$('#save-consent')?.addEventListener('click',()=>saveConsent($('#consent-analytics').checked,$('#consent-advertising').checked));
const navToggle=$('.menu-toggle'),mobileNav=$('#mobile-nav');
navToggle?.addEventListener('click',()=>{const open=navToggle.getAttribute('aria-expanded')==='true';navToggle.setAttribute('aria-expanded',String(!open));mobileNav.hidden=open;navToggle.textContent=open?'Menu':'Close';});
document.addEventListener('keydown',e=>{if(e.key==='Escape'&&navToggle?.getAttribute('aria-expanded')==='true'){navToggle.click();navToggle.focus()}});
$$('[data-register]').forEach(b=>b.addEventListener('click',()=>{if(mobileNav&&!mobileNav.hidden)navToggle.click();openModal($('#registration-modal'),b);track('form_open')}));
const countries=$('#phone-country');
if(countries){for(const [iso,name,code] of COUNTRY_OPTIONS){const o=document.createElement('option');o.value=iso;o.textContent=name+(code?' (+'+code+')':'');countries.append(o)}countries.value='GB';countries.addEventListener('change',()=>{const entry=COUNTRY_OPTIONS.find(c=>c[0]===countries.value);$('#phone-help').textContent=entry[2]?'Enter your national number or full international number. Calling code: +'+entry[2]+'.':'Enter your full number, starting with + and your country code.';$('#phone').placeholder=entry[2]?'+ '+entry[2]+' …':'+ country code and number';});}
function fieldData(form){const d=Object.fromEntries(new FormData(form));for(const k of ['acceptTerms','acceptPrivacy','marketingEmail','marketingPhone','marketingSms'])d[k]=!!form.elements[k]?.checked;return d}
function showErrors(form,errors){
 $$('[data-error-for]',form).forEach(e=>{e.textContent=errors[e.dataset.errorFor]||''});
 $$('input,select,textarea',form).forEach(i=>i.setAttribute('aria-invalid',errors[i.name]?'true':'false'));
 const first=Object.keys(errors)[0];if(first)form.elements[first]?.focus();
}
function setStatus(form,msg,error=false){const status=$('[data-form-status]',form);status.hidden=false;status.classList.toggle('error-status',error);status.textContent=msg;status.setAttribute('role',error?'alert':'status');status.scrollIntoView({block:'nearest',behavior:'smooth'})}
function randomKey(){return crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+'-'+Math.random().toString(36).slice(2)}
async function getSession(){if(sessionToken&&Date.now()<sessionToken.expiresAt-5000)return sessionToken.token;const r=await fetch(C.apiBase+'/session',{credentials:'same-origin',headers:{Accept:'application/json'}});if(!r.ok)throw new Error('This service is temporarily unavailable. Please try again later.');sessionToken=await r.json();return sessionToken.token}
async function send(form,type){
 const data=fieldData(form),validator=type==='register'?validateRegistration:validateContact,errors=validator(data);showErrors(form,errors);if(Object.keys(errors).length)return;
 if(type==='register')track('form_submit');
 if(!(type==='register'?C.registrationEnabled:C.contactEnabled)){setStatus(form,type==='register'?'Online enrolment is not enabled. Your details have not been sent. The lessons are open to read. For access questions, email '+C.supportEmail+'.':'This form is not enabled. Your message has not been sent. For learning enquiries, email '+C.supportEmail+'; for privacy enquiries, email '+C.privacyEmail+'.',true);return}
 const button=$('button[type=submit]',form),old=button.textContent;button.disabled=true;button.textContent='Sending…';
 try{
  const token=await getSession();if(!form.dataset.requestKey)form.dataset.requestKey=randomKey();
  if(type==='register')data.phone=normalizePhone(data.phone,data.phoneCountry);
  const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),18000);
  let res;try{res=await fetch(C.apiBase+'/'+type,{method:'POST',credentials:'same-origin',signal:controller.signal,headers:{'Content-Type':'application/json','X-TC-Token':token,'Idempotency-Key':form.dataset.requestKey},body:JSON.stringify({...data,termsVersion:C.termsVersion,privacyVersion:C.privacyVersion,cookieConsent:{analytics:consent.analytics,advertising:consent.advertising}})})}finally{clearTimeout(timer)}
  let result;try{result=await res.json()}catch{throw new Error('We could not confirm the response. Your details are still here; you can try again.')}
  if(!res.ok||!result.ok||!result.receipt){if(result.errors)showErrors(form,result.errors);throw new Error(result.message||'Your request could not be confirmed. Please try again.')}
  track(type==='register'?'registration_success':'contact_success',result.receipt);
  if(type==='register'){storage.set('tc_receipt',JSON.stringify({receipt:result.receipt,at:Date.now()}),true);location.assign('/thank-you-confirmation/');}
  else{setStatus(form,'Your message has been received. Keep this reference: '+result.receipt+'. We will reply using the email address you provided.');form.reset();delete form.dataset.requestKey;}
 }catch(e){setStatus(form,e.name==='AbortError'?'The connection timed out. We could not confirm your request. Your details are still here; please try again.':e.message,true)}
 finally{button.disabled=false;button.textContent=old}
}
const registrationForm=$('#registration-form'),contactForm=$('#contact-form');
 for(const [form,type] of [[registrationForm,'register'],[contactForm,'contact']])if(form){form.addEventListener('submit',e=>{e.preventDefault();send(form,type)});form.addEventListener('input',e=>{delete form.dataset.requestKey;const error=$('[data-error-for="'+e.target.name+'"]',form);if(error){error.textContent='';e.target.setAttribute('aria-invalid','false')}});$('button[type=submit]',form).disabled=false;}
if(window.visualViewport){const syncViewport=()=>{document.documentElement.style.setProperty('--visual-height',window.visualViewport.height+'px');document.documentElement.style.setProperty('--visual-top',window.visualViewport.offsetTop+'px')};window.visualViewport.addEventListener('resize',syncViewport);window.visualViewport.addEventListener('scroll',syncViewport);syncViewport();}
$$('[data-operator]').forEach(e=>e.textContent=C.operator||C.brand);
$$('[data-address]').forEach(e=>{if(C.operatorAddress||C.address)e.textContent=C.operatorAddress||C.address;else e.hidden=true});
$$('[data-support-email]').forEach(e=>{if(C.supportEmail){e.textContent=C.supportEmail;if(e.tagName==='A')e.href='mailto:'+C.supportEmail}});
$$('[data-privacy-email]').forEach(e=>{if(C.privacyEmail){e.textContent=C.privacyEmail;if(e.tagName==='A')e.href='mailto:'+C.privacyEmail}});
$$('[data-domain]').forEach(e=>e.textContent=C.domain||location.hostname);
$$('[data-retention]').forEach(e=>e.textContent=String(C.retentionDays));
if(C.registrationEnabled&&C.operator&&C.supportEmail){$$('[data-prelaunch]').forEach(e=>e.hidden=true);$$('[data-live-registration]').forEach(e=>e.hidden=false)}
if(C.contactEnabled&&C.operator&&C.supportEmail){$$('[data-contact-prelaunch]').forEach(e=>e.hidden=true);$$('[data-contact-live]').forEach(e=>e.hidden=false)}
const thank=$('#thank-you-content');if(thank){
 let receipt=null;try{receipt=JSON.parse(storage.get('tc_receipt',true))}catch{}
 if(receipt&&Date.now()-receipt.at<864e5){$('#thank-heading').textContent='You’re on your way.';$('#thank-message').textContent='Your registration has been received. You can begin with the open lesson below. No email invitation is required to read the published materials.';$('#receipt').textContent='Your reference: '+receipt.receipt;$('#receipt').hidden=false;}
}
$$('[data-filter]').forEach(b=>b.addEventListener('click',()=>{$$('[data-filter]').forEach(x=>x.setAttribute('aria-pressed',String(x===b)));const f=b.dataset.filter;let count=0;$$('[data-topic]').forEach(c=>{c.hidden=f!=='all'&&c.dataset.topic!==f;if(!c.hidden)count++});$('#resource-count').textContent=count+' resource'+(count===1?'':'s')+' shown.';}));
$$('[data-print]').forEach(b=>b.addEventListener('click',()=>window.print()));
