// ─── راهنمای شکار لید ────────────────────────────────────────────────────────
// auto: 'always' = سیستم همیشه انجام می‌ده | 'toggle' = قابل فعال/غیرفعال | 'manual' = دستی
const RHG_ROWS = [
  // فاز ربات
  { id:'rg1',  sec:'🤖 فاز ربات',          sC:'#818cf8', sBg:'rgba(99,102,241,0.07)',
    status:'new',              badge:'#6366f1', what:'توزیع خودکار لید به فروشنده (هر ۳۰ دقیقه)',
    auto:'always', cronDesc:'کرون هر ۳۰ دقیقه' },
  { id:'rg2',  sec:'🤖 فاز ربات',          sC:'#818cf8', sBg:'rgba(99,102,241,0.07)',
    status:'امتیاز ≥ ۷',      badge:'#10b981', what:'لید پُرامتیاز → فروشنده ارشد (مسیر توزیع اولویت‌دار)',
    auto:'toggle', ruleType:'routing', ruleId:'rr_hot' },
  { id:'rg3',  sec:'🤖 فاز ربات',          sC:'#818cf8', sBg:'rgba(99,102,241,0.07)',
    status:'💸 بودجه-کم',     badge:'#eab308', what:'تگ‌گذاری خودکار لیدهایی که بودجه=کم اعلام کردن',
    auto:'toggle', ruleType:'pool', ruleId:'plr_nobudget' },
  { id:'rg4',  sec:'🤖 فاز ربات',          sC:'#818cf8', sBg:'rgba(99,102,241,0.07)',
    status:'🎓 دوره رایگان',  badge:'#8b5cf6', what:'تگ‌گذاری خودکار لیدهایی که دوره رایگان دیدن',
    auto:'toggle', ruleType:'pool', ruleId:'plr_free' },
  // فاز فروشنده
  { id:'rg5',  sec:'📞 فاز فروشنده',       sC:'#34d399', sBg:'rgba(52,211,153,0.07)',
    status:'follow_up بدون تماس', badge:'#f97316', what:'هشدار لیدهایی که بعد از ۲۴h هنوز تماسی نگرفتن',
    auto:'toggle', ruleType:'market', ruleId:'rule_aging_alert' },
  { id:'rg6',  sec:'📞 فاز فروشنده',       sC:'#34d399', sBg:'rgba(52,211,153,0.07)',
    status:'⏰ وقت‌کش',       badge:'#f87171', what:'تگ‌گذاری لیدهایی که ۵+ تماس در follow_up دارن',
    auto:'toggle', ruleType:'pool', ruleId:'plr_noshw' },
  { id:'rg7',  sec:'📞 فاز فروشنده',       sC:'#34d399', sBg:'rgba(52,211,153,0.07)',
    status:'interested',      badge:'#10b981', what:'رزرو وقت مشاوره — باید دستی انجام بشه',
    auto:'manual' },
  { id:'rg8',  sec:'📞 فاز فروشنده',       sC:'#34d399', sBg:'rgba(52,211,153,0.07)',
    status:'scheduled',       badge:'#0ea5e9', what:'ریمایندر ۲۴h قبل — باید دستی ارسال بشه',
    auto:'manual' },
  { id:'rg9',  sec:'📞 فاز فروشنده',       sC:'#34d399', sBg:'rgba(52,211,153,0.07)',
    status:'🎯 آماده-خرید',   badge:'#10b981', what:'تگ‌گذاری لیدهای scheduled/consultation با امتیاز ≥ ۷',
    auto:'toggle', ruleType:'pool', ruleId:'plr_hot' },
  // باخت قابل نجات
  { id:'rg10', sec:'⚰️ باخت — قابل نجات', sC:'#f87171', sBg:'rgba(248,113,113,0.07)',
    status:'lost / cancelled', badge:'#ef4444', what:'بازگشت خودکار اگه لید دوباره پیام بده',
    auto:'always', cronDesc:'کرون هر ۵ دقیقه' },
  { id:'rg11', sec:'⚰️ باخت — قابل نجات', sC:'#f87171', sBg:'rgba(248,113,113,0.07)',
    status:'❄️ سرد-واقعی',   badge:'#64748b', what:'تگ‌گذاری: ۳+ بی‌جواب و ۱۴+ روز بدون تماس',
    auto:'toggle', ruleType:'pool', ruleId:'plr_cold' },
  { id:'rg12', sec:'⚰️ باخت — قابل نجات', sC:'#f87171', sBg:'rgba(248,113,113,0.07)',
    status:'🔄 برگشتی',       badge:'#f59e0b', what:'تگ‌گذاری لیدهای لغو شده‌ای که دوباره تماس گرفتن',
    auto:'toggle', ruleType:'pool', ruleId:'plr_returned' },
  // قبرستان
  { id:'rg13', sec:'🪦 قبرستان',           sC:'#a5b4fc', sBg:'rgba(99,102,241,0.04)',
    status:'ورود به قبرستان', badge:'#6366f1', what:'انتقال خودکار توسط موتور سگمنت',
    auto:'always', cronDesc:'موتور سگمنت' },
  { id:'rg14', sec:'🪦 قبرستان',           sC:'#a5b4fc', sBg:'rgba(99,102,241,0.04)',
    status:'برگشت از قبرستان', badge:'#10b981', what:'بازگشت + توزیع فوری اگه لید پیام بده',
    auto:'always', cronDesc:'کرون هر ۵ دقیقه' },
  // سیستمی
  { id:'rg15', sec:'⚙️ حالت‌های سیستمی',  sC:'#fbbf24', sBg:'rgba(251,191,36,0.06)',
    status:'فریز',            badge:'#eab308', what:'خروج خودکار از فریز بعد از پایان تاریخ',
    auto:'always', cronDesc:'کرون هر ۵ دقیقه' },
  { id:'rg16', sec:'⚙️ حالت‌های سیستمی',  sC:'#fbbf24', sBg:'rgba(251,191,36,0.06)',
    status:'بدون فروشنده',    badge:'#3b82f6', what:'توزیع خودکار لیدهای unassigned',
    auto:'always', cronDesc:'توزیع هر ۳۰ دقیقه' },
  { id:'rg17', sec:'⚙️ حالت‌های سیستمی',  sC:'#fbbf24', sBg:'rgba(251,191,36,0.06)',
    status:'💸 بودجه-کم → اقساط', badge:'#f97316', what:'مسیر توزیع لیدهای بودجه-کم به متخصص اقساط',
    auto:'toggle', ruleType:'routing', ruleId:'rr_budget' },
];

