import {checklist,checklistCSV,schedule,scheduleCSV,labelPlan,labelSheet} from './planning-engine.v1.mjs'; const root=document.getElementById('planning-tool'); if(root){try{init(root);}catch(e){const f=document.getElementById('planning-fallback');if(f)f.textContent='Interactive editor could not start. The original examples and downloads remain available below.';}} function init(root){ const by=id=>{const e=document.getElementById(id);if(!e)throw Error('Missing control '+id);return e;}; const node=(tag,txt)=>{const n=document.createElement(tag);if(txt!==undefined)n.textContent=txt;return n;}; const status=by('planning-status'),editor=by('planning-editor'),output=by('planning-output'),download=by('planning-download'),print=by('planning-print');let result=null,file=null; function invalid(message){result=null;file=null;output.replaceChildren();output.hidden=true;download.disabled=print.disabled=true;delete document.body.dataset.planningReady;status.textContent=message;} function ready(content,name,mime,bytes,message){output.replaceChildren(content);output.hidden=false;download.disabled=print.disabled=false;document.body.dataset.planningReady='yes';file={name,mime,bytes};status.textContent=message;} function table(headers,rows){const wrap=node('div');wrap.className='planning-table';wrap.tabIndex=0;wrap.setAttribute('role','region');wrap.setAttribute('aria-label','Generated printable results');const t=node('table'),head=node('thead'),tr=node('tr');for(const h of headers){const th=node('th',h);th.scope='col';tr.append(th);}head.append(tr);t.append(head);const body=node('tbody');for(const r of rows){const row=node('tr');for(const cell of r)row.append(node('td',String(cell)));body.append(row);}t.append(body);wrap.append(t);return wrap;} function field(parent,label,type,value,max,attrs={}){const l=node('label',label),i=node(type==='textarea'?'textarea':'input');if(type!=='textarea')i.type=type;Object.assign(i,attrs);if(max)i.maxLength=max;if(type==='checkbox')i.checked=!!value;else i.value=value;l.append(i);parent.append(l);return i;} function btn(label,fn){const b=node('button',label);b.type='button';b.addEventListener('click',fn);return b;} download.addEventListener('click',()=>{if(!file)return;let url;try{url=URL.createObjectURL(new Blob([file.bytes],{type:file.mime}));const a=node('a');a.href=url;a.download=file.name;document.body.append(a);a.click();a.remove();status.textContent='Download requested. Keep exported information private.';}catch{status.textContent='Download could not start. Try again or use the original resources.';}finally{if(url)setTimeout(()=>URL.revokeObjectURL(url),30000);}}); print.addEventListener('click',()=>{if(!file)return;try{window.print();}catch{status.textContent='Print is unavailable in this browser.';}}); function update(fn){try{fn();}catch(e){invalid(e.message||'Check your inputs.');}} const kind=root.dataset.planning; if(kind==='wedding'){ const date=by('planning-date'),list=by('planning-rows');const source=[...document.querySelectorAll('.pme-resource tbody tr')];if(source.length!==16)throw Error('Invalid original task list');const rows=source.map((r,i)=>{const [phase,task]=[...r.querySelectorAll('td')].map(t=>t.textContent.trim());const card=node('fieldset');card.append(node('legend',`${i+1}. ${task}`),node('p',phase));const fields={phase,task,owner:field(card,'Owner (optional)','text','',80),due:field(card,'Due date','date',''),done:field(card,'Completed','checkbox',false),notes:field(card,'Notes (optional)','textarea','',240)};list.append(card);return fields;}); const collect=()=>rows.map(r=>({phase:r.phase,task:r.task,owner:r.owner.value,due:r.due.value,done:r.done.checked,notes:r.notes.value})); function render(){result=checklist(collect(),date.value);const done=result.filter(r=>r.done).length,box=node('div');box.append(node('h3','Wedding planning checklist'),node('p',`Wedding date: ${date.value||'Not set'} · ${done} of 16 completed`),table(['Phase','Task','Owner','Due date','Status','Notes'],result.map(r=>[r.phase,r.task,r.owner,r.due,r.done?'Done':'Not started',r.notes])));ready(box,'wedding-checklist-custom.csv','text/csv;charset=utf-8',checklistCSV(result,date.value),`${done} of 16 tasks completed. Changes are temporary until exported.`);} by('planning-suggest').addEventListener('click',()=>update(()=>{const suggested=checklist(collect(),date.value,true);suggested.forEach((r,i)=>{rows[i].due.value=r.due;});render();status.textContent+=' Blank dates filled using the example offsets only.';}));editor.addEventListener('input',()=>update(render));update(render); }else if(kind==='run'){ const list=by('planning-rows'),rows=[];const sample=[...document.querySelectorAll('.pme-resource tbody tr')];if(sample.length!==6)throw Error('Invalid original schedule'); function add(v={segment:'',duration:'5',owner:'',cue:'',dependency:''}){if(rows.length>=40)return;const card=node('fieldset'),legend=node('legend');card.append(legend);const row={card,legend,segment:field(card,'Segment','text',v.segment,100),duration:field(card,'Duration (minutes)','number',v.duration,null,{min:'1',max:'720',step:'1'}),owner:field(card,'Owner (optional)','text',v.owner,80),cue:field(card,'Cue / fallback (optional)','textarea',v.cue,240),dependency:field(card,'Dependency (optional)','text',v.dependency,120)};row.remove=btn('Remove segment',()=>{if(rows.length<=1)return;const i=rows.indexOf(row);rows.splice(i,1);card.remove();renumber();update(render);(rows[Math.min(i,rows.length-1)].segment).focus();});card.append(row.remove);list.append(card);rows.push(row);renumber();return row;} function renumber(){rows.forEach((r,i)=>{r.legend.textContent=`Segment ${i+1}`;r.remove.disabled=rows.length<=1;});by('planning-add').disabled=rows.length>=40;} function render(){result=schedule({date:by('planning-date').value,start:by('planning-start').value,timezone:by('planning-zone').value,revision:by('planning-revision').value,rows:rows.map(r=>({segment:r.segment.value,duration:r.duration.value,owner:r.owner.value,cue:r.cue.value,dependency:r.dependency.value}))});const box=node('div');box.append(node('h3','Run of show'),node('p',`Revision ${result.revision} · ${result.timezone} · ${result.total} minutes`),table(['Start (local)','End (local)','Minutes','Segment','Owner','Cue / fallback','Dependency'],result.segments.map(r=>[r.start.date+' '+r.start.time,r.end.date+' '+r.end.time,r.duration,r.segment,r.owner,r.cue,r.dependency])));ready(box,'run-of-show-custom.csv','text/csv;charset=utf-8',scheduleCSV(result),`${rows.length} segments · ${result.total} minutes. Verify the schedule and distribute the approved revision.`);} sample.forEach(r=>{const c=[...r.querySelectorAll('td')].map(x=>x.textContent.trim());add({segment:c[2],duration:c[1].replace(' min',''),owner:c[3],cue:c[4],dependency:''});});by('planning-add').addEventListener('click',()=>{const r=add();update(render);r?.segment.focus();});editor.addEventListener('input',()=>update(render));update(render); }else if(kind==='labels'){ let page=1;const prev=by('planning-prev'),next=by('planning-next'); const options=()=>({first:by('planning-first').value,count:by('planning-count').value,paper:by('planning-paper').value,theme:by('planning-theme').value,prefix:by('planning-prefix').value,pad:by('planning-pad').checked}); function render(){prev.disabled=next.disabled=true;const opts=options(),plan=labelPlan(opts);page=Math.min(page,plan.pages);result=labelSheet(opts,page);const doc=new DOMParser().parseFromString(result.svg,'image/svg+xml');if(doc.querySelector('parsererror'))throw Error('Unable to prepare label sheet.');const box=node('div');box.className='planning-sheet';box.append(document.importNode(doc.documentElement,true));ready(box,`table-numbers-sheet-${page}.svg`,'image/svg+xml;charset=utf-8',result.svg,`Sheet ${page} of ${plan.pages} · numbers ${result.labels.join(', ')} · ${plan.paper}. Print/download this sheet; use Next for more.`);prev.disabled=page===1;next.disabled=page===plan.pages;} prev.addEventListener('click',()=>{if(page>1){page--;update(render);}});next.addEventListener('click',()=>{page++;update(render);});editor.addEventListener('input',()=>{page=1;update(render);});update(render); }else throw Error('Unknown tool'); editor.hidden=false;by('planning-fallback').hidden=true; }