/* ============================================================
   Storecheck — viloyat bo'yicha do'kon tekshiruvi (assortiment + konkurentlar).
   Qog'oz shablon rasmi yuklanadi → AI uni digital matritsaga o'tkazadi →
   tahrirlanadi va saqlanadi. Bo'lim ichida alohida Dashboard bor.
   Ruxsat: super admin (hamma viloyat) + regional menejer (o'z viloyat(lar)i).
   ============================================================ */

// Foydalanuvchining ko'ra oladigan viloyatlari (super — hammasi).
function scRegionOptions(user) {
  const role = (DB.ROLES && DB.ROLES[user.role]) || {};
  const isSuper = !!role.super;
  if (isSuper) return DB.REGIONS;
  let ids = (user.regions && user.regions.length) ? user.regions : [];
  if (!ids.length && DB.userRegionIds) ids = DB.userRegionIds(user.id) || [];
  return DB.REGIONS.filter((r) => ids.includes(r.id));
}

function scIsSuper(user) {
  const role = (DB.ROLES && DB.ROLES[user.role]) || {};
  return !!role.super;
}

// PDF (skaner) birinchi sahifasini siqilgan JPEG data URL ga aylantiradi.
async function scPdfToDataURL(file) {
  if (!window.pdfjsLib) throw new Error('PDF qo‘llab-quvvatlanmadi — JPG yoki PNG yuklang');
  try {
    if (!window.pdfjsLib.GlobalWorkerOptions.workerSrc) {
      window.pdfjsLib.GlobalWorkerOptions.workerSrc =
        'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
    }
    const buf = await file.arrayBuffer();
    const pdf = await window.pdfjsLib.getDocument({ data: buf }).promise;
    const page = await pdf.getPage(1);
    const base = page.getViewport({ scale: 1 });
    const scale = Math.min(3, Math.max(1, 1568 / Math.max(base.width, base.height)));
    const viewport = page.getViewport({ scale });
    const canvas = document.createElement('canvas');
    canvas.width = Math.round(viewport.width);
    canvas.height = Math.round(viewport.height);
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = '#fff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    await page.render({ canvasContext: ctx, viewport }).promise;
    return canvas.toDataURL('image/jpeg', 0.9);
  } catch (e) {
    throw new Error('PDF ni o‘qib bo‘lmadi — JPG yoki PNG ko‘rinishida yuklang');
  }
}

// DOCX ichidagi birinchi rasmni ajratib olib JPEG data URL ga aylantiradi.
async function scDocxToDataURL(file) {
  if (!window.JSZip) throw new Error('DOCX qo‘llab-quvvatlanmadi — rasm yoki PDF yuklang');
  let zip;
  try {
    zip = await window.JSZip.loadAsync(file);
  } catch (e) {
    throw new Error('DOCX ni o‘qib bo‘lmadi — rasm yoki PDF yuklang');
  }
  const names = Object.keys(zip.files || {})
    .filter((n) => /^word\/media\/.*\.(png|jpe?g|gif|bmp|webp)$/i.test(n))
    .sort();
  if (!names.length) throw new Error('DOCX ichida rasm topilmadi — jadval rasmini PDF yoki JPG qilib yuboring');
  const name = names[0];
  const ext = (name.split('.').pop() || '').toLowerCase();
  const mime = ext === 'png' ? 'image/png'
    : ext === 'gif' ? 'image/gif'
    : ext === 'bmp' ? 'image/bmp'
    : ext === 'webp' ? 'image/webp'
    : 'image/jpeg';
  const blob = await zip.files[name].async('blob');
  const f = new File([blob], 'docx-image.' + ext, { type: mime });
  return await fileToDataURL(f, 1568, 'image/jpeg', 0.9);
}

