// @ts-check
(()=>{
  'use strict';
  const App=window.IUS_TEMPLATE,{utils,state}=App;let purpose='project';
  const fields={
    project:[['name','text','form.name','form.placeholder.name','name',true],['email','email','form.email','form.placeholder.email','email',true],['organisation','text','form.organisation','form.placeholder.org','organization',false],['projectType','select','form.type','', '',true],['budget','text','form.budget','form.placeholder.budget','',false],['launchDate','text','form.date','form.placeholder.date','',false],['summary','textarea','form.summary','form.placeholder.summary','',true,'wide'],['reference','url','form.reference','form.placeholder.url','url',false,'wide']],
    general:[['name','text','form.name','form.placeholder.name','name',true],['email','email','form.email','form.placeholder.email','email',true],['subject','text','form.subject','form.placeholder.subject','',true,'wide'],['message','textarea','form.message','form.placeholder.message','',true,'wide'],['reply','select','form.reply','', '',true]]
  };
  const q=s=>utils.$(s),draftKey=()=>`ius-template-form-draft:${purpose}`;
  const memory=new Map(),safeGet=k=>{try{return localStorage.getItem(k)}catch(_){return memory.get(k)||null}},safeSet=(k,v)=>{try{localStorage.setItem(k,v)}catch(_){memory.set(k,v)}},safeRemove=k=>{try{localStorage.removeItem(k)}catch(_){memory.delete(k)}};
  function createField(def){const [name,type,labelKey,placeholderKey,autocomplete,required,width]=def,wrap=document.createElement('div');wrap.className=`field${width==='wide'?' field-wide':''}`;const label=document.createElement('label');label.htmlFor=`form-${name}`;label.textContent=App.modules.i18n.t(labelKey)+(required?' *':'');let input;if(type==='textarea')input=document.createElement('textarea');else if(type==='select'){input=document.createElement('select');const opts=purpose==='project'?['','Brand or strategy','Website or digital product','Campaign or content','Development or implementation','Ongoing support','Other enquiry']:['','Email','Telephone','Video call'];opts.forEach((text,i)=>{const o=document.createElement('option');o.value=text;o.textContent=text||(state.locale==='ja'?'選択してください':'Choose one');input.append(o)})}else{input=document.createElement('input');input.type=type}input.id=`form-${name}`;input.name=name;if(required)input.required=true;if(autocomplete)input.autocomplete=autocomplete;if(placeholderKey)input.placeholder=App.modules.i18n.t(placeholderKey);if(type==='textarea')input.maxLength=purpose==='project'?1600:1200;else input.maxLength=240;wrap.append(label,input);return wrap}
  function buildFields(){const host=q('[data-form-fields]');host.replaceChildren();const grid=document.createElement('div');grid.className='form-grid';fields[purpose].forEach(def=>grid.append(createField(def)));host.append(grid);const saved=safeGet(draftKey());q('[data-draft-banner]').hidden=!saved}
  function values(){return Object.fromEntries(new FormData(q('[data-purpose-form]')).entries())}
  function saveDraft(){const form=q('[data-purpose-form]');if(!form)return;const data=values();delete data.consent;safeSet(draftKey(),JSON.stringify(data));q('[data-draft-banner]').hidden=false}
  function restore(){try{const data=JSON.parse(safeGet(draftKey())||'{}');Object.entries(data).forEach(([name,value])=>{const field=q(`[name="${CSS.escape(name)}"]`,q('[data-purpose-form]'));if(field)field.value=String(value)});q('[data-draft-banner]').hidden=true}catch(_){}}
  function discard(){safeRemove(draftKey());q('[data-purpose-form]').reset();q('[data-draft-banner]').hidden=true}
  function open(next,trigger){purpose=next==='general'?'general':'project';q('[data-form-title]').textContent=App.modules.i18n.t(`form.${purpose}.title`);q('[data-form-description]').textContent=App.modules.i18n.t(`form.${purpose}.desc`);buildFields();q('[data-form-status]').textContent='';q('[data-error-summary]').hidden=true;utils.openDialog(q('[data-form-dialog]'),trigger);q('[data-purpose-form] input, [data-purpose-form] textarea, [data-purpose-form] select')?.focus()}
  function close(){saveDraft();utils.closeDialog(q('[data-form-dialog]'))}
  function summary(data){const labels={name:'form.name',email:'form.email',organisation:'form.organisation',projectType:'form.type',budget:'form.budget',launchDate:'form.date',summary:'form.summary',reference:'form.reference',subject:'form.subject',message:'form.message',reply:'form.reply'};return Object.entries(data).filter(([k])=>k!=='consent').map(([k,v])=>`${App.modules.i18n.t(labels[k]||k)}: ${v||'—'}`).join('\n')}
  function printForm(){const form=q('[data-purpose-form]');if(!form.reportValidity())return;const data=values(),print=q('[data-print-document]');print.replaceChildren();const header=document.createElement('header'),h=document.createElement('h1');h.textContent=App.modules.i18n.t(`form.${purpose}.title`);const meta=document.createElement('div');meta.className='print-meta';meta.innerHTML=`<span>${utils.escapeHtml(App.data.siteConfig.brand.name)}</span><span>${utils.escapeHtml(new Intl.DateTimeFormat(state.locale==='ja'?'ja-JP':'en-GB',{dateStyle:'long',timeStyle:'short'}).format(new Date()))}</span>`;header.append(h,meta);const dl=document.createElement('dl');Object.entries(data).filter(([k])=>k!=='consent').forEach(([k,v])=>{const def=fields[purpose].find(f=>f[0]===k),dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=App.modules.i18n.t(def?.[2]||k);dd.textContent=String(v||'—');dl.append(dt,dd)});const sign=document.createElement('div');sign.className='print-signature';sign.innerHTML='<span>Signature</span><span>Date</span>';const footer=document.createElement('footer');footer.innerHTML=`<span>${utils.escapeHtml(location.href)}</span><span>Designed by I/US brand. · iusmusic.com</span>`;print.append(header,dl,sign,footer);window.print()}
  function submit(event){event.preventDefault();const form=event.currentTarget,status=q('[data-form-status]'),invalid=utils.$$(':invalid',form);status.className='form-status';if(invalid.length){const box=q('[data-error-summary]');box.hidden=false;box.textContent=App.modules.i18n.t('form.required');box.focus();invalid[0].focus();return}const data=values(),subject=purpose==='project'?`Project enquiry — ${data.name}`:`General contact — ${data.subject}`,body=summary(data),email=App.data.siteConfig.brand.email;status.textContent=App.modules.i18n.t('form.prepared');status.classList.add('success');safeRemove(draftKey());window.location.href=`mailto:${email}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`}
  function init(){utils.$$('[data-form-open]').forEach(b=>b.addEventListener('click',()=>{const details=q('[data-details-dialog]');if(details?.open)utils.closeDialog(details);open(b.dataset.formOpen,b)}));utils.$$('[data-form-close]').forEach(b=>b.addEventListener('click',close));q('[data-purpose-form]')?.addEventListener('input',()=>{clearTimeout(q('[data-purpose-form]')._draftTimer);q('[data-purpose-form]')._draftTimer=setTimeout(saveDraft,400)});q('[data-purpose-form]')?.addEventListener('submit',submit);q('[data-form-print]')?.addEventListener('click',printForm);q('[data-draft-restore]')?.addEventListener('click',restore);q('[data-draft-discard]')?.addEventListener('click',discard);document.addEventListener('ius:localechange',()=>{if(q('[data-form-dialog]')?.open){const data=values();q('[data-form-title]').textContent=App.modules.i18n.t(`form.${purpose}.title`);q('[data-form-description]').textContent=App.modules.i18n.t(`form.${purpose}.desc`);buildFields();Object.entries(data).forEach(([name,value])=>{const field=utils.$(`[name=\"${CSS.escape(name)}\"]`,q('[data-purpose-form]'));if(field)field.value=String(value)})}})}
  App.modules.forms={init,open,close,printForm};
})();
