/* calendar.jsx — Календарь: месяц с напоминаниями + список на выбранный день. */

function _pad(n) { return String(n).padStart(2, "0"); }
function _dayKey(d) { return `${d.getFullYear()}-${_pad(d.getMonth() + 1)}-${_pad(d.getDate())}`; }

function _buildMonth(base) {
  // base — первое число месяца. Возвращает 6 недель по 7 дат (Пн-первый).
  const first = new Date(base.getFullYear(), base.getMonth(), 1);
  const offset = (first.getDay() + 6) % 7; // Пн=0
  const start = new Date(first);
  start.setDate(1 - offset);
  const weeks = [];
  for (let w = 0; w < 6; w++) {
    const row = [];
    for (let d = 0; d < 7; d++) {
      row.push(new Date(start.getFullYear(), start.getMonth(), start.getDate() + w * 7 + d));
    }
    weeks.push(row);
  }
  return weeks;
}

function CalendarScreen({ onOpenNote }) {
  const [base, setBase] = React.useState(() => { const d = new Date(); return new Date(d.getFullYear(), d.getMonth(), 1); });
  const [items, setItems] = React.useState([]);
  const [sel, setSel] = React.useState(() => _dayKey(new Date()));
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    setLoading(true);
    api.getReminders().then((r) => { setItems(r || []); setLoading(false); }).catch(() => setLoading(false));
  }, []);

  const byDay = React.useMemo(() => {
    const m = {};
    items.forEach((r) => { const k = _dayKey(new Date(r.remind_at)); (m[k] = m[k] || []).push(r); });
    return m;
  }, [items]);

  const weeks = _buildMonth(base);
  const todayKey = _dayKey(new Date());
  const selItems = (byDay[sel] || []).slice().sort((a, b) => new Date(a.remind_at) - new Date(b.remind_at));

  const openNote = async (r) => {
    if (!r.note_id) return;
    try { const list = await api.getNotes({}); const n = list.find((x) => x.id === r.note_id); if (n) onOpenNote(n); } catch (e) {}
  };

  const prev = () => setBase(new Date(base.getFullYear(), base.getMonth() - 1, 1));
  const next = () => setBase(new Date(base.getFullYear(), base.getMonth() + 1, 1));
  const goToday = () => { const d = new Date(); setBase(new Date(d.getFullYear(), d.getMonth(), 1)); setSel(_dayKey(d)); };

  const dows = ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"];

  return (
    <div>
      <ScreenHead title="Календарь" sub="Напоминания по дням" />

      <div className="rounded-2xl border border-[var(--border)] bg-[var(--surface)] p-3 sm:p-4 mb-4">
        <div className="flex items-center gap-2 mb-3">
          <button onClick={prev} className="grid place-items-center w-9 h-9 rounded-lg text-[var(--muted)] hover:text-[var(--text)] hover:bg-[var(--surface-2)] transition"><Icon name="chevron" size={18} className="rotate-180" /></button>
          <div className="flex-1 text-center text-[15px] font-bold text-[var(--text)] capitalize">{MONTHS_FULL[base.getMonth()]} {base.getFullYear()}</div>
          <button onClick={next} className="grid place-items-center w-9 h-9 rounded-lg text-[var(--muted)] hover:text-[var(--text)] hover:bg-[var(--surface-2)] transition"><Icon name="chevron" size={18} /></button>
          <button onClick={goToday} className="ml-1 text-[12px] font-semibold text-[var(--accent)] px-2.5 h-9 rounded-lg hover:bg-[var(--surface-2)] transition">Сегодня</button>
        </div>

        <div className="grid grid-cols-7 gap-1 mb-1">
          {dows.map((d) => <div key={d} className="text-center text-[11px] font-semibold text-[var(--muted)] py-1">{d}</div>)}
        </div>
        <div className="grid grid-cols-7 gap-1">
          {weeks.flat().map((d) => {
            const k = _dayKey(d);
            const inMonth = d.getMonth() === base.getMonth();
            const isToday = k === todayKey;
            const isSel = k === sel;
            const dayItems = byDay[k] || [];
            const hasPending = dayItems.some((r) => r.status === "pending");
            return (
              <button key={k} onClick={() => setSel(k)}
                className={`relative aspect-square rounded-lg flex flex-col items-center justify-center text-[13px] transition
                  ${isSel ? "bg-[var(--accent)] text-white font-bold" : isToday ? "bg-[var(--accent-weak)] text-[var(--accent)] font-bold" : inMonth ? "text-[var(--text)] hover:bg-[var(--surface-2)]" : "text-[var(--muted)] opacity-50"}`}>
                {d.getDate()}
                {dayItems.length > 0 && (
                  <span className={`mt-0.5 w-1.5 h-1.5 rounded-full ${isSel ? "bg-white" : hasPending ? "bg-[var(--accent)]" : "bg-[var(--border-strong)]"}`} />
                )}
              </button>
            );
          })}
        </div>
      </div>

      {/* список выбранного дня */}
      <h3 className="text-[13px] font-bold uppercase tracking-wide text-[var(--muted)] mb-2.5">
        {(() => { const [y, m, dd] = sel.split("-").map(Number); const dt = new Date(y, m - 1, dd); return `${dt.getDate()} ${MONTHS_FULL[dt.getMonth()]}`; })()} · {selItems.length}
      </h3>
      {loading ? (
        <div className="grid gap-2">{[0, 1].map((i) => <div key={i} className="sk h-14 rounded-2xl" />)}</div>
      ) : selItems.length === 0 ? (
        <p className="text-[13px] text-[var(--muted)] px-1">На этот день напоминаний нет.</p>
      ) : (
        <div className="grid gap-2">
          {selItems.map((r) => {
            const f = formatRemind(r.remind_at);
            const done = r.status !== "pending";
            return (
              <button key={r.id} onClick={() => openNote(r)}
                className="text-left flex items-center gap-3 rounded-2xl border border-[var(--border)] bg-[var(--surface)] p-3.5 hover:border-[var(--border-strong)] transition">
                <span className={`grid place-items-center w-9 h-9 rounded-lg shrink-0 reminder-icon-${done ? "done" : f.tone}`}>
                  <Icon name={r.status === "cancelled" ? "close" : done ? "check" : "bell"} size={16} />
                </span>
                <span className={`text-[14px] text-[var(--text)] truncate flex-1 ${r.status === "cancelled" ? "line-through opacity-70" : ""}`}>{r.text}</span>
                <span className="text-[12px] font-semibold text-[var(--muted)] shrink-0 mono">{hhmm(r.remind_at)}</span>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CalendarScreen });