// Faylni (rasm/HEIC/PDF/DOCX) siqilgan JPEG data URL ga aylantiradi.
// 1) PDF  -> pdf.js bilan 1-sahifani rasmga aylantiramiz.
// 2) DOCX -> JSZip bilan ichidagi rasmni ajratamiz.
// 3) Rasm -> avval brauzer dekoderi, bo'lmasa heic2any (HEIC/HEIF) bilan.
async function scLoadImageDataURL(file) {
  const name = (file && file.name) || '';
  const type = (file && file.type) || '';
  const isPdf = type === 'application/pdf' || /\.pdf$/i.test(name);
  const isDocx = /officedocument\.wordprocessingml/i.test(type) || /\.docx$/i.test(name);
  if (isPdf) return await scPdfToDataURL(file);
  if (isDocx) return await scDocxToDataURL(file);
  try {
    return await fileToDataURL(file, 1568, 'image/jpeg', 0.9);
  } catch (_) {
    const isHeic = /heic|heif/i.test(type) || /\.(heic|heif)$/i.test(name);
    if (!isHeic) throw new Error('Rasmni o‘qib bo‘lmadi — boshqa rasm tanlang');
    if (typeof window.heic2any !== 'function') {
      throw new Error('HEIC qo‘llab-quvvatlanmadi — JPG yuklang yoki ekran skrinshotini oling');
    }
    let blob;
    try {
      const out = await window.heic2any({ blob: file, toType: 'image/jpeg', quality: 0.92 });
      blob = Array.isArray(out) ? out[0] : out;
    } catch (e) {
      throw new Error('Bu HEIC faylni o‘girib bo‘lmadi — telefonda JPG qilib yuboring yoki skrinshot oling');
    }
    const f = new File([blob], 'image.jpg', { type: 'image/jpeg' });
    return await fileToDataURL(f, 1568, 'image/jpeg', 0.9);
  }
}

/* ---------- Bitta katak (bor / yo'q) ---------- */
function SCcell({ on, onToggle, type }) {
  const color = type === 'competitor' ? '#C2453A' : 'var(--brand)';
  return (
    <button onClick={onToggle} title={on ? "Bor — bosib olib tashlash" : "Yo'q — bosib belgilash"}
      style={{
        width: 30, height: 30, flex: 'none', display: 'grid', placeItems: 'center', cursor: 'pointer',
        border: '1px solid var(--border)', borderRadius: 7,
        background: on ? color : 'var(--bg-2)', color: on ? '#fff' : 'var(--ink-4)',
        fontWeight: 800, fontSize: 13, transition: 'all .12s var(--ease)',
      }}>
      {on ? '+' : ''}
    </button>
  );
}

