/* ============================================================
   Region kunlik (Iyun) — jonli Google Sheets dashboard
   Backend /api/sheet-dashboard'dan tozalangan JSON oladi,
   har ~5 daqiqada avtomatik yangilanadi. Token serverda qoladi.
   ============================================================ */

const SD_REFRESH_MS = 5 * 60 * 1000; // 5 daqiqa

// Katta sonni qisqa ko'rinishda: 10.7 mlrd, 245 mln, ...
function sdShort(v) {
  const n = Number(v) || 0;
  const a = Math.abs(n);
  if (a >= 1e9) return (n / 1e9).toFixed(2).replace(/\.?0+$/, '') + ' mlrd';
  if (a >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + ' mln';
  if (a >= 1e3) return Math.round(n / 1e3) + ' ming';
  return String(Math.round(n));
}
const sdFull = (v) => Number(v || 0).toLocaleString('ru-RU').replace(/,/g, ' ');
const sdPct = (v) => (Number(v || 0) * 100).toFixed(1) + '%';
// Karobka (kor) — kasrли bo'lishi mumkin, 1 xona aниqлиkда ko'rsatamiz.
const sdKor = (v) => (Math.round((Number(v) || 0) * 10) / 10).toLocaleString('ru-RU').replace(/,/g, ' ');

// Region'ning byBrand.skus'idan karobka (kor) yig'indisini hisoblaydi: {plan, fakt, prognoz}.
// Google Sheet Iyul+ parserida har SKU'da planKor/faktKor/prognozKor bor.
function sdRegionKor(r) {
  const bb = (r && r.byBrand) || {};
  let plan = 0, fakt = 0, prognoz = 0;
  for (const key of Object.keys(bb)) {
    const skus = (bb[key] && bb[key].skus) || [];
    for (const s of skus) {
      plan += s.planKor || 0;
      fakt += s.faktKor || 0;
      prognoz += s.prognozKor || 0;
    }
  }
  return { plan, fakt, prognoz };
}
// Region ko'rsatkichlarini tanlangan brend kesimiga o'tkazadi ('all' — asl region).
// byBrand'da brend bo'lmasa null qaytaradi (kartochka ko'rsatilmaydi).
function sdBrandRegion(r, brand) {
  if (!brand || brand === 'all') return r;
  const bb = (r.byBrand || {})[brand];
  if (!bb) return null;
  return {
    ...r,
    plan: bb.planSom || 0,
    fakt: bb.faktSom || 0,
    prognoz: bb.prognozSom || 0,
    pct: bb.pct || 0,
    prognozPct: bb.prognozPct || 0,
    akb: 0, // AKB jadvalda brend kesimida yo'q
    byBrand: { [brand]: bb }, // kor hisobi va modal faqat shu brendni ko'radi
    _brand: brand,
  };
}

// Barcha regionlarning kor yig'indisi (umumiy KPI uchun).
function sdTotalKor(regions) {
  return (regions || []).reduce((a, r) => {
    const k = sdRegionKor(r);
    a.plan += k.plan; a.fakt += k.fakt; a.prognoz += k.prognoz;
    return a;
  }, { plan: 0, fakt: 0, prognoz: 0 });
}

// Bajarilish foiziga qarab rang holati
function sdStatus(pct) {
  if (pct >= 1) return { key: 'ok', tint: 'rgba(61,190,156,.14)', ink: '#1D8A6E', label: 'Bajarildi' };
  if (pct >= 0.7) return { key: 'warn', tint: 'rgba(227,162,59,.16)', ink: '#A6651E', label: 'Yaqin' };
  return { key: 'bad', tint: 'rgba(232,115,95,.14)', ink: '#C2453A', label: 'Past' };
}

function SdKpi({ label, value, sub, accent, big }) {
  return (
    <div className="dash-card" style={{
      background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)',
      padding: '14px 16px', boxShadow: 'var(--sh-1)', display: 'flex', flexDirection: 'column', gap: 6, minWidth: 0,
    }}>
      <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.04em' }}>{label}</div>
      <div className="tnum" style={{ fontSize: big ? 24 : 20, fontWeight: 700, letterSpacing: '-.02em', lineHeight: 1.05, color: accent || 'var(--ink)' }}>{value}</div>
      {sub != null && <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>{sub}</div>}
    </div>
  );
}

// Kunlik natijani "svetofor" rangiga ajratamiz (rejaga nisbatan).
// >=100% yashil (oshdi), 70-99% sariq (yaqin), <70% qizil (past).
function sdDayTone(pct, hasTarget) {
  if (!hasTarget) return { fill: 'linear-gradient(180deg,var(--brand),var(--brand-700))', solid: 'var(--brand)', label: '' };
  if (pct >= 1) return { fill: 'linear-gradient(180deg,#34d399,#2FAE8D)', solid: '#2FAE8D', label: 'rejadan oshdi' };
  if (pct >= 0.7) return { fill: 'linear-gradient(180deg,#EDBB62,#D08A2A)', solid: '#D08A2A', label: 'rejaga yaqin' };
  return { fill: 'linear-gradient(180deg,#EE9483,#C2453A)', solid: '#C2453A', label: 'rejadan past' };
}

