/* ============ CYCLE COUNT (physical count → variance) ============ */
function CycleCountScreen({products, movements, cycleCount}){
  const [pid, setPid] = React.useState(null);
  const [counted, setCounted] = React.useState('');
  const [by, setBy] = React.useState('');
  const [comments, setComments] = React.useState('');
  const p = products.find(x=>x.id===pid);
  const system = p ? Math.round(H.stockOf(p)*100)/100 : 0;
  const hasCount = counted!=='' && !isNaN(+counted);
  const variance = hasCount ? Math.round((+counted - system)*10)/10 : 0;
  const valueImpact = p ? Math.round(variance*(p.price||0)) : 0;
  const valid = p && hasCount && +counted>=0;

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

  function submit(){
    if(!valid) return;
    rememberName('counter', by);
    cycleCount({productId:pid, countedQty:+counted, countedBy:by, comments});
    if(variance===0) toast({title:t('count.matchToast'), desc:`${p.nameEn} · ${H.fmtQty(system,p.unit)}`});
    else toast({kind:'info', title:t('count.varToast'), desc:`${p.nameEn}: ${variance>0?'+':''}${H.fmtQty(variance,p.unit)}`});
    setCounted(''); setComments('');
  }

  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('count.heading')}</h2>
          <div className="muted" style={{marginBottom:20,fontSize:13}}>{t('count.sub')}</div>
          <div style={{display:'flex',flexDirection:'column',gap:16}}>
            <Field label={t('product')}><ProductPicker products={products} 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('count.systemSays')}</span>
                <span className="num" style={{fontWeight:800}}>{H.fmtQty(system,p.unit)}</span>
              </div>
            )}
            <Field label={p&&p.unit==='pcs'?t('count.countedQty'):t('count.countedWeight')} hint={t('count.countedHint')}>
              <QtyInput unit={p?p.unit:'kg'} value={counted} onChange={setCounted} disabled={!p}/>
            </Field>
            <Field label={t('count.countedBy')}><NameInput value={by} onChange={setBy} storageKey="counter" suggestions={DATA.employees} placeholder={t('count.whoCount')}/></Field>
            <Field label={t('commentsOpt')}><textarea className="input" rows={2} placeholder={t('count.commentEg')} value={comments} onChange={e=>setComments(e.target.value)} style={{resize:'vertical',minHeight:54}}/></Field>

            {p && hasCount && (
              <div className="spread" style={{borderRadius:12,padding:'12px 16px',fontWeight:800,
                background: variance===0?'#E8F7EE':'var(--crit-bg)', color: variance===0?'#16A34A':'var(--crit)'}}>
                <span style={{display:'flex',alignItems:'center',gap:8}}>
                  <Icon name={variance===0?'checkCircle':'alert'} size={18}/>
                  {variance===0?t('count.matches'):t('count.variance')+' '+(variance>0?'+':'')+H.fmtQty(variance,p.unit)}
                </span>
                {variance!==0 && <span className="num">{variance>0?t('count.surplus'):t('count.shortfall')} ≈ {H.money(Math.abs(valueImpact))}</span>}
              </div>
            )}
            <button className="btn btn-primary btn-lg" disabled={!valid} onClick={submit}>
              <Icon name="clipboard" size={19}/> {t('count.reconcile')}
            </button>
          </div>
        </Card>

        <Card className="card-pad" style={{alignSelf:'start'}}>
          <h2 style={{fontSize:16,fontWeight:800,margin:'0 0 6px'}}>{t('count.recent')}</h2>
          {recent.map(m=>(
            <div className="act" key={m.id}>
              <div className="aic" style={{background:'#E0F2FE',color:'#0891B2'}}><Icon name="refresh" size={18}/></div>
              <div style={{minWidth:0}}>
                <div className="atitle">{m.product}</div>
                <div className="adesc">{m.comments||('±'+H.fmtQty(m.qty,m.unit))}</div>
              </div>
              <div className="atime">{H.relTime(m.date,m.time)}</div>
            </div>
          ))}
          {recent.length===0 && <div className="empty" style={{padding:30}}><Icon name="clipboard"/><div>{t('count.noCounts')}</div></div>}
        </Card>
      </div>
    </div>
  );
}

window.CycleCountScreen = CycleCountScreen;
