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.

${field('Demo verification code','code','','text','required inputmode="numeric" maxlength="6"')}${submit('Verify & continue')}
`);} const route=location.pathname.replace(/\/?$/,'/'); const money=M.money; const a=(label,path,cls='')=>`${label}`; const b=(label,action,cls='',extra='')=>``; const note=(text,cls='')=>`
${text}
`; const status=(text,cls='')=>`${esc(text)}`; const field=(label,name,value='',type='text',extra='required')=>``; const select=(label,name,values,value='')=>``; const check=(text,name)=>``; const submit=label=>`
`; const heading=(eyebrow,title,desc='')=>`
${eyebrow}

${title}

${desc}

`; 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)=>`
  1. ${i+1}${label}
  2. `).join('')}
`;} function gates(){return ``;} 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()}
${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.

${state.findings.filter((x,i)=>[0,1,312,313,399,440].includes(i)).map(f=>``).join('')}
ShipmentFindingPotential
•••• ${f.shipment.slice(-4)}${f.category}${money(f.cents)}
${feeSummary()}

What happens next?

  1. Review terms and fee authorization.
  2. Confirm carrier accounts and connect data.
  3. Approve eligible disputes and track results.

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'):`
${field('Legal business name','legalName',d.legalName,'text','required maxlength="200"') }
${select('Entity type','entityType',['Corporation','LLC','Partnership','Sole proprietor','Other'],d.entityType)}
${field('State / country of formation','formation',d.formation)}
${field('Authorized signer','signer',d.signer)}
${field('Signer email','email',d.email,'email')}
${field('Billing email','billing',d.billing,'email')}

Your approval preference

${field('Demo automatic approval threshold ($0–$500)','threshold',d.threshold,'number','min="0" max="500" step="0.01" required')}${note(`Sample ${state.service} fee: ${M.bps(state)/100}%. This rate is fixed by the demonstration price book. No commitment or charge is created.`)}${submit('Continue to agreements →')}
`,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'):`

Demonstration agreement summary

Business: ${esc(state.order.legalName)}
Service: ${state.service} audit · ${M.bps(state)/100}% illustrative success fee.

Scope and control

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.

${b('Download review summary','agreement-download','small')}
${field('Sample signer name','name',state.order.signer)}
${field('Sample signer title','title','Finance Director')}
${check('I am testing the authorized-signer confirmation. This does not create a legal signature.','authority')}${field('Demo verification code (use 246810)','code','','text','required inputmode="numeric" pattern="246810" maxlength="6"')}

No verification email is sent. The displayed code simulates identity verification only.

${submit('Simulate agreement acceptance →')}
`,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'):''}
${select('Connection scenario','scenario',['Instant bank verification','Microdeposits pending','Connection failure','Sample business card'])}${check('For this simulation, I authorize variable fees on documented recoveries after advance notice. Queried fee lines are held separately. No bank is connected and no money can move.','mandate')}${submit(state.method?'Simulate replacement method':'Simulate fee authorization')}
${state.replacement?`
${b('Simulate microdeposit verification','verify-bank','primary')}${b('Simulate verification failure','bank-failure')}
`:''}${state.mandate==='active'?`
${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?`
${state.accounts.map(x=>``).join('')}
Carrier / accountStructureAuthorization
${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)}"`)}
`:note('Start with a sample UPS or FedEx account. Only generated demonstration account numbers are used.')}
${select('Carrier','carrier',['UPS','FedEx','LTL carrier'])}
${select('Account structure','kind',['Parent','Child','Affiliate'])}
${field('Account nickname','nickname','Sample billing account')}${submit('Add sample carrier account')}
${M.allLetters(state)?`
${check('I confirm that the sample account list includes all accounts intended for coverage.','complete')}${submit('Continue to billing data →')}
`: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}"`)}
`).join('')}
${state.sources.length?`

Data received

