/* Exported promotion-detail composition, backed by persisted promotion snapshots. */
(function(){
 const {useState,useEffect,useRef}=React;
 const money=c=>c==null?'—':'$'+(c/100).toFixed(2);
 const date=s=>s?String(s).slice(0,10).split('-').reverse().join('/'):'—';
 const ACTION={publish:['Publish','Publish this promotion? It writes prices or rules to the register sync feed.'],pause:['Pause','Pause it? The registers stop applying it until you resume.'],resume:['Resume'],endEarly:['End early','End it now? Prices revert on the registers and it cannot be resumed.'],extend:['Extend'],cancel:['Cancel','Cancel it? It will not start.'],startNow:['Start now','Start today instead of the scheduled date?'],rerun:['Run it again'],edit:['Edit'],discard:['Discard','Discard this draft?']};
 const API_ACTION={endEarly:'end',startNow:'start-now'};
 const CHANNELS={pos:'Register & receipt',esl:'Electronic shelf labels',ticket:'Printed tickets',cfd:'Customer display',online:'Online & click-collect',cat:'Catalogue export',prompt:'Staff prompt at the till'};
 const Fact=({label,children})=><div className="pg-fact"><span>{label}</span><strong>{children}</strong></div>;
 const Card=({title,children})=><section className="off-table pg-card"><div className="pg-card-h">{title}</div>{children}</section>;
 function Detail(){
  const {screenState={},setScreen,setScreenState,pushToast}=window.useOffice();const id=screenState.promotionId;
  const [d,setD]=useState(null),[error,setError]=useState(null),[busy,setBusy]=useState(false),[loading,setLoading]=useState(true),[extendTo,setExtendTo]=useState('');
  const inFlight=useRef(false),mounted=useRef(false),currentId=useRef(id);currentId.current=id;
  useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
  useEffect(()=>{let alive=true;setD(null);setError(null);setLoading(true);if(!id){setError('No promotion selected.');setLoading(false);return;}
   window.OfficeAPI.promotion(id).then(value=>{if(alive){if(!value)throw Error('Promotion not found.');setD(value);setExtendTo(value.endsOn);}}).catch(e=>{if(alive)setError(e.message||"Couldn't load this promotion.");}).finally(()=>{if(alive)setLoading(false);});return()=>{alive=false;};
  },[id]);
  const act=async key=>{
   if(inFlight.current||!d?.actions?.includes(key))return;
   if(key==='edit'||key==='rerun'){setScreenState(s=>({...s,promotionEditId:key==='edit'?id:null,promotionRerunOf:key==='rerun'?id:null}));setScreen('promotionNew');return;}
   if(key==='extend'&&(!extendTo||extendTo<=d.endsOn)){setError('Pick a later end date first.');return;}
   if(ACTION[key]?.[1]&&!window.confirm(ACTION[key][1]))return;
   inFlight.current=true;setBusy(true);setError(null);const actionId=id;
   try{
    if(key==='discard'){await window.OfficeAPI.discardPromotion(id);if(mounted.current&&currentId.current===actionId){pushToast?.({kind:'ok',text:'Draft discarded.'});setScreen('promotions');}}
    else{await window.OfficeAPI.promotionAction(id,API_ACTION[key]||key,key==='extend'?{endsOn:extendTo}:undefined);const fresh=await window.OfficeAPI.promotion(id);if(mounted.current&&currentId.current===actionId){setD(fresh);setExtendTo(fresh.endsOn);pushToast?.({kind:'ok',text:(ACTION[key]?.[0]||key)+' — done.'});}}
   }catch(e){if(mounted.current&&currentId.current===actionId)setError(e.message||"That didn't work.");}
   finally{inFlight.current=false;if(mounted.current)setBusy(false);}
  };
  const lines=d?.lines||[],holds=d?.tillHolds,channels=d?.channels||['pos'];
  return <div className="off-screen"><header className="off-screen-header"><div className="off-screen-header-meta">
   <button className="sup-back" onClick={()=>setScreen('promotions')}><window.OIcon name="chevron-left"/> Promotions</button>
   <div style={{display:'flex',alignItems:'center',gap:10,flexWrap:'wrap'}}><h2 className="off-screen-title">{d?.name||'Promotion'}</h2>{d&&<><span className={'badge badge--'+({live:'paid',scheduled:'sched',paused:'hold',draft:'flat',ended:'flat',cancelled:'void'}[d.state]||'flat')}>{d.state[0].toUpperCase()+d.state.slice(1)}</span><span className={'pg-where pg-where--'+d.where}>{d.where==='price'?'Shelf price':'Basket rule'}</span></>}</div>
   {d&&<div className="off-muted" style={{fontSize:13,marginTop:4}}><span className="off-cell-mono">{d.id}</span> · {date(d.startsOn)} to {date(d.endsOn)} · {d.siteName||d.siteId}</div>}
  </div>{d&&<div className="off-screen-actions">{d.actions?.includes('extend')&&<input className="input" aria-label="New promotion end date" type="date" value={extendTo} min={d.endsOn} disabled={busy} onChange={e=>setExtendTo(e.target.value)} style={{width:150}}/>}{(d.actions||[]).map(key=><button className={'btn btn--'+(['publish','edit','rerun'].includes(key)?'secondary':'ghost')+' btn--sm'} key={key} disabled={busy} onClick={()=>act(key)}>{ACTION[key]?.[0]||key}</button>)}<button className="btn btn--secondary btn--sm" disabled={busy} onClick={()=>{setScreenState(s=>({...s,promotionTicketId:id}));setScreen('promoTickets');}}><window.OIcon name="printer"/> Tickets</button></div>}</header>
  <div className="off-screen-body off-promotions-body">{loading&&<div className="pc-note" role="status">Loading promotion…</div>}{error&&<div className="pc-warn" role="alert">{error}</div>}{d&&<div className="pg-detail"><div className="pg-dcol">
   <Card title="What it does"><div className="pg-mech"><div className="pg-mech-v">{d.say}</div><div className="pg-mech-d">{d.where==='price'?'A promotional unit price in the register pricing profile.':'A basket rule evaluated when the qualifying quantity is bought.'}</div></div><div className="pg-facts"><Fact label="Mechanic">{d.mechanicLabel}</Fact><Fact label="Applies to">{d.scopeLabel}</Fact><Fact label="Published lines">{lines.length}</Fact><Fact label="Delivered as">{d.where==='price'?'A price the register receives':'A rule the register runs'}</Fact><Fact label="Runs">{date(d.startsOn)} – {date(d.endsOn)}</Fact></div>{d.exclusions?.length>0&&<div className="xp-note">Selected exclusions: {d.exclusions.join(', ')}. Mandatory exclusions are also enforced at publication.</div>}{d.why&&<div className="xp-note" style={{marginTop:8}}>{d.why}</div>}</Card>
   <Card title="When it ends"><div className="pg-card-s">{d.where==='price'?'The promotional override expires or is removed. Registers use the shelf price in their current pricing profile; the pre-promotion snapshot is not written back.':'The basket rule stops being evaluated when its window ends or it is disabled. No unit price needs to revert.'}</div></Card>
   {d.funded&&<Card title="Supplier funded"><div className="pg-facts"><Fact label="Supplier">{d.funded.supplier}</Fact><Fact label="Deal reference">{d.funded.ref||'—'}</Fact><Fact label="They fund">{money(d.funded.perCents)} per unit</Fact></div><div className="pg-card-s">Documented claims and eligible sales are shown in Supplier funding. This saved funding rate alone does not establish a claim value.</div><button className="pg-linkbtn" onClick={()=>{setScreenState(s=>({...s,promotionTab:'fund'}));setScreen('promotions');}}>View supplier funding</button></Card>}
   <details className="off-table pg-card"><summary className="pg-card-h" style={{cursor:'pointer'}}>What the register holds</summary><div className="pg-card-s">Read back from the tables the tills sync. This does not confirm delivery to an individual till.</div>{holds?<div className="pg-facts"><Fact label={d.where==='price'?'Lines carrying a promo price':'Lines in the pricing group'}>{(d.where==='price'?holds.profilesWithPromoPrice:holds.profilesInGroup)??'—'}</Fact>{d.where==='basket'&&<><Fact label="Pricing group">{holds.pricingGroup??'—'}</Fact><Fact label="Register rule">{holds.rule?(holds.rule.isActive?'active':'inactive'):'not written'}</Fact>{holds.rule&&<><Fact label="Rule offer">{holds.rule.quantityA} for {money(holds.rule.bundlePriceCents)}</Fact><Fact label="Rule window">{holds.rule.startDate||'—'} → {holds.rule.endDate||'—'}</Fact></>}</>}<Fact label="Published">{d.publishedAt||'not yet'}</Fact></div>:<div className="pg-card-s">Register diagnostics are unavailable.</div>}</details>
  </div><div className="pg-dcol"><Card title="Lines affected"><div className="pg-card-s">{d.state==='draft'?'Nothing has been written yet. Edit the draft to review its current scope and exclusions before publishing.':'These are the saved publication lines. They are historical snapshots, not the effective prices for a different date.'}</div>{lines.length>0?<><div className="pg-live-table-wrap"><div className="off-grid" style={{gridTemplateColumns:'minmax(150px,1.4fr) 82px 82px 74px minmax(140px,1fr) minmax(110px,.9fr)',marginTop:11}}>{['Line','Was','Promo','Margin','Against the market','Note'].map(h=><div className="off-grid-headcell" key={h}>{h}</div>)}{lines.map(line=><div className="off-grid-row" key={line.productId}><div className="off-grid-cell" style={{whiteSpace:'normal',fontSize:12.5}}>{line.name}<small className="pg-live-muted">{line.sku}</small></div><div className="off-grid-cell off-cell-num">{money(line.beforeCents)}</div><div className="off-grid-cell off-cell-num off-cell-strong">{line.promoCents==null?(d.where==='basket'?'at till':'—'):money(line.promoCents)}</div><div className="off-grid-cell off-cell-num">—</div><div className="off-grid-cell" style={{whiteSpace:'normal',fontSize:11,color:'var(--text-muted)'}}>{d.where==='basket'?'No unit price to compare':'Not in the saved snapshot'}</div><div className="off-grid-cell" style={{whiteSpace:'normal',fontSize:11,color:'var(--text-muted)'}}>{d.where==='basket'?d.say:'Published price'}</div></div>)}</div></div><div className="pg-card-s">Cost and competitor observations were not stored with these lines; historical margins and market comparisons are unavailable.</div></>:<div className="xp-empty">No published lines.</div>}</Card>
   <Card title="Where it appears"><div className="pg-chans">{Object.entries(CHANNELS).map(([key,label])=><div className={'pg-chan'+(channels.includes(key)?' is-on':'')} key={key}><span className={'xp-yn '+(channels.includes(key)?'is-y':'is-n')}><window.OIcon name={channels.includes(key)?'check':'x'}/></span><span>{label}</span></div>)}</div><div className="pg-card-s">Saved channel selections; print tickets separately. Delivery and display playback are not confirmed here.</div>{d.prompt&&<div className="pg-promptbox"><div className="pg-card-h" style={{marginBottom:4}}>Staff prompt at the till</div><div className="pg-promptq">“{d.prompt}”</div></div>}</Card>
  </div></div>}</div></div>;
 }
 window.OFFICE_SCREENS=Object.assign(window.OFFICE_SCREENS||{},{promotionDetail:Detail});
})();
