import * as M from './model.mjs';
const KEY='fcb.review.v1', root=document.querySelector('#client-app'), dialog=document.querySelector('#client-dialog');
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
let state=M.initialState();try{const saved=JSON.parse(localStorage.getItem(KEY));if(saved?.version===M.VERSION)state=saved;}catch{}
const query=new URLSearchParams(location.search);if(query.get('service')==='freight'&&!state.order)state.service='freight';
let pendingStep=null, stepExpires=0;
let page=1, filters={search:'',carrier:'',status:'',sort:'amount'},selected=new Set(),modalContext='',toastTimer;
const paths=['/start/order/','/start/sign/','/start/payment/','/start/accounts/','/start/data/'];
function stepUp(callback){pendingStep=callback;stepExpires=Date.now()+300000;openModal('Confirm this sensitive action',`
Use the sample code 246810. This simulates a fresh, single-action verification; no email is sent.
`;
const total=()=>state.findings.reduce((n,f)=>n+f.cents,0);
function save(){try{localStorage.setItem(KEY,JSON.stringify(state));}catch{toast('Browser storage is unavailable. Keep this tab open; progress may not survive a reload.');}}
function toast(text){const el=document.querySelector('#client-toast');el.textContent=text;el.hidden=false;clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.hidden=true,5500);}
function go(path){save();location.href=path;}
function openModal(title,content){dialog.innerHTML=`
${title}
${content}`;dialog.showModal();}
function download(name,content,type='text/plain'){const url=URL.createObjectURL(new Blob([content],{type}));const link=document.createElement('a');link.href=url;link.download=name;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
function steps(){return `${['Order','Agreements','Payment','Accounts','Data'].map((label,i)=>`
`;}
function feeSummary(){const f=M.fee(total(),M.bps(state));return ``;}
function wizard(title,desc,body,index){return steps()+heading(`GET STARTED · STEP ${index+1} OF 5`,title,desc)+`
${body}${feeSummary()}
`;}
function need(text,path){return note(text,'warning')+a('Continue setup →',path,'primary');}
function portal(content){return `
${content}
`;}
function review(){return heading('PRIVATE CUSTOMER EXPERIENCE','From audit to money back.','Explore the entire journey using sample records. Each step is interactive, and your progress stays in this browser.')+`
Start where your customer starts.
Review a free audit summary, complete onboarding, then follow a finding through approval, recovery, and a fee statement.
${a('Start with the sample report →','/report/sample/','primary')}${b('Load a ready-to-use portal','ready')}
${note('This prototype does not create a contract, connect a bank, upload documents, file claims, send invitations, or charge money. Please use sample details only.')}${feeSummary()}
${[['01','Audit summary','Totals, masked findings and a clear next step.','/report/sample/'],['02–06','Customer onboarding','Order, agreements, payment, accounts and data.','/start/order/'],['07','Findings dashboard','Filter, inspect evidence and queue findings.','/app/findings/'],['08','Dispute approvals','Approve or reject with role and deadline checks.','/app/approvals/'],['09','Recovery tracking','See the filing timeline and documented credits.','/app/disputes/'],['10–11','Statements & queries','Trace each fee and hold only the queried line.','/app/billing/statements/sample/'],['S0','Passwordless sign-in','Try email-code and optional passkey states.','/signin/'],['EMAIL','Campaign management','Six sequences and 21 draft email templates.','/review/campaigns/'],['43 CHECKS','Watchtower','Inspect monitoring checks and synthetic alerts.','/review/watchtower/'],['12','Account settings','Payment changes, user roles and service controls.','/app/settings/'],['OPS','Operations preview','Review queries, filing holds and the event log.','/review/operations/']].map(([n,t,d,p])=>`${n} →${t}
${note('The amounts and records are invented. Browser-local roles and signatures demonstrate the design; they are not production authentication or legal acceptance. All customer preview pages are marked noindex. Hostinger password protection must also be enabled before sharing a private copy.')}`;}
function report(){return heading('FREE AUDIT SUMMARY · SAMPLE HOME GOODS CO.','Your shipping spend, explained.','We identified potential billing discrepancies across 90 days of sample invoices. Start with the evidence. Decide what happens next.')+`
ESTIMATED POTENTIAL RECOVERY · 463 FINDINGS
${money(total())}
Flagged for review. Recovery is not guaranteed.
${M.categories.map(([name,count,cents])=>`
${name} (${count})${money(cents)}
`).join('')}
${note('Timing matters. $18,420.55 is inside the sample filing window on October 23, 2026. The earliest deadline is November 3. Actual deadlines depend on each carrier and claim.','warning')}
${a(state.signed?'Open full sample findings →':'Review & continue →',state.signed?'/app/findings/':'/start/order/','primary')}${b('Print / save summary PDF','print')}
A preview of the findings
Shipment references are masked here. Completing the sample agreements unlocks the full demonstration table.
Demo report generated October 23, 2026. All data is synthetic.
${b('Try report status states','report-states','small')}
`;}
function order(){const d=state.orderDraft;return wizard('Confirm your business details.','A short order summary establishes the scope, fee and who can act for your business.',state.signed?note('This sample order is pinned to the completed agreement. Reset the demo to explore a different service or approval rule.','success')+a('Continue →','/start/payment/','primary'):``,0);}
function sign(){return wizard('Review before you authorize.','Understand the service and confirm who is signing.',!state.order?need('Complete the order first.','/start/order/'):state.signed?note('Sample agreement review complete. This is not a legally executed agreement.','success')+a('Continue to payment setup →','/start/payment/','primary'):`
Review invoice records, present supported findings, and seek approval before filing eligible disputes. Carrier decisions and applicable deadlines determine recovery.
Fees and records
Every sample fee maps to a documented recovery. Statement queries hold the affected line while the remaining eligible fees can proceed after notice.
Documents required for production
The full master service agreement, data processing agreement, fee exhibit, carrier letters and bank mandate require finalized legal text. They were not supplied with the specification. This summary does not replace them.
Template DEMO-SUMMARY-v1 · For design review only.
`,1);}
function payment(){return wizard('Authorize fees. Keep control.','Try a bank authorization without sharing financial information.',!state.signed?need('Review the sample agreements before authorizing fees.','/start/sign/'):`${state.method?note(`Active sample method: ${esc(state.method.name)} •••• ${state.method.last4}. ${state.replacement?'A replacement is pending; the existing method stays active.':''}`,'success'):''}${state.mandate==='pending'?note('Sample microdeposits are pending. Complete the simulation below to activate the authorization.','warning'):''}${state.mandate==='failed'?note('Sample bank connection failed. Nothing was authorized. Choose another simulation below.','error'):''}${state.replacement?`
${a('Continue to carrier accounts →','/start/accounts/','primary')}
`:''}${note('Production will use a payment provider’s hosted bank connection and signed webhook confirmation. This preview never requests account numbers or card details.')}`,2);}
function accounts(){return wizard('Connect the right carrier accounts.','Include every account you want covered. Each carrier needs its own authorization.',!state.signed?need('Complete the sample agreements first.','/start/sign/'):`${state.accounts.length?`
Carrier / account
Structure
Authorization
${state.accounts.map(x=>`
${esc(x.carrier)} ${esc(x.nickname)} ${x.number} · ZIP ${x.zip}
${esc(x.kind)}
${state.letters[x.carrier]?status('Sample letter complete','good'):b('Review '+esc(x.carrier)+' letter','letter','small',`data-id="${esc(x.carrier)}"`)}
`).join('')}
`:note('Start with a sample UPS or FedEx account. Only generated demonstration account numbers are used.')}${M.allLetters(state)?``:note('Adding another account updates the carrier letter. Review and confirm that carrier’s letter again.','warning')}`,3);}
function data(){return wizard('Bring the billing data together.','Choose a connection method and see what happens when the first file is parsed.',!M.allLetters(state)?need('Complete the carrier accounts and authorization letters first.','/start/accounts/'):`${state.dataConnected?note('Sample file parsed: 463 invoice lines are ready. No real document was uploaded.','success'):''}
${[['Upload','Use the sample invoice file.'],['Email','Preview a dedicated intake address.'],['Carrier portal','Preview a read-only connection.'],['SFTP / API','Preview a scheduled feed.']].map(([kind,desc])=>`
${kind}
${desc}
${b('Set up '+kind,'source','small',`data-id="${kind}"`)}
`;}
function filtered(){return state.findings.filter(f=>(!filters.search||[f.id,f.shipment,f.invoice,f.category].join(' ').toLowerCase().includes(filters.search.toLowerCase()))&&(!filters.carrier||f.carrier===filters.carrier)&&(!filters.status||f.status===filters.status)).sort((a,b)=>filters.sort==='deadline'?a.deadline.localeCompare(b.deadline):filters.sort==='id'?a.id.localeCompare(b.id):b.cents-a.cents);}
function findingTable(){const rows=filtered(),pages=Math.max(1,Math.ceil(rows.length/20));page=Math.min(page,pages);return `
${b('← Previous','prev','small',page===1?'disabled':'')}Page ${page} of ${pages}${b('Next →','next','small',page===pages?'disabled':'')}
`;}
function findings(){return portal(heading('CUSTOMER PORTAL','Your findings. Your next move.','Review the evidence, prioritize by deadline, and decide which discrepancies to pursue.')+(!state.signed?`
Full findings unlock after agreement review.
Your free summary remains available. Complete the sample agreements to explore all 463 demonstration findings.
${a('Review agreements →',state.order?'/start/sign/':'/start/order/','primary')}`:`${!M.active(state)?note('Finish setup to enable filing. You can explore the findings now.')+gates():''}${kpis()}${findingTable()}`));}
function approvals(){const pending=state.findings.filter(f=>f.status==='Pending approval'),approved=state.findings.filter(f=>f.status==='Approved');return portal(heading('DISPUTE APPROVALS','You decide what gets filed.','Opening this page never approves a dispute. Review the evidence and take an explicit action.')+note(`Current role: ${esc(state.role)}. ${M.approver(state)?'Demo MFA verified. Approval actions are available.':'Approval actions require an Owner, Admin or Approver with demo MFA verified.'}`)+(!state.signed?need('Complete the sample agreement to access approval packets.','/start/order/'):`
Needs your review
${status(pending.length+' pending','warn')}
${pending.length?`${b('Review all pending approvals','bulk-review','small')}${pending.slice(0,50).map(f=>`
${f.id} · ${f.category}
${f.carrier} · ${f.shipment} File by ${f.deadline} · ${f.confidence} confidence
${b('Approve','approve','primary small',`data-id="${f.id}"`)}${b('Reject','reject','small',`data-id="${f.id}"`)}${b('Ask a question','question','small',`data-id="${f.id}"`)}
`).join('')}${pending.length>50?note('Showing the first 50 pending packets. The bulk review lists the total for the full queue.'):''}`:`
'}`));}
function disputes(){return portal(heading('RECOVERY TRACKING','Every claim has a paper trail.','Follow a dispute from filing through the carrier response and a documented recovery.')+kpis()+`
${b('Load example recoveries','billing-example')}${a('View statement →','/app/billing/statements/sample/','primary')}
`);}
function billing(){const lines=M.statement(state),paid=state.payments.find(p=>p.statement==='DEMO-ST-1');const heldTotal=lines.filter(l=>M.held(l.query)).reduce((n,l)=>n+l.feeCents,0);return portal(heading('BILLING · DEMO-ST-1','A fee you can trace.','Each line connects to a confirmed recovery. Ask about a line without holding up the rest of the statement.')+`
Scheduled demonstration debit
${money(paid?paid.cents:M.debitTotal(state))}
${paid?'Simulated paid on '+paid.date:'Sample debit date: '+state.debitDate}
Advance notice: ${state.noticeSent}. No real notice is sent and no money moves.
${l.query?`${status(l.query.status,M.held(l.query)?'warn':'')} ${b('View query','query-view','small',`data-id="${l.id}"`)}`:paid?status('Included in sample payment','good'):b('Query this line','query','small',`data-id="${l.id}"`)}
`).join('')}
${note('Open queries are excluded from this demonstration debit. Undisputed fees remain payable after the notice period. All amounts and carrier documents shown here are samples.')}${paid?note(`Sample payment ${paid.id}: ${money(paid.cents)}. Duplicate processing is disabled.`,'success'):`
${b('Advance demo date to debit day','debit-day')}${b('Simulate scheduled debit','debit','primary')}
`}`:`
No confirmed recovery, no fee line.
Record a sample carrier credit in Disputes, or load the three-line billing example.
${b('Load example recoveries','billing-example','primary')}`}`);}
function settings(){return portal(heading('ACCOUNT SETTINGS','Your account, under control.','Explore payment changes, covered accounts, roles and service preferences.')+`
Payment method
${state.method?`${esc(state.method.name)} ending ${state.method.last4} · ${state.mandate}`:'No fee authorization configured.'}${state.replacement?' A replacement is pending. The original method remains active.':''}
${note('Roles and MFA are simulated in this browser. They do not provide real account security. Switch roles to inspect which actions are allowed.')}${state.users.map(u=>`
${state.ended?'Demonstration termination requested; new filings are held.':'Demonstration active. Production termination terms need a finalized agreement.'}
`);}
function operations(){return heading('OPERATIONS · SIMULATED ADMIN VIEW','Handle exceptions with context.','A review queue for billing questions, filing holds and the event history. Production permissions and durable audit logs still need implementation.')+note('This operations screen is visible for design review only. Customer roles cannot change its controls unless you select Owner or Admin in Settings.','warning')+`
Filing control
${state.filingHold?'All new filings are currently on hold.':'No account-wide filing hold.'}
This local log can be reset. Production requires a durable, append-only audit trail.
Time
Action
Actor
Details
${state.auditLog.slice(-80).reverse().map(l=>`
${esc(l.at.slice(0,19).replace('T',' '))}
${esc(l.action.replaceAll('_',' '))}
${esc(l.actor)}
${esc(l.detail)}
`).join('')||'
No events yet.
'}
`;}
function signin(){const auth=state.auth;return `
${heading('SIGN IN · PRIVATE DEMONSTRATION','Welcome back.','Use a sample email address to explore passwordless sign-in. No message or real account is created.')}${state.sessionLevel==='full'?`
Sample sign-in complete.
Your demonstration session can access the portal. Real authentication requires a secure server.
${a('Continue to portal →','/app/findings/','primary')}${b(state.passkey?'Sample passkey enabled':'Try optional passkey setup','passkey')}
`:auth&&!auth.used?`
Check your sample inbox.
If this were a connected account, a code would be sent. For this preview use 246810. It expires in ten minutes and can be used once.
${b('Request another demo code','resend-code','small')}${b('Test expired code','expire-code','small')}
`:`${state.passkey?b('Use Face ID, fingerprint or device PIN (demo)','passkey-login','wide'):''}`}${note('Displayed codes, sessions and passkeys are simulations. No WebAuthn credential is created.')}
`;}
function complete(){return heading('SETUP COMPLETE','Your sample account is ready.','The order, agreements, fee authorization, carrier letters and billing source are all in place.')+`${M.active(state)?`
✓
Next: review your findings.
Check the evidence and filing windows, send eligible findings for approval, and track the outcome.
${a('Open findings dashboard →','/app/findings/','primary')}`:need('A few setup steps still need attention.','/start/order/')}${gates()}`;}
function freeTerms(){return heading('FREE AUDIT · REVIEW DRAFT','Know what the free review includes.','These terms describe this private demonstration. They are not the finalized Free Audit Terms for a live service.')+`
Scope of the initial review
The proposed offer covers up to 90 days of invoice records. The free report provides totals by category and sample findings. Full line-level findings unlock after signup and agreement acceptance.
Estimates and authority
Estimated potential recovery is an estimate, not a guarantee. Carrier terms, evidence and filing windows determine eligibility. Completing this prototype does not authorize access, filing, payment or a legal engagement.
Data in this private preview
Use sample details only. No invoice upload is enabled. Demonstration progress stays in this browser and can be cleared using Reset demo. The ordinary Contact Us form is separate and sends through FormSubmit.
Before a live launch
The business identity, approved agreement language, retention period and service providers must be finalized. The source specification proposes deletion of unsigned audit data after 60 days; no real customer files are collected here and no retention service is running.
`;}
function render(){const views={'/signin/':signin,'/start/complete/':complete,'/free-audit-terms/':freeTerms,'/review/':review,'/report/sample/':report,'/start/order/':order,'/start/sign/':sign,'/start/payment/':payment,'/start/accounts/':accounts,'/start/data/':data,'/app/findings/':findings,'/app/approvals/':approvals,'/app/disputes/':disputes,'/app/billing/statements/sample/':billing,'/app/settings/':settings,'/review/operations/':operations};root.innerHTML=state.sessionLevel==='report_only'&&route.startsWith('/app/')?heading('REPORT-ONLY SESSION','This link opens your report only.','Sign in to access billing, settings and the customer portal.')+a('Sign in →','/signin/','primary'):(views[route]||review)();save();}
function ready(){const service=state.service;state=M.initialState();state.service=service;M.saveOrder(state,state.orderDraft);M.sign(state,'Alex Morgan','Finance Director');M.setMandate(state,'active');for(const carrier of ['UPS','FedEx']){M.addAccount(state,carrier);M.signLetter(state,carrier);}M.connectSource(state,'Upload');M.loadBillingExample(state);go('/app/findings/');}
function admin(){if(!['Owner','Admin'].includes(state.role))throw Error('Select the Owner or Admin preview role to use this operation.');}
function action(name,id){
try{const ops=JSON.parse(localStorage.getItem('fcb.internal.v1'));if(ops){state.filingHold=!!ops.switches.filing;state.debitHold=!!ops.switches.debits;state.autoApprovePaused=!!ops.switches.autoApprove;}}catch{}
switch(name){
case 'close':dialog.close();pendingStep=null;return;
case 'resend-code':M.requestCode(state);break;
case 'expire-code':state.auth.expires=Date.now()-1;toast('Demo code expired. Try verification to see the error.');break;
case 'report-session':state.sessionLevel='report_only';go('/app/settings/');return;
case 'passkey':state.passkey=true;M.log(state,'passkey_setup_simulated');toast('Sample passkey added. No device credential was created.');break;
case 'passkey-login':state.sessionLevel='full';M.log(state,'passkey_signin_simulated');break;
case 'signout':state.sessionLevel='report_only';state.auth=null;M.log(state,'demo_sessions_ended');go('/signin/');return;
case 'remove-passkey':state.passkey=false;M.log(state,'passkey_removed_simulated');break;
case 'print':window.print();return;
case 'reset':openModal('Reset the sample journey?',`
This clears only the customer preview saved in this browser. Your analytics preference stays unchanged.
${b('Reset sample data','reset-confirm','danger')}${b('Keep my progress','close')}
`);return;
case 'reset-confirm':state=M.initialState();go('/review/');return;
case 'ready':openModal('Load a completed setup?',`
This replaces the current sample journey with a completed parcel or freight onboarding and three example recoveries. No real account is affected.
${b('Load sample portal','ready-confirm','primary')}`);return;
case 'ready-confirm':ready();return;
case 'report-states':openModal('Report availability states',`
In production, report links need expiring access tokens. These buttons preview the messages only.
`);return;
case 'report-expired':dialog.innerHTML=`
This sample link has expired.
A production customer would request a fresh secure link. No email is sent in this demonstration.
${b('Return to sample report','close','primary')}`;return;
case 'report-pending':dialog.innerHTML=`
Your audit is being prepared.
The report will appear after the invoice review is complete. This is a sample status, not a live audit.
${b('Return to sample report','close','primary')}`;return;
case 'agreement-download':if(state.signed&&id!=='verified'){if(!['Owner','Admin'].includes(state.role))throw Error('Owner or Admin access required.');stepUp(()=>action('agreement-download','verified'));return;}download('FreightCashBack-DEMO-agreement-review.txt',`DEMONSTRATION ONLY — NOT A LEGAL AGREEMENT\n\nBusiness: ${state.order?.legalName||'Sample Home Goods Co.'}\nService: ${state.service}\nIllustrative fee: ${M.bps(state)/100}%\nTemplate: DEMO-SUMMARY-v1\nSample signer: ${state.signature?.name||'Not reviewed'}\nReview time: ${state.signature?.at||'Not reviewed'}\n\nThis prototype uses an explanatory summary. The full MSA, DPA, fee exhibit, carrier authorizations and payment mandate must be finalized before production. No legal signature or payment authorization is created here.`);toast('Demonstration review record downloaded.');return;
case 'verify-bank':M.setMandate(state,'active',state.replacement?.type);break;
case 'bank-failure':M.setMandate(state,'failed');break;
case 'letter':modalContext=id;openModal(`${esc(id)} account authorization`,note('Demonstration letter. This does not authorize access or contact a carrier.')+`
Authorize the sample audit team to review and pursue approved billing discrepancies for these covered accounts:
`);return;
case 'source':modalContext=id;openModal('Connect by '+esc(id),`
${id==='Upload'?'Use the sample invoice file below. No real file picker or upload is enabled.':id==='Email'?'Sample intake address: sample-audit@freightcashback.invalid. This address does not receive email.':id==='Carrier portal'?'Production will use an approved read-only integration. No carrier login is requested in this preview.':'Production will supply a scoped endpoint and credentials. None are created by this preview.'}
${note('The connection activates only after the sample file is successfully parsed.')}
`);return;
case 'sample-csv':download('DEMO-invoice.csv','invoice,carrier,shipment,charge_cents\nINV-DEMO-1,UPS,DEMO-UPS-1042,3592\nINV-DEMO-1,FedEx,DEMO-FDX-1043,3592\n','text/csv');toast('Sample CSV downloaded.');return;
case 'parse-error':state.parseError=true;save();dialog.querySelector('#parse-result').innerHTML=note('Sample parsing failed: the invoice date column is missing. Fix the format and retry. No source was activated.','error');return;
case 'parsed':M.connectSource(state,modalContext);state.parseError=false;dialog.close();toast('Sample file parsed. Data connection is ready.');break;
case 'clear-filter':filters={search:'',carrier:'',status:'',sort:'amount'};page=1;selected.clear();break;
case 'prev':page--;break;
case 'next':page++;break;
case 'queue':if(!selected.size)throw Error('Select at least one new finding.');M.queue(state,[...selected]);selected.clear();toast('Findings queued. Open Approvals for the next step.');break;
case 'findings-export':download('DEMO-filtered-findings.csv','finding,carrier,shipment,category,potential_cents,deadline,status\n'+filtered().map(f=>[f.id,f.carrier,f.shipment,f.category,f.cents,f.deadline,f.status].map(v=>'"'+String(v).replaceAll('"','""')+'"').join(',')).join('\n'),'text/csv');toast('Filtered sample findings downloaded.');return;
case 'finding':{const f=state.findings.find(x=>x.id===id);openModal(`${f.id} · ${f.category}`,`${status(f.status)}
Estimated potential recovery${money(f.cents)}
Carrier / shipment${f.carrier} · ${f.shipment}
Filing deadline${f.deadline}
Why this was flagged
${f.reason}
Sample evidence packet
${f.evidence}
${note('This evidence is synthetic. A production packet would link to the carrier invoice, shipment scans and applicable service terms.')}
${b('Download sample evidence','evidence','small',`data-id="${f.id}"`)}${f.status==='New'?b('Queue this finding','queue-one','primary',`data-id="${f.id}"`):''}
`);return;}
case 'evidence':{const f=state.findings.find(x=>x.id===id);download(id+'-DEMO-evidence.txt',`SAMPLE EVIDENCE — NO REAL SHIPMENT\n${f.id}\n${f.carrier}\n${f.shipment}\n${money(f.cents)}\n${f.reason}\n${f.evidence}`);toast('Sample evidence downloaded.');return;}
case 'queue-one':M.queue(state,[id]);dialog.close();toast('Finding queued for approval.');break;
case 'approve':M.decide(state,id,true);toast('Finding approved. Filing is a separate step.');break;
case 'reject':modalContext=id;openModal('Reject '+esc(id),``);return;
case 'question':modalContext=id;openModal('Question about '+esc(id),``);return;
case 'bulk-review':{const rows=state.findings.filter(f=>f.status==='Pending approval');openModal('Review bulk approval',`
You are about to approve ${rows.length} sample findings, totaling ${money(rows.reduce((n,f)=>n+f.cents,0))}. This does not file them.
${note('Every finding is checked for approval role, MFA and an unexpired filing window. An invalid record stops the whole batch.')}
${b('Approve all pending findings','bulk-approve','primary')}${b('Cancel','close')}
`);return;}
case 'bulk-approve':{const copy=structuredClone(state);for(const f of copy.findings.filter(x=>x.status==='Pending approval'))M.decide(copy,f.id,true);state=copy;dialog.close();toast('Pending findings approved.');break;}
case 'file':M.fileApproved(state,id);toast('Filing simulated. View the timeline in Disputes.');break;
case 'dispute':{const d=state.disputes.find(x=>x.id===id);modalContext=id;openModal(d.id+' · '+d.carrier,`
${money(d.cents)} potential · ${status(d.status)}
${d.timeline.map(t=>`
${t.date}${esc(t.text)}
`).join('')}
No carrier is contacted. A sample credit adds one recovery ledger entry.
`);return;}
case 'billing-example':M.loadBillingExample(state);toast('Three synthetic recovery lines are available.');break;
case 'recovery':{const r=state.recoveries.find(x=>x.id===id);openModal('Recovery evidence · '+r.id,`
${money(r.cents)} confirmed in this example.
${esc(r.evidence)}
Reference: ${esc(r.reference)} Dispute: ${r.dispute} Evidence type: demonstration record
This placeholder shows where the original carrier evidence will appear in production. It is not an authentic carrier document.
`);return;}
case 'query':modalContext=id;openModal('Query fee line '+id,`
Explain what does not match your records. This line will be held while the query is open; other eligible lines remain payable.
`);return;
case 'query-view':{const q=state.queries[id];openModal('Query · '+id,`${status(q.status,M.held(q)?'warn':'')}
${esc(q.reason)}
${esc(q.explanation)}
${q.attachment?`
Sample reference: ${esc(q.attachment)} (no file uploaded)
`:''}${q.status==='Open'?b('Withdraw this query','query-withdraw','small',`data-id="${id}"`):''}`);return;}
case 'query-withdraw':if(!['Owner','Admin','Billing'].includes(state.role))throw Error('Billing access is required.');if(state.payments.length)throw Error('The sample statement is already closed. Review this line with operations.');state.queries[id].status='Withdrawn';M.log(state,'query_withdrawn',id);dialog.close();break;
case 'query-review':admin();modalContext=id;openModal('Resolve '+id,``);return;
case 'debit-day':state.today=state.debitDate;M.log(state,'demo_date_advanced',state.today);toast('Demo date advanced to '+state.today+'.');break;
case 'debit':M.simulateDebit(state);toast('Sample debit recorded. No money moved.');break;
case 'invite':admin();openModal('Invite a sample teammate',``);return;
case 'remove-user':admin();if(id==='owner')throw Error('At least one owner must remain.');state.users=state.users.filter(x=>x.id!==id);M.log(state,'sample_user_removed',id);break;
case 'terminate':if(state.role!=='Owner')throw Error('Only the Owner can request termination.');openModal('Review service termination',`
This preview stops new simulated filings. A production request must show the executed agreement’s notice period, effective date and treatment of recoveries already in progress.
${note('The source specification mentions 30 days’ notice and a 12-month recovery tail. Those terms are not activated here because finalized agreements were not provided.')}
${b('Simulate termination request','terminate-confirm','danger')}${b('Keep service active','close')}
`);return;
case 'terminate-confirm':if(state.role!=='Owner')throw Error('Only the Owner can request termination.');dialog.close();stepUp(()=>{state.ended=true;M.log(state,'termination_requested_simulated');});return;
case 'hold':admin();state.filingHold=!state.filingHold;M.log(state,state.filingHold?'filing_hold_placed':'filing_hold_released');break;
default:return;
}
render();
}
document.addEventListener('click',e=>{const el=e.target.closest('[data-action]');if(!el)return;e.preventDefault();try{action(el.dataset.action,el.dataset.id);}catch(err){save();toast(err.message);}});
document.addEventListener('change',e=>{if(e.target.matches('[data-select]')){e.target.checked?selected.add(e.target.dataset.select):selected.delete(e.target.dataset.select);document.querySelector('#selected-count').textContent=selected.size+' selected';}if(e.target.matches('[data-select-all]')){for(const input of root.querySelectorAll('[data-select]:not(:disabled)')){input.checked=e.target.checked;input.checked?selected.add(input.dataset.select):selected.delete(input.dataset.select);}document.querySelector('#selected-count').textContent=selected.size+' selected';}});
document.addEventListener('submit',e=>{const form=e.target.closest('[data-form]');if(!form)return;e.preventDefault();const d=Object.fromEntries(new FormData(form));try{
switch(form.dataset.form){
case 'signin-email':M.requestCode(state);break;
case 'signin-code':M.verifyCode(state,d.code);break;
case 'step-up':{if(d.code!=='246810')throw Error('Incorrect sample code. Use 246810.');if(Date.now()>stepExpires||!pendingStep)throw Error('This one-action verification expired. Start the action again.');const fn=pendingStep;pendingStep=null;dialog.close();M.log(state,'step_up_simulated');fn();break;}
case 'order':{const errors=M.saveOrder(state,d);if(Object.keys(errors).length)throw Error(Object.values(errors).join(' '));go('/start/sign/');return;}
case 'sign':if(d.code!=='246810'||!d.authority)throw Error('Confirm the sample authority and enter the displayed demo code.');M.sign(state,d.name,d.title);state.sessionLevel='full';go('/start/payment/');return;
case 'payment':if(state.method&&!['Owner','Billing'].includes(state.role))throw Error('Only Owner or Billing can replace the payment method.');if(!d.mandate)throw Error('Confirm the demonstration authorization first.');if(state.method){stepUp(()=>M.setMandate(state,d.scenario==='Microdeposits pending'?'pending':d.scenario==='Connection failure'?'failed':'active',d.scenario==='Sample business card'?'card':'bank'));return;}M.setMandate(state,d.scenario==='Microdeposits pending'?'pending':d.scenario==='Connection failure'?'failed':'active',d.scenario==='Sample business card'?'card':'bank');break;
case 'account':M.addAccount(state,d.carrier,d.nickname,d.kind);break;
case 'letter':M.signLetter(state,modalContext);dialog.close();break;
case 'accounts-done':go('/start/data/');return;
case 'filter':filters=d;page=1;selected.clear();break;
case 'reject':M.decide(state,modalContext,false,d.reason);dialog.close();break;
case 'question':M.log(state,'sample_customer_question',modalContext+': '+d.message);dialog.close();toast('Question saved locally. No message was sent.');break;
case 'carrier-reply':M.carrierReply(state,modalContext,d.status);dialog.close();break;
case 'query':M.queryLine(state,modalContext,d.reason,d.explanation,d.attachment);dialog.close();toast('Only this fee line is held.');break;
case 'resolve-query':admin();state.queries[modalContext].status=d.status;state.queries[modalContext].reviewNote=d.note;M.log(state,'query_reviewed',modalContext+' '+d.status);dialog.close();break;
case 'role':state.role=d.role;state.mfa=d.mfa==='Verified';M.log(state,'preview_role_changed');break;
case 'invite':admin();state.users.push({id:'demo-'+Date.now(),...d});M.log(state,'sample_user_invited',d.role);dialog.close();break;
}
render();
}catch(err){save();const error=form.querySelector('[data-form-error]');if(error)error.textContent=err.message;else toast(err.message);}
});
render();