// ── چکاپ سلامت سیستم — بخش آزمایشگاه ───────────────────────

const LC_GROUPS = ['زیرساخت', 'داده اصلی', 'چرخه لید', 'کمپین و قوانین', 'آزمایشگاه'];

const LC_STATUS_CFG = {
  ok:   { color: '#10B981', bg: 'rgba(16,185,129,0.1)',  border: 'rgba(16,185,129,0.25)', label: 'سالم'   },
  warn: { color: '#F59E0B', bg: 'rgba(245,158,11,0.1)',  border: 'rgba(245,158,11,0.25)', label: 'هشدار'  },
  fail: { color: '#EF4444', bg: 'rgba(239,68,68,0.1)',   border: 'rgba(239,68,68,0.25)',  label: 'خرابی'  },
};

const LC_GROUP_ICONS = {
  'زیرساخت':        'database',
  'داده اصلی':      'file-text',
  'چرخه لید':       'git-branch',
  'کمپین و قوانین': 'settings',
  'آزمایشگاه':      'flask-conical',
};

const LC_REPAIR_TIPS = {
  db_leads:         'سرور را ریستارت کنید — node server/index.js',
  db_scripts:       'دیتابیس scripts.db را بررسی کنید',
  db_lab:           'جدول lab_populations در DB آزمایشگاه بررسی شود',
  sellers:          'از پنل → فروشندگان حداقل یک فروشنده فعال اضافه کنید',
  scripts:          'از پنل → اسکریپت‌ها یک اسکریپت فعال تعریف کنید',
  bot_rules:        'از پنل → قوانین ربات، خط‌قرمز یا راهنمایی اضافه کنید',
  products:         'از پنل → محصولات حداقل یک محصول اضافه کنید',
  leads_total:      'داده واقعی وارد کنید یا node seed_test.js اجرا کنید',
  leads_buyers:     'هنوز خریداری ثبت نشده — ممکن است سیستم تازه راه‌اندازی شده',
  lead_events:      'جدول lead_events خالی است — seed بزنید یا تست واقعی اجرا کنید',
  conversions:      'تبدیلی ثبت نشده — مطمئن شوید outcome=sold صحیح ثبت می‌شود',
  sales_feed:       'جدول sales_feed خالی — ربات یا فروشنده فروشی ثبت نکرده',
  installments:     'قسط معوق دارید — از پنل → اقساط بررسی کنید',
  campaigns:        'از پنل → کمپین‌ها حداقل یک کمپین فعال بسازید',
  followup_rules:   'از پنل → قوانین فالوآپ را تعریف کنید',
  auto_tag_rules:   'از پنل → قوانین تگ خودکار را تعریف کنید',
  segments:         'از پنل → Pool → سگمنت‌ها حداقل یک سگمنت بسازید',
  lab_populations:  'از تب آزمایشگاه → جامعه یک جامعه آزمایشی بسازید',
  test_seed:        'اجرا کنید: node seed_test.js',
};

