/* ============================================================
   Cheklist — kunlik vazifalar (ish grafigi + daromad hisob)
   Super admin: cheklist yaratadi, hodimga biriktiradi, summani belgilaydi.
   Hodim: bugungi vazifalarni belgilaydi (faqat ish kuni, ish vaqtida).
   ============================================================ */

// O'zbekiston vaqti (UTC+5) bo'yicha bugungi sana va soat
function uzNow() {
  const d = new Date(Date.now() + 5 * 3_600_000);
  const dateStr = d.toISOString().slice(0, 10);
  const h = d.getUTCHours(), m = d.getUTCMinutes();
  return { dateStr, h, m, dow: d.getUTCDay() };
}

function parseHHMM(t) {
  const [h, m] = (t || '00:00').split(':').map(Number);
  return (h || 0) * 60 + (m || 0);
}

// Berilgan oydagi ish kunlari soni (grafik bo'yicha).
function workingDaysInMonth(monthStr, scheduleType, cycleStart) {
  const [y, m] = monthStr.split('-').map(Number);
  const dim = new Date(y, m, 0).getDate();
  let count = 0;
  for (let d = 1; d <= dim; d++) {
    const ds = monthStr + '-' + String(d).padStart(2, '0');
    if (isWorkingDay(ds, scheduleType, cycleStart)) count++;
  }
  return count;
}

// Har katak summasi = jami / (oydagi ish kunlari × bandlar soni).
// monthStr berilmasa — joriy oy.
function perItemAmount(cl, monthStr) {
  const ms = monthStr || uzNow().dateStr.slice(0, 7);
  const wd = workingDaysInMonth(ms, cl.scheduleType, cl.cycleStart);
  const n = (cl.items || []).length;
  return Math.round((cl.totalAmount || 0) / Math.max(1, wd * Math.max(1, n)));
}

function scheduleLabel(t) {
  return t === '3x1' ? '3x1 aylanma' : 'Har kuni (Yakshanba dam)';
}

function isWorkingDay(dateStr, scheduleType, cycleStart) {
  const d = new Date(dateStr + 'T00:00:00Z');
  if (d.getUTCDay() === 0) return false;
  if (scheduleType === '3x1') {
    const c = new Date(cycleStart + 'T00:00:00Z');
    const diff = Math.round((d - c) / 86_400_000);
    return ((diff % 4) + 4) % 4 < 3;
  }
  return true;
}

function fmtMonth(m) {
  const [y, mo] = m.split('-');
  const MONTHS = ['Yanvar','Fevral','Mart','Aprel','May','Iyun','Iyul','Avgust','Sentyabr','Oktyabr','Noyabr','Dekabr'];
  return MONTHS[Number(mo) - 1] + ' ' + y;
}

const DAY_SHORT = ['Ya','Du','Se','Ch','Pa','Ju','Sh']; // 0=Yak

/* ─── Kesh (stale-while-revalidate) — cheklist bo'limini tezlashtirish ─────
   Bo'lim ochilganda oxirgi keshlangan ma'lumot DARHOL ko'rsatiladi (spinner yo'q),
   so'ng fonda serverdan yangilanib, farq bo'lsa jimgina yangilanadi.
   Kesh localStorage'da saqlanadi — sahifa qayta yuklansa ham tez ochiladi. */
const CL_CACHE_PREFIX = 'gs_cl_cache_v1:';
function clCacheGet(key) {
  try { const raw = localStorage.getItem(CL_CACHE_PREFIX + key); return raw ? JSON.parse(raw) : null; }
  catch (_) { return null; }
}
function clCacheSet(key, val) {
  try { localStorage.setItem(CL_CACHE_PREFIX + key, JSON.stringify(val)); } catch (_) {}
}

/* ─── Oylik matritsa: ishlar (qator) × kunlar (ustun) ─────────────
   Chap ustun — ishlar (sticky). Yuqori qator — kunlar.
   Kesishma — belgilash katakchasi. Faqat BUGUNGI ustun interaktiv
   (ish kuni + ish vaqti bo'lsa); qolgan kunlar faqat ko'rsatish. */