${state.sources.map(s=>`

✓ ${s.kind} · ${s.files} sample file · ${s.lines} lines · ${s.received}

`).join('')}`:''}${M.active(state)?`
${a('Finish sample setup →','/start/complete/','primary')}
`:gates()}`,4);} function kpis(){return `
${[['Estimated potential recovery',money(total())],['Needs approval',state.findings.filter(f=>f.status==='Pending approval').length],['Approved',state.findings.filter(f=>f.status==='Approved').length],['Filed disputes',state.disputes.length],['Confirmed recovery',money(state.recoveries.reduce((n,r)=>n+r.cents,0))]].map(([t,n])=>`
${t}${n}
`).join('')}
`;} 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 `
${rows.length} findings · ${selected.size} selected
${b('Queue selected for approval','queue','primary small')}${b('Export filtered CSV','findings-export','small')}
${rows.slice((page-1)*20,page*20).map(f=>``).join('')||''}
Finding / shipmentCarrierCategoryPotentialDeadlineStatus

${f.shipment}
${f.carrier}${f.category}${money(f.cents)}${f.deadline}${status(f.status,f.status==='Approved'||f.status==='Credited'?'good':f.status==='Pending approval'?'warn':'')}
No findings match. Change or clear the filters.
${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()}
${b('Clear','clear-filter','small')}
${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('Review evidence','finding','small',`data-id="${f.id}"`)}
${money(f.cents)}
${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.'):''}`:`

No disputes are awaiting approval.

${a('Choose findings →','/app/findings/','small')}`}

Approved & ready for filing

Each simulated filing rechecks the deadline, fee authorization, carrier letter and account holds.

