/* ============================================================
   Region Plan-Fakt 2026 — oylik reja/fakt dashboard
   Oy tanlanadi (Dekabr…Iyun), tanlovga qarab raqamlar o'zgaradi.
   sdShort / sdFull / sdPct / sdStatus — sheetdash.jsx'dan (global).
   ============================================================ */

const PF_REFRESH_MS = 5 * 60 * 1000;
// Tashqi bozorlar dollarda — "$46,995" ko'rinishida
const pfUsd = (v) => '$' + Math.round(Number(v) || 0).toLocaleString('en-US');

function PlanFaktDashboard() {
  // Sahifa keshi — bo'limga qayta kirilganda oldingi ma'lumot darrov ko'rsatiladi.
  const pfCached = window.PageCache ? window.PageCache.get('planfakt') : null;
  const [data, setData] = useState(pfCached || null);
  const [loading, setLoading] = useState(!pfCached);
  const [err, setErr] = useState(null);
  const [refreshing, setRefreshing] = useState(false);
  // Tanlangan oy indeksi — keshdan kelganda ham darrov oxirgi oy ko'rsatiladi.
  const [mi, setMi] = useState(pfCached && (pfCached.months || []).length ? pfCached.months.length - 1 : null);

  async function load(force) {
    if (force) setRefreshing(true); else setLoading(true);
    setErr(null);
    try {
      const res = await API.planFakt(force);
      setData(res);
      if (window.PageCache) window.PageCache.set('planfakt', res);
      setMi((prev) => {
        const n = (res.months || []).length;
        if (n === 0) return null;
        if (prev == null || prev >= n) return n - 1; // oxirgi oy
        return prev;
      });
    } catch (ex) {
      setErr(ex.message || 'Maʼlumotni yuklab boʼlmadi');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }

  useEffect(() => {
    load(false);
    const t = setInterval(() => load(false), PF_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="grid" 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 months = (data && data.months) || [];
  const m = mi != null && months[mi] ? months[mi] : null;
  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 t = (m && m.totals) || { reja: 0, fakt: 0, pct: null };
  const st = sdStatus(t.pct || 0);
  const regions = (m && m.regions) || [];
  // Reja vs fakt grafikida eng katta o'lcham
  const chartMax = Math.max(1, ...regions.slice(0, 12).map((r) => Math.max(r.reja, r.fakt)));

  return (
    <div className="dash-wrap" style={{ padding: '8px 28px 32px', overflowY: 'auto', height: '100%' }}>
      {/* Sarlavha + yangilash */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', margin: '8px 0 14px' }}>
        <div>
          <h2 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-.02em', margin: 0 }}>SELL IN — Region Plan-Fakt 2026</h2>
          <p style={{ fontSize: 12.5, margin: '4px 0 0', color: 'var(--ink-4)' }}>
            Oylik reja va fakt taqqoslamasi · Oxirgi yangilanish: {updatedStr}
          </p>
        </div>
        <button className="btn btn--ghost" onClick={() => load(true)} disabled={refreshing} style={{ gap: 8 }}>
          <Icon name="refresh" size={15} />
          {refreshing ? 'Yangilanmoqda…' : 'Yangilash'}
        </button>
      </div>

      {/* Oy tanlash */}
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 18 }}>
        {months.map((mo, i) => {
          const active = i === mi;
          return (
            <button key={mo.name} type="button" onClick={() => setMi(i)}
              style={{
                padding: '7px 16px', borderRadius: 999, fontSize: 13, fontWeight: 600, cursor: 'pointer',
                border: '1px solid ' + (active ? 'var(--brand)' : 'var(--border)'),
                background: active ? 'var(--brand)' : 'var(--surface)',
                color: active ? '#fff' : 'var(--ink-3)',
                boxShadow: active ? 'var(--sh-1)' : 'none', transition: 'all .15s',
              }}>
              {mo.name}
            </button>
          );
        })}
      </div>

      {!m ? (
        <div style={{ color: 'var(--ink-4)', fontSize: 13 }}>Maʼlumot yoʼq.</div>
      ) : (
        <>
          {/* KPI kartalar */}
          <div className="dash-cards" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 18 }}>
            <SdKpi label={m.name + ' — reja'} value={m.hasPlan ? sdShort(t.reja) : '—'} sub={m.hasPlan ? sdFull(t.reja) + ' soʼm' : 'Reja kiritilmagan'} big />
            <SdKpi label="Fakt" value={sdShort(t.fakt)} sub={sdFull(t.fakt) + ' soʼm'} accent="var(--brand-700)" big />
            <SdKpi label="Bajarilish" value={m.hasPlan ? sdPct(t.pct) : '—'} sub={m.hasPlan ? st.label : 'rejasiz'} accent={m.hasPlan ? st.ink : 'var(--ink-4)'} big />
            <SdKpi label="Regionlar" value={String(regions.length)} sub="ta nuqta" big />
          </div>

          {/* Progress bar (reja bo'lsa) */}
          {m.hasPlan && (
            <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 }}>{m.name} rejaning bajarilishi</div>
                <div className="tnum" style={{ fontSize: 12.5, color: 'var(--ink-4)' }}>{sdShort(t.fakt)} / {sdShort(t.reja)} soʼm</div>
              </div>
              <div style={{ height: 14, borderRadius: 8, background: 'var(--bg-soft, rgba(127,127,127,.12))', overflow: 'hidden' }}>
                <div style={{ width: Math.min(100, (t.pct || 0) * 100) + '%', height: '100%', borderRadius: 8, background: st.ink, transition: 'width .5s var(--ease)' }} />
              </div>
            </div>
          )}

          {/* Reja vs Fakt — region kesimi (top 12) */}
          <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', alignItems: 'center', gap: 16, marginBottom: 12, flexWrap: 'wrap' }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Reja vs Fakt (eng yirik 12 region)</div>
              <div style={{ display: 'flex', gap: 14, fontSize: 11.5, color: 'var(--ink-4)' }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><i style={{ width: 10, height: 10, borderRadius: 3, background: 'var(--border-strong, #c9c9c9)', display: 'inline-block' }} /> Reja</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><i style={{ width: 10, height: 10, borderRadius: 3, background: 'var(--brand)', display: 'inline-block' }} /> Fakt</span>
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {regions.slice(0, 12).map((r, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '130px 1fr 86px', alignItems: 'center', gap: 10 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} title={r.name}>{r.name}</div>
                  <div style={{ position: 'relative', height: 22 }}>
                    {r.reja > 0 && (
                      <div title={'Reja: ' + sdFull(r.reja)} style={{ position: 'absolute', top: 0, left: 0, height: 8, width: Math.max(1, (r.reja / chartMax) * 100) + '%', background: 'var(--border-strong, #c9c9c9)', borderRadius: 4 }} />
                    )}
                    <div title={'Fakt: ' + sdFull(r.fakt)} style={{ position: 'absolute', bottom: 0, left: 0, height: 8, width: Math.max(1, (r.fakt / chartMax) * 100) + '%', background: 'linear-gradient(90deg,var(--brand),var(--brand-700))', borderRadius: 4 }} />
                  </div>
                  <div className="tnum" style={{ fontSize: 11.5, textAlign: 'right', color: 'var(--ink-3)' }}>{sdShort(r.fakt)}</div>
                </div>
              ))}
            </div>
          </div>

          {/* To'liq jadval */}
          <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 }}>
              {m.name} — barcha regionlar ({regions.length})
              {!m.hasPlan && <span style={{ fontWeight: 500, fontSize: 11.5, color: 'var(--ink-4)', marginLeft: 8 }}>· bu oy uchun reja hali kiritilmagan</span>}
            </div>
            <div style={{ overflowX: 'auto' }}>
              <table className="sd-table" style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, minWidth: 560 }}>
                <thead>
                  <tr style={{ textAlign: 'right', color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                    <th style={{ textAlign: 'left', padding: '8px 20px', fontWeight: 600 }}>Region</th>
                    <th style={{ padding: '8px 12px', fontWeight: 600 }}>Reja</th>
                    <th style={{ padding: '8px 12px', fontWeight: 600 }}>Fakt</th>
                    <th style={{ padding: '8px 20px', fontWeight: 600 }}>Bajarilish</th>
                  </tr>
                </thead>
                <tbody>
                  {regions.map((r, i) => {
                    const rs = sdStatus(r.pct || 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)' }}>{r.reja > 0 ? sdShort(r.reja) : '—'}</td>
                        <td className="tnum" style={{ textAlign: 'right', padding: '9px 12px', fontWeight: 600 }}>{sdShort(r.fakt)}</td>
                        <td style={{ textAlign: 'right', padding: '9px 20px' }}>
                          {r.pct == null ? (
                            <span style={{ color: 'var(--ink-4)' }}>—</span>
                          ) : (
                            <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>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>

          {/* Tashqi bozorlar — DOLLARDA (so'm yig'indisiga aralashmaydi) */}
          {m.external && m.external.length > 0 && (
            <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--sh-1)', overflow: 'hidden', marginTop: 18 }}>
              <div style={{ padding: '14px 20px 10px', display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 13, fontWeight: 700 }}>🌍 Tashqi bozorlar ({m.external.length})</span>
                <span style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>· dollarda (USD)</span>
                <div style={{ flex: 1 }} />
                <span className="tnum" style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--brand-700)' }}>Jami fakt: {pfUsd(m.externalTotals ? m.externalTotals.fakt : 0)}</span>
              </div>
              <div style={{ overflowX: 'auto' }}>
                <table className="sd-table" style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, minWidth: 480 }}>
                  <thead>
                    <tr style={{ textAlign: 'right', color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                      <th style={{ textAlign: 'left', padding: '8px 20px', fontWeight: 600 }}>Bozor</th>
                      <th style={{ padding: '8px 12px', fontWeight: 600 }}>Reja ($)</th>
                      <th style={{ padding: '8px 12px', fontWeight: 600 }}>Fakt ($)</th>
                      <th style={{ padding: '8px 20px', fontWeight: 600 }}>Bajarilish</th>
                    </tr>
                  </thead>
                  <tbody>
                    {m.external.map((r, i) => {
                      const rs = sdStatus(r.pct || 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)' }}>{r.reja > 0 ? pfUsd(r.reja) : '—'}</td>
                          <td className="tnum" style={{ textAlign: 'right', padding: '9px 12px', fontWeight: 600 }}>{pfUsd(r.fakt)}</td>
                          <td style={{ textAlign: 'right', padding: '9px 20px' }}>
                            {r.pct == null ? <span style={{ color: 'var(--ink-4)' }}>—</span> : (
                              <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>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}

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

window.PlanFaktDashboard = PlanFaktDashboard;

/* ============================================================
   PlanFaktView — SELL IN wrapper (SELL OUT'dagi RegionView bilan bir xil g'oya):
   • "Oldingi oylar" → PlanFaktDashboard (Region Plan-Fakt 2026, o'zgarishsiz)
   • "Iyul"          → SheetDashboard section="sellin" ("Pervichka - IYUL" jadvali,
                        HUDUD → Brend → SKU → karobka/summa batafsil ko'rinishi)
   ============================================================ */
function PlanFaktView() {
  // Iyul+ (2026-07 dan) — batafsil oylik ko'rinish; sukut bo'yicha JORIY oy ochiladi.
  const mo = new Date().getMonth(); // 0-based; 6=Iyul, 7=Avgust
  const defaultMode = mo >= 7 ? 'avgust' : mo === 6 ? 'iyul' : 'old';
  const [mode, setMode] = useState(defaultMode);

  const tabs = [
    { key: 'old', label: 'Oldingi oylar' },
    { key: 'iyul', label: 'Iyul' },
    { key: 'avgust', label: 'Avgust' },
  ];

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
      {/* Bo'lim tab paneli */}
      <div style={{
        display: 'flex', gap: 4, padding: '10px 20px 0', background: 'var(--surface)',
        borderBottom: '1px solid var(--border)', overflowX: 'auto', flexShrink: 0,
      }}>
        {tabs.map((t) => {
          const active = t.key === mode;
          return (
            <button
              key={t.key}
              onClick={() => setMode(t.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,
              }}
            >
              {t.label}
            </button>
          );
        })}
      </div>

      {/* Kontent */}
      <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
        {mode === 'iyul'
          ? <SheetDashboard key="sellin-iyul" section="sellin" initialMonth="iyul" />
          : mode === 'avgust'
          ? <SheetDashboard key="sellin-avgust" section="sellin" initialMonth="avgust" />
          : <PlanFaktDashboard />}
      </div>
    </div>
  );
}

window.PlanFaktView = PlanFaktView;