/* ---------- Raqamli jadval (do'konlar × ustunlar) ---------- */
function SCgrid({ columns, rows, setRows, editable = true }) {
  function toggle(ri, key) {
    if (!editable) return;
    setRows((prev) => prev.map((r, i) => {
      if (i !== ri) return r;
      const cells = { ...(r.cells || {}) };
      if (cells[key]) delete cells[key]; else cells[key] = true;
      return { ...r, cells };
    }));
  }
  function setStore(ri, val) {
    setRows((prev) => prev.map((r, i) => (i === ri ? { ...r, store: val } : r)));
  }
  function removeRow(ri) {
    setRows((prev) => prev.filter((_, i) => i !== ri));
  }
  function addRow() {
    setRows((prev) => [...prev, { store: '', cells: {} }]);
  }

  const NAMEW = 180;
  return (
    <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--r)', overflow: 'auto', maxHeight: '52vh' }}>
      <div style={{ display: 'inline-block', minWidth: '100%' }}>
        {/* Sarlavha qatori */}
        <div style={{ display: 'flex', position: 'sticky', top: 0, zIndex: 3, background: 'var(--surface)', borderBottom: '2px solid var(--border)' }}>
          <div style={{ width: NAMEW, flex: 'none', position: 'sticky', left: 0, zIndex: 4, background: 'var(--surface)',
                        padding: '8px 10px', fontWeight: 700, fontSize: 12.5, borderRight: '1px solid var(--border)' }}>
            Do'kon
          </div>
          {columns.map((c) => (
            <div key={c.key} title={c.label}
              style={{ width: 34, flex: 'none', padding: '6px 2px', display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
                       borderRight: '1px solid var(--border-2, var(--border))' }}>
              <span style={{ writingMode: 'vertical-rl', transform: 'rotate(180deg)', whiteSpace: 'nowrap',
                             fontSize: 11, fontWeight: 600, maxHeight: 130, overflow: 'hidden', textOverflow: 'ellipsis',
                             color: c.type === 'competitor' ? '#C2453A' : 'var(--ink-2)' }}>
                {c.label}
              </span>
            </div>
          ))}
          {editable && <div style={{ width: 34, flex: 'none' }} />}
        </div>

        {/* Ma'lumot qatorlari */}
        {rows.map((r, ri) => (
          <div key={ri} style={{ display: 'flex', borderBottom: '1px solid var(--border)' }}>
            <div style={{ width: NAMEW, flex: 'none', position: 'sticky', left: 0, zIndex: 2, background: 'var(--surface)',
                          borderRight: '1px solid var(--border)', padding: 3, display: 'flex', alignItems: 'center', gap: 4 }}>
              {editable ? (
                <input className="input" value={r.store} placeholder={"Do'kon nomi…"} onChange={(e) => setStore(ri, e.target.value)}
                  style={{ height: 28, fontSize: 12.5, padding: '4px 7px' }} />
              ) : (
                <span style={{ fontSize: 12.5, fontWeight: 600, padding: '4px 6px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.store}</span>
              )}
            </div>
            {columns.map((c) => (
              <div key={c.key} style={{ width: 34, flex: 'none', display: 'grid', placeItems: 'center', padding: 2,
                                        borderRight: '1px solid var(--border-2, var(--border))' }}>
                <SCcell on={!!(r.cells && r.cells[c.key])} type={c.type} onToggle={() => toggle(ri, c.key)} />
              </div>
            ))}
            {editable && (
              <div style={{ width: 34, flex: 'none', display: 'grid', placeItems: 'center' }}>
                <button className="btn btn--icon btn--ghost" title="Qatorni o'chirish" onClick={() => removeRow(ri)} style={{ color: '#C2453A', width: 26, height: 26 }}>
                  <Icon name="x" size={14} />
                </button>
              </div>
            )}
          </div>
        ))}

        {rows.length === 0 && (
          <div style={{ padding: 20, textAlign: 'center', color: 'var(--ink-4)', fontSize: 12.5 }}>Hozircha do'kon yo'q</div>
        )}
      </div>
      {editable && (
        <div style={{ padding: 8, borderTop: '1px solid var(--border)', position: 'sticky', left: 0 }}>
          <button className="btn btn--ghost" style={{ height: 32 }} onClick={addRow}>
            <Icon name="plus" size={14} stroke={2.4} /> Do'kon qo'shish
          </button>
        </div>
      )}
    </div>
  );
}

/* ---------- Yangi yoki mavjud tekshiruv modali ---------- */
function StoreCheckModal({ initial, user, regionOpts, onClose, onSaved, onDeleted, showToast }) {
  const isNew = !initial.id;
  const [regionId, setRegionId] = useState(initial.regionId || (regionOpts[0] && regionOpts[0].id) || '');
  const [territory, setTerritory] = useState(initial.territory || '');
  const [agent, setAgent] = useState(initial.agent || '');
  const [columns, setColumns] = useState(initial.columns || []);
  const [rows, setRows] = useState(initial.rows || []);
  const [image, setImage] = useState(initial.image || null);
  const [note, setNote] = useState(initial.note || '');
  const [aiNote, setAiNote] = useState(initial.aiNote || '');
  const [parsed, setParsed] = useState(!isNew || (initial.columns && initial.columns.length));
  const [busy, setBusy] = useState(false);
  const [parsing, setParsing] = useState(false);
  const fileRef = useRef(null);

  async function pickImage(file) {
    if (!file) return;
    setParsing(true); // HEIC konvertatsiya + tahlil davomida indikator
    try {
      // Aniqlik uchun yuqoriroq o'lcham/sifat (Anthropic ~1568px gacha ishlatadi)
      const dataUrl = await scLoadImageDataURL(file);
      setImage(dataUrl);
      // Yangi tekshiruvda rasm yuklanishi bilan avtomatik raqamlashtiramiz
      if (isNew && regionId) { runParse(dataUrl); return; }
    } catch (ex) { showToast((ex && ex.message) || 'Rasmni o‘qib bo‘lmadi'); }
    setParsing(false);
  }

  async function runParse(imgArg) {
    const img = imgArg || image;
    if (!regionId) return showToast('Avval viloyatni tanlang');
    if (!img) return showToast('Avval shablon rasmini yuklang');
    setParsing(true);
    try {
      const { draft } = await API.parseStoreCheck(regionId, img);
      setColumns(draft.columns || []);
      setRows(draft.rows || []);
      if (draft.territory) setTerritory(draft.territory);
      if (draft.agent) setAgent(draft.agent);
      setAiNote(draft.aiNote || '');
      setParsed(true);
      showToast(draft.aiNote ? "Raqamlashtirildi — AI izohni o‘qing" : 'Rasm raqamlashtirildi — tekshirib chiqing');
    } catch (ex) {
      showToast((ex && ex.message) || 'Raqamlashtirishda xatolik');
    } finally { setParsing(false); }
  }

  // Qo'lda kiritish — rasm shart emas. Standart ustunlar (assortiment + konkurent)
  // serverdan yuklanadi (konkurentlar tepa qatorda avtomatik chiqadi), bo'sh qator qo'yiladi.
  async function startManual() {
    setParsing(true);
    try {
      let cols = columns;
      if (!cols || !cols.length) {
        const meta = await API.storeCheckColumns();
        cols = meta.columns || [];
      }
      if (!cols.length) return showToast("Ustunlarni yuklab bo'lmadi");
      setColumns(cols);
      setRows((prev) => (prev && prev.length ? prev : [{ store: '', cells: {} }]));
      setParsed(true);
    } catch (ex) { showToast((ex && ex.message) || "Ustunlarni yuklab bo'lmadi"); }
    finally { setParsing(false); }
  }

  // Konkurent ustunini ushbu tekshiruvga qo'shish (tepa qatorga yangi konkurent).
  function addCompetitor() {
    const label = (window.prompt('Yangi konkurent nomi:') || '').trim();
    if (!label) return;
    setColumns((prev) => {
      const base = label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'konkurent';
      const used = new Set((prev || []).map((c) => c.key));
      let key = base, i = 2;
      while (used.has(key)) key = base + '-' + (i++);
      return [...(prev || []), { key, label, type: 'competitor' }];
    });
  }

  async function save() {
    if (!regionId) return showToast('Viloyat tanlang');
    setBusy(true);
    try {
      const payload = { regionId, territory: territory || null, agent: agent || null, image: image || null, columns, rows, note: note || null };
      if (isNew) {
        const { storeCheck } = await API.createStoreCheck(payload);
        showToast('Tekshiruv saqlandi');
        onSaved(storeCheck);
      } else {
        const { storeCheck } = await API.updateStoreCheck(initial.id, payload);
        showToast('Saqlandi');
        onSaved(storeCheck);
      }
      onClose();
    } catch (ex) { showToast((ex && ex.message) || 'Saqlashda xatolik'); setBusy(false); }
  }

  async function remove() {
    if (!window.confirm("Bu tekshiruvni o'chirishni tasdiqlaysizmi?")) return;
    setBusy(true);
    try {
      await API.deleteStoreCheck(initial.id);
      showToast("Tekshiruv o'chirildi");
      onDeleted(initial.id);
      onClose();
    } catch (ex) { showToast((ex && ex.message) || 'O‘chirishda xatolik'); setBusy(false); }
  }

  return (
    <Modal onClose={onClose} width={920}>
      <ModalHeader title={isNew ? 'Yangi tekshiruv' : 'Tekshiruvni tahrirlash'}
        subtitle="Shablon rasmidan avtomatik raqamli versiya" onClose={onClose} />
      <div style={{ padding: 20, overflow: 'auto' }}>
        {/* Yuqori maydonlar */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: 12, marginBottom: 16 }}>
          <label style={{ display: 'block' }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 5 }}>Viloyat *</div>
            <select className="input" value={regionId} onChange={(e) => setRegionId(e.target.value)} style={{ width: '100%' }}>
              <option value="">— tanlang —</option>
              {regionOpts.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
            </select>
          </label>
          <label style={{ display: 'block' }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 5 }}>Hudud (Тер-я)</div>
            <input className="input" value={territory} onChange={(e) => setTerritory(e.target.value)} style={{ width: '100%' }} />
          </label>
          <label style={{ display: 'block' }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 5 }}>Savdo vakili (Т.П)</div>
            <input className="input" value={agent} onChange={(e) => setAgent(e.target.value)} style={{ width: '100%' }} />
          </label>
        </div>

        {/* Rasm yuklash / raqamlashtirish */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
          <input ref={fileRef} type="file" accept="image/*,.heic,.heif,.pdf,.docx,application/pdf" style={{ display: 'none' }} onChange={(e) => pickImage(e.target.files && e.target.files[0])} />
          {image ? (
            <img src={image} alt="shablon" style={{ height: 80, borderRadius: 8, border: '1px solid var(--border)', cursor: 'pointer' }}
              onClick={() => fileRef.current && fileRef.current.click()} title="Boshqa rasm tanlash" />
          ) : (
            <button className="btn btn--ghost" style={{ height: 64, width: 120, flexDirection: 'column', gap: 4 }} onClick={() => fileRef.current && fileRef.current.click()}>
              <Icon name="upload" size={20} /> <span style={{ fontSize: 12 }}>Shablon rasmi</span>
            </button>
          )}
          {isNew && (
            <button className="btn btn--primary" style={{ height: 40 }} onClick={() => runParse()} disabled={parsing || !image}>
              {parsing ? <><Icon name="refresh" size={15} /> Tahlil qilinmoqda…</> : <><Icon name="sparkle" size={15} /> {parsed ? 'Qayta raqamlashtirish' : 'Rasmni raqamlashtirish'}</>}
            </button>
          )}
          {isNew && !parsed && (
            <button className="btn btn--ghost" style={{ height: 40 }} onClick={startManual} disabled={parsing}>
              <Icon name="edit" size={15} /> Qo'lda kiritish
            </button>
          )}
          {image && <span style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>Rasm yuklansa kataklar avtomatik to'ldiriladi · original saqlanadi</span>}
        </div>

        {/* Jadval */}
        {parsed ? (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, flexWrap: 'wrap' }}>
              <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>Do'kon nomini o'zingiz yozing · tepa qatordagi konkurentlar avtomatik chiqadi</span>
              <div style={{ flex: 1 }} />
              <button className="btn btn--ghost" style={{ height: 32, color: '#C2453A' }} onClick={addCompetitor}>
                <Icon name="plus" size={14} stroke={2.4} /> Konkurent ustun qo'shish
              </button>
            </div>
            <SCgrid columns={columns} rows={rows} setRows={setRows} editable />
          </>
        ) : (
          <div style={{ border: '1px dashed var(--border)', borderRadius: 'var(--r)', padding: 28, textAlign: 'center', color: 'var(--ink-4)', fontSize: 13 }}>
            {parsing ? 'Yuklanmoqda — kataklar tayyorlanmoqda…'
                     : "Viloyat tanlab, shablon rasmini yuklang (avtomatik raqamlashtiriladi) yoki “Qo'lda kiritish” ni bosing."}
          </div>
        )}

        {/* AI izoh — raqamlashtirishda muammo bo'lsa */}
        {parsed && aiNote && (
          <div style={{ marginTop: 12, padding: '10px 12px', background: 'rgba(231,160,46,.12)',
                        border: '1px solid rgba(231,160,46,.45)', borderRadius: 'var(--r)', display: 'flex', gap: 9 }}>
            <span style={{ color: '#A6651E', flex: 'none', marginTop: 1, display: 'inline-flex' }}><Icon name="alert" size={15} /></span>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)', whiteSpace: 'pre-wrap', lineHeight: 1.5 }}>
              <b>AI izoh:</b> {aiNote}
            </div>
          </div>
        )}

        {parsed && (
          <label style={{ display: 'block', marginTop: 14 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 5 }}>Izoh</div>
            <textarea className="input" rows={2} value={note} onChange={(e) => setNote(e.target.value)} style={{ width: '100%' }} />
          </label>
        )}
      </div>

      {/* Footer */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 20px', borderTop: '1px solid var(--border)' }}>
        {!isNew && (
          <button className="btn btn--ghost" style={{ color: '#C2453A' }} onClick={remove} disabled={busy}>
            <Icon name="trash" size={15} /> O'chirish
          </button>
        )}
        <div style={{ flex: 1 }} />
        <button className="btn btn--ghost" onClick={onClose}>Bekor qilish</button>
        <button className="btn btn--primary" onClick={save} disabled={busy || !parsed}>
          <Icon name="check" size={15} stroke={2.4} /> Saqlash
        </button>
      </div>
    </Modal>
  );
}