function SdBarChart({ daily, dailyTarget }) {
  const rows = (daily || []).filter((d) => d.total > 0);
  if (!rows.length) return <div style={{ fontSize: 12.5, color: 'var(--ink-4)', padding: '12px 0' }}>Hozircha kunlik sotuv ma'lumoti yo'q.</div>;
  const hasTarget = dailyTarget > 0;
  const max = Math.max(dailyTarget || 0, ...rows.map((d) => d.total)) || 1;
  const targetH = hasTarget ? (dailyTarget / max) * 100 : 0;
  const hitCount = hasTarget ? rows.filter((d) => d.total >= dailyTarget).length : 0;
  const avg = rows.reduce((s, d) => s + d.total, 0) / rows.length;
  const best = rows.reduce((a, b) => (b.total > a.total ? b : a), rows[0]);

  return (
    <div>
      {/* Bir qatorlik xulosa — darrov tushunarli bo'lishi uchun */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 12 }}>
        {hasTarget && (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600, background: 'rgba(61,190,156,.12)', color: '#1D8A6E', padding: '4px 10px', borderRadius: 999 }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: '#2FAE8D' }} />
            {rows.length} kundan {hitCount} tasi rejadan oshdi
          </span>
        )}
        <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', background: 'var(--bg-soft,rgba(0,0,0,.04))', padding: '4px 10px', borderRadius: 999 }}>
          O'rtacha kunlik: {sdShort(avg)}
        </span>
        <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', background: 'var(--bg-soft,rgba(0,0,0,.04))', padding: '4px 10px', borderRadius: 999 }}>
          Eng yaxshi kun: {best.date} ({sdShort(best.total)})
        </span>
      </div>

      <div style={{ position: 'relative', display: 'flex', alignItems: 'flex-end', gap: 8, height: 180, paddingTop: 18 }}>
        {/* Kunlik reja chizig'i */}
        {targetH > 0 && (
          <div title={"Kunlik reja: " + sdShort(dailyTarget)} style={{
            position: 'absolute', left: 0, right: 0, bottom: targetH + '%',
            borderTop: '2px dashed var(--ink-4)', opacity: .55, pointerEvents: 'none', zIndex: 2,
          }}>
            <span style={{ position: 'absolute', right: 0, top: -15, fontSize: 10.5, fontWeight: 700, color: 'var(--ink-3)', background: 'var(--surface)', padding: '0 4px' }}>
              Reja {sdShort(dailyTarget)}
            </span>
          </div>
        )}
        {rows.map((d, i) => {
          const h = Math.max(2, (d.total / max) * 100);
          const pct = hasTarget ? d.total / dailyTarget : 0;
          const tone = sdDayTone(pct, hasTarget);
          const tip = d.date + ' • ' + sdFull(d.total) + (hasTarget ? ('\nReja bajarilishi: ' + Math.round(pct * 100) + '% • ' + tone.label) : '');
          return (
            <div key={i} style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, height: '100%', justifyContent: 'flex-end' }}>
              <div className="tnum" style={{ fontSize: 9.5, fontWeight: 700, color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>{sdShort(d.total)}</div>
              <div title={tip} style={{
                width: '100%', maxWidth: 42, height: h + '%', borderRadius: 999,
                background: tone.fill, cursor: 'default',
                transition: 'height .4s var(--ease)',
              }} />
              <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--ink-3)' }}>{d.date}</div>
            </div>
          );
        })}
      </div>

      {/* Rang izohi (legenda) */}
      {hasTarget && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 14, marginTop: 12, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
          {[
            { c: '#2FAE8D', t: 'Rejadan oshdi (≥100%)' },
            { c: '#D08A2A', t: 'Rejaga yaqin (70–99%)' },
            { c: '#C2453A', t: 'Rejadan past (<70%)' },
          ].map((x, i) => (
            <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--ink-4)' }}>
              <span style={{ width: 11, height: 11, borderRadius: 3, background: x.c }} />{x.t}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

/* ============================================================
   Region detail modal — kartochkani bosganida ochiladigan
   brend + SKU bo'yicha batafsil ko'rinish
   ============================================================ */
function SdRegionModal({ region, elapsed, totalDays, onClose }) {
  if (!region) return null;
  const r = region;
  const fp = r.pct || 0;
  const pp = r.prognozPct || 0;
  const elapsedFrac = totalDays > 0 ? (elapsed || 0) / totalDays : 0;
  const score = pp > 0 ? pp : (elapsedFrac > 0 ? fp / elapsedFrac : 0);
  const st = score >= 0.95
    ? { tint: 'rgba(61,190,156,.13)', ink: '#1D8A6E', label: 'Planni yopadi', dot: '#3DBE9C' }
    : score >= 0.75
    ? { tint: 'rgba(227,162,59,.16)', ink: '#A6651E', label: 'Kechikishi mumkin', dot: '#D08A2A' }
    : { tint: 'rgba(232,115,95,.13)', ink: '#C2453A', label: 'Planni yopolmaydi', dot: '#C2453A' };

  const brands = r.byBrand || {};
  const rk = sdRegionKor(r); // karobka (kor): {plan, fakt, prognoz}
  const rHasKor = rk.plan > 0 || rk.fakt > 0 || rk.prognoz > 0;
  const SD_BRAND_PAL = ['#EC7A55', '#2B2927', '#3DBE9C', '#E9B949', '#5A9FD4', '#8E74FF'];
  const brandMeta = Object.keys(brands).map((key, i) => {
    const db = DB.brandByTag(key);
    const color = (db && db.color && db.color.startsWith('#')) ? db.color : SD_BRAND_PAL[i % SD_BRAND_PAL.length];
    return { key, label: db ? db.name : key, color, bg: color + '12', border: color + '38' };
  });

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'rgba(0,0,0,.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: 'var(--surface)', borderRadius: 16, boxShadow: '0 24px 60px rgba(0,0,0,.25)',
        width: '100%', maxWidth: 640, maxHeight: '90vh', overflowY: 'auto',
      }}>
        {/* Modal sarlavha */}
        <div style={{ padding: '18px 20px 14px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
          <div>
            <div style={{ fontSize: 17, fontWeight: 800, letterSpacing: '-.01em', lineHeight: 1.2 }}>{r.name}</div>
            <span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 999, background: st.tint, color: st.ink, marginTop: 6, display: 'inline-block' }}>{st.label}</span>
          </div>
          <button onClick={onClose} style={{ flexShrink: 0, width: 32, height: 32, borderRadius: 8, border: '1px solid var(--border)', background: 'transparent', cursor: 'pointer', fontSize: 17, color: 'var(--ink-3)', display: 'grid', placeItems: 'center' }}>✕</button>
        </div>

        <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* Umumiy progress bloki */}
          <div style={{ background: 'var(--bg-soft,rgba(127,127,127,.06))', borderRadius: 12, padding: '14px 16px' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 10 }}>Umumiy natija (so'm + karobka)</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginBottom: 12 }}>
              {[
                { label: 'Reja', val: sdShort(r.plan), sub: sdPct(1), color: 'var(--ink-3)', kor: rk.plan },
                { label: 'Fakt', val: sdShort(r.fakt), sub: sdPct(fp), color: st.ink, kor: rk.fakt },
                { label: 'Prognoz', val: pp > 0 ? sdShort(r.prognoz) : '—', sub: pp > 0 ? sdPct(pp) : null, color: '#5B45D6', kor: rk.prognoz },
              ].map((col) => (
                <div key={col.label} style={{ textAlign: 'center', padding: '8px 4px', borderRadius: 8, background: 'var(--surface)' }}>
                  <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 4 }}>{col.label}</div>
                  <div className="tnum" style={{ fontSize: 14, fontWeight: 800, color: col.color, lineHeight: 1.1 }}>{col.val}</div>
                  {col.sub && <div className="tnum" style={{ fontSize: 11, color: col.color, opacity: .8, marginTop: 2 }}>{col.sub}</div>}
                  {rHasKor && <div className="tnum" style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 3, borderTop: '1px solid var(--border)', paddingTop: 3 }}>{sdKor(col.kor)} kor</div>}
                </div>
              ))}
            </div>
            <div style={{ height: 10, borderRadius: 5, background: 'rgba(127,127,127,.14)', overflow: 'hidden', position: 'relative' }}>
              {pp > 0 && <div style={{ position: 'absolute', inset: 0, width: Math.min(100, pp * 100) + '%', borderRadius: 5, background: 'repeating-linear-gradient(45deg,rgba(142,116,255,.2),rgba(142,116,255,.2) 5px,rgba(142,116,255,.07) 5px,rgba(142,116,255,.07) 10px)' }} />}
              <div style={{ position: 'relative', height: '100%', width: Math.min(100, fp * 100) + '%', borderRadius: 5, background: st.dot, transition: 'width .4s' }} />
            </div>
            {r.akb > 0 && <div style={{ marginTop: 10, fontSize: 12, color: 'var(--ink-4)' }}>AKB: <b className="tnum" style={{ color: 'var(--ink-2)' }}>{sdFull(r.akb)}</b></div>}
          </div>

          {/* Brend bo'limlari */}
          {brandMeta.length > 0
            ? brandMeta.map(({ key, label, color, bg, border }) => {
                const bd = brands[key];
                const bPct = bd.pct || 0;
                const skuList = bd.skus || [];
                const hasSom = bd.planSom > 0 || bd.faktSom > 0;
                const hasKor = skuList.some((s) => s.planKor > 0 || s.faktKor > 0 || s.prognozKor > 0);
                return (
                  <div key={key} style={{ border: `1.5px solid ${border}`, borderRadius: 12, overflow: 'hidden' }}>
                    {/* Brend sarlavha */}
                    <div style={{ background: bg, padding: '11px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 800, color }}>{label}</div>
                      {hasSom && (
                        <div className="tnum" style={{ fontSize: 12.5, fontWeight: 700, color, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                          <span style={{ color: 'var(--ink-4)', fontWeight: 500 }}>Reja {sdShort(bd.planSom)}</span>
                          <span>·</span>
                          <span>Fakt {sdShort(bd.faktSom)}</span>
                          {bd.prognozSom > 0 && (
                            <React.Fragment>
                              <span>·</span>
                              <span style={{ color: '#5B45D6' }}>Prognoz {sdShort(bd.prognozSom)}</span>
                            </React.Fragment>
                          )}
                          {bd.planSom > 0 && (
                            <span style={{ padding: '1px 7px', borderRadius: 999, background: bPct >= 0.95 ? 'rgba(61,190,156,.18)' : bPct >= 0.7 ? 'rgba(227,162,59,.2)' : 'rgba(232,115,95,.16)', color: bPct >= 0.95 ? '#1D8A6E' : bPct >= 0.7 ? '#A6651E' : '#C2453A', fontSize: 11.5 }}>
                              {sdPct(bPct)}
                            </span>
                          )}
                        </div>
                      )}
                    </div>
                    {/* Brand progress bar */}
                    {hasSom && bd.planSom > 0 && (
                      <div style={{ height: 4, background: 'rgba(127,127,127,.1)' }}>
                        <div style={{ width: Math.min(100, bPct * 100) + '%', height: '100%', background: color, transition: 'width .4s' }} />
                      </div>
                    )}
                    {/* SKU karobka jadvali */}
                    {hasKor ? (
                      <div style={{ padding: '10px 16px 14px' }}>
                        <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--ink-4)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.04em' }}>Karobka bo'yicha</div>
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto auto auto auto', gap: '0 10px' }}>
                          {['Mahsulot', 'Reja (kor)', 'Fakt (kor)', 'Prognoz (kor)', '%'].map((h) => (
                            <div key={h} style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.03em', paddingBottom: 6, borderBottom: '1px solid var(--border)', marginBottom: 2 }}>{h}</div>
                          ))}
                          {skuList.map((s, i) => {
                            const sp = s.planKor > 0 ? s.faktKor / s.planKor : 0;
                            const sc = sp >= 0.95 ? '#1D8A6E' : sp >= 0.7 ? '#A6651E' : '#C2453A';
                            const hasPlan = s.planKor > 0;
                            return (
                              <React.Fragment key={i}>
                                <div style={{ fontSize: 13, fontWeight: 600, padding: '5px 0' }}>{s.sku}</div>
                                <div className="tnum" style={{ textAlign: 'right', fontSize: 13, color: 'var(--ink-3)', padding: '5px 0' }}>{hasPlan ? sdFull(s.planKor) : '—'}</div>
                                <div className="tnum" style={{ textAlign: 'right', fontSize: 13, fontWeight: 700, padding: '5px 0' }}>{s.faktKor > 0 ? sdFull(s.faktKor) : '—'}</div>
                                <div className="tnum" style={{ textAlign: 'right', fontSize: 13, color: '#5B45D6', padding: '5px 0' }}>{s.prognozKor > 0 ? sdFull(s.prognozKor) : '—'}</div>
                                <div className="tnum" style={{ textAlign: 'right', fontSize: 12.5, fontWeight: 700, color: hasPlan ? sc : 'var(--ink-4)', padding: '5px 0' }}>
                                  {hasPlan ? sdPct(sp) : '—'}
                                </div>
                              </React.Fragment>
                            );
                          })}
                          {/* Brend jami (karobka) */}
                          {(() => {
                            const bPlanKor    = skuList.reduce((a, s) => a + (s.planKor || 0), 0);
                            const bFaktKor    = skuList.reduce((a, s) => a + (s.faktKor || 0), 0);
                            const bPrognozKor = skuList.reduce((a, s) => a + (s.prognozKor || 0), 0);
                            const bKorPct = bPlanKor > 0 ? bFaktKor / bPlanKor : 0;
                            const kc = bKorPct >= 0.95 ? '#1D8A6E' : bKorPct >= 0.7 ? '#A6651E' : '#C2453A';
                            const cell = { textAlign: 'right', fontSize: 13, fontWeight: 800, padding: '6px 0 0', borderTop: '1px solid var(--border)', marginTop: 2 };
                            return (
                              <React.Fragment>
                                <div style={{ fontSize: 12, fontWeight: 800, padding: '6px 0 0', borderTop: '1px solid var(--border)', marginTop: 2, textTransform: 'uppercase', letterSpacing: '.03em' }}>Jami</div>
                                <div className="tnum" style={{ ...cell, color: 'var(--ink-2)' }}>{bPlanKor > 0 ? sdKor(bPlanKor) : '—'}</div>
                                <div className="tnum" style={cell}>{bFaktKor > 0 ? sdKor(bFaktKor) : '—'}</div>
                                <div className="tnum" style={{ ...cell, color: '#5B45D6' }}>{bPrognozKor > 0 ? sdKor(bPrognozKor) : '—'}</div>
                                <div className="tnum" style={{ ...cell, color: bPlanKor > 0 ? kc : 'var(--ink-4)' }}>{bPlanKor > 0 ? sdPct(bKorPct) : '—'}</div>
                              </React.Fragment>
                            );
                          })()}
                        </div>
                      </div>
                    ) : (
                      !hasSom && <div style={{ padding: '12px 16px', fontSize: 12.5, color: 'var(--ink-4)' }}>Ma'lumot yo'q</div>
                    )}
                  </div>
                );
              })
            : (
              <div style={{ fontSize: 12.5, color: 'var(--ink-4)', textAlign: 'center', padding: '12px 0' }}>
                Brend ma'lumotlari mavjud emas (Iyul jadvalidan tortiladi)
              </div>
            )
          }

          {/* Distributor (diller) kesimi — jadvaldagi diller qatoridan (faqat umumiy ko'rinishda) */}
          {!r._brand && (r.dists || []).length > 0 && (
            <div style={{ background: 'var(--bg-soft,rgba(127,127,127,.06))', borderRadius: 12, padding: '12px 16px' }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 8 }}>
                Distributorlar bo'yicha
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr auto auto auto auto', gap: '0 10px' }}>
                {['Diller', 'Reja', 'Fakt', '%', 'Fakt (kor)'].map((h) => (
                  <div key={h} style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.03em', paddingBottom: 6, borderBottom: '1px solid var(--border)', marginBottom: 2 }}>{h}</div>
                ))}
                {r.dists.map((d, i) => {
                  const dp = d.pct || 0;
                  const dc = dp >= 0.95 ? '#1D8A6E' : dp >= 0.7 ? '#A6651E' : '#C2453A';
                  const hasPlan = (d.planSom || 0) > 0;
                  return (
                    <React.Fragment key={i}>
                      <div style={{ fontSize: 13, fontWeight: 600, padding: '5px 0', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={d.name}>{d.name}</div>
                      <div className="tnum" style={{ textAlign: 'right', fontSize: 13, color: 'var(--ink-3)', padding: '5px 0' }}>{hasPlan ? sdShort(d.planSom) : '—'}</div>
                      <div className="tnum" style={{ textAlign: 'right', fontSize: 13, fontWeight: 700, padding: '5px 0' }}>{d.faktSom > 0 ? sdShort(d.faktSom) : '—'}</div>
                      <div className="tnum" style={{ textAlign: 'right', fontSize: 12.5, fontWeight: 700, color: hasPlan ? dc : 'var(--ink-4)', padding: '5px 0' }}>{hasPlan ? sdPct(dp) : '—'}</div>
                      <div className="tnum" style={{ textAlign: 'right', fontSize: 13, color: 'var(--ink-3)', padding: '5px 0' }}>{d.faktKor > 0 ? sdKor(d.faktKor) : '—'}</div>
                    </React.Fragment>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function SheetDashboard({ data: injected, initialMonth, section }) {
  const isSellin = section === 'sellin';
  // Sahifa keshi — bo'limga qayta kirilganda oldingi ma'lumot darrov ko'rsatiladi.
  const cacheKey = 'sd:' + (section || 'sellout') + ':' + (initialMonth || 'default');
  const cached = !injected && window.PageCache ? window.PageCache.get(cacheKey) : null;
  const [data, setData] = useState(injected || (cached && cached.data) || null);
  const [loading, setLoading] = useState(!injected && !cached);
  const [err, setErr] = useState(null);
  const [refreshing, setRefreshing] = useState(false);
  const [selectedRegion, setSelectedRegion] = useState(null);
  // Hudud kartochkalari uchun brend kesimi: 'all' | <BREND TEGI>.
  const [brandView, setBrandView] = useState('all');
  // Regionlar jadvalini ustun bo'yicha saralash (a-z / z-a). col=null — standart (faktdan).
  const [sort, setSort] = useState({ col: null, dir: 'asc' });
  // Oy tanlash (sheetdagi varaqlar) — null bo'lsa server default (joriy) oyni qaytaradi.
  const [month, setMonth] = useState((cached && cached.month) || null);
  const [months, setMonths] = useState((cached && cached.months) || []);
  const monthRef = useRef((cached && cached.month) || null);

  async function load(force) {
    if (injected) return;
    if (force) setRefreshing(true); else setLoading(true);
    setErr(null);
    try {
      const res = await API.sheetDashboard(force, monthRef.current, section);
      setData(res);
      if (res.months) setMonths(res.months);
      if (res.month) { if (monthRef.current == null) monthRef.current = initialMonth || res.month; setMonth(initialMonth || res.month); }
      // Keshga saqlash — bo'limga qayta kirilganda darrov ko'rsatish uchun.
      if (window.PageCache) window.PageCache.set(cacheKey, { data: res, months: res.months || [], month: monthRef.current });
    } catch (ex) {
      setErr(ex.message || 'Maʼlumotni yuklab boʼlmadi');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }

  // Oy almashtirish — tanlangan varaqni qayta yuklaydi.
  function pickMonth(m) {
    if (!m || m === monthRef.current || refreshing) return;
    monthRef.current = m;
    setMonth(m);
    load(false); // oy almashtirish — keshdan darrov, fonda yangilanadi
  }

  useEffect(() => {
    if (injected) return;
    // initialMonth birinchi so'rovdan OLDIN o'rnatilishi kerak, aks holda
    // server default oyni (iyun) qaytaradi — iyul uchun noto'g'ri natija.
    if (initialMonth && monthRef.current == null) monthRef.current = initialMonth;
    load(false); // keshdan darrov ko'rsat, server fonda yangilaydi (stale-while-revalidate)
    const t = setInterval(() => load(false), SD_REFRESH_MS);
    return () => clearInterval(t);
  }, []); // eslint-disable-line

  if (loading && !data) {
    return (
      <div style={{ height: '100%', display: 'grid', placeItems: 'center', color: 'var(--ink-4)' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
          <Icon name="chart" size={26} />
          <div style={{ fontSize: 13, fontWeight: 600 }}>Maʼlumot yuklanmoqda…</div>
        </div>
      </div>
    );
  }

  if (err && !data) {
    return (
      <div style={{ height: '100%', display: 'grid', placeItems: 'center', padding: 24 }}>
        <div style={{ maxWidth: 420, textAlign: 'center', display: 'flex', flexDirection: 'column', gap: 12, color: 'var(--ink-3)' }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)' }}>Dashboard yuklanmadi</div>
          <div style={{ fontSize: 13 }}>{err}</div>
          <div><button className="btn btn--primary" onClick={() => load(true)}>Qayta urinish</button></div>
        </div>
      </div>
    );
  }

  const k = (data && data.kpi) || {};
  const monthLabel = (months.find((x) => x.key === month) || {}).label || (month ? month : 'Iyun');
  const regionsRaw = (data && data.regions) || [];
  const daily = (data && data.daily) || [];
  // Umumiy karobka (kor) — barcha regionlarning SKU kor yig'indisi.
  // Iyul+ (Google Sheet'da "... (kor)" qatorlari) bo'lsa > 0, aks holda 0 → ko'rsatilmaydi.
  const totalKor = sdTotalKor(regionsRaw);
  const hasKor = totalKor.plan > 0 || totalKor.fakt > 0 || totalKor.prognoz > 0;

  // Ustun bo'yicha saralangan regionlar. 'name' — matn (a-z/z-a), qolganlari — raqam.
  const regions = (() => {
    if (!sort.col) return regionsRaw;
    const arr = [...regionsRaw];
    const dir = sort.dir === 'asc' ? 1 : -1;
    arr.sort((a, b) => {
      if (sort.col === 'name') {
        return String(a.name || '').localeCompare(String(b.name || ''), 'uz') * dir;
      }
      return ((a[sort.col] || 0) - (b[sort.col] || 0)) * dir;
    });
    return arr;
  })();
  // Ustun sarlavhasini bosish: bir xil ustun — yo'nalishni almashtirish, boshqasi — a-z dan boshlash.
  const toggleSort = (col) =>
    setSort((s) => (s.col === col ? { col, dir: s.dir === 'asc' ? 'desc' : 'asc' } : { col, dir: 'asc' }));
  const sortArrow = (col) => (sort.col === col ? (sort.dir === 'asc' ? ' ▲' : ' ▼') : '');
  const brands = (data && data.brands) || null;
  const zones = (data && data.zones) || [];
  const updated = data && data.updatedAt ? new Date(data.updatedAt) : null;
  const updatedStr = updated ? updated.toLocaleString('ru-RU', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) : '—';
  const st = sdStatus(k.pct || 0);
  const warnings = (data && data.warnings) || [];
  const structureBad = !!data && data.structureOk === false && warnings.length > 0;

  return (
    <div className="dash-wrap" style={{ padding: '8px 28px 32px', overflowY: 'auto', height: '100%' }}>
      {/* Sarlavha + oy tanlash + yangilash */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', margin: '8px 0 16px' }}>
        <div>
          <h2 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-.02em', margin: 0 }}>{isSellin ? 'SELL IN — Pervichka' : 'SELL OUT — Region kunlik'} ({monthLabel})</h2>
          <p style={{ fontSize: 12.5, margin: '4px 0 0', color: 'var(--ink-4)' }}>
            {k.startDate && k.endDate ? `${k.startDate} – ${k.endDate} · ` : ''}
            {k.elapsedDays != null ? `${k.elapsedDays}/${k.totalDays} ish kuni · ` : ''}
            Oxirgi yangilanish: {updatedStr}
          </p>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          {!isSellin && months.length > 0 && (
            <label style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 12.5, color: 'var(--ink-4)', fontWeight: 600 }}>
              <Icon name="cal" size={15} />
              <select value={month || ''} onChange={(e) => pickMonth(e.target.value)} disabled={refreshing}
                style={{ height: 36, borderRadius: 9, border: '1px solid var(--border)', background: 'var(--surface)', color: 'var(--ink)', fontSize: 13, fontWeight: 600, padding: '0 10px', cursor: 'pointer' }}>
                {months.map((m) => <option key={m.key} value={m.key}>{m.label}</option>)}
              </select>
            </label>
          )}
          <button className="btn btn--ghost" onClick={() => load(true)} disabled={refreshing} style={{ gap: 8 }}>
            <Icon name="refresh" size={15} />
            {refreshing ? 'Yangilanmoqda…' : 'Yangilash'}
          </button>
        </div>
      </div>

      {/* Jadval strukturasi o'zgargan bo'lsa — ogohlantirish banneri */}
      {structureBad && (
        <div style={{
          background: 'rgba(232,115,95,.10)', border: '1px solid rgba(232,115,95,.35)',
          borderRadius: 'var(--r-lg)', padding: '14px 18px', marginBottom: 16,
          display: 'flex', gap: 12, alignItems: 'flex-start',
        }}>
          <span style={{ flex: 'none', width: 30, height: 30, borderRadius: 8, background: 'rgba(232,115,95,.16)', color: '#C2453A', display: 'grid', placeItems: 'center' }}>
            <Icon name="alert" size={17} />
          </span>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontWeight: 700, fontSize: 13.5, color: '#C2453A' }}>Jadval strukturasi o'zgargan ko'rinadi</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)', margin: '3px 0 8px' }}>
              Quyidagi elementlar topilmadi — shu sababli raqamlar to'liq yoki noto'g'ri chiqishi mumkin. Google Sheet tuzilmasini tekshiring (ustun/qator nomlari) yoki dasturchiga murojaat qiling.
            </div>
            <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12.5, color: 'var(--ink-2)', display: 'grid', gap: 3 }}>
              {warnings.map((w, i) => <li key={i}>{w}</li>)}
            </ul>
          </div>
        </div>
      )}

      {/* 8 ta asosiy raqam — sarlavha kartalar (4×2) */}
      <div className="dash-cards" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 14 }}>
        <SdKpi label="Oylik reja" value={sdShort(k.plan)} sub={sdFull(k.plan) + ' soʼm' + (hasKor ? ` · ${sdKor(totalKor.plan)} kor` : '')} big />
        <SdKpi label="Joriy fakt" value={sdShort(k.fakt)} sub={sdFull(k.fakt) + ' soʼm' + (hasKor ? ` · ${sdKor(totalKor.fakt)} kor` : '')} accent="var(--brand-700)" big />
        <SdKpi label="Bajarilish" value={sdPct(k.pct)} sub={st.label} accent={st.ink} big />
        <SdKpi label="Prognoz" value={sdShort(k.prognoz)} sub={sdPct(k.prognozPct) + ' rejadan' + (hasKor ? ` · ${sdKor(totalKor.prognoz)} kor` : '')} big />
        <SdKpi label="Qolgan reja" value={sdShort(k.remainingPlan)} sub={sdFull(k.remainingPlan) + ' soʼm'} big />
        <SdKpi label="Kunlik kerak" value={sdShort(k.neededPerDay)} sub={`qolgan ${k.remainingDays || 0} kunga`} accent="var(--brand-700)" big />
        <SdKpi label="Oʼrtacha / kun" value={sdShort(k.avgPerElapsed)} sub={`${k.elapsedDays || 0} ish kuni boʼyicha`} big />
        <SdKpi label="AKB" value={sdFull(k.akb)} sub="faol mijozlar bazasi" big />
      </div>

      {/* Karobka (kor) bo'yicha umumiy plan / fakt / prognoz — faqat Iyul+ (kor ma'lumoti bor) */}
      {hasKor && (
        <div className="dash-cards" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 14 }}>
          <SdKpi label="Reja (karobka)" value={sdKor(totalKor.plan)} sub="karobka" />
          <SdKpi label="Fakt (karobka)" value={sdKor(totalKor.fakt)} sub={`bajarilish ${sdPct(totalKor.plan > 0 ? totalKor.fakt / totalKor.plan : 0)}`} accent={totalKor.fakt >= totalKor.plan ? '#1D8A6E' : 'var(--brand-700)'} />
          <SdKpi label="Prognoz (karobka)" value={sdKor(totalKor.prognoz)} sub={`rejadan ${sdPct(totalKor.plan > 0 ? totalKor.prognoz / totalKor.plan : 0)}`} accent="#5B45D6" />
        </div>
      )}

      {/* Ikkilamchi ko'rsatkichlar — yupqa qator */}
      <div style={{
        display: 'flex', flexWrap: 'wrap', gap: '8px 22px', alignItems: 'center',
        background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)',
        padding: '11px 18px', boxShadow: 'var(--sh-1)', marginBottom: 18, fontSize: 12,
      }}>
        <div><span style={{ color: 'var(--ink-4)' }}>Ish kunlari: </span><b className="tnum">{k.elapsedDays || 0} / {k.totalDays || 0}</b> <span style={{ color: 'var(--ink-4)' }}>({k.remainingDays || 0} qoldi)</span></div>
        <div style={{ width: 1, height: 14, background: 'var(--border)' }} />
        <div><span style={{ color: 'var(--ink-4)' }}>Kunlik reja (target): </span><b className="tnum">{sdShort(k.dailyTarget)}</b></div>
        <div style={{ width: 1, height: 14, background: 'var(--border)' }} />
        <div><span style={{ color: 'var(--ink-4)' }}>Davr: </span><b className="tnum">{k.startDate || '—'} – {k.endDate || '—'}</b></div>
        {k.today && <><div style={{ width: 1, height: 14, background: 'var(--border)' }} /><div><span style={{ color: 'var(--ink-4)' }}>Bugun: </span><b className="tnum">{k.today}</b></div></>}
      </div>

      {/* Progress bar + qolgan reja */}
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: '16px 20px', boxShadow: 'var(--sh-1)', marginBottom: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10, flexWrap: 'wrap', gap: 8 }}>
          <div style={{ fontSize: 13, fontWeight: 700 }}>Oylik rejaning bajarilishi</div>
          <div className="tnum" style={{ fontSize: 12.5, color: 'var(--ink-4)' }}>
            {sdShort(k.fakt)} / {sdShort(k.plan)} soʼm
          </div>
        </div>
        <div style={{ height: 14, borderRadius: 8, background: 'var(--bg-soft, rgba(127,127,127,.12))', overflow: 'hidden', position: 'relative' }}>
          {/* Prognoz ko'rsatkichi — ochiq soya */}
          {k.prognozPct > 0 && (
            <div title={'Prognoz: ' + sdPct(k.prognozPct)} style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: Math.min(100, (k.prognozPct || 0) * 100) + '%', borderRadius: 8, background: 'repeating-linear-gradient(45deg, rgba(142,116,255,.18), rgba(142,116,255,.18) 6px, rgba(142,116,255,.08) 6px, rgba(142,116,255,.08) 12px)' }} />
          )}
          <div style={{ position: 'relative', width: Math.min(100, (k.pct || 0) * 100) + '%', height: '100%', borderRadius: 8, background: st.ink, transition: 'width .5s var(--ease)' }} />
        </div>
        <div style={{ display: 'flex', gap: 20, marginTop: 12, flexWrap: 'wrap', fontSize: 12 }}>
          <div><span style={{ color: 'var(--ink-4)' }}>Fakt: </span><b className="tnum" style={{ color: st.ink }}>{sdPct(k.pct)}</b></div>
          <div><span style={{ color: 'var(--ink-4)' }}>Prognoz: </span><b className="tnum" style={{ color: '#5B45D6' }}>{sdPct(k.prognozPct)}</b></div>
          <div><span style={{ color: 'var(--ink-4)' }}>Qolgan reja: </span><b className="tnum">{sdShort(k.remainingPlan)}</b></div>
        </div>
      </div>

      {/* Brendlar + Zonalar — yonma-yon */}
      {(brands || zones.length > 0) && (
        <div style={{ display: 'grid', gridTemplateColumns: brands && zones.length ? '1fr 1fr' : '1fr', gap: 14, marginBottom: 18 }}>
          {brands && (
            <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: '16px 20px', boxShadow: 'var(--sh-1)' }}>
              <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 12 }}>Brend boʼyicha fakt</div>
              {(() => {
                const PAL = ['#EC7A55', '#2B2927', '#3DBE9C', '#E9B949', '#5A9FD4', '#8E74FF'];
                const items = Object.keys(brands).filter((k) => k !== 'other').map((k, i) => {
                  const db = DB.brandByTag(k);
                  return { name: db ? db.name : k.toUpperCase(), val: brands[k] || 0, color: (db && db.color && db.color.startsWith('#')) ? db.color : PAL[i % PAL.length] };
                }).concat([{ name: 'Boshqa', val: brands.other || 0, color: '#A39A90' }]);
                const tot = items.reduce((a, b) => a + b.val, 0) || 1;
                return (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                    {/* Yagona proportsiya chizig'i */}
                    <div style={{ display: 'flex', height: 16, borderRadius: 8, overflow: 'hidden', background: 'var(--bg-soft, rgba(127,127,127,.12))' }}>
                      {items.map((it, i) => (
                        <div key={i} title={it.name + ': ' + sdPct(it.val / tot)} style={{ width: (it.val / tot) * 100 + '%', background: it.color, transition: 'width .5s var(--ease)' }} />
                      ))}
                    </div>
                    {items.map((it, i) => (
                      <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12.5 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <span style={{ width: 10, height: 10, borderRadius: 3, background: it.color, flex: 'none' }} />
                          <span style={{ fontWeight: 600 }}>{it.name}</span>
                        </div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                          <span className="tnum" style={{ color: 'var(--ink-4)' }}>{sdPct(it.val / tot)}</span>
                          <b className="tnum" style={{ minWidth: 64, textAlign: 'right' }}>{sdShort(it.val)}</b>
                        </div>
                      </div>
                    ))}
                  </div>
                );
              })()}
            </div>
          )}
          {zones.length > 0 && (
            <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: '16px 20px', boxShadow: 'var(--sh-1)' }}>
              <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 12 }}>Zona boʼyicha fakt</div>
              {(() => {
                const tot = zones.reduce((a, z) => a + (z.value || 0), 0) || 1;
                const palette = ['#5A9FD4', '#3DBE9C', '#A98CFF', '#E8735F', '#E3A23B'];
                return (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
                    {zones.map((z, i) => (
                      <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5 }}>
                          <span style={{ fontWeight: 600 }}>{z.name}</span>
                          <span><b className="tnum">{sdShort(z.value)}</b> <span style={{ color: 'var(--ink-4)' }} className="tnum">· {sdPct(z.value / tot)}</span></span>
                        </div>
                        <div style={{ height: 9, borderRadius: 6, background: 'var(--bg-soft, rgba(127,127,127,.12))', overflow: 'hidden' }}>
                          <div style={{ width: (z.value / tot) * 100 + '%', height: '100%', borderRadius: 6, background: palette[i % palette.length], transition: 'width .5s var(--ease)' }} />
                        </div>
                      </div>
                    ))}
                  </div>
                );
              })()}
            </div>
          )}
        </div>
      )}

      {/* Kunlik sotuv grafigi */}
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: '16px 20px 12px', boxShadow: 'var(--sh-1)', marginBottom: 18 }}>
        <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 4 }}>Kunlik sotuv</div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginBottom: 10 }}>Har bir ustun — shu kunlik sotuv; rang reja bajarilishini ko'rsatadi</div>
        <SdBarChart daily={daily} dailyTarget={k.dailyTarget} />
      </div>

      {/* Hududlar kartochkalari */}
      {regionsRaw.length > 0 && (() => {
        // Brend kesimi: tanlangan brend bo'yicha region ko'rsatkichlari (byBrand'dan).
        const hasBrandData = regionsRaw.some((r) => r.byBrand && Object.keys(r.byBrand).length > 0);
        const viewRegions = brandView === 'all'
          ? regionsRaw
          : regionsRaw
              .map((r) => sdBrandRegion(r, brandView))
              .filter(Boolean)
              .filter((r) => r.plan > 0 || r.fakt > 0 || r.prognoz > 0);
        return (
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap', marginBottom: 10 }}>
            <div style={{ fontSize: 13, fontWeight: 700 }}>
              Hududlar bo'yicha <span style={{ color: 'var(--ink-4)', fontWeight: 400 }}>({viewRegions.length} ta)</span>
            </div>
            <div style={{ flex: 1 }} />
            {hasBrandData && (
              <div style={{ display: 'inline-flex', gap: 2, padding: 3, borderRadius: 999, background: 'var(--bg-2)', border: '1px solid var(--border)' }}>
                {[['all', 'Hammasi'], ...(DB.BRANDS || []).map((b) => [DB.brandTag(b), b.name])].map(([bk, lbl]) => {
                  const on = brandView === bk;
                  return (
                    <button key={bk} onClick={() => setBrandView(bk)}
                      style={{ border: 'none', cursor: 'pointer', fontSize: 11.5, fontWeight: on ? 800 : 600, padding: '5px 12px', borderRadius: 999,
                               background: on ? 'var(--brand)' : 'transparent', color: on ? '#fff' : 'var(--ink-3)', transition: 'all .15s' }}>
                      {lbl}
                    </button>
                  );
                })}
              </div>
            )}
          </div>
          {viewRegions.length === 0 && (
            <div style={{ fontSize: 12.5, color: 'var(--ink-4)', padding: '10px 0 16px' }}>Bu brend bo'yicha hozircha ma'lumot yo'q.</div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(255px, 1fr))', gap: 12 }}>
            {[...viewRegions].sort((a, b) => (b.plan || 0) - (a.plan || 0)).map((r, i) => {
              const fp = r.pct || 0;           // fakt / plan
              const pp = r.prognozPct || 0;    // prognoz / plan
              // Kun sur'ati: oy davomida qancha o'tgan
              const elapsed = k.totalDays > 0 ? (k.elapsedDays || 0) / k.totalDays : 0;
              // Status: prognoz bo'lsa — prognozga qarab, bo'lmasa — sur'atga qarab
              const score = pp > 0 ? pp : (elapsed > 0 ? fp / elapsed : 0);
              const st = score >= 0.95
                ? { tint: 'rgba(61,190,156,.13)', ink: '#1D8A6E', label: 'Planni yopadi', dot: '#3DBE9C' }
                : score >= 0.75
                ? { tint: 'rgba(227,162,59,.16)', ink: '#A6651E', label: 'Kechikishi mumkin', dot: '#D08A2A' }
                : { tint: 'rgba(232,115,95,.13)', ink: '#C2453A', label: 'Planni yopolmaydi', dot: '#C2453A' };
              // Reja 0 bo'lsa — neytral
              const noData = !r.plan;
              const stFinal = noData
                ? { tint: 'var(--bg-2)', ink: 'var(--ink-4)', label: "Reja yo'q", dot: 'var(--border)' }
                : st;
              const rk = sdRegionKor(r); // karobka (kor): {plan, fakt, prognoz}
              const rHasKor = rk.plan > 0 || rk.fakt > 0 || rk.prognoz > 0;
              return (
                <div key={i} onClick={() => setSelectedRegion(r)} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderTop: `3px solid ${stFinal.dot}`, borderRadius: 'var(--r-lg)', boxShadow: 'var(--sh-1)', padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 10, cursor: 'pointer', transition: 'box-shadow .15s' }}
                  onMouseEnter={(e) => e.currentTarget.style.boxShadow = '0 4px 20px rgba(0,0,0,.12)'}
                  onMouseLeave={(e) => e.currentTarget.style.boxShadow = 'var(--sh-1)'}
                >
                  {/* Sarlavha + status badge */}
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                    <div style={{ fontWeight: 700, fontSize: 12.5, lineHeight: 1.35 }}>{r.name}</div>
                    <span style={{ flexShrink: 0, fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 999, background: stFinal.tint, color: stFinal.ink, whiteSpace: 'nowrap' }}>{stFinal.label}</span>
                  </div>
                  {/* Progress bar: kulrang = reja, to'q = fakt, chiziqli = prognoz */}
                  <div style={{ position: 'relative', height: 8, borderRadius: 4, background: 'var(--bg-soft,rgba(127,127,127,.12))' }}>
                    {pp > 0 && (
                      <div style={{ position: 'absolute', inset: 0, width: Math.min(100, pp * 100) + '%', borderRadius: 4, background: 'repeating-linear-gradient(45deg,rgba(142,116,255,.2),rgba(142,116,255,.2) 5px,rgba(142,116,255,.07) 5px,rgba(142,116,255,.07) 10px)' }} />
                    )}
                    <div style={{ position: 'relative', height: '100%', width: Math.min(100, fp * 100) + '%', borderRadius: 4, background: stFinal.dot, transition: 'width .4s' }} />
                  </div>
                  {/* Uch ustun: Reja | Fakt | Prognoz (summa + karobka) */}
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 4 }}>
                    {[
                      { label: 'Reja', val: sdShort(r.plan), sub: null, color: 'var(--ink-3)', kor: rk.plan },
                      { label: 'Fakt', val: sdShort(r.fakt), sub: sdPct(fp), color: stFinal.ink, kor: rk.fakt },
                      { label: 'Prognoz', val: pp > 0 ? sdShort(r.prognoz) : '—', sub: pp > 0 ? sdPct(pp) : null, color: pp > 0 ? '#5B45D6' : 'var(--ink-4)', kor: rk.prognoz },
                    ].map((col) => (
                      <div key={col.label}>
                        <div style={{ fontSize: 9, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 3 }}>{col.label}</div>
                        <div className="tnum" style={{ fontSize: 12.5, fontWeight: 700, color: col.color }}>{col.val}</div>
                        {col.sub && <div className="tnum" style={{ fontSize: 10, color: col.color, marginTop: 1, opacity: .85 }}>{col.sub}</div>}
                        {rHasKor && <div className="tnum" style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 1 }}>{sdKor(col.kor)} kor</div>}
                      </div>
                    ))}
                  </div>
                  {/* AKB pastki chiziq */}
                  {r.akb > 0 && (
                    <div style={{ fontSize: 10.5, color: 'var(--ink-4)', borderTop: '1px solid var(--border)', paddingTop: 7, marginTop: -2 }}>
                      AKB: <b className="tnum" style={{ color: 'var(--ink-2)' }}>{sdFull(r.akb)}</b>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
        );
      })()}

      {/* Regionlar jadvali */}
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--sh-1)', overflow: 'hidden' }}>
        <div style={{ padding: '14px 20px 10px', fontSize: 13, fontWeight: 700 }}>Regionlar boʼyicha ({regions.length})</div>
        <div style={{ overflowX: 'auto' }}>
          <table className="sd-table" style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, minWidth: 640 }}>
            <thead>
              <tr style={{ textAlign: 'right', color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                <th onClick={() => toggleSort('name')} style={{ textAlign: 'left', padding: '8px 20px', fontWeight: 600, cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap' }}>Region{sortArrow('name')}</th>
                <th onClick={() => toggleSort('plan')} style={{ padding: '8px 12px', fontWeight: 600, cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap' }}>Reja{sortArrow('plan')}</th>
                <th onClick={() => toggleSort('fakt')} style={{ padding: '8px 12px', fontWeight: 600, cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap' }}>Fakt{sortArrow('fakt')}</th>
                <th onClick={() => toggleSort('pct')} style={{ padding: '8px 12px', fontWeight: 600, cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap' }}>Bajarilish{sortArrow('pct')}</th>
                <th onClick={() => toggleSort('share')} style={{ padding: '8px 12px', fontWeight: 600, cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap' }}>Ulush{sortArrow('share')}</th>
                <th onClick={() => toggleSort('prognoz')} style={{ padding: '8px 12px', fontWeight: 600, cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap' }}>Prognoz{sortArrow('prognoz')}</th>
                <th onClick={() => toggleSort('akb')} style={{ padding: '8px 20px', fontWeight: 600, cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap' }}>AKB{sortArrow('akb')}</th>
              </tr>
            </thead>
            <tbody>
              {regions.map((r, i) => {
                const rs = sdStatus(r.pct || 0);
                const rk = sdRegionKor(r); // karobka (kor)
                const rHasKor = rk.plan > 0 || rk.fakt > 0 || rk.prognoz > 0;
                return (
                  <tr key={i} style={{ borderTop: '1px solid var(--border)' }}>
                    <td style={{ textAlign: 'left', padding: '9px 20px', fontWeight: 600 }}>{r.name}</td>
                    <td className="tnum" style={{ textAlign: 'right', padding: '9px 12px', color: 'var(--ink-3)' }}>
                      {sdShort(r.plan)}
                      {rHasKor && <div style={{ fontSize: 10, color: 'var(--ink-4)' }}>{sdKor(rk.plan)} kor</div>}
                    </td>
                    <td className="tnum" style={{ textAlign: 'right', padding: '9px 12px', fontWeight: 600 }}>
                      {sdShort(r.fakt)}
                      {rHasKor && <div style={{ fontSize: 10, color: 'var(--ink-4)', fontWeight: 400 }}>{sdKor(rk.fakt)} kor</div>}
                    </td>
                    <td style={{ textAlign: 'right', padding: '9px 12px' }}>
                      <span className="tnum" style={{ display: 'inline-block', minWidth: 54, textAlign: 'center', padding: '2px 8px', borderRadius: 999, fontWeight: 700, fontSize: 11.5, background: rs.tint, color: rs.ink }}>
                        {sdPct(r.pct)}
                      </span>
                    </td>
                    <td style={{ textAlign: 'right', padding: '9px 12px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 7, justifyContent: 'flex-end' }}>
                        <div style={{ width: 46, height: 6, borderRadius: 4, background: 'var(--bg-soft, rgba(127,127,127,.12))', overflow: 'hidden' }}>
                          <div style={{ width: Math.min(100, (r.share || 0) * 100) + '%', height: '100%', borderRadius: 4, background: 'var(--brand)' }} />
                        </div>
                        <span className="tnum" style={{ color: 'var(--ink-4)', minWidth: 38, textAlign: 'right' }}>{sdPct(r.share)}</span>
                      </div>
                    </td>
                    <td className="tnum" style={{ textAlign: 'right', padding: '9px 12px', color: 'var(--ink-3)' }}>
                      {sdShort(r.prognoz)}
                      {rHasKor && <div style={{ fontSize: 10, color: 'var(--ink-4)' }}>{sdKor(rk.prognoz)} kor</div>}
                    </td>
                    <td className="tnum" style={{ textAlign: 'right', padding: '9px 20px', color: 'var(--ink-3)' }}>{r.akb ? sdFull(r.akb) : '—'}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {err && data && (
        <div style={{ marginTop: 12, fontSize: 12, color: '#C2453A' }}>Yangilashda xatolik: {err}</div>
      )}

      {selectedRegion && (
        <SdRegionModal
          region={selectedRegion}
          elapsed={k.elapsedDays}
          totalDays={k.totalDays}
          onClose={() => setSelectedRegion(null)}
        />
      )}
    </div>
  );
}

window.SheetDashboard = SheetDashboard;

/* ============================================================
   RegionView — oy tanlash wrapper:
   Yanvar–Iyun → SheetDashboard (Google Sheets)
   Iyul–Dekabr → SelloutDashboard (DB)
   ============================================================ */

const REGION_MONTHS = [
  { key: 'yanvar',   label: 'Yanvar' },
  { key: 'fevral',   label: 'Fevral' },
  { key: 'mart',     label: 'Mart' },
  { key: 'aprel',    label: 'Aprel' },
  { key: 'may',      label: 'May' },
  { key: 'iyun',     label: 'Iyun' },
  { key: 'iyul',     label: 'Iyul' },
  { key: 'avgust',   label: 'Avgust' },
];

// Joriy oy kaliti (o'zbek oy nomi)
function currentMonthKey() {
  const keys = ['yanvar','fevral','mart','aprel','may','iyun','iyul','avgust'];
  return keys[new Date().getMonth()] || 'avgust';
}

function RegionView() {
  const [selected, setSelected] = useState(currentMonthKey);
  const cur = REGION_MONTHS.find((m) => m.key === selected) || REGION_MONTHS[6];

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
      {/* Oy tab paneli */}
      <div style={{
        display: 'flex', gap: 4, padding: '10px 20px 0', background: 'var(--surface)',
        borderBottom: '1px solid var(--border)', overflowX: 'auto', flexShrink: 0,
      }}>
        {REGION_MONTHS.map((m) => {
          const active = m.key === selected;
          return (
            <button
              key={m.key}
              onClick={() => setSelected(m.key)}
              style={{
                flex: 'none', padding: '7px 14px', fontSize: 12.5, fontWeight: active ? 700 : 500,
                border: 'none', borderBottom: active ? '2px solid var(--brand)' : '2px solid transparent',
                background: 'transparent', cursor: 'pointer', borderRadius: '4px 4px 0 0',
                color: active ? 'var(--brand)' : 'var(--ink-3)', marginBottom: -1,
              }}
            >
              {m.label}
            </button>
          );
        })}
      </div>

      {/* Kontent */}
      <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
        <SheetDashboard key={cur.key} initialMonth={cur.key} />
      </div>
    </div>
  );
}

window.RegionView = RegionView;
