/* ============ ACTION CENTER (exception / error queue) ============ */
const EX_TYPE_META = {
  DAMAGE:     {icon:'alert',    label:t('ac.type.DAMAGE')},
  DISCREPANCY:{icon:'hash',     label:t('ac.type.DISCREPANCY')},
  VAN:        {icon:'truck',    label:t('ac.type.VAN')},
  LOSS:       {icon:'trash',    label:t('ac.type.LOSS')},
  MANUAL:     {icon:'clipboard',label:t('ac.type.MANUAL')},
  EXPIRY:     {icon:'expire',   label:t('ac.type.EXPIRY')},
};
const SEV_COLOR = {high:['#DC2626','#FDE7E7'], med:['#D97706','#FEF3C7'], low:['#2563EB','#E5EEFD']};
const STATUS_LABEL = {open:t('ac.open'), investigating:t('ac.investigating'), resolved:t('ac.resolved')};

function ResolveModal({ex, onClose, onSave}){
  const [note, setNote] = React.useState('');
  return (
    <Modal title={t('ac.resolveTitle')} onClose={onClose} width={520}
      footer={<><button className="btn btn-ghost" onClick={onClose}>{t('cancel')}</button>
        <button className="btn btn-primary" onClick={()=>onSave(note)}><Icon name="check" size={18}/> {t('ac.markResolved')}</button></>}>
      <div style={{display:'flex',flexDirection:'column',gap:14}}>
        <div style={{fontWeight:800,fontSize:15}}>{ex.title}</div>
        {ex.detail && <div className="muted" style={{fontSize:13.5}}>{ex.detail}</div>}
        <Field label={t('ac.resolveQ')} hint={t('ac.resolveHint')}>
          <textarea className="input" rows={3} placeholder={t('ac.resolveQ')} value={note} onChange={e=>setNote(e.target.value)} style={{resize:'vertical',minHeight:80}}/>
        </Field>
      </div>
    </Modal>
  );
}

function RaiseIssueModal({products, user, onClose, onSave}){
  const [f,setF] = React.useState({title:'',detail:'',severity:'med',productId:null,source:''});
  const set=(k,v)=>setF(p=>({...p,[k]:v}));
  const valid = f.title.trim();
  return (
    <Modal title={t('ac.raiseTitle')} onClose={onClose} width={560}
      footer={<><button className="btn btn-ghost" onClick={onClose}>{t('cancel')}</button>
        <button className="btn btn-primary" disabled={!valid} onClick={()=>onSave(f)}><Icon name="plus" size={18}/> {t('ac.addToCenter')}</button></>}>
      <div style={{display:'flex',flexDirection:'column',gap:14}}>
        <Field label={t('ac.issueQ')}><input className="input" placeholder={t('ac.issueSummary')} value={f.title} onChange={e=>set('title',e.target.value)} autoFocus/></Field>
        <Field label={t('ac.details')}><textarea className="input" rows={3} placeholder={t('ac.detailsPh')} value={f.detail} onChange={e=>set('detail',e.target.value)} style={{resize:'vertical',minHeight:70}}/></Field>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}}>
          <Field label={t('ac.severity')}>
            <Segmented value={f.severity} onChange={v=>set('severity',v)} options={[{value:'low',label:t('sev.low')},{value:'med',label:t('sev.med')},{value:'high',label:t('sev.high')}]}/>
          </Field>
          <Field label={t('ac.whereCheck')}><input className="input" placeholder={t('ac.wherePh')} value={f.source} onChange={e=>set('source',e.target.value)}/></Field>
        </div>
        <Field label={t('ac.relatedProduct')}><ProductPicker products={products} value={f.productId} onChange={v=>set('productId',v)}/></Field>
      </div>
    </Modal>
  );
}

