// ─── تب برگشت به استخر فروش ─────────────────────────────────────────────────

const RulesReturnTab = ({ opsGrouped, segments, headers, load, toast, setEditing }) => {
  const retRules  = opsGrouped['return_policy'] || [];
  const retEnable = retRules.find(r => r.key === 'return_stale_enable');
  const retDays   = retRules.find(r => r.key === 'return_stale_days');
  const retStat   = retRules.find(r => r.key === 'return_stale_statuses');
  const retTarget = retRules.find(r => r.key === 'return_stale_target');
  const retOn     = retEnable?.value === '1' || retEnable?.value === 'true';
  const retStatuses = (retStat?.value || '').split(',').map(s => s.trim()).filter(Boolean);

  const selectedSegmentId = retTarget?.value?.startsWith('segment:') ? retTarget.value.replace('segment:', '') : null;
  const selectedSegment   = selectedSegmentId ? segments.find(sg => sg.id === selectedSegmentId) : null;

  const ALL_STATUSES = [
    { v:'new',       l:'جدید' },
    { v:'no_answer', l:'بی‌پاسخ' },
    { v:'lost',      l:'از دست رفته' },
    { v:'cancelled', l:'کنسل' },
  ];

  const saveRuleVal = (rule, newVal) => {
    if (!rule) return;
    fetch('/api/distrules/rules/' + rule.id, { method:'PUT', headers, body: JSON.stringify({ value: String(newVal) }) })
      .then(r => r.json()).then(d => { if (d.success) load(); else toast('خطا در ذخیره', 'error'); });
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ padding: '10px 14px', borderRadius: 9, background: 'rgba(99,102,241,0.07)', border: '1px solid rgba(99,102,241,0.2)', fontSize: 11, color: '#94a3b8', lineHeight: 1.7 }}>
        {'↩️ رویدادهایی که لید را از فروشنده می‌گیرند و به '}
        {selectedSegment
          ? <strong style={{ color: '#a5b4fc' }}>{'سگمنت «' + selectedSegment.name + '»'}</strong>
          : <strong style={{ color: '#a5b4fc' }}>{'استخر آزاد'}</strong>}
        {' منتقل می‌گردانند.'}
      </div>

      {/* رفتار تماس — بی‌پاسخی، کنسلی، شماره اشتباه */}
      {(opsGrouped['behavior'] || []).length > 0 && (
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, color: '#818CF8', marginBottom: 8, padding: '6px 0', borderBottom: '1px solid rgba(99,102,241,0.2)' }}>
            {'📞 رفتار تماس'}
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
            {(opsGrouped['behavior'] || []).map(r => (
              <RulesRow key={r.id} rule={r} type="ops" headers={headers} load={load} toast={toast} setEditing={setEditing} />
            ))}
          </div>
        </div>
      )}

      {/* برگشت راکد */}
      <div>
        <div style={{ fontSize: 12, fontWeight: 700, color: '#818CF8', marginBottom: 8, padding: '6px 0', borderBottom: '1px solid rgba(99,102,241,0.2)' }}>
          {'♻️ برگشت راکد — شماره‌های بدون تماس'}
        </div>

        <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:8, padding:'8px 12px', borderRadius:8, background:'rgba(255,255,255,0.03)', border:'1px solid rgba(255,255,255,0.07)' }}>
          <span style={{ fontSize:12, fontWeight:600, color:'#e2e8f0', flex:1 }}>{'برگشت خودکار شماره‌های بدون تماس'}</span>
          {retEnable && (
            <button onClick={() => saveRuleVal(retEnable, retOn ? '0' : '1')}
              style={{ width:36, height:20, borderRadius:10, padding:0, border:'none', cursor:'pointer', flexShrink:0, background: retOn ? 'rgba(52,211,153,0.3)' : 'rgba(107,114,128,0.2)', position:'relative' }}>
              <div style={{ width:14, height:14, borderRadius:'50%', position:'absolute', top:3, left: retOn ? 18 : 3, background: retOn ? '#34D399' : '#6B7280', transition:'left 0.2s' }} />
            </button>
          )}
          <span style={{ fontSize:10, color: retOn ? '#34D399' : '#475569' }}>{retOn ? 'فعال' : 'غیرفعال'}</span>
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap:8, opacity: retOn ? 1 : 0.4, pointerEvents: retOn ? 'auto' : 'none' }}>

          <div style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 14px', borderRadius:8, background:'rgba(255,255,255,0.03)', border:'1px solid rgba(255,255,255,0.07)' }}>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:12, fontWeight:600, color:'#e2e8f0', marginBottom:2 }}>{'روزهای بدون تماس'}</div>
              <div style={{ fontSize:11, color:'#475569' }}>{'اگر فروشنده این تعداد روز با لید تماس نگیرد'}</div>
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:6 }}>
              <input type="number" defaultValue={retDays?.value || '14'} min={1} max={90}
                onBlur={e => saveRuleVal(retDays, e.target.value)}
                style={{ width:60, padding:'4px 8px', borderRadius:6, border:'1px solid rgba(255,255,255,0.12)', background:'rgba(255,255,255,0.06)', color:'#e2e8f0', fontSize:13, fontFamily:'monospace', textAlign:'center' }} />
              <span style={{ fontSize:11, color:'#475569' }}>{'روز'}</span>
            </div>
          </div>

          <div style={{ padding:'10px 14px', borderRadius:8, background:'rgba(255,255,255,0.03)', border:'1px solid rgba(255,255,255,0.07)' }}>
            <div style={{ fontSize:12, fontWeight:600, color:'#e2e8f0', marginBottom:8 }}>{'وضعیت‌های مشمول (خالی = همه)'}</div>
            <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
              {ALL_STATUSES.map(st => {
                const checked = retStatuses.includes(st.v);
                return (
                  <button key={st.v} onClick={() => {
                    const next = checked ? retStatuses.filter(x => x !== st.v) : [...retStatuses, st.v];
                    saveRuleVal(retStat, next.join(','));
                  }} style={{ padding:'4px 12px', borderRadius:20, fontSize:11, cursor:'pointer', border:'none',
                    background: checked ? 'rgba(99,102,241,0.25)' : 'rgba(255,255,255,0.05)',
                    color: checked ? '#a5b4fc' : '#64748b', fontWeight: checked ? 600 : 400, transition:'all 0.15s' }}>
                    {checked ? '✓ ' : ''}{st.l}
                  </button>
                );
              })}
            </div>
          </div>

          <div style={{ padding:'10px 14px', borderRadius:8, background:'rgba(255,255,255,0.03)', border:'1px solid rgba(255,255,255,0.07)' }}>
            <div style={{ fontSize:12, fontWeight:600, color:'#e2e8f0', marginBottom:8 }}>{'مقصد برگشت'}</div>
            <div style={{ display:'flex', gap:8, flexWrap:'wrap', alignItems:'center' }}>
              <button onClick={() => saveRuleVal(retTarget, 'pool')}
                style={{ padding:'6px 16px', borderRadius:7, fontSize:12, cursor:'pointer', border:'none',
                  background: (!retTarget?.value || retTarget.value === 'pool') ? '#6366F1' : 'rgba(255,255,255,0.05)',
                  color: (!retTarget?.value || retTarget.value === 'pool') ? '#fff' : '#64748b' }}>
                {'🗃️ استخر آزاد'}
              </button>
              {segments.length > 0 && (
                <React.Fragment>
                  <span style={{ fontSize:11, color:'#475569' }}>{'یا سگمنت:'}</span>
                  <select onChange={e => saveRuleVal(retTarget, 'segment:' + e.target.value)}
                    value={retTarget?.value?.startsWith('segment:') ? retTarget.value.replace('segment:','') : ''}
                    style={{ padding:'5px 10px', borderRadius:7, border:'1px solid rgba(255,255,255,0.12)', background:'rgba(255,255,255,0.06)', color:'#e2e8f0', fontSize:12 }}>
                    <option value="" style={{ background: '#1e293b', color: '#64748b' }}>{'— انتخاب سگمنت —'}</option>
                    {segments.filter(sg => sg.id !== 'seg_auto_graveyard').map(sg => (
                      <option key={sg.id} value={sg.id} style={{ background: '#1e293b', color: '#e2e8f0' }}>{sg.name}</option>
                    ))}
                  </select>
                </React.Fragment>
              )}
            </div>
            {retTarget?.value?.startsWith('segment:') && (
              <div style={{ marginTop:8, fontSize:11, color:'#94a3b8' }}>
                {'🔖 لید آزاد می‌شود و در اجرای بعدی موتور سگمنت جذب سگمنت انتخاب‌شده می‌گردد.'}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
