// CEO Dashboard v3 — کنترل مرکزی مدیرعامل · با داده واقعی
const CeoDashboard = () => {
  const { fa } = window.SB_DATA;

  // ─── State ────────────────────────────────────────────────
  const [ceoTab,        setCeoTab]        = useState('command');
  const [ceoLoading,    setCeoLoading]    = useState(true);
  const [ceoLS,         setCeoLS]         = useState(null);   // leads/stats/overview
  const [ceoMS,         setCeoMS]         = useState(null);   // market/stats
  const [ceoSR,         setCeoSR]         = useState(null);   // market/sales-report (overall)
  const [ceoSellers,    setCeoSellers]    = useState([]);     // market/sales-report sellers
  const [ceoSellerDet,  setCeoSellerDet]  = useState([]);     // market/sellers (detail)
  const [ceoCamps,      setCeoCamps]      = useState([]);     // campaigns
  const [ceoScripts,    setCeoScripts]    = useState([]);     // scripts
  const [ceoFuSt,       setCeoFuSt]       = useState(null);  // followup/stats
  const [ceoFuRules,    setCeoFuRules]    = useState([]);    // followup/rules

  const ceoHdrs = { Authorization: `Bearer ${localStorage.getItem(window.TOKEN_KEY)}` };

  // ─── CSS injection ────────────────────────────────────────
  useEffect(() => {
    const SID = 'ceo-v3-css';
    if (document.getElementById(SID)) return;
    const el = document.createElement('style');
    el.id = SID;
    el.textContent = `
.ceo-page{font-family:inherit;direction:rtl}
.ceo-nav{display:flex;gap:6px;flex-wrap:wrap;background:#101622;border:1px solid rgba(255,255,255,0.06);border-radius:14px;padding:6px;margin-bottom:20px}
.ceo-nav-btn{padding:9px 16px;border-radius:9px;cursor:pointer;font-size:12px;font-weight:700;color:#8b95a7;background:transparent;border:1px solid transparent;transition:all .15s;white-space:nowrap;font-family:inherit}
.ceo-nav-btn:hover{color:#c4cbd8;background:rgba(255,255,255,0.04)}
.ceo-nav-btn.active{color:#fff;background:rgba(129,140,248,0.18);border-color:rgba(129,140,248,0.38)}
.ceo-tab{display:none}.ceo-tab.active{display:block}
.ceo-pnl{background:linear-gradient(180deg,#161d2b,#11161f);border:1px solid rgba(255,255,255,0.09);border-radius:18px;padding:22px 24px;margin-bottom:16px;position:relative;overflow:hidden}
.ceo-pnl::before{content:'';position:absolute;top:0;right:0;left:0;height:3px;background:linear-gradient(90deg,#34d399,#818cf8,#f87171)}
.ceo-card{background:#121823;border:1px solid rgba(255,255,255,0.07);border-radius:14px;padding:18px 20px;margin-bottom:14px}
.ceo-card-sm{background:#141a24;border:1px solid rgba(255,255,255,0.07);border-radius:12px;padding:15px 18px}
.ceo-grid5{display:grid;grid-template-columns:repeat(5,1fr);gap:12px;margin-bottom:14px}
.ceo-grid4{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:14px}
.ceo-grid3{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:14px}
.ceo-grid2{display:grid;grid-template-columns:repeat(2,1fr);gap:12px;margin-bottom:14px}
.ceo-knum{font-size:26px;font-weight:800;margin:6px 0 3px}
.ceo-klbl{font-size:11px;color:#8b95a7}
.ceo-ksub{font-size:11px;margin-top:4px}
.ceo-tag{display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:700;border-radius:8px;padding:4px 10px;white-space:nowrap}
.ceo-tag-g{color:#5ee9b5;background:rgba(52,211,153,0.12);border:1px solid rgba(52,211,153,0.22)}
.ceo-tag-r{color:#fb9d9d;background:rgba(248,113,113,0.12);border:1px solid rgba(248,113,113,0.22)}
.ceo-tag-y{color:#fcd66b;background:rgba(251,191,36,0.12);border:1px solid rgba(251,191,36,0.22)}
.ceo-tag-p{color:#c7cdfa;background:rgba(129,140,248,0.12);border:1px solid rgba(129,140,248,0.22)}
.ceo-insight{display:flex;gap:9px;align-items:flex-start;background:rgba(129,140,248,0.07);border:1px solid rgba(129,140,248,0.16);border-radius:11px;padding:12px 14px;font-size:12px;line-height:1.7;color:#c4cbd8;margin-top:14px}
.ceo-insight-r{background:rgba(248,113,113,0.07);border-color:rgba(248,113,113,0.16)}
.ceo-insight-g{background:rgba(52,211,153,0.07);border-color:rgba(52,211,153,0.16)}
.ceo-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 0;border-bottom:1px solid rgba(255,255,255,0.05)}
.ceo-row:last-child{border-bottom:none}
.ceo-bar-wrap{height:8px;border-radius:4px;background:rgba(255,255,255,0.06)}
.ceo-bar-fill{height:100%;border-radius:4px;transition:width .4s ease}
.ceo-ondot{width:8px;height:8px;border-radius:50%;flex:none}
.ceo-divider{border:none;border-top:1px solid rgba(255,255,255,0.06);margin:12px 0}
.ceo-section-title{font-size:15px;font-weight:800;margin-bottom:14px;display:flex;align-items:center;gap:8px}
.ceo-av{width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:800;flex:none}
@media(max-width:900px){.ceo-grid5{grid-template-columns:repeat(3,1fr)}.ceo-grid4{grid-template-columns:repeat(2,1fr)}}
@media(max-width:600px){.ceo-grid5,.ceo-grid4,.ceo-grid3{grid-template-columns:repeat(2,1fr)}.ceo-grid2{grid-template-columns:1fr}}
    `;
    document.head.appendChild(el);
  }, []);

  // ─── Data fetch ───────────────────────────────────────────
  useEffect(() => {
    const h = ceoHdrs;
    Promise.all([
      fetch('/api/leads/stats/overview',  { headers: h }).then(r => r.json()).catch(() => ({})),
      fetch('/api/market/stats',           { headers: h }).then(r => r.json()).catch(() => ({})),
      fetch('/api/market/sales-report',    { headers: h }).then(r => r.json()).catch(() => ({})),
      fetch('/api/market/sellers',         { headers: h }).then(r => r.json()).catch(() => ({})),
      fetch('/api/campaigns/campaigns',    { headers: h }).then(r => r.json()).catch(() => []),
      fetch('/api/scripts',               { headers: h }).then(r => r.json()).catch(() => ({})),
      fetch('/api/followup/stats',        { headers: h }).then(r => r.json()).catch(() => ({})),
      fetch('/api/followup/rules',        { headers: h }).then(r => r.json()).catch(() => ({})),
    ]).then(([ls, ms, sr, selDet, camps, scripts, fuSt, fuRules]) => {
      if (ls.success)    setCeoLS(ls.data.stats);
      if (ms.success)    setCeoMS(ms.data.stats);
      if (sr.success) {
        setCeoSR(sr.data.overall);
        setCeoSellers(sr.data.sellers || []);
      }
      if (selDet.success) setCeoSellerDet(selDet.data.sellers || []);
      const cl = Array.isArray(camps) ? camps : [];
      setCeoCamps(cl);
      if (scripts.success) setCeoScripts(scripts.data.scripts || []);
      if (fuSt.success)    setCeoFuSt(fuSt.data);
      if (fuRules.success) setCeoFuRules(fuRules.data || []);
    }).finally(() => setCeoLoading(false));
  }, []);

  // ─── Helpers ──────────────────────────────────────────────
  const fmon = (v) => {
    if (!v && v !== 0) return '—';
    if (v >= 1000000) return fa(+(v / 1000000).toFixed(1)) + 'M';
    if (v >= 1000)    return fa(+(v / 1000).toFixed(0)) + 'K';
    return fa(v);
  };
  const fpc = (v) => v != null ? fa(Math.round(v)) + '٪' : '—';
  const pbar = (pct, color, h=8) => (
    <div className="ceo-bar-wrap" style={{height: h}}>
      <div className="ceo-bar-fill" style={{width: `${Math.min(pct||0, 100)}%`, background: color, height: h}} />
    </div>
  );
  const tagC = (cls, txt) => <span className={`ceo-tag ceo-tag-${cls}`}>{txt}</span>;

  // ─── Derived ──────────────────────────────────────────────
  const ls = ceoLS || {};
  const ms = ceoMS || {};
  const sr = ceoSR  || {};

  const totalLeads  = ls.total    || 0;
  const buyers      = ls.buyer    || 0;
  const lostLeads   = (ls.lost || 0) + (ls.cancelled || 0);
  const convRate    = totalLeads > 0 ? Math.round(buyers / totalLeads * 100) : 0;
  const todayLeads  = ls.today    || 0;
  const frozenLeads = ls.frozen   || 0;
  const slaOverdue  = ms.overdue  || 0;
  const poolCount   = ms.pool_count || 0;
  const totalRev    = sr.totalRevenue || 0;

  // funnel drop %
  const funnelSteps = [
    { label: 'ورود لید',     val: totalLeads,              color: '#818cf8' },
    { label: 'پیگیری',       val: ls.follow_up || 0,       color: '#7986e6' },
    { label: 'در دست فروش',  val: ls.in_sales  || 0,       color: '#5dd0c0' },
    { label: 'تماس گرفته',   val: ls.called    || 0,       color: '#fbbf24' },
    { label: 'خرید',         val: buyers,                  color: '#34d399' },
  ];
  const funnelMax = funnelSteps[0].val || 1;

  // channel data
  const chTg   = ls.telegram || 0;
  const chBale = ls.bale     || 0;
  const chOther = Math.max(0, totalLeads - chTg - chBale);

  // seller merge: combine sales-report with detail
  const selMerged = ceoSellers.map(s => {
    const det = ceoSellerDet.find(d => d.id === s.id) || {};
    return { ...s, ...det, overdue_leads: det.overdue_leads || 0 };
  });

  // seller diagnosis
  const selDiag = (s) => {
    if (!s.is_active) return { lbl: 'غیرفعال', cls: 'p' };
    if (s.overdue_leads > 2) return { lbl: 'SLA منقضی', cls: 'r' };
    if (s.conversionRate < 15) return { lbl: 'نرخ پایین', cls: 'r' };
    if (s.conversionRate < 30) return { lbl: 'متوسط', cls: 'y' };
    return { lbl: 'عملکرد خوب', cls: 'g' };
  };

  // campaign ROI (rough: buyer_count / lead_count * scalar)
  const campRoi = (c) => {
    if (!c.lead_count) return null;
    return +(c.buyer_count / c.lead_count * 100).toFixed(0);
  };

  if (ceoLoading) return (
    <div className="ceo-grid5" style={{marginBottom: 0}}>
      {[1,2,3,4,5].map(i => (
        <div key={i} className="ceo-card-sm" style={{height: 80, opacity: 0.3}} />
      ))}
    </div>
  );

  // ─── Sub-render: KPI Card ─────────────────────────────────
  const KpiCard = ({ label, val, sub, valColor, subColor }) => (
    <div className="ceo-card-sm">
      <div className="ceo-klbl">{label}</div>
      <div className="ceo-knum" style={{color: valColor || '#e6eaf2'}}>{val}</div>
      {sub && <div className="ceo-ksub" style={{color: subColor || '#8b95a7'}}>{sub}</div>}
    </div>
  );

  // ─── TAB: Command Center ──────────────────────────────────
  const TabCommand = () => {
    const biggestLeak = slaOverdue > 3
      ? `${fa(slaOverdue)} لید با SLA منقضی بدون پیگیری`
      : frozenLeads > 5
      ? `${fa(frozenLeads)} لید فریز رهاشده`
      : lostLeads > 10
      ? `${fa(lostLeads)} لید باخته‌شده این ماه`
      : 'بدون هشدار بحرانی';

    const funnelDrop = (curr, prev) => {
      if (!prev) return null;
      const d = Math.round((prev - curr) / prev * 100);
      return d > 0 ? `−${fa(d)}٪` : null;
    };

    return (
      <div>
        {/* P&L Hero */}
        <div className="ceo-pnl">
          <div style={{fontSize: 11, color: '#8b95a7', fontWeight: 700, letterSpacing: '.5px', marginBottom: 10}}>
            تابلوی سود و زیان · پول کجاست؟
          </div>
          <div style={{fontSize: 24, fontWeight: 800, lineHeight: 1.4, marginBottom: 16}}>
            درآمد کل{' '}
            <span style={{color: '#34d399'}}>{fmon(totalRev)}</span>
            <span style={{color: '#5b6679', margin: '0 10px'}}>·</span>
            خریداران{' '}
            <span style={{color: '#c7cdfa'}}>{fa(buyers)} نفر</span>
            <span style={{color: '#5b6679', margin: '0 10px'}}>·</span>
            نرخ تبدیل{' '}
            <span style={{color: convRate >= 30 ? '#34d399' : convRate >= 15 ? '#fbbf24' : '#f87171'}}>{fpc(convRate)}</span>
          </div>
          <div className="ceo-grid2" style={{gap: 12, marginBottom: 14}}>
            <div style={{background: 'rgba(52,211,153,0.06)', border: '1px solid rgba(52,211,153,0.2)', borderRadius: 12, padding: '13px 16px'}}>
              <div style={{fontSize: 12, fontWeight: 800, color: '#34d399', marginBottom: 10}}>▲ منابع درآمد</div>
              <div style={{display: 'flex', flexDirection: 'column', gap: 7}}>
                {[
                  { n: 'تلگرام', v: fa(chTg) + ' لید' },
                  { n: 'بله', v: fa(chBale) + ' لید' },
                  { n: 'خریداران کل', v: fa(buyers) + ' نفر' },
                  { n: 'درآمد ثبت‌شده', v: fmon(totalRev) },
                ].map((g, i) => (
                  <div key={i} style={{display: 'flex', justifyContent: 'space-between', fontSize: 13}}>
                    <span style={{color: '#cdd4e0'}}>{g.n}</span>
                    <b style={{color: '#34d399'}}>{g.v}</b>
                  </div>
                ))}
              </div>
            </div>
            <div style={{background: 'rgba(248,113,113,0.06)', border: '1px solid rgba(248,113,113,0.2)', borderRadius: 12, padding: '13px 16px'}}>
              <div style={{fontSize: 12, fontWeight: 800, color: '#f87171', marginBottom: 10}}>▼ نشتی و ریزش</div>
              <div style={{display: 'flex', flexDirection: 'column', gap: 7}}>
                {[
                  { n: 'لیدهای باخته', v: fa(lostLeads) + ' نفر', warn: lostLeads > 20 },
                  { n: 'SLA منقضی',    v: fa(slaOverdue) + ' لید',  warn: slaOverdue > 0 },
                  { n: 'فریز رهاشده', v: fa(frozenLeads) + ' لید',  warn: frozenLeads > 5 },
                  { n: 'در استخر بلاتکلیف', v: fa(poolCount) + ' لید', warn: poolCount > 30 },
                ].map((g, i) => (
                  <div key={i} style={{display: 'flex', justifyContent: 'space-between', fontSize: 13}}>
                    <span style={{color: '#cdd4e0'}}>{g.n}</span>
                    <b style={{color: g.warn ? '#f87171' : '#fbbf24'}}>{g.v}</b>
                  </div>
                ))}
              </div>
            </div>
          </div>
          <div className="ceo-insight">
            <span style={{color: '#818cf8', fontSize: 15}}>✦</span>
            <div>
              <b style={{color: '#fff'}}>تحلیل:</b>
              {' '}بزرگ‌ترین نشتی: <b style={{color: '#fbbf24'}}>{biggestLeak}</b>.
              نرخ تبدیل کل <b style={{color: convRate >= 20 ? '#34d399' : '#f87171'}}>{fpc(convRate)}</b> است.
              {convRate < 20 && ' بهینه‌سازی اسکریپت و پیگیری اولیه توصیه می‌شود.'}
            </div>
          </div>
        </div>

        {/* KPIs */}
        <div className="ceo-grid5">
          <KpiCard label="فروش کل" val={fmon(totalRev)} sub={`از ${fa(buyers)} خریدار`} valColor="#34d399" subColor="#5ee9b5" />
          <KpiCard label="نرخ تبدیل" val={fpc(convRate)} sub={convRate >= 20 ? '▲ در سطح هدف' : '▼ زیر هدف'} valColor={convRate >= 20 ? '#34d399' : '#f87171'} subColor={convRate >= 20 ? '#5ee9b5' : '#fb9d9d'} />
          <KpiCard label="SLA منقضی" val={fa(slaOverdue)} sub={slaOverdue > 0 ? 'اقدام فوری' : 'همه در وقت'} valColor={slaOverdue > 0 ? '#fb9d9d' : '#34d399'} subColor={slaOverdue > 0 ? '#f87171' : '#5ee9b5'} />
          <KpiCard label="فریز رهاشده" val={fa(frozenLeads)} sub={frozenLeads > 5 ? '+۵ لید بی‌حرکت' : 'تحت کنترل'} valColor={frozenLeads > 5 ? '#fcd66b' : '#e6eaf2'} subColor={frozenLeads > 5 ? '#fbbf24' : '#8b95a7'} />
          <KpiCard label="لید امروز" val={fa(todayLeads)} sub={`از ${fa(totalLeads)} کل`} />
        </div>

        {/* Funnel */}
        <div className="ceo-card">
          <div className="ceo-section-title">قیف فروش</div>
          <div style={{display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 8, marginBottom: 12}}>
            {funnelSteps.map((f, i) => {
              const h = Math.max(18, Math.round((f.val / funnelMax) * 100));
              const drop = i > 0 ? funnelDrop(f.val, funnelSteps[i-1].val) : null;
              return (
                <React.Fragment key={i}>
                  {drop && (
                    <div style={{fontSize: 10, fontWeight: 700, background: 'rgba(248,113,113,0.14)', borderRadius: 5, padding: '2px 5px', color: '#f87171', alignSelf: 'center', flexShrink: 0}}>
                      {drop}
                    </div>
                  )}
                  <div style={{flex: 1, textAlign: 'center'}}>
                    <div style={{fontSize: 14, fontWeight: 800, marginBottom: 6, color: i === funnelSteps.length - 1 ? '#34d399' : '#e6eaf2'}}>{fa(f.val)}</div>
                    <div style={{height: h, background: `linear-gradient(180deg,${f.color},${f.color}bb)`, borderRadius: '7px 7px 3px 3px'}} />
                    <div style={{fontSize: 11, color: '#cdd4e0', marginTop: 6}}>{f.label}</div>
                  </div>
                </React.Fragment>
              );
            })}
          </div>
          <div className="ceo-insight ceo-insight-r" style={{marginTop: 10}}>
            <span style={{color: '#f87171', fontSize: 14}}>⚠</span>
            <div>
              <b style={{color: '#fff'}}>نقطه بحران:</b>
              {' '}از {fa(totalLeads)} لید ورودی، تنها {fa(buyers)} خریدار شدند ({fpc(convRate)}).
              {ls.in_sales > 0 && ` در حال حاضر ${fa(ls.in_sales)} لید در دست فروشندگان است.`}
            </div>
          </div>
        </div>

        {/* Quick Stats */}
        <div className="ceo-grid4" style={{marginBottom: 0}}>
          <KpiCard label="لید در استخر" val={fa(poolCount)} sub="منتظر انتساب" />
          <KpiCard label="لید در فروش" val={fa(ls.in_sales || 0)} sub="در دست فروشنده" />
          <KpiCard label="تماس گرفته‌شده" val={fa(ls.called || 0)} sub={`از ${fa(totalLeads)} کل`} />
          <KpiCard label="باخته شده" val={fa(lostLeads)} sub="lost + cancelled" valColor={lostLeads > 20 ? '#fb9d9d' : '#e6eaf2'} subColor={lostLeads > 20 ? '#f87171' : '#8b95a7'} />
        </div>
      </div>
    );
  };

  // ─── TAB: Campaigns & Scripts ─────────────────────────────
  const TabCampaigns = () => {
    const activeCamps = ceoCamps.filter(c => c.is_active);
    const inactiveCamps = ceoCamps.filter(c => !c.is_active);

    return (
      <div>
        <div style={{fontSize: 20, fontWeight: 800, marginBottom: 4}}>کمپین‌ها و اسکریپت‌ها</div>
        <div style={{fontSize: 12, color: '#8b95a7', marginBottom: 16}}>کدام کمپین سودده است؟ اسکریپت‌ها چه وضعی دارند؟</div>

        <div className="ceo-grid4" style={{marginBottom: 14}}>
          <KpiCard label="کمپین کل" val={fa(ceoCamps.length)} sub={`${fa(activeCamps.length)} فعال`} />
          <KpiCard label="لید در کمپین" val={fa(ceoCamps.reduce((a,c) => a + (c.lead_count||0), 0))} sub="مجموع لیدها" />
          <KpiCard label="خریدار از کمپین" val={fa(ceoCamps.reduce((a,c) => a + (c.buyer_count||0), 0))} sub="مجموع خریداران" valColor="#34d399" />
          <KpiCard label="اسکریپت‌ها" val={fa(ceoScripts.length)} sub="در سیستم" valColor="#c7cdfa" />
        </div>

        {/* Campaigns List */}
        <div className="ceo-card" style={{marginBottom: 14}}>
          <div className="ceo-section-title">📣 کمپین‌ها</div>
          {ceoCamps.length === 0 ? (
            <div style={{color: '#8b95a7', fontSize: 13, padding: '12px 0'}}>هیچ کمپینی ثبت نشده</div>
          ) : (
            <div className="ceo-grid4" style={{marginBottom: 0}}>
              {ceoCamps.slice(0, 8).map((c, i) => {
                const roi = campRoi(c);
                const roiCls = roi == null ? 'p' : roi >= 30 ? 'g' : roi >= 10 ? 'y' : 'r';
                return (
                  <div key={i} className="ceo-card-sm" style={{borderRight: `3px solid ${roiCls === 'g' ? '#34d399' : roiCls === 'y' ? '#fbbf24' : roiCls === 'r' ? '#f87171' : '#818cf8'}`}}>
                    <div style={{fontWeight: 800, marginBottom: 6, fontSize: 14}}>{c.name}</div>
                    <div style={{fontSize: 22, fontWeight: 800, color: roiCls === 'g' ? '#34d399' : roiCls === 'y' ? '#fbbf24' : roiCls === 'r' ? '#f87171' : '#c7cdfa', marginBottom: 8}}>
                      {roi != null ? fa(roi) + '٪ تبدیل' : '—'}
                    </div>
                    <div style={{fontSize: 12, color: '#8b95a7', marginBottom: 10}}>
                      لید: {fa(c.lead_count||0)} · خریدار: {fa(c.buyer_count||0)}
                    </div>
                    <div style={{display: 'flex', gap: 6}}>
                      {tagC(roiCls, roi >= 30 ? 'سودده' : roi >= 10 ? 'متوسط' : roi != null ? 'ضعیف' : 'بدون داده')}
                      {tagC(c.is_active ? 'g' : 'p', c.is_active ? 'فعال' : 'غیرفعال')}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
          {ceoCamps.length > 0 && (
            <div className="ceo-insight">
              <span style={{color: '#818cf8', fontSize: 15}}>✦</span>
              <div>
                {activeCamps.length > 0
                  ? <><b style={{color: '#fff'}}>{fa(activeCamps.length)} کمپین فعال.</b> بهترین تبدیل: <b>{(() => { const best = [...ceoCamps].sort((a,b) => campRoi(b)-campRoi(a))[0]; return best ? best.name + ' ' + fa(campRoi(best)||0) + '٪' : '—'; })()}</b>.</>
                  : 'هیچ کمپین فعالی وجود ندارد.'
                }
              </div>
            </div>
          )}
        </div>

        {/* Scripts */}
        <div className="ceo-card">
          <div className="ceo-section-title">📝 اسکریپت‌ها</div>
          {ceoScripts.length === 0 ? (
            <div style={{color: '#8b95a7', fontSize: 13, padding: '12px 0'}}>هیچ اسکریپتی ثبت نشده</div>
          ) : ceoScripts.map((sc, i) => (
            <div key={i} className="ceo-row">
              <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
                <span className="ceo-ondot" style={{background: '#818cf8'}} />
                <div>
                  <div style={{fontWeight: 700}}>{sc.name}</div>
                  <div style={{fontSize: 11, color: '#8b95a7'}}>{sc.description || 'بدون توضیح'}</div>
                </div>
              </div>
              <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
                {tagC(sc.is_active ? 'g' : 'p', sc.is_active ? 'فعال' : 'غیرفعال')}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  // ─── TAB: Follow-up ───────────────────────────────────────
  const TabFollowup = () => {
    const fuSt = ceoFuSt || {};
    const responseRate = fuSt.log_total > 0 ? Math.round(fuSt.response_count / fuSt.log_total * 100) : 0;
    const activeRules = ceoFuRules.filter(r => r.is_active);

    return (
      <div>
        <div style={{fontSize: 20, fontWeight: 800, marginBottom: 4}}>فالوآپ</div>
        <div style={{fontSize: 12, color: '#8b95a7', marginBottom: 16}}>دنباله‌های پیگیری · نرخ پاسخ · لید گیرکرده</div>

        <div className="ceo-grid4" style={{marginBottom: 14}}>
          <KpiCard label="قوانین فالوآپ" val={fa(fuSt.rules_total||0)} sub={`${fa(fuSt.rules_active||0)} فعال`} />
          <KpiCard label="در صف ارسال" val={fa(fuSt.pending_count||0)} sub="منتظر ارسال" valColor={fuSt.pending_count > 50 ? '#fcd66b' : '#e6eaf2'} />
          <KpiCard label="ارسال شده" val={fa(fuSt.sent_count||0)} sub={`از ${fa(fuSt.log_total||0)} کل`} />
          <KpiCard label="نرخ پاسخ" val={fpc(responseRate)} sub={`${fa(fuSt.response_count||0)} پاسخ`} valColor={responseRate >= 30 ? '#34d399' : responseRate >= 15 ? '#fbbf24' : '#f87171'} subColor={responseRate >= 30 ? '#5ee9b5' : responseRate >= 15 ? '#fbbf24' : '#f87171'} />
        </div>

        <div className="ceo-card">
          <div className="ceo-section-title">قوانین فالوآپ</div>
          {ceoFuRules.length === 0 ? (
            <div style={{color: '#8b95a7', fontSize: 13, padding: '12px 0'}}>هیچ قانونی تعریف نشده</div>
          ) : ceoFuRules.map((r, i) => (
            <div key={i} className="ceo-row" style={{flexDirection: 'column', alignItems: 'stretch', gap: 8}}>
              <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between'}}>
                <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
                  <span className="ceo-ondot" style={{background: r.is_active ? '#34d399' : '#8b95a7'}} />
                  <div>
                    <div style={{fontWeight: 700}}>{r.name}</div>
                    <div style={{fontSize: 11, color: '#8b95a7'}}>{r.step_count || 0} گام · رویداد: {r.trigger_event || '—'}</div>
                  </div>
                </div>
                <div style={{display: 'flex', alignItems: 'center', gap: 12}}>
                  <div style={{textAlign: 'left'}}>
                    <div style={{fontSize: 11, color: '#8b95a7'}}>در صف</div>
                    <b style={{color: r.pending_count > 10 ? '#fcd66b' : '#e6eaf2'}}>{fa(r.pending_count||0)}</b>
                  </div>
                  <div style={{textAlign: 'left'}}>
                    <div style={{fontSize: 11, color: '#8b95a7'}}>ارسال</div>
                    <b>{fa(r.sent_count||0)}</b>
                  </div>
                  {tagC(r.is_active ? 'g' : 'p', r.is_active ? 'فعال' : 'غیرفعال')}
                </div>
              </div>
            </div>
          ))}
        </div>

        <div className="ceo-insight">
          <span style={{color: '#818cf8', fontSize: 15}}>✦</span>
          <div>
            <b style={{color: '#fff'}}>وضعیت فالوآپ:</b>
            {' '}{fa(fuSt.rules_active||0)} قانون فعال، {fa(fuSt.pending_count||0)} پیام در صف.
            نرخ پاسخ <b style={{color: responseRate >= 30 ? '#34d399' : '#fbbf24'}}>{fpc(responseRate)}</b>.
            {fuSt.failed_count > 0 && <> <b style={{color: '#f87171'}}>{fa(fuSt.failed_count)} پیام ناموفق</b> — بررسی شود.</>}
          </div>
        </div>
      </div>
    );
  };

  // ─── TAB: Distribution ────────────────────────────────────
  const TabDistribution = () => {
    const totalSellerLeads = selMerged.reduce((a, s) => a + (s.active_leads || 0), 0) || 1;

    return (
      <div>
        <div style={{fontSize: 20, fontWeight: 800, marginBottom: 4}}>توزیع خودکار</div>
        <div style={{fontSize: 12, color: '#8b95a7', marginBottom: 16}}>لیدها چطور توزیع می‌شوند؟ سهم هر فروشنده</div>

        <div className="ceo-grid4" style={{marginBottom: 14}}>
          <KpiCard label="لید بی‌انتساب" val={fa(poolCount)} sub="در استخر منتظر" valColor={poolCount > 10 ? '#fb9d9d' : '#e6eaf2'} subColor={poolCount > 10 ? '#f87171' : '#8b95a7'} />
          <KpiCard label="SLA منقضی" val={fa(slaOverdue)} sub="نیاز به اقدام فوری" valColor={slaOverdue > 0 ? '#fb9d9d' : '#34d399'} subColor={slaOverdue > 0 ? '#f87171' : '#5ee9b5'} />
          <KpiCard label="لید فریز" val={fa(frozenLeads)} sub="موقتاً متوقف" valColor={frozenLeads > 5 ? '#fcd66b' : '#e6eaf2'} />
          <KpiCard label="لید در فروش" val={fa(ls.in_sales||0)} sub="در دست فروشنده" valColor="#c7cdfa" />
        </div>

        <div className="ceo-card">
          <div className="ceo-section-title">سهم لید هر فروشنده</div>
          {selMerged.length === 0 ? (
            <div style={{color: '#8b95a7', fontSize: 13, padding: '12px 0'}}>هیچ فروشنده‌ای ثبت نشده</div>
          ) : selMerged.filter(s => s.is_active).map((s, i) => {
            const pct = Math.round((s.active_leads||0) / totalSellerLeads * 100);
            const col = s.overdue_leads > 2 ? '#f87171' : pct > 40 ? '#f87171' : pct > 25 ? '#fbbf24' : '#818cf8';
            return (
              <div key={i} style={{padding: '10px 0', borderBottom: '1px solid rgba(255,255,255,0.05)'}}>
                <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 6}}>
                  <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
                    <div className="ceo-av" style={{background: col + '33', color: col}}>{s.name?.[0] || '؟'}</div>
                    <span style={{fontWeight: 700}}>{s.name}</span>
                  </div>
                  <div style={{display: 'flex', alignItems: 'center', gap: 12}}>
                    <span style={{color: '#8b95a7', fontSize: 11}}>فعال: <b style={{color: '#e6eaf2'}}>{fa(s.active_leads||0)}</b></span>
                    <span style={{color: '#8b95a7', fontSize: 11}}>سهم: <b style={{color: col}}>{fa(pct)}٪</b></span>
                    {s.overdue_leads > 0 && <span style={{fontSize: 11, color: '#f87171'}}>SLA: {fa(s.overdue_leads)}</span>}
                  </div>
                </div>
                {pbar(pct, col)}
              </div>
            );
          })}
          {poolCount > 0 && (
            <div className="ceo-insight ceo-insight-r">
              <span style={{color: '#f87171', fontSize: 14}}>⚠</span>
              <div><b style={{color: '#fff'}}>هشدار:</b> {fa(poolCount)} لید در استخر بدون انتساب مانده‌اند — توزیع خودکار را فعال کنید.</div>
            </div>
          )}
        </div>
      </div>
    );
  };

  // ─── TAB: Media + Agents (merged) ────────────────────────
  const TabMedia = () => {
    const channels = [
      {
        name: 'تلگرام', leads: chTg, color: '#34d399',
        status: chTg > 0 ? 'g' : 'p',
        botNote: chTg > 0 ? 'بات فعال' : 'بدون داده',
        convApprox: totalLeads > 0 && buyers > 0 ? Math.round(buyers * chTg / totalLeads) : 0,
      },
      {
        name: 'بله', leads: chBale, color: chBale > 50 ? '#34d399' : '#fbbf24',
        status: chBale > 50 ? 'g' : chBale > 0 ? 'y' : 'p',
        botNote: chBale > 50 ? 'بات فعال' : chBale > 0 ? 'کم‌ترافیک' : 'بدون داده',
        convApprox: totalLeads > 0 && buyers > 0 ? Math.round(buyers * chBale / totalLeads) : 0,
      },
      {
        name: 'دستی / سایر', leads: chOther, color: '#818cf8',
        status: 'p',
        botNote: 'ورود دستی',
        convApprox: totalLeads > 0 && buyers > 0 ? Math.round(buyers * chOther / totalLeads) : 0,
      },
    ].filter(m => m.leads > 0);

    const chMax = Math.max(...channels.map(c => c.leads), 1);
    const bestCh = [...channels].sort((a,b) => b.leads - a.leads)[0];

    return (
      <div>
        <div style={{fontSize: 20, fontWeight: 800, marginBottom: 4}}>رسانه‌ها و بات‌ها</div>
        <div style={{fontSize: 12, color: '#8b95a7', marginBottom: 16}}>
          وضعیت هر کانال · سهم لید · خریدار تخمینی · بودجه کجا برود؟
        </div>

        {/* KPIs — 5 card */}
        <div className="ceo-grid5" style={{marginBottom: 14}}>
          <KpiCard label="کل لید" val={fa(totalLeads)} sub="از همه کانال‌ها" />
          <KpiCard label="تلگرام" val={fa(chTg)}
            sub={totalLeads > 0 ? fpc(chTg/totalLeads*100) + ' سهم' : '—'}
            valColor="#34d399" subColor="#5ee9b5" />
          <KpiCard label="بله" val={fa(chBale)}
            sub={totalLeads > 0 ? fpc(chBale/totalLeads*100) + ' سهم' : '—'}
            valColor="#5dd0c0" />
          <KpiCard label="خریداران" val={fa(buyers)}
            sub={`تخمین از کانال‌ها`} valColor="#c7cdfa" />
          <KpiCard label="نرخ تبدیل" val={fpc(convRate)}
            sub={convRate >= 20 ? '▲ در سطح هدف' : '▼ زیر هدف'}
            valColor={convRate >= 20 ? '#34d399' : '#f87171'}
            subColor={convRate >= 20 ? '#5ee9b5' : '#fb9d9d'} />
        </div>

        {/* Channel detail table */}
        <div className="ceo-card">
          <div className="ceo-section-title">عملکرد هر کانال / بات</div>
          {channels.length === 0 ? (
            <div style={{color: '#8b95a7', fontSize: 13, padding: '12px 0'}}>داده‌ای ثبت نشده</div>
          ) : channels.map((ch, i) => (
            <div key={i} style={{
              padding: '14px 0',
              borderBottom: i < channels.length - 1 ? '1px solid rgba(255,255,255,0.05)' : 'none',
              borderRight: `3px solid ${ch.color}`,
              paddingRight: 14,
            }}>
              {/* row top */}
              <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10}}>
                <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
                  <span className="ceo-ondot" style={{background: ch.color}} />
                  <div>
                    <div style={{fontWeight: 700, fontSize: 15}}>{ch.name}</div>
                    <div style={{fontSize: 11, color: '#8b95a7'}}>{ch.botNote}</div>
                  </div>
                </div>
                <div style={{display: 'flex', alignItems: 'center', gap: 16}}>
                  <div style={{textAlign: 'center'}}>
                    <div style={{fontSize: 11, color: '#8b95a7', marginBottom: 2}}>لید</div>
                    <b style={{color: ch.color, fontSize: 15}}>{fa(ch.leads)}</b>
                  </div>
                  <div style={{textAlign: 'center'}}>
                    <div style={{fontSize: 11, color: '#8b95a7', marginBottom: 2}}>سهم</div>
                    <b style={{fontSize: 15}}>{totalLeads > 0 ? fpc(ch.leads/totalLeads*100) : '—'}</b>
                  </div>
                  <div style={{textAlign: 'center'}}>
                    <div style={{fontSize: 11, color: '#8b95a7', marginBottom: 2}}>خریدار تخمینی</div>
                    <b style={{color: '#34d399', fontSize: 15}}>{ch.convApprox > 0 ? fa(ch.convApprox) : '—'}</b>
                  </div>
                  <span className={`ceo-tag ceo-tag-${ch.status}`}>
                    {ch.status === 'g' ? 'سودده' : ch.status === 'y' ? 'متوسط' : 'سایر'}
                  </span>
                </div>
              </div>
              {/* volume bar */}
              <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#8b95a7', marginBottom: 4}}>
                <span>حجم لید</span>
                <b style={{color: ch.color}}>{fpc(ch.leads / chMax * 100)}</b>
              </div>
              {pbar(ch.leads / chMax * 100, ch.color)}
            </div>
          ))}
        </div>

        {/* Insight */}
        <div className="ceo-insight">
          <span style={{color: '#818cf8', fontSize: 15}}>✦</span>
          <div>
            <b style={{color: '#fff'}}>تحلیل رسانه‌ها و بات‌ها:</b>
            {' '}
            {bestCh
              ? `قوی‌ترین کانال: ${bestCh.name} با ${fa(bestCh.leads)} لید (${totalLeads > 0 ? fpc(bestCh.leads/totalLeads*100) : '—'} سهم).`
              : 'داده کانالی ثبت نشده.'}
            {' '}نرخ تبدیل کل <b style={{color: convRate >= 20 ? '#34d399' : '#fbbf24'}}>{fpc(convRate)}</b>.
            {slaOverdue > 0 && <> <b style={{color: '#f87171'}}>{fa(slaOverdue)} لید SLA منقضی</b> — اقدام فوری.</>}
          </div>
        </div>
      </div>
    );
  };

  // ─── TAB: Sales Team ──────────────────────────────────────
  const TabTeam = () => {
    const activeSellers = selMerged.filter(s => s.is_active);
    const totalSellerRev = selMerged.reduce((a,s) => a + (s.totalRevenue||0), 0);
    const totalSrOverdue = selMerged.reduce((a,s) => a + (s.overdue_leads||0), 0);
    const srMax = Math.max(...activeSellers.map(s => s.conversionRate||0), 1);

    return (
      <div>
        <div style={{fontSize: 20, fontWeight: 800, marginBottom: 4}}>تیم فروش</div>
        <div style={{fontSize: 12, color: '#8b95a7', marginBottom: 16}}>عملکرد هر فروشنده · نرخ تبدیل · SLA</div>

        <div className="ceo-grid4" style={{marginBottom: 14}}>
          <KpiCard label="فروشنده فعال" val={fa(activeSellers.length)} sub={`از ${fa(selMerged.length)} کل`} />
          <KpiCard label="درآمد کل تیم" val={fmon(totalSellerRev)} sub="مجموع فروش" valColor="#34d399" />
          <KpiCard label="SLA منقضی" val={fa(totalSrOverdue)} sub="لید تأخیری" valColor={totalSrOverdue > 0 ? '#fb9d9d' : '#34d399'} subColor={totalSrOverdue > 0 ? '#f87171' : '#5ee9b5'} />
          <KpiCard label="خریداران کل" val={fa(sr.totalBuyers||0)} sub={`تبدیل ${fpc(convRate)}`} valColor="#c7cdfa" />
        </div>

        <div className="ceo-card" style={{marginBottom: 14}}>
          <div className="ceo-section-title">فروشندگان</div>
          {activeSellers.length === 0 ? (
            <div style={{color: '#8b95a7', fontSize: 13, padding: '12px 0'}}>هیچ فروشنده فعالی ثبت نشده</div>
          ) : activeSellers.map((s, i) => {
            const diag = selDiag(s);
            const col = diag.cls === 'g' ? '#34d399' : diag.cls === 'y' ? '#fbbf24' : diag.cls === 'r' ? '#f87171' : '#818cf8';
            return (
              <div key={i} className="ceo-row" style={{borderRight: `3px solid ${col}`, paddingRight: 12}}>
                <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
                  <div className="ceo-av" style={{background: col + '33', color: col}}>{s.name?.[0] || '؟'}</div>
                  <div>
                    <div style={{fontWeight: 700}}>{s.name}</div>
                    <div style={{fontSize: 11, color: '#8b95a7'}}>
                      {fa(s.totalLeads||0)} لید · {fa(s.buyers||0)} خریدار · SLA: {fa(s.overdue_leads||0)}
                    </div>
                  </div>
                </div>
                <div style={{display: 'flex', alignItems: 'center', gap: 16}}>
                  <div style={{minWidth: 120}}>
                    <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#8b95a7', marginBottom: 3}}>
                      <span>تبدیل</span><b style={{color: col}}>{fpc(s.conversionRate)}</b>
                    </div>
                    {pbar(s.conversionRate/srMax*100, col)}
                    {s.score != null && (
                      <>
                        <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#8b95a7', marginTop: 5, marginBottom: 3}}>
                          <span>امتیاز</span><b style={{color: s.score >= 70 ? '#34d399' : s.score >= 40 ? '#fbbf24' : '#f87171'}}>{fa(s.score)}</b>
                        </div>
                        {pbar(s.score, s.score >= 70 ? '#34d399' : s.score >= 40 ? '#fbbf24' : '#f87171')}
                      </>
                    )}
                  </div>
                  <b style={{minWidth: 38, fontSize: 14, color: col}}>{fmon(s.totalRevenue)}</b>
                  <span className={`ceo-tag ceo-tag-${diag.cls}`}>{diag.lbl}</span>
                </div>
              </div>
            );
          })}
        </div>

        {/* Manager alerts */}
        {totalSrOverdue > 0 && (
          <div className="ceo-card">
            <div className="ceo-section-title" style={{color: '#fb9d9d'}}>⚠ هشدار مدیر فروش</div>
            <div className="ceo-insight ceo-insight-r" style={{marginTop: 0}}>
              <span style={{color: '#f87171', fontSize: 14}}>⚠</span>
              <div>
                <b style={{color: '#fff'}}>{fa(totalSrOverdue)} لید SLA منقضی</b> در تیم فروش وجود دارد.
                {selMerged.filter(s => s.overdue_leads > 0).map(s => (
                  <span key={s.id}> {s.name}: <b>{fa(s.overdue_leads)}</b> لید.</span>
                ))}
              </div>
            </div>
          </div>
        )}

        {ceoSellers.length > 0 && (
          <div className="ceo-insight">
            <span style={{color: '#818cf8', fontSize: 15}}>✦</span>
            <div>
              <b style={{color: '#fff'}}>تحلیل تیم:</b>
              {(() => {
                const best = [...ceoSellers].sort((a,b) => (b.conversionRate||0)-(a.conversionRate||0))[0];
                const worst = [...ceoSellers].filter(s=>s.is_active && (s.totalLeads||0)>5).sort((a,b) => (a.conversionRate||0)-(b.conversionRate||0))[0];
                return <> بهترین عملکرد: <b style={{color:'#34d399'}}>{best?.name} ({fpc(best?.conversionRate)})</b>.
                  {worst && worst.id !== best?.id && <> ضعیف‌ترین: <b style={{color:'#f87171'}}>{worst.name} ({fpc(worst.conversionRate)})</b>.</>}
                </>;
              })()}
            </div>
          </div>
        )}
      </div>
    );
  };

  // ─── RENDER ───────────────────────────────────────────────
  const tabs = [
    { id: 'command',      label: '🏠 مرکز فرماندهی' },
    { id: 'campaigns',    label: '📋 کمپین و اسکریپت' },
    { id: 'followup',     label: '🔁 فالوآپ' },
    { id: 'distribution', label: '⚡ توزیع' },
    { id: 'media',        label: '📡 رسانه‌ها و بات‌ها' },
    { id: 'team',         label: '👥 تیم فروش' },
  ];

  return (
    <div className="ceo-page">
      <nav className="ceo-nav">
        {tabs.map(t => (
          <button key={t.id} className={`ceo-nav-btn${ceoTab === t.id ? ' active' : ''}`} onClick={() => setCeoTab(t.id)}>
            {t.label}
          </button>
        ))}
      </nav>

      <div className={`ceo-tab${ceoTab === 'command'      ? ' active' : ''}`}><TabCommand /></div>
      <div className={`ceo-tab${ceoTab === 'campaigns'    ? ' active' : ''}`}><TabCampaigns /></div>
      <div className={`ceo-tab${ceoTab === 'followup'     ? ' active' : ''}`}><TabFollowup /></div>
      <div className={`ceo-tab${ceoTab === 'distribution' ? ' active' : ''}`}><TabDistribution /></div>
      <div className={`ceo-tab${ceoTab === 'media'        ? ' active' : ''}`}><TabMedia /></div>
      <div className={`ceo-tab${ceoTab === 'team'         ? ' active' : ''}`}><TabTeam /></div>
    </div>
  );
};