function ActionCenterScreen({exceptions=[], updateException, addManualException, products, user, isManager}){
  const [filter, setFilter] = React.useState('open');
  const [resolveEx, setResolveEx] = React.useState(null);
  const [raise, setRaise] = React.useState(false);

  const counts = {
    open: exceptions.filter(e=>e.status==='open').length,
    investigating: exceptions.filter(e=>e.status==='investigating').length,
    resolved: exceptions.filter(e=>e.status==='resolved').length,
  };
  const openHigh = exceptions.filter(e=>e.status!=='resolved' && e.severity==='high').length;
  const list = exceptions.filter(e=> filter==='all' ? true : e.status===filter)
    .sort((a,b)=>{ const sv={high:0,med:1,low:2}; return (sv[a.severity]-sv[b.severity]) || (a.date<b.date?1:-1); });

  function doResolve(note){
    updateException(resolveEx.id, {status:'resolved', resolution:note, resolvedBy:user?user.displayName:''});
    setResolveEx(null);
  }
  function saveIssue(f){
    addManualException({...f, reportedBy:user?user.displayName:''});
    setRaise(false);
  }

  const TABS = [['open',t('ac.open'),counts.open],['investigating',t('ac.investigating'),counts.investigating],['resolved',t('ac.resolved'),counts.resolved],['all',t('all'),exceptions.length]];

  return (
    <div className="content fade-up">
      {/* KPI strip */}
      <div className="kpi-grid" style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(180px,1fr))',gap:14,marginBottom:18}}>
        <Card className="card-pad"><div className="muted" style={{fontSize:12,fontWeight:700}}>{t('ac.openItems')}</div><div className="num" style={{fontSize:28,fontWeight:800,color:counts.open?'var(--crit)':'var(--ok)'}}>{counts.open}</div></Card>
        <Card className="card-pad"><div className="muted" style={{fontSize:12,fontWeight:700}}>{t('ac.highPriority')}</div><div className="num" style={{fontSize:28,fontWeight:800,color:openHigh?'var(--crit)':'var(--ink)'}}>{openHigh}</div></Card>
        <Card className="card-pad"><div className="muted" style={{fontSize:12,fontWeight:700}}>{t('ac.investigating')}</div><div className="num" style={{fontSize:28,fontWeight:800}}>{counts.investigating}</div></Card>
        <Card className="card-pad"><div className="muted" style={{fontSize:12,fontWeight:700}}>{t('ac.resolved')}</div><div className="num" style={{fontSize:28,fontWeight:800,color:'var(--ok)'}}>{counts.resolved}</div></Card>
      </div>

      <Card className="card-pad">
        <div className="spread" style={{marginBottom:14,flexWrap:'wrap',gap:10}}>
          <div className="seg" style={{flexWrap:'wrap'}}>
            {TABS.map(([k,lbl,n])=>(
              <button key={k} className={filter===k?'on':''} onClick={()=>setFilter(k)}>{lbl}{n>0?` (${n})`:''}</button>
            ))}
          </div>
          <button className="btn btn-primary" onClick={()=>setRaise(true)}><Icon name="plus" size={18}/> {t('ac.raise')}</button>
        </div>

        {list.length===0 ? (
          <div className="empty" style={{padding:'50px 20px'}}>
            <Icon name="shield"/><div style={{fontWeight:700,color:'var(--ink)'}}>{filter==='open'?t('ac.allClear'):t('ac.nothingHere')}</div>
            <div>{filter==='open'?t('ac.allClearSub'):t('ac.tryTab')}</div>
          </div>
        ) : (
          <div style={{display:'flex',flexDirection:'column',gap:12}}>
            {list.map(ex=>{
              const meta = EX_TYPE_META[ex.type] || EX_TYPE_META.MANUAL;
              const [c,bg] = SEV_COLOR[ex.severity] || SEV_COLOR.med;
              return (
                <div key={ex.id} style={{display:'flex',gap:12,border:'1px solid var(--line)',borderLeft:`4px solid ${c}`,borderRadius:12,padding:'14px 16px',opacity:ex.status==='resolved'?.72:1}}>
                  <div style={{width:38,height:38,borderRadius:10,background:bg,color:c,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
                    <Icon name={meta.icon} size={19}/>
                  </div>
                  <div style={{flex:1,minWidth:0}}>
                    <div className="spread" style={{gap:8,alignItems:'flex-start'}}>
                      <div style={{fontWeight:800,fontSize:14.5}}>{ex.title}</div>
                      <span style={{fontSize:10.5,fontWeight:800,color:c,background:bg,padding:'3px 8px',borderRadius:20,textTransform:'uppercase',flexShrink:0}}>{ex.severity}</span>
                    </div>
                    {ex.detail && <div className="muted" style={{fontSize:13,marginTop:3}}>{ex.detail}</div>}
                    <div style={{display:'flex',flexWrap:'wrap',gap:'4px 14px',marginTop:8,fontSize:12,color:'var(--muted)'}}>
                      <span>{meta.label}</span>
                      {ex.source && <span style={{color:'var(--magenta)',fontWeight:600}}><Icon name="search" size={12} style={{verticalAlign:-1,marginRight:3}}/>{ex.source}</span>}
                      {ex.reportedBy && <span>{t('ac.by')} {ex.reportedBy}</span>}
                      <span>{H.fmtDate(ex.date)}</span>
                      <span style={{fontWeight:700,color:ex.status==='resolved'?'var(--ok)':ex.status==='investigating'?'#D97706':'var(--crit)'}}>{STATUS_LABEL[ex.status]}</span>
                    </div>
                    {ex.status==='resolved' && ex.resolution && (
                      <div style={{marginTop:8,background:'#F0FAF3',borderRadius:8,padding:'8px 12px',fontSize:12.5,color:'#166534'}}>
                        <Icon name="check" size={13} style={{verticalAlign:-2,marginRight:4}}/>{ex.resolution}{ex.resolvedBy?` — ${ex.resolvedBy}`:''}
                      </div>
                    )}
                    {isManager && ex.status!=='resolved' && (
                      <div style={{display:'flex',gap:8,marginTop:10,flexWrap:'wrap'}}>
                        {ex.status==='open' && <button className="btn btn-ghost" style={{padding:'6px 12px',fontSize:12.5}} onClick={()=>updateException(ex.id,{status:'investigating'})}><Icon name="search" size={14}/> {t('ac.startInvestigating')}</button>}
                        <button className="btn btn-primary" style={{padding:'6px 12px',fontSize:12.5}} onClick={()=>setResolveEx(ex)}><Icon name="check" size={14}/> {t('ac.resolve')}</button>
                      </div>
                    )}
                    {!isManager && ex.status!=='resolved' && <div className="muted" style={{fontSize:11.5,marginTop:8,fontStyle:'italic'}}>{t('onlyManagerResolve')}</div>}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </Card>

      {resolveEx && <ResolveModal ex={resolveEx} onClose={()=>setResolveEx(null)} onSave={doResolve}/>}
      {raise && <RaiseIssueModal products={products} user={user} onClose={()=>setRaise(false)} onSave={saveIssue}/>}
    </div>
  );
}

window.ActionCenterScreen = ActionCenterScreen;