/* ---------- Konkurentlar ro'yxati (faqat super) ---------- */
function CompetitorsModal({ onClose, showToast, onUpdated }) {
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    API.storeCheckColumns()
      .then((d) => setList((d.competitors || []).map((c) => c.label)))
      .catch((ex) => showToast((ex && ex.message) || 'Yuklashda xatolik'))
      .finally(() => setLoading(false));
  }, []);

  function setItem(i, v) { setList((p) => p.map((x, idx) => (idx === i ? v : x))); }
  function removeItem(i) { setList((p) => p.filter((_, idx) => idx !== i)); }
  function addItem() { setList((p) => [...p, '']); }

  async function save() {
    setBusy(true);
    try {
      const clean = list.map((x) => x.trim()).filter(Boolean);
      const { competitors } = await API.updateCompetitors(clean);
      showToast('Konkurentlar yangilandi');
      onUpdated && onUpdated(competitors);
      onClose();
    } catch (ex) { showToast((ex && ex.message) || 'Saqlashda xatolik'); setBusy(false); }
  }

  return (
    <Modal onClose={onClose} width={440}>
      <ModalHeader title="Konkurentlar ro'yxati" subtitle="Storecheck jadvalidagi konkurent ustunlari" onClose={onClose} />
      <div style={{ padding: 18, overflow: 'auto', maxHeight: '60vh' }}>
        {loading ? <Empty icon="box" text="Yuklanmoqda…" /> : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {list.map((c, i) => (
              <div key={i} style={{ display: 'flex', gap: 8 }}>
                <input className="input" value={c} onChange={(e) => setItem(i, e.target.value)} style={{ flex: 1 }} placeholder="Brend nomi…" />
                <button className="btn btn--icon btn--ghost" onClick={() => removeItem(i)} style={{ color: '#C2453A' }} title="O'chirish"><Icon name="x" size={15} /></button>
              </div>
            ))}
            <button className="btn btn--ghost" style={{ height: 34, alignSelf: 'flex-start' }} onClick={addItem}>
              <Icon name="plus" size={14} stroke={2.4} /> Qo'shish
            </button>
          </div>
        )}
      </div>
      <div style={{ display: 'flex', gap: 10, padding: '14px 18px', borderTop: '1px solid var(--border)', justifyContent: 'flex-end' }}>
        <button className="btn btn--ghost" onClick={onClose}>Bekor qilish</button>
        <button className="btn btn--primary" onClick={save} disabled={busy || loading}><Icon name="check" size={15} stroke={2.4} /> Saqlash</button>
      </div>
    </Modal>
  );
}

