/* SalesDoc — Distributsiya zanjiri dashboardi
   Dizayn: asosiy dashboard bilan bir xil (dx-card, dx-kpi, dx-head, dx-g2, dash-anim) */

/* ─── Lokal yordamchi komponentlar (dashboard.jsx dan olingan pattern) ─── */

function SDCountUp({ value, duration, fmt }) {
  const [n, setN] = React.useState(0);
  const st = React.useRef({ raf: 0, from: 0 });
  React.useEffect(function () {
    var from = st.current.from;
    var t0 = performance.now();
    function tick(t) {
      var p = Math.min(1, (t - t0) / (duration || 950));
      var e = 1 - Math.pow(1 - p, 3);
      setN(from + (value - from) * e);
      if (p < 1) st.current.raf = requestAnimationFrame(tick);
      else st.current.from = value;
    }
    cancelAnimationFrame(st.current.raf);
    st.current.raf = requestAnimationFrame(tick);
    return function () { cancelAnimationFrame(st.current.raf); };
  }, [value, duration]);
  return React.createElement(React.Fragment, null, fmt ? fmt(n) : Math.round(n));
}

var DONUT_PALETTE = ['#EC7A55', '#2B2927', '#3DBE9C', '#E9B949', '#5A9FD4', '#8E74FF', '#D9708F', '#7FC8B5', '#C9A27E', '#9BBF5A', '#6E8FB8', '#B9A2FF'];