const RulesHuntGuide = ({ headers }) => {
  const { useState, useEffect } = React;
  const { useToast } = window.SB_UI;
  const toast = useToast();
  const [rules, setRules] = useState({ pool: {}, market: {}, routing: {} });
  const [toggling, setToggling] = useState(null);

  const loadRules = () => {
    Promise.all([
      fetch('/api/pool/rules', { headers }).then(r => r.json()),
      fetch('/api/distrules/rules', { headers }).then(r => r.json()),
      fetch('/api/distrules/routing-rules', { headers }).then(r => r.json()),
    ]).then(([p, m, rr]) => {
      const toMap = arr => arr.reduce((acc, x) => { acc[x.id] = x; return acc; }, {});
      setRules({
        pool:    toMap(p.success    ? (p.data.rules    || []) : []),
        market:  toMap(m.success    ? (m.data.rules    || []) : []),
        routing: toMap(rr.success   ? (rr.data.rules   || []) : []),
      });
    }).catch(() => {});
  };
  useEffect(loadRules, []);

  const toggle = (row) => {
    const ruleMap = { pool: rules.pool, market: rules.market, routing: rules.routing };
    const rule = ruleMap[row.ruleType]?.[row.ruleId];
    if (!rule) return toast('قانون در سیستم یافت نشد', 'error');
    const newActive = rule.is_active ? 0 : 1;
    const urls = {
      pool:    `/api/pool/rules/${row.ruleId}`,
      market:  `/api/distrules/rules/${row.ruleId}`,
      routing: `/api/distrules/routing-rules/${row.ruleId}`,
    };
    setToggling(row.id);
    fetch(urls[row.ruleType], { method: 'PUT', headers, body: JSON.stringify({ is_active: newActive }) })
      .then(r => r.json()).then(d => {
        setToggling(null);
        if (d.success) { toast(newActive ? 'فعال شد' : 'غیرفعال شد', 'success'); loadRules(); }
        else toast(d.message || 'خطا', 'error');
      }).catch(() => { setToggling(null); toast('خطای شبکه', 'error'); });
  };

  // گروه‌بندی بر اساس section
  const sections = [];
  RHG_ROWS.forEach(row => {
    let sec = sections.find(s => s.name === row.sec);
    if (!sec) { sec = { name: row.sec, color: row.sC, bg: row.sBg, rows: [] }; sections.push(sec); }
    sec.rows.push(row);
  });

  const getIsActive = (row) => {
    if (row.auto !== 'toggle') return null;
    const rule = rules[row.ruleType]?.[row.ruleId];
    return rule ? !!rule.is_active : null;
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {/* راهنما */}
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', padding: '8px 12px', borderRadius: 8, background: 'rgba(255,255,255,0.03)', fontSize: 11, color: '#64748b' }}>
        <span><span style={{ color: '#10b981' }}>●</span> {'خودکار — سیستم همیشه انجام می‌ده'}</span>
        <span><span style={{ color: '#6366f1' }}>●</span> {'فعال‌سازی — می‌تونی روشن/خاموش کنی'}</span>
        <span><span style={{ color: '#374151' }}>●</span> {'دستی — باید خودت انجام بدی'}</span>
      </div>

      {sections.map(sec => (
        <div key={sec.name} style={{ borderRadius: 10, border: `1px solid ${sec.color}20`, overflow: 'hidden' }}>
          <div style={{ padding: '8px 14px', background: sec.bg, fontSize: 12, fontWeight: 700, color: sec.color, borderBottom: `1px solid ${sec.color}20` }}>
            {sec.name}
          </div>
          {sec.rows.map((row, i) => {
            const isActive = getIsActive(row);
            const isLoading = toggling === row.id;
            return (
              <div key={row.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 14px', background: i % 2 === 0 ? 'transparent' : 'rgba(255,255,255,0.015)', borderTop: i === 0 ? 'none' : '1px solid rgba(255,255,255,0.04)' }}>
                {/* وضعیت */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 150, flexShrink: 0 }}>
                  <span style={{ width: 7, height: 7, borderRadius: '50%', background: row.badge, flexShrink: 0, display: 'inline-block' }} />
                  <span style={{ fontSize: 11, fontWeight: 600, color: row.badge }}>{row.status}</span>
                </div>
                {/* توضیح */}
                <div style={{ flex: 1, fontSize: 11, color: '#94a3b8', lineHeight: 1.6 }}>{row.what}</div>
                {/* نوع اتوماسیون */}
                <div style={{ flexShrink: 0 }}>
                  {row.auto === 'always' && (
                    <span style={{ fontSize: 10, padding: '3px 8px', borderRadius: 20, background: 'rgba(16,185,129,0.12)', color: '#10b981', border: '1px solid rgba(16,185,129,0.2)' }}>
                      {'✓ '}{row.cronDesc}
                    </span>
                  )}
                  {row.auto === 'manual' && (
                    <span style={{ fontSize: 10, padding: '3px 8px', borderRadius: 20, background: 'rgba(55,65,81,0.4)', color: '#475569' }}>
                      {'دستی'}
                    </span>
                  )}
                  {row.auto === 'toggle' && (
                    <button
                      onClick={() => !isLoading && toggle(row)}
                      disabled={isLoading || isActive === null}
                      style={{
                        width: 44, height: 24, borderRadius: 12, border: 'none', cursor: isLoading || isActive === null ? 'default' : 'pointer',
                        background: isActive ? '#6366f1' : 'rgba(255,255,255,0.1)',
                        position: 'relative', transition: 'background 0.2s', flexShrink: 0,
                        opacity: isActive === null ? 0.4 : 1,
                      }}
                    >
                      <span style={{
                        position: 'absolute', top: 3, width: 18, height: 18, borderRadius: '50%',
                        background: '#fff', transition: 'left 0.2s',
                        left: isActive ? 23 : 3,
                      }} />
                    </button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      ))}
    </div>
  );
};


// ─── ماژول قوانین (thin shell) ─────────────────────────────────────────────
// تب‌ها در فایل‌های جداگانه:
//   rules_shared.jsx   ← RulesRow
//   rules_input.jsx    ← RulesInputTab
//   rules_dist.jsx     ← RulesDistTab  (توزیع + امتیاز + توقف)
//   rules_return.jsx   ← RulesReturnTab  (برگشت به استخر)
//   rules_graveyard.jsx← RulesGraveyardTab  (قبرستان)
//   rules_ops.jsx      ← RulesOpsTab

const Rules = () => {
  const { useToast } = window.SB_UI;
  const { useState, useEffect } = React;
  const toast = useToast();
  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };

  const [opsRules,  setOpsRules]  = useState([]);
  const [evalRules, setEvalRules] = useState([]);
  const [suspRules, setSuspRules] = useState([]);
  const [segments,  setSegments]  = useState([]);
  const [loading,   setLoading]   = useState(true);
  const [editing,   setEditing]   = useState(null);
  const [saving,    setSaving]    = useState(false);
  const [section,   setSection]   = useState('input');

  const load = () => {
    setLoading(true);
    Promise.all([
      fetch('/api/distrules/rules',            { headers }).then(r => r.json()),
      fetch('/api/distrules/evaluation/rules', { headers }).then(r => r.json()),
      fetch('/api/distrules/suspension-rules', { headers }).then(r => r.json()),
      fetch('/api/pool/segments',              { headers }).then(r => r.json()),
    ]).then(([o, e, s, sg]) => {
      if (o.success)  setOpsRules(o.data.rules  || []);
      if (e.success)  setEvalRules(e.data.rules  || []);
      if (s.success)  setSuspRules(s.data.rules  || []);
      if (sg.success) setSegments(sg.data.segments || []);
      setLoading(false);
    }).catch(() => setLoading(false));
  };
  useEffect(load, []);

  const save = () => {
    if (!editing) return;
    setSaving(true);
    const { rule, type } = editing;
    const url  = type === 'eval'
      ? `/api/distrules/evaluation/rules/${rule.rule_key}`
      : `/api/distrules/rules/${rule.id}`;
    const body = type === 'eval'
      ? { value: rule.value, enabled: rule.enabled ? 1 : 0 }
      : { value: rule.value, is_active: rule.is_active };
    fetch(url, { method: 'PUT', headers, body: JSON.stringify(body) })
      .then(r => r.json()).then(d => {
        setSaving(false);
        if (d.success) { toast('ذخیره شد', 'success'); setEditing(null); load(); }
        else toast(d.message || 'خطا', 'error');
      }).catch(() => { setSaving(false); toast('خطای شبکه', 'error'); });
  };

  const opsGrouped  = opsRules.reduce((acc, r) => { (acc[r.category]    = acc[r.category]    || []).push(r); return acc; }, {});
  const evalGrouped = evalRules.reduce((acc, r) => { (acc[r.group_name] = acc[r.group_name]  || []).push(r); return acc; }, {});

  const TABS = [
    ['input',     '📥 ورودی'],
    ['dist',      '📤 توزیع'],
    ['return',    '↩️ برگشت'],
    ['graveyard', '🪦 قبرستان'],
    ['ops',       '⚙️ عملیاتی'],
    ['guide',     '🗺️ راهنمای شکار'],
  ];

  const sharedProps = { opsGrouped, headers, load, toast, setEditing };

  return (
    <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 16, height: '100%' }}>

      <div>
        <div style={{ fontSize: 18, fontWeight: 700, color: '#e2e8f0' }}>{'قوانین'}</div>
        <div style={{ fontSize: 12, color: '#64748b', marginTop: 2 }}>{'قوانین ورودی لید، توزیع، برگشت به استخر، قبرستان و عملیات'}</div>
      </div>

      <div style={{ display: 'flex', gap: 4, padding: '4px', borderRadius: 10, background: 'rgba(255,255,255,0.04)', width: 'fit-content', flexWrap: 'wrap' }}>
        {TABS.map(([id, label]) => (
          <button key={id} onClick={() => setSection(id)} style={{
            padding: '6px 14px', borderRadius: 7, fontSize: 12, cursor: 'pointer', border: 'none',
            background: section === id ? '#6366F1' : 'transparent',
            color: section === id ? '#fff' : '#64748b', fontWeight: section === id ? 600 : 400,
            transition: 'all 0.15s',
          }}>{label}</button>
        ))}
      </div>

      <div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#374151' }}>{'در حال بارگذاری...'}</div>

        ) : section === 'input' ? (
          <RulesInputTab
            {...sharedProps}
            entryRules={opsGrouped['entry'] || []}
          />

        ) : section === 'dist' ? (
          <RulesDistTab
            {...sharedProps}
            evalGrouped={evalGrouped}
            evalRules={evalRules}
            suspRules={suspRules}
          />

        ) : section === 'return' ? (
          <RulesReturnTab
            {...sharedProps}
            segments={segments}
          />

        ) : section === 'graveyard' ? (
          <RulesGraveyardTab
            segments={segments}
            headers={headers}
            load={load}
            toast={toast}
          />

        ) : section === 'guide' ? (
          <RulesHuntGuide headers={headers} />
        ) : (
          <RulesOpsTab />
        )}
      </div>

      {editing && (() => {
        const { rule, type } = editing;
        const name     = rule.label || rule.name;
        const desc     = rule.description;
        const vType    = rule.value_type;
        const hasRange = rule.min_value !== null && rule.max_value !== null;
        return (
          <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.7)', zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center' }}
            onClick={e => e.target === e.currentTarget && setEditing(null)}>
            <div style={{ background:'#111118', border:'1px solid rgba(255,255,255,0.1)', borderRadius:14, padding:24, width:400 }}>
              <div style={{ fontSize:14, fontWeight:700, color:'#e2e8f0', marginBottom:4 }}>{name}</div>
              {desc && <div style={{ fontSize:11, color:'#475569', marginBottom:16, lineHeight:1.6 }}>{desc}</div>}

              <div style={{ marginBottom:14 }}>
                <div style={{ fontSize:11, color:'#64748b', marginBottom:6 }}>
                  {'مقدار '}{rule.unit ? '(' + rule.unit + ')' : ''}
                  {hasRange && <span style={{ color:'#64748b' }}>{' — بازه: '}{rule.min_value}{' تا '}{rule.max_value}</span>}
                </div>
                {vType === 'boolean' ? (
                  <div style={{ display:'flex', gap:8 }}>
                    {['true','false'].map(v => (
                      <button key={v} onClick={() => setEditing(p => ({ ...p, rule: { ...p.rule, value: v } }))} style={{
                        flex:1, padding:'9px 0', borderRadius:8, fontSize:12, cursor:'pointer', border:'none',
                        background: rule.value === v ? (v === 'true' ? 'rgba(52,211,153,0.2)' : 'rgba(248,113,113,0.2)') : 'rgba(255,255,255,0.06)',
                        color: rule.value === v ? (v === 'true' ? '#34D399' : '#F87171') : '#64748b',
                        fontWeight: rule.value === v ? 700 : 400,
                      }}>{v === 'true' ? '✅ بله' : '❌ خیر'}</button>
                    ))}
                  </div>
                ) : (
                  <input type="number"
                    value={rule.value}
                    min={rule.min_value ?? undefined}
                    max={rule.max_value ?? undefined}
                    onChange={e => setEditing(p => ({ ...p, rule: { ...p.rule, value: e.target.value } }))}
                    style={{ width:'100%', padding:'9px 12px', borderRadius:8, background:'rgba(255,255,255,0.06)', border:'1px solid rgba(255,255,255,0.12)', color:'#e2e8f0', fontSize:15, outline:'none', boxSizing:'border-box', direction:'ltr' }} />
                )}
              </div>

              <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:18, padding:'8px 12px', borderRadius:8, background:'rgba(255,255,255,0.04)' }}>
                <span style={{ flex:1, fontSize:12, color:'#94a3b8' }}>
                  {type === 'eval' ? 'این معیار در محاسبه امتیاز لحاظ شود؟' : 'وضعیت قانون'}
                </span>
                <button
                  onClick={() => {
                    if (type === 'eval') setEditing(p => ({ ...p, rule: { ...p.rule, enabled: p.rule.enabled ? 0 : 1 } }));
                    else setEditing(p => ({ ...p, rule: { ...p.rule, is_active: p.rule.is_active ? 0 : 1 } }));
                  }}
                  style={{
                    padding:'4px 14px', borderRadius:20, fontSize:11, cursor:'pointer', border:'none', fontWeight:600,
                    background: (type === 'eval' ? rule.enabled : rule.is_active) ? 'rgba(52,211,153,0.15)' : 'rgba(107,114,128,0.15)',
                    color:      (type === 'eval' ? rule.enabled : rule.is_active) ? '#34D399' : '#6B7280',
                  }}>
                  {(type === 'eval' ? rule.enabled : rule.is_active) ? '✅ فعال' : '⏸ غیرفعال'}
                </button>
              </div>

              <div style={{ display:'flex', gap:8, justifyContent:'flex-end' }}>
                <button onClick={() => setEditing(null)} style={{ padding:'7px 16px', borderRadius:8, fontSize:12, cursor:'pointer', border:'1px solid rgba(255,255,255,0.12)', background:'transparent', color:'#64748b' }}>{'انصراف'}</button>
                <button onClick={save} disabled={saving} style={{ padding:'7px 16px', borderRadius:8, fontSize:12, cursor:'pointer', border:'none', background:'#6366F1', color:'#fff', fontWeight:600 }}>
                  {saving ? 'در حال ذخیره...' : 'ذخیره'}
                </button>
              </div>
            </div>
          </div>
        );
      })()}
    </div>
  );
};

window.Rules = Rules;