/* ---------- Foiz qatori (bar) ---------- */
function SCbar({ label, pct, color }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '5px 0' }}>
      <div style={{ width: 150, flex: 'none', fontSize: 12.5, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={label}>{label}</div>
      <div style={{ flex: 1, height: 9, background: 'var(--bg-2)', borderRadius: 100, overflow: 'hidden' }}>
        <div style={{ width: pct + '%', height: '100%', background: color, borderRadius: 100, transition: 'width .3s var(--ease)' }} />
      </div>
      <div className="tnum" style={{ width: 46, flex: 'none', textAlign: 'right', fontSize: 12.5, fontWeight: 700 }}>{pct}%</div>
    </div>
  );
}

/* ---------- Dashboard ---------- */
function SCdashboard({ showToast }) {
  const scDashCached = window.PageCache ? window.PageCache.get('storecheck:dash') : null;
  const [data, setData] = useState(scDashCached || null);
  const [loading, setLoading] = useState(!scDashCached);

  useEffect(() => {
    API.storeCheckDashboard()
      .then((d) => { setData(d); if (window.PageCache) window.PageCache.set('storecheck:dash', d); })
      .catch((ex) => { if (!scDashCached) showToast((ex && ex.message) || 'Yuklashda xatolik'); })
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-4)', fontSize: 13 }}>Yuklanmoqda…</div>;
  if (!data) return <Empty icon="chart" text="Ma'lumot yo'q" />;

  const card = (label, value) => (
    <div style={{ flex: '1 1 140px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r)', padding: '14px 16px' }}>
      <div style={{ fontSize: 12, color: 'var(--ink-4)', fontWeight: 600 }}>{label}</div>
      <div className="tnum" style={{ fontSize: 26, fontWeight: 800, marginTop: 2 }}>{value}</div>
    </div>
  );

  return (
    <div style={{ padding: '4px 22px 24px', overflow: 'auto' }}>
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 18 }}>
        {card('Tekshiruvlar', data.summary.checks)}
        {card("Do'konlar", data.summary.stores)}
        {card('Viloyatlar', data.summary.regions)}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 16 }}>
        {/* Assortiment qamrovi */}
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r)', padding: 16 }}>
          <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 8 }}>Assortiment qamrovi</div>
          {(data.assortment || []).length === 0 ? <Empty icon="box" text="Ma'lumot yo'q" /> :
            (data.assortment || []).map((c) => <SCbar key={c.key} label={c.label} pct={c.pct} color="var(--brand)" />)}
        </div>

        {/* Konkurentlar mavjudligi */}
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r)', padding: 16 }}>
          <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 8 }}>Konkurentlar mavjudligi</div>
          {(data.competitors || []).length === 0 ? <Empty icon="box" text="Ma'lumot yo'q" /> :
            (data.competitors || []).map((c) => <SCbar key={c.key} label={c.label} pct={c.pct} color="#C2453A" />)}
        </div>

        {/* Viloyatlar kesimi */}
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r)', padding: 16 }}>
          <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 8 }}>Viloyatlar kesimi</div>
          {(data.byRegion || []).length === 0 ? <Empty icon="pin" text="Ma'lumot yo'q" /> : (
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
              <thead><tr style={{ color: 'var(--ink-4)', textAlign: 'left' }}>
                <th style={{ padding: '4px 0' }}>Viloyat</th>
                <th style={{ padding: '4px 0', textAlign: 'right' }}>Tekshiruv</th>
                <th style={{ padding: '4px 0', textAlign: 'right' }}>Do'kon</th>
              </tr></thead>
              <tbody>
                {(data.byRegion || []).map((r) => (
                  <tr key={r.regionId} style={{ borderTop: '1px solid var(--border)' }}>
                    <td style={{ padding: '6px 0', fontWeight: 600 }}>{r.name}</td>
                    <td className="tnum" style={{ padding: '6px 0', textAlign: 'right' }}>{r.checks}</td>
                    <td className="tnum" style={{ padding: '6px 0', textAlign: 'right' }}>{r.stores}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------- Bitta saqlangan tekshiruv kartasi ---------- */
function SCcard({ sc, onOpen }) {
  return (
    <button onClick={() => onOpen(sc)}
      style={{ textAlign: 'left', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r)',
               padding: 14, cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 6, transition: 'box-shadow .15s' }}
      onMouseEnter={(e) => (e.currentTarget.style.boxShadow = 'var(--sh-2)')}
      onMouseLeave={(e) => (e.currentTarget.style.boxShadow = 'none')}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ color: 'var(--brand)', display: 'inline-flex' }}><Icon name="pin" size={15} /></span>
        <span style={{ fontWeight: 700, fontSize: 14 }}>{DB.regionName ? DB.regionName(sc.regionId) : sc.regionId}</span>
      </div>
      <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>
        {sc.territory ? sc.territory + ' · ' : ''}{sc.agent || ''}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>
        <span><b className="tnum" style={{ color: 'var(--ink-2)' }}>{sc.storeCount}</b> do'kon</span>
        <span>{new Date(sc.createdAt).toLocaleDateString('uz')}</span>
      </div>
    </button>
  );
}

/* ============================================================
   Asosiy bo'lim
   ============================================================ */
function Storecheck({ user, showToast }) {
  const [tab, setTab] = useState('list');         // 'list' | 'dashboard'
  const [checks, setChecks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState(null);   // tekshiruv obyekti yoki {} (yangi)
  const [compOpen, setCompOpen] = useState(false);

  const isSuper = scIsSuper(user);
  const regionOpts = scRegionOptions(user);

  // SWR: keshdan darhol ko'rsatamiz, fonda serverdan yangilaymiz
  const load = useCallback(async () => {
    const cached = window.PageCache ? window.PageCache.get('storecheck:list') : null;
    if (cached) { setChecks(cached); setLoading(false); }
    else setLoading(true);
    try {
      const { storeChecks } = await API.listStoreChecks();
      setChecks(storeChecks || []);
      if (window.PageCache) window.PageCache.set('storecheck:list', storeChecks || []);
    }
    catch (ex) { if (!cached) showToast((ex && ex.message) || 'Yuklashda xatolik'); }
    finally { setLoading(false); }
  }, [showToast]);

  useEffect(() => { load(); }, [load]);

  async function openCheck(sc) {
    // To'liq versiyani (rasm bilan) yuklab tahrirlash
    try {
      const { storeCheck } = await API.getStoreCheck(sc.id);
      setEditing(storeCheck);
    } catch (ex) { showToast((ex && ex.message) || 'Ochishda xatolik'); }
  }

  function onSaved(sc) {
    setChecks((prev) => {
      const idx = prev.findIndex((x) => x.id === sc.id);
      const lite = { ...sc, storeCount: (sc.rows || []).length };
      delete lite.image;
      const next = idx === -1 ? [lite, ...prev] : prev.map((x, i) => (i === idx ? lite : x));
      if (window.PageCache) window.PageCache.set('storecheck:list', next);
      return next;
    });
  }
  function onDeleted(id) {
    setChecks((prev) => {
      const next = prev.filter((x) => x.id !== id);
      if (window.PageCache) window.PageCache.set('storecheck:list', next);
      return next;
    });
  }

  return (
    <>
      {/* Toolbar */}
      <div className="board-toolbar" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 22px 12px', flexWrap: 'wrap' }}>
        <div>
          <h2 style={{ fontSize: 18, fontWeight: 800, letterSpacing: '-.02em', margin: 0 }}>Storecheck</h2>
          <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>{checks.length} ta tekshiruv · assortiment va konkurentlar</div>
        </div>
        <div style={{ flex: 1 }} />
        {/* Tab tugmalari */}
        <div style={{ display: 'inline-flex', background: 'var(--bg-2)', borderRadius: 'var(--r-sm)', padding: 3, gap: 3 }}>
          {[['list', 'Tekshiruvlar', 'board'], ['dashboard', 'Dashboard', 'chart']].map(([k, lbl, ic]) => (
            <button key={k} onClick={() => setTab(k)}
              style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '7px 13px', border: 'none', borderRadius: 'var(--r-xs, 7px)',
                       background: tab === k ? 'var(--surface)' : 'transparent', color: tab === k ? 'var(--ink)' : 'var(--ink-3)',
                       fontWeight: 600, fontSize: 13, cursor: 'pointer', boxShadow: tab === k ? 'var(--sh-1)' : 'none' }}>
              <Icon name={ic} size={15} /> {lbl}
            </button>
          ))}
        </div>
        {isSuper && (
          <button className="btn btn--ghost" style={{ height: 38 }} onClick={() => setCompOpen(true)}>
            <Icon name="layers" size={16} /> Konkurentlar
          </button>
        )}
        <button className="btn btn--primary" style={{ height: 38 }} onClick={() => setEditing({})} disabled={!regionOpts.length}>
          <Icon name="plus" size={16} stroke={2.4} /> Yangi tekshiruv
        </button>
      </div>

      {tab === 'dashboard' ? (
        <SCdashboard showToast={showToast} />
      ) : loading ? (
        <div style={{ flex: 1, display: 'grid', placeItems: 'center', color: 'var(--ink-4)' }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Yuklanmoqda…</div>
        </div>
      ) : checks.length === 0 ? (
        <div style={{ padding: 40 }}><Empty icon="board" text="Hozircha tekshiruv yo'q. Shablon rasmini yuklab boshlang." /></div>
      ) : (
        <div style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: '4px 22px 24px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 12 }}>
            {checks.map((sc) => <SCcard key={sc.id} sc={sc} onOpen={openCheck} />)}
          </div>
        </div>
      )}

      {editing && (
        <StoreCheckModal initial={editing} user={user} regionOpts={regionOpts}
          onClose={() => setEditing(null)} onSaved={onSaved} onDeleted={onDeleted} showToast={showToast} />
      )}
      {compOpen && (
        <CompetitorsModal onClose={() => setCompOpen(false)} showToast={showToast} />
      )}
    </>
  );
}
