// Emphasis System — Daily Checklist tab (split out, registered in emphasis.jsx).
// One saved row per (user, day). Saves to Supabase `daily_checklists` via
// window.db.dailyChecklist (per-user through RLS), with a localStorage fallback
// so it keeps working offline / before login. Built to mirror the shared
// "DAILY CHECKLIST" design: motto banner, day navigator, progress ring +
// per-section bars, PV field, "Copy ส่ง Upline", and a month heatmap calendar.

// ---- date helpers (local time, not UTC) ----
const DC_TH_DOW   = ['อา', 'จ', 'อ', 'พ', 'พฤ', 'ศ', 'ส'];          // Sun..Sat
const DC_TH_DOW_F = ['อาทิตย์','จันทร์','อังคาร','พุธ','พฤหัสบดี','ศุกร์','เสาร์'];
const DC_TH_MONTH_F = ['มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน','กรกฎาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'];
const _dcMonthAbbr = (typeof TH_MONTH_ABBR !== 'undefined')
  ? TH_MONTH_ABBR
  : ['ม.ค.','ก.พ.','มี.ค.','เม.ย.','พ.ค.','มิ.ย.','ก.ค.','ส.ค.','ก.ย.','ต.ค.','พ.ย.','ธ.ค.'];
const dcYmd = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
const dcParse = (s) => { const [y, m, d] = s.split('-').map(Number); return new Date(y, m - 1, d); };
const dcAddDays = (s, n) => { const d = dcParse(s); d.setDate(d.getDate() + n); return dcYmd(d); };

// ---- checklist structure ----
// Daily sections are counted toward the day's "X/total". Weekly is a separate
// once-a-week cadence and is tracked but not folded into the daily ring.
const DC_DAILY = [
  {
    id: 'myself', label: 'Myself', icon: 'user', color: '#8B5CF6', tint: '#F3EEFE',
    items: [
      { id: 'use_product', label: 'ใช้สินค้า' },
      { id: 'listen_link', label: 'ฟัง Link' },
      { id: 'read_15', label: 'อ่านหนังสือ 15 หน้า' },
    ],
  },
  {
    id: 'social', label: 'My Social Media', icon: 'share-2', color: '#06B6D4', tint: '#E0F7FB',
    items: [
      { id: 'post', label: 'Post', count: true },
      { id: 'add_friend', label: 'เพิ่มเพื่อน', count: true },
      { id: 'comment_story', label: 'Comment / Reply Story' },
      { id: 'hbd_inbox', label: 'HBD ใน Inbox' },
    ],
  },
  {
    id: 'business', label: 'My Business', icon: 'target', color: '#2F5DE5', tint: '#EEF4FF',
    items: [
      { id: 'open_talk', label: 'ทักเข้าเรื่อง', count: true, hint: 'เป้า: เข้าเรื่อง 8 · ปิดได้ 1 เคส' },
      { id: 'em6w_model', label: 'EM6W / Model' },
      { id: 'fu_sponsor', label: 'Follow up Sponsor' },
      { id: 'analyze_sheet', label: 'วิเคราะห์งาน / Follow up Sheet' },
    ],
  },
];
const DC_WEEKLY = {
  id: 'weekly', label: 'Weekly', icon: 'list', color: '#F59E0B', tint: '#FEF3DD',
  items: [
    { id: 'w_list', label: 'ทำ List รายชื่อ' },
    { id: 'w_case_other', label: 'ทำ Case สินค้าอื่น' },
    { id: 'w_repeat_cust', label: 'ดูแลลูกค้าซื้อซ้ำ' },
    { id: 'w_call_system', label: 'โทรนัดหมาย / เข้าระบบ' },
    { id: 'w_hm', label: 'ทำ HM ฝึก' },
    { id: 'w_upline', label: 'คุยกับ Upline' },
    { id: 'w_evaluate', label: 'ประเมินผล ยอด คน แผน' },
  ],
};
const DC_DAILY_ITEMS = DC_DAILY.flatMap(s => s.items);
const DC_DAILY_TOTAL = DC_DAILY_ITEMS.length;