function MonthMatrix({ days, items, monthStr, perItem, onPrevMonth, onNextMonth, canCheckToday, freeCheck, checking, onToggle, isSuper, onEditItem, onReorder }) {
  const total = days.reduce((s, d) => s + (d.earned || 0), 0);
  const COL = 38;       // kun ustuni kengligi
  const NAMEW = 220;    // ishlar ustuni kengligi
  // Bandlarni qayta tartiblash (drag-and-drop) holati
  const [dragId, setDragId] = useState(null);
  const [overId, setOverId] = useState(null);

  // dragId bandini targetId o'rniga ko'chirib, yangi id tartibini qaytaradi
  function reorderIds(dragId, targetId) {
    const ids = items.map((i) => i.id);
    const from = ids.indexOf(dragId);
    if (from < 0 || dragId === targetId) return null;
    ids.splice(from, 1);
    const to = ids.indexOf(targetId);
    ids.splice(to < 0 ? ids.length : to, 0, dragId);
    return ids;
  }
  function handleDrop(targetId) {
    const order = reorderIds(dragId, targetId);
    setDragId(null); setOverId(null);
    if (order && onReorder) onReorder(order);
  }

  // Kun ustuni fon rangi
  const colBg = (d) => {
    if (d.komandirovka) return 'rgba(90,159,212,.12)'; // komandirovka — moviy tus
    if (d.isToday) return 'rgba(142,116,255,.08)';
    if (d.isSunday) return 'rgba(232,115,95,.06)';
    if (!d.isWorking) return 'var(--bg-2)';
    return 'transparent';
  };

  // Har ish (qator) bo'yicha oylik belgilash soni
  const itemChecks = (itemId) => days.filter((d) => (d.checkedItemIds || []).includes(itemId)).length;

  return (
    <div>
      {/* Oy navigatsiyasi */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
        <button className="btn btn--icon btn--ghost" onClick={onPrevMonth}><Icon name="chevL" size={15} /></button>
        <div style={{ flex: 1, textAlign: 'center', fontWeight: 800, fontSize: 15 }}>{fmtMonth(monthStr)}</div>
        <button className="btn btn--icon btn--ghost" onClick={onNextMonth}><Icon name="chevR" size={15} /></button>
      </div>

      {items.length === 0 ? (
        <div style={{ fontSize: 12.5, color: 'var(--ink-4)', textAlign: 'center', padding: 24 }}>
          Hali band qo'shilmagan
        </div>
      ) : (
        <div style={{ overflowX: 'auto', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)' }}>
          <table style={{ borderCollapse: 'separate', borderSpacing: 0, fontSize: 12, width: 'max-content', minWidth: '100%' }}>
            {/* Yuqori qator — kunlar */}
            <thead>
              <tr>
                <th style={{ position: 'sticky', left: 0, zIndex: 3, width: NAMEW, minWidth: NAMEW, textAlign: 'left',
                  padding: '8px 12px', background: 'var(--surface)', borderBottom: '1px solid var(--border)',
                  borderRight: '2px solid var(--border)', fontWeight: 700, color: 'var(--ink-3)' }}>Ishlar</th>
                {days.map((d) => (
                  <th key={d.date} title={d.komandirovka ? d.date + ' · Komandirovka' : d.date} style={{ width: COL, minWidth: COL, padding: '5px 0', textAlign: 'center',
                    background: colBg(d), borderBottom: '1px solid var(--border)',
                    borderLeft: d.isToday ? '2px solid var(--brand)' : '1px solid var(--border)',
                    borderRight: d.isToday ? '2px solid var(--brand)' : 'none' }}>
                    <div style={{ fontSize: 9, fontWeight: 600, color: d.isSunday ? '#E8735F' : 'var(--ink-4)' }}>{d.komandirovka ? '✈️' : DAY_SHORT[d.dow]}</div>
                    <div style={{ fontSize: 12, fontWeight: d.isToday ? 800 : 600,
                      color: d.isToday ? 'var(--brand)' : (d.isSunday ? '#E8735F' : 'var(--ink-2)') }}>{d.day}</div>
                  </th>
                ))}
                <th style={{ width: 56, minWidth: 56, padding: '5px 8px', textAlign: 'right',
                  background: 'var(--surface)', borderBottom: '1px solid var(--border)',
                  borderLeft: '2px solid var(--border)', fontWeight: 700, color: 'var(--ink-3)', fontSize: 10 }}>Jami</th>
              </tr>
            </thead>
            <tbody>
              {/* Har ish — bitta qator */}
              {items.map((item) => {
                const cnt = itemChecks(item.id);
                const isDragOver = isSuper && dragId && overId === item.id && dragId !== item.id;
                return (
                  <tr key={item.id}
                    onDragOver={isSuper ? (e) => { if (dragId) { e.preventDefault(); setOverId(item.id); } } : undefined}
                    onDrop={isSuper ? (e) => { e.preventDefault(); handleDrop(item.id); } : undefined}
                    style={{ opacity: dragId === item.id ? 0.4 : 1 }}>
                    <td style={{ position: 'sticky', left: 0, zIndex: 2, width: NAMEW, minWidth: NAMEW,
                      padding: '5px 8px 5px 12px', background: 'var(--surface)', borderBottom: '1px solid var(--border)',
                      borderTop: isDragOver ? '2px solid var(--brand)' : 'none',
                      borderRight: '2px solid var(--border)', maxWidth: NAMEW }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        {isSuper && (
                          <span title="Tartibni o'zgartirish uchun torting" draggable
                            onDragStart={(e) => { setDragId(item.id); e.dataTransfer.effectAllowed = 'move'; try { e.dataTransfer.setData('text/plain', item.id); } catch (_) {} }}
                            onDragEnd={() => { setDragId(null); setOverId(null); }}
                            style={{ flex: 'none', cursor: 'grab', color: 'var(--ink-4)', display: 'inline-flex', touchAction: 'none' }}>
                            <Icon name="drag" size={14} />
                          </span>
                        )}
                        <span style={{ flex: 1, minWidth: 0, fontWeight: 600, whiteSpace: 'normal',
                          overflowWrap: 'break-word', lineHeight: 1.35 }}>{item.title}</span>
                        {isSuper && (
                          <button onClick={() => onEditItem(item)} title="Bandni tahrirlash"
                            className="btn btn--icon btn--ghost" style={{ flex: 'none', width: 24, height: 24 }}>
                            <Icon name="gear" size={12} />
                          </button>
                        )}
                      </div>
                    </td>
                    {days.map((d) => {
                      const checked = (d.checkedItemIds || []).includes(item.id);
                      // boshliq (freeCheck) — istalgan katakni istalgan vaqtda belgilaydi.
                      // Komandirovka kunlari avtomatik (derive) — qo'lda o'zgartirilmaydi.
                      const interactive = !d.komandirovka && (freeCheck || (d.isToday && canCheckToday)) && !checking[item.id + ':' + d.date];
                      const restDay = d.isSunday || !d.isWorking;
                      return (
                        <td key={d.date} onClick={() => interactive && onToggle(item.id, checked, d.date)}
                          style={{ width: COL, minWidth: COL, height: 34, textAlign: 'center', background: colBg(d),
                            borderBottom: '1px solid var(--border)',
                            borderLeft: d.isToday ? '2px solid var(--brand)' : '1px solid var(--border)',
                            borderRight: d.isToday ? '2px solid var(--brand)' : 'none',
                            cursor: interactive ? 'pointer' : 'default' }}>
                          {checked ? (
                            <span style={{ display: 'inline-grid', placeItems: 'center', width: 20, height: 20,
                              borderRadius: 5, background: '#3DBE9C', color: '#fff', margin: '0 auto' }}>
                              <Icon name="check" size={12} stroke={3} />
                            </span>
                          ) : (restDay && !interactive) ? (
                            <span style={{ color: 'var(--ink-4)', fontSize: 11 }}>·</span>
                          ) : (
                            <span style={{ display: 'inline-block', width: 20, height: 20, borderRadius: 5,
                              border: '1.5px solid ' + (interactive ? 'var(--brand)' : 'var(--border)'),
                              background: interactive ? 'var(--surface)' : 'transparent',
                              opacity: interactive ? 1 : 0.5 }} />
                          )}
                        </td>
                      );
                    })}
                    <td style={{ width: 56, minWidth: 56, padding: '7px 8px', textAlign: 'right',
                      background: 'var(--surface)', borderBottom: '1px solid var(--border)',
                      borderLeft: '2px solid var(--border)' }}>
                      <span className="tnum" style={{ fontWeight: 700, fontSize: 12 }}>{cnt}</span>
                      <span style={{ fontSize: 10, color: 'var(--ink-4)' }}>/{days.filter((d) => d.isWorking).length}</span>
                    </td>
                  </tr>
                );
              })}
              {/* Pastki qator — kunlik daromad */}
              <tr>
                <td style={{ position: 'sticky', left: 0, zIndex: 2, width: NAMEW, minWidth: NAMEW,
                  padding: '7px 12px', background: 'var(--bg-2)', borderRight: '2px solid var(--border)',
                  fontWeight: 700, fontSize: 11, color: 'var(--ink-3)' }}>Kunlik daromad</td>
                {days.map((d) => (
                  <td key={d.date} style={{ width: COL, minWidth: COL, padding: '5px 1px', textAlign: 'center',
                    background: d.isToday ? 'rgba(142,116,255,.08)' : 'var(--bg-2)',
                    borderLeft: d.isToday ? '2px solid var(--brand)' : '1px solid var(--border)',
                    borderRight: d.isToday ? '2px solid var(--brand)' : 'none' }}>
                    {d.earned > 0 && (
                      <span style={{ fontSize: 8, fontWeight: 700, color: '#1D8A6E', lineHeight: 1,
                        display: 'block', whiteSpace: 'nowrap' }}>{ioShort(d.earned)}</span>
                    )}
                  </td>
                ))}
                <td style={{ width: 56, minWidth: 56, padding: '5px 8px', textAlign: 'right', background: 'var(--bg-2)',
                  borderLeft: '2px solid var(--border)' }}>
                  <span className="tnum" style={{ fontWeight: 800, fontSize: 11, color: '#1D8A6E' }}>{ioShort(total)}</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      )}

      {/* Oylik jami */}
      <div style={{ marginTop: 14, padding: '11px 16px', borderRadius: 10,
        background: 'rgba(61,190,156,.10)', border: '1px solid rgba(61,190,156,.3)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
        <span style={{ fontSize: 13, fontWeight: 700, color: '#1D8A6E' }}>{fmtMonth(monthStr)} jami daromad</span>
        <span className="tnum" style={{ fontSize: 17, fontWeight: 800, color: '#1D8A6E' }}>+{DB.fmtSum(total)} so'm</span>
      </div>
    </div>
  );
}

/* ─── Cheklist detail (hodim + admin) ─────────────────────────── */
function ChecklistDetail({ clId, initialCl, isSuper, freeCheck, showToast, onBack, onDeleted }) {
  const [cl, setCl] = useState(initialCl || null);
  const [todayLogs, setTodayLogs] = useState([]);
  const [monthData, setMonthData] = useState(null);
  const [monthStr, setMonthStr] = useState(uzNow().dateStr.slice(0, 7));
  const [loading, setLoading] = useState(!initialCl);
  const [checking, setChecking] = useState({}); // itemId -> true
  const [editModal, setEditModal] = useState(false);
  const [itemModal, setItemModal] = useState(null); // null | {} | {item}
  const [confirmDel, setConfirmDel] = useState(false);
  const [tick, setTick] = useState(0); // vaqt yangilanishi uchun

  // Har daqiqada vaqtni yangilaymiz (ish vaqti tekshiruvi uchun)
  useEffect(() => {
    const t = setInterval(() => setTick((n) => n + 1), 60_000);
    return () => clearInterval(t);
  }, []);

  useEffect(() => { loadDetail(); }, [clId]);
  useEffect(() => { loadMonth(); }, [clId, monthStr]);

  // SWR: keshdan darhol → fonda yangilash
  async function loadDetail(useCache = true) {
    const ck = 'detail:' + clId + ':' + uzNow().dateStr;
    if (useCache) {
      const c = clCacheGet(ck);
      if (c) { setCl(c.checklist); setTodayLogs(c.todayLogs || []); setLoading(false); }
    }
    try {
      const r = await API.getChecklist(clId);
      setCl(r.checklist);
      setTodayLogs(r.todayLogs || []);
      clCacheSet(ck, { checklist: r.checklist, todayLogs: r.todayLogs || [] });
    } catch (e) {
      if (!clCacheGet(ck) && !initialCl) showToast(e.message || 'Yuklab bo\'lmadi');
    } finally { setLoading(false); }
  }

  async function loadMonth(useCache = true) {
    const ck = 'month:' + clId + ':' + monthStr;
    if (useCache) { const c = clCacheGet(ck); if (c) setMonthData(c); }
    try {
      const r = await API.checklistMonth(clId, monthStr);
      setMonthData(r);
      clCacheSet(ck, r);
    } catch (e) { /* silent — keshdagi ko'rinadi */ }
  }

  // Optimistik belgilash: DARHOL lokal yangilaymiz, server javobini kutmaymiz.
  // Amount = oyning perItem qiymati (server bilan bir xil formula) — drift yo'q.
  function applyLocalToggle(itemId, nowChecked, date, per) {
    setMonthData((md) => {
      if (!md) return md;
      const days = (md.days || []).map((d) => {
        if (d.date !== date) return d;
        const ids = new Set(d.checkedItemIds || []);
        let earned = d.earned || 0;
        if (nowChecked && !ids.has(itemId)) { ids.add(itemId); earned += per; }
        if (!nowChecked && ids.has(itemId)) { ids.delete(itemId); earned = Math.max(0, earned - per); }
        return { ...d, checkedItemIds: Array.from(ids), earned };
      });
      const next = { ...md, days };
      clCacheSet('month:' + clId + ':' + monthStr, next);
      return next;
    });
    // todayLogs faqat BUGUNGI kun uchun (banner) — boshqa kunlar unga tegmaydi
    if (date === uzNow().dateStr) {
      setTodayLogs((logs) => {
        const next = nowChecked
          ? (logs.some((l) => l.itemId === itemId) ? logs : [...logs, { itemId, amount: per }])
          : logs.filter((l) => l.itemId !== itemId);
        const dck = 'detail:' + clId + ':' + date;
        const cached = clCacheGet(dck);
        if (cached) clCacheSet(dck, { ...cached, todayLogs: next });
        return next;
      });
    }
  }

  async function handleCheck(itemId, isChecked, date) {
    const targetDate = date || uzNow().dateStr;
    const per = (monthData && monthData.perItem) || 0;
    const nowChecked = !isChecked;
    const key = itemId + ':' + targetDate;
    const prevMonth = monthData, prevLogs = todayLogs;
    applyLocalToggle(itemId, nowChecked, targetDate, per); // darhol ko'rinadi
    setChecking((c) => ({ ...c, [key]: true }));
    try {
      await API.checklistCheck(clId, itemId, isChecked ? 'uncheck' : 'check', targetDate);
    } catch (e) {
      setMonthData(prevMonth); setTodayLogs(prevLogs); // xato — orqaga qaytaramiz
      showToast(e.message || 'Xatolik');
    } finally { setChecking((c) => ({ ...c, [key]: false })); }
  }

  async function handleSaveCl(data) {
    try {
      const r = await API.updateChecklist(clId, data);
      setCl(r.checklist);
      setEditModal(false);
      showToast('Saqlandi');
      loadMonth(false); // summa/grafik o'zgargan bo'lishi mumkin — oyni yangilaymiz
    } catch (e) { showToast(e.message || 'Xatolik'); }
  }

  async function handleDelCl() {
    try {
      await API.deleteChecklist(clId);
      showToast("Cheklist o'chirildi");
      onDeleted && onDeleted();
    } catch (e) { showToast(e.message || 'Xatolik'); }
  }

  async function handleSaveItem(data) {
    try {
      if (data.id) {
        await API.updateChecklistItem(clId, data.id, { title: data.title });
      } else {
        await API.addChecklistItem(clId, { title: data.title });
      }
      await loadDetail(false);
      loadMonth(false); // band soni o'zgardi — perItem qayta hisoblanadi
      setItemModal(null);
      showToast('Saqlandi');
    } catch (e) { showToast(e.message || 'Xatolik'); }
  }

  async function handleDelItem(itemId) {
    try {
      await API.deleteChecklistItem(clId, itemId);
      await loadDetail(false);
      loadMonth(false); // band soni o'zgardi — perItem qayta hisoblanadi
      showToast("Band o'chirildi");
    } catch (e) { showToast(e.message || 'Xatolik'); }
  }

  async function handleReorder(orderIds) {
    if (!cl) return;
    const byId = new Map((cl.items || []).map((i) => [i.id, i]));
    const newItems = orderIds.map((id) => byId.get(id)).filter(Boolean);
    const prev = cl;
    setCl({ ...cl, items: newItems }); // optimistik
    try {
      await API.reorderChecklistItems(clId, orderIds);
      loadDetail(false); // keshni yangilaymiz
    } catch (e) {
      setCl(prev); // xato — orqaga qaytaramiz
      showToast(e.message || 'Xatolik');
    }
  }

  if (loading) return (
    <div style={{ padding: 32, textAlign: 'center', color: 'var(--ink-4)', fontSize: 13 }}>Yuklanmoqda…</div>
  );
  if (!cl) return null;

  const uz = uzNow();
  const todayWorking = uz.dow !== 0 && isWorkingDay(uz.dateStr, cl.scheduleType, cl.cycleStart);
  const wStart = parseHHMM(cl.workStart), wEnd = parseHHMM(cl.workEnd);
  const curMins = uz.h * 60 + uz.m;
  const inTime = curMins >= wStart && curMins < wEnd;
  const canCheck = todayWorking && inTime;
  const checkedIds = new Set(todayLogs.map((l) => l.itemId));
  const todayEarned = todayLogs.reduce((s, l) => s + (l.amount || 0), 0);
  // Har katak summasi — backend hisobi (oydagi ish kunlari × bandlar) yoki frontend zaxira
  const perItem = (monthData && monthData.perItem != null) ? monthData.perItem : perItemAmount(cl, monthStr);
  const workDays = monthData ? monthData.workDays : workingDaysInMonth(monthStr, cl.scheduleType, cl.cycleStart);

  // Status banner rangi
  let bannerColor = '#1D8A6E', bannerBg = 'rgba(61,190,156,.10)', bannerIcon = 'check';
  let bannerText = `Ish kuni · ${cl.workStart}–${cl.workEnd} · Belgilash ${inTime ? 'ochiq' : 'yopiq'}`;
  if (uz.dow === 0) { bannerColor = '#C2453A'; bannerBg = 'rgba(232,115,95,.10)'; bannerIcon = 'x'; bannerText = "Yakshanba — dam olish kuni"; }
  else if (!todayWorking) { bannerColor = '#A6651E'; bannerBg = 'rgba(227,162,59,.12)'; bannerIcon = 'clock'; bannerText = "Bugun dam olish kuni (3x1 aylanma grafik)"; }
  else if (!inTime) { bannerColor = '#A6651E'; bannerBg = 'rgba(227,162,59,.12)'; bannerIcon = 'clock'; bannerText = `Ish vaqti: ${cl.workStart}–${cl.workEnd} · Hozir yopiq`; }

  return (
    <div style={{ overflowY: 'auto', height: '100%', padding: '16px 24px 32px' }}>
      {/* Orqaga + sarlavha */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
        <button className="btn btn--icon btn--ghost" onClick={onBack} title="Orqaga"><Icon name="chevL" size={18} /></button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 800, fontSize: 17, lineHeight: 1.2 }}>{cl.title}</div>
          {cl.user && <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>{cl.user.name}</div>}
        </div>
        {isSuper && (
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn btn--ghost" style={{ fontSize: 12 }} onClick={() => setItemModal({})}>
              <Icon name="plus" size={14} /> Band qo'shish
            </button>
            <button className="btn btn--ghost" style={{ fontSize: 12 }} onClick={() => setEditModal(true)}>
              <Icon name="gear" size={14} /> Tahrirlash
            </button>
            <button className="btn btn--ghost" style={{ fontSize: 12, color: '#C2453A' }} onClick={() => setConfirmDel(true)}>
              <Icon name="trash" size={14} />
            </button>
          </div>
        )}
      </div>

      {/* KPI band (super admin) */}
      {isSuper && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px,1fr))', gap: 10, marginBottom: 16 }}>
          {[
            { label: "Oylik jami summa", value: DB.fmtSum(cl.totalAmount) + " so'm", accent: 'var(--brand)' },
            { label: "Har katak", value: DB.fmtSum(perItem) + " so'm", accent: '#7A5CF0' },
            { label: "Kataklar (oy)", value: workDays + '×' + (cl.items || []).length + ' = ' + (workDays * (cl.items || []).length), accent: '#5A9FD4' },
            { label: "Ish vaqti", value: cl.workStart + '–' + cl.workEnd, accent: '#3DBE9C' },
          ].map((k, i) => (
            <div key={i} className="dx-kpi" style={{ '--_a': k.accent }}>
              <div className="dx-kpi__l">{k.label}</div>
              <div className="dx-kpi__v" style={{ color: k.accent, fontSize: 16 }}>{k.value}</div>
            </div>
          ))}
        </div>
      )}

      {/* Status banner — bugungi ish kuni / vaqt holati (boshliqqa ko'rsatilmaydi) */}
      {!freeCheck && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '10px 14px',
          borderRadius: 10, background: bannerBg, marginBottom: 14,
          border: '1px solid ' + bannerColor + '33', fontSize: 12.5, color: bannerColor, fontWeight: 600, flexWrap: 'wrap' }}>
          <Icon name={bannerIcon} size={15} />
          {bannerText}
          {todayEarned > 0 && (
            <span className="tnum" style={{ marginLeft: 'auto', color: '#1D8A6E', fontWeight: 800 }}>
              Bugun: +{DB.fmtSum(todayEarned)} so'm
            </span>
          )}
        </div>
      )}

      {/* Oylik matritsa: ishlar × kunlar */}
      <div className="dx-card dx-card--pad">
        {monthData ? (
          <MonthMatrix
            days={monthData.days}
            items={cl.items || []}
            monthStr={monthStr}
            perItem={perItem}
            canCheckToday={canCheck}
            freeCheck={freeCheck}
            checking={checking}
            isSuper={isSuper}
            onEditItem={(item) => setItemModal({ item })}
            onReorder={handleReorder}
            onToggle={(itemId, checked, date) => handleCheck(itemId, checked, date)}
            onPrevMonth={() => {
              const [y, m] = monthStr.split('-').map(Number);
              const prev = m === 1 ? (y - 1) + '-12' : y + '-' + String(m - 1).padStart(2, '0');
              setMonthStr(prev);
            }}
            onNextMonth={() => {
              const [y, m] = monthStr.split('-').map(Number);
              const next = m === 12 ? (y + 1) + '-01' : y + '-' + String(m + 1).padStart(2, '0');
              setMonthStr(next);
            }}
          />
        ) : (
          <div style={{ fontSize: 12.5, color: 'var(--ink-4)', textAlign: 'center', padding: 24 }}>Yuklanmoqda…</div>
        )}

        {/* Ish vaqti eslatmasi */}
        {!freeCheck && !canCheck && todayWorking && (
          <div style={{ marginTop: 12, fontSize: 11.5, color: 'var(--ink-4)', textAlign: 'center' }}>
            Belgilash faqat bugungi ustunda, {cl.workStart}–{cl.workEnd} orasida mumkin (O'zbekiston vaqti)
          </div>
        )}
      </div>

      {/* Edit cheklist modal (super admin) */}
      {editModal && (
        <ChecklistFormModal
          initial={cl}
          onClose={() => setEditModal(false)}
          onSave={handleSaveCl}
          users={[]}
          editMode
        />
      )}

      {/* Item modal */}
      {itemModal !== null && (
        <ItemFormModal
          initial={itemModal.item}
          onClose={() => setItemModal(null)}
          onSave={handleSaveItem}
          onDelete={itemModal.item ? () => { setItemModal(null); handleDelItem(itemModal.item.id); } : null}
        />
      )}

      {/* O'chirish tasdiqi */}
      {confirmDel && (
        <Modal onClose={() => setConfirmDel(false)} width={400}>
          <ModalHeader title="Cheklist o'chirilsinmi?" onClose={() => setConfirmDel(false)} />
          <div style={{ padding: '16px 22px', fontSize: 13.5, color: 'var(--ink-2)' }}>
            "<b>{cl.title}</b>" cheklisti va barcha belgilash tarixi butunlay o'chiriladi.
          </div>
          <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
            <button className="btn btn--ghost" onClick={() => setConfirmDel(false)}>Bekor</button>
            <button className="btn btn--primary" style={{ background: '#E8735F' }} onClick={handleDelCl}>O'chirish</button>
          </div>
        </Modal>
      )}
    </div>
  );
}

