// lich.jsx — Lịch Dịch Lý ngay trong đạo tràng: xem theo Ngày (12 giờ quẻ) hoặc Tháng (âm dương + trăng + giao tiết).
// Bản web gốc lich-dichly-2026.html GIỮ NGUYÊN — link ở cuối màn. Exports to window: LichDichLy
const LICH_THU = ['T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'CN'];
const LICH_TONE = { cat: '#79c98b', trung: 'rgba(230,220,184,0.55)', hung: '#e0604f' };
// tên tắt quẻ (bỏ hai chữ quái đầu) + giải danh 2 chữ gốc DLVN — cùng phép với thẻ ghi nhanh Đạo Tràng
function lichTen(hex) { const p = (hex.name || '').split(' '); if (p[0] === 'Thuần') return hex.name; return p.length > 2 ? p.slice(2).join(' ') : p[p.length - 1]; }
function lichDanh(hex) {
  const gd = hexGiaiDanh(hex) || '';
  const kw = (gd.split('—')[1] || gd).split(',')[0].trim();
  return kw ? kw.split(/\s+/).map(w => w[0] + w.slice(1).toLowerCase()).join(' ') : '';
}

function LichTrang({ d, size = 12 }) {
  const tr = dlTrangKhuyet(d);
  const lit = '#e6dcb8', dark = 'rgba(230,220,184,0.12)';
  const p = Math.round(tr.frac * 100);
  const bg = p <= 2 ? dark : p >= 98 ? lit : (tr.waxing ? `linear-gradient(to right, ${dark} ${100 - p}%, ${lit} ${100 - p}%)` : `linear-gradient(to right, ${lit} ${p}%, ${dark} ${p}%)`);
  return <span title={`trăng ngày ${tr.ngay}${tr.pha ? ' · ' + tr.pha : ''}`} style={{ display: 'inline-block', width: size, height: size, borderRadius: '50%', background: bg, border: '1px solid rgba(230,220,184,0.4)', verticalAlign: -2 }}></span>;
}

// cụm thông tin một ngày — cùng giọng với đầu Đạo Tràng
function LichNgayInfo({ d }) {
  const d12 = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 12);
  const li = dlLunarInfo(d12), th = dlTietHanh(d12), tl = dlTuLenh(d12), tr = dlTrangKhuyet(d12), cn = dlCanChiNgay(d12);
  return (
    <div style={{ margin: '2px 0 12px' }}>
      <div style={{ fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 12.5, color: INK.text, fontWeight: 600, letterSpacing: 0.3 }}>{fmtDate(d)}</div>
      <div style={{ fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 11, color: INK.faint, marginTop: 3, lineHeight: 1.7 }}>
        Âm {li.full} <LichTrang d={d12} />{tr.pha && <span style={{ color: '#e6dcb8', fontWeight: 600 }}> {tr.pha}</span>}
        <br />
        <span title="tiết lệnh — khung 15 ngày" style={{ color: th.color, textShadow: `0 0 9px ${th.color}66`, fontWeight: 600 }}>{th.tiet}</span>
        {' · lệnh '}<span title={`nhân nguyên tư lệnh — ngày ${tl.ngayThu} của tiết`} style={{ color: tl.color, fontWeight: 600 }}>{tl.can}</span>
        {' · ngày '}{cn.full}
      </div>
    </div>
  );
}