${approved.length?approved.slice(0,50).map(f=>`
${f.id} · ${money(f.cents)}

${f.category} · ${f.approvedBy?.startsWith('auto')?'Approved by demo automatic rule':'Approved by '+esc(f.approvedBy||'reviewer')}

${b('Simulate filing','file','primary small',`data-id="${f.id}"`)}
`).join(''):'

No approved findings yet.

'}
`));} 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()+`

Your disputes

${state.disputes.length?state.disputes.map(d=>`
${d.id} · ${d.carrier}

${d.finding} · ${money(d.cents)} potential · ${status(d.status,d.status==='Credited'?'good':'')}

${b('View timeline','dispute','small',`data-id="${d.id}"`)}
`).join(''):`

No claims have been filed in this demonstration.

${a('Review approvals →','/app/approvals/','primary')}`}

Confirmed recovery ledger

A recovery needs carrier evidence before a fee can appear on a statement.

${state.recoveries.length?`
${state.recoveries.map(r=>``).join('')}
RecoveryDisputeEvidenceConfirmed
${r.id}${r.dispute}${b(esc(r.evidence),'recovery','small',`data-id="${r.id}"`)}${money(r.cents)}
`:'

No confirmed recoveries yet.

'}
${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.

Statement details

Recovery fee${M.bps(state)/100}%
Queried fees held${money(heldTotal)}
Payment method${state.method?esc(state.method.name)+' •'+state.method.last4:'Not authorized'}
${b('Print / save statement PDF','print','small')}
${lines.length?`

Itemized recoveries & fees

${lines.map(l=>``).join('')}
Recovery / disputeEvidenceRecoveryFeeStatus / action
${l.id}
${l.dispute}
${b('View proof','recovery','small',`data-id="${l.id}"`)}${money(l.cents)}${money(l.feeCents)}${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}"`)}
${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.':''}

${a('Manage sample payment method →','/start/payment/','small')}

Users & permissions

${note('Roles and MFA are simulated in this browser. They do not provide real account security. Switch roles to inspect which actions are allowed.')}
${select('Preview as role','role',['Owner','Admin','Approver','Billing','Viewer'],state.role)}
${select('Demo MFA','mfa',['Verified','Not verified'],state.mfa?'Verified':'Not verified')}
${submit('Apply preview role')}
${state.users.map(u=>`
${esc(u.name)}

${esc(u.email)} · ${esc(u.role)}

${u.id==='owner'?status('Required owner'):b('Remove','remove-user','small',`data-id="${u.id}"`)}
`).join('')}
${b('Simulate user invitation','invite','small')}

Sessions & payment history

Demo session: ${state.sessionLevel||'Preview'} · ${state.passkey?'Sample passkey enabled':'No sample passkey'}

${b('Sign out everywhere (demo)','signout','small')}${state.passkey?b('Remove sample passkey','remove-passkey','small'):''}
${state.payments.map(p=>`

${p.date} · ${money(p.cents)} · ${p.status}

`).join('')||'

No sample payments yet.

'}

Coverage & service

Carrier accounts

${state.accounts.length} sample accounts. Letters must cover every account.

${a('Manage accounts','/start/accounts/','small')}
Data connections

${state.sources.length} sample sources connected.

${a('Manage data','/start/data/','small')}
Agreement record

${state.signed?'DEMO-SUMMARY-v1 · reviewed '+state.signature.at.slice(0,10):'Not completed'}

${b('Download review record','agreement-download','small')}
Service status

${state.ended?'Demonstration termination requested; new filings are held.':'Demonstration active. Production termination terms need a finalized agreement.'}

${b('Review termination request','terminate','danger small')}
`);} 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.'}

${b(state.filingHold?'Release sample filing hold':'Place sample filing hold','hold','small')}

Queue overview

${[['Pending bank verification',state.replacement?1:0],['Missing carrier letters',state.accounts.filter(a=>!state.letters[a.carrier]).length],['Awaiting customer approval',state.findings.filter(f=>f.status==='Pending approval').length],['Billing queries',Object.keys(state.queries).length],['Sample parse failures',state.parseError?1:0]].map(([l,n])=>`
${l}${n}
`).join('')}

Fee-line query review

${Object.entries(state.queries).length?Object.entries(state.queries).map(([id,q])=>`
${id} · ${esc(q.status)}

${esc(q.reason)}
${esc(q.explanation)}

${b('Review query','query-review','small',`data-id="${id}"`)}
`).join(''):'

No queries yet. Create one from a statement line.

'}${a('Open statement →','/app/billing/statements/sample/','small')}

Demonstration event log

This local log can be reset. Production requires a durable, append-only audit trail.

${state.auditLog.slice(-80).reverse().map(l=>``).join('')||''}
TimeActionActorDetails
${esc(l.at.slice(0,19).replace('T',' '))}${esc(l.action.replaceAll('_',' '))}${esc(l.actor)}${esc(l.detail)}
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.

${field('Six-digit demo code','code','','text','required inputmode="numeric" maxlength="6"')}${submit('Verify sample code →')}
${b('Request another demo code','resend-code','small')}${b('Test expired code','expire-code','small')}
`:`
${field('Work email (sample only)','email','alex@example.com','email')}${submit('Continue with email →')}
${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.')}
${b('Try report-only access','report-session','small')}
`;} 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.

${a('Privacy policy','/privacy/')}${a('Contact us','/contact/')}
`;} 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.

${b('Preview expired link','report-expired')}${b('Preview report pending','report-pending')}
`);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:

${check('I confirm the sample account list and understand this is a simulated carrier letter.','confirm')}${submit('Confirm sample carrier letter')}
`);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.')}
${b('Download sample invoice CSV','sample-csv')}${b('Simulate parsed file','parsed','primary')}${b('Try parse error','parse-error')}
`);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),`
${submit('Reject this finding')}
`);return; case 'question':modalContext=id;openModal('Question about '+esc(id),`

No email is sent. This saves a question in the demonstration event log.

${submit('Save sample question')}
`);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=>`
  1. ${t.date}${esc(t.text)}
  2. `).join('')}
${select('Sample carrier response','status',['Acknowledged','Needs information','Rejected','Credited'])}${submit('Simulate carrier response')}

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.

${select('Reason','reason',['Credit not received','Recovery amount differs','Duplicate fee','Wrong account','Other'])}${field('Sample evidence filename (optional)','attachment','','text','maxlength="120" placeholder="Example: sample-credit-note.pdf"')}

No attachment is uploaded. Use a sample filename only.

${submit('Submit sample query & hold this line')}
`);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,`
${select('Review outcome','status',['Substantiated','Conceded'])}

Substantiated keeps the line held for follow-up. Conceded removes the fee from this statement. A production reviewer needs carrier evidence and the finalized contractual process.

${field('Review note','note','','text','required maxlength="1000"')}${submit('Save sample review outcome')}
`);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',`
${field('Sample name','name','Jamie Lee')}${field('Sample email','email','jamie@example.com','email')}${select('Role','role',['Admin','Approver','Billing','Viewer'])}

No invitation email is sent.

${submit('Add 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();