/* ─── Cheklist yaratish / tahrirlash modal ──────────────────────── */
function ChecklistFormModal({ initial, onClose, onSave, users, editMode, heading }) {
  const [form, setForm] = useState({
    userId: initial?.userId || initial?.user?.id || '',
    title: initial?.title || '',
    totalAmount: initial?.totalAmount ?? 0,
    scheduleType: initial?.scheduleType || '3x1',
    cycleStart: initial?.cycleStart || uzNow().dateStr,
    workStart: initial?.workStart || '09:00',
    workEnd: initial?.workEnd || '18:00',
  });
  const [busy, setBusy] = useState(false);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  // Tahrirlashda: joriy oy ish kunlari × bandlar soniga qarab har katak summasi
  const itemCount = (initial?.items || []).length;
  const curMonth = uzNow().dateStr.slice(0, 7);
  const wDays = workingDaysInMonth(curMonth, form.scheduleType, form.cycleStart);
  const totalCells = wDays * itemCount;
  const previewPerItem = totalCells > 0
    ? Math.round((Number(form.totalAmount) || 0) / totalCells)
    : null;

  async function save() {
    if (!form.title.trim()) return;
    if (!editMode && !form.userId) return;
    setBusy(true);
    try { await onSave({ ...form, totalAmount: Number(form.totalAmount) || 0 }); }
    finally { setBusy(false); }
  }

  return (
    <Modal onClose={onClose} width={520}>
      <ModalHeader title={heading || (editMode ? "Cheklistni tahrirlash" : "Yangi cheklist")} onClose={onClose} />
      <div style={{ padding: '16px 22px', display: 'grid', gap: 14 }}>
        {!editMode && (
          <div>
            <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-3)', display: 'block', marginBottom: 5 }}>Hodim</label>
            <select className="select" style={{ width: '100%' }} value={form.userId} onChange={(e) => set('userId', e.target.value)}>
              <option value="">— tanlang —</option>
              {(users || []).map((u) => <option key={u.id} value={u.id}>{u.name} ({(DB.ROLES[u.role] || {}).label || u.role})</option>)}
            </select>
          </div>
        )}
        <div>
          <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-3)', display: 'block', marginBottom: 5 }}>Cheklist nomi</label>
          <input className="input" style={{ width: '100%' }} value={form.title}
            onChange={(e) => set('title', e.target.value)} placeholder="Kunlik vazifalar…" />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-3)', display: 'block', marginBottom: 5 }}>Jami summa (so'm)</label>
            <input className="input" style={{ width: '100%' }} type="number" min="0" value={form.totalAmount}
              onChange={(e) => set('totalAmount', e.target.value)} placeholder="0" />
            <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 4 }}>
              {previewPerItem != null
                ? `${wDays} ish kuni × ${itemCount} band = ${totalCells} katak → ${DB.fmtSum(previewPerItem)} so'm/katak`
                : "Oydagi ish kunlari × bandlar soniga bo'linadi"}
            </div>
          </div>
          <div>
            <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-3)', display: 'block', marginBottom: 5 }}>Ish grafigi</label>
            <select className="select" style={{ width: '100%' }} value={form.scheduleType} onChange={(e) => set('scheduleType', e.target.value)}>
              <option value="daily">Har kuni (Yakshanba dam)</option>
              <option value="3x1">3x1 aylanma (3 ish, 1 dam)</option>
            </select>
            <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 4 }}>
              {form.scheduleType === '3x1' ? 'Tsikldan: 3 kun ish, 1 kun dam' : 'Yakshanbadan boshqa barcha kunlar'}
            </div>
          </div>
        </div>
        {form.scheduleType === '3x1' && (
          <div>
            <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-3)', display: 'block', marginBottom: 5 }}>Tsikl boshlanish sanasi</label>
            <input className="input" style={{ width: '100%' }} type="date" value={form.cycleStart}
              onChange={(e) => set('cycleStart', e.target.value)} />
            <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 4 }}>Shu kundan: 3 kun ish → 1 kun dam → takrorlanadi</div>
          </div>
        )}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-3)', display: 'block', marginBottom: 5 }}>Belgilash boshlanishi</label>
            <input className="input" style={{ width: '100%' }} type="time" value={form.workStart}
              onChange={(e) => set('workStart', e.target.value)} />
          </div>
          <div>
            <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-3)', display: 'block', marginBottom: 5 }}>Belgilash tugashi</label>
            <input className="input" style={{ width: '100%' }} type="time" value={form.workEnd}
              onChange={(e) => set('workEnd', e.target.value)} />
          </div>
        </div>
      </div>
      <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
        <button className="btn btn--ghost" onClick={onClose}>Bekor</button>
        <button className="btn btn--primary" disabled={busy || !form.title.trim() || (!editMode && !form.userId)} onClick={save}>
          <Icon name="check" size={15} stroke={2.4} /> Saqlash
        </button>
      </div>
    </Modal>
  );
}