function LichDichLy({ open, onClose, anim, dungSu, onDungSuAdd, onDungSuUpdate, onDungSuDel, onGhiTamKy, queTot, onToggleTot }) {
  const homNay = () => { const n = new Date(); return new Date(n.getFullYear(), n.getMonth(), n.getDate()); };
  const [view, setView] = React.useState('ngay');
  const [sel, setSel] = React.useState(homNay);
  const [thang, setThang] = React.useState(() => { const n = new Date(); return new Date(n.getFullYear(), n.getMonth(), 1); });
  const [gioMo, setGioMo] = React.useState(null); // giờ đang mở sổ dụng sự (0..11)
  React.useEffect(() => { setGioMo(null); }, [sel && sel.getTime(), view]);
  React.useEffect(() => { if (open) { const t = homNay(); setSel(t); setThang(new Date(t.getFullYear(), t.getMonth(), 1)); setView('ngay'); } }, [open]);

  // lưới tháng — âm lịch, trăng 4 mốc, ngày giao tiết
  const oThang = React.useMemo(() => {
    const y = thang.getFullYear(), m = thang.getMonth();
    const nDays = new Date(y, m + 1, 0).getDate();
    const startCol = (new Date(y, m, 1).getDay() + 6) % 7; // T2 = cột 0
    const cells = [];
    for (let i = 0; i < startCol; i++) cells.push(null);
    let secTruoc = dlTietSector(new Date(y, m, 0, 12));
    for (let dd = 1; dd <= nDays; dd++) {
      const d12 = new Date(y, m, dd, 12);
      const li = dlLunarInfo(d12), tr = dlTrangKhuyet(d12);
      const sec = dlTietSector(d12);
      const giaoTiet = sec !== secTruoc ? TIET_SECTOR[sec] : null;
      secTruoc = sec;
      cells.push({ dd, am: li.ngay === 1 ? `1/${li.thang}` : String(li.ngay), pha: tr.pha, frac: tr.frac, giaoTiet, mau: giaoTiet ? dlTietHanh(d12).color : null });
    }
    return { cells, nDays };
  }, [thang]);

  if (!open) return null;
  const t0 = homNay();
  const laHomNay = (d) => d.getTime() === t0.getTime();
  const doiNgay = (n) => setSel(s => new Date(s.getFullYear(), s.getMonth(), s.getDate() + n));
  const doiThang = (n) => setThang(s => new Date(s.getFullYear(), s.getMonth() + n, 1));
  const gioNow = dlGioIndex(new Date());

  const navBtn = (glyph, onClick) => (
    <button onClick={onClick} style={{ width: 32, height: 32, borderRadius: 10, cursor: 'pointer', background: INK.panel, border: `1px solid ${INK.hair}`, color: INK.dim, fontSize: 15, lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{glyph}</button>
  );
  const chipHomNay = (onClick) => (
    <button onClick={onClick} style={{ padding: '6px 12px', borderRadius: 999, cursor: 'pointer', background: 'rgba(var(--gold-rgb),0.1)', border: `1px solid ${INK.goldDim}55`, fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 11, fontWeight: 600, color: INK.gold }}>Hôm nay</button>
  );

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 45, display: 'flex', flexDirection: 'column', background: 'linear-gradient(180deg, #15111f 0%, #100d16 60%)', animation: anim ? 'tt-sheet 0.34s cubic-bezier(.2,.7,.2,1)' : 'none' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '54px 18px 14px', flexShrink: 0, borderBottom: `1px solid ${INK.hair}` }}>
        <div style={{ flex: 1 }}>
          <div style={{ ...han, fontSize: 23, color: INK.gold, lineHeight: 1 }}>曆</div>
          <div style={{ fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 11, color: INK.dim, marginTop: 3, letterSpacing: 0.3 }}>Lịch Dịch Lý · quẻ ngày giờ</div>
        </div>
        <div style={{ display: 'flex', gap: 6, background: INK.panel, border: `1px solid ${INK.hair}`, borderRadius: 999, padding: 3 }}>
          {[['ngay', 'Ngày'], ['thang', 'Tháng']].map(([v, label]) => (
            <button key={v} onClick={() => setView(v)} style={{ padding: '6px 13px', borderRadius: 999, cursor: 'pointer', background: view === v ? 'rgba(var(--gold-rgb),0.16)' : 'transparent', border: 'none', fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 11.5, fontWeight: 600, color: view === v ? INK.gold : INK.faint }}>{label}</button>
          ))}
        </div>
        <button onClick={onClose} style={{ width: 36, height: 36, borderRadius: '50%', cursor: 'pointer', background: 'rgba(255,255,255,0.05)', border: `1px solid ${INK.hair}`, color: INK.dim, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20, lineHeight: 1 }}>×</button>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 18px 28px' }}>
        {view === 'ngay' ? (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 10 }}>
              {navBtn('‹', () => doiNgay(-1))}
              <div style={{ flex: 1 }}><LichNgayInfo d={sel} /></div>
              {navBtn('›', () => doiNgay(1))}
            </div>
            {!laHomNay(sel) && <div style={{ marginBottom: 12 }}>{chipHomNay(() => setSel(t0))}</div>}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              {DL_CHI.map((chi, i) => {
                const d12 = new Date(sel.getFullYear(), sel.getMonth(), sel.getDate(), 12);
                const h = dlHourHex(d12, i);
                const lt = dlLucThan(d12, i);
                const cl = dlCatLoi(h.hex, h.hao);
                const now = laHomNay(sel) && i === gioNow;
                const sc = statColor(h.buffStat.hue);
                const soDS = ((dungSu || {})[h.hex.n] || []).length;
                const tot = !!(((queTot || {})[h.hex.n + '.' + h.hao]) || {}).v;
                const mo = gioMo === i;
                return (
                  <div key={chi} style={{ borderRadius: 12, background: tot ? 'rgba(var(--gold-rgb),0.09)' : (now ? 'rgba(var(--gold-rgb),0.09)' : INK.panel), border: `1px solid ${mo || now ? INK.goldDim : (tot ? 'rgba(var(--gold-rgb),0.55)' : INK.panelBd)}`, boxShadow: tot ? '0 0 14px rgba(var(--gold-rgb),0.28)' : 'none' }}>
                    <div onClick={() => setGioMo(mo ? null : i)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 11px', cursor: 'pointer' }}>
                    <div style={{ width: 46, flexShrink: 0, position: 'relative' }}>
                      <div style={{ fontFamily: "'Spectral', serif", fontSize: 13.5, fontWeight: 700, color: now ? INK.gold : INK.text }}>{chi}{soDS > 0 && <span title="có sổ dụng sự" style={{ ...han, fontSize: 9, color: INK.goldDim, marginLeft: 4 }}>用</span>}</div>
                      <div style={{ fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 9.5, color: INK.faint }}>{GIO_KHUNG[i]}</div>
                    </div>
                    <HexLines lines={hexLines(h.hex)} w={22} gap={2.5} h={2.5} color={now ? INK.gold : INK.goldDim} dong={h.hao} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontFamily: "'Spectral', serif", fontSize: 13, fontWeight: 600, color: INK.text, lineHeight: 1.3, textWrap: 'pretty' }}>
                        {lichTen(h.hex)}{cl.bien && <span> – {lichTen(cl.bien)}</span>}{tot && <span title="giờ tốt — bạn đã đánh dấu quẻ này" style={{ color: INK.gold }}> ☀</span>}{cl.cat && <span title="cặp chánh–biến cát lợi" style={{ color: '#79c98b' }}> ✦</span>}
                      </div>
                      <div style={{ fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 10, color: INK.goldDim, marginTop: 1 }}>{lichDanh(h.hex)}{cl.bien && lichDanh(cl.bien) ? ` – ${lichDanh(cl.bien)}` : ''}</div>
                    </div>
                    <span title={lt.note} style={{ display: 'inline-flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2, flexShrink: 0 }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                        <span style={{ ...han, fontSize: 15, color: LICH_TONE[lt.tone] }}>{lt.glyph}</span>
                        <span style={{ fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 10, color: LICH_TONE[lt.tone] }}>{lt.name}</span>
                      </span>
                      <span style={{ fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 9, color: sc, whiteSpace: 'nowrap' }}>✦ {h.buffStat.name} +{h.buffPct}%</span>
                    </span>
                    </div>
                    {mo && onDungSuAdd && (
                      <div style={{ padding: '0 11px 11px' }}>
                        {onToggleTot && (
                          <button onClick={() => onToggleTot(h.hex.n + '.' + h.hao)} style={{
                            display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 14px', borderRadius: 999, cursor: 'pointer', marginBottom: 10,
                            background: tot ? 'rgba(var(--gold-rgb),0.16)' : 'transparent',
                            border: `1px solid ${tot ? INK.goldDim : INK.hair}`,
                            fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 11.5, fontWeight: 600, color: tot ? INK.gold : INK.dim,
                          }}>☀ {tot ? 'Giờ tốt — bỏ dấu' : 'Đánh dấu giờ tốt'}</button>
                        )}
                        <DungSu hex={h.hex} gioName={chi} isNow={now} list={(dungSu || {})[h.hex.n] || []}
                          onAdd={onDungSuAdd} onUpdate={onDungSuUpdate} onDel={onDungSuDel} onGhiTamKy={onGhiTamKy} />
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
            <p style={{ fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 10.5, lineHeight: 1.6, color: INK.faint, margin: '12px 2px 0', textWrap: 'pretty' }}>
              Chạm một giờ để mở sổ dụng sự của quẻ ấy và đánh dấu ☀ giờ tốt — điền dần, gặp lại quẻ ngày nào cũng tự sáng. Dấu 用 = quẻ đã có sổ. Tất cả đi theo đồng bộ mây.
            </p>
          </>
        ) : (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 12 }}>
              {navBtn('‹', () => doiThang(-1))}
              <div style={{ flex: 1, textAlign: 'center' }}>
                <span style={{ fontFamily: "'Spectral', serif", fontSize: 15.5, fontWeight: 700, color: INK.text }}>Tháng {thang.getMonth() + 1} · {thang.getFullYear()}</span>
              </div>
              {navBtn('›', () => doiThang(1))}
            </div>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 12 }}>{chipHomNay(() => { setThang(new Date(t0.getFullYear(), t0.getMonth(), 1)); setSel(t0); })}</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4, marginBottom: 5 }}>
              {LICH_THU.map(t => <div key={t} style={{ textAlign: 'center', fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 10, letterSpacing: 1, color: t === 'CN' ? INK.cinnabar : INK.faint }}>{t}</div>)}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
              {oThang.cells.map((c, idx) => {
                if (!c) return <div key={'x' + idx}></div>;
                const d = new Date(thang.getFullYear(), thang.getMonth(), c.dd);
                const nay = laHomNay(d);
                return (
                  <button key={c.dd} onClick={() => { setSel(d); setView('ngay'); }} style={{
                    padding: '7px 2px 6px', borderRadius: 11, cursor: 'pointer', minHeight: 56,
                    background: nay ? 'rgba(var(--gold-rgb),0.1)' : INK.panel,
                    border: `1px solid ${nay ? INK.goldDim : INK.panelBd}`,
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
                  }}>
                    <span style={{ fontFamily: "'Spectral', serif", fontSize: 14.5, fontWeight: 700, lineHeight: 1, color: nay ? INK.gold : INK.text, display: 'inline-flex', alignItems: 'center', gap: 3 }}>
                      {c.dd}{c.pha && <LichTrang d={new Date(thang.getFullYear(), thang.getMonth(), c.dd, 12)} size={7} />}
                    </span>
                    <span style={{ fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 8.5, color: c.am.includes('/') ? INK.goldDim : INK.faint, fontWeight: c.am.includes('/') ? 700 : 400 }}>{c.am}</span>
                    {c.giaoTiet && <span style={{ fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 7.5, fontWeight: 700, color: c.mau, lineHeight: 1.15, textAlign: 'center' }}>{c.giaoTiet}</span>}
                  </button>
                );
              })}
            </div>
            <p style={{ fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 10.5, lineHeight: 1.6, color: INK.faint, margin: '12px 2px 0', textWrap: 'pretty' }}>
              Chạm một ngày để xem 12 giờ quẻ. Chấm trăng ở 4 mốc sóc · thượng huyền · rằm · hạ huyền; tên tiết ghi ở ngày giao tiết.
            </p>
          </>
        )}
        <a href="lich-dichly-2026.html" style={{ display: 'block', textAlign: 'center', marginTop: 18, padding: '11px', borderRadius: 12, textDecoration: 'none', background: 'transparent', border: `1px dashed ${INK.goldDim}44`, fontFamily: "'Be Vietnam Pro', sans-serif", fontSize: 11.5, color: INK.goldDim }}>曆 Mở Lịch Dịch Lý bản web đầy đủ ›</a>
      </div>
    </div>
  );
}

Object.assign(window, { LichDichLy });
