// frontend/components/calendar/MonthView.tsx — 월 뷰 (셀당 이벤트 ≤3 + +N개 더)
"use client";
import type { MouseEvent } from "react";
import { toMin } from "@/lib/calendar/time";
import type { CalEvent, Calendar } from "@/lib/calendar/types";

export function MonthView({
  events,
  calMap,
  weekdays,
  today,
  onOpen,
  onSelDay,
}: {
  events: CalEvent[];
  calMap: Record<string, Calendar>;
  weekdays: string[];
  today: number;
  onOpen: (ev: CalEvent, e: MouseEvent) => void;
  onSelDay: (n: number) => void;
}) {
  const first = new Date(2026, 5, 1);
  const off = first.getDay();
  const byDay: Record<number, CalEvent[]> = {};
  events.forEach((e) => {
    (byDay[e.day] = byDay[e.day] || []).push(e);
  });
  Object.values(byDay).forEach((a) => a.sort((x, y) => toMin(x.start) - toMin(y.start)));
  const cells: { inMonth: boolean; n: number }[] = [];
  for (let i = 0; i < 42; i++) {
    const d = new Date(2026, 5, 1 - off + i);
    cells.push({ inMonth: d.getMonth() === 5, n: d.getDate() });
  }
  return (
    <div className="cpanel">
      <div className="mo-head">
        {weekdays.map((w, i) => (
          <div key={w} className={"mo-wd" + (i === 0 || i === 6 ? " wknd" : "")}>
            {w}
          </div>
        ))}
      </div>
      <div className="mo-grid">
        {cells.map((c, i) => {
          const evs = c.inMonth ? byDay[c.n] || [] : [];
          return (
            <div
              key={i}
              className={
                "mo-cell" + (c.inMonth ? "" : " out") + (c.inMonth && c.n === today ? " today" : "")
              }
              onClick={() => c.inMonth && onSelDay(c.n)}
            >
              <div className="mo-dn">{c.n}</div>
              {evs.slice(0, 3).map((ev) => (
                <div
                  key={ev.id}
                  className={"mo-ev tint-" + calMap[ev.cal].tone}
                  onClick={(e) => {
                    e.stopPropagation();
                    onOpen(ev, e);
                  }}
                >
                  <span className="pdot" />
                  <span className="mt">{ev.start}</span>
                  <span className="mn">{ev.title}</span>
                </div>
              ))}
              {evs.length > 3 && <div className="mo-more">+{evs.length - 3}개 더</div>}
            </div>
          );
        })}
      </div>
    </div>
  );
}