/* ─── Band qo'shish / tahrirlash modal ─────────────────────────── */
function ItemFormModal({ initial, onClose, onSave, onDelete }) {
  const [title, setTitle] = useState(initial?.title || '');
  const [busy, setBusy] = useState(false);
  async function save() {
    if (!title.trim()) return;
    setBusy(true);
    try { await onSave({ id: initial?.id, title: title.trim() }); }
    finally { setBusy(false); }
  }
  return (
    <Modal onClose={onClose} width={400}>
      <ModalHeader title={initial ? "Bandni tahrirlash" : "Yangi band"} onClose={onClose} />
      <div style={{ padding: '16px 22px' }}>
        <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-3)', display: 'block', marginBottom: 5 }}>Band nomi</label>
        <input className="input" style={{ width: '100%' }} value={title} autoFocus
          onChange={(e) => setTitle(e.target.value)} placeholder="Vazifa nomi…"
          onKeyDown={(e) => e.key === 'Enter' && save()} />
      </div>
      <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', gap: 10, justifyContent: 'space-between' }}>
        <div>
          {onDelete && (
            <button className="btn btn--ghost" style={{ color: '#C2453A' }} onClick={onDelete}>
              <Icon name="trash" size={14} /> O'chirish
            </button>
          )}
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn--ghost" onClick={onClose}>Bekor</button>
          <button className="btn btn--primary" disabled={busy || !title.trim()} onClick={save}>
            <Icon name="check" size={15} stroke={2.4} /> Saqlash
          </button>
        </div>
      </div>
    </Modal>
  );
}

