import type { ReactNode } from 'react';

const WEEKDAY_LABELS = ['Po', 'Út', 'St', 'Čt', 'Pá', 'So', 'Ne'];

interface Props {
  month: string; // "YYYY-MM"
  renderDay: (dateStr: string, dayNumber: number) => ReactNode;
}

/** JS Date#getDay() is 0=Sun..6=Sat; the Czech week starts Monday. */
function mondayFirst(jsDay: number): number {
  return (jsDay + 6) % 7;
}

export function MonthCalendar({ month, renderDay }: Props) {
  const [yearStr, monthStr] = month.split('-');
  const year = Number(yearStr);
  const monthIndex = Number(monthStr) - 1;

  const daysInMonth = new Date(year, monthIndex + 1, 0).getDate();
  const leadingBlanks = mondayFirst(new Date(year, monthIndex, 1).getDay());
  const totalCells = Math.ceil((leadingBlanks + daysInMonth) / 7) * 7;

  const today = new Date();
  const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(
    today.getDate()
  ).padStart(2, '0')}`;

  const cells = Array.from({ length: totalCells }, (_, i) => {
    const dayNumber = i - leadingBlanks + 1;
    if (dayNumber < 1 || dayNumber > daysInMonth) return null;
    return `${year}-${String(monthIndex + 1).padStart(2, '0')}-${String(dayNumber).padStart(2, '0')}`;
  });

  return (
    <div className="month-calendar-scroll">
      <div className="month-calendar">
        <div className="month-calendar-head">
          {WEEKDAY_LABELS.map((label) => (
            <div key={label}>{label}</div>
          ))}
        </div>
        <div className="month-calendar-body">
          {cells.map((dateStr, i) => (
            <div
              key={i}
              className={`month-calendar-cell ${dateStr ? '' : 'is-outside'} ${dateStr === todayStr ? 'is-today' : ''}`}
            >
              {dateStr && (
                <>
                  <div className="month-calendar-daynum">{Number(dateStr.slice(8, 10))}</div>
                  {renderDay(dateStr, Number(dateStr.slice(8, 10)))}
                </>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