const _dcBlank = () => ({ checks: {}, counts: {}, pv: '', note: '' });
const _dcSectionDone = (sec, checks) => sec.items.filter(it => checks[it.id]).length;

function DailyChecklistTab({ currentUser }) {
  const [day, setDay] = useState(() => dcYmd(new Date()));
  const [doc, setDoc] = useState(_dcBlank());
  const [loading, setLoading] = useState(true);
  const [saveLabel, setSaveLabel] = useState('บันทึกอัตโนมัติ');
  const [monthMap, setMonthMap] = useState({});   // 'YYYY-MM-DD' -> done count (daily)
  const [copied, setCopied] = useState(false);
  const saveTimer = React.useRef(null);
  const todayStr = dcYmd(new Date());
  const dObj = dcParse(day);
  // Namespace localStorage per-account so a previously-logged-in user's offline
  // fallback never leaks into another account on the same device. Falls back to
  // 'anon' before login. (Supabase rows are already isolated via RLS/user_id.)
  const lsUid = currentUser?.id || 'anon';
  const lsKeyFor = (d) => `emphasis_daily_${lsUid}_${d}`;
  const lsKey = lsKeyFor(day);

  // ---- one-time cleanup of legacy device-global keys ----
  // Old format was `emphasis_daily_YYYY-MM-DD` (no user id), which leaked one
  // account's data into another on a shared device. Purge any leftovers once.
  useEffect(() => {
    try {
      const legacy = /^emphasis_daily_\d{4}-\d{2}-\d{2}$/;
      for (let i = localStorage.length - 1; i >= 0; i--) {
        const k = localStorage.key(i);
        if (k && legacy.test(k)) localStorage.removeItem(k);
      }
    } catch {}
  }, []);

  // ---- load the selected day ----
  useEffect(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      let loaded = null;
      try {
        if (window.SB_READY && window.db?.dailyChecklist) {
          const { data } = await window.db.dailyChecklist.get(day);
          if (data) loaded = data.data;
        }
      } catch (e) { /* fall through */ }
      if (!loaded) { try { const raw = localStorage.getItem(lsKey); if (raw) loaded = JSON.parse(raw); } catch {} }
      if (cancelled) return;
      setDoc({ ..._dcBlank(), ...(loaded || {}) });
      setSaveLabel(loaded ? 'บันทึกไว้แล้ว' : 'บันทึกอัตโนมัติ');
      setLoading(false);
    })();
    return () => { cancelled = true; };
  }, [day, lsUid]); // eslint-disable-line

  // ---- load month heatmap (the month of the selected day) ----
  const loadMonth = useCallback(async () => {
    const first = new Date(dObj.getFullYear(), dObj.getMonth(), 1);
    const last  = new Date(dObj.getFullYear(), dObj.getMonth() + 1, 0);
    const map = {};
    try {
      if (window.SB_READY && window.db?.dailyChecklist) {
        const { data } = await window.db.dailyChecklist.range(dcYmd(first), dcYmd(last));
        (data || []).forEach(row => {
          const checks = (row.data && row.data.checks) || {};
          map[row.day] = DC_DAILY_ITEMS.filter(it => checks[it.id]).length;
        });
      } else {
        // localStorage scan for offline mode
        for (let d = 1; d <= last.getDate(); d++) {
          const key = dcYmd(new Date(dObj.getFullYear(), dObj.getMonth(), d));
          try { const raw = localStorage.getItem(lsKeyFor(key)); if (raw) { const j = JSON.parse(raw); map[key] = DC_DAILY_ITEMS.filter(it => (j.checks || {})[it.id]).length; } } catch {}
        }
      }
    } catch {}
    setMonthMap(map);
  }, [dObj.getFullYear(), dObj.getMonth(), lsUid]); // eslint-disable-line
  useEffect(() => { loadMonth(); }, [loadMonth, loading]);

  // ---- persist (debounced) ----
  const persist = useCallback(async (next) => {
    try { localStorage.setItem(lsKeyFor(day), JSON.stringify(next)); } catch {}
    try { if (window.SB_READY && window.db?.dailyChecklist) await window.db.dailyChecklist.save(day, next); } catch {}
    setSaveLabel('บันทึกแล้ว · ' + new Date().toLocaleTimeString('th-TH', { hour: '2-digit', minute: '2-digit' }));
    setMonthMap(m => ({ ...m, [day]: DC_DAILY_ITEMS.filter(it => (next.checks || {})[it.id]).length }));
  }, [day, lsUid]);
  const queueSave = (next) => {
    setSaveLabel('กำลังบันทึก…');
    clearTimeout(saveTimer.current);
    saveTimer.current = setTimeout(() => persist(next), 500);
  };
  const update = (mut) => { setDoc(prev => { const next = mut({ ...prev, checks: { ...prev.checks }, counts: { ...prev.counts } }); queueSave(next); return next; }); };

  const toggle = (id) => update(d => { d.checks[id] = !d.checks[id]; return d; });
  const bump = (id, delta) => update(d => {
    const n = Math.max(0, (Number(d.counts[id]) || 0) + delta);
    d.counts[id] = n;
    if (delta > 0 && n > 0) d.checks[id] = true;     // first count auto-checks the item
    return d;
  });
  const setPv = (v) => update(d => { d.pv = v.replace(/[^0-9]/g, ''); return d; });
  const setNote = (v) => update(d => { d.note = v; return d; });

  // ---- progress ----
  const dailyDone = DC_DAILY_ITEMS.filter(it => doc.checks[it.id]).length;
  const pct = DC_DAILY_TOTAL ? Math.round((dailyDone / DC_DAILY_TOTAL) * 100) : 0;
  const weeklyDone = DC_WEEKLY.items.filter(it => doc.checks[it.id]).length;

  // ---- copy-to-upline text ----
  const buildCopy = () => {
    const lbl = `${DC_TH_DOW_F[dObj.getDay()]} ${dObj.getDate()} ${_dcMonthAbbr[dObj.getMonth()]} ${dObj.getFullYear() + 543}`;
    const lines = [`📋 Daily Checklist — ${lbl}`, `✅ รวม ${dailyDone}/${DC_DAILY_TOTAL} (${pct}%)`, ''];
    DC_DAILY.forEach(sec => {
      lines.push(`■ ${sec.label} ${_dcSectionDone(sec, doc.checks)}/${sec.items.length}`);
      sec.items.forEach(it => {
        const cnt = it.count && (Number(doc.counts[it.id]) || 0) > 0 ? ` (${doc.counts[it.id]})` : '';
        lines.push(`${doc.checks[it.id] ? '☑' : '☐'} ${it.label}${cnt}`);
      });
      lines.push('');
    });
    lines.push(`■ ${DC_WEEKLY.label} ${weeklyDone}/${DC_WEEKLY.items.length}`);
    DC_WEEKLY.items.forEach(it => lines.push(`${doc.checks[it.id] ? '☑' : '☐'} ${it.label}`));
    lines.push('');
    lines.push(`💰 PV วันนี้: ${doc.pv ? Number(doc.pv).toLocaleString('th-TH') : 0}`);
    if ((doc.note || '').trim()) lines.push(`📝 หมายเหตุ: ${doc.note.trim()}`);
    return lines.join('\n');
  };
  const doCopy = () => { try { navigator.clipboard.writeText(buildCopy()); } catch {} setCopied(true); setTimeout(() => setCopied(false), 1600); };

  // ---- month heatmap cells ----
  const calCells = (() => {
    const first = new Date(dObj.getFullYear(), dObj.getMonth(), 1);
    const daysIn = new Date(dObj.getFullYear(), dObj.getMonth() + 1, 0).getDate();
    const pad = first.getDay(); // 0=Sun → leading blanks
    const cells = [];
    for (let i = 0; i < pad; i++) cells.push(null);
    for (let d = 1; d <= daysIn; d++) cells.push(d);
    return cells;
  })();
  const savedDaysCount = Object.values(monthMap).filter(v => v > 0).length;
  const heatTint = (done) => {
    if (!done) return '#F1F5F9';
    if (done >= DC_DAILY_TOTAL) return '#2F5DE5';
    if (done >= 8) return '#5B82EB';
    if (done >= 5) return '#9DB6F4';
    if (done >= 3) return '#C7D6F9';
    return '#E3EAFB';
  };

  const goPrev = () => setDay(d => dcAddDays(d, -1));
  const goNext = () => { if (day < todayStr) setDay(d => dcAddDays(d, 1)); };
  const isToday = day === todayStr;

  return (
    <div className="space-y-5">
      {/* Motto + banner */}
      <div className="flex items-start justify-between gap-3 flex-wrap">
        <p className="text-[12.5px] text-ink-500 leading-relaxed max-w-xl">
          คนที่ประสบความสำเร็จในแบบที่โลกไม่มีวันลืม…<br />
          คือคนที่เริ่มต้นจากการทำสิ่งเล็ก ๆ ที่โลกไม่มีวันเห็น
        </p>
        <div className="px-4 py-2 rounded-lg text-white text-sm font-extrabold tracking-widest shadow-card"
          style={{ background: 'linear-gradient(135deg,#C8A24B,#A87E2E)' }}>
          DAILY CHECKLIST
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-4 items-start">
        {/* ============ Left: day nav + progress + PV + calendar ============ */}
        <div className="lg:col-span-4 space-y-4 lg:sticky lg:top-4">
          <Card pad>
            {/* Day navigator */}
            <div className="flex items-center justify-between">
              <button onClick={goPrev} className="w-9 h-9 rounded-lg hover:bg-ink-50 text-ink-500 flex items-center justify-center"><Icon name="chevL" className="w-5 h-5" /></button>
              <div className="text-center">
                <div className="text-base font-bold text-ink-900">{DC_TH_DOW_F[dObj.getDay()]} {dObj.getDate()} {_dcMonthAbbr[dObj.getMonth()]}</div>
                <div className="text-[11px] text-ink-400">ปี {dObj.getFullYear() + 543} · {isToday ? 'วันนี้' : <button onClick={() => setDay(todayStr)} className="text-brand-600 font-semibold hover:underline">กลับไปวันนี้</button>}</div>
              </div>
              <button onClick={goNext} disabled={isToday}
                className={`w-9 h-9 rounded-lg flex items-center justify-center ${isToday ? 'text-ink-200 cursor-not-allowed' : 'hover:bg-ink-50 text-ink-500'}`}><Icon name="chevR" className="w-5 h-5" /></button>
            </div>

            {/* Progress ring + summary */}
            <div className="flex items-center gap-4 mt-4">
              <div className="relative flex-shrink-0" style={{ width: 92, height: 92 }}>
                <svg viewBox="0 0 36 36" className="w-[92px] h-[92px] -rotate-90">
                  <circle cx="18" cy="18" r="15.5" fill="none" stroke="#EEF2F7" strokeWidth="3.2" />
                  <circle cx="18" cy="18" r="15.5" fill="none" stroke="#2F5DE5" strokeWidth="3.2" strokeLinecap="round"
                    strokeDasharray={`${(pct / 100) * 97.4} 97.4`} style={{ transition: 'stroke-dasharray .5s ease' }} />
                </svg>
                <div className="absolute inset-0 flex flex-col items-center justify-center">
                  <div className="text-xl font-extrabold text-ink-900 leading-none num">{pct}%</div>
                  <div className="text-[9px] text-ink-400 mt-0.5">วันนี้</div>
                </div>
              </div>
              <div className="min-w-0">
                <div className="text-sm font-bold text-ink-900">ทำไปแล้ว {dailyDone} จาก {DC_DAILY_TOTAL} ข้อ</div>
                <div className="text-[12px] text-ink-400">{dailyDone >= DC_DAILY_TOTAL ? 'ครบทุกข้อแล้ว เยี่ยมมาก! 🎉' : `เหลืออีก ${DC_DAILY_TOTAL - dailyDone} ข้อของวันนี้`}</div>
              </div>
            </div>

            {/* Per-section bars */}
            <div className="space-y-2.5 mt-4">
              {[...DC_DAILY, DC_WEEKLY].map(sec => {
                const done = _dcSectionDone(sec, doc.checks);
                const total = sec.items.length;
                return (
                  <div key={sec.id} className="flex items-center gap-2">
                    <span className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: sec.color }} />
                    <span className="text-[12px] text-ink-600 flex-1 truncate">{sec.label}</span>
                    <div className="w-20 h-1.5 rounded-full bg-ink-100 overflow-hidden">
                      <div className="h-full rounded-full" style={{ width: `${total ? (done / total) * 100 : 0}%`, background: sec.color, transition: 'width .4s ease' }} />
                    </div>
                    <span className="text-[11px] text-ink-400 num w-8 text-right">{done}/{total}</span>
                  </div>
                );
              })}
            </div>

            {/* PV */}
            <div className="flex items-center justify-between gap-2 mt-4 pt-4 border-t border-ink-100">
              <label className="text-[13px] font-semibold text-ink-700">PV วันนี้</label>
              <div className="flex items-center gap-1">
                <input value={doc.pv} onChange={e => setPv(e.target.value)} inputMode="numeric" placeholder="0"
                  className="w-24 h-9 text-right px-2 rounded-lg border border-ink-200 bg-white text-sm font-semibold text-ink-900 num focus:border-brand-400 focus:ring-2 focus:ring-brand-100 outline-none" />
                <span className="text-[12px] text-ink-400">฿ PV</span>
              </div>
            </div>

            {/* Copy to upline */}
            <button onClick={doCopy}
              className={`w-full mt-3 h-11 rounded-xl text-sm font-bold flex items-center justify-center gap-2 transition-all ${copied ? 'bg-emerald-500 text-white' : 'bg-brand-500 text-white hover:bg-brand-600'}`}>
              {copied ? <><Icon name="check" className="w-4 h-4" strokeWidth={3} /> คัดลอกแล้ว — วางส่ง Upline ได้เลย</> : <><Icon name="share-2" className="w-4 h-4" /> Copy ส่ง Upline</>}
            </button>
          </Card>

          {/* Month heatmap */}
          <Card pad>
            <div className="flex items-center justify-between mb-3">
              <div className="text-sm font-bold text-ink-900">เดือนนี้</div>
              <div className="text-[11px] text-ink-400">{DC_TH_MONTH_F[dObj.getMonth()]} {dObj.getFullYear() + 543} · บันทึก {savedDaysCount} วัน</div>
            </div>
            <div className="grid grid-cols-7 gap-1 text-center">
              {DC_TH_DOW.map((d, i) => <div key={i} className="text-[10px] text-ink-300 font-semibold pb-1">{d}</div>)}
              {calCells.map((d, i) => {
                if (d === null) return <div key={`p${i}`} />;
                const key = dcYmd(new Date(dObj.getFullYear(), dObj.getMonth(), d));
                const done = monthMap[key] || 0;
                const sel = key === day;
                const isT = key === todayStr;
                const dark = done >= 8;
                return (
                  <button key={key} onClick={() => setDay(key)}
                    className={`aspect-square rounded-lg text-[11px] font-semibold flex items-center justify-center transition-all ${sel ? 'ring-2 ring-brand-500 ring-offset-1' : isT ? 'ring-1 ring-brand-300' : ''}`}
                    style={{ background: heatTint(done), color: dark ? '#fff' : (done ? '#1E3A8A' : '#94A3B8') }}
                    title={`${d} — ทำ ${done}/${DC_DAILY_TOTAL} ข้อ`}>
                    {d}
                  </button>
                );
              })}
            </div>
            <div className="flex items-center justify-end gap-1.5 mt-3 text-[10px] text-ink-400">
              <span>น้อย</span>
              {['#F1F5F9', '#C7D6F9', '#9DB6F4', '#5B82EB', '#2F5DE5'].map(c => <span key={c} className="w-3 h-3 rounded" style={{ background: c }} />)}
              <span>มาก</span>
            </div>
          </Card>
        </div>

        {/* ============ Right: the checklist ============ */}
        <div className="lg:col-span-8 space-y-4">
          {loading ? (
            <Card><div className="py-16 text-center text-sm text-ink-400">กำลังโหลด…</div></Card>
          ) : (
            <>
              {DC_DAILY.map(sec => <DcSection key={sec.id} sec={sec} doc={doc} onToggle={toggle} onBump={bump} />)}
              <DcSection sec={DC_WEEKLY} doc={doc} onToggle={toggle} onBump={bump}
                badge={<Pill color="#B45309" tint="#FEF3DD" size="xs">ทำสัปดาห์ละครั้ง</Pill>} />

              {/* Note to upline */}
              <Card pad>
                <label className="text-[13px] font-bold text-ink-800 flex items-center gap-1.5">
                  <Icon name="megaphone" className="w-4 h-4 text-ink-400" /> หมายเหตุถึง Upline <span className="text-[11px] font-normal text-ink-400">(ไม่บังคับ)</span>
                </label>
                <textarea value={doc.note} onChange={e => setNote(e.target.value)} rows={3}
                  placeholder="เช่น วันนี้เข้าเรื่อง 8 ราย ปิดได้ 1 คน / ติดปัญหาเรื่อง…"
                  className="w-full mt-2 px-3 py-2.5 rounded-xl border border-ink-200 bg-white text-[13px] text-ink-800 leading-relaxed focus:border-brand-400 focus:ring-2 focus:ring-brand-100 outline-none resize-none" />
              </Card>

              <div className="text-center text-[11px] text-ink-400 pb-2">{saveLabel}</div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// One checklist section card.
function DcSection({ sec, doc, onToggle, onBump, badge = null }) {
  const done = _dcSectionDone(sec, doc.checks);
  return (
    <Card pad>
      <div className="flex items-center gap-2 mb-3">
        <span className="w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0" style={{ background: sec.tint, color: sec.color }}>
          <Icon name={sec.icon} className="w-4 h-4" />
        </span>
        <span className="text-sm font-bold text-ink-900">{sec.label}</span>
        {badge}
        <span className="ml-auto text-[12px] font-semibold num" style={{ color: done === sec.items.length && done > 0 ? sec.color : '#94A3B8' }}>{done}/{sec.items.length}</span>
      </div>
      <div className="space-y-1">
        {sec.items.map(it => {
          const checked = !!doc.checks[it.id];
          return (
            <div key={it.id} className="flex items-center gap-3 py-1.5 group">
              <button onClick={() => onToggle(it.id)}
                className={`w-5 h-5 rounded-md border-2 flex-shrink-0 flex items-center justify-center transition-all ${checked ? 'border-transparent text-white' : 'border-ink-200 hover:border-ink-300'}`}
                style={checked ? { background: sec.color } : {}}>
                {checked && <Icon name="check" className="w-3 h-3" strokeWidth={3.5} />}
              </button>
              <button onClick={() => onToggle(it.id)} className="flex-1 text-left min-w-0">
                <div className={`text-[13.5px] ${checked ? 'text-ink-400 line-through' : 'text-ink-800'}`}>{it.label}</div>
                {it.hint && <div className="text-[11px] text-ink-400">{it.hint}</div>}
              </button>
              {it.count && (
                <div className="flex items-center gap-1 flex-shrink-0">
                  <button onClick={() => onBump(it.id, -1)} className="w-7 h-7 rounded-lg border border-ink-200 text-ink-500 hover:bg-ink-50 flex items-center justify-center text-base leading-none">−</button>
                  <span className="w-7 text-center text-sm font-bold text-ink-900 num">{Number(doc.counts[it.id]) || 0}</span>
                  <button onClick={() => onBump(it.id, 1)} className="w-7 h-7 rounded-lg border border-ink-200 text-ink-500 hover:bg-ink-50 flex items-center justify-center"><Icon name="plus" className="w-3.5 h-3.5" /></button>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </Card>
  );
}