const LabCheckup = () => {
  const { Icon, useToast } = window.SB_UI;
  const { fa } = window.SB_DATA;
  const toast = useToast();

  const [running,   setRunning]   = useState(false);
  const [result,    setResult]    = useState(null);   // آخرین نتیجه
  const [history,   setHistory]   = useState([]);     // تاریخچه آخرین ۵ بار
  const [autoMin,   setAutoMin]   = useState(0);      // 0 = خاموش
  const [expanded,  setExpanded]  = useState({});     // بسط check برای دیدن tip
  const autoRef = useRef(null);

  const fmtTime = (iso) => {
    if (!iso) return '';
    try {
      return new Date(iso).toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
    } catch { return iso.slice(11, 19); }
  };

  const runCheck = async () => {
    setRunning(true);
    try {
      const data = await window.api('/lab/health');
      if (data?.checks) {
        setResult(data);
        setHistory(prev => [data, ...prev].slice(0, 5));
        const { ok, warn, fail } = data.summary;
        if (fail > 0) toast(`⚠ چکاپ: ${fail} خرابی پیدا شد`, 'error');
        else if (warn > 0) toast(`چکاپ کامل شد — ${warn} هشدار`, 'warning');
        else toast(`سیستم سالم است — ${ok}/${ok} چک پاس شد ✓`, 'success');
      }
    } catch (e) {
      toast('خطا در اجرای چکاپ: ' + e.message, 'error');
    }
    setRunning(false);
  };

  // اتوران
  useEffect(() => {
    clearInterval(autoRef.current);
    if (autoMin > 0) {
      autoRef.current = setInterval(runCheck, autoMin * 60 * 1000);
    }
    return () => clearInterval(autoRef.current);
  }, [autoMin]);

  const toggleExpand = (id) => setExpanded(prev => ({ ...prev, [id]: !prev[id] }));

  const sumColor = (s) => s?.fail > 0 ? '#EF4444' : s?.warn > 0 ? '#F59E0B' : '#10B981';

  return (
    <div className="col gap-14">

      {/* ─── هدر و کنترل‌ها ─── */}
      <div className="row between" style={{ flexWrap: 'wrap', gap: 10 }}>
        <div>
          <div className="bold" style={{ fontSize: 15 }}>چکاپ سلامت سیستم</div>
          <div className="text-xs text-3 mt-4">
            {result
              ? `آخرین بررسی: ${fmtTime(result.ts)} — ${result.summary.ok}/${result.summary.total} سالم`
              : 'هنوز اجرا نشده'}
          </div>
        </div>

        <div className="row gap-8" style={{ flexWrap: 'wrap', alignItems: 'center' }}>
          {/* تکرار خودکار */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 7,
            padding: '6px 11px', borderRadius: 8,
            background: 'var(--bg-3)', border: '1px solid var(--border-soft)',
          }}>
            <Icon name="repeat" size={13} color={autoMin > 0 ? '#6C63FF' : 'var(--text-3)'} />
            <span style={{ fontSize: 11, color: 'var(--text-3)', whiteSpace: 'nowrap' }}>تکرار خودکار:</span>
            <select
              value={autoMin}
              onChange={e => setAutoMin(Number(e.target.value))}
              style={{
                background: 'transparent', border: 'none', outline: 'none',
                color: autoMin > 0 ? '#6C63FF' : 'var(--text-1)',
                fontSize: 12, fontWeight: autoMin > 0 ? 600 : 400, cursor: 'pointer',
              }}>
              <option value={0}>غیرفعال</option>
              <option value={5}>هر ۵ دقیقه</option>
              <option value={15}>هر ۱۵ دقیقه</option>
              <option value={30}>هر ۳۰ دقیقه</option>
              <option value={60}>هر ۶۰ دقیقه</option>
            </select>
          </div>

          <button
            onClick={runCheck}
            disabled={running}
            style={{
              display: 'flex', alignItems: 'center', gap: 8,
              padding: '9px 20px', borderRadius: 10,
              cursor: running ? 'wait' : 'pointer',
              background: running ? 'rgba(108,99,255,0.55)' : '#6C63FF',
              border: 'none',
              color: '#fff', fontSize: 13, fontWeight: 700,
              boxShadow: running ? 'none' : '0 2px 14px rgba(108,99,255,0.45)',
              transition: 'background 0.15s, box-shadow 0.15s',
            }}>
            <Icon name={running ? 'loader' : 'activity'} size={15} />
            {running ? 'در حال بررسی...' : 'اجرای چکاپ'}
          </button>
        </div>
      </div>

      {/* ─── خلاصه آماری ─── */}
      {result && (
        <div className="row gap-10" style={{ flexWrap: 'wrap' }}>
          {[
            { label: 'سالم',  count: result.summary.ok,   color: '#10B981', bg: 'rgba(16,185,129,0.08)',  icon: 'circle-check' },
            { label: 'هشدار', count: result.summary.warn, color: '#F59E0B', bg: 'rgba(245,158,11,0.08)',  icon: 'alert-triangle' },
            { label: 'خرابی', count: result.summary.fail, color: '#EF4444', bg: 'rgba(239,68,68,0.08)',   icon: 'x-circle' },
          ].map(s => (
            <div key={s.label} style={{
              flex: 1, minWidth: 100, padding: '10px 14px', borderRadius: 10,
              background: s.bg, border: `1px solid ${s.color}33`,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <Icon name={s.icon} size={18} color={s.color} />
              <div>
                <div style={{ fontSize: 20, fontWeight: 700, color: s.color, fontFamily: 'monospace' }}>{fa(s.count)}</div>
                <div style={{ fontSize: 11, color: 'var(--text-3)' }}>{s.label}</div>
              </div>
            </div>
          ))}

          {/* نوار پیشرفت */}
          <div style={{ width: '100%', height: 6, background: 'var(--border-soft)', borderRadius: 99, overflow: 'hidden' }}>
            <div style={{
              width: `${Math.round((result.summary.ok / result.summary.total) * 100)}%`,
              height: '100%',
              background: sumColor(result.summary),
              transition: 'width 0.5s ease',
              borderRadius: 99,
            }} />
          </div>
        </div>
      )}

      {/* ─── نتایج گروه‌بندی‌شده ─── */}
      {result && LC_GROUPS.map(group => {
        const checks = result.checks.filter(c => c.group === group);
        if (!checks.length) return null;
        const groupFail = checks.filter(c => c.status === 'fail').length;
        const groupWarn = checks.filter(c => c.status === 'warn').length;
        const groupOk   = checks.filter(c => c.status === 'ok').length;

        return (
          <div key={group} style={{
            border: `1px solid ${groupFail > 0 ? 'rgba(239,68,68,0.2)' : groupWarn > 0 ? 'rgba(245,158,11,0.2)' : 'var(--border-soft)'}`,
            borderRadius: 12, overflow: 'hidden',
          }}>
            {/* هدر گروه */}
            <div style={{
              padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10,
              background: groupFail > 0 ? 'rgba(239,68,68,0.05)' : groupWarn > 0 ? 'rgba(245,158,11,0.05)' : 'rgba(108,99,255,0.04)',
              borderBottom: '1px solid var(--border-soft)',
            }}>
              <Icon name={LC_GROUP_ICONS[group] || 'box'} size={14} color="var(--primary-2)" />
              <span className="bold text-sm">{group}</span>
              <div className="row gap-6" style={{ marginRight: 'auto' }}>
                {groupOk > 0   && <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 20, background: 'rgba(16,185,129,0.12)', color: '#10B981' }}>{fa(groupOk)} سالم</span>}
                {groupWarn > 0 && <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 20, background: 'rgba(245,158,11,0.12)', color: '#F59E0B' }}>{fa(groupWarn)} هشدار</span>}
                {groupFail > 0 && <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 20, background: 'rgba(239,68,68,0.12)', color: '#EF4444' }}>{fa(groupFail)} خرابی</span>}
              </div>
            </div>

            {/* ردیف‌های چک */}
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {checks.map((c, i) => {
                const cfg = LC_STATUS_CFG[c.status] || LC_STATUS_CFG.warn;
                const tip = LC_REPAIR_TIPS[c.id];
                const isExpanded = expanded[c.id];

                return (
                  <div key={c.id} style={{
                    borderTop: i > 0 ? '1px solid var(--border-soft)' : 'none',
                  }}>
                    <div
                      onClick={() => tip && toggleExpand(c.id)}
                      style={{
                        padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 12,
                        cursor: tip ? 'pointer' : 'default',
                        background: isExpanded ? 'rgba(15,15,26,0.4)' : 'transparent',
                        transition: 'background 0.15s',
                      }}
                      onMouseEnter={e => { if (tip) e.currentTarget.style.background = 'rgba(15,15,26,0.3)'; }}
                      onMouseLeave={e => { if (!isExpanded) e.currentTarget.style.background = 'transparent'; }}>

                      {/* وضعیت */}
                      <div style={{
                        width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
                        background: cfg.color,
                        boxShadow: c.status !== 'ok' ? `0 0 6px ${cfg.color}` : 'none',
                      }} />

                      {/* نام */}
                      <span style={{ fontSize: 13, flex: 1, color: 'var(--text)' }}>{c.name}</span>

                      {/* جزئیات */}
                      <span style={{ fontSize: 11, color: 'var(--text-3)', fontFamily: 'monospace', textAlign: 'left' }}>
                        {c.detail}
                      </span>

                      {/* بج وضعیت */}
                      <span style={{
                        fontSize: 10, padding: '2px 8px', borderRadius: 20,
                        background: cfg.bg, border: `1px solid ${cfg.border}`,
                        color: cfg.color, fontWeight: 600, flexShrink: 0, minWidth: 44, textAlign: 'center',
                      }}>{cfg.label}</span>

                      {/* آیکون باز/بسته */}
                      {tip && (
                        <Icon name={isExpanded ? 'chevron-up' : 'chevron-down'} size={13} color="var(--text-3)" />
                      )}
                    </div>

                    {/* راهنمای تعمیر */}
                    {isExpanded && tip && (
                      <div style={{
                        margin: '0 14px 10px',
                        padding: '10px 14px',
                        borderRadius: 8,
                        background: `${cfg.bg}`,
                        border: `1px solid ${cfg.border}`,
                        display: 'flex', alignItems: 'flex-start', gap: 8,
                      }}>
                        <Icon name="tool" size={14} color={cfg.color} style={{ marginTop: 2, flexShrink: 0 }} />
                        <div>
                          <div style={{ fontSize: 11, fontWeight: 600, color: cfg.color, marginBottom: 4 }}>راهنمای تعمیر</div>
                          <div style={{ fontSize: 12, color: 'var(--text-2)', lineHeight: 1.7, fontFamily: 'monospace', direction: 'ltr', textAlign: 'left' }}>{tip}</div>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}

      {/* ─── تاریخچه اجراها ─── */}
      {history.length > 1 && (
        <div style={{ borderTop: '1px solid var(--border-soft)', paddingTop: 14 }}>
          <div className="text-xs text-3 semi" style={{ marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
            تاریخچه آخرین {fa(history.length)} بار
          </div>
          <div className="row gap-8" style={{ flexWrap: 'wrap' }}>
            {history.map((h, i) => (
              <div key={i} style={{
                padding: '6px 12px', borderRadius: 8,
                background: 'rgba(15,15,26,0.4)',
                border: `1px solid ${h.summary.fail > 0 ? 'rgba(239,68,68,0.3)' : h.summary.warn > 0 ? 'rgba(245,158,11,0.3)' : 'rgba(16,185,129,0.3)'}`,
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <div style={{
                  width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
                  background: h.summary.fail > 0 ? '#EF4444' : h.summary.warn > 0 ? '#F59E0B' : '#10B981',
                }} />
                <span className="mono text-xs" style={{ color: 'var(--text-3)' }}>{fmtTime(h.ts)}</span>
                <span style={{ fontSize: 11, color: 'var(--text-2)' }}>{h.summary.ok}/{h.summary.total}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ─── حالت خالی ─── */}
      {!result && !running && (
        <div style={{
          padding: '32px 0', textAlign: 'center',
          color: 'var(--text-3)', fontSize: 13,
          border: '1px dashed var(--border-soft)', borderRadius: 12,
        }}>
          <Icon name="activity" size={32} color="var(--text-3)" style={{ marginBottom: 12, display: 'block', margin: '0 auto 12px' }} />
          <div>روی «اجرای چکاپ» کلیک کن تا سیستم بررسی بشه</div>
          <div className="text-xs mt-6">۱۷ چک در ۵ دسته — نتیجه آنی</div>
        </div>
      )}
    </div>
  );
};

window.LabCheckup = LabCheckup;
