/* ============ LOSS / WASTE SCREEN ============ */
const LOSS_REASONS = ['Dropped / broken','Expired','Damaged in transit','Quality reject','Other'];
const CHAIN_STAGES = [
  {value:'Factory',    label:t('stage.Factory')},
  {value:'In transit', label:t('stage.In transit')},
  {value:'Receiving',  label:t('stage.Receiving')},
  {value:'Showroom',   label:t('stage.Showroom')},
];

function LossScreen({products, movements, recordLoss}){
  const [pid, setPid] = React.useState(null);
  const [qty, setQty] = React.useState('');
  const [reason, setReason] = React.useState('Dropped / broken');
  const [stage, setStage] = React.useState('Receiving');
  const [by, setBy] = React.useState('');
  const [comments, setComments] = React.useState('');
  const [photo, setPhoto] = React.useState('');
  const p = products.find(x=>x.id===pid);
  const avail = p ? H.stockOf(p) : 0;
  const over = p && +qty>avail;
  const valid = p && +qty>0 && !over && reason;
  const value = p && +qty>0 ? Math.round(+qty*(p.price||0)*100)/100 : 0;

  const recentLoss = (movements||[]).filter(m=>m.type==='LOSS').slice(0,7);

  function submit(){
    if(!valid) return;
    rememberName('reporter', by);
    recordLoss({productId:pid, qty:+qty, reason, chainStage:stage, reportedBy:by, comments, photo});
    toast({kind:'info', title:t('loss.recorded'), desc:`${H.fmtQty(+qty,p.unit)} · ${p.nameEn} · ${t('reason.'+reason)} · ${H.money(value)}`});
    setQty(''); setComments(''); setPhoto('');
  }

  return (
    <div className="content fade-up">
      <div className="action-layout">
        <Card className="card-pad">
          <h2 style={{fontSize:18,fontWeight:800,margin:'0 0 4px'}}>{t('loss.heading')}</h2>
          <div className="muted" style={{marginBottom:20,fontSize:13}}>{t('loss.sub')}</div>
          <div style={{display:'flex',flexDirection:'column',gap:16}}>
            <Field label={t('product')}><ProductPicker products={products.filter(p=>H.stockOf(p)>0)} value={pid} onChange={setPid}/></Field>
            {p && (
              <div className="spread" style={{background:'#FAF8FB',borderRadius:12,padding:'11px 14px'}}>
                <span className="muted" style={{fontWeight:600,fontSize:13}}>{t('available')}</span>
                <span className="num" style={{fontWeight:800,color:over?'var(--crit)':undefined}}>{H.fmtQty(avail,p.unit)}</span>
              </div>
            )}
            <Field label={p&&p.unit==='pcs'?t('loss.qtyLost'):t('loss.weightLost')} hint={over?t('out.exceeds'):undefined}>
              <QtyInput unit={p?p.unit:'kg'} value={qty} onChange={setQty} disabled={!p} invalid={over}/>
            </Field>
            <Field label={t('loss.reason')}>
              <select className="select" value={reason} onChange={e=>setReason(e.target.value)}>
                {LOSS_REASONS.map(r=><option key={r} value={r}>{t('reason.'+r)}</option>)}
              </select>
            </Field>
            <Field label={t('loss.where')} hint={t('loss.whereHint')}>
              <Segmented value={stage} onChange={setStage} options={CHAIN_STAGES}/>
            </Field>
            <Field label={t('loss.reportedBy')}><NameInput value={by} onChange={setBy} storageKey="reporter" suggestions={DATA.employees} placeholder={t('loss.whoReport')}/></Field>
            <Field label={t('comments')}><textarea className="input" rows={2} placeholder={t('loss.what')} value={comments} onChange={e=>setComments(e.target.value)} style={{resize:'vertical',minHeight:60}}/></Field>
            <Field label={t('photoEvidence')}><PhotoInput value={photo} onChange={setPhoto}/></Field>

            {p && +qty>0 && !over && (
              <div className="spread" style={{background:'var(--crit-bg)',color:'var(--crit)',borderRadius:12,padding:'12px 16px',fontWeight:800}}>
                <span style={{display:'flex',alignItems:'center',gap:8}}><Icon name="trendDown" size={18}/> {t('loss.estValue')}</span>
                <span className="num">{H.money(value)}</span>
              </div>
            )}
            <button className="btn btn-primary btn-lg" disabled={!valid} onClick={submit} style={{background:valid?'var(--crit)':undefined}}>
              <Icon name="trash" size={19}/> {t('loss.record')}
            </button>
          </div>
        </Card>

        <Card className="card-pad" style={{alignSelf:'start'}}>
          <h2 style={{fontSize:16,fontWeight:800,margin:'0 0 6px'}}>{t('loss.recent')}</h2>
          {recentLoss.map(m=>(
            <div className="act" key={m.id}>
              <div className="aic" style={{background:'var(--crit-bg)',color:'var(--crit)'}}><Icon name="trash" size={18}/></div>
              <div style={{minWidth:0}}>
                <div className="atitle">{m.product}</div>
                <div className="adesc">{H.fmtQty(m.qty,m.unit)} · {m.reason?t('reason.'+m.reason):t('rep.loss')}{m.valueLost?' · '+H.money(m.valueLost):''}</div>
              </div>
              <div className="atime">{H.relTime(m.date,m.time)}</div>
            </div>
          ))}
          {recentLoss.length===0 && <div className="empty" style={{padding:30}}><Icon name="checkCircle"/><div>{t('loss.none')}</div></div>}
        </Card>
      </div>
    </div>
  );
}

window.LossScreen = LossScreen;