/* ─── Asosiy Cheklist komponenti ────────────────────────────────── */
function Checklist({ user, showToast, isSuper, viewAll }) {
  // Sotuv bo'limi rahbari (boshliq) — kataklarni istalgan vaqtda belgilay oladi
  const freeCheck = !!(user && user.role === 'boshliq');
  // Barcha cheklistlarni ko'rish (ruxsat) — ro'yxat ko'rinishi; boshqaruv esa faqat super
  const canSeeAll = viewAll !== undefined ? !!viewAll : !!isSuper;
  const [checklists, setChecklists] = useState(null);
  const [detail, setDetail] = useState(null); // tanlangan checklist id
  const [createModal, setCreateModal] = useState(false);
  const [copySource, setCopySource] = useState(null); // nusxa olinadigan cheklist
  const [users, setUsers] = useState([]);

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

  async function load() {
    // 1) Keshdan darhol ko'rsatamiz (agar bo'lsa)
    const cachedList = clCacheGet('list');
    if (cachedList) setChecklists(cachedList);
    const cachedUsers = clCacheGet('users');
    if (cachedUsers) setUsers(cachedUsers);
    // 2) Fonda serverdan yangilaymiz
    try {
      const r = await API.listChecklists();
      setChecklists(r.checklists || []);
      clCacheSet('list', r.checklists || []);
      // Super admin uchun foydalanuvchilar ro'yxatini olish
      if (isSuper) {
        try {
          const ur = await API.listUsers();
          setUsers(ur.users || []);
          clCacheSet('users', ur.users || []);
        } catch (_) {}
      }
    } catch (e) { if (!cachedList) showToast(e.message || 'Yuklab bo\'lmadi'); }
  }

  async function handleCreate(data) {
    try {
      await API.createChecklist(data);
      setCreateModal(false);
      showToast('Cheklist yaratildi');
      await load();
    } catch (e) { showToast(e.message || 'Xatolik'); }
  }

  async function handleCopy(data) {
    try {
      await API.duplicateChecklist(copySource.id, data);
      setCopySource(null);
      showToast('Cheklistdan nusxa olindi');
      await load();
    } catch (e) { showToast(e.message || 'Xatolik'); }
  }

  // Agar detail ko'rinish ochiq bo'lsa
  if (detail) {
    return (
      <ChecklistDetail
        clId={detail}
        initialCl={checklists && checklists.find((c) => c.id === detail)}
        isSuper={isSuper}
        freeCheck={freeCheck}
        showToast={showToast}
        onBack={() => setDetail(null)}
        onDeleted={() => { setDetail(null); load(); }}
      />
    );
  }

  if (checklists === null) {
    return <div style={{ padding: 32, textAlign: 'center', color: 'var(--ink-4)', fontSize: 13 }}>Yuklanmoqda…</div>;
  }

  // ── Hodim uchun ko'rinish (o'ziga biriktirilgan cheklist) ──
  if (!canSeeAll) {
    if (checklists.length === 0) {
      return (
        <div style={{ height: '100%', display: 'grid', placeItems: 'center' }}>
          <Empty icon="tasks" text="Sizga hali cheklist biriktirilmagan" sub="Super admin cheklist yaratib beradi" />
        </div>
      );
    }
    if (checklists.length === 1) {
      return (
        <ChecklistDetail
          clId={checklists[0].id}
          initialCl={checklists[0]}
          isSuper={false}
          freeCheck={freeCheck}
          showToast={showToast}
          onBack={() => {}}
        />
      );
    }
    // Bir nechta cheklist — tanlash
    return (
      <div style={{ padding: '20px 24px', overflowY: 'auto', height: '100%' }}>
        <div style={{ fontWeight: 800, fontSize: 18, marginBottom: 16 }}>Mening cheklistlarim</div>
        <div style={{ display: 'grid', gap: 10 }}>
          {checklists.map((cl) => (
            <button key={cl.id} onClick={() => setDetail(cl.id)}
              style={{ textAlign: 'left', padding: '14px 18px', borderRadius: 12, background: 'var(--surface)',
                border: '1px solid var(--border)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{cl.title}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>
                  {(cl.items || []).length} ta band · {cl.workStart}–{cl.workEnd}
                </div>
              </div>
              {perItemAmount(cl) > 0 && (
                <span className="tnum" style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--brand)' }}>
                  {DB.fmtSum(perItemAmount(cl))}/katak
                </span>
              )}
              <Icon name="chevR" size={16} />
            </button>
          ))}
        </div>
      </div>
    );
  }

  // ── Super admin ko'rinishi ──
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Toolbar */}
      <div className="dx-toolbar" style={{ margin: '14px 24px 10px', flexShrink: 0 }}>
        <div>
          <div style={{ fontWeight: 800, fontSize: 18, letterSpacing: '-.02em' }}>Cheklistlar</div>
          <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>{checklists.length} ta cheklist</div>
        </div>
        <div className="dx-toolbar__sp" />
        {isSuper && (
          <button className="btn btn--primary" onClick={() => setCreateModal(true)}>
            <Icon name="plus" size={15} stroke={2.4} /> Yangi cheklist
          </button>
        )}
      </div>

      {/* List */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '0 24px 32px' }}>
        {checklists.length === 0 && (
          <Empty icon="tasks" text="Hali cheklist yaratilmagan" sub="Hodimlar uchun kunlik vazifalar cheklistini yarating" />
        )}
        <div style={{ display: 'grid', gap: 10 }}>
          {checklists.map((cl) => {
            const uz = uzNow();
            const todayWork = uz.dow !== 0 && isWorkingDay(uz.dateStr, cl.scheduleType, cl.cycleStart);
            return (
              <div key={cl.id} className="dx-card"
                style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 18px', cursor: 'pointer' }}
                onClick={() => setDetail(cl.id)}>
                <Avatar src={cl.user && cl.user.avatar} name={cl.user && cl.user.name} size={40} radius={10} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{cl.title}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>
                    {cl.user && cl.user.name} ·
                    {' '}{(cl.items || []).length} ta band ·
                    {' '}{cl.workStart}–{cl.workEnd} ·
                    {' '}{scheduleLabel(cl.scheduleType)}
                  </div>
                </div>
                <div style={{ display: 'flex', flex: 'none', flexDirection: 'column', alignItems: 'flex-end', gap: 4 }}>
                  {cl.totalAmount > 0 && (
                    <span className="tnum" style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--brand)' }}>
                      {DB.fmtSum(cl.totalAmount)} so'm jami
                    </span>
                  )}
                  <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 999,
                    background: todayWork ? 'rgba(61,190,156,.12)' : 'var(--bg-2)',
                    color: todayWork ? '#1D8A6E' : 'var(--ink-4)' }}>
                    {todayWork ? 'Bugun ish kuni' : 'Bugun dam olish'}
                  </span>
                </div>
                {isSuper && (
                  <button className="btn btn--icon btn--ghost" title="Nusxa olish (boshqa mas'ulga)" style={{ flex: 'none' }}
                    onClick={(e) => { e.stopPropagation(); setCopySource(cl); }}>
                    <Icon name="copy" size={15} />
                  </button>
                )}
                <Icon name="chevR" size={16} style={{ color: 'var(--ink-4)', flex: 'none' }} />
              </div>
            );
          })}
        </div>
      </div>

      {/* Yaratish modal */}
      {createModal && (
        <ChecklistFormModal
          onClose={() => setCreateModal(false)}
          onSave={handleCreate}
          users={users}
          editMode={false}
        />
      )}

      {/* Nusxa olish modal — manba sozlamalari + bandlar oldindan to'ldiriladi,
          faqat yangi mas'ul tanlanadi */}
      {copySource && (
        <ChecklistFormModal
          initial={{ ...copySource, userId: '', user: null, title: copySource.title }}
          heading="Cheklistdan nusxa olish"
          onClose={() => setCopySource(null)}
          onSave={handleCopy}
          users={users}
          editMode={false}
        />
      )}
    </div>
  );
}

window.Checklist = Checklist;