function SDDonutChart({ rows, empty, palette }) {
  var [hi, setHi] = React.useState(-1);
  var data = (rows || []).filter(function (r) { return (r.sum || 0) > 0; });
  if (!data.length) return <div className="dx-empty">{empty || "Ma'lumot yo'q"}</div>;
  var total = data.reduce(function (s, r) { return s + r.sum; }, 0);
  var pal = palette || DONUT_PALETTE;
  var R = 70, SW = 22, C = 2 * Math.PI * R, GAP = data.length > 1 ? 2.5 : 0;
  var acc = 0;
  var segs = data.map(function (r, i) {
    var len = r.sum / total * C;
    var s = { i: i, name: r.name, sum: r.sum, meta: r.meta, color: r.color || pal[i % pal.length], frac: r.sum / total, len: len, offset: acc };
    acc += len; return s;
  });
  var act = hi >= 0 && hi < segs.length ? segs[hi] : null;
  var dim = function (i) { return hi === -1 || hi === i ? 1 : 0.28; };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 22, flexWrap: 'wrap' }}>
      <div style={{ position: 'relative', width: 180, height: 180, flex: 'none', margin: '0 auto' }}>
        <svg width="180" height="180" viewBox="0 0 180 180" style={{ transform: 'rotate(-90deg)' }}>
          <circle cx="90" cy="90" r={R} fill="none" stroke="var(--bg-2)" strokeWidth={SW} />
          {segs.map(function (s) {
            var dash = Math.max(0.5, s.len - GAP);
            return <circle key={s.i} cx="90" cy="90" r={R} fill="none" stroke={s.color}
              strokeWidth={hi === s.i ? SW + 6 : SW}
              strokeDasharray={dash + ' ' + (C - dash)} strokeDashoffset={-s.offset}
              onMouseEnter={function () { setHi(s.i); }} onMouseLeave={function () { setHi(-1); }}
              style={{ cursor: 'default', opacity: dim(s.i), transition: 'opacity .2s, stroke-width .2s' }} />;
          })}
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', textAlign: 'center', pointerEvents: 'none', padding: 30 }}>
          <div>
            <div className="tnum" style={{ fontSize: 18, fontWeight: 800, letterSpacing: '-.02em', lineHeight: 1.05, color: act ? act.color : 'var(--ink)' }}>{sdFmt(act ? act.sum : total)}</div>
            <div style={{ fontSize: 10.5, color: 'var(--ink-4)', fontWeight: 700, marginTop: 2, maxWidth: 116, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{act ? act.name : 'Jami'}</div>
            {act && <div className="tnum" style={{ fontSize: 11.5, fontWeight: 800, color: act.color, marginTop: 1 }}>{(act.frac * 100).toFixed(1)}%</div>}
          </div>
        </div>
      </div>
      <div style={{ flex: 1, minWidth: 170, display: 'grid', gap: 3 }}>
        {segs.map(function (s) {
          return (
            <div key={s.i} onMouseEnter={function () { setHi(s.i); }} onMouseLeave={function () { setHi(-1); }}
              title={s.name + ': ' + sdFmt(s.sum)}
              style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '5px 8px', borderRadius: 8, cursor: 'default', background: hi === s.i ? 'var(--bg-2)' : 'transparent', opacity: dim(s.i), transition: 'all .15s' }}>
              <span style={{ width: 11, height: 11, borderRadius: 4, background: s.color, flex: 'none', transition: 'box-shadow .15s', boxShadow: hi === s.i ? '0 0 0 3px color-mix(in srgb, ' + s.color + ' 32%, transparent)' : 'none' }} />
              <span style={{ fontSize: 12.5, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0 }}>{s.name}</span>
              <div style={{ flex: 1 }} />
              {s.meta && <span style={{ fontSize: 10.5, color: 'var(--ink-4)', fontWeight: 600, flex: 'none' }}>{s.meta}</span>}
              <span className="tnum" style={{ fontSize: 12, fontWeight: 700, flex: 'none' }}>{sdFmt(s.sum)}</span>
              <span className="tnum" style={{ fontSize: 11, color: 'var(--ink-4)', width: 40, textAlign: 'right', flex: 'none' }}>{(s.frac * 100).toFixed(1)}%</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function SDStatBarList({ rows, max, accent }) {
  if (!rows || !rows.length) return <div className="dx-empty">Ma'lumot yo'q</div>;
  var ac = accent || 'var(--brand)';
  return (
    <div style={{ display: 'grid', gap: 6 }}>
      {rows.map(function (r, i) {
        return (
          <div key={r.key != null ? r.key : i} className="dx-bar" title={r.name + ': ' + sdFmt(r.sum)}>
            <div className="dx-bar__top">
              <span className="dx-bar__rank" style={i < 3 ? { background: 'color-mix(in srgb, ' + ac + ' 15%, transparent)', color: ac } : undefined}>{i + 1}</span>
              <span className="dx-bar__name">{r.name}</span>
              <div style={{ flex: 1 }} />
              {r.meta && <span className="dx-bar__meta">{r.meta}</span>}
              <span className="dx-bar__val tnum">{sdFmt(r.sum)}</span>
            </div>
            <div className="dx-bar__track" style={{ marginLeft: 31 }}>
              <div className="dx-bar__fill" style={{ width: (r.sum / (max || 1) * 100) + '%', background: 'linear-gradient(90deg, ' + ac + ', color-mix(in srgb, ' + ac + ' 50%, transparent))' }} />
            </div>
          </div>
        );
      })}
    </div>
  );
}

function SDSectionHead({ icon, title, sub, tint, ink, right }) {
  return (
    <div className="dx-head">
      <span className="dx-head__ic" style={{ background: tint || 'var(--brand-tint)', color: ink || 'var(--brand-700)' }}><Icon name={icon} size={19} /></span>
      <div className="dx-head__tx">
        <div className="dx-head__t">{title}</div>
        {sub && <div className="dx-head__s">{sub}</div>}
      </div>
      {right && <div style={{ marginLeft: 'auto' }}>{right}</div>}
    </div>
  );
}

function PctBadge({ val, good, warn }) {
  var c = val >= good ? '#1D8A6E' : val >= warn ? '#A6651E' : '#C2453A';
  var bg = val >= good ? 'rgba(61,190,156,.14)' : val >= warn ? 'rgba(227,162,59,.16)' : 'rgba(232,115,95,.14)';
  return <span className="tnum" style={{ background: bg, color: c, padding: '2px 8px', borderRadius: 999, fontWeight: 800, fontSize: 11, whiteSpace: 'nowrap' }}>{val}%</span>;
}

function SDTrendChart({ trend }) {
  var [hi, setHi] = React.useState(-1);
  if (!trend || !trend.length) return <div className="dx-empty">Trend ma'lumoti yo'q</div>;
  var W = 560, H = 160, pad = 10;
  var maxV = Math.max(1, Math.max.apply(null, trend.map(function (d) { return Math.max(d.planned || 0, d.actual || 0); })));
  var stepX = (W - pad * 2) / Math.max(1, trend.length - 1);
  function py(v) { return H - pad - (v / maxV) * (H - pad * 2 - 12); }
  var ptsA = trend.map(function (d, i) { return [pad + i * stepX, py(d.actual || 0)]; });
  var ptsP = trend.map(function (d, i) { return [pad + i * stepX, py(d.planned || 0)]; });
  function polyline(pts) { return pts.map(function (p, i) { return (i ? 'L' : 'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1); }).join(' '); }
  var lineA = polyline(ptsA);
  var lineP = polyline(ptsP);
  var areaA = lineA + (' L' + (pad + (trend.length - 1) * stepX) + ' ' + (H - pad) + ' L' + pad + ' ' + (H - pad) + ' Z');
  var onMove = function (e) {
    var r = e.currentTarget.getBoundingClientRect();
    var rx = (e.clientX - r.left) / r.width * W;
    setHi(Math.max(0, Math.min(trend.length - 1, Math.round((rx - pad) / stepX))));
  };
  var hp = hi >= 0 ? ptsA[hi] : null;
  var hd = hi >= 0 ? trend[hi] : null;
  return (
    <div style={{ position: 'relative' }} onMouseMove={onMove} onMouseLeave={function () { setHi(-1); }}>
      <svg viewBox={'0 0 ' + W + ' ' + H} width="100%" style={{ display: 'block' }} preserveAspectRatio="none">
        <defs>
          <linearGradient id="sdtg" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#EC7A55" stopOpacity=".18" />
            <stop offset="100%" stopColor="#EC7A55" stopOpacity="0" />
          </linearGradient>
        </defs>
        {[0.25, 0.5, 0.75].map(function (g, i) { return <line key={i} x1={pad} x2={W - pad} y1={pad + g * (H - pad * 2)} y2={pad + g * (H - pad * 2)} stroke="var(--border)" strokeDasharray="3 4" />; })}
        <path d={areaA} fill="url(#sdtg)" />
        <path d={lineP} fill="none" stroke="var(--border)" strokeWidth="1.5" strokeDasharray="4 3" strokeLinejoin="round" />
        <path d={lineA} fill="none" stroke="#EC7A55" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
        {hp && <line x1={hp[0]} x2={hp[0]} y1={pad} y2={H - pad} stroke="var(--brand)" strokeWidth="1.5" strokeDasharray="3 4" opacity=".5" />}
        {ptsA.map(function (p, i) { return <circle key={i} cx={p[0]} cy={p[1]} r={i === hi ? 6 : 3.5} fill={i === hi ? '#EC7A55' : '#fff'} stroke="#EC7A55" strokeWidth="2.2" style={{ transition: 'r .12s, fill .12s' }} />; })}
        {trend.map(function (d, i) { return <text key={i} x={pad + i * stepX} y={H - 1} fontSize="10" fill={i === hi ? 'var(--brand)' : 'var(--ink-4)'} textAnchor="middle" fontWeight={i === hi ? 800 : 600} fontFamily="Manrope">{(d.date || '').slice(5)}</text>; })}
      </svg>
      {hp && hd && (
        <div className="chart-tip" style={{ left: (hp[0] / W * 100) + '%', top: (py(hd.actual || 0) / H * 100) + '%', opacity: 1 }}>
          {hd.date} · Rej:{hd.planned || 0} Bo'lgan:{hd.actual || 0} GPS:{hd.gps || 0}
        </div>
      )}
    </div>
  );
}

function sdFmt(v) { var n = Number(v) || 0, a = Math.abs(n); if (a >= 1e9) return (n / 1e9).toFixed(1) + ' mlrd'; if (a >= 1e6) return (n / 1e6).toFixed(1) + ' mln'; if (a >= 1e3) return Math.round(n / 1e3) + ' ming'; return String(Math.round(n)); }
function pct(a, b) { return b ? Math.round(a / b * 100) : 0; }
function todayStr() { return new Date().toISOString().slice(0, 10); }
function monthStartStr() { var d = new Date(); d.setDate(1); return d.toISOString().slice(0, 10); }

/* ══════════════════════════════════════════════════════════════
   ASOSIY KOMPONENT
   ══════════════════════════════════════════════════════════════ */
function SalesDocDashboard() {
  var [from, setFrom] = React.useState(monthStartStr);
  var [to, setTo] = React.useState(todayStr);
  // Sahifa keshi — bo'limga qayta kirilganda oldingi ma'lumot darrov ko'rsatiladi.
  var sdCached = window.PageCache ? window.PageCache.get('salesdoc:' + monthStartStr + ':' + todayStr) : null;
  var [loading, setLoading] = React.useState(false);
  var [error, setError] = React.useState(null);
  var [data, setData] = React.useState(sdCached || null);
  var [tab, setTab] = React.useState('visits');

  function load() {
    setLoading(true); setError(null);
    API.sdDashboard(from, to)
      .then(function (dash) {
        var next = {
          orders: dash.orders || [],
          visits: dash.visits || [],
          payments: dash.payments || [],
          balances: dash.balances || [],
          returns: dash.returns || [],
          summary: dash.summary || {},
          agentStats: dash.agentStats || [],
          visitTrend: dash.visitTrend || [],
          clientsByFilial: dash.clientsByFilial || {},
        };
        setData(next);
        if (window.PageCache) window.PageCache.set('salesdoc:' + from + ':' + to, next);
      })
      .catch(function (e) { setError(e.message || 'Xatolik'); })
      .finally(function () { setLoading(false); });
  }
  React.useEffect(function () { load(); }, []);

  var filials = React.useMemo(function () {
    if (!data) return [];
    var map = {};
    function ensure(f) {
      if (!f || !f.id) return;
      if (!map[f.id]) map[f.id] = { id: f.id, name: f.name || f.id, planned: 0, actual: 0, gps: 0, withOrder: 0, orders: 0, sales: 0, payments: 0, returns: 0, returnSum: 0, clients: 0 };
    }
    (data.visits || []).forEach(function (v) { var f = v._filial; ensure(f); if (!f || !map[f.id]) return; if (v.planned) map[f.id].planned++; if (v.visited) map[f.id].actual++; if (v.gps_visit) map[f.id].gps++; if (v.has_order) map[f.id].withOrder++; });
    (data.orders || []).forEach(function (o) { var f = o._filial; ensure(f); if (!f || !map[f.id]) return; map[f.id].orders++; map[f.id].sales += (o.totalSummaAfterDiscount || 0); });
    (data.payments || []).forEach(function (p) { var f = p._filial; ensure(f); if (!f || !map[f.id]) return; map[f.id].payments += (p.amount || 0); });
    (data.returns || []).forEach(function (r) { var f = r._filial; ensure(f); if (!f || !map[f.id]) return; map[f.id].returns++; map[f.id].returnSum += (r.totalSummaAfterDiscount || r.totalSumma || 0); });
    var cbf = data.clientsByFilial || {};
    Object.keys(map).forEach(function (id) { map[id].clients = cbf[id] || 0; });
    return Object.values(map).map(function (f) {
      return Object.assign({}, f, { visitRate: pct(f.actual, f.planned), gpsRate: pct(f.gps, f.actual), orderRate: pct(f.withOrder, f.actual) });
    }).sort(function (a, b) { return b.actual - a.actual; });
  }, [data]);

  var debtors = React.useMemo(function () {
    if (!data) return [];
    return (data.balances || []).filter(function (b) { return (b.balance || 0) < 0; }).sort(function (a, b) { return (a.balance || 0) - (b.balance || 0); });
  }, [data]);

  var s = (data && data.summary) || {};
  var agents = (data && data.agentStats) || [];
  var trend = (data && data.visitTrend) || [];
  var orders = (data && data.orders) || [];
  var payments = (data && data.payments) || [];
  var balances = (data && data.balances) || [];
  var returns_ = (data && data.returns) || [];

  var visitRate = s.plannedVisits ? pct(s.actualVisits, s.plannedVisits) : 0;
  var gpsRate = s.actualVisits ? pct(s.gpsVisits, s.actualVisits) : 0;
  var orderRate = s.actualVisits ? pct(s.visitsWithOrder, s.actualVisits) : 0;
  var totalDebt = debtors.reduce(function (a, b) { return a + Math.abs(b.balance || 0); }, 0);

  var filialSalesRows = filials.filter(function (f) { return f.sales > 0; }).map(function (f, i) { return { i: i, name: f.name, sum: f.sales }; });
  var filialVisitRows = filials.filter(function (f) { return f.actual > 0; }).map(function (f, i) { return { i: i, name: f.name, sum: f.actual }; });

  var topSalesRows = filials.filter(function (f) { return f.sales > 0; }).slice(0, 8).map(function (f) { return { key: f.id, name: f.name, sum: f.sales, meta: f.orders + ' buyurtma' }; });
  var topPayRows = filials.filter(function (f) { return f.payments > 0; }).slice(0, 8).map(function (f) { return { key: f.id, name: f.name, sum: f.payments }; });
  var maxSales = Math.max(1, Math.max.apply(null, topSalesRows.map(function (r) { return r.sum; }).concat([1])));
  var maxPay = Math.max(1, Math.max.apply(null, topPayRows.map(function (r) { return r.sum; }).concat([1])));

  var agentStatRows = agents.slice(0, 8).map(function (a) {
    return { key: a.id, name: a.name, sum: a.actual, meta: pct(a.actual, a.planned) + '% · ' + (a.planned || 0) + ' rej' };
  });
  var maxAgent = Math.max(1, Math.max.apply(null, agentStatRows.map(function (r) { return r.sum; }).concat([1])));

  var TABS = [
    { key: 'visits', label: 'Tashriflar' },
    { key: 'orders', label: 'Buyurtmalar' },
    { key: 'payments', label: "To'lovlar" },
    { key: 'returns', label: 'Qaytarishlar' },
    { key: 'balances', label: 'Qarz' },
    { key: 'agents', label: 'Agentlar' },
    { key: 'trend', label: 'Trend' },
  ];

  return (
    <div className="dash-wrap" style={{ padding: '8px 28px 32px', overflowY: 'auto', height: '100%' }}>

      {/* ── Toolbar ── */}
      <div className="dx-toolbar dash-anim" style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 34, height: 34, borderRadius: 9, background: 'rgba(142,116,255,.12)', color: '#5B45D6', display: 'grid', placeItems: 'center', flex: 'none' }}>
            <Icon name="pin" size={17} />
          </span>
          <div>
            <div style={{ fontWeight: 800, fontSize: 14.5, lineHeight: 1.1 }}>Distributsiya zanjiri</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 1 }}>SalesDoc · {filials.length} filial · {agents.length} agent</div>
          </div>
        </div>
        <div className="dx-toolbar__sp" />
        <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
          <input type="date" value={from} onChange={function (e) { setFrom(e.target.value); }}
            style={{ fontSize: 12, padding: '5px 8px', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', background: 'var(--surface)', color: 'var(--ink)', height: 32 }} />
          <span style={{ color: 'var(--ink-4)', fontSize: 12 }}>—</span>
          <input type="date" value={to} onChange={function (e) { setTo(e.target.value); }}
            style={{ fontSize: 12, padding: '5px 8px', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', background: 'var(--surface)', color: 'var(--ink)', height: 32 }} />
          <button className="btn btn--primary" onClick={load} disabled={loading} style={{ height: 32, padding: '0 16px', fontSize: 12 }}>
            {loading ? '…' : 'Yangilash'}
          </button>
        </div>
      </div>

      {error && (
        <div style={{ background: 'rgba(232,115,95,.1)', border: '1px solid rgba(232,115,95,.3)', borderRadius: 10, padding: '10px 14px', color: '#C2453A', fontSize: 12.5, marginBottom: 14, display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon name="info" size={16} /> {error}
        </div>
      )}

      {loading && !data && (
        <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-4)', fontSize: 13 }}>Yuklanmoqda…</div>
      )}

      {data && (
        <div>
          {/* ══════════ KPI BAND ══════════ */}
          <div className="dx-card dx-card--pad dash-anim" style={{ marginBottom: 16, animationDelay: '.04s' }}>
            <SDSectionHead icon="trendUp" title="Asosiy ko'rsatkichlar"
              sub={'Davr: ' + from + ' — ' + to}
              tint="rgba(142,116,255,.12)" ink="#5B45D6" />
            <div className="dx-g3" style={{ marginTop: 14 }}>
              <div className="dx-kpi" style={{ '--_a': 'var(--brand)' }}>
                <div className="dx-kpi__l"><span className="dx-kpi__ic" style={{ background: 'var(--brand-tint)', color: 'var(--brand-700)' }}><Icon name="chart" size={15} /></span>Rejalangan tashrif</div>
                <div className="dx-kpi__v tnum"><SDCountUp value={s.plannedVisits || 0} /></div>
              </div>
              <div className="dx-kpi" style={{ '--_a': visitRate >= 90 ? '#3DBE9C' : visitRate >= 70 ? '#D08A2A' : '#E8735F' }}>
                <div className="dx-kpi__l"><span className="dx-kpi__ic" style={{ background: visitRate >= 90 ? '#D9F0E8' : visitRate >= 70 ? '#F6E7CF' : '#F6DCD6', color: visitRate >= 90 ? '#1D8A6E' : visitRate >= 70 ? '#A6651E' : '#C2453A' }}><Icon name="check" size={15} /></span>Bo'lgan tashrif</div>
                <div className="dx-kpi__v tnum" style={{ color: visitRate >= 90 ? '#3DBE9C' : visitRate >= 70 ? '#D08A2A' : '#E8735F' }}><SDCountUp value={s.actualVisits || 0} /></div>
                <div className="dx-kpi__s">{visitRate}% bajarildi</div>
              </div>
              <div className="dx-kpi" style={{ '--_a': '#3F7FB8' }}>
                <div className="dx-kpi__l"><span className="dx-kpi__ic" style={{ background: '#E6EFF7', color: '#1D4ED8' }}><Icon name="pin" size={15} /></span>GPS tasdiqlangan</div>
                <div className="dx-kpi__v tnum" style={{ color: '#3F7FB8' }}><SDCountUp value={s.gpsVisits || 0} /></div>
                <div className="dx-kpi__s">{gpsRate}%</div>
              </div>
              <div className="dx-kpi" style={{ '--_a': '#7A5CF0' }}>
                <div className="dx-kpi__l"><span className="dx-kpi__ic" style={{ background: '#E7E1FB', color: '#5B45D6' }}><Icon name="box" size={15} /></span>Buyurtmali tashrif</div>
                <div className="dx-kpi__v tnum" style={{ color: '#7A5CF0' }}><SDCountUp value={s.visitsWithOrder || 0} /></div>
                <div className="dx-kpi__s">{orderRate}%</div>
              </div>
              <div className="dx-kpi" style={{ '--_a': 'var(--brand)' }}>
                <div className="dx-kpi__l"><span className="dx-kpi__ic" style={{ background: 'var(--brand-tint)', color: 'var(--brand-700)' }}><Icon name="layers" size={15} /></span>Buyurtmalar</div>
                <div className="dx-kpi__v tnum"><SDCountUp value={orders.length} /></div>
              </div>
              <div className="dx-kpi" style={{ '--_a': '#5A9FD4' }}>
                <div className="dx-kpi__l"><span className="dx-kpi__ic" style={{ background: '#DCE9F4', color: '#2F6F9E' }}><Icon name="users" size={15} /></span>Faol mijozlar</div>
                <div className="dx-kpi__v tnum" style={{ color: '#2F6F9E' }}><SDCountUp value={s.activeClientsCount || 0} /></div>
              </div>
              <div className="dx-kpi" style={{ '--_a': '#3DBE9C' }}>
                <div className="dx-kpi__l"><span className="dx-kpi__ic" style={{ background: '#D9F0E8', color: '#1D8A6E' }}><Icon name="coin" size={15} /></span>Jami sotuv</div>
                <div className="dx-kpi__v tnum" style={{ color: '#3DBE9C' }}><SDCountUp value={s.totalSales || 0} fmt={sdFmt} /></div>
              </div>
              <div className="dx-kpi" style={{ '--_a': '#5A9FD4' }}>
                <div className="dx-kpi__l"><span className="dx-kpi__ic" style={{ background: '#DCE9F4', color: '#2F6F9E' }}><Icon name="coin" size={15} /></span>To'lovlar</div>
                <div className="dx-kpi__v tnum" style={{ color: '#2F6F9E' }}><SDCountUp value={s.totalPayments || 0} fmt={sdFmt} /></div>
              </div>
              <div className="dx-kpi" style={{ '--_a': returns_.length ? '#E8735F' : 'var(--ink-4)' }}>
                <div className="dx-kpi__l"><span className="dx-kpi__ic" style={{ background: returns_.length ? '#F6DCD6' : 'var(--bg-2)', color: returns_.length ? '#C2453A' : 'var(--ink-4)' }}><Icon name="info" size={15} /></span>Qaytarishlar</div>
                <div className="dx-kpi__v tnum" style={{ color: returns_.length ? '#E8735F' : 'var(--ink-4)' }}><SDCountUp value={returns_.length} /></div>
                <div className="dx-kpi__s">{sdFmt(s.totalReturns || 0)} summa</div>
              </div>
              <div className="dx-kpi" style={{ '--_a': debtors.length > 20 ? '#E8735F' : '#D08A2A' }}>
                <div className="dx-kpi__l"><span className="dx-kpi__ic" style={{ background: debtors.length > 20 ? '#F6DCD6' : '#F6E7CF', color: debtors.length > 20 ? '#C2453A' : '#A6651E' }}><Icon name="clock" size={15} /></span>Qarzdor mijozlar</div>
                <div className="dx-kpi__v tnum" style={{ color: debtors.length > 20 ? '#E8735F' : '#D08A2A' }}><SDCountUp value={debtors.length} /></div>
                <div className="dx-kpi__s">{sdFmt(totalDebt)} jami qarz</div>
              </div>
            </div>
          </div>

          {/* ══════════ TAB NAVIGATSIYA ══════════ */}
          <div className="dx-seg dash-anim" style={{ marginBottom: 14, animationDelay: '.08s' }}>
            {TABS.map(function (t) {
              var badge = '';
              if (data) {
                if (t.key === 'orders') badge = orders.length;
                else if (t.key === 'payments') badge = payments.length;
                else if (t.key === 'returns') badge = returns_.length;
                else if (t.key === 'balances') badge = debtors.length;
                else if (t.key === 'agents') badge = agents.length;
              }
              return (
                <button key={t.key} className={tab === t.key ? 'on' : ''} onClick={function () { setTab(t.key); }}>
                  {t.label}{badge ? ' · ' + badge : ''}
                </button>
              );
            })}
          </div>

          {/* ══════════ TASHRIFLAR ══════════ */}
          {tab === 'visits' && (
            <div>
              <div className="dx-g2" style={{ marginBottom: 16 }}>
                <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.10s' }}>
                  <SDSectionHead icon="chart" title="Tashrif sifati" sub="Bajarilish foizlari bo'yicha tahlil" tint="rgba(142,116,255,.12)" ink="#5B45D6" />
                  <div style={{ marginTop: 14, display: 'grid', gap: 10 }}>
                    {[
                      { label: 'Tashrif bajarish', val: visitRate, act: s.actualVisits, plan: s.plannedVisits, good: 90, warn: 70 },
                      { label: 'GPS tasdiqlash', val: gpsRate, act: s.gpsVisits, plan: s.actualVisits, good: 95, warn: 80 },
                      { label: 'Buyurtmali tashriflar', val: orderRate, act: s.visitsWithOrder, plan: s.actualVisits, good: 60, warn: 40 },
                    ].map(function (k) {
                      var c = k.val >= k.good ? '#3DBE9C' : k.val >= k.warn ? '#D08A2A' : '#E8735F';
                      return (
                        <div key={k.label}>
                          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5, alignItems: 'center' }}>
                            <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)' }}>{k.label}</span>
                            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                              <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>{k.act}/{k.plan}</span>
                              <PctBadge val={k.val} good={k.good} warn={k.warn} />
                            </div>
                          </div>
                          <div style={{ height: 8, borderRadius: 99, background: 'var(--bg-2)', overflow: 'hidden' }}>
                            <div style={{ width: Math.min(k.val, 100) + '%', height: '100%', background: c, borderRadius: 99, transition: 'width .5s var(--ease)' }} />
                          </div>
                        </div>
                      );
                    })}
                  </div>
                  <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                    {[
                      { label: 'Rejalangan', val: s.plannedVisits || 0, color: 'var(--ink-3)' },
                      { label: "Bo'lgan", val: s.actualVisits || 0, color: '#3DBE9C' },
                      { label: 'GPS', val: s.gpsVisits || 0, color: '#3F7FB8' },
                      { label: 'Buyurtmali', val: s.visitsWithOrder || 0, color: '#7A5CF0' },
                    ].map(function (c) {
                      return (
                        <div key={c.label} style={{ background: 'var(--bg-2)', borderRadius: 'var(--r-md)', padding: '10px 12px' }}>
                          <div style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.04em', marginBottom: 3 }}>{c.label}</div>
                          <div className="tnum" style={{ fontSize: 22, fontWeight: 800, color: c.color }}><SDCountUp value={c.val} /></div>
                        </div>
                      );
                    })}
                  </div>
                </div>

                <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.14s' }}>
                  <SDSectionHead icon="pin" title={'Filiallar bo\'yicha tashrif · ' + filials.length + ' ta'} sub="Har filial nechta tashrif bo'ldi" tint="rgba(142,116,255,.12)" ink="#5B45D6" />
                  <div style={{ marginTop: 14 }}>
                    <SDDonutChart rows={filialVisitRows} empty="Tashrif ma'lumoti yo'q" />
                  </div>
                </div>
              </div>

              <div className="dx-card dx-card--pad dash-anim" style={{ marginBottom: 16, animationDelay: '.18s' }}>
                <SDSectionHead icon="grid" title="Filiallar tafsiloti" sub="Har filial bo'yicha barcha ko'rsatkichlar" tint="rgba(90,159,212,.12)" ink="#2F6F9E" />
                <div style={{ overflowX: 'auto', marginTop: 14 }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, minWidth: 560 }}>
                    <thead>
                      <tr style={{ color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                        {['Filial', 'Rej.', "Bo'lgan", 'Tashrif%', 'GPS%', 'Buyurtma%', 'Mijoz'].map(function (h) {
                          return <th key={h} style={{ padding: '6px 10px', textAlign: h === 'Filial' ? 'left' : 'right', fontWeight: 600, borderBottom: '2px solid var(--border)', whiteSpace: 'nowrap' }}>{h}</th>;
                        })}
                      </tr>
                    </thead>
                    <tbody>
                      {filials.map(function (f, i) {
                        return (
                          <tr key={f.id} style={{ borderBottom: '1px solid var(--border)', background: i % 2 ? 'rgba(0,0,0,.015)' : 'transparent' }}>
                            <td style={{ padding: '8px 10px', fontWeight: 700 }}>{f.name}</td>
                            <td className="tnum" style={{ padding: '8px 10px', textAlign: 'right', color: 'var(--ink-4)' }}>{f.planned}</td>
                            <td className="tnum" style={{ padding: '8px 10px', textAlign: 'right', fontWeight: 800 }}>{f.actual}</td>
                            <td style={{ padding: '8px 10px', textAlign: 'right' }}><PctBadge val={f.visitRate} good={90} warn={70} /></td>
                            <td style={{ padding: '8px 10px', textAlign: 'right' }}><PctBadge val={f.gpsRate} good={95} warn={80} /></td>
                            <td style={{ padding: '8px 10px', textAlign: 'right' }}><PctBadge val={f.orderRate} good={60} warn={40} /></td>
                            <td className="tnum" style={{ padding: '8px 10px', textAlign: 'right', color: 'var(--ink-4)' }}>{f.clients || '—'}</td>
                          </tr>
                        );
                      })}
                      {!filials.length && <tr><td colSpan={7} style={{ textAlign: 'center', padding: 28, color: 'var(--ink-4)' }}>Ma'lumot yo'q</td></tr>}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* ══════════ BUYURTMALAR ══════════ */}
          {tab === 'orders' && (
            <div>
              <div className="dx-g2" style={{ marginBottom: 16 }}>
                <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.10s' }}>
                  <SDSectionHead icon="coin" title="Top filiallar — sotuv summasi" sub={'Jami ' + orders.length + ' buyurtma · ' + sdFmt(s.totalSales || 0)} tint="#D9F0E8" ink="#1D8A6E" />
                  <div style={{ marginTop: 14 }}>
                    <SDStatBarList rows={topSalesRows} max={maxSales} accent="#3DBE9C" />
                  </div>
                </div>
                <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.14s' }}>
                  <SDSectionHead icon="chart" title="Filiallar bo'yicha sotuv ulushi" sub="Har filialning jami sotuvdagi ulushi" tint="rgba(61,190,156,.12)" ink="#1D8A6E" />
                  <div style={{ marginTop: 14 }}>
                    <SDDonutChart rows={filialSalesRows} empty="Sotuv ma'lumoti yo'q" />
                  </div>
                </div>
              </div>

              <div className="dx-card dx-card--pad dash-anim" style={{ marginBottom: 16, animationDelay: '.18s' }}>
                <SDSectionHead icon="layers" title={'Buyurtmalar ro\'yxati · ' + orders.length + ' ta'} sub="Status, sana, summa bo'yicha" tint="rgba(142,116,255,.12)" ink="#5B45D6" />
                <div style={{ overflowX: 'auto', marginTop: 14, maxHeight: 360, overflowY: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, minWidth: 480 }}>
                    <thead style={{ position: 'sticky', top: 0, background: 'var(--surface)' }}>
                      <tr style={{ color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                        {['Filial', 'Sana', 'Status', 'Summa'].map(function (h) { return <th key={h} style={{ padding: '6px 10px', textAlign: h === 'Summa' ? 'right' : 'left', fontWeight: 600, borderBottom: '2px solid var(--border)', whiteSpace: 'nowrap' }}>{h}</th>; })}
                      </tr>
                    </thead>
                    <tbody>
                      {orders.slice(0, 200).map(function (o, i) {
                        var st = o.status === 1 ? 'Yangi' : o.status === 2 ? 'Tasdiqlandi' : o.status === 3 ? 'Yetkazildi' : o.status === 4 ? 'Bekor' : ('' + o.status);
                        var sc = o.status === 3 ? '#3DBE9C' : o.status === 4 ? '#E8735F' : o.status === 2 ? '#3F7FB8' : '#D08A2A';
                        return (
                          <tr key={o.CS_id || i} style={{ borderBottom: '1px solid var(--border)', background: i % 2 ? 'rgba(0,0,0,.015)' : 'transparent' }}>
                            <td style={{ padding: '7px 10px', color: 'var(--ink-3)', fontSize: 11.5 }}>{(o._filial && o._filial.name) || '—'}</td>
                            <td className="tnum" style={{ padding: '7px 10px', color: 'var(--ink-4)', fontSize: 11.5 }}>{(o.dateCreate || '').slice(0, 10)}</td>
                            <td style={{ padding: '7px 10px' }}><span style={{ display: 'inline-block', background: sc + '1a', color: sc, padding: '2px 9px', borderRadius: 999, fontWeight: 700, fontSize: 11 }}>{st}</span></td>
                            <td className="tnum" style={{ padding: '7px 10px', textAlign: 'right', fontWeight: 800, color: '#3DBE9C' }}>{sdFmt(o.totalSummaAfterDiscount || 0)}</td>
                          </tr>
                        );
                      })}
                      {!orders.length && <tr><td colSpan={4} style={{ textAlign: 'center', padding: 28, color: 'var(--ink-4)' }}>Buyurtmalar yo'q</td></tr>}
                    </tbody>
                  </table>
                </div>
                {orders.length > 200 && <div style={{ textAlign: 'center', fontSize: 11.5, color: 'var(--ink-4)', marginTop: 8 }}>Jami {orders.length} ta (200 ta ko'rsatilmoqda)</div>}
              </div>
            </div>
          )}

          {/* ══════════ TO'LOVLAR ══════════ */}
          {tab === 'payments' && (
            <div>
              <div className="dx-g2" style={{ marginBottom: 16 }}>
                <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.10s' }}>
                  <SDSectionHead icon="coin" title="Top filiallar — to'lovlar" sub={'Jami ' + sdFmt(s.totalPayments || 0)} tint="#DCE9F4" ink="#2F6F9E" />
                  <div style={{ marginTop: 14 }}>
                    <SDStatBarList rows={topPayRows} max={maxPay} accent="#5A9FD4" />
                  </div>
                </div>
                <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.14s' }}>
                  <SDSectionHead icon="chart" title="To'lovlar ulushi" sub="Har filial to'lovlarining ulushi" tint="rgba(90,159,212,.12)" ink="#2F6F9E" />
                  <div style={{ marginTop: 14 }}>
                    <SDDonutChart rows={topPayRows.map(function (r, i) { return { i: i, name: r.name, sum: r.sum }; })} empty="To'lovlar yo'q" />
                  </div>
                </div>
              </div>

              <div className="dx-card dx-card--pad dash-anim" style={{ marginBottom: 16, animationDelay: '.18s' }}>
                <SDSectionHead icon="layers" title={'To\'lovlar ro\'yxati · ' + payments.length + ' ta · Jami: ' + sdFmt(s.totalPayments || 0)} tint="rgba(90,159,212,.12)" ink="#2F6F9E" />
                <div style={{ overflowX: 'auto', marginTop: 14, maxHeight: 400, overflowY: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, minWidth: 440 }}>
                    <thead style={{ position: 'sticky', top: 0, background: 'var(--surface)' }}>
                      <tr style={{ color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                        {['Filial', 'Sana', 'Mijoz', 'Summa'].map(function (h) { return <th key={h} style={{ padding: '6px 10px', textAlign: h === 'Summa' ? 'right' : 'left', fontWeight: 600, borderBottom: '2px solid var(--border)', whiteSpace: 'nowrap' }}>{h}</th>; })}
                      </tr>
                    </thead>
                    <tbody>
                      {payments.slice(0, 300).map(function (p, i) {
                        var cn = (p.client && (p.client.name || p.client.full_name)) || p.clientName || '—';
                        return (
                          <tr key={p.CS_id || i} style={{ borderBottom: '1px solid var(--border)', background: i % 2 ? 'rgba(0,0,0,.015)' : 'transparent' }}>
                            <td style={{ padding: '7px 10px', color: 'var(--ink-3)', fontSize: 11.5 }}>{(p._filial && p._filial.name) || '—'}</td>
                            <td className="tnum" style={{ padding: '7px 10px', color: 'var(--ink-4)', fontSize: 11.5 }}>{(p.paymentDate || '').slice(0, 10)}</td>
                            <td style={{ padding: '7px 10px', fontWeight: 600 }}>{cn}</td>
                            <td className="tnum" style={{ padding: '7px 10px', textAlign: 'right', fontWeight: 800, color: '#3DBE9C' }}>{sdFmt(p.amount || 0)}</td>
                          </tr>
                        );
                      })}
                      {!payments.length && <tr><td colSpan={4} style={{ textAlign: 'center', padding: 28, color: 'var(--ink-4)' }}>To'lovlar yo'q</td></tr>}
                    </tbody>
                  </table>
                </div>
                {payments.length > 300 && <div style={{ textAlign: 'center', fontSize: 11.5, color: 'var(--ink-4)', marginTop: 8 }}>Jami {payments.length} ta (300 ta ko'rsatilmoqda)</div>}
              </div>
            </div>
          )}

          {/* ══════════ QAYTARISHLAR ══════════ */}
          {tab === 'returns' && (
            <div>
              {returns_.length === 0 ? (
                <div className="dx-card dx-card--pad dash-anim" style={{ marginBottom: 16 }}>
                  <SDSectionHead icon="check" title="Qaytarishlar yo'q" sub={'Tanlangan davr uchun qaytarish topilmadi (' + from + ' — ' + to + ')'} tint="rgba(61,190,156,.12)" ink="#1D8A6E" />
                </div>
              ) : (
                <div className="dx-g2" style={{ marginBottom: 16 }}>
                  <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.10s' }}>
                    <SDSectionHead icon="info" title="Filiallar bo'yicha qaytarishlar" sub={'Jami ' + returns_.length + ' ta · ' + sdFmt(s.totalReturns || 0)} tint="rgba(232,115,95,.12)" ink="#C2453A" />
                    <div style={{ overflowX: 'auto', marginTop: 14 }}>
                      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
                        <thead><tr style={{ color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                          {['Filial', 'Soni', 'Summa'].map(function (h) { return <th key={h} style={{ padding: '6px 10px', textAlign: h === 'Filial' ? 'left' : 'right', fontWeight: 600, borderBottom: '2px solid var(--border)' }}>{h}</th>; })}
                        </tr></thead>
                        <tbody>
                          {filials.filter(function (f) { return f.returns > 0; }).map(function (f, i) {
                            return (
                              <tr key={f.id} style={{ borderBottom: '1px solid var(--border)', background: i % 2 ? 'rgba(0,0,0,.015)' : 'transparent' }}>
                                <td style={{ padding: '8px 10px', fontWeight: 700 }}>{f.name}</td>
                                <td className="tnum" style={{ padding: '8px 10px', textAlign: 'right', color: '#E8735F', fontWeight: 800 }}>{f.returns}</td>
                                <td className="tnum" style={{ padding: '8px 10px', textAlign: 'right', color: '#C2453A', fontWeight: 800 }}>{sdFmt(f.returnSum)}</td>
                              </tr>
                            );
                          })}
                        </tbody>
                        <tfoot>
                          <tr style={{ borderTop: '2px solid var(--border)' }}>
                            <td style={{ padding: '7px 10px', fontWeight: 800 }}>JAMI</td>
                            <td className="tnum" style={{ padding: '7px 10px', textAlign: 'right', color: '#E8735F', fontWeight: 800 }}>{returns_.length}</td>
                            <td className="tnum" style={{ padding: '7px 10px', textAlign: 'right', color: '#C2453A', fontWeight: 900, fontSize: 14 }}>{sdFmt(s.totalReturns || 0)}</td>
                          </tr>
                        </tfoot>
                      </table>
                    </div>
                  </div>
                  <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.14s' }}>
                    <SDSectionHead icon="layers" title="Qaytarishlar ro'yxati" sub="Sana va filial bo'yicha" tint="rgba(232,115,95,.12)" ink="#C2453A" />
                    <div style={{ overflowX: 'auto', marginTop: 14, maxHeight: 340, overflowY: 'auto' }}>
                      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                        <thead style={{ position: 'sticky', top: 0, background: 'var(--surface)' }}>
                          <tr style={{ color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                            {['Filial', 'Sana', 'Summa'].map(function (h) { return <th key={h} style={{ padding: '6px 10px', textAlign: h === 'Summa' ? 'right' : 'left', fontWeight: 600, borderBottom: '2px solid var(--border)' }}>{h}</th>; })}
                          </tr>
                        </thead>
                        <tbody>
                          {returns_.slice(0, 100).map(function (r, i) {
                            return (
                              <tr key={r.CS_id || i} style={{ borderBottom: '1px solid var(--border)', background: i % 2 ? 'rgba(0,0,0,.015)' : 'transparent' }}>
                                <td style={{ padding: '7px 10px', color: 'var(--ink-3)', fontSize: 11.5 }}>{(r._filial && r._filial.name) || '—'}</td>
                                <td className="tnum" style={{ padding: '7px 10px', color: 'var(--ink-4)', fontSize: 11.5 }}>{(r.dateCreate || r.date || '').slice(0, 10)}</td>
                                <td className="tnum" style={{ padding: '7px 10px', textAlign: 'right', fontWeight: 800, color: '#C2453A' }}>{sdFmt(r.totalSummaAfterDiscount || r.totalSumma || 0)}</td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* ══════════ QARZ / BALANS ══════════ */}
          {tab === 'balances' && (
            <div className="dx-g2" style={{ marginBottom: 16 }}>
              <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.10s' }}>
                <SDSectionHead icon="info" title={'Qarzdor mijozlar · ' + debtors.length + ' ta'} sub={'Jami qarz: ' + sdFmt(totalDebt)} tint="rgba(232,115,95,.12)" ink="#C2453A" />
                <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, marginBottom: 16 }}>
                  {[
                    { label: 'Qarzdor', val: debtors.length, color: '#E8735F', bg: '#F6DCD6' },
                    { label: 'Nol', val: balances.filter(function (b) { return !(b.balance || 0); }).length, color: 'var(--ink-4)', bg: 'var(--bg-2)' },
                    { label: 'Ijobiy', val: balances.filter(function (b) { return (b.balance || 0) > 0; }).length, color: '#3DBE9C', bg: '#D9F0E8' },
                  ].map(function (c) {
                    return (
                      <div key={c.label} style={{ background: c.bg, borderRadius: 'var(--r-md)', padding: '12px 10px', textAlign: 'center' }}>
                        <div className="tnum" style={{ fontSize: 26, fontWeight: 900, color: c.color }}>{c.val}</div>
                        <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 2 }}>{c.label}</div>
                      </div>
                    );
                  })}
                </div>
                <div style={{ overflowX: 'auto', maxHeight: 320, overflowY: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                    <thead style={{ position: 'sticky', top: 0, background: 'var(--surface)' }}>
                      <tr style={{ color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                        {['Mijoz', 'Qarz summasi'].map(function (h) { return <th key={h} style={{ padding: '6px 10px', textAlign: h === 'Mijoz' ? 'left' : 'right', fontWeight: 600, borderBottom: '2px solid var(--border)' }}>{h}</th>; })}
                      </tr>
                    </thead>
                    <tbody>
                      {debtors.slice(0, 150).map(function (b, i) {
                        return (
                          <tr key={b.CS_id || i} style={{ borderBottom: '1px solid var(--border)', background: i % 2 ? 'rgba(0,0,0,.015)' : 'transparent' }}>
                            <td style={{ padding: '7px 10px', fontWeight: 600 }}>{b.name || '—'}</td>
                            <td className="tnum" style={{ padding: '7px 10px', textAlign: 'right', fontWeight: 800, color: '#C2453A' }}>{sdFmt(Math.abs(b.balance || 0))}</td>
                          </tr>
                        );
                      })}
                      {!debtors.length && <tr><td colSpan={2} style={{ textAlign: 'center', padding: 28, color: 'var(--ink-4)' }}>Qarzdor mijozlar yo'q ✓</td></tr>}
                    </tbody>
                    {debtors.length > 0 && (
                      <tfoot>
                        <tr style={{ borderTop: '2px solid var(--border)' }}>
                          <td style={{ padding: '7px 10px', fontWeight: 800 }}>JAMI QARZ</td>
                          <td className="tnum" style={{ padding: '7px 10px', textAlign: 'right', color: '#C2453A', fontWeight: 900, fontSize: 14 }}>{sdFmt(totalDebt)}</td>
                        </tr>
                      </tfoot>
                    )}
                  </table>
                </div>
                {debtors.length > 150 && <div style={{ textAlign: 'center', fontSize: 11.5, color: 'var(--ink-4)', marginTop: 8 }}>Jami {debtors.length} ta (150 ta ko'rsatilmoqda)</div>}
              </div>

              <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.14s' }}>
                <SDSectionHead icon="chart" title="Balans taqsimoti" sub={'Jami ' + balances.length + ' ta mijoz'} tint="rgba(232,115,95,.12)" ink="#C2453A" />
                <div style={{ marginTop: 14 }}>
                  <SDDonutChart
                    rows={[
                      { name: 'Qarzdor', sum: debtors.length, color: '#E8735F' },
                      { name: 'Nol', sum: balances.filter(function (b) { return !(b.balance || 0); }).length, color: '#A39A90' },
                      { name: 'Ijobiy', sum: balances.filter(function (b) { return (b.balance || 0) > 0; }).length, color: '#3DBE9C' },
                    ].filter(function (r) { return r.sum > 0; })}
                    empty="Balans ma'lumoti yo'q" />
                </div>
                <div style={{ marginTop: 16, borderTop: '1px solid var(--border)', paddingTop: 14 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                    <span style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>Jami qarz</span>
                    <span className="tnum" style={{ fontSize: 14, fontWeight: 900, color: '#C2453A' }}>{sdFmt(totalDebt)}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>O'rtacha qarz</span>
                    <span className="tnum" style={{ fontSize: 13, fontWeight: 700, color: '#E8735F' }}>{debtors.length ? sdFmt(totalDebt / debtors.length) : '—'}</span>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* ══════════ AGENTLAR ══════════ */}
          {tab === 'agents' && (
            <div>
              <div className="dx-g2" style={{ marginBottom: 16 }}>
                <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.10s' }}>
                  <SDSectionHead icon="users" title={'Agent reytingi · ' + agents.length + ' ta'} sub="Tashrif soni bo'yicha top agentlar" tint="rgba(142,116,255,.12)" ink="#5B45D6" />
                  <div style={{ marginTop: 14 }}>
                    <SDStatBarList rows={agentStatRows} max={maxAgent} accent="#7A5CF0" />
                  </div>
                </div>
                <div className="dx-card dx-card--pad dash-anim" style={{ animationDelay: '.14s' }}>
                  <SDSectionHead icon="chart" title="Tashrif ulushi — agentlar" sub="Har agent bo'lgan tashriflar soni" tint="rgba(142,116,255,.12)" ink="#5B45D6" />
                  <div style={{ marginTop: 14 }}>
                    <SDDonutChart rows={agents.slice(0, 8).map(function (a) { return { name: a.name, sum: a.actual }; })} empty="Agent ma'lumoti yo'q" />
                  </div>
                </div>
              </div>

              <div className="dx-card dx-card--pad dash-anim" style={{ marginBottom: 16, animationDelay: '.18s' }}>
                <SDSectionHead icon="grid" title="Agentlar batafsil jadvali" sub="Rejalangan, bo'lgan, GPS, buyurtma ko'rsatkichlari" tint="rgba(142,116,255,.12)" ink="#5B45D6" />
                <div style={{ overflowX: 'auto', marginTop: 14 }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, minWidth: 620 }}>
                    <thead>
                      <tr style={{ color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                        {['#', 'Agent', 'Filial', 'Rej.', "Bo'lgan", 'Tashrif%', 'GPS%', 'Buyurtma%'].map(function (h) {
                          return <th key={h} style={{ padding: '6px 10px', textAlign: (h === 'Agent' || h === 'Filial' || h === '#') ? 'left' : 'right', fontWeight: 600, borderBottom: '2px solid var(--border)', whiteSpace: 'nowrap' }}>{h}</th>;
                        })}
                      </tr>
                    </thead>
                    <tbody>
                      {agents.map(function (a, i) {
                        var vr = pct(a.actual, a.planned);
                        var gr = pct(a.gps, a.actual);
                        var or2 = pct(a.withOrder, a.actual);
                        return (
                          <tr key={a.id} style={{ borderBottom: '1px solid var(--border)', background: i % 2 ? 'rgba(0,0,0,.015)' : 'transparent' }}>
                            <td className="tnum" style={{ padding: '7px 10px', color: 'var(--ink-4)', fontSize: 11 }}>{i + 1}</td>
                            <td style={{ padding: '7px 10px', fontWeight: 700 }}>{a.name}</td>
                            <td style={{ padding: '7px 10px', color: 'var(--ink-4)', fontSize: 11.5 }}>{(a.filial && a.filial.name) || '—'}</td>
                            <td className="tnum" style={{ padding: '7px 10px', textAlign: 'right', color: 'var(--ink-4)' }}>{a.planned}</td>
                            <td className="tnum" style={{ padding: '7px 10px', textAlign: 'right', fontWeight: 800 }}>{a.actual}</td>
                            <td style={{ padding: '7px 10px', textAlign: 'right' }}><PctBadge val={vr} good={90} warn={70} /></td>
                            <td style={{ padding: '7px 10px', textAlign: 'right' }}><PctBadge val={gr} good={95} warn={80} /></td>
                            <td style={{ padding: '7px 10px', textAlign: 'right' }}><PctBadge val={or2} good={60} warn={40} /></td>
                          </tr>
                        );
                      })}
                      {!agents.length && <tr><td colSpan={8} style={{ textAlign: 'center', padding: 28, color: 'var(--ink-4)' }}>Agent ma'lumoti yo'q</td></tr>}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* ══════════ TREND ══════════ */}
          {tab === 'trend' && (
            <div>
              <div className="dx-card dx-card--pad dash-anim" style={{ marginBottom: 16, animationDelay: '.10s' }}>
                <SDSectionHead icon="trendUp" title="Kunlik tashrif trendi" sub="Rejalangan (---) vs bo'lgan (—) davr bo'yicha"
                  tint="rgba(142,116,255,.12)" ink="#5B45D6"
                  right={
                    <div style={{ fontSize: 11.5, color: 'var(--ink-4)', display: 'flex', gap: 12 }}>
                      <span><span style={{ display: 'inline-block', width: 20, height: 3, background: 'var(--border)', borderRadius: 2, marginRight: 5, verticalAlign: 'middle' }} />Rej.</span>
                      <span><span style={{ display: 'inline-block', width: 20, height: 3, background: 'var(--brand)', borderRadius: 2, marginRight: 5, verticalAlign: 'middle' }} />Bo'lgan</span>
                    </div>
                  } />
                <div style={{ marginTop: 14 }}>
                  <SDTrendChart trend={trend} />
                </div>
              </div>

              <div className="dx-card dx-card--pad dash-anim" style={{ marginBottom: 16, animationDelay: '.14s' }}>
                <SDSectionHead icon="layers" title="Kunlik batafsil" sub="Rej./bo'lgan/GPS/buyurtma ko'rsatkichlari" tint="rgba(90,159,212,.12)" ink="#2F6F9E" />
                <div style={{ overflowX: 'auto', marginTop: 14, maxHeight: 380, overflowY: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
                    <thead style={{ position: 'sticky', top: 0, background: 'var(--surface)' }}>
                      <tr style={{ color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                        {['Sana', 'Rej.', "Bo'lgan", 'GPS', 'Buyurtma', '%'].map(function (h) { return <th key={h} style={{ padding: '6px 10px', textAlign: h === 'Sana' ? 'left' : 'right', fontWeight: 600, borderBottom: '2px solid var(--border)' }}>{h}</th>; })}
                      </tr>
                    </thead>
                    <tbody>
                      {trend.map(function (d, i) {
                        var vr = d.planned ? pct(d.actual, d.planned) : 0;
                        return (
                          <tr key={d.date} style={{ borderBottom: '1px solid var(--border)', background: i % 2 ? 'rgba(0,0,0,.015)' : 'transparent' }}>
                            <td style={{ padding: '8px 10px', fontWeight: 700 }}>{d.date}</td>
                            <td className="tnum" style={{ padding: '8px 10px', textAlign: 'right', color: 'var(--ink-4)' }}>{d.planned || 0}</td>
                            <td className="tnum" style={{ padding: '8px 10px', textAlign: 'right', fontWeight: 800 }}>{d.actual || 0}</td>
                            <td className="tnum" style={{ padding: '8px 10px', textAlign: 'right', color: '#3F7FB8' }}>{d.gps || 0}</td>
                            <td className="tnum" style={{ padding: '8px 10px', textAlign: 'right', color: '#7A5CF0' }}>{d.withOrder || 0}</td>
                            <td style={{ padding: '8px 10px', textAlign: 'right' }}><PctBadge val={vr} good={90} warn={70} /></td>
                          </tr>
                        );
                      })}
                      {!trend.length && <tr><td colSpan={6} style={{ textAlign: 'center', padding: 28, color: 'var(--ink-4)' }}>Trend ma'lumoti yo'q</td></tr>}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

        </div>
      )}
    </div>
  );
}

window.SalesDocDashboard = SalesDocDashboard;
